text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Updates an existing RRSet's Rdata in the specified zone. <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:> Deletes an RRSet. <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:> Create a web forward record. <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:> Creates a new SB Pool. <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:> Creates a new TC Pool. <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:> Remove a particular factor from a tensor product space. <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:> Find the mutual tensor factors of two Hilbert spaces. <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:> Check whether `expr` is an instance of the class with name <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:> Simplifies OperatorTrace expressions over tensor-product spaces by <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:> Factor out coefficients of all factors. <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:> Print a dictionary of attributes in the DOT format <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:> Merge style dictionaries in order <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:> If installed with 'pip installe -e .' from inside a git repo, the <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:> Pad a circuit by adding a `n`-channel identity circuit at index `k` <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 dimension $N+n$, where the channels $k$, $k+1$, ...$k+n-1$, just pass through the system unaffected. E.g. let ``A``, ``B`` be two single channel systems:: >>> A = CircuitSymbol('A', cdim=1) >>> B = CircuitSymbol('B', cdim=1) >>> print(ascii(pad_with_identity(A+B, 1, 2))) 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 $k$, $k+1$, ..., $k+n-1$ """
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:> Prepare the adiabatic elimination on an SLH object <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:> Compute the limiting SLH model for the adiabatic approximation <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:> Attempt to automatically do adiabatic elimination on an SLH object <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:> Return the index a channel has within the subblock it belongs to <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:> For a reducible circuit, get a sequence of subblocks that when <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:> Show the circuit expression in an IPython notebook. <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:> Render the circuit expression and store the result in a file <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:> Set of all symbols occcuring in S, L, or H <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:> Expand out all operator expressions within S, L and H <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:> Simplify all scalar expressions within S, L and H <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:> Compute the symbolic Liouvillian acting on a state rho <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:> Compute the symbolic Heisenberg equations of motion of a system <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:> If the circuit is reducible into permutations within subranges of <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:> Compute the series product with another channel permutation circuit <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:> Save the rendered html to a file in the same directory as the notebook. <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:> Try to render a subscript or superscript string in unicode, fall back on <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:> Given a description of a Greek letter or other special character, <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:> Save the rendered html to a file and returns an IFrame to display the plot in the notebook. <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:> Obtain cached result, prepend with the keyname if necessary, and <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:> Store the cached result without indentation, and without the <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:> Given a description of a Greek letter or other special character, <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:> Returned a texified version of the string <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:> Return true if the string is a mathematical symbol. <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:> Find matches for words in the format "3 thousand 6 hundred 2". <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:> Given a string and an ISO 639-2 language code, <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:> Convert a list of evaluatable tokens to postfix format. <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:> Given a list of evaluatable tokens in postfix format, <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:> Given a string, return a list of math symbol tokens <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:> Return a solution to the equation in the input string. <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:> A default order key for arbitrary expressions <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:> Instantiator for an arbitrary indexed sum. <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:: >>> i = IdxSym('i'); j = IdxSym('j') >>> ket_i = BasisKet(FockIndex(i), hs=0) >>> ket_j = BasisKet(FockIndex(j), hs=0) >>> hs0 = LocalSpace('0') Giving `i` as the only argument will sum over the indices of the basis states of the Hilbert space of `term`:: >>> s = Sum(i)(ket_i) >>> unicode(s) '∑_{i ∈ ℌ₀} |i⟩⁽⁰⁾' You may also specify a Hilbert space manually:: >>> Sum(i, hs0)(ket_i) == Sum(i, hs=hs0)(ket_i) == s True Note that using :func:`Sum` is vastly more readable than the equivalent "manual" instantiation:: >>> s == KetIndexedSum.create(ket_i, IndexOverFockSpace(i, hs=hs0)) True By nesting calls to `Sum`, you can instantiate sums running over multiple indices:: >>> unicode( Sum(i)(Sum(j)(ket_i * ket_j.dag())) ) '∑_{i,j ∈ ℌ₀} |i⟩⟨j|⁽⁰⁾' Giving two integers in addition to the index `i` in `args`, the index will run between the two values:: >>> unicode( Sum(i, 1, 10)(ket_i) ) '∑_{i=1}^{10} |i⟩⁽⁰⁾' >>> Sum(i, 1, 10)(ket_i) == Sum(i, 1, to=10)(ket_i) True You may also include an optional step width, either as a third integer or using the `step` keyword argument. >>> #unicode( Sum(i, 1, 10, step=2)(ket_i) ) # TODO Lastly, by passing a tuple or list of values, the index will run over all the elements in that tuple or list:: >>> unicode( Sum(i, (1, 2, 3))(ket_i)) '∑_{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:> Differentiate by scalar parameter `sym`. <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:> r"""Expand the expression as a truncated power series in a <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:: >>> expr = KetSymbol("Psi", hs=0) >>> t = sympy.symbols("t") >>> assert expr.series_expand(t, 0, 1) == (expr, ZeroKet) """
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:> Return a tuple of two products, where the first product contains the <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:> Evaluate the derivative at a specific point <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:> Set of Sympy symbols that are eliminated by evaluation. <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:> Generate clickable map tags if clickable item exists. <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:> Given the label or index of a basis state, return the label <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:> Output the graph for Texinfo. This will insert a PNG. <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:> Given a class object, return a fully-qualified name. <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:> Return a new dictionnary of configs updated with given parameters. <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:> Return a copy of the equation with a new `tag` <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:> Apply `func` to both sides of the equation <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:> Call the method `mtd` on both sides of the equation <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:> Substitute sub-expressions both on the lhs and rhs <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:> Subtract the rhs from the lhs of the equation <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:> Set of free SymPy symbols contained within the equation. <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:> Set of bound SymPy symbols contained within the equation. <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:> Creation operator for a Hilbert space of dimension `n`, as an instance <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:> Allow formfield_overrides to contain field names too. <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:> Return `name`, total `subscript`, total `superscript` and <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:> Return the label of the given Hilbert space as a string <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:> Render `expr` and wrap the result in parentheses if the precedence <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:> Generate a graphic representation of circuit and store them in a file. <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:> Recursively transform a container structure to a nested tuple. <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:> Returns the precedence of a given object. <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:> Decorator to process a callback prototype. <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:> Return only published entries for the current site. <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:> Return the entries written by the given usernames <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:> Return the entries with the given category slugs. <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:> Return the items which are tagged with a specific tag. <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:> Format and combine the name, subscript, and superscript <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:> Returned a unicodified version of the string <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:> r"""Pauli-type X-operator <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:> r""" Pauli-type Y-operator <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:> Render a textual representation of `expr` using <END_TASK> <USER_TASK:> Description: def render_head_repr( expr: Any, sub_render=None, key_sub_render=None) -> str: """Render a textual representation of `expr` using Positional and keyword arguments are recursively rendered using `sub_render`, which defaults to `render_head_repr` by default. If desired, a different renderer may be used for keyword arguments by giving `key_sub_renderer` Raises: AttributeError: if `expr` is not an instance of :class:`Expression`, or more specifically, if `expr` does not have `args` and `kwargs` (respectively `minimal_kwargs`) properties """
head_repr_fmt = r'{head}({args}{kwargs})' if sub_render is None: sub_render = render_head_repr if key_sub_render is None: key_sub_render = sub_render if isinstance(expr.__class__, Singleton): # We exploit that Singletons override __expr__ to directly return # their name return repr(expr) if isinstance(expr, Expression): args = expr.args keys = expr.minimal_kwargs.keys() kwargs = '' if len(keys) > 0: kwargs = ", ".join([ "%s=%s" % (key, key_sub_render(expr.kwargs[key])) for key in keys]) if len(args) > 0: kwargs = ", " + kwargs return head_repr_fmt.format( head=expr.__class__.__name__, args=", ".join([sub_render(arg) for arg in args]), kwargs=kwargs) elif isinstance(expr, (tuple, list)): delims = ("(", ")") if isinstance(expr, tuple) else ("[", "]") if len(expr) == 1: delims = (delims[0], "," + delims[1]) return ( delims[0] + ", ".join([ render_head_repr( v, sub_render=sub_render, key_sub_render=key_sub_render) for v in expr]) + delims[1]) else: return sympy_srepr(expr)
<SYSTEM_TASK:> Verify the `rules` that classes may use for the `_rules` or <END_TASK> <USER_TASK:> Description: def check_rules_dict(rules): """Verify the `rules` that classes may use for the `_rules` or `_binary_rules` class attribute. Specifically, `rules` must be a :class:`~collections.OrderedDict`-compatible object (list of key-value tuples, :class:`dict`, :class:`~collections.OrderedDict`) that maps a rule name (:class:`str`) to a rule. Each rule consists of a :class:`~qnet.algebra.pattern_matching.Pattern` and a replaceent callable. The Pattern must be set up to match a :class:`~qnet.algebra.pattern_matching.ProtoExpr`. That is, the Pattern should be constructed through the :func:`~qnet.algebra.pattern_matching.pattern_head` routine. Raises: TypeError: If `rules` is not compatible with :class:`~collections.OrderedDict`, the keys in `rules` are not strings, or rule is not a tuple of (:class:`~qnet.algebra.pattern_matching.Pattern`, `callable`) ValueError: If the `head`-attribute of each Pattern is not an instance of :class:`~qnet.algebra.pattern_matching.ProtoExpr`, or if there are duplicate keys in `rules` Returns: :class:`~collections.OrderedDict` of rules """
from qnet.algebra.pattern_matching import Pattern, ProtoExpr if hasattr(rules, 'items'): items = rules.items() # `rules` is already a dict / OrderedDict else: items = rules # `rules` is a list of (key, value) tuples keys = set() for key_rule in items: try: key, rule = key_rule except ValueError: raise TypeError("rules does not contain (key, rule) tuples") if not isinstance(key, str): raise TypeError("Key '%s' is not a string" % key) if key in keys: raise ValueError("Duplicate key '%s'" % key) else: keys.add(key) try: pat, replacement = rule except TypeError: raise TypeError( "Rule in '%s' is not a (pattern, replacement) tuple" % key) if not isinstance(pat, Pattern): raise TypeError( "Pattern in '%s' is not a Pattern instance" % key) if pat.head is not ProtoExpr: raise ValueError( "Pattern in '%s' does not match a ProtoExpr" % key) if not callable(replacement): raise ValueError( "replacement in '%s' is not callable" % key) else: arg_names = inspect.signature(replacement).parameters.keys() if not arg_names == pat.wc_names: raise ValueError( "arguments (%s) of replacement function differ from the " "wildcard names (%s) in pattern" % ( ", ".join(sorted(arg_names)), ", ".join(sorted(pat.wc_names)))) return OrderedDict(rules)
<SYSTEM_TASK:> Try to de-rationalize the denominator of the given expression. <END_TASK> <USER_TASK:> Description: def derationalize_denom(expr): """Try to de-rationalize the denominator of the given expression. The purpose is to allow to reconstruct e.g. ``1/sqrt(2)`` from ``sqrt(2)/2``. Specifically, this matches `expr` against the following pattern:: Mul(..., Rational(n, d), Pow(d, Rational(1, 2)), ...) and returns a tuple ``(numerator, denom_sq, post_factor)``, where ``numerator`` and ``denom_sq`` are ``n`` and ``d`` in the above pattern (of type `int`), respectively, and ``post_factor`` is the product of the remaining factors (``...`` in `expr`). The result will fulfill the following identity:: (numerator / sqrt(denom_sq)) * post_factor == expr If `expr` does not follow the appropriate pattern, a :exc:`ValueError` is raised. """
r_pos = -1 p_pos = -1 numerator = S.Zero denom_sq = S.One post_factors = [] if isinstance(expr, Mul): for pos, factor in enumerate(expr.args): if isinstance(factor, Rational) and r_pos < 0: r_pos = pos numerator, denom_sq = factor.p, factor.q elif isinstance(factor, Pow) and r_pos >= 0: if factor == sqrt(denom_sq): p_pos = pos else: post_factors.append(factor) else: post_factors.append(factor) if r_pos >= 0 and p_pos >= 0: return numerator, denom_sq, Mul(*post_factors) else: raise ValueError("Cannot derationalize") else: raise ValueError("expr is not a Mul instance")
<SYSTEM_TASK:> Return the entries that are published under this node. <END_TASK> <USER_TASK:> Description: def entries(self): """ Return the entries that are published under this node. """
# Since there is currently no filtering in place, return all entries. EntryModel = get_entry_model() qs = get_entry_model().objects.order_by('-publication_date') # Only limit to current language when this makes sense. if issubclass(EntryModel, TranslatableModel): admin_form_language = self.get_current_language() # page object is in current language tab. qs = qs.active_translations(admin_form_language).language(admin_form_language) return qs
<SYSTEM_TASK:> Create a placeholder on this blog entry. <END_TASK> <USER_TASK:> Description: def create_placeholder(self, slot="blog_contents", role='m', title=None): """ Create a placeholder on this blog entry. To fill the content items, use :func:`ContentItemModel.objects.create_for_placeholder() <fluent_contents.models.managers.ContentItemManager.create_for_placeholder>`. :rtype: :class:`~fluent_contents.models.Placeholder` """
return Placeholder.objects.create_for_object(self, slot, role=role, title=title)
<SYSTEM_TASK:> Open saved html file in an virtual browser and save a screen shot to PNG format. <END_TASK> <USER_TASK:> Description: def save_as_png(self, filename, width=300, height=250, render_time=1): """Open saved html file in an virtual browser and save a screen shot to PNG format."""
self.driver.set_window_size(width, height) self.driver.get('file://{path}/{filename}'.format( path=os.getcwd(), filename=filename + ".html")) time.sleep(render_time) self.driver.save_screenshot(filename + ".png")
<SYSTEM_TASK:> Format the year value of the ``YearArchiveView``, <END_TASK> <USER_TASK:> Description: def format_year(year): """ Format the year value of the ``YearArchiveView``, which can be a integer or date object. This tag is no longer needed, but exists for template compatibility. It was a compatibility tag for Django 1.4. """
if isinstance(year, (date, datetime)): # Django 1.5 and up, 'year' is a date object, consistent with month+day views. return unicode(year.year) else: # Django 1.4 just passes the kwarg as string. return unicode(year)
<SYSTEM_TASK:> Set of all free symbols <END_TASK> <USER_TASK:> Description: def free_symbols(self): """Set of all free symbols"""
return set([ sym for sym in self.term.free_symbols if sym not in self.bound_symbols])
<SYSTEM_TASK:> Iterator over the terms of the sum <END_TASK> <USER_TASK:> Description: def terms(self): """Iterator over the terms of the sum Yield from the (possibly) infinite list of terms of the indexed sum, if the sum was written out explicitly. Each yielded term in an instance of :class:`.Expression` """
from qnet.algebra.core.scalar_algebra import ScalarValue for mapping in yield_from_ranges(self.ranges): term = self.term.substitute(mapping) if isinstance(term, ScalarValue._val_types): term = ScalarValue.create(term) assert isinstance(term, Expression) yield term
<SYSTEM_TASK:> Write out the indexed sum explicitly <END_TASK> <USER_TASK:> Description: def doit( self, classes=None, recursive=True, indices=None, max_terms=None, **kwargs): """Write out the indexed sum explicitly If `classes` is None or :class:`IndexedSum` is in `classes`, (partially) write out the indexed sum in to an explicit sum of terms. If `recursive` is True, write out each of the new sum's summands by calling its :meth:`doit` method. Args: classes (None or list): see :meth:`.Expression.doit` recursive (bool): see :meth:`.Expression.doit` indices (list): List of :class:`IdxSym` indices for which the sum should be expanded. If `indices` is a subset of the indices over which the sum runs, it will be partially expanded. If not given, expand the sum completely max_terms (int): Number of terms after which to truncate the sum. This is particularly useful for infinite sums. If not given, expand all terms of the sum. Cannot be combined with `indices` kwargs: keyword arguments for recursive calls to :meth:`doit`. See :meth:`.Expression.doit` """
return super().doit( classes, recursive, indices=indices, max_terms=max_terms, **kwargs)
<SYSTEM_TASK:> Return a copy with modified indices to ensure disjunct indices with <END_TASK> <USER_TASK:> Description: def make_disjunct_indices(self, *others): """Return a copy with modified indices to ensure disjunct indices with `others`. Each element in `others` may be an index symbol (:class:`.IdxSym`), a index-range object (:class:`.IndexRangeBase`) or list of index-range objects, or an indexed operation (something with a ``ranges`` attribute) Each index symbol is primed until it does not match any index symbol in `others`. """
new = self other_index_symbols = set() for other in others: try: if isinstance(other, IdxSym): other_index_symbols.add(other) elif isinstance(other, IndexRangeBase): other_index_symbols.add(other.index_symbol) elif hasattr(other, 'ranges'): other_index_symbols.update( [r.index_symbol for r in other.ranges]) else: other_index_symbols.update( [r.index_symbol for r in other]) except AttributeError: raise ValueError( "Each element of other must be an an instance of IdxSym, " "IndexRangeBase, an object with a `ranges` attribute " "with a list of IndexRangeBase instances, or a list of" "IndexRangeBase objects.") for r in self.ranges: index_symbol = r.index_symbol modified = False while index_symbol in other_index_symbols: modified = True index_symbol = index_symbol.incr_primed() if modified: new = new._substitute( {r.index_symbol: index_symbol}, safe=True) return new
<SYSTEM_TASK:> Tag to render CodeMirror Javascript assets needed for all given fields. <END_TASK> <USER_TASK:> Description: def codemirror_field_js_assets(*args): """ Tag to render CodeMirror Javascript assets needed for all given fields. Example: :: {% load djangocodemirror_tags %} {% codemirror_field_js_assets form.myfield1 form.myfield2 %} """
manifesto = CodemirrorAssetTagRender() manifesto.register_from_fields(*args) return mark_safe(manifesto.js_html())
<SYSTEM_TASK:> Tag to render CodeMirror CSS assets needed for all given fields. <END_TASK> <USER_TASK:> Description: def codemirror_field_css_assets(*args): """ Tag to render CodeMirror CSS assets needed for all given fields. Example: :: {% load djangocodemirror_tags %} {% codemirror_field_css_assets form.myfield1 form.myfield2 %} """
manifesto = CodemirrorAssetTagRender() manifesto.register_from_fields(*args) return mark_safe(manifesto.css_html())
<SYSTEM_TASK:> Filter to get CodeMirror Javascript bundle name needed for a single field. <END_TASK> <USER_TASK:> Description: def codemirror_field_js_bundle(field): """ Filter to get CodeMirror Javascript bundle name needed for a single field. Example: :: {% load djangocodemirror_tags %} {{ form.myfield|codemirror_field_js_bundle }} Arguments: field (django.forms.fields.Field): A form field that contains a widget :class:`djangocodemirror.widget.CodeMirrorWidget`. Raises: CodeMirrorFieldBundleError: If Codemirror configuration form field does not have a bundle name. Returns: string: Bundle name to load with webassets. """
manifesto = CodemirrorAssetTagRender() manifesto.register_from_fields(field) try: bundle_name = manifesto.js_bundle_names()[0] except IndexError: msg = ("Given field with configuration name '{}' does not have a " "Javascript bundle name") raise CodeMirrorFieldBundleError(msg.format(field.config_name)) return bundle_name
<SYSTEM_TASK:> Filter to get CodeMirror CSS bundle name needed for a single field. <END_TASK> <USER_TASK:> Description: def codemirror_field_css_bundle(field): """ Filter to get CodeMirror CSS bundle name needed for a single field. Example: :: {% load djangocodemirror_tags %} {{ form.myfield|codemirror_field_css_bundle }} Arguments: field (djangocodemirror.fields.CodeMirrorField): A form field. Raises: CodeMirrorFieldBundleError: Raised if Codemirror configuration from field does not have a bundle name. Returns: string: Bundle name to load with webassets. """
manifesto = CodemirrorAssetTagRender() manifesto.register_from_fields(field) try: bundle_name = manifesto.css_bundle_names()[0] except IndexError: msg = ("Given field with configuration name '{}' does not have a " "Javascript bundle name") raise CodeMirrorFieldBundleError(msg.format(field.config_name)) return bundle_name
<SYSTEM_TASK:> Filter to include CodeMirror parameters as a JSON string for a single <END_TASK> <USER_TASK:> Description: def codemirror_parameters(field): """ Filter to include CodeMirror parameters as a JSON string for a single field. This must be called only on an allready rendered field, meaning you must not use this filter on a field before a form. Else, the field widget won't be correctly initialized. Example: :: {% load djangocodemirror_tags %} {{ form.myfield|codemirror_parameters }} Arguments: field (djangocodemirror.fields.CodeMirrorField): A form field. Returns: string: JSON object for parameters, marked safe for Django templates. """
manifesto = CodemirrorAssetTagRender() names = manifesto.register_from_fields(field) config = manifesto.get_codemirror_parameters(names[0]) return mark_safe(json.dumps(config))
<SYSTEM_TASK:> Return HTML to init a CodeMirror instance for an element. <END_TASK> <USER_TASK:> Description: def codemirror_instance(config_name, varname, element_id, assets=True): """ Return HTML to init a CodeMirror instance for an element. This will output the whole HTML needed to initialize a CodeMirror instance with needed assets loading. Assets can be omitted with the ``assets`` option. Example: :: {% load djangocodemirror_tags %} {% codemirror_instance 'a-config-name' 'foo_codemirror' 'foo' %} Arguments: config_name (string): A registred config name. varname (string): A Javascript variable name. element_id (string): An HTML element identifier (without leading ``#``) to attach to a CodeMirror instance. Keyword Arguments: assets (Bool): Adds needed assets before the HTML if ``True``, else only CodeMirror instance will be outputed. Default value is ``True``. Returns: string: HTML. """
output = io.StringIO() manifesto = CodemirrorAssetTagRender() manifesto.register(config_name) if assets: output.write(manifesto.css_html()) output.write(manifesto.js_html()) html = manifesto.codemirror_html(config_name, varname, element_id) output.write(html) content = output.getvalue() output.close() return mark_safe(content)
<SYSTEM_TASK:> Given a Field or BoundField, return widget instance. <END_TASK> <USER_TASK:> Description: def resolve_widget(self, field): """ Given a Field or BoundField, return widget instance. Todo: Raise an exception if given field object does not have a widget. Arguments: field (Field or BoundField): A field instance. Returns: django.forms.widgets.Widget: Retrieved widget from given field. """
# When filter is used within template we have to reach the field # instance through the BoundField. if hasattr(field, 'field'): widget = field.field.widget # When used out of template, we have a direct field instance else: widget = field.widget return widget
<SYSTEM_TASK:> Register config name from field widgets <END_TASK> <USER_TASK:> Description: def register_from_fields(self, *args): """ Register config name from field widgets Arguments: *args: Fields that contains widget :class:`djangocodemirror.widget.CodeMirrorWidget`. Returns: list: List of registered config names from fields. """
names = [] for field in args: widget = self.resolve_widget(field) self.register(widget.config_name) if widget.config_name not in names: names.append(widget.config_name) return names
<SYSTEM_TASK:> Render HTML tag for a given path. <END_TASK> <USER_TASK:> Description: def render_asset_html(self, path, tag_template): """ Render HTML tag for a given path. Arguments: path (string): Relative path from static directory. tag_template (string): Template string for HTML tag. Returns: string: HTML tag with url from given path. """
url = os.path.join(settings.STATIC_URL, path) return tag_template.format(url=url)
<SYSTEM_TASK:> Render HTML for a CodeMirror instance. <END_TASK> <USER_TASK:> Description: def codemirror_html(self, config_name, varname, element_id): """ Render HTML for a CodeMirror instance. Since a CodeMirror instance have to be attached to a HTML element, this method requires a HTML element identifier with or without the ``#`` prefix, it depends from template in ``settings.CODEMIRROR_FIELD_INIT_JS`` (default one require to not prefix with ``#``). Arguments: config_name (string): A registred config name. varname (string): A Javascript variable name. element_id (string): An HTML element identifier (without leading ``#``) to attach to a CodeMirror instance. Returns: string: HTML to instanciate CodeMirror for a field input. """
parameters = json.dumps(self.get_codemirror_parameters(config_name), sort_keys=True) return settings.CODEMIRROR_FIELD_INIT_JS.format( varname=varname, inputid=element_id, settings=parameters, )