from .ParserBase import ParserBase
class SlowRecoverAfterRLF(ParserBase):
    def __init__(self, shared_states):
        super().__init__(shared_states)
        self.reset_to_normal_state()
        self.have_sent_meas_report_to_current_cell = False
        self.trying_cell_dl_freq = None
        self.trying_cell_ul_freq = None
        self.trying_cell_id = None
        self.trying_cell_identity = None
        self.last_packet_timestamp_before_rlf = None
        self.just_switched = False

    def reset_to_normal_state(self):
        self.reestablishment_requested_on_rlf = False
        self.mac_rach_triggered_by_rlf = False
        self.mac_rach_attempt_succeeded = False
        self.connection_setup = False
        self.rrc_reconfiguration_started = False
        self.reestablishment_request_timestamp = None
        self.rrc_reestablishment_rejected = False
        self.mac_rach_connection_request_reason = None

    def act_on_rrc_connection_reestablishment_request(self, event):
        timestamp, _, fields = event
        if 'otherFailure' in fields['reestablishmentCause']:
            self.reestablishment_requested_on_rlf = True
            self.reestablishment_request_timestamp = timestamp
            self.last_packet_timestamp_before_rlf = fields['LastPDCPPacketTimestamp']

    def act_on_mac_rach_trigger(self, event):
        _, _, fields = event
        if fields['Reason'] == 'RLF'\
        and self.reestablishment_requested_on_rlf:
            self.mac_rach_triggered_by_rlf = True
        elif fields['Reason'] == 'CONNECTION_REQ'\
        and self.mac_rach_triggered_by_rlf:
            self.mac_rach_connection_request_reason = 'radio link failure'
        elif fields['Reason'] == 'CONNECTION_REQ'\
        and not self.mac_rach_triggered_by_rlf:
            self.mac_rach_connection_request_reason = 'connection setup'

    def act_on_mac_rach_attempt(self, event):
        _, _, fields = event
        if fields['Result'] == 'Success'\
        and (self.mac_rach_connection_request_reason == 'radio link failure'\
             or self.mac_rach_connection_request_reason == 'connection setup'):
            self.mac_rach_attempt_succeeded = True

    def act_on_rrc_serv_cell_info(self, event):
        _, _, fields = event
        self.trying_cell_dl_freq = fields['Downlink frequency']
        self.trying_cell_ul_freq = fields['Uplink frequency']
        self.trying_cell_id = fields['Cell ID']
        self.trying_cell_identity = fields['Cell Identity']

    def act_on_rrc_connection_setup(self, event):
        if self.mac_rach_attempt_succeeded:
            self.connection_setup = True

    def act_on_rrc_connection_reconfiguration(self, event):
        _, _, fields = event
        if fields['mobilityControlInfo'] == '0'\
        and self.connection_setup:
            self.rrc_reconfiguration_started = True

    def act_on_rrc_connection_reconfiguration_complete(self, event):
        timestamp, _, _ = event
        if self.rrc_reconfiguration_started:
            if self.mac_rach_connection_request_reason == 'radio link failure':
                if self.trying_cell_id == self.shared_states['last_serving_cell_id']:
                    print('Slow Recover After RLF (to prev serving cell) $ From: %s, To: %s'
                          ', Previous Cell Identity: %s, Current Cell Identity: %s'
                           % (self.reestablishment_request_timestamp, timestamp,
                              self.shared_states['last_serving_cell_identity'],
                              self.trying_cell_identity))
                else:
                    print('Slow Recover After RLF (to new cell) $ From: %s, To: %s'
                          ', Previous Cell Identity: %s, Current Cell Identity: %s'
                           % (self.reestablishment_request_timestamp, timestamp,
                              self.shared_states['last_serving_cell_identity'],
                              self.trying_cell_identity))
                self.just_switched = True
                self.shared_states['last_serving_cell_dl_freq'] = self.trying_cell_dl_freq
                self.shared_states['last_serving_cell_ul_freq'] = self.trying_cell_ul_freq
                self.shared_states['last_serving_cell_id'] = self.trying_cell_id
                self.shared_states['last_serving_cell_identity'] = self.trying_cell_identity
            elif self.mac_rach_connection_request_reason == 'connection setup':
                print('Connection Setup $')
            self.shared_states['reset_all'] = True

    def act_on_pdcp_packet(self, event):
        timestamp, _, _ = event
        if self.just_switched:
            print('Slow Recover After RLF PDCP Disruption $ From: %s, To: %s' % (self.last_packet_timestamp_before_rlf, timestamp))
            self.shared_states['reset_all'] = True
            self.just_switched = False

    def _act_on_rrc_connection_release(self, event):
        self.shared_states['reset_all'] = True

    action_to_events = {
        'rrcConnectionReestablishmentRequest' : act_on_rrc_connection_reestablishment_request,
        'LTE_MAC_Rach_Trigger' : act_on_mac_rach_trigger,
        'LTE_MAC_Rach_Attempt' : act_on_mac_rach_attempt,
        'rrcConnectionSetup' : act_on_rrc_connection_setup,
        'rrcConnectionReconfiguration' : act_on_rrc_connection_reconfiguration,
        'rrcConnectionReconfigurationComplete' : act_on_rrc_connection_reconfiguration_complete,
        'FirstPDCPPacketAfterDisruption' : act_on_pdcp_packet,
        'LTE_RRC_Serv_Cell_Info' : act_on_rrc_serv_cell_info,
        'rrcConnectionRelease' : _act_on_rrc_connection_release
    }

    def run(self, event):
        _, pkt_type, _ = event
        self.action_to_events.get(pkt_type, lambda self, event: None)(self, event)

    def reset(self):
        self.reset_to_normal_state()


# -*- coding: utf-8 -*-
import scrapy

class FinancespiderSpider(scrapy.Spider):
    name = 'financespider'
    allowed_domains = ['www.yellowpages.com.au']
    start_urls = ['https://www.yellowpages.com.au/search/listings?clue=financial+planners&locationClue=&lat=&lon=']

    def parse(self, response):
        items = response.xpath("//div[@class='search-contact-card call-to-actions-4 feedback-feature-on']")
        for item in items:
            email = item.xpath(".//a[contains(@href,'mailto')]/@data-email").get()
            business = item.xpath(".//a[@class='listing-name']/text()").get()
            yield {
                'Business Name':business,
                'Email': email,
                'User-Agent': response.request.headers['User-Agent']
            }

        next_page = response.xpath("//a[text()='Next »']/@href").get()
        if next_page:
            print("**********************",next_page)
            next_abs_url = response.urljoin(next_page)
            print("****", next_abs_url)
            yield response.follow(
                url= next_abs_url,
                callback= self.parse,
                headers= {
                    'User-Agent':"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36"
                }
            )


"""
Game controller input for Kivy.

Open game controllers as they become available, expose with full SDL2 API.
"""

# Kivy must open so we can find the symbols,
# or kivyjoy must explicitly link with the same
# kivyjoy2 shared library as kivy.
import kivy.app

from kivy.event import EventDispatcher
from kivy.properties import DictProperty

# Special version of (pysdl2-cffi) that doesn't explictly link
# to a particular version on OSX. It could link to the SDL2
# bundled wih kivy explicitly.
import kivyjoy

JOYSTICK_EVENTS = (
    kivyjoy.JoyDeviceEvent,
    kivyjoy.JoyAxisEvent,
    kivyjoy.JoyHatEvent,
    kivyjoy.JoyBallEvent,
    kivyjoy.JoyButtonEvent,
    kivyjoy.ControllerDeviceEvent,
    kivyjoy.ControllerAxisEvent,
    kivyjoy.ControllerButtonEvent,
)

class KivyController(EventDispatcher):
    """
    Manage game controllers.

    Game controllers are assigned to and removed from the controllers list at the
    index of their id (so controllers[n] could be None if one was removed)
    """
    controllers = DictProperty()

    def __init__(self):
        self._handle = kivyjoy.ffi.new_handle(self.event)

    def install(self):
        """
        Attach to kivyjoy2 event loop
        """
        # will generate controllerdeviceadded events for existing sticks when first init
        kivyjoy.init(kivyjoy.INIT_GAMECONTROLLER|kivyjoy.INIT_JOYSTICK)
        kivyjoy.addEventWatch(kivyjoy.lib.pysdl2_event_filter, self._handle)

    def event(self, event):
        """
        Handle wrapped kivyjoy2 event
        """
        event = kivyjoy.Event(event).unwrapEvent()
        if isinstance(event, JOYSTICK_EVENTS):
            print(event)

        if isinstance(event, kivyjoy.ControllerDeviceEvent):
            if event.type == kivyjoy.CONTROLLERDEVICEADDED:
                j = kivyjoy.gameControllerOpen(event.which)
                self.controllers[event.which] = j
            elif event.type == kivyjoy.CONTROLLERDEVICEREMOVED:
                j = self.controllers.pop(event.which)
                j.gameControllerClose()

        # Just GameController for now...
        # If a controller is only a joystick, try adding a third party mapping
        # to make it show up as a GameController.

        return 0


# -*- coding: UTF-8 -*-
from __future__ import unicode_literals, print_function, division
from datetime import datetime
from pprint import pprint
import common

RETRIEVE_COLUMNS = {
    0: ('date', lambda v: datetime.strptime(v, '%Y%m%d').date()),
    1: ('name', lambda v: v),
    2: ('key', lambda v: v),
    3: ('module', lambda v: v),
    4: ('os', lambda v: v.lower()),
    5: ('da', int),
    6: ('di', int)
}

def get_data_key(code_name, module, os):
    return '{}:{}@{}'.format(code_name, module, os)

def read_lines_from_worksheet(worksheet):
    def is_first_row(row):
        return row[1].value == 'App_Name' or row[2].value == 'App_Key'

    lines = []
    for row in worksheet.rows:
        if is_first_row(row):
            continue
        line = dict(
            (name_and_normalizer[0], name_and_normalizer[1](row[column_index].value))
            for column_index, name_and_normalizer in RETRIEVE_COLUMNS.items()
        )
        lines.append(line)
    return lines

def group_by_line_key(lines):
    data = {}
    for line in lines:
        data.setdefault(get_data_key(line['name'], line['module'], line['os']), []).append(line)
    for lines in data.values():
        lines.sort(key=lambda v: v['date'])
    return data

def main():
    filename = common.get_filename()
    workbook = common.get_workbook(filename)
    print(workbook.get_sheet_names())
    worksheets = workbook.worksheets
    assert len(worksheets) == 1, 'support only one worksheet'
    lines = read_lines_from_worksheet(worksheets[0])
    app_data = group_by_line_key(lines)
    for line in app_data.values()[5]:
        pprint(line)

if __name__ == '__main__':
    main()


from __future__ import print_function
from future.utils import iteritems, itervalues

import contextlib
import errno
import json
import os
import shutil
import subprocess
import sys
import textwrap

from six.moves import cStringIO as StringIO

import attr

from google.protobuf import json_format as jsonpb

from PB.recipe_engine.recipes_cfg import RepoSpec
from recipe_engine import __path__ as RECIPE_ENGINE_PATH
from recipe_engine.internal.fetch import GitBackend, CommitMetadata
from recipe_engine.internal.simple_cfg import RECIPES_CFG_LOCATION_REL
from recipe_engine.internal.test.test_util import filesystem_safe

ROOT_DIR = os.path.dirname(RECIPE_ENGINE_PATH[0])
DEVNULL = open(os.devnull, 'w')
REAL_STDERR = sys.stderr  # capture stderr before tests potentially mess with it

def _get_suite(buf, default, indent='  '):
  """This is a helper function to extract a python code suite from a StringIO
  object.

  This will dedent the buffer's content, split it into lines, and then re-indent
  it by the amount indicated.

  Args:
    * buf (StringIO) - The buffer to take the content from.
    * default (str) - The content to use if `buf` is empty.
    * indent (str) - The string to prepend to all de-indented lines.

  Returns the transformed string.
  """
  value = textwrap.dedent(buf.getvalue() or default).strip('\n')
  return '\n'.join(indent + l for l in value.splitlines())

