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 _resource_index(self, resource):
"""Get index for given resource. by default it will be `self.index`, but it can be overriden via app.config :param resource:... |
datasource = self.get_datasource(resource)
indexes = self._resource_config(resource, 'INDEXES') or {}
default_index = self._resource_config(resource, 'INDEX')
return indexes.get(datasource[0], default_index) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _refresh_resource_index(self, resource):
"""Refresh index for given resource. :param resource: resource name """ |
if self._resource_config(resource, 'FORCE_REFRESH', True):
self.elastic(resource).indices.refresh(self._resource_index(resource)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _resource_prefix(self, resource=None):
"""Get elastic prefix for given resource. Resource can specify ``elastic_prefix`` which behaves same like ``mongo_pref... |
px = 'ELASTICSEARCH'
if resource and config.DOMAIN[resource].get('elastic_prefix'):
px = config.DOMAIN[resource].get('elastic_prefix')
return px |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def elastic(self, resource=None):
"""Get ElasticSearch instance for given resource.""" |
px = self._resource_prefix(resource)
if px not in self.elastics:
url = self._resource_config(resource, 'URL')
assert url, 'no url for %s' % px
self.elastics[px] = get_es(url, **self.kwargs)
return self.elastics[px] |
<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_md5sum(fname, chunk_size=1024):
""" Returns the MD5 checksum of a file. Args: fname (str):
Filename chunk_size (Optional[int]):
Size (in Bytes) of the ... |
def iter_chunks(f):
while True:
chunk = f.read(chunk_size)
if not chunk:
break
yield chunk
sig = hashlib.md5()
with open(fname, 'rb') as f:
for chunk in iter_chunks(f):
sig.update(chunk)
# data = f.read()
# ... |
<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_and_verify(url, md5sum, fname=None, chunk_size=1024, clobber=False, verbose=True):
""" Download a file and verify the MD5 sum. Args: url (str):
The... |
# Determine the filename
if fname is None:
fname = url.split('/')[-1]
# Check if the file already exists on disk
if (not clobber) and os.path.isfile(fname):
print('Checking existing file to see if MD5 sum matches ...')
md5_existing = get_md5sum(fname, chunk_size=chunk_size)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(url, fname=None):
""" Downloads a file. Args: url (str):
The URL to download. fname (Optional[str]):
The filename to store the downloaded file in.... |
# Determine the filename
if fname is None:
fname = url.split('/')[-1]
# Stream the URL as a file, copying to local disk
with contextlib.closing(requests.get(url, stream=True)) as r:
try:
r.raise_for_status()
except requests.exceptions.HTTPError as error:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dataverse_download_doi(doi, local_fname=None, file_requirements={}, clobber=False):
""" Downloads a file from the Dataverse, using a DOI and set of metadata ... |
metadata = dataverse_search_doi(doi)
def requirements_match(metadata):
for key in file_requirements.keys():
if metadata['dataFile'].get(key, None) != file_requirements[key]:
return False
return True
for file_metadata in metadata['data']['latestVersion']['files'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def address_reencode(address, blockchain='bitcoin', **blockchain_opts):
""" Reencode an address """ |
if blockchain == 'bitcoin':
return btc_address_reencode(address, **blockchain_opts)
else:
raise ValueError("Unknown blockchain '{}'".format(blockchain)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_multisig(privkey_info, blockchain='bitcoin', **blockchain_opts):
""" Is the given private key bundle a multisig bundle? """ |
if blockchain == 'bitcoin':
return btc_is_multisig(privkey_info, **blockchain_opts)
else:
raise ValueError('Unknown blockchain "{}"'.format(blockchain)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_multisig_address(addr, blockchain='bitcoin', **blockchain_opts):
""" Is the given address a multisig address? """ |
if blockchain == 'bitcoin':
return btc_is_multisig_address(addr, **blockchain_opts)
else:
raise ValueError('Unknown blockchain "{}"'.format(blockchain)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_multisig_script(script, blockchain='bitcoin', **blockchain_opts):
""" Is the given script a multisig script? """ |
if blockchain == 'bitcoin':
return btc_is_multisig_script(script, **blockchain_opts)
else:
raise ValueError('Unknown blockchain "{}"'.format(blockchain)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_singlesig(privkey_info, blockchain='bitcoin', **blockchain_opts):
""" Is the given private key bundle a single-sig key bundle? """ |
if blockchain == 'bitcoin':
return btc_is_singlesig(privkey_info, **blockchain_opts)
else:
raise ValueError('Unknown blockchain "{}"'.format(blockchain)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_singlesig_address(addr, blockchain='bitcoin', **blockchain_opts):
""" Is the given address a single-sig address? """ |
if blockchain == 'bitcoin':
return btc_is_singlesig_address(addr, **blockchain_opts)
else:
raise ValueError('Unknown blockchain "{}"'.format(blockchain)) |
<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_privkey_address(privkey_info, blockchain='bitcoin', **blockchain_opts):
""" Get the address from a private key bundle """ |
if blockchain == 'bitcoin':
return btc_get_privkey_address(privkey_info, **blockchain_opts)
else:
raise ValueError('Unknown blockchain "{}"'.format(blockchain)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_grad_cartesian_tensor(grad_X, zmat_dist):
"""Apply the gradient for transformation to cartesian space onto zmat_dist. Args: grad_X (:class:`numpy.ndarr... |
columns = ['bond', 'angle', 'dihedral']
C_dist = zmat_dist.loc[:, columns].values.T
try:
C_dist = C_dist.astype('f8')
C_dist[[1, 2], :] = np.radians(C_dist[[1, 2], :])
except (TypeError, AttributeError):
C_dist[[1, 2], :] = sympy.rad(C_dist[[1, 2], :])
cart_dist = np.tensord... |
<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_model_converter(model, app):
"""Add url converter for model Example: class Student(db.model):
id = Column(Integer, primary_key=True) name = Column(... |
if hasattr(model, 'id'):
class Converter(_ModelConverter):
_model = model
app.url_map.converters[model.__name__] = Converter |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iupacify(self):
"""Give the IUPAC conform representation. Mathematically speaking the angles in a zmatrix are representations of an equivalence class. We wil... |
def convert_d(d):
r = d % 360
return r - (r // 180) * 360
new = self.copy()
new.unsafe_loc[:, 'angle'] = new['angle'] % 360
select = new['angle'] > 180
new.unsafe_loc[select, 'angle'] = new.loc[select, 'angle'] - 180
new.unsafe_loc[select, 'dihe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def minimize_dihedrals(self):
r"""Give a representation of the dihedral with minimized absolute value. Mathematically speaking the angles in a zmatrix are repres... |
new = self.copy()
def convert_d(d):
r = d % 360
return r - (r // 180) * 360
new.unsafe_loc[:, 'dihedral'] = convert_d(new.loc[:, 'dihedral'])
return new |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def change_numbering(self, new_index=None):
"""Change numbering to a new index. Changes the numbering of index and all dependent numbering The user has to make s... |
if (new_index is None):
new_index = range(len(self))
elif len(new_index) != len(self):
raise ValueError('len(new_index) has to be the same as len(self)')
c_table = self.loc[:, ['b', 'a', 'd']]
# Strange bug in pandas where .replace is transitive for object colum... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _insert_dummy_cart(self, exception, last_valid_cartesian=None):
"""Insert dummy atom into the already built cartesian of exception """ |
def get_normal_vec(cartesian, reference_labels):
b_pos, a_pos, d_pos = cartesian._get_positions(reference_labels)
BA = a_pos - b_pos
AD = d_pos - a_pos
N1 = np.cross(BA, AD)
n1 = N1 / np.linalg.norm(N1)
return n1
def insert_dummy(... |
<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_cartesian(self):
"""Return the molecule in cartesian coordinates. Raises an :class:`~exceptions.InvalidReference` exception, if the reference of the i-th... |
def create_cartesian(positions, row):
xyz_frame = pd.DataFrame(columns=['atom', 'x', 'y', 'z'],
index=self.index[:row], dtype='f8')
xyz_frame['atom'] = self.loc[xyz_frame.index, 'atom']
xyz_frame.loc[:, ['x', 'y', 'z']] = positions[:row]
... |
<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_grad_cartesian(self, as_function=True, chain=True, drop_auto_dummies=True):
r"""Return the gradient for the transformation to a Cartesian. If ``as_functi... |
zmat = self.change_numbering()
c_table = zmat.loc[:, ['b', 'a', 'd']]
c_table = c_table.replace(constants.int_label).values.T
C = zmat.loc[:, ['bond', 'angle', 'dihedral']].values.T
if C.dtype == np.dtype('i8'):
C = C.astype('f8')
C[[1, 2], :] = np.radians(C[... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tx_extend(partial_tx_hex, new_inputs, new_outputs, blockchain='bitcoin', **blockchain_opts):
""" Add a set of inputs and outputs to a tx. Return the new tx o... |
if blockchain == 'bitcoin':
return btc_tx_extend(partial_tx_hex, new_inputs, new_outputs, **blockchain_opts)
else:
raise ValueError('Unknown blockchain "{}"'.format(blockchain)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setcontext(context, _local=local):
""" Set the current context to that given. Attributes provided by ``context`` override those in the current context. If ``... |
oldcontext = getcontext()
_local.__bigfloat_context__ = oldcontext + context |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _apply_function_in_context(cls, f, args, context):
""" Apply an MPFR function 'f' to the given arguments 'args', rounding to the given context. Returns a new... |
rounding = context.rounding
bf = mpfr.Mpfr_t.__new__(cls)
mpfr.mpfr_init2(bf, context.precision)
args = (bf,) + args + (rounding,)
ternary = f(*args)
with _temporary_exponent_bounds(context.emin, context.emax):
ternary = mpfr.mpfr_check_range(bf, ternary, rounding)
if context.su... |
<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_logger(name=None):
""" Get virtualchain's logger """ |
level = logging.CRITICAL
if DEBUG:
logging.disable(logging.NOTSET)
level = logging.DEBUG
if name is None:
name = "<unknown>"
log = logging.getLogger(name=name)
log.setLevel( level )
console = logging.StreamHandler()
console.setLevel( level )
log_format = ('[%(... |
<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_config_filename(impl, working_dir):
""" Get the absolute path to the config file. """ |
config_filename = impl.get_virtual_chain_name() + ".ini"
return os.path.join(working_dir, config_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 get_db_filename(impl, working_dir):
""" Get the absolute path to the last-block file. """ |
db_filename = impl.get_virtual_chain_name() + ".db"
return os.path.join(working_dir, db_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 get_snapshots_filename(impl, working_dir):
""" Get the absolute path to the chain's consensus snapshots file. """ |
snapshots_filename = impl.get_virtual_chain_name() + ".snapshots"
return os.path.join(working_dir, snapshots_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 get_lockfile_filename(impl, working_dir):
""" Get the absolute path to the chain's indexing lockfile """ |
lockfile_name = impl.get_virtual_chain_name() + ".lock"
return os.path.join(working_dir, lockfile_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 get_bitcoind_config(config_file=None, impl=None):
""" Set bitcoind options globally. Call this before trying to talk to bitcoind. """ |
loaded = False
bitcoind_server = None
bitcoind_port = None
bitcoind_user = None
bitcoind_passwd = None
bitcoind_timeout = None
bitcoind_regtest = None
bitcoind_p2p_port = None
bitcoind_spv_path = None
regtest = None
if config_file is not None:
parser = SafeConfi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_empty(self):
"""Returns True if all child date elements present are empty and other nodes are not set. Returns False if any child date elements are not em... |
return all(date.is_empty() for date in [self.created, self.issued]) \
and not self.publisher |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def is_empty(self):
'''Returns True if all titleInfo subfields are not set or
empty; returns False if any of the fields are not empty.'''
return not bool(self.title or self.subtitle or self.part_number \
or self.part_name or self.non_sort or self.type) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def is_empty(self):
'''Returns True if details, extent, and type are not set or
return True for ``is_empty``; returns False if any of the
fields are not empty.'''
return all(field.is_empty() for field in [self.details, self.extent]
if field is not 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 getinfo(self):
""" Backwards-compatibility for 0.14 and later """ |
try:
old_getinfo = AuthServiceProxy(self.__service_url, 'getinfo', self.__timeout, self.__conn, True)
res = old_getinfo()
if 'error' not in res:
# 0.13 and earlier
return res
except JSONRPCException:
pass
network_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def btc_make_payment_script( address, segwit=None, **ignored ):
""" Make a pay-to-address script. """ |
if segwit is None:
segwit = get_features('segwit')
# is address bech32-encoded?
witver, withash = segwit_addr_decode(address)
if witver is not None and withash is not None:
# bech32 segwit address
if not segwit:
raise ValueError("Segwit is disabled")
i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def btc_make_data_script( data, **ignored ):
""" Make a data-bearing transaction output. Data must be a hex string Returns a hex string. """ |
if len(data) >= MAX_DATA_LEN * 2:
raise ValueError("Data hex string is too long") # note: data is a hex string
if len(data) % 2 != 0:
raise ValueError("Data hex string is not even length")
return "6a{:02x}{}".format(len(data)/2, 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 btc_make_p2sh_address( script_hex ):
""" Make a P2SH address from a hex script """ |
h = hashing.bin_hash160(binascii.unhexlify(script_hex))
addr = bin_hash160_to_address(h, version_byte=multisig_version_byte)
return addr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def btc_make_p2wpkh_address( pubkey_hex ):
""" Make a p2wpkh address from a hex pubkey """ |
pubkey_hex = keylib.key_formatting.compress(pubkey_hex)
hash160_bin = hashing.bin_hash160(pubkey_hex.decode('hex'))
return segwit_addr_encode(hash160_bin) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def btc_make_p2sh_p2wpkh_redeem_script( pubkey_hex ):
""" Make the redeem script for a p2sh-p2wpkh witness script """ |
pubkey_hash = hashing.bin_hash160(pubkey_hex.decode('hex')).encode('hex')
redeem_script = btc_script_serialize(['0014' + pubkey_hash])
return redeem_script |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def btc_make_p2sh_p2wsh_redeem_script( witness_script_hex ):
""" Make the redeem script for a p2sh-p2wsh witness script """ |
witness_script_hash = hashing.bin_sha256(witness_script_hex.decode('hex')).encode('hex')
redeem_script = btc_script_serialize(['0020' + witness_script_hash])
return redeem_script |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def btc_is_p2sh_address( address ):
""" Is the given address a p2sh address? """ |
vb = keylib.b58check.b58check_version_byte( address )
if vb == multisig_version_byte:
return True
else:
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 btc_is_p2pkh_address( address ):
""" Is the given address a p2pkh address? """ |
vb = keylib.b58check.b58check_version_byte( address )
if vb == version_byte:
return True
else:
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 btc_is_p2wpkh_address( address ):
""" Is the given address a p2wpkh address? """ |
wver, whash = segwit_addr_decode(address)
if whash is None:
return False
if len(whash) != 20:
return False
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 btc_is_p2wsh_address( address ):
""" Is the given address a p2wsh address? """ |
wver, whash = segwit_addr_decode(address)
if whash is None:
return False
if len(whash) != 32:
return False
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 btc_is_p2sh_script( script_hex ):
""" Is the given scriptpubkey a p2sh script? """ |
if script_hex.startswith("a914") and script_hex.endswith("87") and len(script_hex) == 46:
return True
else:
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 btc_address_reencode( address, **blockchain_opts ):
""" Depending on whether or not we're in testnet or mainnet, re-encode an address accordingly. """ |
# re-encode bitcoin address
network = blockchain_opts.get('network', None)
opt_version_byte = blockchain_opts.get('version_byte', None)
if btc_is_segwit_address(address):
# bech32 address
hrp = None
if network == 'mainnet':
hrp = 'bc'
elif network == 'testn... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def btc_is_singlesig_segwit(privkey_info):
""" Is the given key bundle a p2sh-p2wpkh key bundle? """ |
try:
jsonschema.validate(privkey_info, PRIVKEY_MULTISIG_SCHEMA)
if len(privkey_info['private_keys']) > 1:
return False
return privkey_info.get('segwit', False)
except ValidationError:
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 segwit_addr_encode(witprog_bin, hrp=bech32_prefix, witver=bech32_witver):
""" Encode a segwit script hash to a bech32 address. Returns the bech32-encoded str... |
witprog_bytes = [ord(c) for c in witprog_bin]
ret = bech32_encode(hrp, [int(witver)] + convertbits(witprog_bytes, 8, 5))
assert segwit_addr_decode(hrp, ret) is not (None, None)
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_git_describe(git_str, pep440=False):
"""format the result of calling 'git describe' as a python version""" |
if git_str is None:
return None
if "-" not in git_str: # currently at a tag
return git_str
else:
# formatted as version-N-githash
# want to convert to version.postN-githash
git_str = git_str.replace("-", ".post", 1)
if pep440: # does not allow git hash afte... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_release_version():
"""Update VERSION file""" |
version = get_version(pep440=True)
with open(VERSION_FILE, "w") as outfile:
outfile.write(version)
outfile.write("\n") |
<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_version(pep440=False):
"""Tracks the version number. pep440: bool When True, this function returns a version string suitable for a release as defined by ... |
git_version = format_git_describe(call_git_describe(), pep440=pep440)
if git_version is None: # not a git repository
return read_release_version()
return git_version |
<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_git_branch():
"""return the string output of git desribe""" |
try:
with open(devnull, "w") as fnull:
arguments = [GIT_COMMAND, 'rev-parse', '--abbrev-ref', 'HEAD']
return check_output(arguments, cwd=CURRENT_DIRECTORY,
stderr=fnull).decode("ascii").strip()
except (OSError, CalledProcessError):
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 load_xmlobject_from_string(string, xmlclass=XmlObject, validate=False, resolver=None):
"""Initialize an XmlObject from a string. If an xmlclass is specified,... |
parser = _get_xmlparser(xmlclass=xmlclass, validate=validate, resolver=resolver)
element = etree.fromstring(string, parser)
return xmlclass(element) |
<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_xmlobject_from_file(filename, xmlclass=XmlObject, validate=False, resolver=None):
"""Initialize an XmlObject from a file. See :meth:`load_xmlobject_from... |
parser = _get_xmlparser(xmlclass=xmlclass, validate=validate, resolver=resolver)
tree = etree.parse(filename, parser)
return xmlclass(tree.getroot()) |
<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_zmat(cls, inputfile, implicit_index=True):
"""Reads a zmat file. Lines beginning with ``#`` are ignored. Args: inputfile (str):
implicit_index (bool):
... |
cols = ['atom', 'b', 'bond', 'a', 'angle', 'd', 'dihedral']
if implicit_index:
zmat_frame = pd.read_table(inputfile, comment='#',
delim_whitespace=True,
names=cols)
zmat_frame.index = range(1, len(zmat... |
<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_zmat(self, buf=None, upper_triangle=True, implicit_index=True, float_format='{:.6f}'.format, overwrite=True, header=False):
"""Write zmat-file Args: buf (... |
out = self.copy()
if implicit_index:
out = out.change_numbering(new_index=range(1, len(self) + 1))
if not upper_triangle:
out = out._remove_upper_triangle()
output = out.to_string(index=(not implicit_index),
float_format=float_form... |
<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_xyz(self, buf=None, sort_index=True, index=False, header=False, float_format='{:.6f}'.format, overwrite=True):
"""Write xyz-file Args: buf (str):
StringI... |
if sort_index:
molecule_string = self.sort_index().to_string(
header=header, index=index, float_format=float_format)
else:
molecule_string = self.to_string(header=header, index=index,
float_format=float_format)
... |
<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_xyz(cls, buf, start_index=0, get_bonds=True, nrows=None, engine=None):
"""Read a file of coordinate information. Reads xyz-files. Args: inputfile (str):... |
frame = pd.read_table(buf, skiprows=2, comment='#',
nrows=nrows,
delim_whitespace=True,
names=['atom', 'x', 'y', 'z'], engine=engine)
remove_digits = partial(re.sub, r'[0-9]+', '')
frame['atom'] = frame['... |
<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_cjson(self, buf=None, **kwargs):
"""Write a cjson file or return dictionary. The cjson format is specified `here <https://github.com/OpenChemistry/chemica... |
cjson_dict = {'chemical json': 0}
cjson_dict['atoms'] = {}
atomic_number = constants.elements['atomic_number'].to_dict()
cjson_dict['atoms'] = {'elements': {}}
cjson_dict['atoms']['elements']['number'] = [
int(atomic_number[x]) for x in self['atom']]
cjson... |
<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_cjson(cls, buf):
"""Read a cjson file or a dictionary. The cjson format is specified `here <https://github.com/OpenChemistry/chemicaljson>`_. Args: buf ... |
if isinstance(buf, dict):
data = buf.copy()
else:
with open(buf, 'r') as f:
data = json.load(f)
assert data['chemical json'] == 0
n_atoms = len(data['atoms']['coords']['3d'])
metadata = {}
_metadata = {}
coords = np.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 view(self, viewer=None, use_curr_dir=False):
"""View your molecule. .. note:: This function writes a temporary file and opens it with an external viewer. If ... |
if viewer is None:
viewer = settings['defaults']['viewer']
if use_curr_dir:
TEMP_DIR = os.path.curdir
else:
TEMP_DIR = tempfile.gettempdir()
def give_filename(i):
filename = 'ChemCoord_' + str(i) + '.xyz'
return os.path.join(T... |
<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_pymatgen_molecule(self):
"""Create a Molecule instance of the pymatgen library .. warning:: The `pymatgen library <http://pymatgen.org>`_ is imported loc... |
from pymatgen import Molecule
return Molecule(self['atom'].values,
self.loc[:, ['x', 'y', 'z']].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 from_pymatgen_molecule(cls, molecule):
"""Create an instance of the own class from a pymatgen molecule Args: molecule (:class:`pymatgen.core.structure.Molecu... |
new = cls(atoms=[el.value for el in molecule.species],
coords=molecule.cart_coords)
return new._to_numeric() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_ase_atoms(cls, atoms):
"""Create an instance of the own class from an ase molecule Args: molecule (:class:`ase.atoms.Atoms`):
Returns: Cartesian: """ |
return cls(atoms=atoms.get_chemical_symbols(), coords=atoms.positions) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _convert_eq(self, eq):
"""WORKS INPLACE on eq """ |
rename = dict(enumerate(self.index))
eq['eq_sets'] = {rename[k]: {rename[x] for x in v}
for k, v in eq['eq_sets'].items()}
eq['sym_ops'] = {rename[k]: {rename[x]: v[x] for x in v}
for k, v in eq['sym_ops'].items()}
try:
sym_m... |
<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_pointgroup(self, tolerance=0.3):
"""Returns a PointGroup object for the molecule. Args: tolerance (float):
Tolerance to generate the full set of symmetr... |
PA = self._get_point_group_analyzer(tolerance=tolerance)
return PointGroupOperations(PA.sch_symbol, PA.symmops) |
<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_equivalent_atoms(self, tolerance=0.3):
"""Returns sets of equivalent atoms with symmetry operations Args: tolerance (float):
Tolerance to generate the f... |
PA = self._get_point_group_analyzer(tolerance=tolerance)
eq = PA.get_equivalent_atoms()
self._convert_eq(eq)
return eq |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def btc_tx_serialize(_txobj):
""" Given a transaction dict returned by btc_tx_deserialize, convert it back into a hex-encoded byte string. Derived from code writ... |
# output buffer
o = []
txobj = None
if encoding.json_is_base(_txobj, 16):
# txobj is built from hex strings already. deserialize them
txobj = encoding.json_changebase(_txobj, lambda x: binascii.unhexlify(x))
else:
txobj = copy.deepcopy(_txobj)
# version
o.app... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def btc_tx_witness_strip( tx_serialized ):
""" Strip the witness information from a serialized transaction """ |
if not btc_tx_is_segwit(tx_serialized):
# already strippped
return tx_serialized
tx = btc_tx_deserialize(tx_serialized)
for inp in tx['ins']:
del inp['witness_script']
tx_stripped = btc_tx_serialize(tx)
return tx_stripped |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def btc_tx_script_to_asm( script_hex ):
""" Decode a script into assembler """ |
if len(script_hex) == 0:
return ""
try:
script_array = btc_script_deserialize(script_hex)
except:
log.error("Failed to convert '%s' to assembler" % script_hex)
raise
script_tokens = []
for token in script_array:
if token is None:
token = 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 btc_tx_extend(partial_tx_hex, new_inputs, new_outputs, **blockchain_opts):
""" Given an unsigned serialized transaction, add more inputs and outputs to it. @... |
# recover tx
tx = btc_tx_deserialize(partial_tx_hex)
tx_inputs, tx_outputs = tx['ins'], tx['outs']
locktime, version = tx['locktime'], tx['version']
tx_inputs += new_inputs
tx_outputs += new_outputs
new_tx = {
'ins': tx_inputs,
'outs': tx_outputs,
'locktime': lock... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def btc_tx_der_encode_length(l):
""" Return a DER-encoded length field Based on code from python-ecdsa (https://github.com/warner/python-ecdsa) by Brian Warner. ... |
if l < 0:
raise ValueError("length cannot be negative")
if l < 0x80:
return int2byte(l)
s = ("%x" % l).encode()
if len(s) % 2:
s = b("0") + s
s = binascii.unhexlify(s)
llen = len(s)
return int2byte(0x80 | llen) + s |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def btc_tx_der_encode_sequence(*encoded_pieces):
""" Return a DER-encoded sequence Based on code from python-ecdsa (https://github.com/warner/python-ecdsa) by Br... |
# borrowed from python-ecdsa
total_len = sum([len(p) for p in encoded_pieces])
return b('\x30') + btc_tx_der_encode_length(total_len) + b('').join(encoded_pieces) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def btc_tx_sighash( tx, idx, script, hashcode=SIGHASH_ALL):
""" Calculate the sighash of a non-segwit transaction. If it's SIGHASH_NONE, then digest the inputs b... |
txobj = btc_tx_deserialize(tx)
idx = int(idx)
hashcode = int(hashcode)
newtx = copy.deepcopy(txobj)
# remove all scriptsigs in all inputs, except for the ith input's scriptsig.
# the other inputs will be 'partially signed', except for SIGHASH_ANYONECANPAY mode.
for i in xrange(0, len(new... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def btc_tx_sign_multisig_segwit(tx, idx, prevout_amount, witness_script, private_keys, hashcode=SIGHASH_ALL, hashcodes=None, native=False):
""" Sign a native p2w... |
from .multisig import parse_multisig_redeemscript
if hashcodes is None:
hashcodes = [hashcode] * len(private_keys)
txobj = btc_tx_deserialize(str(tx))
privs = {}
for pk in private_keys:
pubk = ecdsalib.ecdsa_private_key(pk).public_key().to_hex()
compressed_pubkey = keyli... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def btc_privkey_scriptsig_classify(private_key_info):
""" What kind of scriptsig can this private key make? """ |
if btc_is_singlesig(private_key_info):
return 'p2pkh'
if btc_is_multisig(private_key_info):
return 'p2sh'
if btc_is_singlesig_segwit(private_key_info):
return 'p2sh-p2wpkh'
if btc_is_multisig_segwit(private_key_info):
return 'p2sh-p2wsh'
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 btc_tx_sign_all_unsigned_inputs(private_key_info, prev_outputs, unsigned_tx_hex, scriptsig_type=None, segwit=None, **blockchain_opts):
""" Sign all unsigned ... |
if segwit is None:
segwit = get_features('segwit')
txobj = btc_tx_deserialize(unsigned_tx_hex)
inputs = txobj['ins']
if scriptsig_type is None:
scriptsig_type = btc_privkey_scriptsig_classify(private_key_info)
tx_hex = unsigned_tx_hex
prevout_index = 0
# impo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def block_header_serialize( inp ):
""" Given block header information, serialize it and return the hex hash. inp has: * version (int) * prevhash (str) * merkle_r... |
# concatenate to form header
o = encoding.encode(inp['version'], 256, 4)[::-1] + \
inp['prevhash'].decode('hex')[::-1] + \
inp['merkle_root'].decode('hex')[::-1] + \
encoding.encode(inp['timestamp'], 256, 4)[::-1] + \
encoding.encode(inp['bits'], 256, 4)[::-1] + \
e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def block_header_to_hex( block_data, prev_hash ):
""" Calculate the hex form of a block's header, given its getblock information from bitcoind. """ |
header_info = {
"version": block_data['version'],
"prevhash": prev_hash,
"merkle_root": block_data['merkleroot'],
"timestamp": block_data['time'],
"bits": int(block_data['bits'], 16),
"nonce": block_data['nonce'],
"hash": block_data['hash']
}
return block_h... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def block_header_verify( block_data, prev_hash, block_hash ):
""" Verify whether or not bitcoind's block header matches the hash we expect. """ |
serialized_header = block_header_to_hex( block_data, prev_hash )
candidate_hash_bin_reversed = hashing.bin_double_sha256(binascii.unhexlify(serialized_header))
candidate_hash = binascii.hexlify( candidate_hash_bin_reversed[::-1] )
return block_hash == candidate_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 save(self, force=False):
""" Saves the configuration to a JSON, in the standard config location. Args: force (Optional[:obj:`bool`]):
Continue writing, even... |
if (not self._success) and (not force):
raise ConfigError((
'The config file appears to be corrupted:\n\n'
' {fname}\n\n'
'Before attempting to save the configuration, please either '
'fix the config file manually, or overwrite it w... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset(self):
""" Resets the configuration, and overwrites the existing configuration file. """ |
self._options = {}
self.save(force=True)
self._success = 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 run( self ):
""" Interact with the blockchain peer, until we get a socket error or we exit the loop explicitly. The order of operations is: * send version * ... |
log.debug("Segwit support: {}".format(get_features('segwit')))
self.begin()
try:
self.loop()
except socket.error, se:
if not self.finished:
# unexpected
log.exception(se)
return False
# fetch rem... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def have_all_block_data(self):
""" Have we received all block data? """ |
if not (self.num_blocks_received == self.num_blocks_requested):
log.debug("num blocks received = %s, num requested = %s" % (self.num_blocks_received, self.num_blocks_requested))
return False
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 fetch_sender_txs(self):
""" Fetch all sender txs via JSON-RPC, and merge them into our block data. Try backing off (up to 5 times) if we fail to fetch transa... |
# fetch remaining sender transactions
if len(self.sender_info.keys()) > 0:
sender_txids = self.sender_info.keys()[:]
sender_txid_batches = []
batch_size = 20
for i in xrange(0, len(sender_txids), batch_size ):
sender_txid_batche... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def block_data_sanity_checks(self):
""" Verify that the data we received makes sense. Return True on success Raise on error """ |
assert self.have_all_block_data(), "Still missing block data"
assert self.num_txs_received == len(self.sender_info.keys()), "Num TXs received: %s; num TXs requested: %s" % (self.num_txs_received, len(self.sender_info.keys()))
for (block_hash, block_info) in self.block_info.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 begin(self):
""" This method will implement the handshake of the Bitcoin protocol. It will send the Version message, and block until it receives a VerAck. On... |
log.debug("handshake (version %s)" % PROTOCOL_VERSION)
version = Version()
version.services = 0 # can't send blocks
log.debug("send Version")
self.send_message(version) |
<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_sender_info( self, sender_txhash, nulldata_vin_outpoint, sender_out_data ):
""" Record sender information in our block info. @sender_txhash: txid of the ... |
assert sender_txhash in self.sender_info.keys(), "Missing sender info for %s" % sender_txhash
assert nulldata_vin_outpoint in self.sender_info[sender_txhash], "Missing outpoint %s for sender %s" % (nulldata_vin_outpoint, sender_txhash)
block_hash = self.sender_info[sender_txhash][nulldata_vin_... |
<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_sender_info( self, block_hash, txn, i, block_height ):
""" Make sender information bundle for a particular input of a nulldata transaction. We'll use it... |
inp = txn['ins'][i]
ret = {
# to be filled in...
'scriptPubKey': None,
'addresses': None,
# for matching the input and sender funded
"txindex": txn['txindex'],
"relindex": txn['relindex'],
"output_index": inp['outpoin... |
<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_txs_rpc( self, bitcoind_opts, txids ):
""" Fetch the given list of transactions via the JSON-RPC interface. Return a dict of parsed transactions on suc... |
headers = {'content-type': 'application/json'}
reqs = []
ret = {}
for i in xrange(0, len(txids)):
txid = txids[i]
if txid == "0000000000000000000000000000000000000000000000000000000000000000":
# coinbase; we never send these
ret[t... |
<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_config(config_file=CONFIG_FILE_DEFAULT, override_url=None):
''' Read configuration file, perform sanity check and return configuration
dictionary used by other functions.'''
config = ConfigParser()
config.read_dict(DEFAULT_SETTINGS)
try:
config.readfp(open(config_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 check_config(config):
'''
Check the executor config file for consistency.
'''
# Check server URL
url = config.get("Server", "url")
try:
urlopen(url)
except Exception as e:
logger.error(
"The configured OpenSubmit server URL ({0}) seems to be invalid: {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 has_config(config_fname):
'''
Determine if the given config file exists.
'''
config = RawConfigParser()
try:
config.readfp(open(config_fname))
return True
except IOError:
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 create_config(config_fname, override_url=None):
'''
Create the config file from the defaults under the given name.
'''
config_path = os.path.dirname(config_fname)
os.makedirs(config_path, exist_ok=True)
# Consider override URL. Only used by test suite runs
settings = DEFAULT_SETTINGS_FL... |
<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_student(user):
'''
Makes the given user a student.
'''
tutor_group, owner_group = _get_user_groups()
user.is_staff = False
user.is_superuser = False
user.save()
owner_group.user_set.remove(user)
owner_group.save()
tutor_group.user_set.remove(user)
tutor_group.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 make_tutor(user):
'''
Makes the given user a tutor.
'''
tutor_group, owner_group = _get_user_groups()
user.is_staff = True
user.is_superuser = False
user.save()
owner_group.user_set.remove(user)
owner_group.save()
tutor_group.user_set.add(user)
tutor_group.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 make_owner(user):
'''
Makes the given user a owner and tutor.
'''
tutor_group, owner_group = _get_user_groups()
user.is_staff = True
user.is_superuser = False
user.save()
owner_group.user_set.add(user)
owner_group.save()
tutor_group.user_set.add(user)
tutor_group.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 make_admin(user):
'''
Makes the given user an admin.
'''
tutor_group, owner_group = _get_user_groups()
user.is_staff = True
user.is_superuser = True
user.save()
owner_group.user_set.add(user)
owner_group.save()
tutor_group.user_set.add(user)
tutor_group.save() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.