text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_email_address(self): """ Return full email address from login and domain from params in class initialization or generate new. """
if self.login is None: self.login = self.generate_login() available_domains = self.available_domains if self.domain is None: self.domain = random.choice(available_domains) elif self.domain not in available_domains: raise ValueError('Domain not found ...
<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_mailbox(self, email=None, email_hash=None): """ Return list of emails in given email address or dict with `error` key if mail box is empty. :param email:...
if email is None: email = self.get_email_address() if email_hash is None: email_hash = self.get_hash(email) url = 'http://{0}/request/mail/id/{1}/format/json/'.format( self.api_domain, email_hash) req = requests.get(url) return req.json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def setup_domain_socket(location): ''' Setup Domain Socket Setup a connection to a Unix Domain Socket -- @param location:str The path to the Unix Domain Socket to connect to. @return <class 'socket._socketobject'> ''' clientsocket = socket.socket(socket.AF_UNI...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def setup_tcp_socket(location, port): ''' Setup TCP Socket Setup a connection to a TCP Socket -- @param location:str The Hostname / IP Address of the remote TCP Socket. @param port:int The TCP Port the remote Socket is listening on. @return <class 'sock...
<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_primary_zone(self, account_name, zone_name): """Creates a new primary zone. Arguments: account_name -- The name of the account that will contain this ...
zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "NEW"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_primary_zone_by_upload(self, account_name, zone_name, bind_file): """Creates a new primary zone by uploading a bind file Arguments: account_name -- Th...
zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "UPLOAD"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} files = {'zone': ('', json.dumps(zone_data), 'appli...
<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_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new primary zone by zone transferring off a m...
zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} prim...
<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_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new secondary zone. Arguments: account_name -- The ...
zone_properties = {"name": zone_name, "accountName": account_name, "type": "SECONDARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} na...
<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_zones_of_account(self, account_name, q=None, **kwargs): """Returns a list of zones for the specified account. Arguments: account_name -- The name of the ...
uri = "/v1/accounts/" + account_name + "/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_zones(self, q=None, **kwargs): """Returns a list of zones across all of the user's accounts. Keyword Arguments: q -- The search parameters, in a dict. Va...
uri = "/v1/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def edit_secondary_name_server(self, zone_name, primary=None, backup=None, second_backup=None): """Edit the axfr name servers of a secondary zone. Arguments: zon...
name_server_info = {} if primary is not None: name_server_info['nameServerIp1'] = {'ip':primary} if backup is not None: name_server_info['nameServerIp2'] = {'ip':backup} if second_backup is not None: name_server_info['nameServerIp3'] = {'ip':second_ba...
<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_rrsets(self, zone_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone. Arguments: zone_name -- The name of the zone. Keyword Arg...
uri = "/v1/zones/" + zone_name + "/rrsets" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata): """Creates a new RRSet in the specified zone. Arguments: zone_name -- The zone that will contai...
if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name, json.dumps(rrset))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None): """Updates an existing RRSet in the specified zone. Arguments: zone_name -- The zon...
if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} if profile: rrset["profile"] = profile uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return self.rest_api_connection.put(uri, json.dumps(rrset))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def edit_rrset_rdata(self, zone_name, rtype, owner_name, rdata, profile=None): """Updates an existing RRSet's Rdata in the specified zone. Arguments: zone_name -...
if type(rdata) is not list: rdata = [rdata] rrset = {"rdata": rdata} method = "patch" if profile: rrset["profile"] = profile method = "put" uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return getattr(self.rest...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_rrset(self, zone_name, rtype, owner_name): """Deletes an RRSet. Arguments: zone_name -- The zone containing the RRSet to be deleted. The trailing dot ...
return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_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 create_web_forward(self, zone_name, request_to, redirect_to, forward_type): """Create a web forward record. Arguments: zone_name -- The zone in which the web...
web_forward = {"requestTo": request_to, "defaultRedirectTo": redirect_to, "defaultForwardType": forward_type} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/webforwards", json.dumps(web_forward))
<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_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Creates a new SB Pool. Arguments: zone_name -- The zone that ...
rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset))
<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_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Creates a new TC Pool. Arguments: zone_name -- The zone that conta...
rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset))
<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, other): """Remove a particular factor from a tensor product space."""
if other is FullSpace: return TrivialSpace if other is TrivialSpace: return self if isinstance(other, ProductSpace): oops = set(other.operands) else: oops = {other} return ProductSpace.create( *sorted(set(self.opera...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intersect(self, other): """Find the mutual tensor factors of two Hilbert spaces."""
if other is FullSpace: return self if other is TrivialSpace: return TrivialSpace if isinstance(other, ProductSpace): other_ops = set(other.operands) else: other_ops = {other} return ProductSpace.create( *sorted(set(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _isinstance(expr, classname): """Check whether `expr` is an instance of the class with name `classname` This is like the builtin `isinstance`, but it take th...
for cls in type(expr).__mro__: if cls.__name__ == classname: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decompose_space(H, A): """Simplifies OperatorTrace expressions over tensor-product spaces by turning it into iterated partial traces. Args: H (ProductSpace):...
return OperatorTrace.create( OperatorTrace.create(A, over_space=H.operands[-1]), over_space=ProductSpace.create(*H.operands[:-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 factor_coeff(cls, ops, kwargs): """Factor out coefficients of all factors."""
coeffs, nops = zip(*map(_coeff_term, ops)) coeff = 1 for c in coeffs: coeff *= c if coeff == 1: return nops, coeffs else: return coeff * cls.create(*nops, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def doit(self, classes=None, recursive=True, **kwargs): """Write out commutator Write out the commutator according to its definition $[\Op{A}, \Op{B}] = \Op{A}\O...
return super().doit(classes, recursive, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _attrprint(d, delimiter=', '): """Print a dictionary of attributes in the DOT format"""
return delimiter.join(('"%s"="%s"' % item) for item in sorted(d.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 _styleof(expr, styles): """Merge style dictionaries in order"""
style = dict() for expr_filter, sty in styles: if expr_filter(expr): style.update(sty) return style
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _git_version(): """If installed with 'pip installe -e .' from inside a git repo, the current git revision as a string"""
import subprocess import os def _minimal_ext_cmd(cmd): # construct minimal environment env = {} for k in ['SYSTEMROOT', 'PATH']: v = os.environ.get(k) if v is not None: env[k] = v # LANGUAGE is used on win32 env['LANGUAGE'] =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pad_with_identity(circuit, k, n): """Pad a circuit by adding a `n`-channel identity circuit at index `k` That is, a circuit of channel dimension $N$ is exten...
circuit_n = circuit.cdim combined_circuit = circuit + circuit_identity(n) permutation = (list(range(k)) + list(range(circuit_n, circuit_n + n)) + list(range(k, circuit_n))) return (CPermutation.create(invert_permutation(permutation)) << combined_circuit << CPermutation.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 move_drive_to_H(slh, which=None, expand_simplify=True): r'''Move coherent drives from the Lindblad operators to the Hamiltonian. For the given SLH model, move inhomogeneities in the Lindblad operators (resulting from the presence of a coherent drive, see :class:`CoherentDriveCC`) to the Hamiltonian...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_adiabatic_limit(slh, k=None): """Prepare the adiabatic elimination on an SLH object Args: slh: The SLH object to take the limit for k: The scaling pa...
if k is None: k = symbols('k', positive=True) Ld = slh.L.dag() LdL = (Ld * slh.L)[0, 0] K = (-LdL / 2 + I * slh.H).expand().simplify_scalar() N = slh.S.dag() B, A, Y = K.series_expand(k, 0, 2) G, F = Ld.series_expand(k, 0, 1) return Y, A, B, F, G, 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 eval_adiabatic_limit(YABFGN, Ytilde, P0): """Compute the limiting SLH model for the adiabatic approximation Args: YABFGN: The tuple (Y, A, B, F, G, N) as ret...
Y, A, B, F, G, N = YABFGN Klim = (P0 * (B - A * Ytilde * A) * P0).expand().simplify_scalar() Hlim = ((Klim - Klim.dag())/2/I).expand().simplify_scalar() Ldlim = (P0 * (G - A * Ytilde * F) * P0).expand().simplify_scalar() dN = identity_matrix(N.shape[0]) + F.H * Ytilde * F Nlim = (P0 * N * dN...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def try_adiabatic_elimination(slh, k=None, fock_trunc=6, sub_P0=True): """Attempt to automatically do adiabatic elimination on an SLH object This will project th...
ops = prepare_adiabatic_limit(slh, k) Y = ops[0] if isinstance(Y.space, LocalSpace): try: b = Y.space.basis_labels if len(b) > fock_trunc: b = b[:fock_trunc] except BasisNotSetError: b = range(fock_trunc) projectors = set(LocalProj...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def index_in_block(self, channel_index: int) -> int: """Return the index a channel has within the subblock it belongs to I.e., only for reducible circuits, this g...
if channel_index < 0 or channel_index >= self.cdim: raise ValueError() struct = self.block_structure if len(struct) == 1: return channel_index, 0 i = 1 while sum(struct[:i]) <= channel_index and i < self.cdim: i += 1 block_index = 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 get_blocks(self, block_structure=None): """For a reducible circuit, get a sequence of subblocks that when concatenated again yield the original circuit. The ...
if block_structure is None: block_structure = self.block_structure try: return self._get_blocks(block_structure) except IncompatibleBlockStructures as e: raise 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 show(self): """Show the circuit expression in an IPython notebook."""
# noinspection PyPackageRequirements from IPython.display import Image, display fname = self.render() display(Image(filename=fname))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render(self, fname=''): """Render the circuit expression and store the result in a file Args: fname (str): Path to an image file to store the result in. Ret...
import qnet.visualization.circuit_pyx as circuit_visualization from tempfile import gettempdir from time import time, sleep if not fname: tmp_dir = gettempdir() fname = os.path.join(tmp_dir, "tmp_{}.png".format(hash(time))) if circuit_visualization.dra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def space(self): """Total Hilbert space"""
args_spaces = (self.S.space, self.L.space, self.H.space) return ProductSpace.create(*args_spaces)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def free_symbols(self): """Set of all symbols occcuring in S, L, or H"""
return set.union( self.S.free_symbols, self.L.free_symbols, self.H.free_symbols)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expand(self): """Expand out all operator expressions within S, L and H Return a new :class:`SLH` object with these expanded expressions. """
return SLH(self.S.expand(), self.L.expand(), self.H.expand())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def simplify_scalar(self, func=sympy.simplify): """Simplify all scalar expressions within S, L and H Return a new :class:`SLH` object with the simplified express...
return SLH( self.S.simplify_scalar(func=func), self.L.simplify_scalar(func=func), self.H.simplify_scalar(func=func))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def symbolic_master_equation(self, rho=None): """Compute the symbolic Liouvillian acting on a state rho If no rho is given, an OperatorSymbol is created in its p...
L, H = self.L, self.H if rho is None: rho = OperatorSymbol('rho', hs=self.space) return (-I * (H * rho - rho * H) + sum(Lk * rho * adjoint(Lk) - (adjoint(Lk) * Lk * rho + rho * adjoint(Lk) * Lk) / 2 for Lk in L.matrix.ravel()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def symbolic_heisenberg_eom( self, X=None, noises=None, expand_simplify=True): """Compute the symbolic Heisenberg equations of motion of a system operator X. If ...
L, H = self.L, self.H if X is None: X = OperatorSymbol('X', hs=(L.space | H.space)) summands = [I * (H * X - X * H), ] for Lk in L.matrix.ravel(): summands.append(adjoint(Lk) * X * Lk) summands.append(-(adjoint(Lk) * Lk * X + X * adjoint(Lk) * Lk) /...
<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_perms(self): """If the circuit is reducible into permutations within subranges of the full range of channels, this yields a tuple with the internal per...
if not self._block_perms: self._block_perms = permutation_to_block_permutations( self.permutation) return self._block_perms
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def series_with_permutation(self, other): """Compute the series product with another channel permutation circuit Args: other (CPermutation): Returns: Circuit: T...
combined_permutation = tuple([self.permutation[p] for p in other.permutation]) return CPermutation.create(combined_permutation)
<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, data, chart_type, options=None, filename='chart', w=800, h=420, overwrite=True): """Save the rendered html to a file in the same directory as the ...
html = self.render( data=data, chart_type=chart_type, options=options, div_id=filename, head=self.head, w=w, h=h) if overwrite: with open(filename.replace(" ", "_") + '.html', 'w') as f: f.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 _unicode_sub_super(string, mapping, max_len=None): """Try to render a subscript or superscript string in unicode, fall back on ascii if this is not possible"...
string = str(string) if string.startswith('(') and string.endswith(')'): len_string = len(string) - 2 else: len_string = len(string) if max_len is not None: if len_string > max_len: raise KeyError("max_len exceeded") unicode_letters = [] for letter in string:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _translate_symbols(string): """Given a description of a Greek letter or other special character, return the appropriate unicode letter."""
res = [] string = str(string) for s in re.split(r'(\W+)', string, flags=re.UNICODE): tex_str = _GREEK_DICTIONARY.get(s) if tex_str: res.append(tex_str) elif s.lower() in _GREEK_DICTIONARY: res.append(_GREEK_DICTIONARY[s]) else: res.append(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_and_save(self, data, w=800, h=420, filename='chart', overwrite=True): """Save the rendered html to a file and returns an IFrame to display the plot in t...
self.save(data, filename, overwrite) return IFrame(filename + '.html', w, 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 _get_from_cache(self, expr): """Obtain cached result, prepend with the keyname if necessary, and indent for the current level"""
is_cached, res = super()._get_from_cache(expr) if is_cached: indent_str = " " * self._print_level return True, indent(res, indent_str) else: return False, 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 _write_to_cache(self, expr, res): """Store the cached result without indentation, and without the keyname"""
res = dedent(res) super()._write_to_cache(expr, res)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _translate_symbols(string): """Given a description of a Greek letter or other special character, return the appropriate latex."""
res = [] for s in re.split(r'([,.:\s=]+)', string): tex_str = _TEX_GREEK_DICTIONARY.get(s) if tex_str: res.append(tex_str) elif s.lower() in greek_letters_set: res.append("\\" + s.lower()) elif s in other_symbols: res.append("\\" + 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 _render_str(self, string): """Returned a texified version of the string"""
if isinstance(string, StrLabel): string = string._render(string.expr) string = str(string) if len(string) == 0: return '' name, supers, subs = split_super_sub(string) return render_latex_sub_super( name, subs, supers, translate_symbols=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 is_symbol(string): """ Return true if the string is a mathematical symbol. """
return ( is_int(string) or is_float(string) or is_constant(string) or is_unary(string) or is_binary(string) or (string == '(') or (string == ')') )
<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_word_groups(string, words): """ Find matches for words in the format "3 thousand 6 hundred 2". The words parameter should be the list of words to check ...
scale_pattern = '|'.join(words) # For example: # (?:(?:\d+)\s+(?:hundred|thousand)*\s*)+(?:\d+|hundred|thousand)+ regex = re.compile( r'(?:(?:\d+)\s+(?:' + scale_pattern + r')*\s*)+(?:\d+|' + scale_pattern + r')+' ) result = regex.findall(string) return resul...
<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_word_tokens(string, language): """ Given a string and an ISO 639-2 language code, return the string with the words replaced with an operational equiv...
words = mathwords.word_groups_for_language(language) # Replace operator words with numeric operators operators = words['binary_operators'].copy() if 'unary_operators' in words: operators.update(words['unary_operators']) for operator in list(operators.keys()): if operator in string...
<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_postfix(tokens): """ Convert a list of evaluatable tokens to postfix format. """
precedence = { '/': 4, '*': 4, '+': 3, '-': 3, '^': 2, '(': 1 } postfix = [] opstack = [] for token in tokens: if is_int(token): postfix.append(int(token)) elif is_float(token): postfix.append(float(token)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def evaluate_postfix(tokens): """ Given a list of evaluatable tokens in postfix format, calculate a solution. """
stack = [] for token in tokens: total = None if is_int(token) or is_float(token) or is_constant(token): stack.append(token) elif is_unary(token): a = stack.pop() total = mathwords.UNARY_FUNCTIONS[token](a) elif len(stack): b = st...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tokenize(string, language=None, escape='___'): """ Given a string, return a list of math symbol tokens """
# Set all words to lowercase string = string.lower() # Ignore punctuation if len(string) and not string[-1].isalnum(): character = string[-1] string = string[:-1] + ' ' + character # Parenthesis must have space around them to be tokenized properly string = string.replace('(', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(string, language=None): """ Return a solution to the equation in the input string. """
if language: string = replace_word_tokens(string, language) tokens = tokenize(string) postfix = to_postfix(tokens) return evaluate_postfix(postfix)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expr_order_key(expr): """A default order key for arbitrary expressions"""
if hasattr(expr, '_order_key'): return expr._order_key try: if isinstance(expr.kwargs, OrderedDict): key_vals = expr.kwargs.values() else: key_vals = [expr.kwargs[key] for key in sorted(expr.kwargs)] return KeyTuple((expr.__class__.__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 Sum(idx, *args, **kwargs): """Instantiator for an arbitrary indexed sum. This returns a function that instantiates the appropriate :class:`QuantumIndexedSum`...
from qnet.algebra.core.hilbert_space_algebra import LocalSpace from qnet.algebra.core.scalar_algebra import ScalarValue from qnet.algebra.library.spin_algebra import SpinSpace dispatch_table = { tuple(): _sum_over_fockspace, (LocalSpace, ): _sum_over_fockspace, (SpinSpace, ): _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 diff(self, sym: Symbol, n: int = 1, expand_simplify: bool = True): """Differentiate by scalar parameter `sym`. Args: sym: What to differentiate by. n: How of...
if not isinstance(sym, sympy.Basic): raise TypeError("%s needs to be a Sympy symbol" % sym) if sym.free_symbols.issubset(self.free_symbols): # QuantumDerivative.create delegates internally to _diff (the # explicit non-trivial derivative). Using `create` gives us free...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def series_expand( self, param: Symbol, about, order: int) -> tuple: r"""Expand the expression as a truncated power series in a scalar parameter. When expanding a...
expansion = self._series_expand(param, about, order) # _series_expand is generally not "type-stable", so we continue to # ensure the type-stability res = [] for v in expansion: if v == 0 or v.is_zero: v = self._zero elif v == 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 factor_for_space(self, spc): """Return a tuple of two products, where the first product contains the given Hilbert space, and the second product is disjunct ...
if spc == TrivialSpace: ops_on_spc = [ o for o in self.operands if o.space is TrivialSpace] ops_not_on_spc = [ o for o in self.operands if o.space > TrivialSpace] else: ops_on_spc = [ o for o in self.operands if (o.spac...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def evaluate_at(self, vals): """Evaluate the derivative at a specific point"""
new_vals = self._vals.copy() new_vals.update(vals) return self.__class__(self.operand, derivs=self._derivs, vals=new_vals)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bound_symbols(self): """Set of Sympy symbols that are eliminated by evaluation."""
if self._bound_symbols is None: res = set() self._bound_symbols = res.union( *[sym.free_symbols for sym in self._vals.keys()]) return self._bound_symbols
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_dot(self, code, options, format, prefix='graphviz'): # type: (nodes.NodeVisitor, unicode, Dict, unicode, unicode) -> Tuple[unicode, unicode] """Render...
graphviz_dot = options.get('graphviz_dot', self.builder.config.graphviz_dot) hashkey = (code + str(options) + str(graphviz_dot) + str(self.builder.config.graphviz_dot_args)).encode('utf-8') fname = '%s-%s.%s' % (prefix, sha1(hashkey).hexdigest(), format) relfn = posixpath.join(self.buil...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_clickable_map(self): # type: () -> unicode """Generate clickable map tags if clickable item exists. If not exists, this only returns empty string. "...
if self.clickable: return '\n'.join([self.content[0]] + self.clickable + [self.content[-1]]) else: 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 next_basis_label_or_index(self, label_or_index, n=1): """Given the label or index of a basis state, return the label the next basis state. More generally, if...
if isinstance(label_or_index, int): new_index = label_or_index + n if new_index < 0: raise IndexError("index %d < 0" % new_index) if new_index >= self.dimension: raise IndexError( "index %d out of range for basis %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 texinfo_visit_inheritance_diagram(self, node): # type: (nodes.NodeVisitor, inheritance_diagram) -> None """ Output the graph for Texinfo. This will insert a ...
graph = node['graph'] graph_hash = get_graph_hash(node) name = 'inheritance%s' % graph_hash dotcode = graph.generate_dot(name, env=self.builder.env, graph_attrs={'size': '"6.0,6.0"'}) render_dot_texinfo(self, node, dotcode, {}, 'inheritance') raise nodes.SkipN...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def class_name(self, cls, parts=0, aliases=None): # type: (Any, int, Optional[Dict[unicode, unicode]]) -> unicode """Given a class object, return a fully-qualifi...
module = cls.__module__ if module in ('__builtin__', 'builtins'): fullname = cls.__name__ else: fullname = '%s.%s' % (module, cls.__name__) if parts == 0: result = fullname else: name_parts = fullname.split('.') result ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def codemirror_settings_update(configs, parameters, on=None, names=None): """ Return a new dictionnary of configs updated with given parameters. You may use ``on...
# Deep copy of given config output = copy.deepcopy(configs) # Optionnaly filtering config from given names if names: output = {k: output[k] for k in names} # Select every config if selectors is empty if not on: on = output.keys() for k in on: output[k].update(para...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lhs(self): """The left-hand-side of the equation"""
lhs = self._lhs i = 0 while lhs is None: i -= 1 lhs = self._prev_lhs[i] return lhs
<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_tag(self, tag): """Return a copy of the equation with a new `tag`"""
return Eq( self._lhs, self._rhs, tag=tag, _prev_lhs=self._prev_lhs, _prev_rhs=self._prev_rhs, _prev_tags=self._prev_tags)
<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, func, *args, cont=False, tag=None, **kwargs): """Apply `func` to both sides of the equation Returns a new equation where the left-hand-side and r...
new_lhs = func(self.lhs, *args, **kwargs) if new_lhs == self.lhs and cont: new_lhs = None new_rhs = func(self.rhs, *args, **kwargs) new_tag = tag return self._update(new_lhs, new_rhs, new_tag, cont)
<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_mtd(self, mtd, *args, cont=False, tag=None, **kwargs): """Call the method `mtd` on both sides of the equation That is, the left-hand-side and right-han...
new_lhs = getattr(self.lhs, mtd)(*args, **kwargs) if new_lhs == self.lhs and cont: new_lhs = None new_rhs = getattr(self.rhs, mtd)(*args, **kwargs) new_tag = tag return self._update(new_lhs, new_rhs, new_tag, cont)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def substitute(self, var_map, cont=False, tag=None): """Substitute sub-expressions both on the lhs and rhs Args: var_map (dict): Dictionary with entries of the ...
return self.apply(substitute, var_map=var_map, cont=cont, tag=tag)
<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(self, func=None, *args, **kwargs): """Subtract the rhs from the lhs of the equation Before the substraction, each side is expanded and any scalars are...
res = ( self.lhs.expand().simplify_scalar() - self.rhs.expand().simplify_scalar()) if func is not None: return func(res, *args, **kwargs) else: return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self): """Return a copy of the equation"""
return Eq( self._lhs, self._rhs, tag=self._tag, _prev_lhs=self._prev_lhs, _prev_rhs=self._prev_rhs, _prev_tags=self._prev_tags)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def free_symbols(self): """Set of free SymPy symbols contained within the equation."""
try: lhs_syms = self.lhs.free_symbols except AttributeError: lhs_syms = set() try: rhs_syms = self.rhs.free_symbols except AttributeError: rhs_syms = set() return lhs_syms | rhs_syms
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bound_symbols(self): """Set of bound SymPy symbols contained within the equation."""
try: lhs_syms = self.lhs.bound_symbols except AttributeError: lhs_syms = set() try: rhs_syms = self.rhs.bound_symbols except AttributeError: rhs_syms = set() return lhs_syms | rhs_syms
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def SympyCreate(n): """Creation operator for a Hilbert space of dimension `n`, as an instance of `sympy.Matrix`"""
a = sympy.zeros(n) for i in range(1, n): a += sympy.sqrt(i) * basis_state(i, n) * basis_state(i-1, n).H return a
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def formfield_for_dbfield(self, db_field, **kwargs): """ Allow formfield_overrides to contain field names too. """
overrides = self.formfield_overrides.get(db_field.name) if overrides: kwargs.update(overrides) field = super(AbstractEntryBaseAdmin, self).formfield_for_dbfield(db_field, **kwargs) # Pass user to the form. if db_field.name == 'author': field.user = kwar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _split_op( self, identifier, hs_label=None, dagger=False, args=None): """Return `name`, total `subscript`, total `superscript` and `arguments` str. All of th...
if self._isinstance(identifier, 'SymbolicLabelBase'): identifier = QnetAsciiDefaultPrinter()._print_SCALAR_TYPES( identifier.expr) name, total_subscript = self._split_identifier(identifier) total_superscript = '' if (hs_label not in [None, '']): 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 _render_hs_label(self, hs): """Return the label of the given Hilbert space as a string"""
if isinstance(hs.__class__, Singleton): return self._render_str(hs.label) else: return self._tensor_sym.join( [self._render_str(ls.label) for ls in hs.local_factors])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parenthesize(self, expr, level, *args, strict=False, **kwargs): """Render `expr` and wrap the result in parentheses if the precedence of `expr` is below the ...
needs_parenths = ( (precedence(expr) < level) or (strict and precedence(expr) == level)) if needs_parenths: return ( self._parenth_left + self.doprint(expr, *args, **kwargs) + self._parenth_right) else: return self....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw_circuit(circuit, filename, direction = 'lr', hunit = HUNIT, vunit = VUNIT, rhmargin = RHMARGIN, rvmargin = RVMARGIN, rpermutation_length = RPLENGTH, draw...
if direction == 'lr': hunit = abs(hunit) elif direction == 'rl': hunit = -abs(hunit) try: c, dims, c_in, c_out = draw_circuit_canvas(circuit, hunit = hunit, vunit = vunit, rhmargin = rhmargin, rvmargin = rvmargin, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nested_tuple(container): """Recursively transform a container structure to a nested tuple. The function understands container types inheriting from the selec...
if isinstance(container, OrderedDict): return tuple(map(nested_tuple, container.items())) if isinstance(container, Mapping): return tuple(sorted_if_possible(map(nested_tuple, container.items()))) if not isinstance(container, (str, bytes)): if isinstance(container, Sequence): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def precedence(item): """Returns the precedence of a given object."""
try: mro = item.__class__.__mro__ except AttributeError: return PRECEDENCE["Atom"] for i in mro: n = i.__name__ if n in PRECEDENCE_FUNCTIONS: return PRECEDENCE_FUNCTIONS[n](item) elif n in PRECEDENCE_VALUES: return PRECEDENCE_VALUES[n] 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 callback_prototype(prototype): """Decorator to process a callback prototype. A callback prototype is a function whose signature includes all the values that ...
protosig = signature(prototype) positional, keyword = [], [] for name, param in protosig.parameters.items(): if param.kind in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD): raise TypeError("*args/**kwargs not supported in prototypes") if (param.default is not Parameter.empt...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def published(self, for_user=None): """ Return only published entries for the current site. """
if appsettings.FLUENT_BLOGS_FILTER_SITE_ID: qs = self.parent_site(settings.SITE_ID) else: qs = self if for_user is not None and for_user.is_staff: return qs return qs \ .filter(status=self.model.PUBLISHED) \ .filter( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authors(self, *usernames): """ Return the entries written by the given usernames When multiple tags are provided, they operate as "OR" query. """
if len(usernames) == 1: return self.filter(**{"author__{}".format(User.USERNAME_FIELD): usernames[0]}) else: return self.filter(**{"author__{}__in".format(User.USERNAME_FIELD): usernames})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def categories(self, *category_slugs): """ Return the entries with the given category slugs. When multiple tags are provided, they operate as "OR" query. """
categories_field = getattr(self.model, 'categories', None) if categories_field is None: raise AttributeError("The {0} does not include CategoriesEntryMixin".format(self.model.__name__)) if issubclass(categories_field.rel.model, TranslatableModel): # Needs a different fi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tagged(self, *tag_slugs): """ Return the items which are tagged with a specific tag. When multiple tags are provided, they operate as "OR" query. """
if getattr(self.model, 'tags', None) is None: raise AttributeError("The {0} does not include TagsEntryMixin".format(self.model.__name__)) if len(tag_slugs) == 1: return self.filter(tags__slug=tag_slugs[0]) else: return self.filter(tags__slug__in=tag_slugs).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 format(self, **kwargs): """Format and combine the name, subscript, and superscript"""
name = self.name.format(**kwargs) subs = [] if self.sub is not None: subs = [self.sub.format(**kwargs)] supers = [] if self.sup is not None: supers = [self.sup.format(**kwargs)] return render_unicode_sub_super( name, subs, supers, 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 _render_str(self, string): """Returned a unicodified version of the string"""
if isinstance(string, StrLabel): string = string._render(string.expr) string = str(string) if len(string) == 0: return '' name, supers, subs = split_super_sub(string) return render_unicode_sub_super( name, subs, supers, sub_first=True, transla...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def PauliX(local_space, states=None): r"""Pauli-type X-operator .. math:: \hat{\sigma}_x = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} on an arbitrary two-level...
local_space, states = _get_pauli_args(local_space, states) g, e = states return ( LocalSigma.create(g, e, hs=local_space) + LocalSigma.create(e, g, hs=local_space))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def PauliY(local_space, states=None): r""" Pauli-type Y-operator .. math:: \hat{\sigma}_x = \begin{pmatrix} 0 & -i \\ i & 0 \end{pmatrix} on an arbitrary two-lev...
local_space, states = _get_pauli_args(local_space, states) g, e = states return I * (-LocalSigma.create(g, e, hs=local_space) + LocalSigma.create(e, g, hs=local_space))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def PauliZ(local_space, states=None): r"""Pauli-type Z-operator .. math:: \hat{\sigma}_x = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix} on an arbitrary two-leve...
local_space, states = _get_pauli_args(local_space, states) g, e = states return ( LocalProjector(g, hs=local_space) - LocalProjector(e, hs=local_space))