@attr.s
class FakeRecipeRepo(object):
  """Manipulates a recipe repo on disk (as a git repository)."""

  # The FakeRecipeDeps which owns this repo.
  fake_recipe_deps = attr.ib()  # type: FakeRecipeDeps

  # The name of this repo.
  name = attr.ib()  # type: str

  # The absolute path on disk to the root of this repo.
  path = attr.ib()

  # The GitBackend for this FakeRecipeRepo.
  backend = attr.ib(default=attr.Factory(
      lambda self: GitBackend(self.path, None),
      takes_self=True))

  @contextlib.contextmanager
  def edit_recipes_cfg_pb2(self):
    """Context manager for read/modify/write'ing the recipes.cfg file in this
    repo.

    Usage:

        with repo.edit_recipes_cfg_pb2() as pb:
          pb.deps['some_repo'].revision = 'abcdefg'

    Yields a recipes_cfg_pb2.RepoSpec object decoded from the current state of
    the recipes.cfg file. Any modifications done to this object will be recorded
    back to disk.
    """
    spec = self.recipes_cfg_pb2
    yield spec
    cfg_path = os.path.join(self.path, RECIPES_CFG_LOCATION_REL)
    with open(cfg_path, 'w') as fil:
      fil.write(jsonpb.MessageToJson(spec, preserving_proto_field_name=True))

  @property
  def recipes_cfg_pb2(self):
    """Returns the current recipes_cfg_pb2.RepoSpec decoded from the recipes.cfg
    file in this repo."""
    cfg_path = os.path.join(self.path, RECIPES_CFG_LOCATION_REL)
    with open(cfg_path, 'r') as fil:
      return jsonpb.Parse(fil.read(), RepoSpec())

  @contextlib.contextmanager
  def write_file(self, path):
    """Context manager for writing a file inside the repo.

    Any missing directories will be automatically created.

    Usage:

      with repo.write_file('relative/path/filename.ext') as fil:
        fil.write('''
          Content is de-indented.
          So you don't have ugly tests.
        ''')

    Args:
      * path (str) - Path relative to the root of the repo of the file to write.

    Yields a StringIO object which you may write to. For convenience, the data
    written to this StringIO object will be `textwrap.dedent`d to allow nice
    inline strings in test files.
    """
    full_path = os.path.join(self.path, path)
    try:
      os.makedirs(os.path.dirname(full_path))
    except OSError as ex:
      if ex.errno != errno.EEXIST:
        raise

    buf = StringIO()
    yield buf
    with open(full_path, 'w') as fil:
      fil.write(textwrap.dedent(buf.getvalue()))

  def read_file(self, path):
    """Reads a file inside the repo.

    Args:
      * path (str) - Path relative to the root of the repo of the file to read.

    Returns the file contents as a str. If there is an error reading the file
    this will return None.
    """
    full_path = os.path.join(self.path, path)
    try:
      with open(full_path, 'r') as fil:
        return fil.read()
    except:  # pylint: disable=bare-except
      return None

  def exists(self, path):
    """Checks to see if a path exists in the repo.

    Args:
      * path (str) - Path relative to the root of the repo to check.

    Returns True iff the item exists.
    """
    return os.path.exists(os.path.join(self.path, path))

  def is_dir(self, path):
    """Checks to see if a path is a directory in the repo.

    Args:
      * path (str) - Path relative to the root of the repo to check.

    Returns True iff the item exists and is a directory.
    """
    return os.path.isdir(os.path.join(self.path, path))

  def is_file(self, path):
    """Checks to see if a path is a file in the repo.

    Args:
      * path (str) - Path relative to the root of the repo to check.

    Returns True iff the item exists and is a regular file.
    """
    return os.path.isfile(os.path.join(self.path, path))

  @attr.s(slots=True)
  class WriteableRecipe(object):
    """Yielded from the `write_recipe` method. Used to generate a recipe on
    disk.

    This contains two string buffers which you may write to, RunSteps and
    GenTests. These represent the body of the RunSteps and GenTests functions in
    the recipe, respectively. Both buffers will be dedent'd as described in
    `write_file`. If you do not write to them, the function bodies will be
    generated with default values:

        RunSteps: pass
        GenTests: yield api.test('basic')

    The RunSteps_args attribute is a list of argument names to be used in the
    RunSteps function definition. It defaults to ['api'] and should generally
    only be extended.

    The imports attribute is a list of 'import' lines you want at the top of the
    recipe. These lines should be an entire valid python import line (i.e
    starting with `import` or `from`).

    The DEPS attribute corresponds exactly to the recipe DEPS field, and you may
    put a python list or dict here, depending on how you want your recipe's DEPS
    to look. The DEPS comes, by default, as a list containing the
    'recipe_engine/step' module. This list may be appended to, or replaced
    entirely (with assignment), if you choose.

    The PROPERTIES attribute is a Python expression to assign to the recipe
    PROPERTIES field.

    The `expectation` dictionary can be populated with expectation JSON data to
    write to disk. The key is the test name (e.g. "basic", "test_on_luci", etc.)
    and the value is list of dicts (i.e. the expectation format). It defaults to
    a single expectation for the test "basic" which has an empty (`None`)
    final result (i.e. the RunSteps function returned None without running
    steps).
    """
    base_path = attr.ib()

    imports = attr.ib(factory=list)
    RunSteps = attr.ib(factory=StringIO)
    RunSteps_args = attr.ib(factory=lambda: ['api'])
    GenTests = attr.ib(factory=StringIO)
    DEPS = attr.ib(factory=lambda: ['recipe_engine/step'])
    PROPERTIES = attr.ib(default='{}')
    ENV_PROPERTIES = attr.ib(default='None')
    expectation = attr.ib(factory=lambda: {
      'basic': [{'name': '$result'}],
    })

    @property
    def path(self):
      """Returns the repo-relative path to the recipe file."""
      return self.base_path + '.py'

    @property
    def expect_path(self):
      """Returns the repo-relative path to the recipe's expectation dir."""
      return self.base_path + '.expected'

  @contextlib.contextmanager
  def write_recipe(self, name_or_module, name=None):
    """Context manager for writing a recipe to the disk in this testing repo.

    Overwrites any existing recipe. This can be called like:

        write_recipe('recipe_name')
        write_recipe('module_name', 'recipe_name')

    If you need to write a malformed recipe, or one with additional top-level
    functions, please use `write_file` to directly write the entire recipe file.

    Usage:

        with repo.write_recipe('my_recipe') as recipe:
          recipe.DEPS.append('my_module')
          recipe.RunSteps.write('''
            api.step('stepname', ['echo', 'something'])
            api.my_module.cool_function()
          ''')

    Args:
      * name_or_module (str) - If the only argument, this is the name of the
        recipe to write. If provided in tandem with `name`, then this is the
        module to write the recipe under.
      * name (str|None) - If provided, this is the name of the recipe, and
        `name_or_module` is the name of the recipe module.

    Yields a WriteableRecipe object. You may manipulate the DEPS, GenTests and
    RunSteps members to craft the recipe you want for your test. See
    WriteableRecipe for details.
    """
    if name:
      base_path = os.path.join('recipe_modules', name_or_module, name)
    else:
      base_path = os.path.join('recipes', name_or_module)

    recipe = self.WriteableRecipe(base_path)
    yield recipe

    dump = self.fake_recipe_deps._ambient_toplevel_code_dump()

    with self.write_file(base_path + '.py') as buf:
      buf.write(textwrap.dedent('''
        {imports}

        {ambient_toplevel_code}

        DEPS = {DEPS!r}

        PROPERTIES = {PROPERTIES}
        ENV_PROPERTIES = {ENV_PROPERTIES}

        def RunSteps({RunSteps_args}):
        {RunSteps}

        def GenTests(api):
        {GenTests}
      ''').format(
          imports='\n'.join(recipe.imports),
          ambient_toplevel_code=dump,
          DEPS=recipe.DEPS,
          PROPERTIES=recipe.PROPERTIES,
          ENV_PROPERTIES=recipe.ENV_PROPERTIES,
          RunSteps_args=', '.join(recipe.RunSteps_args),
          RunSteps=_get_suite(recipe.RunSteps, 'pass'),
          GenTests=_get_suite(
              recipe.GenTests, "yield api.test('basic')")))

    for test_name, expectation in iteritems(recipe.expectation):
      test_name = filesystem_safe(test_name)
      expect_path = os.path.join(base_path + '.expected', test_name + '.json')
      with self.write_file(expect_path) as buf:
        json.dump(expectation, buf, indent=2)
    self.recipes_py('doc')

  @attr.s(slots=True)
  class WriteableModule(object):
    """Yielded from the `write_module` method. Used to generate a recipe module
    on disk.

    This contains three string buffers which you may write to, `api`, `test_api`
    and `config`. All buffers will be dedent'd as described in `write_file`.

      * `api` represents the body of the {modname.title}Api class inside of
        `api.py`. If not written to, then the body of this class will be `pass`.
      * `test_api` represents the body of the {modname.title}TestApi class
         inside of `test_api.py`. If not written to, then the body of this class
         will be `pass`.
      * `config` represents the body of `config.py`. If not written to then
        `config.py` will not be written to disk.

    The imports attribute is a list of 'import' lines you want at the top of the
    module files. These lines should be an entire valid python import line (i.e
    starting with `import` or `from`).

    The DEPS attribute corresponds exactly to the recipe module's DEPS field,
    and you may put a python list or dict here, depending on how you want your
    recipe's DEPS to look. The DEPS comes, by default, as a list containing the
    'recipe_engine/step' module. This list may be appended to, or replaced
    entirely (with assignment), if you choose.

    The PROPERTIES attribute is a Python expression to assign to the module's
    PROPERTIES field.

    The DISABLE_STRICT_COVERAGE maps directly to the same-named option in
    `__init__.py`.
    """
    path = attr.ib()  # base path of the module folder

    api = attr.ib(factory=StringIO)
    test_api = attr.ib(factory=StringIO)
    config = attr.ib(factory=StringIO)
    imports = attr.ib(factory=list)
    DEPS = attr.ib(factory=lambda: ['recipe_engine/step'])
    PROPERTIES = attr.ib(default='{}')
    GLOBAL_PROPERTIES = attr.ib(default='None')
    ENV_PROPERTIES = attr.ib(default='None')
    WARNINGS = attr.ib(factory=list)
    DISABLE_STRICT_COVERAGE = attr.ib(default=False)

  @contextlib.contextmanager
  def write_module(self, mod_name):
    """Context manager for writing a recipe module to the disk in this testing
    repo.

    Overwrites any existing recipe module (i.e. the existing module, if any,
    will be removed).

    If you need to write a malformed recipe module, or one with additional
    customizations, please use this method, and then use `write_file` to
    overwrite whichever files need to be adjusted.

    Args:
      * mod_name (str) - The name of the module to write.

    Yields a WriteableModule object. You may manipulate its various fields to
    craft the recipe module you want for your test. See WriteableModule for
    details.
    """
    base = os.path.join('recipe_modules', mod_name)

    mod = self.WriteableModule(base)
    yield mod

    if self.exists(base):
      shutil.rmtree(os.path.join(self.path, base))

    with self.write_file(os.path.join(base, '__init__.py')) as buf:
      buf.write('''
      {imports}

      DEPS = {DEPS!r}

      WARNINGS = {WARNINGS!r}

      DISABLE_STRICT_COVERAGE = {DISABLE_STRICT_COVERAGE!r}

      PROPERTIES = {PROPERTIES}
      GLOBAL_PROPERTIES = {GLOBAL_PROPERTIES}
      ENV_PROPERTIES = {ENV_PROPERTIES}
      '''.format(
          imports='\n'.join(mod.imports),
          DEPS=mod.DEPS,
          WARNINGS = mod.WARNINGS,
          DISABLE_STRICT_COVERAGE=mod.DISABLE_STRICT_COVERAGE,
          PROPERTIES=mod.PROPERTIES,
          GLOBAL_PROPERTIES=mod.GLOBAL_PROPERTIES,
          ENV_PROPERTIES=mod.ENV_PROPERTIES,
      ))

    dump = self.fake_recipe_deps._ambient_toplevel_code_dump()

    with self.write_file(os.path.join(base, 'api.py')) as buf:
      buf.write(textwrap.dedent('''
        from recipe_engine.recipe_api import RecipeApi

        {imports}

        {ambient_toplevel_code}

        class {mod_name}Api(RecipeApi):
        {api}
      ''').format(
          imports='\n'.join(mod.imports),
          ambient_toplevel_code=dump,
          mod_name=mod_name.title().replace(' ', ''),
          api=_get_suite(mod.api, 'pass')))

    with self.write_file(os.path.join(base, 'test_api.py')) as buf:
      buf.write(textwrap.dedent('''
        from recipe_engine.recipe_test_api import RecipeTestApi

        {imports}

        {ambient_toplevel_code}

        class {mod_name}Api(RecipeTestApi):
        {test_api}
      ''').format(
          imports='\n'.join(mod.imports),
          ambient_toplevel_code=dump,
          mod_name=mod_name.title().replace(' ', ''),
          test_api=_get_suite(mod.test_api, 'pass')))

    config_body = _get_suite(mod.config, '', indent='')
    if config_body:
      with self.write_file(os.path.join(base, 'config.py')) as buf:
        buf.write(textwrap.dedent('''
          from recipe_engine.config import ConfigGroup, ConfigList, Dict, List
          from recipe_engine.config import Set, Single, config_item_context

          {imports}

          {config_body}
        ''').format(
            imports='\n'.join(mod.imports),
            config_body=config_body,
        ))

  def add_dep(self, *depnames):
    """Adds new repo-level dependencies to this repo.

    The recipes_cfg_pb2 file will be updated to contain all the new entries;
    they'll point to the current HEAD version of the repos.

    Args:
      * depnames (List[str]) - The names of the other repos to depend on. These
        must already have been created with `RecipeDeps.add_repo`.
    """
    with self.edit_recipes_cfg_pb2() as pkg_pb:
      for depname in depnames:
        dep_repo = self.fake_recipe_deps.repos[depname]
        dep_entry = pkg_pb.deps[depname]
        dep_entry.url = 'file://' + dep_repo.path
        dep_entry.branch = 'refs/heads/main'
        dep_entry.revision = dep_repo.backend.commit_metadata('HEAD').revision

  def recipes_py(self, *args, **kwargs):
    """Runs `recipes.py` in this repo with the given args, just like a user
    might run it.

    Args:
      * args (List[str]) - the arguments to pass to recipes.py.

    Kwargs:
      * env (Dict[str, str]) - Extra environment variables to set while invoking
        recipes.py.
      * py3 (bool) - Instruct recipe to run with python3 interpreter.

    Returns (output, retcode) where 'output' is the combined stdout/stderr from
    the command and retcode it's return code.
    """
    env = os.environ.copy()
    env.update(kwargs.pop('env', {}))
    proc = subprocess.Popen(
        ('python3', 'recipes.py') + args,
        cwd=self.path,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        env=env,
        text=True)
    output, _ = proc.communicate()
    return output, proc.returncode

  class TestCommitMetadata(CommitMetadata):
    """Commit metadata for a git commit.

    Identical to `fetch.CommitMetadata`, except that it has a helper function
    to make writing autoroller tests less tedious.
    """
    def as_roll_info(self):
      """Returns a dict of author_email, message_lines and revision which
      is JSON serializable.

      In particular, message_lines is a list instead of a tuple.
      """
      return {
        'author_email': self.author_email,
        'message_lines': list(self.message_lines),
        'revision': self.revision,
      }

  def commit(self, msg,
             author_name='Phinley Pfeiffer',
             author_email='ph.pf@example.com'):
    """Adds all files in the repo, then commits it with the given message.

    Returns a TestCommitMetadata object describing the commit we just created.
    """
    # pylint: disable=protected-access
    self.backend._git('add', '.')
    self.backend._git(
      '-c', 'user.name='+author_name,
      '-c', 'user.email='+author_email,
      'commit', '--allow-empty', '-m', msg)

    return self.TestCommitMetadata(
      **self.backend.commit_metadata('HEAD')._asdict())

