from dis import dis
from io import StringIO
from itertools import product, chain
import random
import sys

import pytest

from codetransformer.code import Code, Flag, pycode
from codetransformer.instructions import LOAD_CONST, LOAD_FAST, uses_free

@pytest.fixture(scope='module')
def sample_flags(request):
    random.seed(8025816322119661921)  # ayy lmao
    nflags = len(Flag.__members__)
    return tuple(
        dict(zip(Flag.__members__.keys(), case)) for case in chain(
            random.sample(list(product((True, False), repeat=nflags)), 1000),
            [[True] * nflags],
            [[False] * nflags],
        )
    )

def test_lnotab_roundtrip():
    # DO NOT ADD EXTRA LINES HERE
    def f():  # pragma: no cover
        a = 1
        b = 2
        c = 3
        d = 4
        a, b, c, d

    start_line = test_lnotab_roundtrip.__code__.co_firstlineno + 3
    lines = [start_line + n for n in range(5)]
    code = Code.from_pycode(f.__code__)
    lnotab = code.lnotab
    assert lnotab.keys() == set(lines)
    assert isinstance(lnotab[lines[0]], LOAD_CONST)
    assert lnotab[lines[0]].arg == 1
    assert isinstance(lnotab[lines[1]], LOAD_CONST)
    assert lnotab[lines[1]].arg == 2
    assert isinstance(lnotab[lines[2]], LOAD_CONST)
    assert lnotab[lines[2]].arg == 3
    assert isinstance(lnotab[lines[3]], LOAD_CONST)
    assert lnotab[lines[3]].arg == 4
    assert isinstance(lnotab[lines[4]], LOAD_FAST)
    assert lnotab[lines[4]].arg == 'a'
    assert f.__code__.co_lnotab == code.py_lnotab == code.to_pycode().co_lnotab

def test_lnotab_really_dumb_whitespace():
    ns = {}
    exec('def f():\n    lol = True' + '\n' * 1024 + '    wut = True', ns)
    f = ns['f']
    code = Code.from_pycode(f.__code__)
    lines = [2, 1026]
    lnotab = code.lnotab
    assert lnotab.keys() == set(lines)
    assert isinstance(lnotab[lines[0]], LOAD_CONST)
    assert lnotab[lines[0]].arg
    assert isinstance(lnotab[lines[1]], LOAD_CONST)
    assert lnotab[lines[1]].arg
    assert f.__code__.co_lnotab == code.py_lnotab == code.to_pycode().co_lnotab

def test_flag_packing(sample_flags):
    for flags in sample_flags:
        assert Flag.unpack(Flag.pack(**flags)) == flags

def test_flag_unpack_too_big():
    assert all(Flag.unpack(Flag.max).values())
    with pytest.raises(ValueError):
        Flag.unpack(Flag.max + 1)

def test_flag_max():
    assert Flag.pack(
        CO_OPTIMIZED=True,
        CO_NEWLOCALS=True,
        CO_VARARGS=True,
        CO_VARKEYWORDS=True,
        CO_NESTED=True,
        CO_GENERATOR=True,
        CO_NOFREE=True,
        CO_COROUTINE=True,
        CO_ITERABLE_COROUTINE=True,
        CO_FUTURE_DIVISION=True,
        CO_FUTURE_ABSOLUTE_IMPORT=True,
        CO_FUTURE_WITH_STATEMENT=True,
        CO_FUTURE_PRINT_FUNCTION=True,
        CO_FUTURE_UNICODE_LITERALS=True,
        CO_FUTURE_BARRY_AS_BDFL=True,
        CO_FUTURE_GENERATOR_STOP=True,
    ) == Flag.max

def test_flag_max_immutable():
    with pytest.raises(AttributeError):
        Flag.CO_OPTIMIZED.max = None

def test_code_multiple_varargs():
    with pytest.raises(ValueError) as e:
        Code(
            (), (
                '*args',
                '*other',
            ),
        )

    assert str(e.value) == 'cannot specify *args more than once'

def test_code_multiple_kwargs():
    with pytest.raises(ValueError) as e:
        Code(
            (), (
                '**kwargs',
                '**kwargs',
            ),
        )

    assert str(e.value) == 'cannot specify **kwargs more than once'

@pytest.mark.parametrize('cls', uses_free)
def test_dangling_var(cls):
    instr = cls('dangling')
    with pytest.raises(ValueError) as e:
        Code((instr,))

    assert (
        str(e.value) ==
        "Argument to %r is not in cellvars or freevars." % instr
    )

def test_code_flags(sample_flags):
    attr_map = {
        'CO_NESTED': 'is_nested',
        'CO_GENERATOR': 'is_generator',
        'CO_COROUTINE': 'is_coroutine',
        'CO_ITERABLE_COROUTINE': 'is_iterable_coroutine',
        'CO_NEWLOCALS': 'constructs_new_locals',
    }
    for flags in sample_flags:
        if sys.version_info < (3, 6):
            codestring = b'd\x00\x00S'  # return None
        else:
            codestring = b'd\x00S'  # return None

        code = Code.from_pycode(pycode(
            argcount=0,
            kwonlyargcount=0,
            nlocals=2,
            stacksize=0,
            flags=Flag.pack(**flags),
            codestring=codestring,
            constants=(None,),
            names=(),
            varnames=('a', 'b'),
            filename='',
            name='',
            firstlineno=0,
            lnotab=b'',
        ))
        assert code.flags == flags
        for flag, attr in attr_map.items():
            if flags[flag]:
                assert getattr(code, attr)

@pytest.fixture
def abc_code():
    a = LOAD_CONST('a')
    b = LOAD_CONST('b')
    c = LOAD_CONST('c')  # not in instrs
    code = Code((a, b), argnames=())

    return (a, b, c), code

def test_instr_index(abc_code):
    (a, b, c), code = abc_code

    assert code.index(a) == 0
    assert code.index(b) == 1

    with pytest.raises(ValueError):
        code.index(c)

def test_code_contains(abc_code):
    (a, b, c), code = abc_code

    assert a in code
    assert b in code
    assert c not in code

def test_code_dis(capsys):
    @Code.from_pyfunc
    def code():  # pragma: no cover
        a = 1
        b = 2
        return a, b

    buf = StringIO()
    dis(code.to_pycode(), file=buf)
    expected = buf.getvalue()

    code.dis()
    out, err = capsys.readouterr()
    assert not err
    assert out == expected

    buf = StringIO()
    code.dis(file=buf)
    assert buf.getvalue() == expected

ayy lmao DO NOT ADD EXTRA LINES HERE pragma: no cover return None return None not in instrs pragma: no cover


# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------

from enum import Enum, EnumMeta
from six import with_metaclass

class _CaseInsensitiveEnumMeta(EnumMeta):
    def __getitem__(self, name):
        return super().__getitem__(name.upper())

    def __getattr__(cls, name):
        """Return the enum member matching `name`
        We use __getattr__ instead of descriptors or inserting into the enum
        class' __dict__ in order to support `name` and `value` being both
        properties for enum members (which live in the class' __dict__) and
        enum members themselves.
        """
        try:
            return cls._member_map_[name.upper()]
        except KeyError:
            raise AttributeError(name)

