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 in available domains!')
return u'{0}{1}'.format(self.login, self.domain)
|
<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: (optional) email address. :param email_hash: (optional) md5 hash from email address. """
|
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_UNIX, socket.SOCK_STREAM)
clientsocket.settimeout(timeout)
clientsocket.connect(location)
return clientsocket
|
<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 'socket._socketobject'>
'''
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.settimeout(timeout)
clientsocket.connect((location, port))
return clientsocket
|
<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. zone_name -- The name of the zone. It must be unique. """
|
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.dumps(zone_data))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_primary_zone_by_upload(self, account_name, zone_name, bind_file):
"""Creates a new primary zone by uploading a bind file Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. bind_file -- The file to upload. """
|
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), 'application/json'),
'file': ('file', open(bind_file, 'rb'), 'application/octet-stream')}
return self.rest_api_connection.post_multi_part("/v1/zones", files)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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 master. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """
|
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}
primary_zone_info = {"forceImport": True, "createType": "TRANSFER", "nameServer": name_server_info}
zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info}
return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None):
"""Creates a new secondary zone. Arguments: account_name -- The name of the account. zone_name -- The name of the zone. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """
|
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}
name_server_ip_1 = {"nameServerIp1": name_server_info}
name_server_ip_list = {"nameServerIpList": name_server_ip_1}
secondary_zone_info = {"primaryNameServers": name_server_ip_list}
zone_data = {"properties": zone_properties, "secondaryCreateInfo": secondary_zone_info}
return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_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 account. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """
|
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. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """
|
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: zone_name -- The name of the secondary zone being edited. primary -- The primary name server value. Keyword Arguments: backup -- The backup name server if any. second_backup -- The second backup name server. """
|
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_backup}
name_server_ip_list = {"nameServerIpList": name_server_info}
secondary_zone_info = {"primaryNameServers": name_server_ip_list}
zone_data = {"secondaryCreateInfo": secondary_zone_info}
return self.rest_api_connection.patch("/v1/zones/" + zone_name, json.dumps(zone_data))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_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 Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """
|
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 contain the new RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The TTL value for the RRSet. rdata -- The BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. """
|
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 zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """
|
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 -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """
|
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_api_connection, method)(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 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 is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) """
|
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 forward is to be created. request_to -- The URL to be redirected. You may use http:// and ftp://. forward_type -- The type of forward. Valid options include: Framed HTTP_301_REDIRECT HTTP_302_REDIRECT HTTP_303_REDIRECT HTTP_307_REDIRECT """
|
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 contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record_list -- list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """
|
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 contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record -- dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """
|
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.operands).difference(oops)))
|
<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(self.operands).intersection(other_ops)))
|
<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 the `classname` a string, instead of the class directly. Useful for when we don't want to import the class for which we want to check (also, remember that printer choose rendering method based on the class name, so this is totally ok) """
|
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):
The full space. A (Operator):
Returns: Operator: Iterative partial trace expression """
|
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}\Op{B} - \Op{A}\Op{B}$. See :meth:`.Expression.doit`. """
|
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'] = 'C'
env['LANG'] = 'C'
env['LC_ALL'] = 'C'
FNULL = open(os.devnull, 'w')
cwd = os.path.dirname(os.path.realpath(__file__))
proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=FNULL, env=env, cwd=cwd)
out = proc.communicate()[0]
return out
try:
out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD'])
return out.strip().decode('ascii')
except OSError:
return "unknown"
|
<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 extended to one of channel through the system unaffected. E.g. let ``A``, ``B`` be two single channel systems:: A + cid(2) + B This method can also be applied to irreducible systems, but in that case the result can not be decomposed as nicely. Args: circuit (Circuit):
circuit to pad k (int):
The index at which to insert the circuit n (int):
The number of channels to pass through Returns: Circuit: An extended circuit that passes through the channels """
|
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.create(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 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.
This exploits the invariance of the Lindblad master equation under the
transformation (cf. Breuer and Pettrucione, Ch 3.2.1)
.. math::
:nowrap:
\begin{align}
\Op{L}_i &\longrightarrow \Op{L}_i' = \Op{L}_i - \alpha_i \\
\Op{H} &\longrightarrow
\Op{H}' = \Op{H} + \frac{1}{2i} \sum_j
(\alpha_j \Op{L}_j^{\dagger} - \alpha_j^* \Op{L}_j)
\end{align}
In the context of SLH, this transformation is achieved by feeding `slh` into
.. math::
\SLH(\identity, -\mat{\alpha}, 0)
where $\mat{\alpha}$ has the elements $\alpha_i$.
Parameters
----------
slh : SLH
SLH model to transform. If `slh` does not contain any inhomogeneities, it is
invariant under the transformation.
which : sequence or None
Sequence of circuit dimensions to apply the transform to. If None, all
dimensions are transformed.
expand_simplify : bool
if True, expand and simplify the new SLH object before returning. This has no
effect if `slh` does not contain any inhomogeneities.
Returns
-------
new_slh : SLH
Transformed SLH model.
'''
if which is None:
which = []
scalarcs = []
for jj, L in enumerate(slh.Ls):
if not which or jj in which:
scalarcs.append(-get_coeffs(L.expand())[IdentityOperator])
else:
scalarcs.append(0)
if np.all(np.array(scalarcs) == 0):
return slh
new_slh = SLH(identity_matrix(slh.cdim), scalarcs, 0) << slh
if expand_simplify:
return new_slh.expand().simplify_scalar()
return new_slh
|
<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 parameter $k \rightarrow \infty$. The default is a positive symbol 'k' Returns: tuple: The objects ``Y, A, B, F, G, N`` necessary to compute the limiting system. """
|
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 returned by prepare_adiabatic_limit. Ytilde: The pseudo-inverse of Y, satisfying Y * Ytilde = P0. P0: The projector onto the null-space of Y. Returns: SLH: Limiting SLH model """
|
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 * P0).expand().simplify_scalar()
return SLH(Nlim.dag(), Ldlim.dag(), Hlim.dag())
|
<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 the `Y` operator onto a truncated basis with dimension specified by `fock_trunc`. `sub_P0` controls whether an attempt is made to replace the kernel projector P0 by an :class:`.IdentityOperator`. """
|
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(LocalProjector(ll, hs=Y.space) for ll in b)
Id_trunc = sum(projectors, ZeroOperator)
Yprojection = (
((Id_trunc * Y).expand() * Id_trunc)
.expand().simplify_scalar())
termcoeffs = get_coeffs(Yprojection)
terms = set(termcoeffs.keys())
for term in terms - projectors:
cannot_eliminate = (
not isinstance(term, LocalSigma) or
not term.operands[1] == term.operands[2])
if cannot_eliminate:
raise CannotEliminateAutomatically(
"Proj. Y operator has off-diagonal term: ~{}".format(term))
P0 = sum(projectors - terms, ZeroOperator)
if P0 == ZeroOperator:
raise CannotEliminateAutomatically("Empty null-space of Y!")
Yinv = sum(t/termcoeffs[t] for t in terms & projectors)
assert (
(Yprojection*Yinv).expand().simplify_scalar() ==
(Id_trunc - P0).expand())
slhlim = eval_adiabatic_limit(ops, Yinv, P0)
if sub_P0:
# TODO for non-unit rank P0, this will not work
slhlim = slhlim.substitute(
{P0: IdentityOperator}).expand().simplify_scalar()
return slhlim
else:
raise CannotEliminateAutomatically(
"Currently only single degree of freedom Y-operators supported")
|
<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 gives a result different from the argument itself. Args: channel_index (int):
The index of the external channel Raises: ValueError: for an invalid `channel_index` """
|
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 - 1
index_in_block = channel_index - sum(struct[:block_index])
return index_in_block, block_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_blocks(self, block_structure=None):
"""For a reducible circuit, get a sequence of subblocks that when concatenated again yield the original circuit. The block structure given has to be compatible with the circuits actual block structure, i.e. it can only be more coarse-grained. Args: block_structure (tuple):
The block structure according to which the subblocks are generated (default = ``None``, corresponds to the circuit's own block structure) Returns: A tuple of subblocks that the circuit consists of. Raises: .IncompatibleBlockStructures """
|
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. Returns: str: The path to the image file """
|
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.draw_circuit(self, fname):
done = False
for k in range(20):
if os.path.exists(fname):
done = True
break
else:
sleep(.5)
if done:
return fname
raise CannotVisualize()
|
<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 expressions. See also: :meth:`.QuantumExpression.simplify_scalar` """
|
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 place. This correspnds to the RHS of the master equation in which an average is taken over the external noise degrees of freedom. Args: rho (Operator):
A symbolic density matrix operator Returns: Operator: The RHS of the master equation. """
|
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 no X is given, an OperatorSymbol is created in its place. If no noises are given, this correspnds to the ensemble-averaged Heisenberg equation of motion. Args: X (Operator):
A system operator noises (Operator):
A vector of noise inputs Returns: Operator: The RHS of the Heisenberg equations of motion of X. """
|
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) / 2)
if noises is not None:
if not isinstance(noises, Matrix):
noises = Matrix(noises)
LambdaT = (noises.adjoint().transpose() * noises.transpose()).transpose()
assert noises.shape == L.shape
S = self.S
summands.append((adjoint(noises) * S.adjoint() * (X * L - L * X))
.expand()[0, 0])
summand = (((L.adjoint() * X - X * L.adjoint()) * S * noises)
.expand()[0, 0])
summands.append(summand)
if len(S.space & X.space):
comm = (S.adjoint() * X * S - X)
summands.append((comm * LambdaT).expand().trace())
ret = OperatorPlus.create(*summands)
if expand_simplify:
ret = ret.expand().simplify_scalar()
return ret
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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 permutations for each such block. :type: tuple """
|
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: The composite permutation circuit (could also be the identity circuit for n channels) """
|
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 notebook."""
|
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.write(html)
else:
if not os.path.exists(filename.replace(" ", "_") + '.html'):
with open(filename.replace(" ", "_") + '.html', 'w') as f:
f.write(html)
else:
raise IOError('File Already Exists!')
|
<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:
unicode_letters.append(mapping[letter])
return ''.join(unicode_letters)
|
<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(s)
return "".join(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 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 the notebook."""
|
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)
else:
if re.match(r'^[a-zA-Z]{4,}$', s):
res.append(r'\text{' + s + '}')
else:
res.append(s)
return "".join(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 _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 for such as "hundred". """
|
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 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 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 equivalent. """
|
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:
string = string.replace(operator, operators[operator])
# Replace number words with numeric values
numbers = words['numbers']
for number in list(numbers.keys()):
if number in string:
string = string.replace(number, str(numbers[number]))
# Replace scaling multipliers with numeric values
scales = words['scales']
end_index_characters = mathwords.BINARY_OPERATORS
end_index_characters.add('(')
word_matches = find_word_groups(string, list(scales.keys()))
for match in word_matches:
string = string.replace(match, '(' + match + ')')
for scale in list(scales.keys()):
for _ in range(0, string.count(scale)):
start_index = string.find(scale) - 1
end_index = len(string)
while is_int(string[start_index - 1]) and start_index > 0:
start_index -= 1
end_index = string.find(' ', start_index) + 1
end_index = string.find(' ', end_index) + 1
add = ' + '
if string[end_index] in end_index_characters:
add = ''
string = string[:start_index] + '(' + string[start_index:]
string = string.replace(
scale, '* ' + str(scales[scale]) + ')' + add,
1
)
string = string.replace(') (', ') + (')
return 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))
elif token in mathwords.CONSTANTS:
postfix.append(mathwords.CONSTANTS[token])
elif is_unary(token):
opstack.append(token)
elif token == '(':
opstack.append(token)
elif token == ')':
top_token = opstack.pop()
while top_token != '(':
postfix.append(top_token)
top_token = opstack.pop()
else:
while (opstack != []) and (
precedence[opstack[-1]] >= precedence[token]
):
postfix.append(opstack.pop())
opstack.append(token)
while opstack != []:
postfix.append(opstack.pop())
return 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 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 = stack.pop()
a = stack.pop()
if token == '+':
total = a + b
elif token == '-':
total = a - b
elif token == '*':
total = a * b
elif token == '^':
total = a ** b
elif token == '/':
if Decimal(str(b)) == 0:
total = 'undefined'
else:
total = Decimal(str(a)) / Decimal(str(b))
else:
raise PostfixTokenEvaluationException(
'Unknown token {}'.format(token)
)
if total is not None:
stack.append(total)
# If the stack is empty the tokens could not be evaluated
if not stack:
raise PostfixTokenEvaluationException(
'The postfix expression resulted in an empty stack'
)
return stack.pop()
|
<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('(', ' ( ')
string = string.replace(')', ' ) ')
if language:
words = mathwords.words_for_language(language)
for phrase in words:
escaped_phrase = phrase.replace(' ', escape)
string = string.replace(phrase, escaped_phrase)
tokens = string.split()
for index, token in enumerate(tokens):
tokens[index] = token.replace(escape, ' ')
return tokens
|
<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__, ) +
tuple(map(expr_order_key, expr.args)) +
tuple(map(expr_order_key, key_vals)))
except AttributeError:
return str(expr)
|
<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` subclass for a given term expression. It is the preferred way to "manually" create indexed sum expressions, closely resembling the normal mathematical notation for sums. Args: idx (IdxSym):
The index symbol over which the sum runs args: arguments that describe the values over which `idx` runs, kwargs: keyword-arguments, used in addition to `args` Returns: callable: an instantiator function that takes a arbitrary `term` that should generally contain the `idx` symbol, and returns an indexed sum over that `term` with the index range specified by the original `args` and `kwargs`. There is considerable flexibility to specify concise `args` for a variety of index ranges. Assume the following setup:: Giving `i` as the only argument will sum over the indices of the basis states of the Hilbert space of `term`:: '∑_{i ∈ ℌ₀} |i⟩⁽⁰⁾' You may also specify a Hilbert space manually:: True Note that using :func:`Sum` is vastly more readable than the equivalent "manual" instantiation:: True By nesting calls to `Sum`, you can instantiate sums running over multiple indices:: '∑_{i,j ∈ ℌ₀} |i⟩⟨j|⁽⁰⁾' Giving two integers in addition to the index `i` in `args`, the index will run between the two values:: '∑_{i=1}^{10} |i⟩⁽⁰⁾' True You may also include an optional step width, either as a third integer or using the `step` keyword argument. Lastly, by passing a tuple or list of values, the index will run over all the elements in that tuple or list:: '∑_{i ∈ {1,2,3}} |i⟩⁽⁰⁾' """
|
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, ): _sum_over_fockspace,
(list, ): _sum_over_list,
(tuple, ): _sum_over_list,
(int, ): _sum_over_range,
(int, int): _sum_over_range,
(int, int, int): _sum_over_range,
}
key = tuple((type(arg) for arg in args))
try:
idx_range_func = dispatch_table[key]
except KeyError:
raise TypeError("No implementation for args of type %s" % str(key))
def sum(term):
if isinstance(term, ScalarValue._val_types):
term = ScalarValue.create(term)
idx_range = idx_range_func(term, idx, *args, **kwargs)
return term._indexed_sum_cls.create(term, idx_range)
return sum
|
<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 often to differentiate expand_simplify: Whether to simplify the result. Returns: The n-th derivative. """
|
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
# caching
deriv = QuantumDerivative.create(self, derivs={sym: n}, vals=None)
if not deriv.is_zero and expand_simplify:
deriv = deriv.expand().simplify_scalar()
return deriv
else:
# the "issubset" of free symbols is a sufficient, but not a
# necessary condition; if `sym` is non-atomic, determining whether
# `self` depends on `sym` is not completely trivial (you'd have to
# substitute with a Dummy)
return self.__class__._zero
|
<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 an expr for a parameter $x$ about the point $x_0$ up to order $N$, the resulting coefficients $(c_1, \dots, c_N)$ fulfill .. math:: \text{expr} = \sum_{n=0}^{N} c_n (x - x_0)^n + O(N+1) Args: param: Expansion parameter $x$ about (Scalar):
Point $x_0$ about which to expand order: Maximum order $N$ of expansion (>= 0) Returns: tuple of length ``order + 1``, where the entries are the expansion coefficients, $(c_0, \dots, c_N)$. Note: The expansion coefficients are "type-stable", in that they share a common base class with the original expression. In particular, this applies to "zero" coefficients:: """
|
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:
v = self._one
assert isinstance(v, self._base_cls)
res.append(v)
return tuple(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 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 from it."""
|
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.space & spc) > TrivialSpace]
ops_not_on_spc = [
o for o in self.operands if (o.space & spc) is TrivialSpace]
return (
self.__class__._times_cls.create(*ops_on_spc),
self.__class__._times_cls.create(*ops_not_on_spc))
|
<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 code into a PNG or PDF output file."""
|
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.builder.imgpath, fname)
outfn = path.join(self.builder.outdir, self.builder.imagedir, fname)
if path.isfile(outfn):
return relfn, outfn
if (hasattr(self.builder, '_graphviz_warned_dot') and
self.builder._graphviz_warned_dot.get(graphviz_dot)):
return None, None
ensuredir(path.dirname(outfn))
# graphviz expects UTF-8 by default
if isinstance(code, text_type):
code = code.encode('utf-8')
dot_args = [graphviz_dot]
dot_args.extend(self.builder.config.graphviz_dot_args)
dot_args.extend(['-T' + format, '-o' + outfn])
if format == 'png':
dot_args.extend(['-Tcmapx', '-o%s.map' % outfn])
try:
p = Popen(dot_args, stdout=PIPE, stdin=PIPE, stderr=PIPE)
except OSError as err:
if err.errno != ENOENT: # No such file or directory
raise
logger.warning(__('dot command %r cannot be run (needed for graphviz '
'output), check the graphviz_dot setting'), graphviz_dot)
if not hasattr(self.builder, '_graphviz_warned_dot'):
self.builder._graphviz_warned_dot = {}
self.builder._graphviz_warned_dot[graphviz_dot] = True
return None, None
try:
# Graphviz may close standard input when an error occurs,
# resulting in a broken pipe on communicate()
stdout, stderr = p.communicate(code)
except (OSError, IOError) as err:
if err.errno not in (EPIPE, EINVAL):
raise
# in this case, read the standard output and standard error streams
# directly, to get the error message(s)
stdout, stderr = p.stdout.read(), p.stderr.read()
p.wait()
if p.returncode != 0:
raise GraphvizError(__('dot exited with error:\n[stderr]\n%s\n'
'[stdout]\n%s') % (stderr, stdout))
if not path.isfile(outfn):
raise GraphvizError(__('dot did not produce an output file:\n[stderr]\n%s\n'
'[stdout]\n%s') % (stderr, stdout))
return relfn, outfn
|
<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 `n` is given, return the `n`'th next basis state label/index; `n` may also be negative to obtain previous basis state labels. Returns a :class:`str` label if `label_or_index` is a :class:`str` or :class:`int`, or a :class:`SpinIndex` if `label_or_index` is a :class:`SpinIndex`. Args: label_or_index (int or str or SpinIndex):
If `int`, the zero-based index of a basis state; if `str`, the label of a basis state n (int):
The increment Raises: IndexError: If going beyond the last or first basis state ValueError: If `label` is not a label for any basis state in the Hilbert space .BasisNotSetError: If the Hilbert space has no defined basis TypeError: if `label_or_index` is neither a :class:`str` nor an :class:`int`, nor a :class:`SpinIndex` Note: This differs from its super-method only by never returning an integer index (which is not accepted when instantiating a :class:`BasisKet` for a :class:`SpinSpace`) """
|
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"
% (new_index, self._basis))
return self.basis_labels[new_index]
elif isinstance(label_or_index, str):
label_index = self.basis_labels.index(label_or_index)
new_index = label_index + n
if (new_index < 0) or (new_index >= len(self._basis)):
raise IndexError(
"index %d out of range for basis %s"
% (new_index, self._basis))
return self.basis_labels[new_index]
elif isinstance(label_or_index, SpinIndex):
return label_or_index.__class__(expr=label_or_index.expr + 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 texinfo_visit_inheritance_diagram(self, node):
# type: (nodes.NodeVisitor, inheritance_diagram) -> None """ Output the graph for Texinfo. This will insert a PNG. """
|
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.SkipNode
|
<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-qualified name. This works for things I've tested in matplotlib so far, but may not be completely general. """
|
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 = '.'.join(name_parts[-parts:])
if aliases is not None and result in aliases:
return aliases[result]
return result
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def codemirror_settings_update(configs, parameters, on=None, names=None):
""" Return a new dictionnary of configs updated with given parameters. You may use ``on`` and ``names`` arguments to select config or filter out some configs from returned dict. Arguments: configs (dict):
Dictionnary of configurations to update. parameters (dict):
Dictionnary of parameters to apply on selected configurations. Keyword Arguments: on (list):
List of configuration names to select for update. If empty, all given configurations will be updated. names (list):
List of configuration names to keep. If not empty, only those configurations will be in returned dict. Else every configs from original dict will be present. Returns: dict: Dict of configurations with updated parameters. """
|
# 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(parameters)
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 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 right-hand side are replaced by the application of `func`:: lhs=func(lhs, *args, **kwargs) rhs=func(rhs, *args, **kwargs) If ``cont=True``, the resulting equation will keep a history of its previous state (resulting in multiple lines of equations when printed, as in the main example above). The resulting equation with have the given `tag`. """
|
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-hand-side are replaced by:: lhs=lhs.<mtd>(*args, **kwargs) rhs=rhs.<mtd>(*args, **kwargs) The `cont` and `tag` parameters are as in :meth:`apply`. """
|
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 form ``{expr: substitution}`` """
|
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 simplified. If given, `func` with the positional arguments `args` and keyword-arguments `kwargs` is applied to the result before returning it. You may complete the verification by checking the :attr:`is_zero` attribute of the returned expression. """
|
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 = kwargs['request'].user
return field
|
<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 the returned strings are fully rendered. Args: identifier (str or SymbolicLabelBase):
A (non-rendered/ascii) identifier that may include a subscript. The output `name` will be the `identifier` without any subscript hs_label (str):
The rendered label for the Hilbert space of the operator, or None. Returned unchanged. dagger (bool):
Flag to indicate whether the operator is daggered. If True, :attr:`dagger_sym` will be included in the `superscript` (or `subscript`, depending on the settings) args (list or None):
List of arguments (expressions). Each element will be rendered with :meth:`doprint`. The total list of args will then be joined with commas, enclosed with :attr:`_parenth_left` and :attr:`parenth_right`, and returnd as the `arguments` string """
|
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, '']):
if self._settings['show_hs_label'] == 'subscript':
if len(total_subscript) == 0:
total_subscript = '(' + hs_label + ')'
else:
total_subscript += ',(' + hs_label + ')'
else:
total_superscript += '(' + hs_label + ')'
if dagger:
total_superscript += self._dagger_sym
args_str = ''
if (args is not None) and (len(args) > 0):
args_str = (self._parenth_left +
",".join([self.doprint(arg) for arg in args]) +
self._parenth_right)
return name, total_subscript, total_superscript, args_str
|
<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 given `level` (or at the given `level` if `strict` is True. Extra `args` and `kwargs` are passed to the internal `doit` renderer"""
|
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.doprint(expr, *args, **kwargs)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw_circuit(circuit, filename, direction = 'lr', hunit = HUNIT, vunit = VUNIT, rhmargin = RHMARGIN, rvmargin = RVMARGIN, rpermutation_length = RPLENGTH, draw_boxes = True, permutation_arrows = False):
""" Generate a graphic representation of circuit and store them in a file. The graphics format is determined from the file extension. :param circuit: The circuit expression :type circuit: ca.Circuit :param filename: A filepath to store the output image under. The file name suffix determines the output graphics format :type filename: str :param direction: The horizontal direction of laying out series products. One of ``'lr'`` and ``'rl'``. This option overrides a negative value for ``hunit``, default = ``'lr'`` :param hunit: The horizontal length unit, default = ``HUNIT`` :type hunit: float :param vunit: The vertical length unit, default = ``VUNIT`` :type vunit: float :param rhmargin: relative horizontal margin, default = ``RHMARGIN`` :type rhmargin: float :param rvmargin: relative vertical margin, default = ``RVMARGIN`` :type rvmargin: float :param rpermutation_length: the relative length of a permutation circuit, default = ``RPLENGTH`` :type rpermutation_length: float :param draw_boxes: Whether to draw indicator boxes to denote subexpressions (Concatenation, SeriesProduct, etc.), default = ``True`` :type draw_boxes: bool :param permutation_arrows: Whether to draw arrows within the permutation visualization, default = ``False`` :type permutation_arrows: bool :return: ``True`` if printing was successful, ``False`` if not. :rtype: bool """
|
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,
rpermutation_length = rpermutation_length,
draw_boxes = draw_boxes,
permutation_arrows = permutation_arrows)
except ValueError as e:
print( ("No graphics returned for circuit {!r}".format(circuit)))
return False
ps_suffixes = ['.pdf', '.eps', '.ps']
gs_suffixes = ['.png', '.jpg']
if any(filename.endswith(suffix) for suffix in ps_suffixes):
c.writetofile(filename)
elif any(filename.endswith(suffix) for suffix in gs_suffixes):
if GS is None:
raise FileNotFoundError(
"No Ghostscript executable available. Ghostscript is required for "
"rendering to {}.".format(", ".join(gs_suffixes))
)
c.writeGSfile(filename, gs=GS)
return True
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nested_tuple(container):
"""Recursively transform a container structure to a nested tuple. The function understands container types inheriting from the selected abstract base classes in `collections.abc`, and performs the following replacements: `Mapping` `tuple` of key-value pair `tuple`s. The order is preserved in the case of an `OrderedDict`, otherwise the key-value pairs are sorted if orderable and otherwise kept in the order of iteration. `Sequence` `tuple` containing the same elements in unchanged order. `Container and Iterable and Sized` (equivalent to `Collection` in python >= 3.6) `tuple` containing the same elements in sorted order if orderable and otherwise kept in the order of iteration. The function recurses into these container types to perform the same replacement, and leaves objects of other types untouched. The returned container is hashable if and only if all the values contained in the original data structure are hashable. Parameters container Data structure to transform into a nested tuple. Returns ------- tuple Nested tuple containing the same data as `container`. """
|
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):
return tuple(map(nested_tuple, container))
if (
isinstance(container, Container)
and isinstance(container, Iterable)
and isinstance(container, Sized)
):
return tuple(sorted_if_possible(map(nested_tuple, container)))
return container
|
<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]
return PRECEDENCE["Atom"]
|
<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 will be passed by the callback API in question. The original function will be returned, with a ``prototype.adapt`` attribute which can be used to prepare third party callbacks. """
|
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.empty) \
or (param.kind == Parameter.KEYWORD_ONLY):
keyword.append(name)
else:
positional.append(name)
kwargs = dict.fromkeys(keyword)
def adapt(callback):
"""Introspect and prepare a third party callback."""
sig = signature(callback)
try:
# XXX: callback can have extra optional parameters - OK?
sig.bind(*positional, **kwargs)
return callback
except TypeError:
pass
# Match up arguments
unmatched_pos = positional[:]
unmatched_kw = kwargs.copy()
unrecognised = []
# TODO: unrecognised parameters with default values - OK?
for name, param in sig.parameters.items():
# print(name, param.kind) #DBG
if param.kind == Parameter.POSITIONAL_ONLY:
if len(unmatched_pos) > 0:
unmatched_pos.pop(0)
else:
unrecognised.append(name)
elif param.kind == Parameter.POSITIONAL_OR_KEYWORD:
if (param.default is not Parameter.empty) and (name in unmatched_kw):
unmatched_kw.pop(name)
elif len(unmatched_pos) > 0:
unmatched_pos.pop(0)
else:
unrecognised.append(name)
elif param.kind == Parameter.VAR_POSITIONAL:
unmatched_pos = []
elif param.kind == Parameter.KEYWORD_ONLY:
if name in unmatched_kw:
unmatched_kw.pop(name)
else:
unrecognised.append(name)
else: # VAR_KEYWORD
unmatched_kw = {}
# print(unmatched_pos, unmatched_kw, unrecognised) #DBG
if unrecognised:
raise TypeError("Function {!r} had unmatched arguments: {}".format(callback, unrecognised))
n_positional = len(positional) - len(unmatched_pos)
@wraps(callback)
def adapted(*args, **kwargs):
"""Wrapper for third party callbacks that discards excess arguments"""
# print(args, kwargs)
args = args[:n_positional]
for name in unmatched_kw:
# XXX: Could name not be in kwargs?
kwargs.pop(name)
# print(args, kwargs, unmatched_pos, cut_positional, unmatched_kw)
return callback(*args, **kwargs)
return adapted
prototype.adapt = adapt
return prototype
|
<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(
Q(publication_date__isnull=True) |
Q(publication_date__lte=now())
).filter(
Q(publication_end_date__isnull=True) |
Q(publication_end_date__gte=now())
)
|
<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 field, assume slug is translated (e.g django-categories-i18n)
filters = {
'categories__translations__slug__in': category_slugs,
}
# TODO: should the current language also be used as filter somehow?
languages = self._get_active_rel_languages()
if languages:
if len(languages) == 1:
filters['categories__translations__language_code'] = languages[0]
else:
filters['categories__translations__language_code__in'] = languages
return self.filter(**filters).distinct()
else:
return self.filter(categories__slug=category_slugs)
|
<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).distinct()
|
<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, sub_first=True, translate_symbols=True,
unicode_sub_super=self.unicode_sub_super)
|
<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, translate_symbols=True,
unicode_sub_super=self._settings['unicode_sub_super'])
|
<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 system. Args: local_space (str or int or .LocalSpace):
Associated Hilbert space. If :class:`str` or :class:`int`, a :class:`LocalSpace` with a matching label will be created. states (None or tuple[int or str]):
The labels for the basis states for the two levels on which the operator acts. If None, the two lowest levels are used. Returns: Operator: Local X-operator as a linear combination of :class:`LocalSigma` """
|
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-level system. See :func:`PauliX` """
|
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-level system. See :func:`PauliX` """
|
local_space, states = _get_pauli_args(local_space, states)
g, e = states
return (
LocalProjector(g, hs=local_space) - LocalProjector(e, hs=local_space))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.