@attr.s
class FakeRecipeDeps(object):
  """FakeRecipeDeps is a heavyweight testing object which controls a collection
  of git repos on disk.

  Every FakeRecipeDeps has a 'main' repo. This is analogous to the user-facing
  recipe repo that you might run recipes from (i.e. it has deps on 'upstream'
  repos, including, but not limited to, the recipe engine repo).

  When you create a new FakeRecipeDeps, it auto-creates this main repo with
  a dependency on the recipe_engine (the repo you're reading this from).

  You can add additional repos with the add_repo method, and create dependencies
  between repos with the 'FakeRecipeRepo.add_dep' method.
  """

  # _root will contain:
  #   * sources/ - All non-main repos are created here, with their name
  #     as a subfolder.
  #   * main/ - The main repo is created here
  #   * main/.recipe_deps - The .recipe_deps folder of the main repo.
  _root = attr.ib()

  # A map of repo_name -> FakeRecipeRepo
  repos = attr.ib(factory=dict)

  # A list of textwrap.deindent-able python snippets which will be injected into
  # every recipe, module api and test_api written with this FakeRecipeDeps.
  #
  # This is useful to add helper methods and imports which are implicitly
  # available everywhere in the test.
  ambient_toplevel_code = attr.ib(factory=list)

  def _ambient_toplevel_code_dump(self):
    return '\n'.join(map(textwrap.dedent, self.ambient_toplevel_code))

  ENGINE_REVISION = None
  @classmethod
  def _get_engine_revision(cls):
    if not cls.ENGINE_REVISION:
      if subprocess.call(['git', 'diff-index', '--quiet', 'HEAD', '--']):
        print('*' * 6, file=REAL_STDERR)
        print(textwrap.dedent('''
        WARNING: Tests may rely on current recipe engine repo, but you have
        un-committed changes. If you see unexpected behavior in the tests please
        try committing your changes to the engine repo first and then running
        the tests again.
        ''').lstrip(), end=' ', file=REAL_STDERR)
        print('*' * 6, file=REAL_STDERR)
        print(file=REAL_STDERR)
        REAL_STDERR.flush()

      cls.ENGINE_REVISION = subprocess.check_output(
          ['git', 'rev-parse', 'HEAD'], text=True).strip()
    return cls.ENGINE_REVISION

  def _create_repo(self, name, path):
    """Creates a recipe repo with the given name at the given path.

    This generates an `infra/config/recipes.cfg` with a file:// dependency on
    the current recipe engine, repo_name set to $name.

    Returns the commit of the created repo.
    """
    assert isinstance(name, str)
    assert name not in self.repos, (
      'duplicate repo_name: %r' % (name,))
    os.makedirs(path)
    subprocess.check_call(
        ['git', 'init', '-b', 'main'], cwd=path, stdout=DEVNULL)
    cfg_path = os.path.join(path, RECIPES_CFG_LOCATION_REL)
    os.makedirs(os.path.dirname(cfg_path))
    with open(cfg_path, 'w') as fil:
      json.dump(
          {
              'api_version': 2,
              'repo_name': name,
              'deps': {
                  'recipe_engine': {
                      'url': 'file://' + ROOT_DIR,
                      'branch': 'HEAD',
                      'revision': self._get_engine_revision(),
                  },
              },
          }, fil)
    readme_path = os.path.join(path, 'README.recipes.md')
    readme_str = ('<!--- AUTOGENERATED BY `./recipes.py test train` -->\n'
                 '# Repo documentation for [main]()\n## Table of Contents')
    with open(readme_path, 'w') as f:
      f.write(readme_str)
    shutil.copy(os.path.join(ROOT_DIR, 'recipes.py'), path)
    subprocess.check_call(['git', 'add', '.'], cwd=path, stdout=DEVNULL)
    subprocess.check_call(['git', 'commit', '-m', 'init '+name], cwd=path,
                          stdout=DEVNULL)
    self.repos[name] = FakeRecipeRepo(self, name, path)
    return subprocess.check_output(
      ['git', 'rev-parse', 'HEAD'], cwd=path).strip()

  def __attrs_post_init__(self):
    """Makes a new RecipeDeps temp folder on disk with a single (main) repo
    called 'main' which has no dependencies."""
    self._create_repo('main', os.path.join(self._root, 'main'))

  @property
  def recipe_deps_path(self):
    """Returns the absolute path to the `.recipe_deps` folder of the main repo.
    """
    return os.path.join(self.main_repo.path, '.recipe_deps')

  def add_repo(self, name, detached=False):
    """Adds a new repo to the RecipeDeps.

    This is created in `{FakeRecipeDeps.recipe_deps_path}/{name}`.

    This adds a dependency of the main repo onto this new repo, AND COMMITS THE
    CHANGE TO recipes.cfg.

    Returns created FakeRecipeRepo.
    """
    assert isinstance(name, str)
    self._create_repo(name, os.path.join(self._root, 'sources', name))

    if not detached:
      self.main_repo.add_dep(name)
      self.main_repo.commit('add dep on ' + name)
    return self.repos[name]

  @property
  def main_repo(self):
    """Returns the main FakeRecipeRepo for this FakeRecipeDeps."""
    return self.repos['main']


import setuptools

def get_content(*filename):
    """ Gets the content of a file and returns it as a string
    Args:
        filename(str): Name of file to pull content from
    Returns:
        str: Content from file
    """
    content = ""
    for file in filename:
        with open(file, "r") as full_description:
            content += full_description.read()
    return content

setuptools.setup(
    name = "pyerewolf",
    version = "0.0.1",
    author = "Kieran Wood",
    author_email = "kieran@canadiancoding.ca",
    description = "A web version of the werewolf game implemented in python using Flask.",
    long_description = get_content("README.md", "CHANGELOG.md"),
    long_description_content_type = "text/markdown",
    project_urls = {
        "User Docs" :  "https://kieranwood.ca/pyerewolf",
        "Source" :     "https://github.com/Descent098/pyerewolf",
    },
    include_package_data = True,
    packages = setuptools.find_packages(),
    classifiers = [
        "Programming Language :: Python :: 3",
        "Operating System :: OS Independent",
        "Development Status :: 1 - Planning"
    ],
)


import numpy as np
from collections import Counter
import matplotlib.pyplot as plt

class DecisionTreeNode(object):

    def __init__(self, indices):
        self.indices = indices
        self.leftChild = None
        self.rightChild = None
        self.leaf = False

    def setSplit(self, splitFeat, splitVal, informationGain, nObsAtSplit):
        self.splitFeat = splitFeat
        self.splitVal = splitVal
        self.informationGain = informationGain
        self.nObsAtSplit = nObsAtSplit

    def setLeft(self, leftChild):
        self.leftChild = leftChild

    def setRight(self, rightChild):
        self.rightChild = rightChild

    def setLeaf(self, classes):
        self.leaf = True

        counts = Counter(classes)

        self.maxClass = counts.most_common(1)[0][0]
        self.percentMax = 1.0 * \
            counts.most_common(1)[0][1] / sum(counts.values())

