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 render_head_repr( expr: Any, sub_render=None, key_sub_render=None) -> str: """Render a textual representation of `expr` using Positional and keyword arguments...
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_rules_dict(rules): """Verify the `rules` that classes may use for the `_rules` or `_binary_rules` class attribute. Specifically, `rules` must be a :cla...
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 `...
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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): ad...
<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_entry_url(self, entry): """ Return the URL of a blog entry, relative to this page. """
# It could be possible this page is fetched as fallback, while the 'entry' does have a translation. # - Currently django-fluent-pages 1.0b3 `Page.objects.get_for_path()` assigns the language of retrieval # as current object language. The page is not assigned a fallback language instead. ...
<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_placeholder(self, slot="blog_contents", role='m', title=None): """ Create a placeholder on this blog entry. To fill the content items, use :func:`Cont...
return Placeholder.objects.create_for_object(self, slot, role=role, title=title)
<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_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:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_version(filename): """Extract the package version"""
with open(filename) as in_fh: for line in in_fh: if line.startswith('__version__'): return line.split('=')[1].strip()[1:-1] raise ValueError("Cannot extract version from %s" % filename)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 ...
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:> 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 free symbols"""
return set([ sym for sym in self.term.free_symbols if sym not in 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 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...
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, Expressio...
<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, indices=None, max_terms=None, **kwargs): """Write out the indexed sum explicitly If `classes` is None or :class:`In...
return super().doit( classes, recursive, indices=indices, max_terms=max_terms, **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 make_disjunct_indices(self, *others): """Return a copy with modified indices to ensure disjunct indices with `others`. Each element in `others` may be an ind...
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) ...
<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_field_js_assets(*args): """ Tag to render CodeMirror Javascript assets needed for all given fields. Example: :: {% load djangocodemirror_tags %} {...
manifesto = CodemirrorAssetTagRender() manifesto.register_from_fields(*args) return mark_safe(manifesto.js_html())
<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_field_css_assets(*args): """ Tag to render CodeMirror CSS assets needed for all given fields. Example: :: {% load djangocodemirror_tags %} {% code...
manifesto = CodemirrorAssetTagRender() manifesto.register_from_fields(*args) return mark_safe(manifesto.css_html())
<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_field_js_bundle(field): """ Filter to get CodeMirror Javascript bundle name needed for a single field. Example: :: {% load djangocodemirror_tags %...
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 CodeMirrorFieldBun...
<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_field_css_bundle(field): """ Filter to get CodeMirror CSS bundle name needed for a single field. Example: :: {% load djangocodemirror_tags %} {{ f...
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 CodeMirrorFieldBu...
<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_parameters(field): """ Filter to include CodeMirror parameters as a JSON string for a single field. This must be called only on an allready render...
manifesto = CodemirrorAssetTagRender() names = manifesto.register_from_fields(field) config = manifesto.get_codemirror_parameters(names[0]) return mark_safe(json.dumps(config))
<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_instance(config_name, varname, element_id, assets=True): """ Return HTML to init a CodeMirror instance for an element. This will output the whole ...
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 = o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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. ...
# 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 r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_from_fields(self, *args): """ Register config name from field widgets Arguments: *args: Fields that contains widget :class:`djangocodemirror.widget....
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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_templa...
url = os.path.join(settings.STATIC_URL, path) return tag_template.format(url=url)
<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_html(self, config_name, varname, element_id): """ Render HTML for a CodeMirror instance. Since a CodeMirror instance have to be attached to a HTML...
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, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_apidoc(_): """Generage API documentation"""
import better_apidoc better_apidoc.main([ 'better-apidoc', '-t', os.path.join('.', '_templates'), '--force', '--no-toc', '--separate', '-o', os.path.join('.', 'API'), os.path.join('..', 'src', 'qnet'), ])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _shorten_render(renderer, max_len): that representation is longer than `max_len`"""
def short_renderer(expr): res = renderer(expr) if len(res) > max_len: return '...' else: return res return short_renderer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_algebra(*, default_hs_cls='LocalSpace'): """Initialize the algebra system Args: default_hs_cls (str): The name of the :class:`.LocalSpace` subclass tha...
from qnet.algebra.core.hilbert_space_algebra import LocalSpace from qnet.algebra.core.abstract_quantum_algebra import QuantumExpression default_hs_cls = getattr(importlib.import_module('qnet'), default_hs_cls) if issubclass(default_hs_cls, LocalSpace): QuantumExpression._default_hs_cls = defaul...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(self, name): """ Register configuration for an editor instance. Arguments: name (string): Config name from available ones in ``settings.CODEMIRROR_...
if name not in settings.CODEMIRROR_SETTINGS: msg = ("Given config name '{}' does not exists in " "'settings.CODEMIRROR_SETTINGS'.") raise UnknowConfigError(msg.format(name)) parameters = copy.deepcopy(self.default_internal_config) parameters.update(co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_many(self, *args): """ Register many configuration names. Arguments: *args: Config names as strings. Returns: list: List of registered configs. """
params = [] for name in args: params.append(self.register(name)) return 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 resolve_mode(self, name): """ From given mode name, return mode file path from ``settings.CODEMIRROR_MODES`` map. Arguments: name (string): Mode name. Raise...
if name not in settings.CODEMIRROR_MODES: msg = ("Given config name '{}' does not exists in " "'settings.CODEMIRROR_MODES'.") raise UnknowModeError(msg.format(name)) return settings.CODEMIRROR_MODES.get(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 resolve_theme(self, name): """ From given theme name, return theme file path from ``settings.CODEMIRROR_THEMES`` map. Arguments: name (string): Theme name. ...
if name not in settings.CODEMIRROR_THEMES: msg = ("Given theme name '{}' does not exists in " "'settings.CODEMIRROR_THEMES'.") raise UnknowThemeError(msg.format(name)) return settings.CODEMIRROR_THEMES.get(name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_configs(self, name=None): """ Returns registred configurations. * If ``name`` argument is not given, default behavior is to return every config from all ...
if name: if name not in self.registry: msg = "Given config name '{}' is not registered." raise NotRegisteredError(msg.format(name)) return {name: self.registry[name]} return self.registry
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_config(self, name): """ Return a registred configuration for given config name. Arguments: name (string): A registred config name. Raises: NotRegistered...
if name not in self.registry: msg = "Given config name '{}' is not registered." raise NotRegisteredError(msg.format(name)) return copy.deepcopy(self.registry[name])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_codemirror_parameters(self, name): """ Return CodeMirror parameters for given configuration name. This is a reduced configuration from internal parameter...
config = self.get_config(name) return {k: config[k] for k in config if k not in self._internal_only}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def commutator(A, B=None): """Commutator of `A` and `B` If ``B != None``, return the commutator :math:`[A,B]`, otherwise return the super-operator :math:`[A,\cdo...
if B: return A * B - B * A return SPre(A) - SPost(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 liouvillian(H, Ls=None): r"""Return the Liouvillian super-operator associated with `H` and `Ls` The Liouvillian :math:`\mathcal{L}` generates the Markovian-d...
if Ls is None: Ls = [] elif isinstance(Ls, Matrix): Ls = Ls.matrix.ravel().tolist() summands = [-I * commutator(H), ] summands.extend([lindblad(L) for L in Ls]) return SuperOperatorPlus.create(*summands)
<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_matrix(A, B, C, D): r"""Generate the operator matrix with quadrants .. math:: \begin{pmatrix} A B \\ C D \end{pmatrix} Args: A (Matrix): Matrix of sha...
return vstackm((hstackm((A, B)), hstackm((C, D))))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def permutation_matrix(permutation): r"""Return orthogonal permutation matrix for permutation tuple Return an orthogonal permutation matrix :math:`M_\sigma` for ...
assert check_permutation(permutation) n = len(permutation) op_matrix = np_zeros((n, n), dtype=int) for i, j in enumerate(permutation): op_matrix[j, i] = 1 return Matrix(op_matrix)
<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_zero(self): """Are all elements of the matrix zero?"""
for o in self.matrix.ravel(): try: if not o.is_zero: return False except AttributeError: if not o == 0: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def conjugate(self): """The element-wise conjugate matrix This is defined only if all the entries in the matrix have a defined conjugate (i.e., they have a `conj...
try: return Matrix(np_conjugate(self.matrix)) except AttributeError: raise NoConjugateMatrix( "Matrix %s contains entries that have no defined " "conjugate" % str(self))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def real(self): """Element-wise real part Raises: NoConjugateMatrix: if entries have no `conjugate` method and no other way to determine the real part Note: A ma...
def re(val): if hasattr(val, 'real'): return val.real elif hasattr(val, 'as_real_imag'): return val.as_real_imag()[0] elif hasattr(val, 'conjugate'): return (val.conjugate() + val) / 2 else: raise 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 imag(self): """Element-wise imaginary part Raises: NoConjugateMatrix: if entries have no `conjugate` method and no other way to determine the imaginary part ...
def im(val): if hasattr(val, 'imag'): return val.imag elif hasattr(val, 'as_real_imag'): return val.as_real_imag()[1] elif hasattr(val, 'conjugate'): return (val.conjugate() - val) / (2 * I) else: r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def element_wise(self, func, *args, **kwargs): """Apply a function to each matrix element and return the result in a new operator matrix of the same shape. Args:...
s = self.shape emat = [func(o, *args, **kwargs) for o in self.matrix.ravel()] return Matrix(np_array(emat).reshape(s))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def series_expand(self, param: Symbol, about, order: int): """Expand the matrix expression as a truncated power series in a scalar parameter. Args: param: Expans...
s = self.shape emats = zip(*[o.series_expand(param, about, order) for o in self.matrix.ravel()]) return tuple((Matrix(np_array(em).reshape(s)) for em in emats))
<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 each matrix element distributively. Returns: Matrix: Expanded matrix. """
return self.element_wise( lambda o: o.expand() if isinstance(o, QuantumExpression) else o)
<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): """Combined Hilbert space of all matrix elements."""
arg_spaces = [o.space for o in self.matrix.ravel() if hasattr(o, 'space')] if len(arg_spaces) == 0: return TrivialSpace else: return ProductSpace.create(*arg_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 simplify_scalar(self, func=sympy.simplify): """Simplify all scalar expressions appearing in the Matrix."""
def element_simplify(v): if isinstance(v, sympy.Basic): return func(v) elif isinstance(v, QuantumExpression): return v.simplify_scalar(func=func) else: return v return self.element_wise(element_simplify)
<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_initial(self): """ Try to find a demo source for given mode if any, if finded use it to fill the demo textarea. """
initial = {} if self.kwargs.get('mode', None): filename = "{}.txt".format(self.kwargs['mode']) filepath = os.path.join(settings.BASE_DIR, 'demo_datas', filename) if os.path.exists(filepath): with io.open(filepath, 'r', encoding='utf-8') as fp: ...
<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_order_by(order, orderby, order_by_fields): """ Return the order by syntax for a model. Checks whether use ascending or descending order, and maps the fi...
try: # Find the actual database fieldnames for the keyword. db_fieldnames = order_by_fields[orderby] except KeyError: raise ValueError("Invalid value for 'orderby': '{0}', supported values are: {1}".format(orderby, ', '.join(sorted(order_by_fields.keys())))) # Default to descending...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_entries( queryset=None, year=None, month=None, day=None, category=None, category_slug=None, tag=None, tag_slug=None, author=None, author_slug=None, futu...
if queryset is None: queryset = get_entry_model().objects.all() if appsettings.FLUENT_BLOGS_FILTER_SITE_ID: queryset = queryset.parent_site(settings.SITE_ID) if not future: queryset = queryset.published() if year: queryset = queryset.filter(publication_date__year=year...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_tags(order=None, orderby=None, limit=None): """ Query the tags, with usage count included. This interface is mainly used by the ``get_tags`` template t...
from taggit.models import Tag, TaggedItem # feature is still optional # Get queryset filters for published entries EntryModel = get_entry_model() ct = ContentType.objects.get_for_model(EntryModel) # take advantage of local caching. entry_filter = { 'status': EntryModel.PUBLISHED }...
<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_category_for_slug(slug, language_code=None): """ Find the category for a given slug """
Category = get_category_model() if issubclass(Category, TranslatableModel): return Category.objects.active_translations(language_code, slug=slug).get() else: return Category.objects.get(slug=slug)
<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_date_range(year=None, month=None, day=None): """ Return a start..end range to query for a specific month, day or year. """
if year is None: return None if month is None: # year only start = datetime(year, 1, 1, 0, 0, 0, tzinfo=utc) end = datetime(year, 12, 31, 23, 59, 59, 999, tzinfo=utc) return (start, end) if day is None: # year + month only start = datetime(year, mon...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pattern(head, *args, mode=1, wc_name=None, conditions=None, **kwargs) \ -> Pattern: """'Flat' constructor for the Pattern class Positional and keyword argumen...
if len(args) == 0: args = None if len(kwargs) == 0: kwargs = None return Pattern(head, args, kwargs, mode=mode, wc_name=wc_name, conditions=conditions)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match_pattern(expr_or_pattern: object, expr: object) -> MatchDict: """Recursively match `expr` with the given `expr_or_pattern` Args: expr_or_pattern: either ...
try: # first try expr_or_pattern as a Pattern return expr_or_pattern.match(expr) except AttributeError: # expr_or_pattern is an expr, not a Pattern if expr_or_pattern == expr: return MatchDict() # success else: res = MatchDict() res.success = 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 update(self, *others): """Update dict with entries from `other` If `other` has an attribute ``success=False`` and ``reason``, those attributes are copied as ...
for other in others: for key, val in other.items(): self[key] = val try: if not other.success: self.success = False self.reason = other.reason except AttributeError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extended_arg_patterns(self): """Iterator over patterns for positional arguments to be matched This yields the elements of :attr:`args`, extended by their `mo...
for arg in self._arg_iterator(self.args): if isinstance(arg, Pattern): if arg.mode > self.single: while True: yield arg else: yield arg else: yield arg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finditer(self, expr): """Return an iterator over all matches in `expr` Iterate over all :class:`MatchDict` results of matches for any matching (sub-)expressi...
try: for arg in expr.args: for m in self.finditer(arg): yield m for arg in expr.kwargs.values(): for m in self.finditer(arg): yield m except AttributeError: pass m = self.match(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 wc_names(self): """Set of all wildcard names occurring in the pattern"""
if self.wc_name is None: res = set() else: res = set([self.wc_name]) if self.args is not None: for arg in self.args: if isinstance(arg, Pattern): res.update(arg.wc_names) if self.kwargs is not None: for ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_expr(cls, expr): """Instantiate proto-expression from the given Expression"""
return cls(expr.args, expr.kwargs, cls=expr.__class__)
<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_entry_model(): """ Return the actual entry model that is in use. This function reads the :ref:`FLUENT_BLOGS_ENTRY_MODEL` setting to find the model. The m...
global _EntryModel if _EntryModel is None: # This method is likely called the first time when the admin initializes, the sitemaps module is imported, or BaseBlogMixin is used. # Either way, it needs to happen after all apps have initialized, to make sure the model can be imported. if n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_category_model(): """ Return the category model to use. This function reads the :ref:`FLUENT_BLOGS_CATEGORY_MODEL` setting to find the model. """
app_label, model_name = appsettings.FLUENT_BLOGS_CATEGORY_MODEL.rsplit('.', 1) try: return apps.get_model(app_label, model_name) except Exception as e: # ImportError/LookupError raise ImproperlyConfigured("Failed to import FLUENT_BLOGS_CATEGORY_MODEL '{0}': {1}".format( appsett...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def blog_reverse(viewname, args=None, kwargs=None, current_app='fluent_blogs', **page_kwargs): """ Reverse a URL to the blog, taking various configuration option...
return mixed_reverse(viewname, args=args, kwargs=kwargs, current_app=current_app, **page_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 expand_commutators_leibniz(expr, expand_expr=True): """Recursively expand commutators in `expr` according to the Leibniz rule. .. math:: [A B, C] = A [B, C] ...
recurse = partial(expand_commutators_leibniz, expand_expr=expand_expr) A = wc('A', head=Operator) C = wc('C', head=Operator) AB = wc('AB', head=OperatorTimes) BC = wc('BC', head=OperatorTimes) def leibniz_right(A, BC): """[A, BC] -> [A, B] C + B [A, C]""" B = BC.operands[0] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_printing(*, reset=False, init_sympy=True, **kwargs): """Initialize the printing system. This determines the behavior of the :func:`ascii`, :func:`unicod...
# return either None (default) or a dict of frozen attributes if # ``_freeze=True`` is given as a keyword argument (internal use in # `configure_printing` only) logger = logging.getLogger(__name__) if reset: SympyPrinter._global_settings = {} if init_sympy: if kwargs.get('repr_f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure_printing(**kwargs): """Context manager for temporarily changing the printing system. This takes the same parameters as :func:`init_printing` Exampl...
freeze = init_printing(_freeze=True, **kwargs) try: yield finally: for obj, attr_map in freeze.items(): for attr, val in attr_map.items(): setattr(obj, attr, val)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_to_qutip(expr, full_space=None, mapping=None): """Convert a QNET expression to a qutip object Args: expr: a QNET expression full_space (HilbertSpace)...
if full_space is None: full_space = expr.space if not expr.space.is_tensor_factor_of(full_space): raise ValueError( "expr '%s' must be in full_space %s" % (expr, full_space)) if full_space == TrivialSpace: raise AlgebraError( "Cannot convert object in Trivial...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _convert_local_operator_to_qutip(expr, full_space, mapping): """Convert a LocalOperator instance to qutip"""
n = full_space.dimension if full_space != expr.space: all_spaces = full_space.local_factors own_space_index = all_spaces.index(expr.space) return qutip.tensor( *([qutip.qeye(s.dimension) for s in all_spaces[:own_space_index]] + [convert_to_qutip(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _time_dependent_to_qutip( op, full_space=None, time_symbol=symbols("t", real=True), convert_as='pyfunc'): """Convert a possiblty time-dependent operator into...
if full_space is None: full_space = op.space if time_symbol in op.free_symbols: op = op.expand() if isinstance(op, OperatorPlus): result = [] for o in op.operands: if time_symbol not in o.free_symbols: if len(result) == 0: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ljust(text, width, fillchar=' '): """Left-justify text to a total of `width` The `width` is based on graphemes:: 'Â' 'Â ' """
len_text = grapheme_len(text) return text + fillchar * (width - len_text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rjust(text, width, fillchar=' '): """Right-justify text for a total of `width` graphemes The `width` is based on graphemes:: 'Â' ' Â' """
len_text = grapheme_len(text) return fillchar * (width - len_text) + text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def KroneckerDelta(i, j, simplify=True): """Kronecker delta symbol Return :class:`One` (`i` equals `j`)), :class:`Zero` (`i` and `j` are non-symbolic an unequal)...
from qnet.algebra.core.scalar_algebra import ScalarValue, One if not isinstance(i, (int, sympy.Basic)): raise TypeError( "i is not an integer or sympy expression: %s" % type(i)) if not isinstance(j, (int, sympy.Basic)): raise TypeError( "j is not an integer or sympy ...
<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(cls, *operands, **kwargs): """Instantiate the product while applying simplification rules"""
converted_operands = [] for op in operands: if not isinstance(op, Scalar): op = ScalarValue.create(op) converted_operands.append(op) return super().create(*converted_operands, **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 conjugate(self): """Complex conjugate of of the product"""
return self.__class__.create( *[arg.conjugate() for arg in reversed(self.args)])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(cls, term, *ranges): """Instantiate the indexed sum while applying simplification rules"""
if not isinstance(term, Scalar): term = ScalarValue.create(term) return super().create(term, *ranges)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def conjugate(self): """Complex conjugate of of the indexed sum"""
return self.__class__.create(self.term.conjugate(), *self.ranges)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect_summands(cls, ops, kwargs): """Collect summands that occur multiple times into a single summand Also filters out zero-summands. Example: ((3 * A^(0),...
from qnet.algebra.core.abstract_quantum_algebra import ( ScalarTimesQuantumExpression) coeff_map = OrderedDict() for op in ops: if isinstance(op, ScalarTimesQuantumExpression): coeff, term = op.coeff, op.term else: coeff, term = 1, op if term in coeff...
<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_binary_replacement(first, second, cls): """Helper function for match_replace_binary"""
expr = ProtoExpr([first, second], {}) if LOG: logger = logging.getLogger('QNET.create') for key, rule in cls._binary_rules.items(): pat, replacement = rule match_dict = match_pattern(pat, expr) if match_dict: try: replaced = replacement(**match_di...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _match_replace_binary(cls, ops: list) -> list: """Reduce list of `ops`"""
n = len(ops) if n <= 1: return ops ops_left = ops[:n // 2] ops_right = ops[n // 2:] return _match_replace_binary_combine( cls, _match_replace_binary(cls, ops_left), _match_replace_binary(cls, ops_right))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _match_replace_binary_combine(cls, a: list, b: list) -> list: """combine two fully reduced lists a, b"""
if len(a) == 0 or len(b) == 0: return a + b r = _get_binary_replacement(a[-1], b[0], cls) if r is None: return a + b if r == cls._neutral_element: return _match_replace_binary_combine(cls, a[:-1], b[1:]) if isinstance(r, cls): r = list(r.args) else: r = [...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def empty_trivial(cls, ops, kwargs): """A ProductSpace of zero Hilbert spaces should yield the TrivialSpace"""
from qnet.algebra.core.hilbert_space_algebra import TrivialSpace if len(ops) == 0: return TrivialSpace else: return ops, 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 disjunct_hs_zero(cls, ops, kwargs): """Return ZeroOperator if all the operators in `ops` have a disjunct Hilbert space, or an unchanged `ops`, `kwargs` other...
from qnet.algebra.core.hilbert_space_algebra import TrivialSpace from qnet.algebra.core.operator_algebra import ZeroOperator hilbert_spaces = [] for op in ops: try: hs = op.space except AttributeError: # scalars hs = TrivialSpace for hs_prev in hilbert_s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def commutator_order(cls, ops, kwargs): """Apply anti-commutative property of the commutator to apply a standard ordering of the commutator arguments """
from qnet.algebra.core.operator_algebra import Commutator assert len(ops) == 2 if cls.order_key(ops[1]) < cls.order_key(ops[0]): return -1 * Commutator.create(ops[1], ops[0]) else: return ops, 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 accept_bras(cls, ops, kwargs): """Accept operands that are all bras, and turn that into to bra of the operation applied to all corresponding kets"""
from qnet.algebra.core.state_algebra import Bra kets = [] for bra in ops: if isinstance(bra, Bra): kets.append(bra.ket) else: return ops, kwargs return Bra.create(cls.create(*kets, **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 _ranges_key(r, delta_indices): """Sorting key for ranges. When used with ``reverse=True``, this can be used to sort index ranges into the order we would pref...
idx = r.index_symbol if idx in delta_indices: return (r.index_symbol.primed, r.index_symbol.name) else: # ranges that are not in delta_indices should remain in the original # order return (0, ' ')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _factors_for_expand_delta(expr): """Yield factors from expr, mixing sympy and QNET Auxiliary routine for :func:`_expand_delta`. """
from qnet.algebra.core.scalar_algebra import ScalarValue from qnet.algebra.core.abstract_quantum_algebra import ( ScalarTimesQuantumExpression) if isinstance(expr, ScalarTimesQuantumExpression): yield from _factors_for_expand_delta(expr.coeff) yield expr.term elif isinstance(exp...
<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_sympy_quantum_factor(expr): """Split a product into sympy and qnet factors This is a helper routine for applying some sympy transformation on an arbit...
from qnet.algebra.core.abstract_quantum_algebra import ( QuantumExpression, ScalarTimesQuantumExpression) from qnet.algebra.core.scalar_algebra import ScalarValue, ScalarTimes, One if isinstance(expr, ScalarTimesQuantumExpression): sympy_factor, quantum_factor = _split_sympy_quantum_factor(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extract_delta(expr, idx): """Extract a "simple" Kronecker delta containing `idx` from `expr`. Assuming `expr` can be written as the product of a Kronecker D...
from qnet.algebra.core.abstract_quantum_algebra import QuantumExpression from qnet.algebra.core.scalar_algebra import ScalarValue sympy_factor, quantum_factor = _split_sympy_quantum_factor(expr) delta, new_expr = _sympy_extract_delta(sympy_factor, idx) if delta is None: new_expr = 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 _deltasummation(term, ranges, i_range): """Partially execute a summation for `term` with a Kronecker Delta for one of the summation indices. This implements ...
from qnet.algebra.core.abstract_quantum_algebra import QuantumExpression idx = ranges[i_range].index_symbol summands = _expand_delta(term, idx) if len(summands) > 1: return [(summand, ranges) for summand in summands], 3 else: delta, expr = _extract_delta(summands[0], idx) if not...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def permutation_to_block_permutations(permutation): """If possible, decompose a permutation into a sequence of permutations each acting on individual ranges of t...
if len(permutation) == 0 or not check_permutation(permutation): raise BadPermutationError() cycles = permutation_to_disjoint_cycles(permutation) if len(cycles) == 1: return (permutation,) current_block_start = cycles[0][0] current_block_end = max(cycles[0]) current_block_cycle...
<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_perm_and_perms_within_blocks(permutation, block_structure): """Decompose a permutation into a block permutation and into permutations acting within eac...
nblocks = len(block_structure) offsets = [sum(block_structure[:k]) for k in range(nblocks)] images = [permutation[offset: offset + length] for (offset, length) in zip(offsets, block_structure)] images_mins = list(map(min, images)) key_block_perm_inv = lambda block_index: images_mins[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 _check_kets(*ops, same_space=False, disjunct_space=False): """Check that all operands are Kets from the same Hilbert space."""
if not all([(isinstance(o, State) and o.isket) for o in ops]): raise TypeError("All operands must be Kets") if same_space: if not len({o.space for o in ops if o is not ZeroKet}) == 1: raise UnequalSpaces(str(ops)) if disjunct_space: spc = TrivialSpace for o in op...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def args(self): """Tuple containing `label_or_index` as its only element."""
if self.space.has_basis or isinstance(self.label, SymbolicLabelBase): return (self.label, ) else: return (self.index, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_fock_representation(self, index_symbol='n', max_terms=None): """Return the coherent state written out as an indexed sum over Fock basis states"""
phase_factor = sympy.exp( sympy.Rational(-1, 2) * self.ampl * self.ampl.conjugate()) if not isinstance(index_symbol, IdxSym): index_symbol = IdxSym(index_symbol) n = index_symbol if max_terms is None: index_range = IndexOverFockSpace(n, hs=self._hs) ...
<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_script(self, inputid): """ Build CodeMirror HTML script tag which contains CodeMirror init. Arguments: inputid (string): Input id. Returns: strin...
varname = "{}_codemirror".format(inputid) html = self.get_codemirror_field_js() opts = self.codemirror_config() return html.format(varname=varname, inputid=inputid, settings=json.dumps(opts, sort_keys=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 _algebraic_rules_scalar(): """Set the default algebraic rules for scalars"""
a = wc("a", head=SCALAR_VAL_TYPES) b = wc("b", head=SCALAR_VAL_TYPES) x = wc("x", head=SCALAR_TYPES) y = wc("y", head=SCALAR_TYPES) z = wc("z", head=SCALAR_TYPES) indranges__ = wc("indranges__", head=IndexRangeBase) ScalarTimes._binary_rules.update(check_rules_dict([ ('R001', ( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _tensor_decompose_series(lhs, rhs): """Simplification method for lhs << rhs Decompose a series product of two reducible circuits with compatible block struct...
if isinstance(rhs, CPermutation): raise CannotSimplify() lhs_structure = lhs.block_structure rhs_structure = rhs.block_structure res_struct = _get_common_block_structure(lhs_structure, rhs_structure) if len(res_struct) > 1: blocks, oblocks = ( lhs.get_blocks(res_struct),...
<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_permutation_for_blocks(cperm, rhs): """Simplification method for cperm << rhs. Decompose a series product of a channel permutation and a reducible ci...
rbs = rhs.block_structure if rhs == cid(rhs.cdim): return cperm if len(rbs) > 1: residual_lhs, transformed_rhs, carried_through_lhs \ = cperm._factorize_for_rhs(rhs) if residual_lhs == cperm: raise CannotSimplify() return SeriesProduct.create(resi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pull_out_perm_lhs(lhs, rest, out_port, in_port): """Pull out a permutation from the Feedback of a SeriesProduct with itself. Args: lhs (CPermutation): The ...
out_inv, lhs_red = lhs._factor_lhs(out_port) return lhs_red << Feedback.create(SeriesProduct.create(*rest), out_port=out_inv, in_port=in_port)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pull_out_unaffected_blocks_lhs(lhs, rest, out_port, in_port): """In a self-Feedback of a series product, where the left-most operand is reducible, pull all ...
_, block_index = lhs.index_in_block(out_port) bs = lhs.block_structure nbefore, nblock, nafter = (sum(bs[:block_index]), bs[block_index], sum(bs[block_index + 1:])) before, block, after = lhs.get_blocks((nbefore, nblock, nafter)) if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _series_feedback(series, out_port, in_port): """Invert a series self-feedback twice to get rid of unnecessary permutations."""
series_s = series.series_inverse().series_inverse() if series_s == series: raise CannotSimplify() return series_s.feedback(out_port=out_port, in_port=in_port)