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 _remove_predicates(xast, node, context): '''Remove any constructible predicates specified in the xpath relative to the specified node. :param xast: parsed xpath (xpath abstract syntax tree) from :mod:`eulxml.xpath` :param node: lxml element which predicates will be removed from :param 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 pop(self, i=None): """Remove the item at the given position in the list, and return it. If no index is specified, removes and returns the last item in the li...
if i is None: i = len(self) - 1 val = self[i] del(self[i]) return val
<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_scc_from_tuples(constraints): """Given set of equivalences, return map of transitive equivalence classes. >> constraints = [(1,2), (2,3)] >> get_scc_from...
classes = unionfind.classes(constraints) return dict((x, tuple(c)) for x, c in classes.iteritems())
<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_field_list(fieldnames, include_parents=False): """ Parse a list of field names, possibly including dot-separated subform fields, into an internal Pars...
field_parts = (name.split('.') for name in fieldnames) return _collect_fields(field_parts, include_parents)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xmlobject_to_dict(instance, fields=None, exclude=None, prefix=''): """ Generate a dictionary based on the data in an XmlObject instance to pass as a Form's `...
data = {} # convert prefix to combining form for convenience if prefix: prefix = '%s-' % prefix else: prefix = '' for name, field in six.iteritems(instance._fields): # not editable? if fields and not name in fields: continue if exclude and name 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 update_instance(self): """Save bound form data into the XmlObject model instance and return the updated instance."""
# NOTE: django model form has a save method - not applicable here, # since an XmlObject by itself is not expected to have a save method # (only likely to be saved in context of a fedora or exist object) if hasattr(self, 'cleaned_data'): # possible to have an empty object/no 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 _update_subinstance(self, name, subform): """Save bound data for a single subform into the XmlObject model instance."""
old_subinstance = getattr(self.instance, name) new_subinstance = subform.update_instance() # if our instance previously had no node for the subform AND the # updated one has data, then attach the new node. if old_subinstance is None and not new_subinstance.is_empty(): ...
<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_bitcoind_connection( rpc_username, rpc_password, server, port, use_https, timeout ): """ Creates an RPC client to a bitcoind instance. It will have "....
from .bitcoin_blockchain import AuthServiceProxy global do_wrap_socket, create_ssl_authproxy log.debug("[%s] Connect to bitcoind at %s://%s@%s:%s, timeout=%s" % (os.getpid(), 'https' if use_https else 'http', rpc_username, server, port, timeout) ) protocol = 'https' if use_https els...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect_bitcoind_impl( bitcoind_opts ): """ Create a connection to bitcoind, using a dict of config options. """
if 'bitcoind_port' not in bitcoind_opts.keys() or bitcoind_opts['bitcoind_port'] is None: log.error("No port given") raise ValueError("No RPC port given (bitcoind_port)") if 'bitcoind_timeout' not in bitcoind_opts.keys() or bitcoind_opts['bitcoind_timeout'] is None: # 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 get_bitcoind_client(config_path=None, bitcoind_opts=None): """ Connect to bitcoind """
if bitcoind_opts is None and config_path is None: raise ValueError("Need bitcoind opts or config path") bitcoind_opts = get_bitcoind_config(config_file=config_path) log.debug("Connect to bitcoind at %s:%s (%s)" % (bitcoind_opts['bitcoind_server'], bitcoind_opts['bitcoind_port'], config_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 set_privkey_compressed(privkey, compressed=True): """ Make sure the private key given is compressed or not compressed """
if len(privkey) != 64 and len(privkey) != 66: raise ValueError("expected 32-byte private key as a hex string") # compressed? if compressed and len(privkey) == 64: privkey += '01' if not compressed and len(privkey) == 66: if privkey[-2:] != '01': raise ValueError("p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_pubkey_hex( privatekey_hex ): """ Get the uncompressed hex form of a private key """
if not isinstance(privatekey_hex, (str, unicode)): raise ValueError("private key is not a hex string but {}".format(str(type(privatekey_hex)))) # remove 'compressed' hint if len(privatekey_hex) > 64: if privatekey_hex[-2:] != '01': raise ValueError("private key does not end in ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode_privkey_hex(privkey_hex): """ Decode a private key for ecdsa signature """
if not isinstance(privkey_hex, (str, unicode)): raise ValueError("private key is not a string") # force uncompressed priv = str(privkey_hex) if len(priv) > 64: if priv[-2:] != '01': raise ValueError("private key does not end in '01'") priv = priv[:64] pk_i = 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 decode_pubkey_hex(pubkey_hex): """ Decode a public key for ecdsa verification """
if not isinstance(pubkey_hex, (str, unicode)): raise ValueError("public key is not a string") pubk = keylib.key_formatting.decompress(str(pubkey_hex)) assert len(pubk) == 130 pubk_raw = pubk[2:] pubk_i = (int(pubk_raw[:64], 16), int(pubk_raw[64:], 16)) return pubk_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 encode_signature(sig_r, sig_s): """ Encode an ECDSA signature, with low-s """
# enforce low-s if sig_s * 2 >= SECP256k1_order: log.debug("High-S to low-S") sig_s = SECP256k1_order - sig_s sig_bin = '{:064x}{:064x}'.format(sig_r, sig_s).decode('hex') assert len(sig_bin) == 64 sig_b64 = base64.b64encode(sig_bin) return sig_b64
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode_signature(sigb64): """ Decode a signature into r, s """
sig_bin = base64.b64decode(sigb64) if len(sig_bin) != 64: raise ValueError("Invalid base64 signature") sig_hex = sig_bin.encode('hex') sig_r = int(sig_hex[:64], 16) sig_s = int(sig_hex[64:], 16) return sig_r, sig_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 sign_raw_data(raw_data, privatekey_hex): """ Sign a string of data. Returns signature as a base64 string """
if not isinstance(raw_data, (str, unicode)): raise ValueError("Data is not a string") raw_data = str(raw_data) si = ECSigner(privatekey_hex) si.update(raw_data) return si.finalize()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify_raw_data(raw_data, pubkey_hex, sigb64): """ Verify the signature over a string, given the public key and base64-encode signature. Return True on succe...
if not isinstance(raw_data, (str, unicode)): raise ValueError("data is not a string") raw_data = str(raw_data) vi = ECVerifier(pubkey_hex, sigb64) vi.update(raw_data) return vi.verify()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sign_digest(hash_hex, privkey_hex, hashfunc=hashlib.sha256): """ Given a digest and a private key, sign it. Return the base64-encoded signature """
if not isinstance(hash_hex, (str, unicode)): raise ValueError("hash hex is not a string") hash_hex = str(hash_hex) pk_i = decode_privkey_hex(privkey_hex) privk = ec.derive_private_key(pk_i, ec.SECP256K1(), default_backend()) sig = privk.sign(hash_hex.decode('hex'), ec.ECDSA(utils.Prehash...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finalize(self): """ Get the base64-encoded signature itself. Can only be called once. """
signature = self.signer.finalize() sig_r, sig_s = decode_dss_signature(signature) sig_b64 = encode_signature(sig_r, sig_s) return sig_b64
<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(self, data): """ Update the hash used to generate the signature """
try: self.verifier.update(data) except TypeError: log.error("Invalid data: {} ({})".format(type(data), data)) 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 semiconvergents(x): """Semiconvergents of continued fraction expansion of a Fraction x."""
(q, n), d = divmod(x.numerator, x.denominator), x.denominator yield Fraction(q) p0, q0, p1, q1 = 1, 0, q, 1 while n: (q, n), d = divmod(d, n), n for _ in range(q): p0, q0 = p0+p1, q0+q1 yield Fraction(p0, q0) p0, q0, p1, q1 = p1, q1, p0, q0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace(self, to_replace=None, value=None, inplace=False, limit=None, regex=False, method='pad', axis=None): """Replace values given in 'to_replace' with 'va...
if inplace: self._frame.replace(to_replace=to_replace, value=value, inplace=inplace, limit=limit, regex=regex, method=method, axis=axis) else: new = self.__class__(self._frame.replace( to_replace=to_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append(self, other, ignore_index=False): """Append rows of `other` to the end of this frame, returning a new object. Wrapper around the :meth:`pandas.DataFra...
if not isinstance(other, self.__class__): raise ValueError('May only append instances of same type.') if type(ignore_index) is bool: new_frame = self._frame.append(other._frame, ignore_index=ignore_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 apply(self, *args, **kwargs): """Applies function along input axis of DataFrame. Wrapper around the :meth:`pandas.DataFrame.apply` method. """
return self.__class__(self._frame.apply(*args, **kwargs), metadata=self.metadata, _metadata=self._metadata)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def applymap(self, *args, **kwargs): """Applies function elementwise Wrapper around the :meth:`pandas.DataFrame.applymap` method. """
return self.__class__(self._frame.applymap(*args, **kwargs), metadata=self.metadata, _metadata=self._metadata)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def marshal_with_model(model, excludes=None, only=None, extends=None): """With this decorator, you can return ORM model instance, or ORM query in view function d...
if isinstance(excludes, six.string_types): excludes = [excludes] if excludes and only: only = None elif isinstance(only, six.string_types): only = [only] field_definition = {} for col in model.__table__.columns: if only: if col.name not in only: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def quick_marshal(*args, **kwargs): """In some case, one view functions may return different model in different situation. Use `marshal_with_model` to handle thi...
@marshal_with_model(*args, **kwargs) def fn(value): return value return fn
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _wrap_field(field): """Improve Flask-RESTFul's original field type"""
class WrappedField(field): def output(self, key, obj): value = _fields.get_value(key if self.attribute is None else self.attribute, obj) # For all fields, when its value was null (None), return null directly, # instead of return its default value (eg. int type's defaul...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_configuration_file(filepath=_give_default_file_path(), overwrite=False): """Create a configuration file. Writes the current state of settings into a co...
config = configparser.ConfigParser() config.read_dict(settings) if os.path.isfile(filepath) and not overwrite: try: raise FileExistsError except NameError: # because of python2 warn('File exists already and overwrite is False (default).') else: with ope...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hasSubseries(self): """Check if this component has subseries or not. Determined based on level of first subcomponent (series or subseries) or if first compon...
if self.c and self.c[0] and ((self.c[0].level in ('series', 'subseries')) or (self.c[0].c and self.c[0].c[0])): 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 initialize( self, M_c, M_r, T, seed, initialization=b'from_the_prior', row_initialization=-1, n_chains=1, ROW_CRP_ALPHA_GRID=(), COLUMN_CRP_ALPHA_GRID=(), S_G...
# FIXME: why is M_r passed? arg_tuples = self.get_initialize_arg_tuples( M_c, M_r, T, initialization, row_initialization, n_chains, ROW_CRP_ALPHA_GRID, COLUMN_CRP_ALPHA_GRID, S_GRID, MU_GRID, N_GRID, make_get_next_seed(seed),) chain_tuples = self.mapper(self...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert( self, M_c, T, X_L_list, X_D_list, new_rows=None, N_GRID=31, CT_KERNEL=0): """Insert mutates the data T."""
if new_rows is None: raise ValueError("new_row must exist") if not isinstance(new_rows, list): raise TypeError('new_rows must be list of lists') if not isinstance(new_rows[0], list): raise TypeError('new_rows must be list of lists') X_L_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 analyze(self, M_c, T, X_L, X_D, seed, kernel_list=(), n_steps=1, c=(), r=(), max_iterations=-1, max_time=-1, do_diagnostics=False, diagnostics_every_N=1, ROW_...
if n_steps <= 0: raise ValueError("You must do at least one analyze step.") if CT_KERNEL not in [0, 1]: raise ValueError("CT_KERNEL must be 0 (Gibbs) or 1 (MH)") if do_timing: # Diagnostics and timing are exclusive. do_diagnostics = 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 simple_predictive_sample(self, M_c, X_L, X_D, Y, Q, seed, n=1): """Sample values from predictive distribution of the given latent state. :param Y: A list of ...
get_next_seed = make_get_next_seed(seed) samples = _do_simple_predictive_sample( M_c, X_L, X_D, Y, Q, n, get_next_seed) return samples
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mutual_information( self, M_c, X_L_list, X_D_list, Q, seed, n_samples=1000): """Estimate mutual information for each pair of columns on Q given the set of sa...
get_next_seed = make_get_next_seed(seed) return iu.mutual_information( M_c, X_L_list, X_D_list, Q, get_next_seed, n_samples)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def similarity( self, M_c, X_L_list, X_D_list, given_row_id, target_row_id, target_columns=None): """Computes the similarity of the given row to the target row, ...
return su.similarity( M_c, X_L_list, X_D_list, given_row_id, target_row_id, target_columns)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def impute(self, M_c, X_L, X_D, Y, Q, seed, n): """Impute values from predictive distribution of the given latent state. :param Y: A list of constraints to apply...
get_next_seed = make_get_next_seed(seed) e = su.impute(M_c, X_L, X_D, Y, Q, n, get_next_seed) return 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 impute_and_confidence(self, M_c, X_L, X_D, Y, Q, seed, n): """Impute values and confidence of the value from the predictive distribution of the given latent ...
get_next_seed = make_get_next_seed(seed) if isinstance(X_L, (list, tuple)): assert isinstance(X_D, (list, tuple)) # TODO: multistate impute doesn't exist yet # e,confidence = su.impute_and_confidence_multistate( # M_c, X_L, X_D, Y, Q, n, self.get_next_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 ensure_col_dep_constraints( self, M_c, M_r, T, X_L, X_D, dep_constraints, seed, max_rejections=100): """Ensures dependencey or indepdendency between columns....
X_L_list, X_D_list, was_multistate = su.ensure_multistate(X_L, X_D) if was_multistate: num_states = len(X_L_list) else: num_states = 1 dependencies = [(c[0], c[1]) for c in dep_constraints if c[2]] independencies = [(c[0], c[1]) for c in dep_constraints...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_row_dep_constraint( self, M_c, T, X_L, X_D, row1, row2, dependent=True, wrt=None, max_iter=100, force=False): """Ensures dependencey or indepdendency ...
X_L_list, X_D_list, was_multistate = su.ensure_multistate(X_L, X_D) if force: raise NotImplementedError else: kernel_list = ('row_partition_assignements',) for i, (X_L_i, X_D_i) in enumerate(zip(X_L_list, X_D_list)): iters = 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 parse_format_specifier(specification): """ Parse the given format specification and return a dictionary containing relevant values. """
m = _parse_format_specifier_regex.match(specification) if m is None: raise ValueError( "Invalid format specifier: {!r}".format(specification)) format_dict = m.groupdict('') # Convert zero-padding into fill and alignment. zeropad = format_dict.pop('zeropad') if zeropad: ...
<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_bonds(self, self_bonding_allowed=False, offset=3, modified_properties=None, use_lookup=False, set_lookup=True, atomic_radius_data=None ): """Return a dic...
if atomic_radius_data is None: atomic_radius_data = settings['defaults']['atomic_radius_data'] def complete_calculation(): old_index = self.index self.index = range(len(self)) fragments = self._divide_et_impera(offset=offset) positions = 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 get_coordination_sphere( self, index_of_atom, n_sphere=1, give_only_index=False, only_surface=True, exclude=None, use_lookup=None): """Return a Cartesian of ...
if use_lookup is None: use_lookup = settings['defaults']['use_lookup'] exclude = set() if exclude is None else exclude bond_dict = self.get_bonds(use_lookup=use_lookup) i = index_of_atom if n_sphere != 0: visited = set([i]) | exclude try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _preserve_bonds(self, sliced_cartesian, use_lookup=None): """Is called after cutting geometric shapes. If you want to change the rules how bonds are preserve...
if use_lookup is None: use_lookup = settings['defaults']['use_lookup'] included_atoms_set = set(sliced_cartesian.index) assert included_atoms_set.issubset(set(self.index)), \ 'The sliced Cartesian has to be a subset of the bigger frame' bond_dic = self.get_bonds...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cut_sphere( self, radius=15., origin=None, outside_sliced=True, preserve_bonds=False): """Cut a sphere specified by origin and radius. Args: radius (float): ...
if origin is None: origin = np.zeros(3) elif pd.api.types.is_list_like(origin): origin = np.array(origin, dtype='f8') else: origin = self.loc[origin, ['x', 'y', 'z']] molecule = self.get_distance_to(origin) if outside_sliced: mole...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cut_cuboid( self, a=20, b=None, c=None, origin=None, outside_sliced=True, preserve_bonds=False): """Cut a cuboid specified by edge and radius. Args: a (float...
if origin is None: origin = np.zeros(3) elif pd.api.types.is_list_like(origin): origin = np.array(origin, dtype='f8') else: origin = self.loc[origin, ['x', 'y', 'z']] b = a if b is None else b c = a if c is None else c sides = np.arra...
<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_barycenter(self): """Return the mass weighted average location. Args: None Returns: :class:`numpy.ndarray`: """
try: mass = self['mass'].values except KeyError: mass = self.add_data('mass')['mass'].values pos = self.loc[:, ['x', 'y', 'z']].values return (pos * mass[:, None]).sum(axis=0) / self.get_total_mass()
<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_bond_lengths(self, indices): """Return the distances between given atoms. Calculates the distance between the atoms with indices ``i`` and ``b``. The ind...
coords = ['x', 'y', 'z'] if isinstance(indices, pd.DataFrame): i_pos = self.loc[indices.index, coords].values b_pos = self.loc[indices.loc[:, 'b'], coords].values else: indices = np.array(indices) if len(indices.shape) == 1: indice...
<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_angle_degrees(self, indices): """Return the angles between given atoms. Calculates the angle in degrees between the atoms with indices ``i, b, a``. The i...
coords = ['x', 'y', 'z'] if isinstance(indices, pd.DataFrame): i_pos = self.loc[indices.index, coords].values b_pos = self.loc[indices.loc[:, 'b'], coords].values a_pos = self.loc[indices.loc[:, 'a'], coords].values else: indices = np.array(indice...
<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_dihedral_degrees(self, indices, start_row=0): """Return the dihedrals between given atoms. Calculates the dihedral angle in degrees between the atoms wit...
coords = ['x', 'y', 'z'] if isinstance(indices, pd.DataFrame): i_pos = self.loc[indices.index, coords].values b_pos = self.loc[indices.loc[:, 'b'], coords].values a_pos = self.loc[indices.loc[:, 'a'], coords].values d_pos = self.loc[indices.loc[:, 'd'], 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 fragmentate(self, give_only_index=False, use_lookup=None): """Get the indices of non bonded parts in the molecule. Args: give_only_index (bool): If ``True``...
if use_lookup is None: use_lookup = settings['defaults']['use_lookup'] fragments = [] pending = set(self.index) self.get_bonds(use_lookup=use_lookup) while pending: index = self.get_coordination_sphere( pending.pop(), use_lookup=True, 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 restrict_bond_dict(self, bond_dict): """Restrict a bond dictionary to self. Args: bond_dict (dict): Look into :meth:`~chemcoord.Cartesian.get_bonds`, to see...
return {j: bond_dict[j] & set(self.index) for j in self.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 get_fragment(self, list_of_indextuples, give_only_index=False, use_lookup=None): """Get the indices of the atoms in a fragment. The list_of_indextuples conta...
if use_lookup is None: use_lookup = settings['defaults']['use_lookup'] exclude = [tuple[0] for tuple in list_of_indextuples] index_of_atom = list_of_indextuples[0][1] fragment_index = self.get_coordination_sphere( index_of_atom, exclude=set(exclude), n_sphere=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 get_without(self, fragments, use_lookup=None): """Return self without the specified fragments. Args: fragments: Either a list of :class:`~chemcoord.Cartesian...
if use_lookup is None: use_lookup = settings['defaults']['use_lookup'] if pd.api.types.is_list_like(fragments): for fragment in fragments: try: index_of_all_fragments |= fragment.index except NameError: ind...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _jit_pairwise_distances(pos1, pos2): """Optimized function for calculating the distance between each pair of points in positions1 and positions2. Does use py...
n1 = pos1.shape[0] n2 = pos2.shape[0] D = np.empty((n1, n2)) for i in range(n1): for j in range(n2): D[i, j] = np.sqrt(((pos1[i] - pos2[j])**2).sum()) return D
<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_inertia(self): """Calculate the inertia tensor and transforms along rotation axes. This function calculates the inertia tensor and returns a 4-tuple. The...
def calculate_inertia_tensor(molecule): masses = molecule.loc[:, 'mass'].values pos = molecule.loc[:, ['x', 'y', 'z']].values inertia = np.sum( masses[:, None, None] * ((pos**2).sum(axis=1)[:, None, None] * np.identity(3)[No...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def basistransform(self, new_basis, old_basis=None, orthonormalize=True): """Transform the frame to a new basis. This function transforms the cartesian coordinat...
if old_basis is None: old_basis = np.identity(3) is_rotation_matrix = np.isclose(np.linalg.det(new_basis), 1) if not is_rotation_matrix and orthonormalize: new_basis = xyz_functions.orthonormalize_righthanded(new_basis) is_rotation_matrix = True if ...
<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_distance_to(self, origin=None, other_atoms=None, sort=False): """Return a Cartesian with a column for the distance from origin. """
if origin is None: origin = np.zeros(3) elif pd.api.types.is_list_like(origin): origin = np.array(origin, dtype='f8') else: origin = self.loc[origin, ['x', 'y', 'z']] if other_atoms is None: other_atoms = self.index new = self.lo...
<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, rename_dict, inplace=False): """Return the reindexed version of Cartesian. Args: rename_dict (dict): A dictionary mapping integers on...
output = self if inplace else self.copy() new_index = [rename_dict.get(key, key) for key in self.index] output.index = new_index if not inplace: return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def partition_chem_env(self, n_sphere=4, use_lookup=None): """This function partitions the molecule into subsets of the same chemical environment. A chemical env...
if use_lookup is None: use_lookup = settings['defaults']['use_lookup'] def get_chem_env(self, i, n_sphere): env_index = self.get_coordination_sphere( i, n_sphere=n_sphere, only_surface=False, give_only_index=True, use_lookup=use_lookup) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def align(self, other, indices=None, ignore_hydrogens=False): """Align two Cartesians. Minimize the RMSD (root mean squared deviation) between ``self`` and ``oth...
m1 = (self - self.get_centroid()).sort_index() m2 = (other - other.get_centroid()).sort_index() if indices is not None and ignore_hydrogens: message = 'Indices != None and ignore_hydrogens == True is invalid' raise IllegalArgumentCombination(message) elif 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 reindex_similar(self, other, n_sphere=4): """Reindex ``other`` to be similarly indexed as ``self``. Returns a reindexed copy of ``other`` that minimizes the ...
def make_subset_similar(m1, subset1, m2, subset2, index_dct): """Changes index_dct INPLACE""" coords = ['x', 'y', 'z'] index1 = list(subset1) for m1_i in index1: dist_m2_to_m1_i = m2.get_distance_to(m1.loc[m1_i, coords], ...
<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_date(date_str): """Parse elastic datetime string."""
if not date_str: return None try: date = ciso8601.parse_datetime(date_str) if not date: date = arrow.get(date_str).datetime except TypeError: date = arrow.get(date_str[0]).datetime 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 get_dates(schema): """Return list of datetime fields for given schema."""
dates = [config.LAST_UPDATED, config.DATE_CREATED] for field, field_schema in schema.items(): if field_schema['type'] == 'datetime': dates.append(field) return dates
<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_doc(hit, schema, dates): """Format given doc to match given schema."""
doc = hit.get('_source', {}) doc.setdefault(config.ID_FIELD, hit.get('_id')) doc.setdefault('_type', hit.get('_type')) if hit.get('highlight'): doc['es_highlight'] = hit.get('highlight') if hit.get('inner_hits'): doc['_inner_hits'] = {} for key, value in hit.get('inner_hits...
<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_filters(query, base_filters): """Put together all filters we have and set them as 'and' filter within filtered query. :param query: elastic query being c...
filters = [f for f in base_filters if f is not None] query_filter = query['query']['filtered'].get('filter', None) if query_filter is not None: if 'and' in query_filter: filters.extend(query_filter['and']) else: filters.append(query_filter) if filters: qu...
<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_es(url, **kwargs): """Create elasticsearch client instance. :param url: elasticsearch url """
urls = [url] if isinstance(url, str) else url kwargs.setdefault('serializer', ElasticJSONSerializer()) es = elasticsearch.Elasticsearch(urls, **kwargs) return es
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_elastic_query(doc): """ Build a query which follows ElasticSearch syntax from doc. 1. Converts {"q":"cricket"} to the below elastic query:: { "query": ...
elastic_query, filters = {"query": {"filtered": {}}}, [] for key in doc.keys(): if key == 'q': elastic_query['query']['filtered']['query'] = _build_query_string(doc['q']) else: _value = doc[key] filters.append({"terms": {key: _value}} if isinstance(_value, l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_query_string(q, default_field=None, default_operator='AND'): """ Build ``query_string`` object from ``q``. :param q: q of type String :param default_f...
def _is_phrase_search(query_string): clean_query = query_string.strip() return clean_query and clean_query.startswith('"') and clean_query.endswith('"') def _get_phrase(query_string): return query_string.strip().strip('"') if _is_phrase_search(q): query = {'match_phrase': ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default(self, value): """Convert mongo.ObjectId."""
if isinstance(value, ObjectId): return str(value) return super(ElasticJSONSerializer, self).default(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extra(self, response): """Add extra info to response."""
if 'facets' in self.hits: response['_facets'] = self.hits['facets'] if 'aggregations' in self.hits: response['_aggregations'] = self.hits['aggregations']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_index(self, app=None): """Create indexes and put mapping."""
elasticindexes = self._get_indexes() for index, settings in elasticindexes.items(): es = settings['resource'] if not es.indices.exists(index): self.create_index(index, settings.get('index_settings'), es) continue else: ...
<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_indexes(self): """Based on the resource definition calculates the index definition"""
indexes = {} for resource in self._get_elastic_resources(): try: index = self._resource_index(resource) except KeyError: # ignore missing continue if index not in indexes: indexes.update({ 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 _get_mapping(self, schema): """Get mapping for given resource or item schema. :param schema: resource or dict/list type item schema """
properties = {} for field, field_schema in schema.items(): field_mapping = self._get_field_mapping(field_schema) if field_mapping: properties[field] = field_mapping return {'properties': 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 _get_field_mapping(self, schema): """Get mapping for single field schema. :param schema: field schema """
if 'mapping' in schema: return schema['mapping'] elif schema['type'] == 'dict' and 'schema' in schema: return self._get_mapping(schema['schema']) elif schema['type'] == 'list' and 'schema' in schema.get('schema', {}): return self._get_mapping(schema['schema']...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_index(self, index=None, settings=None, es=None): """Create new index and ignore if it exists already."""
if index is None: index = self.index if es is None: es = self.es try: alias = index index = generate_index_name(alias) args = {'index': index} if settings: args['body'] = settings es.indices.cr...
<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_mapping(self, app, index=None): """Put mapping for elasticsearch for current schema. It's not called automatically now, but rather left for user to call ...
for resource, resource_config in self._get_elastic_resources().items(): datasource = resource_config.get('datasource', {}) if not is_elastic(datasource): continue if datasource.get('source', resource) != resource: # only put mapping for core 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 get_mapping(self, index, doc_type=None): """Get mapping for index. :param index: index name """
mapping = self.es.indices.get_mapping(index=index, doc_type=doc_type) return next(iter(mapping.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 get_settings(self, index): """Get settings for index. :param index: index name """
settings = self.es.indices.get_settings(index=index) return next(iter(settings.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 get_index_by_alias(self, alias): """Get index name for given alias. If there is no alias assume it's an index. :param alias: alias name """
try: info = self.es.indices.get_alias(name=alias) return next(iter(info.keys())) except elasticsearch.exceptions.NotFoundError: return alias
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def should_aggregate(self, req): """Check the environment variable and the given argument parameter to decide if aggregations needed. argument value is expected ...
try: return self.app.config.get('ELASTICSEARCH_AUTO_AGGREGATIONS') or \ bool(req.args and int(req.args.get('aggregations'))) except (AttributeError, TypeError): 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 should_highlight(self, req): """ Check the given argument parameter to decide if highlights needed. argument value is expected to be '0' or '1' """
try: return bool(req.args and int(req.args.get('es_highlight', 0))) except (AttributeError, TypeError): 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 should_project(self, req): """ Check the given argument parameter to decide if projections needed. argument value is expected to be a list of strings """
try: return req.args and json.loads(req.args.get('projections', [])) except (AttributeError, TypeError): 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 get_projected_fields(self, req): """ Returns the projected fields from request. """
try: args = getattr(req, 'args', {}) return ','.join(json.loads(args.get('projections'))) except (AttributeError, TypeError): 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 find_one(self, resource, req, **lookup): """Find single document, if there is _id in lookup use that, otherwise filter."""
if config.ID_FIELD in lookup: return self._find_by_id(resource=resource, _id=lookup[config.ID_FIELD], parent=lookup.get('parent')) else: args = self._es_args(resource) filters = [{'term': {key: val}} for key, val in lookup.items()] query = {'query': {'co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_by_id(self, resource, _id, parent=None): """Find the document by Id. If parent is not provided then on routing exception try to find using search. """
def is_found(hit): if 'exists' in hit: hit['found'] = hit['exists'] return hit.get('found', False) args = self._es_args(resource) try: # set the parent if available if parent: args['parent'] = parent 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 find_one_raw(self, resource, _id): """Find document by id."""
return self._find_by_id(resource=resource, _id=_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_list_of_ids(self, resource, ids, client_projection=None): """Find documents by ids."""
args = self._es_args(resource) return self._parse_hits(self.elastic(resource).mget(body={'ids': ids}, **args), 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 insert(self, resource, doc_or_docs, **kwargs): """Insert document, it must be new if there is ``_id`` in it."""
ids = [] kwargs.update(self._es_args(resource)) for doc in doc_or_docs: self._update_parent_args(resource, kwargs, doc) _id = doc.pop('_id', None) res = self.elastic(resource).index(body=doc, id=_id, **kwargs) doc.setdefault('_id', res.get('_id', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bulk_insert(self, resource, docs, **kwargs): """Bulk insert documents."""
kwargs.update(self._es_args(resource)) parent_type = self._get_parent_type(resource) if parent_type: for doc in docs: if doc.get(parent_type.get('field')): doc['_parent'] = doc.get(parent_type.get('field')) res = bulk(self.elastic(resourc...
<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(self, resource, id_, updates): """Update document in index."""
args = self._es_args(resource, refresh=True) if self._get_retry_on_conflict(): args['retry_on_conflict'] = self._get_retry_on_conflict() updates.pop('_id', None) updates.pop('_type', None) self._update_parent_args(resource, args, updates) return self.elastic...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace(self, resource, id_, document): """Replace document in index."""
args = self._es_args(resource, refresh=True) document.pop('_id', None) document.pop('_type', None) self._update_parent_args(resource, args, document) return self.elastic(resource).index(body=document, id=id_, **args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self, resource, lookup=None, parent=None, **kwargs): """Remove docs for resource. :param resource: resource name :param lookup: filter :param parent: ...
kwargs.update(self._es_args(resource)) if parent: kwargs['parent'] = parent if lookup: if lookup.get('_id'): try: return self.elastic(resource).delete(id=lookup.get('_id'), refresh=True, **kwargs) except elasticsearch....
<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, resource): """Test if there is no document for resource. :param resource: resource name """
args = self._es_args(resource) res = self.elastic(resource).count(body={'query': {'match_all': {}}}, **args) return res.get('count', 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 put_settings(self, app=None, index=None, settings=None, es=None): """Modify index settings. Index must exist already. """
if not index: index = self.index if not app: app = self.app if not es: es = self.es if not settings: return for alias, old_settings in self.es.indices.get_settings(index=index).items(): try: if test_...
<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_hits(self, hits, resource): """Parse hits response into documents."""
datasource = self.get_datasource(resource) schema = {} schema.update(config.DOMAIN[datasource[0]].get('schema', {})) schema.update(config.DOMAIN[resource].get('schema', {})) dates = get_dates(schema) docs = [] for hit in hits.get('hits', {}).get('hits', []): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _es_args(self, resource, refresh=None, source_projections=None): """Get index and doctype args."""
datasource = self.get_datasource(resource) args = { 'index': self._resource_index(resource), 'doc_type': datasource[0], } if source_projections: args['_source'] = source_projections if refresh: args['refresh'] = refresh re...
<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_parent_id(self, resource, document): """Get the Parent Id of the document :param resource: resource name :param document: document containing the parent ...
parent_type = self._get_parent_type(resource) if parent_type and document: return document.get(parent_type.get('field')) 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 _fields(self, resource): """Get projection fields for given resource."""
datasource = self.get_datasource(resource) keys = datasource[2].keys() return ','.join(keys) + ','.join([config.LAST_UPDATED, config.DATE_CREATED])