class DecisionTree(object):

    def __init__(self, minIG=None, nPointsLeaf=1,
                 nFeaturesToSplit=None):
        self.minIG = minIG
        self.nPointsLeaf = nPointsLeaf
        self.root = None
        self.nFeaturesToSplit = nFeaturesToSplit

    def fit(self, XTrain, yTrain):
        '''
        fit takes in an array of training data with n observations and k
        features and a 1-d array of labels for the training data. It fits a
        decision tree to the training data.

        Input: XTrain as a numpy array shape (n, k) where n is the number of
                observations and k is the number of features
             : yTrain as a 1-d numpy array with n elements

        Output: None
        '''
        self.XTrain = XTrain
        self.yTrain = yTrain
        self.nFeatures = self.XTrain.shape[1]
        self.nObs = self.XTrain.shape[0]

        self.splitCandidates = {}

        for i in xrange(self.nFeatures):
            x = self.XTrain[:, i]
            xUnique = np.unique(x)
            XUniqueAndSorted = np.sort(xUnique)
            self.splitCandidates[i] = XUniqueAndSorted

        self.root = DecisionTreeNode(indices=np.array(range(self.nObs)))
        queue = [self.root]

        while len(queue) > 0:
            currNode = queue.pop(0)
            indices = currNode.indices
            split = self.chooseSplit_(indices, self.nFeaturesToSplit)

            if split is not None:
                splitFeat, splitVal, informationGain, nObsAtSplit = split
                currNode.setSplit(splitFeat, splitVal, informationGain,
                                  nObsAtSplit)
                leftIndices = indices[np.where(
                    XTrain[indices, splitFeat] <= splitVal)[0]]
                rightIndices = indices[np.where(
                    XTrain[indices, splitFeat] > splitVal)[0]]

                leftChild = DecisionTreeNode(indices=leftIndices)
                rightChild = DecisionTreeNode(indices=rightIndices)

                currNode.setLeft(leftChild)
                currNode.setRight(rightChild)

                queue.append(leftChild)
                queue.append(rightChild)
            else:
                currNode.setLeaf(self.yTrain[indices])

    def gini_(self, classes):
        '''
        Calculates the Gini Impurity metric for a given set of class labels
        (https://en.wikipedia.org/wiki/Decision_tree_learning#Gini_impurity)

        Input: classes as a numpy array of class labels
        Output: Gini impurity defined as SUM over i [p_i * (1 - p_i)]
        '''

        class_labels = np.unique(classes)
        n_data_points = len(classes)

        probs = [1.0 * np.sum(classes == i) /
                 n_data_points for i in class_labels]
        gini = 0

        for p_i in probs:
            gini += p_i * (1 - p_i)

        return gini

    def informationGain_(self, classesBefore, classesAfter):
        '''
        Calculates the information gain from splitting a set of class labels
        into two different sets. Information gain is the decrease in Gini
        Impurity achieved by splitting the class labels.

        Input: classesBefore is a numpy array of the classes, before splitting
             : classesAfter is a list of two numpy arrays. Each numpy array
                contains the class labels of one split of the original class
                labels
        Output: information gain, defined as the Gini impurity of the class
                labels prior to splitting, minus the weighted average of Gini
                impurities of the splits
        '''

        splitA = classesAfter[0]
        splitB = classesAfter[1]

        nPreSplit = len(classesBefore)
        nSplitA = len(splitA)
        nSplitB = len(splitB)

        weightSplitA = 1.0 * nSplitA / nPreSplit
        weightSplitB = 1.0 * nSplitB / nPreSplit

        giniPreSplit = self.gini_(classesBefore)
        giniSplitA = self.gini_(splitA)
        giniSplitB = self.gini_(splitB)

        giniSplits = weightSplitA * giniSplitA + weightSplitB * giniSplitB

        informationGain = giniPreSplit - giniSplits

        return informationGain

    def chooseSplit_(self, indices, nFeaturesToSplit=None):
        '''
        Input: numpy array of indices to consider for a given split
        Output: list  - First element: is the feature to split on
                      - Second: is the value on which to split
                      - Third: is Information Gain at split
                      - Fourth: is number of data points at the split
        '''
        XAtSplit = self.XTrain[indices, :]
        yAtSplit = self.yTrain[indices]

        maxInformationGain = 0
        splitFeat = None
        splitVal = None

        if len(indices) <= self.nPointsLeaf:
            return None

        if nFeaturesToSplit is None:
            featuresToTry = range(self.nFeatures)
        else:
            nFeatures = self.XTrain.shape[1]
            featuresToTry = np.random.choice(range(nFeatures),
                                             size=nFeaturesToSplit,
                                             replace=False)

        # loop over all features being checked for splits
        for feat in featuresToTry:
            # array of unique, sorted values to try splitting on
            splitsToTry = self.splitCandidates[feat]

            # loop over all candidate splits for that feature
            for split in splitsToTry:

                indicesLeft = np.where(XAtSplit[:, feat] <= split)[0]
                indicesRight = np.where(XAtSplit[:, feat] > split)[0]

                classes = yAtSplit
                classesLeft = yAtSplit[indicesLeft]
                classesRight = yAtSplit[indicesRight]

                informationGain = self.informationGain_(classes, [classesLeft,
                                                                  classesRight]
                                                        )

                if informationGain > maxInformationGain:
                    maxInformationGain = informationGain
                    splitFeat = feat
                    splitVal = split

        if maxInformationGain == 0:
            return None

        return [splitFeat, splitVal, maxInformationGain, len(indices)]

    def predict(self, X):
        '''
        Predicts class labels for a given input dataset

        Input: X as numpy array with (n, k) shape where n
                is the number of observations and k is the
                number of features
        Output: predictions as n x 2 numpy array --
                first column are the predicted class labels
                    corresponding to each row of X
                second column is the degree of certainty of the
                    prediction, defined as the percentage of the
                    labels in the leaf that match the most common
                    class
        '''
        preds = np.zeros([X.shape[0], 2])

        for i, x in enumerate(X):
            preds[i, :] = self.predictOne(x)

        return preds

    def predictOne(self, x):
        '''
        Predicts class label for one input row

        Input: x as a (1,k) numpy array where k is the number
            of features
        Output:
            predictions as a (2, ) numpy array
            first column is the predicted label
            second column is the degree of certainty of the
                prediction, defined as the percentage of the
                labels in the leaf that match the most common
                class
        '''

        currNode = self.root

        while not currNode.leaf:
            splitFeat = currNode.splitFeat
            splitVal = currNode.splitVal

            if x[splitFeat] <= splitVal:
                currNode = currNode.leftChild
            else:
                currNode = currNode.rightChild

        return np.array([currNode.maxClass, currNode.percentMax])

if __name__ == "__main__":
    x = np.arange(0, 1000) / 1000.
    x2 = x.copy()
    y = x.copy() + np.random.randn(1000) / 30
    y2 = x.copy() + 0.25 + np.random.randn(1000) / 30

    X = np.vstack([np.hstack([x, x2]), np.hstack([y, y2])]).T
    y = np.array([0] * 1000 + [1] * 1000)

    dt = DecisionTree()
    dt.fit(X, y)


"""

                            Cross-platform programming
             Laboratory work 2 "Simple CLI calculator with MVC model"
                             Anton Kosenko IT-ZP01

"""

class Model:

    def __init__(self):
        pass
        self.previous_value = ''
        self.value = ''
        self.operator = ''

    def calculate(self):
        operation = input()

        number_1 = int(input('Enter your first number: '))
        number_2 = int(input('Enter your second number: '))

        # Addition
        if operation == '+':
            print('{} + {} = '.format(number_1, number_2))
            print(number_1 + number_2)
        # Subtraction
        elif operation == '-':
            print('{} - {} = '.format(number_1, number_2))
            print(number_1 - number_2)

        # Multiplication
        elif operation == '*':
            print('{} * {} = '.format(number_1, number_2))
            print(number_1 * number_2)

        # Division
        elif operation == '/':
            print('{} / {} = '.format(number_1, number_2))
            print(number_1 / number_2)

        else:
            print('You have not typed a valid operator, please run the program again.')

    def _evaluate(self):
        return eval(self.previous_value+self.operator+self.value)

    def again(self):
        calc_again = input()
        if calc_again.upper() == 'Y':
            self.calculate()
        else:
            print('See you later.')


import tweepy
from get_all_tickers import get_tickers as gt

# This function scrapes the users you type in and attempts to grab their top count tweets and process them and add them to the maps.
def scrapeUsers(mapOfStocks, allStocks):
    # List of the accounts we want to scrap
    usernames = []
    # how many tweets you want
    count = 150

    for name in usernames:
        try:
            #Create query method using parameters
            tweets = tweepy.Cursor(api.user_timeline, id=name).items(count)
            # Grab the important info from the persons tweets
            tweets_list = [[tweet.created_at, tweet.id, tweet.text] for tweet in tweets]

            for tweet in tweets_list:
                tweetDescp = tweet.text
                addStocks(tweetDescp, mapOfStocks, allStocks)

        except BaseException as e:
            print("failed on_status,", str(e))

# This function needs to add any stock tickers seen in sentnce into into the mapOfStocks
# sentence- The sentence that needs to parsed which possibly contains any stock tickers
# mapOfStocks - The mapping between stock tickers and the number of times they appear
# allstocks- A map of all stock tickers
def addStocks(sentence, mapOfStocks, allstocks):
    # Split the sentence into words
    splits = sentence.split()
    # Loop through each word
    for word in splits:
        # If the word is a ticker then add it to the mapOfStocks
        if allstocks.get(word) != None:
            if mapOfStocks.get(word) == None:
                mapOfStocks.update({word: 1})
            else:
                mapOfStocks.update({word: mapOfStocks.get(word) + 1})

# converts the stockslist into a map
def listToMap(stockslist):
    allStocks = {}
    for i in stockslist:
        allStocks.update({i: 1})
    return allStocks

# Set up authentication
consumer_key = "xxx"
consumer_secret = "xxx"
access_token = "xxx"
access_token_secret = "xxxx"

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True)

# Create the map and get all the stocks from the csv
mapOfStocks = {}
stockslist = gt.get_tickers()
allStocks = listToMap(stockslist)

scrapeUsers(mapOfStocks, allStocks)

# sort the values of the mapofstocks and go through and print all of them in order
sortedVals = sorted(mapOfStocks.values())
seen = {}

#initialize the seen array
for key in mapOfStocks.keys():
    seen.update({key: False})

# Print the stuff out
for i in sortedVals:
    for key in mapOfStocks.keys():
        if mapOfStocks.get(key) == i and seen.get(key) == False:
            print(key + ": " + str(i))
            seen.update({key: True})
            break


#! python3
"""
from: https://adventofcode.com/2021/day/4#part2

--- Part Two ---
On the other hand, it might be wise to try a different strategy: let the giant squid win.

You aren't sure how many bingo boards a giant squid could play at once, so rather than waste time
counting its arms, the safe thing to do is to figure out which board will win last and choose that
one. That way, no matter which boards it picks, it will win for sure.

In the above example, the second board is the last to win, which happens after 13 is eventually
called and its middle column is completely marked. If you were to keep playing until this point,
the second board would have a sum of unmarked numbers equal to 148 for a final score of 148 * 13 =
1924.

Figure out which board will win last. Once it wins, what would its final score be?

"""
import os

class BingoBoard(object):
    def __init__(self, raw_board):
        super().__init__()
        self.board = [
            raw_board[0:5],
            raw_board[5:10],
            raw_board[10:15],
            raw_board[15:20],
            raw_board[20:25]
        ]
        self.marked = [[False for x in range(5)] for x in range(5)]

    def mark_number(self, picked_num):
        """Mark the picked number on the board, if it contains it"""
        for row in range(len(self.board)):
            for col in range(len(self.board[row])):
                if self.board[row][col] == picked_num:
                    self.marked[row][col] = True

    def is_winner(self):
        """Check if this is a winning bingo board"""
        # check each row
        for row in self.marked:
            if row == [True for x in range(len(row))]:
                return True

        # check each column
        for col in range(len(self.marked[0])):
            extracted_col = list()
            for row in range(len(self.marked)):
                extracted_col.append(self.marked[row][col])
            if extracted_col == [True for x in range(len(self.marked[0]))]:
                return True

        return False

    def get_sum_unmarked(self):
        """Calculate the sum of all the unmarked numbers on the board"""
        sum = 0
        for row in range(len(self.board)):
            for col in range(len(self.board[row])):
                if not self.marked[row][col]:
                    sum += self.board[row][col]
        return sum

