<commit_before># Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utilities for API compatibility between TensorFlow release versions.

See [Version
Compatibility](https://tensorflow.org/guide/version_compat#backward_forward)
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import datetime
import os

from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util import tf_contextlib
from tensorflow.python.util.tf_export import tf_export

# This value changes every day with an automatic CL. It can be modified in code
# via `forward_compatibility_horizon()` or with the environment variable
# TF_FORWARD_COMPATIBILITY_DELTA_DAYS, which is added to the compatibility date.
_FORWARD_COMPATIBILITY_HORIZON = datetime.date(2020, 6, 20)
_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME = "TF_FORWARD_COMPATIBILITY_DELTA_DAYS"
_FORWARD_COMPATIBILITY_DATE_NUMBER = None

def _date_to_date_number(year, month, day):
  return (year << 9) | (month << 5) | day

def _update_forward_compatibility_date_number(date_to_override=None):
  """Update the base date to compare in forward_compatible function."""

  global _FORWARD_COMPATIBILITY_DATE_NUMBER

  if date_to_override:
    date = date_to_override
  else:
    date = _FORWARD_COMPATIBILITY_HORIZON
    delta_days = os.getenv(_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME)
    if delta_days:
      date += datetime.timedelta(days=int(delta_days))

  if date < _FORWARD_COMPATIBILITY_HORIZON:
    logging.warning("Trying to set the forward compatibility date to the past"
                    " date %s. This will be ignored by TensorFlow." % (date))
    return
  _FORWARD_COMPATIBILITY_DATE_NUMBER = _date_to_date_number(
      date.year, date.month, date.day)

_update_forward_compatibility_date_number()

@tf_export("compat.forward_compatible")
def forward_compatible(year, month, day):
  """Return true if the forward compatibility window has expired.

  See [Version
  compatibility](https://tensorflow.org/guide/version_compat#backward_forward).

  Forward-compatibility refers to scenarios where the producer of a TensorFlow
  model (a GraphDef or SavedModel) is compiled against a version of the
  TensorFlow library newer than what the consumer was compiled against. The
  "producer" is typically a Python program that constructs and trains a model
  while the "consumer" is typically another program that loads and serves the
  model.

  TensorFlow has been supporting a 3 week forward-compatibility window for
  programs compiled from source at HEAD.

  For example, consider the case where a new operation `MyNewAwesomeAdd` is
  created with the intent of replacing the implementation of an existing Python
  wrapper - `tf.add`.  The Python wrapper implementation should change from
  something like:

  ```python
  def add(inputs, name=None):
    return gen_math_ops.add(inputs, name)
  ```

  to:

  ```python
  from tensorflow.python.compat import compat

  def add(inputs, name=None):
    if compat.forward_compatible(year, month, day):
      # Can use the awesome new implementation.
      return gen_math_ops.my_new_awesome_add(inputs, name)
    # To maintain forward compatibility, use the old implementation.
    return gen_math_ops.add(inputs, name)
  ```

  Where `year`, `month`, and `day` specify the date beyond which binaries
  that consume a model are expected to have been updated to include the
  new operations. This date is typically at least 3 weeks beyond the date
  the code that adds the new operation is committed.

  Args:
    year:  A year (e.g., 2018). Must be an `int`.
    month: A month (1 <= month <= 12) in year. Must be an `int`.
    day:   A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an
      `int`.

  Returns:
    True if the caller can expect that serialized TensorFlow graphs produced
    can be consumed by programs that are compiled with the TensorFlow library
    source code after (year, month, day).
  """
  return _FORWARD_COMPATIBILITY_DATE_NUMBER > _date_to_date_number(
      year, month, day)

@tf_export("compat.forward_compatibility_horizon")
@tf_contextlib.contextmanager
def forward_compatibility_horizon(year, month, day):
  """Context manager for testing forward compatibility of generated graphs.

  See [Version
  compatibility](https://tensorflow.org/guide/version_compat#backward_forward).

  To ensure forward compatibility of generated graphs (see `forward_compatible`)
  with older binaries, new features can be gated with:

  ```python
  if compat.forward_compatible(year=2018, month=08, date=01):
    generate_graph_with_new_features()
  else:
    generate_graph_so_older_binaries_can_consume_it()
  ```

  However, when adding new features, one may want to unittest it before
  the forward compatibility window expires. This context manager enables
  such tests. For example:

  ```python
  from tensorflow.python.compat import compat

  def testMyNewFeature(self):
    with compat.forward_compatibility_horizon(2018, 08, 02):
       # Test that generate_graph_with_new_features() has an effect
  ```

  Args:
    year:  A year (e.g., 2018). Must be an `int`.
    month: A month (1 <= month <= 12) in year. Must be an `int`.
    day:   A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an
      `int`.

  Yields:
    Nothing.
  """
  try:
    _update_forward_compatibility_date_number(datetime.date(year, month, day))
    yield
  finally:
    _update_forward_compatibility_date_number()
<commit_msg>compat: Update forward compatibility horizon to 2020-06-21<commit_after># Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utilities for API compatibility between TensorFlow release versions.

See [Version
Compatibility](https://tensorflow.org/guide/version_compat#backward_forward)
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import datetime
import os

from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util import tf_contextlib
from tensorflow.python.util.tf_export import tf_export

# This value changes every day with an automatic CL. It can be modified in code
# via `forward_compatibility_horizon()` or with the environment variable
# TF_FORWARD_COMPATIBILITY_DELTA_DAYS, which is added to the compatibility date.
_FORWARD_COMPATIBILITY_HORIZON = datetime.date(2020, 6, 21)
_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME = "TF_FORWARD_COMPATIBILITY_DELTA_DAYS"
_FORWARD_COMPATIBILITY_DATE_NUMBER = None

def _date_to_date_number(year, month, day):
  return (year << 9) | (month << 5) | day

def _update_forward_compatibility_date_number(date_to_override=None):
  """Update the base date to compare in forward_compatible function."""

  global _FORWARD_COMPATIBILITY_DATE_NUMBER

  if date_to_override:
    date = date_to_override
  else:
    date = _FORWARD_COMPATIBILITY_HORIZON
    delta_days = os.getenv(_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME)
    if delta_days:
      date += datetime.timedelta(days=int(delta_days))

  if date < _FORWARD_COMPATIBILITY_HORIZON:
    logging.warning("Trying to set the forward compatibility date to the past"
                    " date %s. This will be ignored by TensorFlow." % (date))
    return
  _FORWARD_COMPATIBILITY_DATE_NUMBER = _date_to_date_number(
      date.year, date.month, date.day)

_update_forward_compatibility_date_number()

@tf_export("compat.forward_compatible")
def forward_compatible(year, month, day):
  """Return true if the forward compatibility window has expired.

  See [Version
  compatibility](https://tensorflow.org/guide/version_compat#backward_forward).

  Forward-compatibility refers to scenarios where the producer of a TensorFlow
  model (a GraphDef or SavedModel) is compiled against a version of the
  TensorFlow library newer than what the consumer was compiled against. The
  "producer" is typically a Python program that constructs and trains a model
  while the "consumer" is typically another program that loads and serves the
  model.

  TensorFlow has been supporting a 3 week forward-compatibility window for
  programs compiled from source at HEAD.

  For example, consider the case where a new operation `MyNewAwesomeAdd` is
  created with the intent of replacing the implementation of an existing Python
  wrapper - `tf.add`.  The Python wrapper implementation should change from
  something like:

  ```python
  def add(inputs, name=None):
    return gen_math_ops.add(inputs, name)
  ```

  to:

  ```python
  from tensorflow.python.compat import compat

  def add(inputs, name=None):
    if compat.forward_compatible(year, month, day):
      # Can use the awesome new implementation.
      return gen_math_ops.my_new_awesome_add(inputs, name)
    # To maintain forward compatibility, use the old implementation.
    return gen_math_ops.add(inputs, name)
  ```

  Where `year`, `month`, and `day` specify the date beyond which binaries
  that consume a model are expected to have been updated to include the
  new operations. This date is typically at least 3 weeks beyond the date
  the code that adds the new operation is committed.

  Args:
    year:  A year (e.g., 2018). Must be an `int`.
    month: A month (1 <= month <= 12) in year. Must be an `int`.
    day:   A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an
      `int`.

  Returns:
    True if the caller can expect that serialized TensorFlow graphs produced
    can be consumed by programs that are compiled with the TensorFlow library
    source code after (year, month, day).
  """
  return _FORWARD_COMPATIBILITY_DATE_NUMBER > _date_to_date_number(
      year, month, day)

@tf_export("compat.forward_compatibility_horizon")
@tf_contextlib.contextmanager
def forward_compatibility_horizon(year, month, day):
  """Context manager for testing forward compatibility of generated graphs.

  See [Version
  compatibility](https://tensorflow.org/guide/version_compat#backward_forward).

  To ensure forward compatibility of generated graphs (see `forward_compatible`)
  with older binaries, new features can be gated with:

  ```python
  if compat.forward_compatible(year=2018, month=08, date=01):
    generate_graph_with_new_features()
  else:
    generate_graph_so_older_binaries_can_consume_it()
  ```

  However, when adding new features, one may want to unittest it before
  the forward compatibility window expires. This context manager enables
  such tests. For example:

  ```python
  from tensorflow.python.compat import compat

  def testMyNewFeature(self):
    with compat.forward_compatibility_horizon(2018, 08, 02):
       # Test that generate_graph_with_new_features() has an effect
  ```

  Args:
    year:  A year (e.g., 2018). Must be an `int`.
    month: A month (1 <= month <= 12) in year. Must be an `int`.
    day:   A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an
      `int`.

  Yields:
    Nothing.
  """
  try:
    _update_forward_compatibility_date_number(datetime.date(year, month, day))
    yield
  finally:
    _update_forward_compatibility_date_number()
<|endoftext|>


<commit_before>#!/mnt/usb/wk/jpt/py/bin/python

#TODO logging lib

import time
from serial import Serial
from sys import argv, exit

from lib.runner import Runner
from animations.matrix_animation import Led_clock_pointer, Led_clock_flasher
from lib import lcdControl
from lib.sev_seg_dp import Sev_seg_dp
from lib.motion_sensor import Motion_sensor
import lib.get_data as gdt
from animations.seven_segment_clock import Seven_segment_clock
from animations.rainfall import Rainfall
from animations.stat_show import single_slide, get_slides
from lib.relay import Relay
from lib.httpser import HttpSer
from lib.buffdev import Dev
from lib.current_sensor import Current_sensor
from lib.photo_resistor import Photo_resistor
from lib.notification_led import Notification_led

# SETTINGS
motionLogFile = "/mnt/usb/logs/motionLog.log"
device = "/dev/ttyUSB0"
baudrate = 9600
updateintv = 0.01
debug = "debug" in argv

print("update intv: {}".format(updateintv))

if updateintv != 0:
    print("or {} fps max".format(1 / updateintv))

# Set up usb
usb = Serial(device, baudrate, timeout=2)
usb = Dev(usb)
if debug:
    from test.usb_relay import Usb_relay
    usb = Usb_relay(usb)

time.sleep(3)
runner = Runner()
# init virtual devices
lcd = lcdControl.Lcd(usb)
sevdp = Sev_seg_dp(usb)
mtxdp = Sev_seg_dp(usb, dev_id=1)

runner.add_module(usb)

# led_clock_pointer_sec = Led_clock_pointer(mtxdp, ring=1)
# led_clock_pointer_min = Led_clock_pointer(mtxdp, pointertype="min", ring=0)
# led_clock_flasher = Led_clock_flasher(mtxdp)
runner.add_module(Seven_segment_clock(sevdp))
# seven_segment_clock = Seven_segment_clock(sevdp)

runner.add_module(Rainfall(mtxdp, max_height=6, max_speed=20, min_speed=10))
# rainfall = Rainfall(mtxdp, max_height=6, max_speed=20, min_speed=10)
# lcd_show_tem_net = single_slide("temp", get_temp, "ping", get_netstat, lcd)

lcd_stat_show = get_slides(lcd,
                           (("Temp", gdt.get_temp),
                            ("Up", gdt.get_uptime),
                            ("Load", gdt.get_load),
                            ("Mem", gdt.get_mem_usage),
                            ("Ping", gdt.get_netstat),
                            ("Lost", gdt.get_package_lost)),
                           update_every=3)
runner.add_module(lcd_stat_show)

# lazer notification
notification_led = Notification_led(usb)

# motion sensor
motion_sensor = Motion_sensor(usb.dev,
                              motionLogFile,
                              trigger_handlers=[notification_led.set_led])
# relay
relay = Relay(usb.dev)

current_sensor = Current_sensor(usb.dev)

photo_resistor = Photo_resistor(usb.dev)

def reset_mtx():
    usb.dev.write(bytes((87, ord(';'))))
    return "OK"

#api server
SERVE_MAP = {"/o": relay.on,
             "/f": relay.off,
             "/rs": relay.get_state,
             "/lo": notification_led.on,
             "/lf": notification_led.off,
             "/d": usb.get_json,
             "/c": current_sensor.get_json,
             "/p": photo_resistor.get_json,
             "/me": mtxdp.enable,
             "/md": mtxdp.disable,
             "/le": lcd.enable,
             "/ld": lcd.disable,
             "/reset": reset_mtx}

runner.add_module(HttpSer(SERVE_MAP, addr="0.0.0.0"))

mtxdp.shutdown(0)
sevdp.setintensity(8)
mtxdp.setintensity(0)

sevdp.clear()
mtxdp.clear()
lcd.clear()

def main():
    try:
        while True:
            runner.update()
            time.sleep(updateintv)
    except KeyboardInterrupt:
        apiser.close()
        print("\nport closed")
        exit(0)

if __name__ == "__main__":
    main()
<commit_msg>fixed apiser not defined err when stopping<commit_after>#!/mnt/usb/wk/jpt/py/bin/python

#TODO logging lib

import time
from serial import Serial
from sys import argv, exit

from lib.runner import Runner
from animations.matrix_animation import Led_clock_pointer, Led_clock_flasher
from lib import lcdControl
from lib.sev_seg_dp import Sev_seg_dp
from lib.motion_sensor import Motion_sensor
import lib.get_data as gdt
from animations.seven_segment_clock import Seven_segment_clock
from animations.rainfall import Rainfall
from animations.stat_show import single_slide, get_slides
from lib.relay import Relay
from lib.httpser import HttpSer
from lib.buffdev import Dev
from lib.current_sensor import Current_sensor
from lib.photo_resistor import Photo_resistor
from lib.notification_led import Notification_led

# SETTINGS
motionLogFile = "/mnt/usb/logs/motionLog.log"
device = "/dev/ttyUSB0"
baudrate = 9600
updateintv = 0.01
debug = "debug" in argv

print("update intv: {}".format(updateintv))

if updateintv != 0:
    print("or {} fps max".format(1 / updateintv))

# Set up usb
usb = Serial(device, baudrate, timeout=2)
usb = Dev(usb)
if debug:
    from test.usb_relay import Usb_relay
    usb = Usb_relay(usb)

time.sleep(3)
runner = Runner()
# init virtual devices
lcd = lcdControl.Lcd(usb)
sevdp = Sev_seg_dp(usb)
mtxdp = Sev_seg_dp(usb, dev_id=1)

runner.add_module(usb)

# led_clock_pointer_sec = Led_clock_pointer(mtxdp, ring=1)
# led_clock_pointer_min = Led_clock_pointer(mtxdp, pointertype="min", ring=0)
# led_clock_flasher = Led_clock_flasher(mtxdp)
runner.add_module(Seven_segment_clock(sevdp))
# seven_segment_clock = Seven_segment_clock(sevdp)

runner.add_module(Rainfall(mtxdp, max_height=6, max_speed=20, min_speed=10))
# rainfall = Rainfall(mtxdp, max_height=6, max_speed=20, min_speed=10)
# lcd_show_tem_net = single_slide("temp", get_temp, "ping", get_netstat, lcd)

lcd_stat_show = get_slides(lcd,
                           (("Temp", gdt.get_temp),
                            ("Up", gdt.get_uptime),
                            ("Load", gdt.get_load),
                            ("Mem", gdt.get_mem_usage),
                            ("Ping", gdt.get_netstat),
                            ("Lost", gdt.get_package_lost)),
                           update_every=3)
runner.add_module(lcd_stat_show)

# lazer notification
notification_led = Notification_led(usb)

# motion sensor
motion_sensor = Motion_sensor(usb.dev,
                              motionLogFile,
                              trigger_handlers=[notification_led.set_led])
runner.add_module(motion_sensor)
# relay
relay = Relay(usb.dev)

current_sensor = Current_sensor(usb.dev)

photo_resistor = Photo_resistor(usb.dev)

def reset_mtx():
    usb.dev.write(bytes((87, ord(';'))))
    return "OK"

#api server
SERVE_MAP = {"/o": relay.on,
             "/f": relay.off,
             "/rs": relay.get_state,
             "/lo": notification_led.on,
             "/lf": notification_led.off,
             "/d": usb.get_json,
             "/c": current_sensor.get_json,
             "/p": photo_resistor.get_json,
             "/me": mtxdp.enable,
             "/md": mtxdp.disable,
             "/le": lcd.enable,
             "/ld": lcd.disable,
             "/reset": reset_mtx}

apiser = HttpSer(SERVE_MAP, addr="0.0.0.0")
runner.add_module(apiser)

mtxdp.shutdown(0)
sevdp.setintensity(8)
mtxdp.setintensity(0)

sevdp.clear()
mtxdp.clear()
lcd.clear()

def main():
    try:
        while True:
            runner.update()
            time.sleep(updateintv)
    except KeyboardInterrupt:
        apiser.close()
        print("\nport closed")
        exit(0)

if __name__ == "__main__":
    main()
<|endoftext|>


<commit_before>from abc import ABCMeta

class AbstractLamp(metaclass=ABCMeta):
    def __init__(self, controller):
        self._controller = controller

    def on():
        pass

    def off():
        pass

class DimmerLamp(AbstractLamp):
    def __init__(self, controller):
        self._percent = 0

        return super().__init__(controller)

    @property
    def percent(self):
        return self._percent

    @percent.setter
    def percent(self, x):
        if 0 < x < 100:
            self._percent = x

class RGBLamp(AbstractLamp):
    def __init__(self, controller):
        self._r = 0
        self._g = 0
        self._b = 0
        return super().__init__(controller)

    @property
    def r(self):
        return self._r

    @property
    def g(self):
        return self._g

    @property
    def b(self):
        return self._b

    @r.setter
    def r(self, x):
        if 0 < x < 255:
            self._r = x

    @g.setter
    def g(self, x):
        if 0 < x < 255:
            self._g = x

    @b.setter
    def b(self, x):
        if 0 < x < 255:
            self._b = x

class Lamp(AbstractLamp):
    def __init__(self, controller):
        return super().__init__(controller)

#lol<commit_msg>Changed RGB values to float between 0 and 1<commit_after>from abc import ABCMeta

class AbstractLamp(metaclass=ABCMeta):
    def __init__(self, controller):
        self._controller = controller

    def on():
        pass

    def off():
        pass

class DimmerLamp(AbstractLamp):
    def __init__(self, controller):
        self._percent = 0

        return super().__init__(controller)

    @property
    def percent(self):
        return self._percent

    @percent.setter
    def percent(self, x):
        if 0 < x < 100:
            self._percent = x

class RGBLamp(AbstractLamp):
    def __init__(self, controller):
        self._r = 0.0
        self._g = 0.0
        self._b = 0.0
        return super().__init__(controller)

    @property
    def r(self):
        return self._r

    @property
    def g(self):
        return self._g

    @property
    def b(self):
        return self._b

    @r.setter
    def r(self, x):
        if 0 < x < 1:
            self._r = x

    @g.setter
    def g(self, x):
        if 0 < x < 1:
            self._g = x

    @b.setter
    def b(self, x):
        if 0 < x < 1:
            self._b = x

class Lamp(AbstractLamp):
    def __init__(self, controller):
        return super().__init__(controller)

#lol<|endoftext|>


<commit_before># Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utilities for API compatibility between TensorFlow release versions.

See [Version
Compatibility](https://tensorflow.org/guide/version_compat#backward_forward)
"""

import datetime
import os

from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util import tf_contextlib
from tensorflow.python.util.tf_export import tf_export

# This value changes every day with an automatic CL. It can be modified in code
# via `forward_compatibility_horizon()` or with the environment variable
# TF_FORWARD_COMPATIBILITY_DELTA_DAYS, which is added to the compatibility date.
_FORWARD_COMPATIBILITY_HORIZON = datetime.date(2021, 12, 13)
_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME = "TF_FORWARD_COMPATIBILITY_DELTA_DAYS"
_FORWARD_COMPATIBILITY_DATE_NUMBER = None

def _date_to_date_number(year, month, day):
  return (year << 9) | (month << 5) | day

def _update_forward_compatibility_date_number(date_to_override=None):
  """Update the base date to compare in forward_compatible function."""

  global _FORWARD_COMPATIBILITY_DATE_NUMBER

  if date_to_override:
    date = date_to_override
  else:
    date = _FORWARD_COMPATIBILITY_HORIZON
    delta_days = os.getenv(_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME)
    if delta_days:
      date += datetime.timedelta(days=int(delta_days))

  if date < _FORWARD_COMPATIBILITY_HORIZON:
    logging.warning("Trying to set the forward compatibility date to the past"
                    " date %s. This will be ignored by TensorFlow." % (date))
    return
  _FORWARD_COMPATIBILITY_DATE_NUMBER = _date_to_date_number(
      date.year, date.month, date.day)

_update_forward_compatibility_date_number()

@tf_export("compat.forward_compatible")
def forward_compatible(year, month, day):
  """Return true if the forward compatibility window has expired.

  See [Version
  compatibility](https://tensorflow.org/guide/version_compat#backward_forward).

  Forward-compatibility refers to scenarios where the producer of a TensorFlow
  model (a GraphDef or SavedModel) is compiled against a version of the
  TensorFlow library newer than what the consumer was compiled against. The
  "producer" is typically a Python program that constructs and trains a model
  while the "consumer" is typically another program that loads and serves the
  model.

  TensorFlow has been supporting a 3 week forward-compatibility window for
  programs compiled from source at HEAD.

  For example, consider the case where a new operation `MyNewAwesomeAdd` is
  created with the intent of replacing the implementation of an existing Python
  wrapper - `tf.add`.  The Python wrapper implementation should change from
  something like:

  ```python
  def add(inputs, name=None):
    return gen_math_ops.add(inputs, name)
  ```

  to:

  ```python
  from tensorflow.python.compat import compat

  def add(inputs, name=None):
    if compat.forward_compatible(year, month, day):
      # Can use the awesome new implementation.
      return gen_math_ops.my_new_awesome_add(inputs, name)
    # To maintain forward compatibility, use the old implementation.
    return gen_math_ops.add(inputs, name)
  ```

  Where `year`, `month`, and `day` specify the date beyond which binaries
  that consume a model are expected to have been updated to include the
  new operations. This date is typically at least 3 weeks beyond the date
  the code that adds the new operation is committed.

  Args:
    year:  A year (e.g., 2018). Must be an `int`.
    month: A month (1 <= month <= 12) in year. Must be an `int`.
    day:   A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an
      `int`.

  Returns:
    True if the caller can expect that serialized TensorFlow graphs produced
    can be consumed by programs that are compiled with the TensorFlow library
    source code after (year, month, day).
  """
  return _FORWARD_COMPATIBILITY_DATE_NUMBER > _date_to_date_number(
      year, month, day)

@tf_export("compat.forward_compatibility_horizon")
@tf_contextlib.contextmanager
def forward_compatibility_horizon(year, month, day):
  """Context manager for testing forward compatibility of generated graphs.

  See [Version
  compatibility](https://tensorflow.org/guide/version_compat#backward_forward).

  To ensure forward compatibility of generated graphs (see `forward_compatible`)
  with older binaries, new features can be gated with:

  ```python
  if compat.forward_compatible(year=2018, month=08, date=01):
    generate_graph_with_new_features()
  else:
    generate_graph_so_older_binaries_can_consume_it()
  ```

  However, when adding new features, one may want to unittest it before
  the forward compatibility window expires. This context manager enables
  such tests. For example:

  ```python
  from tensorflow.python.compat import compat

  def testMyNewFeature(self):
    with compat.forward_compatibility_horizon(2018, 08, 02):
       # Test that generate_graph_with_new_features() has an effect
  ```

  Args:
    year:  A year (e.g., 2018). Must be an `int`.
    month: A month (1 <= month <= 12) in year. Must be an `int`.
    day:   A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an
      `int`.

  Yields:
    Nothing.
  """
  try:
    _update_forward_compatibility_date_number(datetime.date(year, month, day))
    yield
  finally:
    _update_forward_compatibility_date_number()
<commit_msg>compat: Update forward compatibility horizon to 2021-12-14<commit_after># Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utilities for API compatibility between TensorFlow release versions.

See [Version
Compatibility](https://tensorflow.org/guide/version_compat#backward_forward)
"""

import datetime
import os

from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util import tf_contextlib
from tensorflow.python.util.tf_export import tf_export

# This value changes every day with an automatic CL. It can be modified in code
# via `forward_compatibility_horizon()` or with the environment variable
# TF_FORWARD_COMPATIBILITY_DELTA_DAYS, which is added to the compatibility date.
_FORWARD_COMPATIBILITY_HORIZON = datetime.date(2021, 12, 14)
_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME = "TF_FORWARD_COMPATIBILITY_DELTA_DAYS"
_FORWARD_COMPATIBILITY_DATE_NUMBER = None

def _date_to_date_number(year, month, day):
  return (year << 9) | (month << 5) | day

def _update_forward_compatibility_date_number(date_to_override=None):
  """Update the base date to compare in forward_compatible function."""

  global _FORWARD_COMPATIBILITY_DATE_NUMBER

  if date_to_override:
    date = date_to_override
  else:
    date = _FORWARD_COMPATIBILITY_HORIZON
    delta_days = os.getenv(_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME)
    if delta_days:
      date += datetime.timedelta(days=int(delta_days))

  if date < _FORWARD_COMPATIBILITY_HORIZON:
    logging.warning("Trying to set the forward compatibility date to the past"
                    " date %s. This will be ignored by TensorFlow." % (date))
    return
  _FORWARD_COMPATIBILITY_DATE_NUMBER = _date_to_date_number(
      date.year, date.month, date.day)

_update_forward_compatibility_date_number()

@tf_export("compat.forward_compatible")
def forward_compatible(year, month, day):
  """Return true if the forward compatibility window has expired.

  See [Version
  compatibility](https://tensorflow.org/guide/version_compat#backward_forward).

  Forward-compatibility refers to scenarios where the producer of a TensorFlow
  model (a GraphDef or SavedModel) is compiled against a version of the
  TensorFlow library newer than what the consumer was compiled against. The
  "producer" is typically a Python program that constructs and trains a model
  while the "consumer" is typically another program that loads and serves the
  model.

  TensorFlow has been supporting a 3 week forward-compatibility window for
  programs compiled from source at HEAD.

  For example, consider the case where a new operation `MyNewAwesomeAdd` is
  created with the intent of replacing the implementation of an existing Python
  wrapper - `tf.add`.  The Python wrapper implementation should change from
  something like:

  ```python
  def add(inputs, name=None):
    return gen_math_ops.add(inputs, name)
  ```

  to:

  ```python
  from tensorflow.python.compat import compat

  def add(inputs, name=None):
    if compat.forward_compatible(year, month, day):
      # Can use the awesome new implementation.
      return gen_math_ops.my_new_awesome_add(inputs, name)
    # To maintain forward compatibility, use the old implementation.
    return gen_math_ops.add(inputs, name)
  ```

  Where `year`, `month`, and `day` specify the date beyond which binaries
  that consume a model are expected to have been updated to include the
  new operations. This date is typically at least 3 weeks beyond the date
  the code that adds the new operation is committed.

  Args:
    year:  A year (e.g., 2018). Must be an `int`.
    month: A month (1 <= month <= 12) in year. Must be an `int`.
    day:   A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an
      `int`.

  Returns:
    True if the caller can expect that serialized TensorFlow graphs produced
    can be consumed by programs that are compiled with the TensorFlow library
    source code after (year, month, day).
  """
  return _FORWARD_COMPATIBILITY_DATE_NUMBER > _date_to_date_number(
      year, month, day)

@tf_export("compat.forward_compatibility_horizon")
@tf_contextlib.contextmanager
def forward_compatibility_horizon(year, month, day):
  """Context manager for testing forward compatibility of generated graphs.

  See [Version
  compatibility](https://tensorflow.org/guide/version_compat#backward_forward).

  To ensure forward compatibility of generated graphs (see `forward_compatible`)
  with older binaries, new features can be gated with:

  ```python
  if compat.forward_compatible(year=2018, month=08, date=01):
    generate_graph_with_new_features()
  else:
    generate_graph_so_older_binaries_can_consume_it()
  ```

  However, when adding new features, one may want to unittest it before
  the forward compatibility window expires. This context manager enables
  such tests. For example:

  ```python
  from tensorflow.python.compat import compat

  def testMyNewFeature(self):
    with compat.forward_compatibility_horizon(2018, 08, 02):
       # Test that generate_graph_with_new_features() has an effect
  ```

  Args:
    year:  A year (e.g., 2018). Must be an `int`.
    month: A month (1 <= month <= 12) in year. Must be an `int`.
    day:   A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an
      `int`.

  Yields:
    Nothing.
  """
  try:
    _update_forward_compatibility_date_number(datetime.date(year, month, day))
    yield
  finally:
    _update_forward_compatibility_date_number()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
import os.path

import config
import logging

from datetime import datetime
from datetime import timedelta

from flask import abort
from flask import flash
from flask import redirect
from flask import request
from flask import url_for

import logic.alias
import logic.department
import logic.employee
import logic.event
import logic.love
import logic.love_link
import logic.love_count
import logic.subscription
from errors import NoSuchEmployee
from errors import TaintedLove
from google.appengine.api import taskqueue
from logic import TIMESPAN_LAST_WEEK
from logic import TIMESPAN_THIS_WEEK
from logic import to_the_future
from logic import utc_week_limits
from logic.love_link import create_love_link
from main import app
from models import AccessKey
from models import Alias
from models import Employee
from models import Subscription
from util.decorators import admin_required
from util.decorators import csrf_protect
from util.decorators import user_required
from util.recipient import sanitize_recipients
from util.render import render_template
from views import common

@app.route('/', methods=['GET'])
@user_required
def home():
    recipients = request.args.get('recipients', request.args.get('recipient'))
    message = request.args.get('message')

    return render_template(
        'home.html',
        current_time=datetime.utcnow(),
        current_user=Employee.get_current_employee(),
        recipients=recipients,
        message=message,
    )

@app.route('/me', methods=['GET'])
@user_required
def me():
    current_employee = Employee.get_current_employee()

    sent_love = logic.love.recent_sent_love(current_employee.key, limit=20)
    received_love = logic.love.recent_received_love(current_employee.key, limit=20)

    return render_template(
        'me.html',
        current_time=datetime.utcnow(),
        current_user=current_employee,
        sent_loves=sent_love.get_result(),
        received_loves=received_love.get_result()
    )

@app.route('/<regex("[a-zA-Z]{3,30}"):user>', methods=['GET'])
@user_required
def me_or_explore(user):
    current_employee = Employee.get_current_employee()
    username = logic.alias.name_for_alias(user.lower().strip())

    try:
        user_key = Employee.get_key_for_username(username)
    except NoSuchEmployee:
        abort(404)

    if current_employee.key == user_key:
        return redirect(url_for('me'))
    else:
        return redirect(url_for('explore', user=username))

@app.route('/l/<string:link_id>', methods=['GET'])
@user_required
def love_link(link_id):
    loveLink = logic.love_link.get_love_link(link_id)
    recipients = loveLink.recipient_list
    message = loveLink.message

    return render_template(
        'love_link.html',
        current_time=datetime.utcnow(),
        current_user=Employee.get_current_employee(),
        recipients=recipients,
        message=message,
        link_id=link_id,
    )

@app.route('/explore', methods=['GET'])
@user_required
def explore():
    username = request.args.get('user', None)
    if not username:
        if username is not None:
            flash('Enter a name, lover.', 'error')
        return render_template(
            'explore.html',
            current_time=datetime.utcnow(),
            user=None
        )
    username = username.lower().strip()

    user_key = Employee.query(
        Employee.username == username,
        Employee.terminated == False,  # noqa
    ).get(keys_only=True)

    if not user_key:
        flash('Sorry, "{}" is not a valid user.'.format(username), 'error')
        return redirect(url_for('explore'))

    sent_love = logic.love.recent_sent_love(user_key, include_secret=False, limit=20)
    received_love = logic.love.recent_received_love(user_key, include_secret=False, limit=20)

    return render_template(
        'explore.html',
        current_time=datetime.utcnow(),
        sent_loves=sent_love.get_result(),
        received_loves=received_love.get_result(),
        user=user_key.get()
    )

@app.route('/leaderboard', methods=['GET'])
@user_required
def leaderboard():
    timespan = request.args.get('timespan', TIMESPAN_THIS_WEEK)
    department = request.args.get('department', None)

    # If last week, we need to subtract *before* getting the week limits to
    # avoid being off by one hour on weeks that include a DST transition
    utc_now = datetime.utcnow()
    if timespan == TIMESPAN_LAST_WEEK:
        utc_now -= timedelta(days=7)
    utc_week_start, _ = utc_week_limits(utc_now)

    top_lovers, top_lovees = logic.love_count.top_lovers_and_lovees(utc_week_start, dept=department)

    top_lover_dicts = [
        {
            'employee': employee_key.get_async(),
            'num_sent': sent_count
        }
        for employee_key, sent_count
        in top_lovers
    ]

    top_loved_dicts = [
        {
            'employee': employee_key.get_async(),
            'num_received': received_count
        }
        for employee_key, received_count
        in top_lovees
    ]

    # get results for the futures set up previously
    map(to_the_future, top_lover_dicts)
    map(to_the_future, top_loved_dicts)

    return render_template(
        'leaderboard.html',
        top_loved=top_loved_dicts,
        top_lovers=top_lover_dicts,
        departments=logic.department.META_DEPARTMENTS,
        sub_departments=logic.department.META_DEPARTMENT_MAP,
        selected_dept=department,
        selected_timespan=timespan,
        org_title=config.ORG_TITLE,
    )

@app.route('/sent', methods=['GET'])
@user_required
def sent():
    link_id = request.args.get('link_id', None)
    recipients_str = request.args.get('recipients', None)
    message = request.args.get('message', None)

    if not link_id or not recipients_str or not message:
        return redirect(url_for('home'))

    recipients = sanitize_recipients(recipients_str)
    loved = [
        Employee.get_key_for_username(recipient).get()
        for recipient in recipients
    ]

    return render_template(
        'sent.html',
        current_time=datetime.utcnow(),
        current_user=Employee.get_current_employee(),
        message=message,
        loved=loved,
        url='{0}/l/{1}'.format(config.APP_BASE_URL, link_id),
    )

@app.route('/keys', methods=['GET'])
@admin_required
def keys():
    api_keys = AccessKey.query().fetch()
    return render_template(
        'keys.html',
        keys=api_keys
    )

@app.route('/keys/create', methods=['POST'])
@csrf_protect
@admin_required
def create_key():
    description = request.form.get('description')
    new_key = AccessKey.create(description)

    flash('Your API key {} has been created. Refresh the page to see it below.'.format(new_key.access_key))
    return redirect(url_for('keys'))

@app.route('/love', methods=['POST'])
@csrf_protect
@user_required
def love():
    recipients = sanitize_recipients(request.form.get('recipients'))
    message = request.form.get('message').strip()
    secret = (request.form.get('secret') == 'true')
    link_id = request.form.get('link_id')

    if not recipients:
        flash('Enter a name, lover.', 'error')
        return redirect(url_for('home'))

    recipients_display_str = ', '.join(recipients)

    if not message:
        flash('Enter a message, lover.', 'error')
        return redirect(url_for('home', recipients=recipients_display_str))

    try:
        real_recipients = logic.love.send_loves(recipients, message, secret=secret)
        # actual recipients may have the sender stripped from the list
        real_display_str = ', '.join(real_recipients)
        logging.info(real_recipients)

        if secret:
            flash('Secret love sent to {}!'.format(real_display_str))
            return redirect(url_for('home'))
        else:
            hash_key = link_id if link_id else create_love_link(real_display_str, message).hash_key
            return redirect(url_for('sent', message=message, recipients=real_display_str, link_id=hash_key))

    except TaintedLove as exc:
        if exc.is_error:
            flash(exc.user_message, 'error')
        else:
            flash(exc.user_message)

@app.route('/user/autocomplete', methods=['GET'])
@user_required
def autocomplete_web():
    return common.autocomplete(request)

@app.route('/subscriptions', methods=['GET'])
@admin_required
def subscriptions():
    return render_template(
        'subscriptions.html',
        subscriptions=Subscription.query().fetch(),
        events=logic.event.EVENTS,
    )

@app.route('/subscriptions/create', methods=['POST'])
@csrf_protect
@admin_required
def create_subscription():
    subscription_dict = dict(
        request_url=request.form.get('request_url').strip(),
        event=request.form.get('event').strip(),
        active=(request.form.get('active') == 'true'),
        secret=request.form.get('secret').strip(),
    )

    try:
        Subscription.create_from_dict(subscription_dict)
        flash('Subscription created. Refresh the page to see it.')
    except ValueError:
        flash('Something went wrong. Please check your input.', 'error')

    return redirect(url_for('subscriptions'))

@app.route('/subscriptions/<int:subscription_id>/delete', methods=['POST'])
@csrf_protect
@admin_required
def delete_subscription(subscription_id):
    logic.subscription.delete_subscription(subscription_id)
    flash('Subscription deleted. Refresh the page to see it\'s gone.', 'info')
    return redirect(url_for('subscriptions'))

@app.route('/aliases', methods=['GET'])
@admin_required
def aliases():
    return render_template(
        'aliases.html',
        aliases=Alias.query().fetch(),
    )

@app.route('/aliases', methods=['POST'])
@csrf_protect
@admin_required
def create_alias():
    try:
        logic.alias.save_alias(
            request.form.get('alias').strip(),
            request.form.get('username').strip(),
        )
        flash('New alias successfully saved. Refresh the page to see it.')
    except Exception as e:
        flash('Something went wrong: {}.'.format(e.message), 'error')

    return redirect(url_for('aliases'))

@app.route('/aliases/<int:alias_id>/delete', methods=['POST'])
@csrf_protect
@admin_required
def delete_alias(alias_id):
    logic.alias.delete_alias(alias_id)
    flash('Alias successfully deleted. Refresh the page to see it\'s gone.', 'info')
    return redirect(url_for('aliases'))

@app.route('/employees', methods=['GET'])
@admin_required
def employees():
    return render_template(
        'employees.html',
        pagination_result=Employee.paginate(
            order_by=Employee.username,
            prev_cursor_str=request.args.get('prev_cursor'),
            next_cursor_str=request.args.get('next_cursor'),
        ),
    )

@app.route('/employees/import', methods=['GET'])
@admin_required
def import_employees_form():
    import_file_exists = os.path.isfile(logic.employee.csv_import_file())
    return render_template(
        'import.html',
        import_file_exists=import_file_exists,
    )

@app.route('/employees/import', methods=['POST'])
@admin_required
def import_employees():
    flash('We started importing employee data in the background. Refresh the page to see it.', 'info')
    taskqueue.add(url='/tasks/employees/load/csv')
    return redirect(url_for('employees'))
<commit_msg>Adding some logging for the crashing leaderboard<commit_after># -*- coding: utf-8 -*-
import os.path

import config
import logging

from datetime import datetime
from datetime import timedelta

from flask import abort
from flask import flash
from flask import redirect
from flask import request
from flask import url_for

import logic.alias
import logic.department
import logic.employee
import logic.event
import logic.love
import logic.love_link
import logic.love_count
import logic.subscription
from errors import NoSuchEmployee
from errors import TaintedLove
from google.appengine.api import taskqueue
from logic import TIMESPAN_LAST_WEEK
from logic import TIMESPAN_THIS_WEEK
from logic import to_the_future
from logic import utc_week_limits
from logic.love_link import create_love_link
from main import app
from models import AccessKey
from models import Alias
from models import Employee
from models import Subscription
from util.decorators import admin_required
from util.decorators import csrf_protect
from util.decorators import user_required
from util.recipient import sanitize_recipients
from util.render import render_template
from views import common

@app.route('/', methods=['GET'])
@user_required
def home():
    recipients = request.args.get('recipients', request.args.get('recipient'))
    message = request.args.get('message')

    return render_template(
        'home.html',
        current_time=datetime.utcnow(),
        current_user=Employee.get_current_employee(),
        recipients=recipients,
        message=message,
    )

@app.route('/me', methods=['GET'])
@user_required
def me():
    current_employee = Employee.get_current_employee()

    sent_love = logic.love.recent_sent_love(current_employee.key, limit=20)
    received_love = logic.love.recent_received_love(current_employee.key, limit=20)

    return render_template(
        'me.html',
        current_time=datetime.utcnow(),
        current_user=current_employee,
        sent_loves=sent_love.get_result(),
        received_loves=received_love.get_result()
    )

@app.route('/<regex("[a-zA-Z]{3,30}"):user>', methods=['GET'])
@user_required
def me_or_explore(user):
    current_employee = Employee.get_current_employee()
    username = logic.alias.name_for_alias(user.lower().strip())

    try:
        user_key = Employee.get_key_for_username(username)
    except NoSuchEmployee:
        abort(404)

    if current_employee.key == user_key:
        return redirect(url_for('me'))
    else:
        return redirect(url_for('explore', user=username))

@app.route('/l/<string:link_id>', methods=['GET'])
@user_required
def love_link(link_id):
    loveLink = logic.love_link.get_love_link(link_id)
    recipients = loveLink.recipient_list
    message = loveLink.message

    return render_template(
        'love_link.html',
        current_time=datetime.utcnow(),
        current_user=Employee.get_current_employee(),
        recipients=recipients,
        message=message,
        link_id=link_id,
    )

@app.route('/explore', methods=['GET'])
@user_required
def explore():
    username = request.args.get('user', None)
    if not username:
        if username is not None:
            flash('Enter a name, lover.', 'error')
        return render_template(
            'explore.html',
            current_time=datetime.utcnow(),
            user=None
        )
    username = username.lower().strip()

    user_key = Employee.query(
        Employee.username == username,
        Employee.terminated == False,  # noqa
    ).get(keys_only=True)

    if not user_key:
        flash('Sorry, "{}" is not a valid user.'.format(username), 'error')
        return redirect(url_for('explore'))

    sent_love = logic.love.recent_sent_love(user_key, include_secret=False, limit=20)
    received_love = logic.love.recent_received_love(user_key, include_secret=False, limit=20)

    return render_template(
        'explore.html',
        current_time=datetime.utcnow(),
        sent_loves=sent_love.get_result(),
        received_loves=received_love.get_result(),
        user=user_key.get()
    )

@app.route('/leaderboard', methods=['GET'])
@user_required
def leaderboard():
    timespan = request.args.get('timespan', TIMESPAN_THIS_WEEK)
    department = request.args.get('department', None)

    # If last week, we need to subtract *before* getting the week limits to
    # avoid being off by one hour on weeks that include a DST transition
    utc_now = datetime.utcnow()
    if timespan == TIMESPAN_LAST_WEEK:
        utc_now -= timedelta(days=7)
    utc_week_start, _ = utc_week_limits(utc_now)

    top_lovers, top_lovees = logic.love_count.top_lovers_and_lovees(utc_week_start, dept=department)
    logging.info(top_lovers)
    logging.info(top_lovees)

    top_lover_dicts = [
        {
            'employee': employee_key.get_async(),
            'num_sent': sent_count
        }
        for employee_key, sent_count
        in top_lovers
    ]

    logging.info(top_lover_dicts)

    top_loved_dicts = [
        {
            'employee': employee_key.get_async(),
            'num_received': received_count
        }
        for employee_key, received_count
        in top_lovees
    ]

    logging.info(top_loved_dicts)

    # get results for the futures set up previously
    map(to_the_future, top_lover_dicts)
    map(to_the_future, top_loved_dicts)

    return render_template(
        'leaderboard.html',
        top_loved=top_loved_dicts,
        top_lovers=top_lover_dicts,
        departments=logic.department.META_DEPARTMENTS,
        sub_departments=logic.department.META_DEPARTMENT_MAP,
        selected_dept=department,
        selected_timespan=timespan,
        org_title=config.ORG_TITLE,
    )

@app.route('/sent', methods=['GET'])
@user_required
def sent():
    link_id = request.args.get('link_id', None)
    recipients_str = request.args.get('recipients', None)
    message = request.args.get('message', None)

    if not link_id or not recipients_str or not message:
        return redirect(url_for('home'))

    recipients = sanitize_recipients(recipients_str)
    loved = [
        Employee.get_key_for_username(recipient).get()
        for recipient in recipients
    ]

    return render_template(
        'sent.html',
        current_time=datetime.utcnow(),
        current_user=Employee.get_current_employee(),
        message=message,
        loved=loved,
        url='{0}/l/{1}'.format(config.APP_BASE_URL, link_id),
    )

@app.route('/keys', methods=['GET'])
@admin_required
def keys():
    api_keys = AccessKey.query().fetch()
    return render_template(
        'keys.html',
        keys=api_keys
    )

@app.route('/keys/create', methods=['POST'])
@csrf_protect
@admin_required
def create_key():
    description = request.form.get('description')
    new_key = AccessKey.create(description)

    flash('Your API key {} has been created. Refresh the page to see it below.'.format(new_key.access_key))
    return redirect(url_for('keys'))

@app.route('/love', methods=['POST'])
@csrf_protect
@user_required
def love():
    recipients = sanitize_recipients(request.form.get('recipients'))
    message = request.form.get('message').strip()
    secret = (request.form.get('secret') == 'true')
    link_id = request.form.get('link_id')

    if not recipients:
        flash('Enter a name, lover.', 'error')
        return redirect(url_for('home'))

    recipients_display_str = ', '.join(recipients)

    if not message:
        flash('Enter a message, lover.', 'error')
        return redirect(url_for('home', recipients=recipients_display_str))

    try:
        real_recipients = logic.love.send_loves(recipients, message, secret=secret)
        # actual recipients may have the sender stripped from the list
        real_display_str = ', '.join(real_recipients)
        logging.info(real_recipients)

        if secret:
            flash('Secret love sent to {}!'.format(real_display_str))
            return redirect(url_for('home'))
        else:
            hash_key = link_id if link_id else create_love_link(real_display_str, message).hash_key
            return redirect(url_for('sent', message=message, recipients=real_display_str, link_id=hash_key))

    except TaintedLove as exc:
        if exc.is_error:
            flash(exc.user_message, 'error')
        else:
            flash(exc.user_message)

@app.route('/user/autocomplete', methods=['GET'])
@user_required
def autocomplete_web():
    return common.autocomplete(request)

@app.route('/subscriptions', methods=['GET'])
@admin_required
def subscriptions():
    return render_template(
        'subscriptions.html',
        subscriptions=Subscription.query().fetch(),
        events=logic.event.EVENTS,
    )

@app.route('/subscriptions/create', methods=['POST'])
@csrf_protect
@admin_required
def create_subscription():
    subscription_dict = dict(
        request_url=request.form.get('request_url').strip(),
        event=request.form.get('event').strip(),
        active=(request.form.get('active') == 'true'),
        secret=request.form.get('secret').strip(),
    )

    try:
        Subscription.create_from_dict(subscription_dict)
        flash('Subscription created. Refresh the page to see it.')
    except ValueError:
        flash('Something went wrong. Please check your input.', 'error')

    return redirect(url_for('subscriptions'))

@app.route('/subscriptions/<int:subscription_id>/delete', methods=['POST'])
@csrf_protect
@admin_required
def delete_subscription(subscription_id):
    logic.subscription.delete_subscription(subscription_id)
    flash('Subscription deleted. Refresh the page to see it\'s gone.', 'info')
    return redirect(url_for('subscriptions'))

@app.route('/aliases', methods=['GET'])
@admin_required
def aliases():
    return render_template(
        'aliases.html',
        aliases=Alias.query().fetch(),
    )

@app.route('/aliases', methods=['POST'])
@csrf_protect
@admin_required
def create_alias():
    try:
        logic.alias.save_alias(
            request.form.get('alias').strip(),
            request.form.get('username').strip(),
        )
        flash('New alias successfully saved. Refresh the page to see it.')
    except Exception as e:
        flash('Something went wrong: {}.'.format(e.message), 'error')

    return redirect(url_for('aliases'))

@app.route('/aliases/<int:alias_id>/delete', methods=['POST'])
@csrf_protect
@admin_required
def delete_alias(alias_id):
    logic.alias.delete_alias(alias_id)
    flash('Alias successfully deleted. Refresh the page to see it\'s gone.', 'info')
    return redirect(url_for('aliases'))

@app.route('/employees', methods=['GET'])
@admin_required
def employees():
    return render_template(
        'employees.html',
        pagination_result=Employee.paginate(
            order_by=Employee.username,
            prev_cursor_str=request.args.get('prev_cursor'),
            next_cursor_str=request.args.get('next_cursor'),
        ),
    )

@app.route('/employees/import', methods=['GET'])
@admin_required
def import_employees_form():
    import_file_exists = os.path.isfile(logic.employee.csv_import_file())
    return render_template(
        'import.html',
        import_file_exists=import_file_exists,
    )

@app.route('/employees/import', methods=['POST'])
@admin_required
def import_employees():
    flash('We started importing employee data in the background. Refresh the page to see it.', 'info')
    taskqueue.add(url='/tasks/employees/load/csv')
    return redirect(url_for('employees'))
<|endoftext|>


<commit_before># Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utilities for API compatibility between TensorFlow release versions.

See [Version
Compatibility](https://tensorflow.org/guide/version_compat#backward_forward)
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import datetime
import os

from tensorflow.python.util import tf_contextlib
from tensorflow.python.util.tf_export import tf_export

# This value changes every day with an automatic CL. It can be modified in code
# via `forward_compatibility_horizon()` or with the environment variable
# TF_FORWARD_COMPATIBILITY_DELTA_DAYS, which is added to the compatibility date.
_FORWARD_COMPATIBILITY_HORIZON = datetime.date(2019, 8, 12)

_FORWARD_COMPATIBILITY_HORIZON_OVERRIDDEN = False
_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME = "TF_FORWARD_COMPATIBILITY_DELTA_DAYS"

def _get_forward_compatibility_date():
  date = _FORWARD_COMPATIBILITY_HORIZON
  delta_days = os.getenv(_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME)
  if delta_days is not None and not _FORWARD_COMPATIBILITY_HORIZON_OVERRIDDEN:
    return date + datetime.timedelta(days=int(delta_days))
  else:
    return date

@tf_export("compat.forward_compatible")
def forward_compatible(year, month, day):
  """Return true if the forward compatibility window has expired.

  See [Version
  compatibility](https://tensorflow.org/guide/version_compat#backward_forward).

  Forward-compatibility refers to scenarios where the producer of a TensorFlow
  model (a GraphDef or SavedModel) is compiled against a version of the
  TensorFlow library newer than what the consumer was compiled against. The
  "producer" is typically a Python program that constructs and trains a model
  while the "consumer" is typically another program that loads and serves the
  model.

  TensorFlow has been supporting a 3 week forward-compatibility window for
  programs compiled from source at HEAD.

  For example, consider the case where a new operation `MyNewAwesomeAdd` is
  created with the intent of replacing the implementation of an existing Python
  wrapper - `tf.add`.  The Python wrapper implementation should change from
  something like:

  ```python
  def add(inputs, name=None):
    return gen_math_ops.add(inputs, name)
  ```

  to:

  ```python
  from tensorflow.python.compat import compat

  def add(inputs, name=None):
    if compat.forward_compatible(year, month, day):
      # Can use the awesome new implementation.
      return gen_math_ops.my_new_awesome_add(inputs, name)
    # To maintain forward compatibiltiy, use the old implementation.
    return gen_math_ops.add(inputs, name)
  ```

  Where `year`, `month`, and `day` specify the date beyond which binaries
  that consume a model are expected to have been updated to include the
  new operations. This date is typically at least 3 weeks beyond the date
  the code that adds the new operation is committed.

  Args:
    year:  A year (e.g., 2018). Must be an `int`.
    month: A month (1 <= month <= 12) in year. Must be an `int`.
    day:   A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an
      `int`.

  Returns:
    True if the caller can expect that serialized TensorFlow graphs produced
    can be consumed by programs that are compiled with the TensorFlow library
    source code after (year, month, day).
  """
  return _get_forward_compatibility_date() > datetime.date(year, month, day)

@tf_export("compat.forward_compatibility_horizon")
@tf_contextlib.contextmanager
def forward_compatibility_horizon(year, month, day):
  """Context manager for testing forward compatibility of generated graphs.

  See [Version
  compatibility](https://tensorflow.org/guide/version_compat#backward_forward).

  To ensure forward compatibility of generated graphs (see `forward_compatible`)
  with older binaries, new features can be gated with:

  ```python
  if compat.forward_compatible(year=2018, month=08, date=01):
    generate_graph_with_new_features()
  else:
    generate_graph_so_older_binaries_can_consume_it()
  ```

  However, when adding new features, one may want to unittest it before
  the forward compatibility window expires. This context manager enables
  such tests. For example:

  ```python
  from tensorflow.python.compat import compat

  def testMyNewFeature(self):
    with compat.forward_compatibility_horizon(2018, 08, 02):
       # Test that generate_graph_with_new_features() has an effect
  ```

  Args:
    year:  A year (e.g., 2018). Must be an `int`.
    month: A month (1 <= month <= 12) in year. Must be an `int`.
    day:   A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an
      `int`.

  Yields:
    Nothing.
  """
  global _FORWARD_COMPATIBILITY_HORIZON
  global _FORWARD_COMPATIBILITY_HORIZON_OVERRIDDEN
  try:
    old_compat_date = _FORWARD_COMPATIBILITY_HORIZON
    _FORWARD_COMPATIBILITY_HORIZON_OVERRIDDEN = True
    _FORWARD_COMPATIBILITY_HORIZON = datetime.date(year, month, day)
    yield
  finally:
    _FORWARD_COMPATIBILITY_HORIZON_OVERRIDDEN = False
    _FORWARD_COMPATIBILITY_HORIZON = old_compat_date
<commit_msg>compat: Update forward compatibility horizon to 2019-08-13<commit_after># Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utilities for API compatibility between TensorFlow release versions.

See [Version
Compatibility](https://tensorflow.org/guide/version_compat#backward_forward)
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import datetime
import os

from tensorflow.python.util import tf_contextlib
from tensorflow.python.util.tf_export import tf_export

# This value changes every day with an automatic CL. It can be modified in code
# via `forward_compatibility_horizon()` or with the environment variable
# TF_FORWARD_COMPATIBILITY_DELTA_DAYS, which is added to the compatibility date.
_FORWARD_COMPATIBILITY_HORIZON = datetime.date(2019, 8, 13)

_FORWARD_COMPATIBILITY_HORIZON_OVERRIDDEN = False
_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME = "TF_FORWARD_COMPATIBILITY_DELTA_DAYS"

def _get_forward_compatibility_date():
  date = _FORWARD_COMPATIBILITY_HORIZON
  delta_days = os.getenv(_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME)
  if delta_days is not None and not _FORWARD_COMPATIBILITY_HORIZON_OVERRIDDEN:
    return date + datetime.timedelta(days=int(delta_days))
  else:
    return date

@tf_export("compat.forward_compatible")
def forward_compatible(year, month, day):
  """Return true if the forward compatibility window has expired.

  See [Version
  compatibility](https://tensorflow.org/guide/version_compat#backward_forward).

  Forward-compatibility refers to scenarios where the producer of a TensorFlow
  model (a GraphDef or SavedModel) is compiled against a version of the
  TensorFlow library newer than what the consumer was compiled against. The
  "producer" is typically a Python program that constructs and trains a model
  while the "consumer" is typically another program that loads and serves the
  model.

  TensorFlow has been supporting a 3 week forward-compatibility window for
  programs compiled from source at HEAD.

  For example, consider the case where a new operation `MyNewAwesomeAdd` is
  created with the intent of replacing the implementation of an existing Python
  wrapper - `tf.add`.  The Python wrapper implementation should change from
  something like:

  ```python
  def add(inputs, name=None):
    return gen_math_ops.add(inputs, name)
  ```

  to:

  ```python
  from tensorflow.python.compat import compat

  def add(inputs, name=None):
    if compat.forward_compatible(year, month, day):
      # Can use the awesome new implementation.
      return gen_math_ops.my_new_awesome_add(inputs, name)
    # To maintain forward compatibiltiy, use the old implementation.
    return gen_math_ops.add(inputs, name)
  ```

  Where `year`, `month`, and `day` specify the date beyond which binaries
  that consume a model are expected to have been updated to include the
  new operations. This date is typically at least 3 weeks beyond the date
  the code that adds the new operation is committed.

  Args:
    year:  A year (e.g., 2018). Must be an `int`.
    month: A month (1 <= month <= 12) in year. Must be an `int`.
    day:   A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an
      `int`.

  Returns:
    True if the caller can expect that serialized TensorFlow graphs produced
    can be consumed by programs that are compiled with the TensorFlow library
    source code after (year, month, day).
  """
  return _get_forward_compatibility_date() > datetime.date(year, month, day)

@tf_export("compat.forward_compatibility_horizon")
@tf_contextlib.contextmanager
def forward_compatibility_horizon(year, month, day):
  """Context manager for testing forward compatibility of generated graphs.

  See [Version
  compatibility](https://tensorflow.org/guide/version_compat#backward_forward).

  To ensure forward compatibility of generated graphs (see `forward_compatible`)
  with older binaries, new features can be gated with:

  ```python
  if compat.forward_compatible(year=2018, month=08, date=01):
    generate_graph_with_new_features()
  else:
    generate_graph_so_older_binaries_can_consume_it()
  ```

  However, when adding new features, one may want to unittest it before
  the forward compatibility window expires. This context manager enables
  such tests. For example:

  ```python
  from tensorflow.python.compat import compat

  def testMyNewFeature(self):
    with compat.forward_compatibility_horizon(2018, 08, 02):
       # Test that generate_graph_with_new_features() has an effect
  ```

  Args:
    year:  A year (e.g., 2018). Must be an `int`.
    month: A month (1 <= month <= 12) in year. Must be an `int`.
    day:   A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an
      `int`.

  Yields:
    Nothing.
  """
  global _FORWARD_COMPATIBILITY_HORIZON
  global _FORWARD_COMPATIBILITY_HORIZON_OVERRIDDEN
  try:
    old_compat_date = _FORWARD_COMPATIBILITY_HORIZON
    _FORWARD_COMPATIBILITY_HORIZON_OVERRIDDEN = True
    _FORWARD_COMPATIBILITY_HORIZON = datetime.date(year, month, day)
    yield
  finally:
    _FORWARD_COMPATIBILITY_HORIZON_OVERRIDDEN = False
    _FORWARD_COMPATIBILITY_HORIZON = old_compat_date
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
import re
import operator
from functools import partial

import sublime
import sublime_plugin

from probe import extract

__all__ = [
    'HayakuCommand',
    'HayakuChangeNumberCommand',
]

# максимальный размер css properties
MAX_SIZE_CSS = len('-webkit-transition-timing-function')

ABBR_REGEX = re.compile(r'[\s|;|{]([a-z-]+)$', re.IGNORECASE)

class HayakuCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        regions = self.view.sel()
        if len(regions) > 1:
            # разобраться с многооконными выборками
            # пока что работаем только с одним регионом
            for r in regions:
                self.view.insert(edit, r, '\t')
            return
        region = regions[0]
        if not region.empty():
            # сделать работы с выделенным словом
            self.view.insert(edit, region, '\t')
            return
        cur_pos = region.begin()

        start_pos = cur_pos - MAX_SIZE_CSS
        if start_pos < 0:
            start_pos = 0
        probably_abbr = self.view.substr(sublime.Region(start_pos, cur_pos))
        match = ABBR_REGEX.search(probably_abbr)
        if match is None:
            self.view.insert(edit, cur_pos, '\t')
            return

        abbr = match.group(1)
        new_cur_pos = cur_pos-len(abbr)
        assert cur_pos-len(abbr) >= 0
        prop = extract(abbr)
        if not prop:
            return
        self.view.erase(edit, sublime.Region(new_cur_pos, cur_pos))
        template = '{0}: ${{1}};'.format(prop)
        self.view.run_command("insert_snippet", {"contents": template})

OPERATION_TABLE = {
    "up": partial(operator.add, 1),
    "down": partial(operator.add, -1),
    "shift_up": partial(operator.add, 10),
    "shift_down": partial(operator.add, -10),
    "alt_up": partial(operator.add, 0.1),
    "alt_down": partial(operator.add, -0.1),
}

# Изменяет число по сочетаниям ctrl/alt/shift + up/down
class HayakuChangeNumberCommand(sublime_plugin.TextCommand):
    def run(self, edit, key):

        # поиск текущей позиции в файле
        regions = self.view.sel()
        if len(regions) > 1:
            # разобраться с многооконными выборками
            # пока что работаем только с одним регионом
            for r in regions:
                self.view.insert(edit, r, '\t')
            return
        region = regions[0]
        if not region.empty():
            # сделать работы с выделенным словом
            self.view.insert(edit, region, '\t')
            return
        cur_pos = region.begin()

        # Буферы для чисел до и после курсора
        before_buf = []
        after_buf = []

        # считывает линию и текущую позицию в куросора в строке
        line_region = self.view.line(cur_pos)
        line = self.view.substr(line_region)
        row, col = self.view.rowcol(cur_pos)

        for i in range(col-1, 0-1, -1):
            if line[i].isdigit() or line[i] in ('.', '-'):
                before_buf.append(line[i])
            else:
                break
        before_buf = before_buf[::-1]
        for i in range(col, len(line)):
            if line[i].isdigit() or line[i] in ('.', '-'):
                after_buf.append(line[i])
            else:
                break

        start_pos_offset = len(before_buf)
        end_pos_offset = len(after_buf)

        # прочитать число
        total_buf = before_buf + after_buf
        buf = u''.join(total_buf)
        value = None
        try:
            value = float(buf)
            value = int(buf)
        except ValueError:
            if value is None:
                return

        # Расчёт нового значения
        operation = OPERATION_TABLE[key]
        new_value = operation(value)

        # Замена региона с числом
        start_pos = cur_pos - start_pos_offset
        end_pos = cur_pos + end_pos_offset
        replace_region = sublime.Region(start_pos, end_pos)
        self.view.replace(edit, replace_region, str(new_value))

        # установить курсор на место
        self.view.sel().clear()
        self.view.sel().add(sublime.Region(cur_pos, cur_pos))

class DetectHayakuValuesEventListener(sublime_plugin.EventListener):
    def on_modified(self, view):

        # поиск текущей позиции в файле
        regions = view.sel()
        if len(regions) > 1:
            # разобраться с многооконными выборками
            # пока что работаем только с одним регионом
            for r in regions:
                view.insert(edit, r, '\t')
            return
        region = regions[0]
        if not region.empty():
            # сделать работы с выделенным словом
            view.insert(edit, region, '\t')
            return
        cur_pos = region.begin()

        st = view.scope_name(cur_pos)
        if not st.startswith('source.css'):
            return

        line_num, col_num = view.rowcol(cur_pos)
        line = view.substr(view.line(cur_pos))

        # курсор находится в значении css-правила
        if re.match('.*[:|\s*]$', line[:col_num]) and re.match('^[;|\s*|$].*', line[col_num:]):
            # Свойство
            prop = re.match('.*?([A-Za-z-]+):[\s*]?$', line[:col_num])
            if prop is not None:
                import datetime
                print prop.group(1), 'prop', datetime.datetime.now()
                # from ololo import PROPS
                # ch = view.substr(cur_pos)
                # values = PROPS[prop]
                # if not values:
                #     return

<commit_msg>update template<commit_after># -*- coding: utf-8 -*-
import re
import operator
from functools import partial

import sublime
import sublime_plugin

from probe import extract

__all__ = [
    'HayakuCommand',
    'HayakuChangeNumberCommand',
]

# максимальный размер css properties
MAX_SIZE_CSS = len('-webkit-transition-timing-function')

ABBR_REGEX = re.compile(r'[\s|;|{]([a-z-]+)$', re.IGNORECASE)

class HayakuCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        regions = self.view.sel()
        if len(regions) > 1:
            # разобраться с многооконными выборками
            # пока что работаем только с одним регионом
            for r in regions:
                self.view.insert(edit, r, '\t')
            return
        region = regions[0]
        if not region.empty():
            # сделать работы с выделенным словом
            self.view.insert(edit, region, '\t')
            return
        cur_pos = region.begin()

        start_pos = cur_pos - MAX_SIZE_CSS
        if start_pos < 0:
            start_pos = 0
        probably_abbr = self.view.substr(sublime.Region(start_pos, cur_pos))
        match = ABBR_REGEX.search(probably_abbr)
        if match is None:
            self.view.insert(edit, cur_pos, '\t')
            return

        abbr = match.group(1)
        new_cur_pos = cur_pos-len(abbr)
        assert cur_pos-len(abbr) >= 0
        prop = extract(abbr)
        if not prop:
            return
        if '' in prop:
            prop, value = prop.split()
            template = '{0}: {1};${{0}}'.format(prop, value)
        else:
            template = '{0}: ${{1}};'.format(prop)
        self.view.erase(edit, sublime.Region(new_cur_pos, cur_pos))
        self.view.run_command("insert_snippet", {"contents": template})

OPERATION_TABLE = {
    "up": partial(operator.add, 1),
    "down": partial(operator.add, -1),
    "shift_up": partial(operator.add, 10),
    "shift_down": partial(operator.add, -10),
    "alt_up": partial(operator.add, 0.1),
    "alt_down": partial(operator.add, -0.1),
}

# Изменяет число по сочетаниям ctrl/alt/shift + up/down
class HayakuChangeNumberCommand(sublime_plugin.TextCommand):
    def run(self, edit, key):

        # поиск текущей позиции в файле
        regions = self.view.sel()
        if len(regions) > 1:
            # разобраться с многооконными выборками
            # пока что работаем только с одним регионом
            for r in regions:
                self.view.insert(edit, r, '\t')
            return
        region = regions[0]
        if not region.empty():
            # сделать работы с выделенным словом
            self.view.insert(edit, region, '\t')
            return
        cur_pos = region.begin()

        # Буферы для чисел до и после курсора
        before_buf = []
        after_buf = []

        # считывает линию и текущую позицию в куросора в строке
        line_region = self.view.line(cur_pos)
        line = self.view.substr(line_region)
        row, col = self.view.rowcol(cur_pos)

        for i in range(col-1, 0-1, -1):
            if line[i].isdigit() or line[i] in ('.', '-'):
                before_buf.append(line[i])
            else:
                break
        before_buf = before_buf[::-1]
        for i in range(col, len(line)):
            if line[i].isdigit() or line[i] in ('.', '-'):
                after_buf.append(line[i])
            else:
                break

        start_pos_offset = len(before_buf)
        end_pos_offset = len(after_buf)

        # прочитать число
        total_buf = before_buf + after_buf
        buf = u''.join(total_buf)
        value = None
        try:
            value = float(buf)
            value = int(buf)
        except ValueError:
            if value is None:
                return

        # Расчёт нового значения
        operation = OPERATION_TABLE[key]
        new_value = operation(value)

        # Замена региона с числом
        start_pos = cur_pos - start_pos_offset
        end_pos = cur_pos + end_pos_offset
        replace_region = sublime.Region(start_pos, end_pos)
        self.view.replace(edit, replace_region, str(new_value))

        # установить курсор на место
        self.view.sel().clear()
        self.view.sel().add(sublime.Region(cur_pos, cur_pos))

class DetectHayakuValuesEventListener(sublime_plugin.EventListener):
    def on_modified(self, view):

        # поиск текущей позиции в файле
        regions = view.sel()
        if len(regions) > 1:
            # разобраться с многооконными выборками
            # пока что работаем только с одним регионом
            for r in regions:
                view.insert(edit, r, '\t')
            return
        region = regions[0]
        if not region.empty():
            # сделать работы с выделенным словом
            view.insert(edit, region, '\t')
            return
        cur_pos = region.begin()

        st = view.scope_name(cur_pos)
        if not st.startswith('source.css'):
            return

        line_num, col_num = view.rowcol(cur_pos)
        line = view.substr(view.line(cur_pos))

        # курсор находится в значении css-правила
        if re.match('.*[:|\s*]$', line[:col_num]) and re.match('^[;|\s*|$].*', line[col_num:]):
            # Свойство
            prop = re.match('.*?([A-Za-z-]+):[\s*]?$', line[:col_num])
            if prop is not None:
                import datetime
                print prop.group(1), 'prop', datetime.datetime.now()
                # from ololo import PROPS
                # ch = view.substr(cur_pos)
                # values = PROPS[prop]
                # if not values:
                #     return

<|endoftext|>


<commit_before># Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utilities for API compatibility between TensorFlow release versions.

See [Version
Compatibility](https://tensorflow.org/guide/version_compat#backward_forward)
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import datetime
import os

from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util import tf_contextlib
from tensorflow.python.util.tf_export import tf_export

# This value changes every day with an automatic CL. It can be modified in code
# via `forward_compatibility_horizon()` or with the environment variable
# TF_FORWARD_COMPATIBILITY_DELTA_DAYS, which is added to the compatibility date.
_FORWARD_COMPATIBILITY_HORIZON = datetime.date(2021, 6, 1)
_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME = "TF_FORWARD_COMPATIBILITY_DELTA_DAYS"
_FORWARD_COMPATIBILITY_DATE_NUMBER = None

def _date_to_date_number(year, month, day):
  return (year << 9) | (month << 5) | day

def _update_forward_compatibility_date_number(date_to_override=None):
  """Update the base date to compare in forward_compatible function."""

  global _FORWARD_COMPATIBILITY_DATE_NUMBER

  if date_to_override:
    date = date_to_override
  else:
    date = _FORWARD_COMPATIBILITY_HORIZON
    delta_days = os.getenv(_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME)
    if delta_days:
      date += datetime.timedelta(days=int(delta_days))

  if date < _FORWARD_COMPATIBILITY_HORIZON:
    logging.warning("Trying to set the forward compatibility date to the past"
                    " date %s. This will be ignored by TensorFlow." % (date))
    return
  _FORWARD_COMPATIBILITY_DATE_NUMBER = _date_to_date_number(
      date.year, date.month, date.day)

_update_forward_compatibility_date_number()

@tf_export("compat.forward_compatible")
def forward_compatible(year, month, day):
  """Return true if the forward compatibility window has expired.

  See [Version
  compatibility](https://tensorflow.org/guide/version_compat#backward_forward).

  Forward-compatibility refers to scenarios where the producer of a TensorFlow
  model (a GraphDef or SavedModel) is compiled against a version of the
  TensorFlow library newer than what the consumer was compiled against. The
  "producer" is typically a Python program that constructs and trains a model
  while the "consumer" is typically another program that loads and serves the
  model.

  TensorFlow has been supporting a 3 week forward-compatibility window for
  programs compiled from source at HEAD.

  For example, consider the case where a new operation `MyNewAwesomeAdd` is
  created with the intent of replacing the implementation of an existing Python
  wrapper - `tf.add`.  The Python wrapper implementation should change from
  something like:

  ```python
  def add(inputs, name=None):
    return gen_math_ops.add(inputs, name)
  ```

  to:

  ```python
  from tensorflow.python.compat import compat

  def add(inputs, name=None):
    if compat.forward_compatible(year, month, day):
      # Can use the awesome new implementation.
      return gen_math_ops.my_new_awesome_add(inputs, name)
    # To maintain forward compatibility, use the old implementation.
    return gen_math_ops.add(inputs, name)
  ```

  Where `year`, `month`, and `day` specify the date beyond which binaries
  that consume a model are expected to have been updated to include the
  new operations. This date is typically at least 3 weeks beyond the date
  the code that adds the new operation is committed.

  Args:
    year:  A year (e.g., 2018). Must be an `int`.
    month: A month (1 <= month <= 12) in year. Must be an `int`.
    day:   A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an
      `int`.

  Returns:
    True if the caller can expect that serialized TensorFlow graphs produced
    can be consumed by programs that are compiled with the TensorFlow library
    source code after (year, month, day).
  """
  return _FORWARD_COMPATIBILITY_DATE_NUMBER > _date_to_date_number(
      year, month, day)

@tf_export("compat.forward_compatibility_horizon")
@tf_contextlib.contextmanager
def forward_compatibility_horizon(year, month, day):
  """Context manager for testing forward compatibility of generated graphs.

  See [Version
  compatibility](https://tensorflow.org/guide/version_compat#backward_forward).

  To ensure forward compatibility of generated graphs (see `forward_compatible`)
  with older binaries, new features can be gated with:

  ```python
  if compat.forward_compatible(year=2018, month=08, date=01):
    generate_graph_with_new_features()
  else:
    generate_graph_so_older_binaries_can_consume_it()
  ```

  However, when adding new features, one may want to unittest it before
  the forward compatibility window expires. This context manager enables
  such tests. For example:

  ```python
  from tensorflow.python.compat import compat

  def testMyNewFeature(self):
    with compat.forward_compatibility_horizon(2018, 08, 02):
       # Test that generate_graph_with_new_features() has an effect
  ```

  Args:
    year:  A year (e.g., 2018). Must be an `int`.
    month: A month (1 <= month <= 12) in year. Must be an `int`.
    day:   A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an
      `int`.

  Yields:
    Nothing.
  """
  try:
    _update_forward_compatibility_date_number(datetime.date(year, month, day))
    yield
  finally:
    _update_forward_compatibility_date_number()
<commit_msg>compat: Update forward compatibility horizon to 2021-06-02<commit_after># Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utilities for API compatibility between TensorFlow release versions.

See [Version
Compatibility](https://tensorflow.org/guide/version_compat#backward_forward)
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import datetime
import os

from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util import tf_contextlib
from tensorflow.python.util.tf_export import tf_export

# This value changes every day with an automatic CL. It can be modified in code
# via `forward_compatibility_horizon()` or with the environment variable
# TF_FORWARD_COMPATIBILITY_DELTA_DAYS, which is added to the compatibility date.
_FORWARD_COMPATIBILITY_HORIZON = datetime.date(2021, 6, 2)
_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME = "TF_FORWARD_COMPATIBILITY_DELTA_DAYS"
_FORWARD_COMPATIBILITY_DATE_NUMBER = None

def _date_to_date_number(year, month, day):
  return (year << 9) | (month << 5) | day

def _update_forward_compatibility_date_number(date_to_override=None):
  """Update the base date to compare in forward_compatible function."""

  global _FORWARD_COMPATIBILITY_DATE_NUMBER

  if date_to_override:
    date = date_to_override
  else:
    date = _FORWARD_COMPATIBILITY_HORIZON
    delta_days = os.getenv(_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME)
    if delta_days:
      date += datetime.timedelta(days=int(delta_days))

  if date < _FORWARD_COMPATIBILITY_HORIZON:
    logging.warning("Trying to set the forward compatibility date to the past"
                    " date %s. This will be ignored by TensorFlow." % (date))
    return
  _FORWARD_COMPATIBILITY_DATE_NUMBER = _date_to_date_number(
      date.year, date.month, date.day)

_update_forward_compatibility_date_number()

@tf_export("compat.forward_compatible")
def forward_compatible(year, month, day):
  """Return true if the forward compatibility window has expired.

  See [Version
  compatibility](https://tensorflow.org/guide/version_compat#backward_forward).

  Forward-compatibility refers to scenarios where the producer of a TensorFlow
  model (a GraphDef or SavedModel) is compiled against a version of the
  TensorFlow library newer than what the consumer was compiled against. The
  "producer" is typically a Python program that constructs and trains a model
  while the "consumer" is typically another program that loads and serves the
  model.

  TensorFlow has been supporting a 3 week forward-compatibility window for
  programs compiled from source at HEAD.

  For example, consider the case where a new operation `MyNewAwesomeAdd` is
  created with the intent of replacing the implementation of an existing Python
  wrapper - `tf.add`.  The Python wrapper implementation should change from
  something like:

  ```python
  def add(inputs, name=None):
    return gen_math_ops.add(inputs, name)
  ```

  to:

  ```python
  from tensorflow.python.compat import compat

  def add(inputs, name=None):
    if compat.forward_compatible(year, month, day):
      # Can use the awesome new implementation.
      return gen_math_ops.my_new_awesome_add(inputs, name)
    # To maintain forward compatibility, use the old implementation.
    return gen_math_ops.add(inputs, name)
  ```

  Where `year`, `month`, and `day` specify the date beyond which binaries
  that consume a model are expected to have been updated to include the
  new operations. This date is typically at least 3 weeks beyond the date
  the code that adds the new operation is committed.

  Args:
    year:  A year (e.g., 2018). Must be an `int`.
    month: A month (1 <= month <= 12) in year. Must be an `int`.
    day:   A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an
      `int`.

  Returns:
    True if the caller can expect that serialized TensorFlow graphs produced
    can be consumed by programs that are compiled with the TensorFlow library
    source code after (year, month, day).
  """
  return _FORWARD_COMPATIBILITY_DATE_NUMBER > _date_to_date_number(
      year, month, day)

@tf_export("compat.forward_compatibility_horizon")
@tf_contextlib.contextmanager
def forward_compatibility_horizon(year, month, day):
  """Context manager for testing forward compatibility of generated graphs.

  See [Version
  compatibility](https://tensorflow.org/guide/version_compat#backward_forward).

  To ensure forward compatibility of generated graphs (see `forward_compatible`)
  with older binaries, new features can be gated with:

  ```python
  if compat.forward_compatible(year=2018, month=08, date=01):
    generate_graph_with_new_features()
  else:
    generate_graph_so_older_binaries_can_consume_it()
  ```

  However, when adding new features, one may want to unittest it before
  the forward compatibility window expires. This context manager enables
  such tests. For example:

  ```python
  from tensorflow.python.compat import compat

  def testMyNewFeature(self):
    with compat.forward_compatibility_horizon(2018, 08, 02):
       # Test that generate_graph_with_new_features() has an effect
  ```

  Args:
    year:  A year (e.g., 2018). Must be an `int`.
    month: A month (1 <= month <= 12) in year. Must be an `int`.
    day:   A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an
      `int`.

  Yields:
    Nothing.
  """
  try:
    _update_forward_compatibility_date_number(datetime.date(year, month, day))
    yield
  finally:
    _update_forward_compatibility_date_number()
<|endoftext|>


<commit_before>import pp

def helloworld():
    print 'hello world'

def parallelrun(job_server,numjobs):
    jobs=[]
    for n in range(numjobs):
        jobs.append(job_server.submit(helloworld,(),depfuncs=(),modules = (),globals=globals()))
    for job in jobs:
        job()
    job_server.print_stats()
    job_server.destroy()

if __name__ == '__main__':
    # job_server = pp.Server(ncpus=0,ppservers=("*",))
    job_server = pp.Server(ncpus=4)
    parallelrun(job_server,20)

<commit_msg>autodiscovery enabled on parallel test code<commit_after>import pp

def helloworld():
    print 'hello world'

def parallelrun(job_server,numjobs):
    jobs=[]
    for n in range(numjobs):
        jobs.append(job_server.submit(helloworld,(),depfuncs=(),modules = (),globals=globals()))
    for job in jobs:
        job()
    job_server.print_stats()
    job_server.destroy()

if __name__ == '__main__':
    job_server = pp.Server(ncpus=0,ppservers=("*",))
    # job_server = pp.Server(ncpus=4)
    parallelrun(job_server,20)

<|endoftext|>