class LockLevel(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
    """The lock level of the management lock.
    """

    NOT_SPECIFIED = "NotSpecified"
    CAN_NOT_DELETE = "CanNotDelete"
    READ_ONLY = "ReadOnly"

The lock level of the management lock.

Return the enum member matching `name`
We use __getattr__ instead of descriptors or inserting into the enum
class' __dict__ in order to support `name` and `value` being both
properties for enum members (which live in the class' __dict__) and
enum members themselves.

 coding=utf-8 -------------------------------------------------------------------------- Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. Code generated by Microsoft (R) AutoRest Code Generator. Changes may cause incorrect behavior and will be lost if the code is regenerated. --------------------------------------------------------------------------


from sourcer import Grammar

# This is work in progress.
# See: https://help.salesforce.com/articleView?id=customize_functions.htm&type=5

g = Grammar(r'''
    ```
    import ast
    ```

    start = Expression

    Expression = OperatorPrecedence(
        Atom | "(" >> Expression << ")",
        Postfix(ArgumentList | FieldAccess),
        Prefix("-" | "+" | "!"),
        RightAssoc("^"),
        LeftAssoc("*" | "/"),
        LeftAssoc("+" | "-" | "&"),
        NonAssoc("<=" | "<" | ">=" | ">"),
        NonAssoc("!=" | "<>" | "==" | "="),
        LeftAssoc("&&"),
        LeftAssoc("||"),
    )

    class ArgumentList {
        arguments: "(" >> (Expression /? ",") << ")"
    }

    class FieldAccess {
        field: "." >> Word
    }

    Atom = Global | Identifier | Rational | Integer | String

    class Global {
        name: "$" >> Word
    }

    class Identifier {
        name: Word
    }

    # ASK: What is the real syntax for these things?
    Word = /[_a-zA-Z][_a-zA-Z0-9]*/
    Rational = /(\d+\.\d*)|(\d*\.\d+)/ |> `float`
    Integer = /\d+/ |> `int`
    StringLiteral = /("([^"\\]|\\.)*")/ | /('([^'\\]|\\.)*')/

    # For now, just use ast module to evaluate string literals.
    class String {
        value: StringLiteral |> `ast.literal_eval`
    }

    ignore /\s+/

''', include_source=True)

aliases = {
    '=': '==',
    '<>': '!=',
}

constants = {
    'NULL': None,
    'TRUE': True,
    'FALSE': False,
}

# Incomplete collection of evaluators.
evaluators = {
    '*': lambda x, y: x * y if x is not None and y is not None else None,
    '/': lambda x, y: x / y if x is not None and y is not None else None,
    '+': lambda x, y: x + y if x is not None and y is not None else None,
    '-': lambda x, y: x - y if x is not None and y is not None else None,
    '==': lambda x, y: x == y,
    '!=': lambda x, y: x != y,
    '&&': lambda x, y: x and y,
    '||': lambda x, y: x or y,
    '>': lambda x, y: x > y if x is not None and y is not None else False,
    '<': lambda x, y: x < y if x is not None and y is not None else False,
    '>=': lambda x, y: x >= y if x is not None and y is not None else False,
    '<=': lambda x, y: x <= y if x is not None and y is not None else False,
    'AND': lambda *a: all(a),
    'CONTAINS': lambda x, y: str(y) in str(x) if x is not None else True,
    'IF': lambda x, y, z: y if x else z,
    'ISBLANK': lambda x: x is None,
    'LOG': lambda x: log10(x) if x is not None else None,
    'MAX': lambda *a: max(*a),
    'MIN': lambda *a: min(*a),
    'MOD': lambda x, y: (x % y) if x is not None and y is not None else None,
    'NOT': lambda x: not(x),
    'OR': lambda *a: any(a),
    'SQRT': lambda x: sqrt(x) if x is not None else None,
    'TEXT': lambda x: str(x),
}

def evaluate(node, bindings):
    # Look up identifiers.
    if isinstance(node, g.Identifier):
        if node.name in bindings:
            return bindings[node.name]

        name = node.name.upper()
        return bindings.get(name, name)

    # Look up fields.
    if isinstance(node, g.Postfix) and isinstance(node.operator, g.FieldAccess):
        obj, field = node.left, node.operator.field
        if hasattr(obj, field):
            return getattr(obj, field)
        elif isinstance(obj, dict):
            return obj.get(field)
        else:
            return node

    # Evaluate function calls and operators.
    if isinstance(node, g.Infix):
        x, func, y = node.left, node.operator, node.right
        args = (x, y)
    elif isinstance(node, g.Postfix) and isinstance(node.operator, g.ArgumentList):
        func, args = node.left, node.operator.arguments
    else:
        return node

    # Check if we're using an alias.
    func = aliases.get(func, func)

    if func in evaluators:
        return evaluators[func](*args)
    else:
        return node

def run(formula, bindings=None):
    updated_bindings = dict(constants)
    updated_bindings.update(bindings or {})
    tree = g.parse(formula)
    return g.transform(tree, lambda node: evaluate(node, updated_bindings))

def test_some_simple_formulas():
    result = run('1 + 2 * 3')
    assert result == 7

    result = run('foo == bar && fiz == buz', bindings={
        'foo': 1, 'bar': 1, 'fiz': 2, 'buz': 2,
    })
    assert result == True

    result = run('foo == bar && fiz == buz', bindings={
        'foo': 1, 'bar': 1, 'fiz': 2, 'buz': 3,
    })
    assert result == False

    result = run('1 <= 2 && (false || true)')
    assert result == True # Explicitly compare to True.

    result = run('1 > 2 || (true && false)')
    assert result == False # Explicitly compare to False.

    result = run('foo != bar', bindings={'foo': 10, 'bar': 10})
    assert not result

    result = run('foo != bar', bindings={'foo': 1, 'bar': 2})
    assert result

    result = run('foo.bar', bindings={'foo': {'bar': 10}})
    assert result == 10

    result = run('foo.bar.baz', bindings={'foo': {'bar': {'baz': 100}}})
    assert result == 100

    result = run('MIN(20, 10, 30)')
    assert result == 10

    result = run('MIN(20, 10, 30) + MAX(11, 12, 13)')
    assert result == 23

This is work in progress. See: https://help.salesforce.com/articleView?id=customize_functions.htm&type=5 Incomplete collection of evaluators. Look up identifiers. Look up fields. Evaluate function calls and operators. Check if we're using an alias. Explicitly compare to True. Explicitly compare to False.


## Copyright 2003-2009 Luc Saffre
## This file is part of the TimTools project.
## TimTools is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
## TimTools is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with TimTools; if not, see <http://www.gnu.org/licenses/>.

import re

def plain2xml(txt):
   txt = txt.replace("&","&")
   txt = txt.replace("<","<")
   return txt

memocommands = (
   ( re.compile('\[url\s+(\S+)\s*(.*?)\]',re.DOTALL),
     lambda m : ''+m.group(2)+' (' + m.group(1)+ ')'),
   )
# urlfind =
# urlrepl = re.compile('\2 (\1)')

# def urlrepl(m):

def memo2xml(txt):
   txt = plain2xml(txt)
   txt = txt.replace('[B]','')
   txt = txt.replace('[b]','')
   txt = txt.replace('[U]','')
   txt = txt.replace('[u]','')
   for find,repl in memocommands:
      txt = re.sub(find,repl,txt)
   return txt

def rst2xml(txt):
   raise "doesn't work"
   import docutils.parsers.rst
   import docutils.utils
   parser = docutils.parsers.rst.Parser()
   doc = docutils.utils.new_document("feed")
   parser.parse(txt, doc)
   raise "and now?"

_feeders={
   'xml' : lambda x : x,
   'plain' : plain2xml,
   'rst' : rst2xml,
   'memo' : memo2xml,
   }

def getFeeder(name):
   return _feeders[name]

Copyright 2003-2009 Luc Saffre This file is part of the TimTools project. TimTools is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. TimTools is distributed in the hope that it will be useful,  but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  GNU General Public License for more details. You should have received a copy of the GNU General Public License along with TimTools; if not, see <http://www.gnu.org/licenses/>. urlfind =  urlrepl = re.compile('\2 (\1)') def urlrepl(m):


from __future__ import absolute_import
from typing import Any, List, Dict, Optional, Text

from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse, HttpRequest
from django.shortcuts import redirect
from django.utils import translation
from django.utils.cache import patch_cache_control
from six.moves import zip_longest, zip, range

from zerver.decorator import zulip_login_required, process_client
from zerver.forms import ToSForm
from zerver.lib.realm_icon import realm_icon_url
from zerver.models import Message, UserProfile, Stream, Subscription, Huddle, \
    Recipient, Realm, UserMessage, DefaultStream, RealmEmoji, RealmAlias, \
    RealmFilter, PreregistrationUser, UserActivity, \
    UserPresence, get_recipient, name_changes_disabled, email_to_username, \
    list_of_domains_for_realm
from zerver.lib.events import do_events_register
from zerver.lib.actions import update_user_presence, do_change_tos_version, \
    do_update_pointer, get_cross_realm_dicts, realm_user_count
from zerver.lib.avatar import avatar_url
from zerver.lib.i18n import get_language_list, get_language_name, \
    get_language_list_for_templates
from zerver.lib.push_notifications import num_push_devices_for_user
from zerver.lib.streams import access_stream_by_name
from zerver.lib.utils import statsd, get_subdomain
from zproject.backends import password_auth_enabled
from zproject.jinja2 import render_to_response

import calendar
import datetime
import logging
import os
import re
import simplejson
import time

@zulip_login_required
def accounts_accept_terms(request):
    # type: (HttpRequest) -> HttpResponse
    if request.method == "POST":
        form = ToSForm(request.POST)
        if form.is_valid():
            do_change_tos_version(request.user, settings.TOS_VERSION)
            return redirect(home)
    else:
        form = ToSForm()

    email = request.user.email
    special_message_template = None
    if request.user.tos_version is None and settings.FIRST_TIME_TOS_TEMPLATE is not None:
        special_message_template = 'zerver/' + settings.FIRST_TIME_TOS_TEMPLATE
    return render_to_response(
        'zerver/accounts_accept_terms.html',
        {'form': form,
         'email': email,
         'special_message_template': special_message_template},
        request=request)

def approximate_unread_count(user_profile):
    # type: (UserProfile) -> int
    not_in_home_view_recipients = [sub.recipient.id for sub in
                                   Subscription.objects.filter(
                                       user_profile=user_profile, in_home_view=False)]

    # TODO: We may want to exclude muted messages from this count.
    #       It was attempted in the past, but the original attempt
    #       was broken.  When we re-architect muting, we may
    #       want to to revisit this (see git issue #1019).
    return UserMessage.objects.filter(
        user_profile=user_profile, message_id__gt=user_profile.pointer).exclude(
        message__recipient__type=Recipient.STREAM,
        message__recipient__id__in=not_in_home_view_recipients).exclude(
        flags=UserMessage.flags.read).count()

def sent_time_in_epoch_seconds(user_message):
    # type: (UserMessage) -> Optional[float]
    # user_message is a UserMessage object.
    if not user_message:
        return None
    # We have USE_TZ = True, so our datetime objects are timezone-aware.
    # Return the epoch seconds in UTC.
    return calendar.timegm(user_message.message.pub_date.utctimetuple())

def home(request):
    # type: (HttpRequest) -> HttpResponse
    if settings.DEVELOPMENT and os.path.exists('var/handlebars-templates/compile.error'):
        response = render_to_response('zerver/handlebars_compilation_failed.html',
                                      request=request)
        response.status_code = 500
        return response
    if not settings.SUBDOMAINS_HOMEPAGE:
        return home_real(request)

    # If settings.SUBDOMAINS_HOMEPAGE, sends the user the landing
    # page, not the login form, on the root domain

    subdomain = get_subdomain(request)
    if subdomain != "":
        return home_real(request)

    return render_to_response('zerver/hello.html',
                              request=request)

@zulip_login_required
def home_real(request):
    # type: (HttpRequest) -> HttpResponse
    # We need to modify the session object every two weeks or it will expire.
    # This line makes reloading the page a sufficient action to keep the
    # session alive.
    request.session.modified = True

    user_profile = request.user

    # If a user hasn't signed the current Terms of Service, send them there
    if settings.TERMS_OF_SERVICE is not None and settings.TOS_VERSION is not None and \
       int(settings.TOS_VERSION.split('.')[0]) > user_profile.major_tos_version():
        return accounts_accept_terms(request)

    narrow = [] # type: List[List[Text]]
    narrow_stream = None
    narrow_topic = request.GET.get("topic")
    if request.GET.get("stream"):
        try:
            narrow_stream_name = request.GET.get("stream")
            (narrow_stream, ignored_rec, ignored_sub) = access_stream_by_name(
                user_profile, narrow_stream_name)
            narrow = [["stream", narrow_stream.name]]
        except Exception:
            logging.exception("Narrow parsing")
        if narrow_stream is not None and narrow_topic is not None:
            narrow.append(["topic", narrow_topic])

    register_ret = do_events_register(user_profile, request.client,
                                      apply_markdown=True, narrow=narrow)
    user_has_messages = (register_ret['max_message_id'] != -1)

    # Reset our don't-spam-users-with-email counter since the
    # user has since logged in
    if user_profile.last_reminder is not None:
        user_profile.last_reminder = None
        user_profile.save(update_fields=["last_reminder"])

    # Brand new users get the tutorial
    needs_tutorial = settings.TUTORIAL_ENABLED and \
        user_profile.tutorial_status != UserProfile.TUTORIAL_FINISHED

    first_in_realm = realm_user_count(user_profile.realm) == 1
    # If you are the only person in the realm and you didn't invite
    # anyone, we'll continue to encourage you to do so on the frontend.
    prompt_for_invites = first_in_realm and \
        not PreregistrationUser.objects.filter(referred_by=user_profile).count()

    if user_profile.pointer == -1 and user_has_messages:
        # Put the new user's pointer at the bottom
        #
        # This improves performance, because we limit backfilling of messages
        # before the pointer.  It's also likely that someone joining an
        # organization is interested in recent messages more than the very
        # first messages on the system.

        register_ret['pointer'] = register_ret['max_message_id']
        user_profile.last_pointer_updater = request.session.session_key

    if user_profile.pointer == -1:
        latest_read = None
    else:
        try:
            latest_read = UserMessage.objects.get(user_profile=user_profile,
                                                  message__id=user_profile.pointer)
        except UserMessage.DoesNotExist:
            # Don't completely fail if your saved pointer ID is invalid
            logging.warning("%s has invalid pointer %s" % (user_profile.email, user_profile.pointer))
            latest_read = None

    desktop_notifications_enabled = user_profile.enable_desktop_notifications
    if narrow_stream is not None:
        desktop_notifications_enabled = False

    if user_profile.realm.notifications_stream:
        notifications_stream = user_profile.realm.notifications_stream.name
    else:
        notifications_stream = ""

    # Set default language and make it persist
    default_language = register_ret['default_language']
    url_lang = '/{}'.format(request.LANGUAGE_CODE)
    if not request.path.startswith(url_lang):
        translation.activate(default_language)

    request.session[translation.LANGUAGE_SESSION_KEY] = default_language

    # Pass parameters to the client-side JavaScript code.
    # These end up in a global JavaScript Object named 'page_params'.
    page_params = dict(
        # Server settings.
        share_the_love        = settings.SHARE_THE_LOVE,
        development_environment = settings.DEVELOPMENT,
        debug_mode            = settings.DEBUG,
        test_suite            = settings.TEST_SUITE,
        poll_timeout          = settings.POLL_TIMEOUT,
        login_page            = settings.HOME_NOT_LOGGED_IN,
        server_uri            = settings.SERVER_URI,
        maxfilesize           = settings.MAX_FILE_UPLOAD_SIZE,
        max_avatar_file_size  = settings.MAX_AVATAR_FILE_SIZE,
        server_generation     = settings.SERVER_GENERATION,
        use_websockets        = settings.USE_WEBSOCKETS,
        save_stacktraces      = settings.SAVE_FRONTEND_STACKTRACES,

        # realm data.
        # TODO: Move all of these data to register_ret and pull from there
        realm_uri             = user_profile.realm.uri,
        password_auth_enabled = password_auth_enabled(user_profile.realm),
        domains               = list_of_domains_for_realm(user_profile.realm),
        name_changes_disabled = name_changes_disabled(user_profile.realm),
        mandatory_topics      = user_profile.realm.mandatory_topics,
        show_digest_email     = user_profile.realm.show_digest_email,
        realm_presence_disabled = user_profile.realm.presence_disabled,
        is_zephyr_mirror_realm = user_profile.realm.is_zephyr_mirror_realm,

        # user_profile data.
        # TODO: Move all of these data to register_ret and pull from there
        fullname              = user_profile.full_name,
        email                 = user_profile.email,
        enter_sends           = user_profile.enter_sends,
        user_id               = user_profile.id,
        is_admin              = user_profile.is_realm_admin,
        can_create_streams    = user_profile.can_create_streams(),
        autoscroll_forever = user_profile.autoscroll_forever,
        default_desktop_notifications = user_profile.default_desktop_notifications,
        avatar_url            = avatar_url(user_profile),
        avatar_url_medium     = avatar_url(user_profile, medium=True),
        avatar_source         = user_profile.avatar_source,
        timezone              = user_profile.timezone,

        # Stream message notification settings:
        stream_desktop_notifications_enabled = user_profile.enable_stream_desktop_notifications,
        stream_sounds_enabled = user_profile.enable_stream_sounds,

        # Private message and @-mention notification settings:
        desktop_notifications_enabled = desktop_notifications_enabled,
        sounds_enabled = user_profile.enable_sounds,
        enable_offline_email_notifications = user_profile.enable_offline_email_notifications,
        pm_content_in_desktop_notifications = user_profile.pm_content_in_desktop_notifications,
        enable_offline_push_notifications = user_profile.enable_offline_push_notifications,
        enable_online_push_notifications = user_profile.enable_online_push_notifications,
        enable_digest_emails  = user_profile.enable_digest_emails,

        # Realm foreign key data from register_ret.
        # TODO: Rename these to match register_ret values.
        subbed_info           = register_ret['subscriptions'],
        unsubbed_info         = register_ret['unsubscribed'],
        neversubbed_info      = register_ret['never_subscribed'],
        people_list           = register_ret['realm_users'],
        bot_list              = register_ret['realm_bots'],
        initial_pointer       = register_ret['pointer'],
        initial_presences     = register_ret['presences'],
        event_queue_id        = register_ret['queue_id'],

        # Misc. extra data.
        have_initial_messages = user_has_messages,
        initial_servertime    = time.time(), # Used for calculating relative presence age
        default_language_name = get_language_name(register_ret['default_language']),
        language_list_dbl_col = get_language_list_for_templates(register_ret['default_language']),
        language_list         = get_language_list(),
        needs_tutorial        = needs_tutorial,
        first_in_realm        = first_in_realm,
        prompt_for_invites    = prompt_for_invites,
        notifications_stream  = notifications_stream,
        cross_realm_bots      = list(get_cross_realm_dicts()),
        unread_count          = approximate_unread_count(user_profile),
        furthest_read_time    = sent_time_in_epoch_seconds(latest_read),
        has_mobile_devices    = num_push_devices_for_user(user_profile) > 0,
    )

    # These fields will be automatically copied from register_ret into
    # page_params.  It is a goal to move more of the page_params list
    # into this sort of cleaner structure.
    page_params_core_fields = [
        'alert_words',
        'attachments',
        'default_language',
        'emoji_alt_code',
        'last_event_id',
        'left_side_userlist',
        'max_icon_file_size',
        'max_message_id',
        'muted_topics',
        'realm_add_emoji_by_admins_only',
        'realm_allow_message_editing',
        'realm_authentication_methods',
        'realm_bot_domain',
        'realm_create_stream_by_admins_only',
        'realm_default_language',
        'realm_default_streams',
        'realm_email_changes_disabled',
        'realm_emoji',
        'realm_filters',
        'realm_icon_source',
        'realm_icon_url',
        'realm_invite_by_admins_only',
        'realm_invite_required',
        'realm_message_content_edit_limit_seconds',
        'realm_name',
        'realm_name_changes_disabled',
        'realm_restricted_to_domain',
        'realm_waiting_period_threshold',
        'referrals',
        'twenty_four_hour_time',
        'zulip_version',
    ]

    for field_name in page_params_core_fields:
        page_params[field_name] = register_ret[field_name]

    if narrow_stream is not None:
        # In narrow_stream context, initial pointer is just latest message
        recipient = get_recipient(Recipient.STREAM, narrow_stream.id)
        try:
            initial_pointer = Message.objects.filter(recipient=recipient).order_by('id').reverse()[0].id
        except IndexError:
            initial_pointer = -1
        page_params["narrow_stream"] = narrow_stream.name
        if narrow_topic is not None:
            page_params["narrow_topic"] = narrow_topic
        page_params["narrow"] = [dict(operator=term[0], operand=term[1]) for term in narrow]
        page_params["max_message_id"] = initial_pointer
        page_params["initial_pointer"] = initial_pointer
        page_params["have_initial_messages"] = (initial_pointer != -1)

    statsd.incr('views.home')
    show_invites = True

    # Some realms only allow admins to invite users
    if user_profile.realm.invite_by_admins_only and not user_profile.is_realm_admin:
        show_invites = False

    request._log_data['extra'] = "[%s]" % (register_ret["queue_id"],)
    response = render_to_response('zerver/index.html',
                                  {'user_profile': user_profile,
                                   'page_params': simplejson.encoder.JSONEncoderForHTML().encode(page_params),
                                   'nofontface': is_buggy_ua(request.META.get("HTTP_USER_AGENT", "Unspecified")),
                                   'avatar_url': avatar_url(user_profile),
                                   'show_debug':
                                       settings.DEBUG and ('show_debug' in request.GET),
                                   'pipeline': settings.PIPELINE_ENABLED,
                                   'show_invites': show_invites,
                                   'is_admin': user_profile.is_realm_admin,
                                   'show_webathena': user_profile.realm.webathena_enabled,
                                   'enable_feedback': settings.ENABLE_FEEDBACK,
                                   'embedded': narrow_stream is not None,
                                   },
                                  request=request)
    patch_cache_control(response, no_cache=True, no_store=True, must_revalidate=True)
    return response

@zulip_login_required
def desktop_home(request):
    # type: (HttpRequest) -> HttpResponse
    return HttpResponseRedirect(reverse('zerver.views.home.home'))

def is_buggy_ua(agent):
    # type: (str) -> bool
    """Discrimiate CSS served to clients based on User Agent

    Due to QTBUG-3467, @font-face is not supported in QtWebKit.
    This may get fixed in the future, but for right now we can
    just serve the more conservative CSS to all our desktop apps.
    """
    return ("Humbug Desktop/" in agent or "Zulip Desktop/" in agent or "ZulipDesktop/" in agent) and \
        "Mac" not in agent

Discrimiate CSS served to clients based on User Agent

Due to QTBUG-3467, @font-face is not supported in QtWebKit.
This may get fixed in the future, but for right now we can
just serve the more conservative CSS to all our desktop apps.

 type: (HttpRequest) -> HttpResponse type: (UserProfile) -> int TODO: We may want to exclude muted messages from this count.       It was attempted in the past, but the original attempt       was broken.  When we re-architect muting, we may       want to to revisit this (see git issue 1019). type: (UserMessage) -> Optional[float] user_message is a UserMessage object. We have USE_TZ = True, so our datetime objects are timezone-aware. Return the epoch seconds in UTC. type: (HttpRequest) -> HttpResponse If settings.SUBDOMAINS_HOMEPAGE, sends the user the landing page, not the login form, on the root domain type: (HttpRequest) -> HttpResponse We need to modify the session object every two weeks or it will expire. This line makes reloading the page a sufficient action to keep the session alive. If a user hasn't signed the current Terms of Service, send them there type: List[List[Text]] Reset our don't-spam-users-with-email counter since the user has since logged in Brand new users get the tutorial If you are the only person in the realm and you didn't invite anyone, we'll continue to encourage you to do so on the frontend. Put the new user's pointer at the bottom This improves performance, because we limit backfilling of messages before the pointer.  It's also likely that someone joining an organization is interested in recent messages more than the very first messages on the system. Don't completely fail if your saved pointer ID is invalid Set default language and make it persist Pass parameters to the client-side JavaScript code. These end up in a global JavaScript Object named 'page_params'. Server settings. realm data. TODO: Move all of these data to register_ret and pull from there user_profile data. TODO: Move all of these data to register_ret and pull from there Stream message notification settings: Private message and @-mention notification settings: Realm foreign key data from register_ret. TODO: Rename these to match register_ret values. Misc. extra data. Used for calculating relative presence age These fields will be automatically copied from register_ret into page_params.  It is a goal to move more of the page_params list into this sort of cleaner structure. In narrow_stream context, initial pointer is just latest message Some realms only allow admins to invite users type: (HttpRequest) -> HttpResponse type: (str) -> bool


Minority interest

In accounting, minority interest (or non-controlling interest) is the portion of a subsidiary corporation's stock that is not owned by the parent corporation. The magnitude of the minority interest in the subsidiary company is generally less than 50% of outstanding shares, or the corporation would generally cease to be a subsidiary of the parent.[1]

Question: define minority interest in stock


Minority interest

Question: minority interest definition


Minority interest

Question: who owns a subsidiary stock of a company


Minority interest

It is, however, possible (such as through special voting rights) for a controlling interest requiring consolidation to be achieved without exceeding 50% ownership, depending on the accounting standards being employed. Minority interest belongs to other investors and is reported on the consolidated balance sheet of the owning company to reflect the claim on assets belonging to other, non-controlling shareholders. Also, minority interest is reported on the consolidated income statement as a share of profit belonging to minority shareholders.

Question: what is minority interest in a company


Minority interest

Question: can minority interests be held on consolidated books


Minority interest

Question: what is minority interest


Minority interest

The reporting of 'minority interest' is a consequence of the requirement by accounting standards to 'fully' consolidate partly owned subsidiaries. Full consolidation, as opposed to partial consolidation, results in financial statements that are constructed as if the parent corporation fully owns these partly owned subsidiaries; except for two line items that reflect partial ownership of subsidiaries: net income to common shareholders and common equity. The two minority interest line items are the net difference between what would have been the common equity and net income to common, if all subsidiaries were fully owned, and the actual ownership of the group. All the other line items in the financial statements assume a fictitious 100% ownership.

Question: what is minority interest


Minority interest

Question: what is minority interest in financial statements


Minority interest

Question: what is minority interest?


Minority interest

Some investors have expressed concern that the minority interest line items cause significant uncertainty for the assessment of value, leverage and liquidity.[2] A key concern of investors is that they cannot be sure what part of the reported cash position is owned by a 100% subsidiary and what part is owned by a 51% subsidiary.

Question: where are minority interest items classified?


unlike molecules which have discrete vibrational frequencies , crystals have a continuous spectrum of vibrations which can propagate as travelling waves @xcite . this fact causes crystals to be much better heat conductors than glasses or liquids . sometimes the spectrum is interrupted by gaps where no propagating normal modes occur . other interesting behavior happens at frequencies inside the gap , such as localized ( non - propagating ) normal modes associated with defects and surfaces . the text by ziman @xcite has a good discussion . a visualization of surface modes on the ( 100 ) surface of cu is on the website of ch . wll , ruhr - universitt bochum @xcite . the present paper shows how this happens for some particular cases of one - dimensional crystals , or linear chains of atoms . our treatment uses only classical mechanics , and gives properties ( frequency and displacement pattern ) rigorously by pictorial arguments with no higher algebra . the surface phonon provides the simplest example of wave localization , an effect which occurs in many branches of physics . analogous phenomena are found in the quantum treatment of electrons in single - particle approximation @xcite , and in the new field of `` photonic band - gap systems '' @xcite . this paper reports a simple way of understanding the surface phonon on the diatomic linear chain . the model is then extended and reinterpreted to give simple explanations of some other localized modes . a diatomic molecule has a single vibrational `` normal mode . '' even though the restoring force of atom 1 on atom 2 has in reality a complicated quantum - mechanical origin , for small displacements away from equilibrium , it can always be well approximated by a spring obeying hooke s law with a spring constant @xmath0 . using standard physics of the two - body problem @xcite , if the two atoms have masses @xmath1 and m@xmath2 ( @xmath3 and @xmath4 are for heavy and light ) , the squared oscillation frequency @xmath5 is @xmath6 where @xmath7 is the `` reduced mass '' @xmath8 . a crystalline solid is a very large molecule , with a continuous spectrum ( or band ) of vibrational frequencies . solids can also be modelled by masses connected to each other by springs . a one - dimensional chain of masses is often studied , not because it is found in nature , but because the mathematics is simple and can be generalized to more realistic three - dimensional arrangements . for a large enough collection of atoms , most of the vibrational normal modes are classified as `` bulk '' normal modes , which means they are essentially identical to those of a hypothetical infinite sample with no boundaries . each `` bulk '' normal mode has a pattern of atomic displacements which extends throughout the system . similar to the normal modes of a vibrating string , these are sine and cosine standing waves . alternately , one can use linear combinations of sines and cosines to give an equivalent basis of left and right - going travelling waves . for the case of all masses equal to @xmath9 , the @xmath10th atom ( located at @xmath11 ) has a displacement @xmath12 in a right - going travelling wave . the corresponding squared frequency is @xmath13 . there are as many such solutions ( @xmath14 ) as there are atoms in the chain , namely solutions for each @xmath15 in the range @xmath16 . this is derived in many texts @xcite . for @xmath17 the spectrum is continuous between the minimum squared frequency of zero and the maximum of @xmath18 . a particularly original discussion is given by martinez @xcite . the vibrational spectrum of a real material sometimes has a gap , an interval of frequencies where there are no travelling wave solutions . a simple model illustrating this is the `` diatomic chain , '' an infinite chain of alternating masses @xmath19 , @xmath1 . the algebra , which is more complicated than the monatomic chain , is also given in texts @xcite . the dispersion curve for @xmath20 is given in fig . there are now two `` branches , '' labelled acoustic and optic , and a gap . exactly in the middle of the gap , the surface may induce a * localized * vibrational normal mode , with amplitude which falls exponentially ( @xmath21 ) with distance @xmath22 into the bulk .    before discussing this , we sharpen our understanding with a quantitative interpretation of the four special bulk modes indicated by circles in fig . the frequencies of these special modes can be understood without the algebra needed to find the frequencies of the modes at general @xmath15-vectors . the four special modes circled in fig . [ disp ] have the simple vibrational patterns shown in fig . [ modes ] . first , why are these patterns `` normal modes '' ? if we take as initial conditions , the velocities of all atoms to be zero and the positions to be as shown in the figures , then newton s laws have simple , and perhaps even obvious solutions : the pattern is preserved , and oscillates in time as @xmath23 for some special choice of @xmath24 . this is the * definition * of a normal mode . second , what is the corresponding frequency of oscillation ? this can be answered by careful consideration of forces and masses . * mode a : * : :    this is the simplest mode with all atoms having the same displacement . this has infinite wavelength ( zero wavevector ) , no stretch of any    spring , and therefore zero restoring force and @xmath25 . * mode b : * : :    this has oppositely directed displacements for adjacent atoms . each    unit cell of the crystal has the same displacment pattern . therefore    the wavelength is infinite and the wavevector is zero . the    displacements in mode @xmath26 are such that    @xmath27 ( the displacement of the light atom ) is proportional    to @xmath1 , and similarly @xmath28 is proportional    to @xmath19 . thus the center of mass of each unit cell is    fixed . the mode is almost the same as in a diatomic molecule , except    each atom has two springs attached , one stretched and the other    compressed by the same amount . therefore , when released from rest ,    each pair of atoms oscillates with fixed center of mass but with twice    the restoring force of an isolated diatomic molecule , _ i.e. _    @xmath29 . this is the highest frequency    normal mode in the spectrum . * mode c : * : :    this has light atoms stationary and heavy atoms moving in an    alternating pattern . the light atoms feel equal and opposite forces    which cancel , while the heavy atoms feel repulsive and attractive    forces which add . this pattern also oscillates in time , with squared    frequency @xmath30 . * mode d : * : :    this is the same as mode * c * except heavy and light atoms are    interchanged , making the squared frequency equal to    @xmath31 . modes * c * and * d * have wavelength    @xmath32 and wavevector @xmath33 . all other normal    modes of the infinite crystal are more complicated and have    frequencies which lie on smooth curves connecting these four modes . modes which are confined to the surface region normally must have frequencies which lie outside the `` bulk '' bands . discussions of such modes are given in texts on surface physics @xcite and measurements are cataloged by kress and de wette @xcite . we have discovered a very simple explanation of the fact @xcite that a  gap mode " confined to the surface occurs in the diatomic chain if the endmost atom is a light atom . consider * mode @xmath34 * , which like mode * @xmath35 * has pairs of atoms vibrating with fixed center of mass . however , adjacent * pairs * vibrate in such a way that the connecting spring is not stretched . thus each pair experiences no force from any other atom and is decoupled from the rest of the chain . the resulting decoupled pairs oscillate with @xmath36 as for isolated diatomic molecules . since all pairs have the same frequency , this is a stable normal mode . the frequency lies exactly in the middle of the gap of the squared frequency spectrum ( @xmath37 ) . in order to be decoupled , the heavy atom of a given pair , and the adjacent light atom of the next pair deeper into the bulk , must have the same displacement , smaller by @xmath38 ( and with opposite sign ) than the displacement of the previous light atom closer to the surface , in order to conserve center of mass position . since adjacent pairs have displacement ratios @xmath39 , the @xmath40-th pair has amplitude proportional to @xmath41 . this is an exponential decay @xmath42 with decay length @xmath43 . if the surface atom had been a heavy atom , this mode would have been exponentially growing rather than decaying , which is not allowed for a normal mode . mode * e * was first found by wallis @xcite in an elegant calculation of the spectrum of finite chains . our simple argument is not ( to our knowledge ) in the literature . a  standard " derivation is given in the text by cottam and tilley @xcite . mode * e * is directly related to a * branch * of surface normal modes of higher - dimensional diatomic crystals . a two - dimensional version is shown in fig . various types of surfaces are possible for such crystals . if cut perpendicular to a conventional @xmath44 or @xmath45 axis shown in the figure by dashed lines , the surface contains equal numbers of @xmath46 and @xmath47 ions , and is referred to as `` non - polar . '' by contrast , the surface shown is a `` polar surface '' with a layer of light atoms exposed and layers of heavy and light atoms alternating underneath . there is a vibrational normal mode in which each * layer * oscillates perpendicular to the surface ( as indicated by arrows ) and which is localized at the surface . of course , in real crystals the forces extend beyond first neighbors , so the displacement ratio @xmath48 may not be exactly obeyed and the squared frequency may not lie exactly at mid - gap , but the actual behavior will mimic reasonably well the idealized one - dimensional example of the previous section .    there is actually not just one mode of this type , but a * branch * of such modes , with displacement patterns sinusoidally modulated along the surface . the one depicted in fig . [ bulk ] has the surface atoms `` a '' , `` b '' , `` c '' , all moving in phase , corresponding to an infinite wavelength , or zero wavevector , parallel to the surface . the other extreme case of modulation is when atoms along the surface are completely out of phase ; when atom `` a '' moves down , atom `` b '' moves up , and so forth , corresponding to a wavelength @xmath49 in the plane of the surface . thus we anticipate a branch of surface excitations with wavevectors lying in the plane of the surface . in order for such a mode to be exponentially localized in the surface region , the frequency of oscillation must lie in a gap where there are no corresponding bulk normal modes with the same components of wavevector in the plane of the surface . a gap is almost certain to occur for the case of zero wavevector , but at increasing wavevectors the gap may disappear , and the mode ceases to be localized near the surface .    dimension two or three also opens new possibilities less directly related to one - dimensional models , such as surface normal modes with displacements in the plane of the surface . many branches of surface normal modes have been seen experimentally by scattering experiments . unfortunately we have not been able to locate in the literature any observation of the simple mode illustrated in fig . this is perhaps because polar surfaces are relatively unstable and hard to create and work with . another known result is that a surface mode appears above the bulk frequency spectrum for a monatomic chain , provided the atom on the surface is lighter than the rest by at least a factor of two . this can be proven by a reinterpretation of the previous construction . for mode @xmath50 in fig . [ modes ] , let the two atoms connected by the unstretched spring be reinterpreted as a single atom of mass @xmath51 . then the model has new interior atoms all with mass @xmath9 , but a surface impurity atom with mass @xmath52 . the surface mode @xmath50 still solves newton s laws with @xmath53 and @xmath54 . in terms of the new variables @xmath55 and @xmath9 the reduced mass @xmath7 is @xmath56 . the frequency @xmath57 lies above the top of the bulk band ( @xmath18 ) if @xmath58 , and merges into the bulk band for @xmath59 . this result seems also to have been first discovered by wallis @xcite . a `` standard '' proof of this result is in the book by desjonqures and spanjaard @xcite . the gap mode * e * of fig . [ modes ] generates a corresponding mode of a defective bulk crystal , shown in fig . [ stacking ] . this mode decays exponentially in both directions away from the center of symmetry . this center lies in the middle of a `` stacking fault '' where two light - mass atoms have been put adjacent to each other . it is a one - dimensional version of a planar defect which occurs in real three - dimensional crystals . the quantum - mechanical force between two light - mass atoms differs from the force which binds the atoms of unlike mass . therefore , we must expect that the separation @xmath60 of the light - mass atoms will differ from the equilibrium separation @xmath61 of unlike atoms , and that the force constant @xmath62 between these atoms will differ from the constant @xmath0 occuring elsewhere . notice that for the special displacement pattern of fig . [ stacking ] , there is no force between the adjacent light atoms , so the values of @xmath60 and @xmath62 are irrelevant ; the squared frequency of the normal mode is exactly the same as the surface mode * e * of fig . [ modes ] , and is pinned at midgap . the stacking fault is a simple example of a `` topological defect , '' that is , a defect which can not be transformed away by any local change . as far as we know , the mid - gap normal mode of vibration found here for the stacking fault has not previously been discussed in the literature . however , a close analog is the `` topological soliton '' found at mid - gap in the electronic spectrum of the `` su - schrieffer - heeger '' model @xcite for polyacetylene with a topological defect in the pattern of dimerization of carbon - carbon bonds along the chain . suppose an impurity of mass @xmath63 is substituted into a monatomic chain of mass @xmath9 with no change in force constants . define the fractional mass deficit to be @xmath64 . it is known that this system supports a localized mode whose frequency `` splits off '' above the frequency @xmath65 of the uppermost bulk mode . specifically , the mode has squared frequency @xmath66 and is localized around the impurity with localization length @xmath67 . the earliest presentation of this mode known to us is by montroll and potts @xcite . the topic of localized modes in solids had been given a systematic formulation in three earlier papers by lifshits , available only in russian @xcite . a textbook derivation is given by mihly and martin @xcite , and a nice qualitative discussion is given by harrison @xcite . these results follow rigorously by reinterpretation of fig . [ stacking ] . simply regard each pair of co - moving atoms as a single atom whose mass is the sum of the two shown in the figure . thus @xmath9 is @xmath68 , @xmath55 is @xmath69 , and the new lattice constant @xmath61 is twice the previous distance @xmath61 . when the impurity mass is heavier than the host mass , there is no longer a split - off bound state , but instead a `` resonance '' within the bulk band .    in three - dimensional crystals the occurrence of a vibrational bound state requires a minimum mass deficit @xmath70 which is model - dependent , whereas our 1-d example has a bound state for arbitrarily small mass deficit . this is a classical discrete - system analog of the continuum quantum - mechanical theorem that an attractive well always has a bound state in a 1-d one - electron problem ( and also in 2-d ) but requires a critical well - depth in 3-d @xcite . for the impurity on the surface , however , we saw that even in 1d there is a critical mass deficit of 1/2 . the quantum analog is that if the well is at the edge of a 1-d half space ( the other half of space is impenetrable because of an infinite potential ) , then there is a critical well - depth , equal to the well - depth at which the second bound state appears for the symmetric well in the full 1-d space . two simple surface phonons and two simple bound defect modes in one - dimensional lattices have been quantitatively explained by pictorial construction and elementary physics of the two - body problem . this is certainly not a complete catalog of interesting localized modes , but we think that these modes can serve as useful pedagogical models for phenomena in several branches in physics .

the diatomic linear chain of masses coupled by harmonic springs is a textboook model for vibrational normal modes ( phonons ) in crystals .
 in addition to propagating acoustic and optic branches , this model is known to support a `` gap mode '' localized at the surface , provided the atom at the surface has light rather than heavy mass .
 an elementary argument is given which explains this mode and provides values for the frequency and localization length . by reinterpreting this mode in different ways ,
 we obtain the frequency and localization lengths for three other interesting modes : ( 1 ) the surface vibrational mode of a light mass impurity at the surface of a monatomic chain ; ( 2 ) the localized vibrational mode of a stacking fault in a diatomic chain ; and ( 3 ) the localized vibrational mode of a light mass impurity in a monatomic chain .


* *  * * quantum teleportation has found important applications for realization of various quantum technologies @xcite . teleportation of quantum states has been demonstrated between light beams @xcite , trapped atoms @xcite , superconducting qubits @xcite , defect spins in solids @xcite , and from light beams to atoms @xcite or solid state spin qubits @xcite . it is of both fundamental interest and practical importance to push quantum teleportation towards more macroscopic objects . * *  * * observing quantum phenomenon in macroscopic objects is a big challenge as their strong coupling to the environment causes fast decoherence which quickly pushes them to the classical world . for example , quantum coherence is hard to survive in mechanical vibration of macroscopic solids , which involves collective motion of a large number of strongly interacting atoms . despite this challenge , achieving quantum control for the optomechanical systems becomes a recent focus of interest with remarkable progress * * @xcite**. this is driven in part by the fundamental interest and in part by the potential applications of these systems for quantum signal transduction * * @xcite * * , sensing * * @xcite * * , and quantum information processing * * @xcite**. there are typically two routes to achieve quantum control for the optomechanical systems : one needs to either identify some isolated degrees of freedom in mechanical vibrations and cool them to very low temperature to minimize their environmental coupling * * @xcite * * , or use the ultrafast laser technology to fast process and detect quantum coherence in such systems * * @xcite**. a remarkable example for the latter approach is provided by the optomechanical control in macroscopic diamond samples * * @xcite * * , where the motions of two separated diamonds have been cast into a quantum entangled state * * @xcite**.    in this paper , we report an experimental demonstration of quantum teleportation from light beams to the vibrational states of a macroscopic diamond sample of @xmath2 mm@xmath3 in size under ambient conditions . the vibration states are carried by two optical phonon modes , representing collective oscillation of over @xmath4 carbon atoms . to facilitate convenient qubit operations , we use the dual - rail representation of qubits instead of the single - rail encoding used in previous experiments * * @xcite * * and generate entanglement between the paths of a photon and different oscillation patterns of the diamond represented by two phononic modes . using quantum state tomography , we demonstrate entanglement fidelity of @xmath5 with the raw data and of @xmath6 after the background noise subtraction . using this entanglement , we prepare arbitrary polarization states for the photon and teleport these polarization states to the phonon modes with the bell measurements on the polarization and the path qubits carried by the same photon . the teleportation is verified by quantum process tomography , and we achieve a high average teleportation fidelity , about @xmath7 ( or @xmath8 ) after ( or before ) subtraction of the background noise . to verify the phonon s state before its fast decay , our implementation of teleportation adopted the technique of reversed time ordering introduced in ref . * * @xcite * * where the phonon s state is read out before the teleportation is completed . similar to the pioneering teleportation experiment of photons @xcite , our implementation of teleportation is conditional as the bell measurements are not deterministic and require postselecting of successful measurement outcomes . and generates a stokes photon in the forward direction and an excitation in the optical phonon mode of the diamond ( denoted by the state @xmath9 ) . the optical phonon mode corresponds to relative oscillation of the atoms in each unit cell of the diamond lattice , as illustrated by the figure on the right side . a read beam after a controllable delay converts the phonon excitation to an anti - stokes photon which can be used for state readout . the corresponding wavelengths and frequencies are shown in the figure . the state @xmath10 denotes the electron conduction band which is far detuned from the optical excitation . * b * , a scheme for generation of entanglement between a phonon in the diamond and a propagating photon . the phonon state is represented by a superposition of different oscillation modes of the diamond , while the photon state is represented by its spatial modes . * c * , readout of the phonon state with the read beams by coherently converting the phonon modes into the corresponding anti - stoke photon modes . * d * , a teleportation scheme using the photon - phonon entanglement . an input state is prepared by the message sender , alice , on the photon s polarization degree of freedom . the photon thus carries two qubits , one by its polarization and one by its spatial modes . alice performs bell measurements on these two qubits . conditional on certain measurement outcomes , the phonon state is projected to the same state input on alice s side , which is read out and verified by bob , the message receiver . , width=321,height=264 ]      we illustrate our entanglement generation and quantum teleportation scheme in fig . 1 , using a type iia single - crystal synthetic diamond sample cut along the @xmath11 face from the element six company . due to the strong interaction of atoms in the diamond , the optical phonon mode , which represents relative oscillation of the two sublattices in the stiff diamond lattice ( see fig . 1a ) , has a very high excitation frequency about @xmath12 @xmath13 near the momentum zero point in the brillouin zone . the corresponding energy scale for this excitation is significantly higher than the room temperature thermal energy ( about @xmath14 @xmath13 ) , and thus the optical phonon mode naturally stays at the vacuum state under ambient conditions , which simplifies its quantum control * * @xcite**. the coherence life time of the optical phonon mode is about @xmath15 ps at room temperature , which is short but accessible with the ultrafast laser technology for which the operational speed can be up to about @xmath16 thz * * @xcite**.    we excite the optical phonon modes through ultrafast laser pulses of duration around @xmath17 fs from the ti - sapphire laser , with the carrier wavelength at @xmath18 nm . the diamond has a large bandgap of @xmath19 ev , so the laser pulses are far detuned from the conduction band with a large gap about @xmath20 thz . each laser pulse generates , with a small probability @xmath21 , an excitation in the optical phonon mode and a stokes photon of wavelength @xmath22 nm in the forward direction ( see fig . 1a ) . the relevant output state has the form    @xmath23 |\text{vac}\rangle , \ ] ]    where @xmath24 and @xmath25 represent , respectively , the creation operators for an optical phonon and a stokes photon , and @xmath26vac@xmath27 denotes the common vacuum state for both the photon and the phonon modes .    to generate entanglement , we split the laser pulse into two coherent paths as shown in fig . 1b , and the pulse in each path generates the corresponding phonon - photon correlated state described by eq . when there is an output photon , in one of the two paths , it is in the following maximally entangled state with the phonon excitation@xmath28here , @xmath29 or @xmath30 represents an excitation in the upper or lower path , and its subscript denotes the nature of the excitation , `` n '' for a phonon and `` t '' for a photon . we drop the vacuum term in eq . ( 1 ) as it is eliminated if we detect a photon emerging from one of the two paths . after entanglement generation , the photon state can be directly measured through single - photon detectors . to read out the phonon state , we apply another ultrafast laser pulse after a controllable delay within the coherence time of the optical phonon mode and convert the phononic state to the same photonic state in the forward anti - stokes mode at the wavelength of @xmath31 nm ( see fig . the state of the anti - stokes photon is then measured through single - photon detectors together with linear optics devices . note that the retrieval laser pulse could have a carrier frequency @xmath32 different from that of the pump laser . for instance , with @xmath32 near the telecom band , our teleportation protocol would naturally realize a quantum frequency transducer that transfers the photon s frequency to a desired band without changing its quantum state . a quantum frequency transducer is widely recognized as an important component for realization of long - distance quantum networks * * @xcite**.    to realize teleportation , we need to prepare another qubit , whose state will be teleported to the phonon modes in the diamond . similar to the teleportation experiments in refs . * * @xcite * * , we use the polarization state of the photon to represent the input qubit , which can be independently prepared into an arbitrary state @xmath33 , where @xmath34 and @xmath35 denote the horizontal and the vertical polarization states and @xmath36 are arbitrary coefficients . the bell measurements on the polarization and the path qubits carried by the same photon can be implemented through linear optics devices together with single - photon detection ( see fig . 1d ) , and the teleported state to the phononic modes is retrieved and detected through its conversion to the anti - stokes photon . same as ref . * * @xcite * * , the short life time of the diamond s vibration modes requires us to retrieve and detect the phonon s state before applying detection on the stokes photon , thus the phonon s state is measured before the teleportation protocol is completed . the reversed time ordering in this demonstration of quantum teleportation makes it unsuitable for application in quantum repeaters which requires a much longer memory time , however , it does not affect application of our teleportation experiment for realization of a quantum frequency transducer or a new source of entangled photons as discussed above . mhz , a carrier wavelength of @xmath18 nm , and a polarization along the @xmath37 direction , are split by a birefringent calcite into two coherent paths with equal amplitudes . after rotation of the pulse polarization to equal superposition of @xmath38 and @xmath39 again with a half wave plate ( hwp1 ) set at @xmath40 , we introduce a time delay of @xmath41 fs to the two polarization components @xmath42 and @xmath43 with a birefringent bbocrystal . we use the lead pulse of @xmath42  polarization as the write beam and the lagged pulse of @xmath43  polarization as the read beam . after semicircle hwps set at @xmath44 and @xmath45 , respectively , at the upper and lower paths , the polarization states of the pump beams are shown in the figure before the diamond sample . the write beam is focused by the lens l1 on the diamond sample and generates a stokes photon in one of the paths and an excitation in the corresponding optical phonon modes of the diamond . the stokes photon , at the wavelength of @xmath22 nm , is transmitted by the dichromatic mirror dm1 after the collection lens l2 , with its two paths recombined by the calcite c2 . to verify entanglement , we do not need hwp3 and the optical elements in the state preparation box . the lens l3 and l4 are used to adjust the distance between the two optical paths so that they can be combined at the calcite c2 . the single - photon detector apd2 , together with rotation of the polarizer p2 , detects the two path ( or polarization ) components of the stokes photon in different bases . to read out the state of the phonon modes , the read pulse converts the phonon to the anti - stokes photon in the corresponding paths , preserving its quantum state . the anti - stokes photon , at a shorter wavelength of @xmath31 nm , is reflected by both of the dichromatic mirrors dm1 and dm2 , with its two paths recombined through the calcite c3 . the single - photon detector apd1 , together with rotation of the half and the quarter wave plates hwp5 and qwp2 , detects the anti - stokes photon ( and thus the phonon ) in any superposition bases . for quantum teleportation , semicircle hwps and the polarizer p1 in the state preparation box transforms the photon - phonon entangled state to the standard form of eq . ( 2 ) and initializes the photon polarization to the state @xmath46 . the waveplates hwp2 and qwp1 then prepare the to - be - teleported photon polarization to any superposition state . the calcite c2 , the hwp3 , the polarizer p2 , and the detector apd2 , together , make a bell measurement on the two qubits carried by the polarization and the path degrees of freedom of the same photon . the photon coincidence counts are registered through a fpga ( field - programmable gate array ) board with a @xmath47 nm coincidence window . , width=642,height=264 ]      our experimental setup is shown in fig . , we verify entanglement generated between the stokes photon and the optical phonon modes in the diamond . for this step , we remove the optical elements in the state preparation box shown in fig . 2 and set the angle of hwp3 to @xmath44 . different from the scheme illustrated in fig . 1 , we insert semicircle hwps set at @xmath44 and @xmath45 , respectively , at the upper and the lower paths of the pump beam , so that both the stokes photon and the anti - stokes photon after the retrieval pulse have orthogonal polarizations along the two output paths , which can be combined together through the calcites c2 and c3 . this facilitates the entanglement measurement through detection in complementary local bases by rotating the polarizers p2 and p3 and the wave plates hwp5 and qwp2 . due to the different incident directions of the pump pulses at the upper and the lower paths , the corresponding phonon modes excited in the diamond have different momenta , so they represent independent modes even if they have partial spatial overlap . the phonon is converted to the anti - stokes photon by the retrieval pulse , so we measure the photon - phonon state by detecting the coincidence counts between stokes and anti - stokes photons in different bases . in fig . 3a , we show the registered coincidence counts as we rotate the angle of the polarizer p2 . the oscillation of the coincidence counts with a visibility of @xmath48 is an indicator of coherence of the underlying state . to verify entanglement of the photon - phonon state , we use quantum state tomography to reconstruct the full density matrix from the measured coincidence counts * * @xcite * * , with the resulting matrix elements shown in fig . 3b . from the reconstructed density matrix @xmath49 , we find its entanglement fidelity , defined as the maximum overlap of @xmath49 with a maximally entangled state , @xmath50 , significantly higher than the criterion of @xmath51 for verification of entanglement * * @xcite**. the error bars are determined by assuming a poissonian distribution for the photon counts and propagated from the raw data to the calculated quantities through exact numerical simulation . the dominant noise in this system comes from the accidental coincidence between the detected stokes and the anti - stokes photons * * @xcite**. to measure the contribution of this accidental coincidence , we introduce an extra time delay of @xmath52 @xmath53 , the repetition period of our pump pulses , to one of the detectors when we record the coincidence . when we subtract the background noise due to this accidental coincidence , the resulting matrix elements reconstructed from the quantum state tomography are shown in fig . we find the entanglement fidelity is improved to @xmath54 after subtraction of the accidental coincidence .    . the error bars denote the standard deviation . * b * , real and imaginary parts of the density matrix elements for the phonon - photon entangled state reconstructed through the quantum state tomography . the hollow caps correspond to the values of matrix elements for a perfect maximally entangled state . * c * , same as fig . 3b , but we subtract the background noise due to the accidental coincidences of the photon detectors . the coincidence count rate for stokes and anti - stokes photons is @xmath55 per second for measurements in the @xmath56 and @xmath57 bases . , width=321,height=264 ]    to perform quantum teleportation using the photon - phonon entanglement , we first transform the effective photon - phonon entangled state to the standard form of eq . ( 2 ) by the semicircle hwps in the state preparation box of fig . 2 . the polarizer p1 and the waveplates hwp2 and qwp1 then prepare the to - be - teleported photon polarization to arbitrary superposition states @xmath58 . we perform bell measurement through the calcite c2 , the hwp3 , the polarizer p2 , and the detector apd2 . for instance , with the hwp3 set at @xmath44 and the polarizer p2 set along the direction @xmath59 , a photon count in the detector apd2 corresponds to a projection to the bell state @xmath60 for the polarization and the path qubits of the photon before the measurement box . by rotating the angles of hwp3 and p2 , we can also perform projection to any other bell states .    the experimental result for teleportation is shown in fig . the teleportation fidelity is defined as @xmath61 , where @xmath62 is the input state at alice s side and @xmath63 denotes the output density matrix at bob s side reconstructed through quantum state tomography measurements . in fig . 4a , we show the teleportation fidelity under six complementary bases states with @xmath64 @xmath65 in cases with and without subtraction of the background noise . the average fidelity over these six bases states is @xmath66 ( or @xmath67 ) with ( or without ) background noise subtraction . this average fidelity is significantly higher than @xmath1 , the boundary value for the fidelity that separates quantum teleportation from classical operations . for more complete characterization , we also perform quantum process tomography ( qpt ) for the teleportation operation . in the ideal case , teleportation should be characterized by an identity transformation , meaning that alice s input state is teleported perfectly to bob s side . the experimentally reconstructed process matrix elements are shown in fig . 4b ( see methods for explanation of qpt ) . the process fidelity is given by @xmath68 , which corresponds to a teleportation fidelity @xmath69 averaged over all possible input states with equal weight in the qubit space . corresponds to the classical - quantum boundary for teleportation . * b * , real and imaginary parts of the process matrix elements for quantum teleportation reconstructed through the quantum process tomography ( see methods ) . the hollow caps correspond to the values of process matrix elements for a perfect teleportation operation . , width=321,height=264 ] teleportation of quantum states from a photon to the vibration modes of a millimeter - sized diamond under ambient conditions generates a quantum link between the microscopic particle and the macroscopic world around us usually under the law of classical physics . in our experiment , the ultrafast laser technology provides the key tool for fast processing and detection of quantum states within its short life time in macroscopic objects consisting of many strongly interacting atoms that are coupled to the environment . combined with the tunability of the wavelength for the retrieval laser pulse * * @xcite * * , the technique introduced in our experiment would be useful for realization of a new source of entangled photons based on the diamond optomechanical coupling with the dual - rail encoding . such a source could generate entangled photons at wavelengths inconvenient to produce by other methods . for instance , we may generate entanglement between ultraviolet and infrared photons , with the infrared photon good for quantum communication and the ultraviolet photon convenient to be interfaced with other qubits , such as the ion matter qubits . such a photon source is hard to generate by the conventional spontaneous parametric down conversion method . in future , the tools based on the ultrafast pump and probe could be combined with the powerful laser cooling or low - temperature technology , to provide more efficient ways for quantum control of the optomechanical systems , with important applications for realization of transduction of quantum signals * * @xcite * * , processing of quantum information or single - photon signals * * @xcite * * , and sensing of small mechanical vibrations * * @xcite**. quantum process tomography ( qpt ) @xcite is defined by a completely positive map @xmath70 that transfers an arbitrary input state @xmath71 to the output @xmath72 . it can be characterized by a unique process matrix @xmath73 through the map @xmath74 by choosing a fixed set of basis operator @xmath75 . in our experiment , we set the basis operators @xmath75 to be the identity operator @xmath76 and the three pauli matrices @xmath77 , @xmath78 , @xmath79 . this corresponds to a choice of six complementary input states @xmath80 , @xmath81 , @xmath82 , @xmath83 through the maximally likelihood estimation @xcite . the process fidelity is determined by @xmath84 , where @xmath85 is the identity process matrix corresponding to the perfect case . the process fidelity @xmath86 determines the average teleportation fidelity @xmath87 by the formula @xmath88 @xcite , where @xmath89 is defined as the fidelity averaged over all possible states of the input qubit with equal weight . * acknowledgements * this work was supported by the ministry of education of china through its grant to tsinghua university . lmd acknowledges in addition support from the iarpa program , the arl , and the afosr muri program .

with the recent development of optomechanics , the vibration in solids , involving collective motion of trillions of atoms , gradually enters into the realm of quantum control . built on the recent remarkable progress in optical control of motional states of diamonds , here
 we report an experimental demonstration of quantum teleportation from light beams to vibrational states of a macroscopic diamond under ambient conditions . through quantum process tomography ,
 we demonstrate average teleportation fidelity @xmath0 , clearly exceeding the classical limit of @xmath1 .
 the experiment pushes the target of quantum teleportation to the biggest object so far , with interesting implications for optomechanical quantum control and quantum information science .