def main(filename):
    """Solve the problem!"""
    script_dir = os.path.dirname(__file__)
    file_path = os.path.join(script_dir, filename)
    picked_numbers = list()
    boards = list()
    BOARD_DIM = 5
    with open(file_path) as input_file:
        picked_numbers = list(map(int, input_file.readline().split(',')))
        temp_board = list()
        for line in input_file:
            if line.isspace():
                continue
            temp_board += list(map(int, line.strip().replace("  ", " ").split()))
            if len(temp_board) == BOARD_DIM * BOARD_DIM:
                initialized_board = BingoBoard(temp_board)
                boards.append(initialized_board)
                temp_board = list()
    boards_still_playing = boards
    for picked in picked_numbers:
        losers = list()
        for board in boards_still_playing:
            board.mark_number(picked)
            if board.is_winner():
                # calculate "score" from the last board to win
                if len(boards_still_playing) == 1:
                    print("FINAL WINNER!")
                    print(board.get_sum_unmarked() * picked)
            else:
                losers.append(board)
        boards_still_playing = losers

if __name__ == "__main__":
    main('example.txt')
    main('input.txt')


#
# Class for single particle with polynomial concentration profile
#
import pybamm

from ..base_particle import BaseParticle

class XAveragedPolynomialProfile(BaseParticle):
    """
    Class for molar conservation in a single x-averaged particle with
    an assumed polynomial concentration profile in r. Model equations from [1]_.

    Parameters
    ----------
    param : parameter class
        The parameters to use for this submodel
    domain : str
        The domain of the model either 'Negative' or 'Positive'
    name : str
        The name of the polynomial approximation to be used. Can be "uniform
        profile", "quadratic profile" or "quartic profile".

    References
    ----------
    .. [1] VR Subramanian, VD Diwakar and D Tapriyal. “Efficient Macro-Micro Scale
           Coupled Modeling of Batteries”. Journal of The Electrochemical Society,
           152(10):A2002-A2008, 2005

    **Extends:** :class:`pybamm.particle.BaseParticle`
    """

    def __init__(self, param, domain, name):
        super().__init__(param, domain)
        self.name = name

        pybamm.citations.register("Subramanian2005")

    def get_fundamental_variables(self):
        # For all orders we solve an equation for the average concentration
        if self.domain == "Negative":
            c_s_rxav = pybamm.standard_variables.c_s_n_rxav

        elif self.domain == "Positive":
            c_s_rxav = pybamm.standard_variables.c_s_p_rxav

        variables = {
            "Average " + self.domain.lower() + " particle concentration": c_s_rxav
        }

        # For the fourth order polynomial approximation we also solve an
        # equation for the average concentration gradient. Note: in the original
        # paper this quantity is referred to as the flux, but here we make the
        # distinction between the flux defined as N = -D*dc/dr and the concentration
        # gradient q = dc/dr
        if self.name == "quartic profile":
            if self.domain == "Negative":
                q_s_rxav = pybamm.standard_variables.q_s_n_rxav
            elif self.domain == "Positive":
                q_s_rxav = pybamm.standard_variables.q_s_p_rxav
            variables.update(
                {
                    "Average "
                    + self.domain.lower()
                    + " particle concentration gradient": q_s_rxav
                }
            )

        return variables

    def get_coupled_variables(self, variables):
        c_s_rxav = variables[
            "Average " + self.domain.lower() + " particle concentration"
        ]
        i_boundary_cc = variables["Current collector current density"]
        a_av = variables[
            "X-averaged "
            + self.domain.lower()
            + " electrode surface area to volume ratio"
        ]
        T_xav = pybamm.PrimaryBroadcast(
            variables["X-averaged " + self.domain.lower() + " electrode temperature"],
            [self.domain.lower() + " particle"],
        )

        # Set surface concentration based on polynomial order
        if self.name == "uniform profile":
            # The concentration is uniform so the surface value is equal to
            # the average
            c_s_surf_xav = c_s_rxav
        elif self.name == "quadratic profile":
            # The surface concentration is computed from the average concentration
            # and boundary flux
            # Note 1: here we use the total average interfacial current for the single
            # particle. We explicitly write this as the current density divided by the
            # electrode thickness instead of getting the average current from the
            # interface submodel since the interface submodel requires the surface
            # concentration to be defined first to compute the exchange current density.
            # Explicitly writing out the average interfacial current here avoids
            # KeyErrors due to variables not being set in the "right" order.
            # Note 2: the concentration, c, inside the diffusion coefficient, D, here
            # should really be the surface value, but this requires solving a nonlinear
            # equation for c_surf (if the diffusion coefficient is nonlinear), adding
            # an extra algebraic equation to solve. For now, using the average c is an
            # ok approximation and means the SPM(e) still gives a system of ODEs rather
            # than DAEs.
            if self.domain == "Negative":
                j_xav = i_boundary_cc / (a_av * self.param.l_n)
                c_s_surf_xav = c_s_rxav - self.param.C_n * (
                    j_xav
                    / 5
                    / self.param.a_R_n
                    / self.param.D_n(c_s_rxav, pybamm.surf(T_xav))
                )

            if self.domain == "Positive":
                j_xav = -i_boundary_cc / (a_av * self.param.l_p)
                c_s_surf_xav = c_s_rxav - self.param.C_p * (
                    j_xav
                    / 5
                    / self.param.a_R_p
                    / self.param.gamma_p
                    / self.param.D_p(c_s_rxav, pybamm.surf(T_xav))
                )
        elif self.name == "quartic profile":
            # The surface concentration is computed from the average concentration,
            # the average concentration gradient and the boundary flux (see notes
            # for the case order=2)
            q_s_rxav = variables[
                "Average " + self.domain.lower() + " particle concentration gradient"
            ]
            if self.domain == "Negative":
                j_xav = i_boundary_cc / (a_av * self.param.l_n)
                c_s_surf_xav = (
                    c_s_rxav
                    + 8 * q_s_rxav / 35
                    - self.param.C_n
                    * (
                        j_xav
                        / 35
                        / self.param.a_R_n
                        / self.param.D_n(c_s_rxav, pybamm.surf(T_xav))
                    )
                )

            if self.domain == "Positive":
                j_xav = -i_boundary_cc / (a_av * self.param.l_p)
                c_s_surf_xav = (
                    c_s_rxav
                    + 8 * q_s_rxav / 35
                    - self.param.C_p
                    * (
                        j_xav
                        / 35
                        / self.param.a_R_p
                        / self.param.gamma_p
                        / self.param.D_p(c_s_rxav, pybamm.surf(T_xav))
                    )
                )

        # Set concentration depending on polynomial order
        if self.name == "uniform profile":
            # The concentration is uniform
            c_s_xav = pybamm.PrimaryBroadcast(
                c_s_rxav, [self.domain.lower() + " particle"]
            )
        elif self.name == "quadratic profile":
            # The concentration is given by c = A + B*r**2
            A = pybamm.PrimaryBroadcast(
                (1 / 2) * (5 * c_s_rxav - 3 * c_s_surf_xav),
                [self.domain.lower() + " particle"],
            )
            B = pybamm.PrimaryBroadcast(
                (5 / 2) * (c_s_surf_xav - c_s_rxav), [self.domain.lower() + " particle"]
            )
            if self.domain == "Negative":
                # Since c_s_xav doesn't depend on x, we need to define a spatial
                # variable r which only has "negative particle" and "current
                # collector" as domains
                r = pybamm.SpatialVariable(
                    "r_n",
                    domain=["negative particle"],
                    auxiliary_domains={"secondary": "current collector"},
                    coord_sys="spherical polar",
                )
                c_s_xav = A + B * r ** 2
            if self.domain == "Positive":
                # Since c_s_xav doesn't depend on x, we need to define a spatial
                # variable r which only has "positive particle" and "current
                # collector" as domains
                r = pybamm.SpatialVariable(
                    "r_p",
                    domain=["positive particle"],
                    auxiliary_domains={"secondary": "current collector"},
                    coord_sys="spherical polar",
                )
                c_s_xav = A + B * r ** 2

        elif self.name == "quartic profile":
            # The concentration is given by c = A + B*r**2 + C*r**4
            A = pybamm.PrimaryBroadcast(
                39 * c_s_surf_xav / 4 - 3 * q_s_rxav - 35 * c_s_rxav / 4,
                [self.domain.lower() + " particle"],
            )
            B = pybamm.PrimaryBroadcast(
                -35 * c_s_surf_xav + 10 * q_s_rxav + 35 * c_s_rxav,
                [self.domain.lower() + " particle"],
            )
            C = pybamm.PrimaryBroadcast(
                105 * c_s_surf_xav / 4 - 7 * q_s_rxav - 105 * c_s_rxav / 4,
                [self.domain.lower() + " particle"],
            )
            if self.domain == "Negative":
                # Since c_s_xav doesn't depend on x, we need to define a spatial
                # variable r which only has "negative particle" and "current
                # collector" as domains
                r = pybamm.SpatialVariable(
                    "r_n",
                    domain=["negative particle"],
                    auxiliary_domains={"secondary": "current collector"},
                    coord_sys="spherical polar",
                )
                c_s_xav = A + B * r ** 2 + C * r ** 4
            if self.domain == "Positive":
                # Since c_s_xav doesn't depend on x, we need to define a spatial
                # variable r which only has "positive particle" and "current
                # collector" as domains
                r = pybamm.SpatialVariable(
                    "r_p",
                    domain=["positive particle"],
                    auxiliary_domains={"secondary": "current collector"},
                    coord_sys="spherical polar",
                )
                c_s_xav = A + B * r ** 2 + C * r ** 4

        c_s = pybamm.SecondaryBroadcast(c_s_xav, [self.domain.lower() + " electrode"])
        c_s_surf = pybamm.PrimaryBroadcast(
            c_s_surf_xav, [self.domain.lower() + " electrode"]
        )

        # Set flux based on polynomial order
        if self.name == "uniform profile":
            # The flux is zero since there is no concentration gradient
            N_s_xav = pybamm.FullBroadcastToEdges(
                0, self.domain.lower() + " particle", "current collector"
            )
        elif self.name == "quadratic profile":
            # The flux may be computed directly from the polynomial for c
            if self.domain == "Negative":
                N_s_xav = (
                    -self.param.D_n(c_s_xav, T_xav) * 5 * (c_s_surf_xav - c_s_rxav) * r
                )
            if self.domain == "Positive":
                N_s_xav = (
                    -self.param.D_p(c_s_xav, T_xav) * 5 * (c_s_surf_xav - c_s_rxav) * r
                )
        elif self.name == "quartic profile":
            q_s_rxav = variables[
                "Average " + self.domain.lower() + " particle concentration gradient"
            ]
            # The flux may be computed directly from the polynomial for c
            if self.domain == "Negative":
                N_s_xav = -self.param.D_n(c_s_xav, T_xav) * (
                    (-70 * c_s_surf_xav + 20 * q_s_rxav + 70 * c_s_rxav) * r
                    + (105 * c_s_surf_xav - 28 * q_s_rxav - 105 * c_s_rxav) * r ** 3
                )
            elif self.domain == "Positive":
                N_s_xav = -self.param.D_p(c_s_xav, T_xav) * (
                    (-70 * c_s_surf_xav + 20 * q_s_rxav + 70 * c_s_rxav) * r
                    + (105 * c_s_surf_xav - 28 * q_s_rxav - 105 * c_s_rxav) * r ** 3
                )

        N_s = pybamm.SecondaryBroadcast(N_s_xav, [self._domain.lower() + " electrode"])

        variables.update(
            self._get_standard_concentration_variables(
                c_s, c_s_av=c_s_rxav, c_s_surf=c_s_surf
            )
        )
        variables.update(self._get_standard_flux_variables(N_s, N_s_xav))
        variables.update(self._get_total_concentration_variables(variables))

        return variables

    def set_rhs(self, variables):
        # Note: we have to use `pybamm.source(rhs, var)` in the rhs dict so that
        # the scalar source term gets multplied by the correct mass matrix when
        # using this model with 2D current collectors with the finite element
        # method (see #1399)

        c_s_rxav = variables[
            "Average " + self.domain.lower() + " particle concentration"
        ]
        j_xav = variables[
            "X-averaged "
            + self.domain.lower()
            + " electrode interfacial current density"
        ]

        if self.domain == "Negative":
            self.rhs = {
                c_s_rxav: pybamm.source(-3 * j_xav / self.param.a_R_n, c_s_rxav)
            }

        elif self.domain == "Positive":
            self.rhs = {
                c_s_rxav: pybamm.source(
                    -3 * j_xav / self.param.a_R_p / self.param.gamma_p, c_s_rxav
                )
            }

        if self.name == "quartic profile":
            # We solve an extra ODE for the average particle concentration gradient
            q_s_rxav = variables[
                "Average " + self.domain.lower() + " particle concentration gradient"
            ]
            c_s_surf_xav = variables[
                "X-averaged " + self.domain.lower() + " particle surface concentration"
            ]
            T_xav = variables[
                "X-averaged " + self.domain.lower() + " electrode temperature"
            ]
            if self.domain == "Negative":
                self.rhs.update(
                    {
                        q_s_rxav: pybamm.source(
                            -30
                            * self.param.D_n(c_s_surf_xav, T_xav)
                            * q_s_rxav
                            / self.param.C_n
                            - 45 * j_xav / self.param.a_R_n / 2,
                            q_s_rxav,
                        )
                    }
                )
            elif self.domain == "Positive":
                self.rhs.update(
                    {
                        q_s_rxav: pybamm.source(
                            -30
                            * self.param.D_p(c_s_surf_xav, T_xav)
                            * q_s_rxav
                            / self.param.C_p
                            - 45 * j_xav / self.param.a_R_p / self.param.gamma_p / 2,
                            q_s_rxav,
                        )
                    }
                )

    def set_initial_conditions(self, variables):
        """
        For single or x-averaged particle models, initial conditions can't depend on x
        so we arbitrarily evaluate them at x=0 in the negative electrode and x=1 in the
        positive electrode (they will usually be constant)
        """
        c_s_rxav = variables[
            "Average " + self.domain.lower() + " particle concentration"
        ]

        if self.domain == "Negative":
            c_init = self.param.c_n_init(0)

        elif self.domain == "Positive":
            c_init = self.param.c_p_init(1)

        self.initial_conditions = {c_s_rxav: c_init}
        if self.name == "quartic profile":
            # We also need to provide an initial condition for the average
            # concentration gradient
            q_s_rxav = variables[
                "Average " + self.domain.lower() + " particle concentration gradient"
            ]
            self.initial_conditions.update({q_s_rxav: 0})


# 아이디어 : 1. 나이트의 8방향 정의
#            2. 방문 여부를 위한 graph 0으로 초기화
# 알고리즘 : bfs
# 자료구조 : queue(deque)

# 시작지점 - (x, y), 도착지점 - (p, q)

from collections import deque
import sys
input = sys.stdin.readline

# bfs 함수 정의
def bfs(x, y):
    # 시작노드 및 큐 정의
    queue = deque()
    queue.append((x, y, 0))
    graph[x][y] = 1

    while queue:
        x, y, cnt = queue.popleft()

        # 도착 지점이라면
        if x == p and y == q :
            return cnt

        for step in steps:
            nx = x + step[0]
            ny = y + step[1]

            # 범위 밖이라면 무시
            if nx < 0 or ny < 0 or nx >= n or ny >= n :
                continue

            # 방문한 적이 없다면
            if graph[nx][ny] == 0 :
                graph[nx][ny] = 1
                queue.append((nx, ny, cnt + 1))

# 나이트의 이동 8방향 정의
steps = [(-2, -1), (-2, 1), (2, -1), (2, 1),
         (-1, -2), (-1, 2), (1, -2), (1, 2)]

T = int(input())

for _ in range(T):
    n = int(input())
    x, y = map(int, input().split())
    p, q = map(int, input().split())

    graph = [[0 for _ in range(n)] for _ in range(n)]

    print(bfs(x, y))

백준/Silver/7562. 나이트의 이동/나이트의 이동.py


import numpy as np
import block
import time

class GameEngine:
    def __init__(self,Nx,Ny,player,timeperiod=1.0):
        self.Nx = Nx
        self.Ny = Ny
        self.block = None
        self.score = 0
        self.player = player
        self.timeperiod = timeperiod

        self.area = np.zeros((Nx,Ny))

    def getarea(self):
        return self.area

    def getscore(self):
        return self.score

    def start(self):
        # Initiate the retro snake
        position = (int(self.Nx/2),0)
        self.block = block.Block(position=position,player=self.player)
        self.prearea = self.area.copy()

        return True

    def restart(self):
        return self.start()

    def updatearea(self):
        body = self.block.getbody()
        shape = self.block.getshape()

        if self.block.survive(area=self.prearea):
            self.area = self.prearea.copy()
            for pos in body:
                self.area[pos] = shape
        else:
            for pos in body:
                self.prearea[pos] = shape
            self.area = self.prearea.copy()

            position = (int(self.Nx/2),0)
            self.block = block.Block(position=position,player=self.player)

        # To cancel one line
        for j in range(self.Ny):
            if np.sum(self.prearea[:,j]!=0) == self.Nx:
                self.prearea[:,1:j+1] = self.prearea[:,0:j]

    def tocontinue(self):
        for i in range(self.Nx):
            if self.prearea[i,0] != 0:
                return False
        return True

    def update(self):

        starttime = time.time()
        self.block.update(self.prearea)
        endtime = time.time()
        if self.timeperiod-(endtime-starttime) > 0:
            time.sleep(self.timeperiod-(endtime-starttime))

        self.updatearea()   # Update Area

        return self.tocontinue()


#maximum for index on direct adressing push and pop.
SEG_OFFSET_LIMITS = {
'temp': 12-5,
'static': 255 - 16,
'constant': 32767 - 0,
'pointer': 4 - 3
}

OFFSET_ER = '''
\n\nfrom memory.py:
memory segment {} needs offset between 0 and {}
'''
def segment_offset_limits(trans):
    '''
    decorates push and pop commands to catch
    trying to access outside a segment.
    '''
    def ret(*x):

        _, seg, ind, _, _, _ = x

        if not seg in SEG_OFFSET_LIMITS.keys():
            return trans(*x)

        lim = SEG_OFFSET_LIMITS[seg]
        if 0 <= int(ind) <= lim:
            return trans(*x)
        else:
            msg = OFFSET_ER.format(seg, lim)
            return Exception(msg)

    return ret

#{memory_segment_name: (starting mem addr, A or M)
# A is address and M is memory in that address.
# A accesses address holding pointer to segment.
# M accesses location of begging of segment
SEG_DESC = {

'local':(1, 'M'),
'argument': (2, 'M'),
'this': (3, 'M'),
'that': (4, 'M'),
#'constant': (0, 'A')
'temp': (5, 'A'),
#'static': (16, 'A'),
'pointer': (3, 'A')

}

PUSH_FROM_D = '''
@SP   //push whatever's on D onto stack
A=M
M=D
@SP
M=M+1
'''

def push_indirect(seg, ind):

    seg_num = SEG_DESC[seg][0]
    ret = '''
@{}      //starting mem addr of seg
D=M      //
@{}      //offset
A=A+D
D=M
'''
    ret = ret.format(seg_num, ind)
    ret = ret + PUSH_FROM_D
    return ret

def push_direct(seg, ind):

    seg_num = SEG_DESC[seg][0]
    j = seg_num + int(ind)
    ret = '@{}\nD=M'
    ret = ret.format(j)
    ret = ret + PUSH_FROM_D
    return ret

def push_constant(ind):

    ret = '@{}\nD=A'.format(ind)
    ret = ret + PUSH_FROM_D
    return ret

def push_static(file_name, ind):

    ret = '\n@{}.{}\nD=M'
    ret = ret.format(file_name, ind)
    ret = ret + PUSH_FROM_D
    return ret

@segment_offset_limits
def Push(*vm_line):

    _, seg, ind, _, _, Xxx = vm_line

    if seg in ['local', 'argument', 'this', 'that']:
        ret = push_indirect(seg, ind)
    elif seg in ['temp', 'pointer']:
        ret = push_direct(seg, ind)
    elif 'constant' == seg:
        ret = push_constant(ind)
    elif 'static' == seg:
        ret = push_static(Xxx, ind)
    else:
        ret = Exception(Xxx+'.vm & memory.py Push')
    return ret

#assuming D holds address to pop to
POP_TO_D ='''
@R13     //
M=D        //R13 holds adrress to pop to
@SP
M=M-1
@SP        //stack pointer decremented
A=M
D=M        // D holds the pop payload
@R13
A=M       //looking at target memory
M=D
'''

def pop_indirect(seg, ind):

    seg_num = SEG_DESC[seg][0]
    ret = '''
@{}
D=M
@{}
D=D+A
'''
    ret = ret.format(seg_num, ind)
    ret = ret + POP_TO_D
    return ret

def pop_direct(seg, ind):

    seg_num = SEG_DESC[seg][0]
    ret = '''
@{}
D=A
@{}
D=D+A'''
    ret = ret.format(seg_num, ind)
    ret = ret + POP_TO_D
    return ret

def pop_static(vm_file, ind):
    ret = '''
@{}.{}  //vm_file, ind
D=A
//@{}   //ind
//D=D+A'''
    ret = ret.format(vm_file, ind, ind)
    ret = ret + POP_TO_D
    return ret

@segment_offset_limits
def Pop(*vm_line):

    _, seg, ind, _, _, Xxx = vm_line

    if seg in ['local', 'argument', 'this', 'that']:
        ret = pop_indirect(seg, ind)
    if seg in ['temp', 'pointer']:
        ret = pop_direct(seg, ind)
    if 'static' == seg:
        ret = pop_static(Xxx, ind)
    if 'constant' == seg:
        ret = Exception( "can't pop to constant")

    return ret


from BulletHero import BulletForHero
import pygame

if __name__ == '__main__':

    pygame.init()
    window = pygame.display.set_mode([512, 768])
    clock = pygame.time.Clock()

    # 初始化弹夹
    bullets = BulletForHero(window)

    while True:

        # 清空屏幕
        window.fill((0, 0, 0))

        # 子弹坐标
        bullets.calc_position()
        # 子弹绘制
        bullets.draw_element()
        # 发射子弹
        bullets.shoot(250, 600, 3)

        # 读取事件，避免窗口卡顿
        pygame.event.get()

        pygame.display.update()
        clock.tick(60)


import os
import glob
import sys
import os.path
import traceback

# this holds the list of plugins that have been loaded.  if you're running
# Pyblosxom as a long-running process, this only gets cleared when the
# process is restarted.
plugins = []

# this holds a list of callbacks (any function that begins with cp_) and the
# list of function instances that support that callback.
# if you're running Pyblosxom as a long-running process, this only
# gets cleared when the process is restarted.
callbacks = {}

# this holds a list of (plugin name, exception) tuples for plugins that
# didn't import.
bad_plugins = []

def catalogue_plugin(plugin_module):
    """
    Goes through the plugin's contents and catalogues all the functions
    that start with cb_.  Functions that start with cb_ are callbacks.

    :param plugin_module: the module to catalogue
    """
    listing = dir(plugin_module)

    listing = [item for item in listing if item.startswith("cb_")]

    for mem in listing:
        func = getattr(plugin_module, mem)
        memadj = mem[3:]
        if callable(func):
            callbacks.setdefault(memadj, []).append(func)

def get_callback_chain(chain):
    """
    Returns a list of functions registered with the callback.

    @returns: list of functions registered with the callback (or an
        empty list)
    @rtype: list of functions
    """
    return callbacks.get(chain, [])

def initialize_plugins(plugin_dirs, plugin_list):
    """
    Imports and initializes plugins from the directories in the list
    specified by "plugins_dir".  If no such list exists, then we don't
    load any plugins.

    If the user specifies a "load_plugins" list of plugins to load, then
    we explicitly load those plugins in the order they're listed.  If the
    load_plugins key does not exist, then we load all the plugins in the
    plugins directory using an alphanumeric sorting order.

    .. Note::

       If Pyblosxom is part of a long-running process, you must
       restart Pyblosxom in order to pick up any changes to your plugins.

    :param plugin_dirs: the list of directories to add to the sys.path
                        because that's where our plugins are located.

    :param plugin_list: the list of plugins to load, or if None, we'll
                        load all the plugins we find in those dirs.
    """
    if plugins or bad_plugins:
        return

    # we clear out the callbacks dict so we can rebuild them
    callbacks.clear()

    # handle plugin_dirs here
    for mem in plugin_dirs:
        if os.path.isdir(mem):
            sys.path.append(mem)
        else:
            raise Exception("Plugin directory '%s' does not exist.  " \
                            "Please check your config file." % mem)

    plugin_list = get_plugin_list(plugin_list, plugin_dirs)

    for mem in plugin_list:
        try:
            _module = __import__(mem)
        except (SystemExit, KeyboardInterrupt):
            raise
        except:
            # this needs to be a catch-all
            bad_plugins.append((mem, "".join(traceback.format_exc())))
            continue

        for comp in mem.split(".")[1:]:
            _module = getattr(_module, comp)
        catalogue_plugin(_module)
        plugins.append(_module)

def get_plugin_by_name(name):
    """
    This retrieves a plugin instance (it's a Python module instance)
    by name.

    :param name: the name of the plugin to retrieve (ex: "xmlrpc")

    :returns: the Python module instance for the plugin or None
    """
    if plugins:
        for mem in plugins:
            if mem.__name__ == name:
                return mem
    return None

def get_module_name(filename):
    """
    Takes a filename and returns the module name from the filename.

    Example: passing in "/blah/blah/blah/module.ext" returns "module"

    :param filename: the filename in question (with a full path)

    :returns: the filename without path or extension
    """
    return os.path.splitext(os.path.split(filename)[1])[0]

def get_plugin_list(plugin_list, plugin_dirs):
    """
    This handles the situation where the user has provided a series of
    plugin dirs, but has not specified which plugins they want to load
    from those dirs.  In this case, we load all possible plugins except
    the ones whose names being with _ .

    :param plugin_list: List of plugins to load

    :param plugin_dirs: A list of directories where plugins can be loaded from

    :return: list of python module names of the plugins to load
    """
    if plugin_list is None:
        plugin_list = []
        for mem in plugin_dirs:
            file_list = glob.glob(os.path.join(mem, "*.py"))

            file_list = [get_module_name(filename) for filename in file_list]

            # remove plugins that start with a _
            file_list = [plugin for plugin in file_list \
                         if not plugin.startswith('_')]
            plugin_list += file_list

        plugin_list.sort()

    return plugin_list


from decimal import Decimal
import pytest
from wightinvoices.invoice import models

def create_invoice():
    client = models.Client(name='a', address='b')
    client.save()

    from django.contrib.auth import get_user_model
    user, created = get_user_model().objects.get_or_create(username='admin')

    invoice = models.Invoice()
    invoice.client = client
    invoice.owner = user
    invoice.save()
    # Item #1 / 300 net
    item = models.InvoiceItem()
    item.vat = Decimal('20.0')
    item.amount = Decimal('100.00')
    item.quantity = 3
    item.invoice = invoice
    item.save()
    # Item #2 / 10 net
    item = models.InvoiceItem()
    item.vat = Decimal('20.0')
    item.amount = Decimal('10.00')
    item.quantity = 1
    item.invoice = invoice
    item.save()

    return invoice

@pytest.mark.django_db
def test_net_total():
    invoice = create_invoice()
    assert invoice.net_total == Decimal('310.00')

@pytest.mark.django_db
def test_gross_total():
    invoice = create_invoice()
    assert invoice.gross_total == Decimal('372.00')

@pytest.mark.django_db
def test_vat_total():
    invoice = create_invoice()
    assert invoice.vat_total == Decimal('62.00')


class Person(object):
    #这里的属性实际上属于类属性（用类名来调用）
    name = "person"
    def __init__(self, name):
        #对象属性
        self.name = name

print(Person.name)
per = Person("tom")
#对象属性的优先级高于类属性
print(per.name)
#动态的给对象添加对象属性
per.age = 18 #只针对于当前对象生效，对于类创建的其他对象没有意义
print(Person.name)
per2 = Person("jdhf")
#print(per2.age)  没有age属性

#删除对象中的name属性,再调用会使用同名的类属性
del per.name
print(per.name)

#以后千万不要将对象属性与类属性重名，对象属性会屏蔽掉类属性。但是当删除对象属性后，又能使用类属性了。

对象属性与类属性/对象属性与类属性.py


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

import sys
import os
import argparse
from propeller.service.client import InferenceClient
from propeller import log
import six
import utils.data
from time import time
import numpy as np

class ErnieClient(InferenceClient):
    def __init__(self,
            vocab_file,
            host='localhost',
            port=8888,
            batch_size=32,
            num_coroutine=1,
            timeout=10.,
            max_seqlen=128):
        host_port = 'tcp://%s:%d' % (host, port)
        client = super(ErnieClient, self).__init__(host_port, batch_size=batch_size, num_coroutine=num_coroutine, timeout=timeout)
        self.vocab = {j.strip().split(b'\t')[0].decode('utf8'): i for i, j in enumerate(open(vocab_file, 'rb'))}
        self.tokenizer = utils.data.CharTokenizer(self.vocab.keys())
        self.max_seqlen = max_seqlen
        self.cls_id = self.vocab['[CLS]']
        self.sep_id = self.vocab['[SEP]']

    def txt_2_id(self, text):
        ids = np.array([self.vocab[i] for i in self.tokenizer(text)])
        return ids

    def pad_and_batch(self, ids):
        max_len = max(map(len, ids))
        padded = np.stack([np.pad(i, [[0, max_len - len(i)]], mode='constant')for i in ids])
        padded = np.expand_dims(padded, axis=-1)
        return padded

    def __call__(self, text_a, text_b=None):
        if text_b is not None and len(text_a) != len(text_b):
            raise ValueError('text_b %d has different size than text_a %d' % (text_b, text_a))
        text_a = [i.encode('utf8') if isinstance(i, six.string_types) else i for i in text_a]
        if text_b is not None:
            text_b = [i.encode('utf8') if isinstance(i, six.string_types) else i for i in text_b]

        ids_a = map(self.txt_2_id, text_a)
        if text_b is not None:
            ids_b = map(self.txt_2_id, text_b)
            ret = [utils.data.build_2_pair(a, b, self.max_seqlen, self.cls_id, self.sep_id) for a, b in zip(ids_a, ids_b)]
        else:
            ret = [utils.data.build_1_pair(a, self.max_seqlen, self.cls_id, self.sep_id) for a in ids_a]
        sen_ids, token_type_ids = zip(*ret)
        sen_ids = self.pad_and_batch(sen_ids)
        token_type_ids = self.pad_and_batch(token_type_ids)
        ret, = super(ErnieClient, self).__call__(sen_ids, token_type_ids)
        return ret

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='ernie_encoder_client')
    parser.add_argument('--host', type=str, default='localhost')
    parser.add_argument('-i', '--input', type=str, required=True)
    parser.add_argument('-o', '--output', type=str, required=True)
    parser.add_argument('-p', '--port', type=int, default=8888)
    parser.add_argument('--batch_size', type=int, default=32)
    parser.add_argument('--num_coroutine', type=int, default=1)
    parser.add_argument('--vocab', type=str, required=True)
    args = parser.parse_args()

    client = ErnieClient(args.vocab, args.host, args.port, batch_size=args.batch_size, num_coroutine=args.num_coroutine)
    inputs = [i.strip().split(b'\t') for i in open(args.input, 'rb').readlines()]
    if len(inputs) == 0:
        raise ValueError('empty input')
    send_batch = args.num_coroutine * args.batch_size
    send_num = len(inputs) // send_batch + 1
    rets = []
    start = time()
    for i in range(send_num):
        slice = inputs[i * send_batch: (i + 1) * send_batch]
        if len(slice) == 0:
            continue
        columns = list(zip(*slice))
        if len(columns) > 2:
            raise ValueError('inputs file has more than 2 columns')
        ret = client(*columns)
        if len(ret.shape) == 3:
            ret = ret[:, 0, :] # take cls
        rets.append(ret)
    end = time()
    with open(args.output, 'wb') as outf:
        arr = np.concatenate(rets, 0)
        np.save(outf, arr)
        log.info('query num: %d average latency %.5f' % (len(inputs), (end - start)/len(inputs)))


import warnings
import requests
from typing import List
from bs4 import BeautifulSoup
from langchain.docstore.document import Document

class NCCSLoader:
    def __init__(self, urls):
        self.urls = urls

    def scrap_url(self, url: str) -> Document:
        response = requests.get(url)
        soup = BeautifulSoup(response.content, 'html.parser')
        main_content = soup.find_all("div", class_="content")
        text = main_content[0].get_text()

        metadata = {"source": url}
        doc = Document(page_content=text, metadata=metadata)

        return doc

    def load(self) -> List[Document]:
        documents = []
        for url in self.urls:
            try:
                doc = self.scrap_url(url)
                documents.append(doc)
            except:
                warnings.warn(f"Failed to scrape {url}.", UserWarning)

        return documents


from decimal import Decimal
import unittest
import datetime

import rdflib  # needed for eval(repr(...)) below
from rdflib.term import Literal, URIRef, _XSD_DOUBLE, bind, _XSD_BOOLEAN
from rdflib.namespace import XSD

class TestLiteral(unittest.TestCase):
    def setUp(self):
        pass

    def test_repr_apostrophe(self):
        a = rdflib.Literal("'")
        b = eval(repr(a))
        self.assertEqual(a, b)

    def test_repr_quote(self):
        a = rdflib.Literal('"')
        b = eval(repr(a))
        self.assertEqual(a, b)

    def test_backslash(self):
        d = r"""
<rdf:RDF
  xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
  xmlns:foo="http://example.org/foo#">
    <rdf:Description>
      <foo:bar>a\b</foo:bar>
    </rdf:Description>
</rdf:RDF>
"""
        g = rdflib.Graph()
        g.parse(data=d, format="xml")
        a = rdflib.Literal("a\\b")
        b = list(g.objects())[0]
        self.assertEqual(a, b)

    def test_literal_from_bool(self):
        l = rdflib.Literal(True)
        self.assertEqual(l.datatype, rdflib.XSD["boolean"])

class TestNew(unittest.TestCase):
    def testCantPassLangAndDatatype(self):
        self.assertRaises(
            TypeError, Literal, "foo", lang="en", datatype=URIRef("http://example.com/")
        )

    def testFromOtherLiteral(self):
        l = Literal(1)
        l2 = Literal(l)
        self.assertTrue(isinstance(l.value, int))
        self.assertTrue(isinstance(l2.value, int))

        # change datatype
        l = Literal("1")
        l2 = Literal(l, datatype=rdflib.XSD.integer)
        self.assertTrue(isinstance(l2.value, int))

    def testDatatypeGetsAutoURIRefConversion(self):
        # drewp disapproves of this behavior, but it should be
        # represented in the tests
        x = Literal("foo", datatype="http://example.com/")
        self.assertTrue(isinstance(x.datatype, URIRef))

        x = Literal("foo", datatype=Literal("pennies"))
        self.assertEqual(x.datatype, URIRef("pennies"))

class TestRepr(unittest.TestCase):
    def testOmitsMissingDatatypeAndLang(self):
        self.assertEqual(repr(Literal("foo")), "rdflib.term.Literal('foo')")

    def testOmitsMissingDatatype(self):
        self.assertEqual(
            repr(Literal("foo", lang="en")),
            "rdflib.term.Literal('foo', lang='en')",
        )

    def testOmitsMissingLang(self):
        self.assertEqual(
            repr(Literal("foo", datatype=URIRef("http://example.com/"))),
            "rdflib.term.Literal('foo', datatype=rdflib.term.URIRef('http://example.com/'))",
        )

    def testSubclassNameAppearsInRepr(self):
        class MyLiteral(Literal):
            pass

        x = MyLiteral("foo")
        self.assertEqual(repr(x), "MyLiteral('foo')")

class TestDoubleOutput(unittest.TestCase):
    def testNoDanglingPoint(self):
        """confirms the fix for https://github.com/RDFLib/rdflib/issues/237"""
        vv = Literal("0.88", datatype=_XSD_DOUBLE)
        out = vv._literal_n3(use_plain=True)
        self.assertTrue(out in ["8.8e-01", "0.88"], out)

class TestParseBoolean(unittest.TestCase):
    """confirms the fix for https://github.com/RDFLib/rdflib/issues/913"""

    def testTrueBoolean(self):
        test_value = Literal("tRue", datatype=_XSD_BOOLEAN)
        self.assertTrue(test_value.value)
        test_value = Literal("1", datatype=_XSD_BOOLEAN)
        self.assertTrue(test_value.value)

    def testFalseBoolean(self):
        test_value = Literal("falsE", datatype=_XSD_BOOLEAN)
        self.assertFalse(test_value.value)
        test_value = Literal("0", datatype=_XSD_BOOLEAN)
        self.assertFalse(test_value.value)

    def testNonFalseBoolean(self):
        test_value = Literal("abcd", datatype=_XSD_BOOLEAN)
        self.assertRaises(UserWarning)
        self.assertFalse(test_value.value)
        test_value = Literal("10", datatype=_XSD_BOOLEAN)
        self.assertRaises(UserWarning)
        self.assertFalse(test_value.value)

class TestBindings(unittest.TestCase):
    def testBinding(self):
        class a:
            def __init__(self, v):
                self.v = v[3:-3]

            def __str__(self):
                return "<<<%s>>>" % self.v

        dtA = rdflib.URIRef("urn:dt:a")
        bind(dtA, a)

        va = a("<<<2>>>")
        la = Literal(va, normalize=True)
        self.assertEqual(la.value, va)
        self.assertEqual(la.datatype, dtA)

        la2 = Literal("<<<2>>>", datatype=dtA)
        self.assertTrue(isinstance(la2.value, a))
        self.assertEqual(la2.value.v, va.v)

        class b:
            def __init__(self, v):
                self.v = v[3:-3]

            def __str__(self):
                return "B%s" % self.v

        dtB = rdflib.URIRef("urn:dt:b")
        bind(dtB, b, None, lambda x: "<<<%s>>>" % x)

        vb = b("<<<3>>>")
        lb = Literal(vb, normalize=True)
        self.assertEqual(lb.value, vb)
        self.assertEqual(lb.datatype, dtB)

    def testSpecificBinding(self):
        def lexify(s):
            return "--%s--" % s

        def unlexify(s):
            return s[2:-2]

        datatype = rdflib.URIRef("urn:dt:mystring")

        # Datatype-specific rule
        bind(datatype, str, unlexify, lexify, datatype_specific=True)

        s = "Hello"
        normal_l = Literal(s)
        self.assertEqual(str(normal_l), s)
        self.assertEqual(normal_l.toPython(), s)
        self.assertEqual(normal_l.datatype, None)

        specific_l = Literal("--%s--" % s, datatype=datatype)
        self.assertEqual(str(specific_l), lexify(s))
        self.assertEqual(specific_l.toPython(), s)
        self.assertEqual(specific_l.datatype, datatype)

class TestXsdLiterals(unittest.TestCase):
    def test_make_literals(self):
        """
        Tests literal construction.
        """
        inputs = [
            # these literals do not get converted to Python types
            ("ABCD", XSD.integer, None),
            ("ABCD", XSD.gYear, None),
            ("-10000", XSD.gYear, None),
            ("-1921-00", XSD.gYearMonth, None),
            ("1921-00", XSD.gMonthDay, None),
            ("1921-13", XSD.gMonthDay, None),
            ("-1921-00", XSD.gMonthDay, None),
            ("10", XSD.gDay, None),
            ("-1", XSD.gDay, None),
            ("0000", XSD.gYear, None),
            ("0000-00-00", XSD.date, None),
            ("NOT A VALID HEX STRING", XSD.hexBinary, None),
            ("NOT A VALID BASE64 STRING", XSD.base64Binary, None),
            # these literals get converted to python types
            ("1921-05-01", XSD.date, datetime.date),
            ("1921-05-01T00:00:00", XSD.dateTime, datetime.datetime),
            ("1921-05", XSD.gYearMonth, datetime.date),
            ("0001-01", XSD.gYearMonth, datetime.date),
            ("0001-12", XSD.gYearMonth, datetime.date),
            ("2002-01", XSD.gYearMonth, datetime.date),
            ("9999-01", XSD.gYearMonth, datetime.date),
            ("9999-12", XSD.gYearMonth, datetime.date),
            ("1921", XSD.gYear, datetime.date),
            ("2000", XSD.gYear, datetime.date),
            ("0001", XSD.gYear, datetime.date),
            ("9999", XSD.gYear, datetime.date),
            ("1982", XSD.gYear, datetime.date),
            ("2002", XSD.gYear, datetime.date),
            ("1921-05-01T00:00:00+00:30", XSD.dateTime, datetime.datetime),
            ("1921-05-01T00:00:00-00:30", XSD.dateTime, datetime.datetime),
            ("abcdef0123", XSD.hexBinary, bytes),
            ("", XSD.hexBinary, bytes),
            ("UkRGTGli", XSD.base64Binary, bytes),
            ("", XSD.base64Binary, bytes),
            ("0.0000000000000000000000000000001", XSD.decimal, Decimal),
            ("0.1", XSD.decimal, Decimal),
            ("1", XSD.integer, int),
        ]
        self.check_make_literals(inputs)

    @unittest.expectedFailure
    def test_make_literals_ki(self):
        """
        Known issues with literal construction.
        """
        inputs = [
            ("1921-01Z", XSD.gYearMonth, datetime.date),
            ("1921Z", XSD.gYear, datetime.date),
            ("1921-00", XSD.gYearMonth, datetime.date),
            ("1921-05-01Z", XSD.date, datetime.date),
            ("1921-05-01+00:30", XSD.date, datetime.date),
            ("1921-05-01+00:30", XSD.date, datetime.date),
            ("1921-05-01+00:00", XSD.date, datetime.date),
            ("1921-05-01+00:00", XSD.date, datetime.date),
            ("1921-05-01T00:00:00Z", XSD.dateTime, datetime.datetime),
            ("1e-31", XSD.decimal, None),  # This is not a valid decimal value
        ]
        self.check_make_literals(inputs)

    def check_make_literals(self, inputs):
        for literal_pair in inputs:
            (lexical, type, value_cls) = literal_pair
            with self.subTest(f"testing {literal_pair}"):
                literal = Literal(lexical, datatype=type)
                if value_cls is not None:
                    self.assertIsInstance(literal.value, value_cls)
                else:
                    self.assertIsNone(literal.value)
                self.assertEqual(lexical, f"{literal}")

if __name__ == "__main__":
    unittest.main()


import os
import time

import numpy as np
from skimage import io, feature

"""
只需要求出小人的位置，和屏幕中心的位置，就可以实现自动跳跃
万变不离其宗，不论目标方块如何变化，中心法则肯定是正确的
"""
# 把adb命令添加到环境变量
os.environ['path'] += ";" + os.path.abspath("./adb/")
# 是否调试，如果调试，保存截图
debug = True
img_count = 0  # 图片编号
person = (63, 53, 81)  # 小人的颜色
center = (650, 373)  # 中心的位置
# 小人底部中心的偏移量
delta = np.array([601, 216]) - (731, 238)
k = 2.0  # 弹性系数

def pull_screenshot():
    # 拉取截图并保存
    global img_count
    os.system('adb shell screencap -p /sdcard/autojump.png')
    if debug:
        img_count += 1
    filename = "img/" + str(img_count) + ".png"
    os.system('adb pull /sdcard/autojump.png ' + filename)
    return io.imread(filename)

def filt_color(img):
    # 颜色过滤，只识别小人的颜色
    p = np.linalg.norm(img - person, ord=2, axis=2) < 30
    grey = np.zeros(img.shape[:2])
    grey[p] = 1
    return grey

def jump(distance):
    # 跳一段距离
    press_time = distance * k
    cmd = 'adb shell input swipe 320 410 320 410 ' + str(int(press_time))
    print(cmd)
    os.system(cmd)

def getperson(img, tem):
    # 获取小人的位置
    img = img[:, :, :3]  # 去掉RGBA中的A
    img[:200, :, :] = (0, 0, 0)  # 去掉顶部
    img[1100:, :, :] = (0, 0, 0)  # 去掉底部
    # 找到与小人颜色相近的像素
    grey = filt_color(img)
    # 模板匹配寻找小人的头部
    res = feature.match_template(grey, tem)
    pos = np.unravel_index(np.argmax(res), res.shape)
    pos = pos - delta
    return pos

tem = io.imread("person.jpg")  # 小人模板图片RGB形式
tem = filt_color(tem)
while 1:
    time.sleep(3)
    img = pull_screenshot()
    person_pos = getperson(img, tem)
    distance = np.linalg.norm((np.array(person_pos) - center) * 2, ord=2)
    jump(distance)


from structlog.testing import capture_logs

from mo_ldap_import_export.logging import logger
from mo_ldap_import_export.processors import _hide_cpr

def test_hide_cpr():
    cpr_string = (
        "my cpr no. is 010101-1234. "
        "My wife's cpr no. is 0102011235. "
        "This is not a cpr-no, but a telephone number: 500203-1236"
    )

    masked_string = _hide_cpr(cpr_string)

    assert "1234" not in masked_string
    assert "1235" not in masked_string
    assert "1236" in masked_string

def test_mask_cpr():
    with capture_logs() as cap_logs:
        logger.info("My cpr no is 010101-1234")
        logger.info("My telephone no is 6001011234")
        messages = [w for w in cap_logs if w["log_level"] == "info"]

        assert messages[0]["event"] == "My cpr no is 010101-xxxx"
        assert messages[1]["event"] == "My telephone no is 6001011234"

    cpr_no = "010101-1234"

    class CprClass:
        def __init__(self, cpr):
            self.cpr = cpr

        def __repr__(self):
            return f"cpr-no = {self.cpr}"

        def __str__(self):
            return self.cpr

    cpr_obj = CprClass(cpr_no)

    with capture_logs() as cap_logs:
        logger.info(f"My cpr no is {cpr_no}")
        logger.info("The cpr attribute is", cpr=cpr_no)
        logger.info("The cpr-no is hidden in this object", obj=cpr_obj)

        messages = [w for w in cap_logs if w["log_level"] == "info"]

        for message in messages:
            assert cpr_no not in str(message)
            assert "010101-xxxx" in str(message)


import sqlite3,os

cxn = sqlite3.connect('tags.db')
cur = cxn.cursor()
try:
	cur.execute('CREATE TABLE filetags(file_path VARCHAR(255), tag VARCHAR(20))')
except:
	pass
control=0
#try:
while control!=-1:
	print("1) TAG A FILE")
	print("2) LIST TAGS")
	print("3) LIST FILES")
	print("4) FIND FILES BY SINGLE TAG")
	print("5) FIND FILES BY TAGS")
	print("6) CLEAR DATABASE")
	print("-1) QUIT")
	control=int(input("$ "))
	if control==1:
		file_dir=input("FILE$ ")
		tag=input("TAG$ ")
		cur.execute('INSERT INTO filetags VALUES("'+file_dir+'","'+tag+'")')
cur.close()
cxn.commit()
cxn.close()