<commit_before># coding=utf-8
from __future__ import unicode_literals

import hashlib
import os
import platform
import random
import sys

try:
    import ConfigParser as configparser
except ImportError:
    import configparser

# download delegate
__wget__ = ('WGET_PATH',)
__thunder__ = ('XUNLEI_LX_PATH',)
__transmission__ = ('TRANSMISSION_RPC_URL', 'TRANSMISSION_RPC_PORT',)
__aria2__ = ('ARIA2_RPC_URL', 'ARIA2_RPC_TOKEN',)

__download_delegate__ = __wget__ + __thunder__ + __aria2__ + __transmission__

# fake __all__
__all__ = ('BANGUMI_MOE_URL', 'SAVE_PATH', 'DOWNLOAD_DELEGATE',
           'MAX_PAGE', 'DATA_SOURCE', 'TMP_PATH', 'DANMAKU_API_URL',
           'LANG', 'FRONT_STATIC_PATH', 'ADMIN_TOKEN', 'SHARE_DMHY_URL')

# cannot be rewrite
__readonly__ = ('BGMI_PATH', 'DB_PATH', 'CONFIG_FILE_PATH',
                'SCRIPT_PATH', 'SCRIPT_DB_PATH', 'FRONT_STATIC_PATH',)

# writeable
__writeable__ = tuple([i for i in __all__ if i not in __readonly__])

# the real __all__
__all__ = __all__ + __download_delegate__ + __readonly__

DOWNLOAD_DELEGATE_MAP = {
    'rr!': __wget__,
    'aria2-rpc': __aria2__,
    'xunlei': __thunder__,
    'transmission-rpc': __transmission__,
}

# --------- Immutable ---------- #
if platform.system() == 'Windows':
    BGMI_PATH = os.path.join(os.environ.get('USERPROFILE', None), '.bgmi')
    if not BGMI_PATH:
        raise SystemExit
else:
    BGMI_PATH = os.path.join(os.environ.get('HOME', '/tmp'), '.bgmi')

DB_PATH = os.path.join(BGMI_PATH, 'bangumi.db')
CONFIG_FILE_PATH = os.path.join(BGMI_PATH, 'bgmi.cfg')

SCRIPT_DB_PATH = os.path.join(BGMI_PATH, 'script.db')
SCRIPT_PATH = os.path.join(BGMI_PATH, 'scripts')

def read_config():
    c = configparser.ConfigParser()
    if not os.path.exists(CONFIG_FILE_PATH):
        write_default_config()
        return
    c.read(CONFIG_FILE_PATH)

    for i in __writeable__:
        if c.has_option('bgmi', i):
            globals().update({i: c.get('bgmi', i)})

    for i in DOWNLOAD_DELEGATE_MAP.get(DOWNLOAD_DELEGATE):
        if c.has_option(DOWNLOAD_DELEGATE, i):
            globals().update({i: c.get(DOWNLOAD_DELEGATE, i)})

def print_config():
    c = configparser.ConfigParser()
    if not os.path.exists(CONFIG_FILE_PATH):
        return

    c.read(CONFIG_FILE_PATH)
    string = ''
    string += '[bgmi]\n'
    for i in __writeable__:
        string += '{0}={1}\n'.format(i, c.get('bgmi', i))

    string += '\n[{0}]\n'.format(DOWNLOAD_DELEGATE)
    for i in DOWNLOAD_DELEGATE_MAP.get(DOWNLOAD_DELEGATE):
        string += '{0}={1}\n'.format(i, c.get(DOWNLOAD_DELEGATE, i))
    return string

def write_default_config():
    c = configparser.ConfigParser()
    if not c.has_section('bgmi'):
        c.add_section('bgmi')

    for k in __writeable__:
        v = globals().get(k, None)
        if k == 'ADMIN_TOKEN' and v is None:
            if sys.version_info > (3, 0):
                v = hashlib.md5(str(random.random()).encode('utf-8')).hexdigest()
            else:
                v = hashlib.md5(str(random.random())).hexdigest()
        c.set('bgmi', k, v)

    if DOWNLOAD_DELEGATE not in DOWNLOAD_DELEGATE_MAP.keys():
        raise Exception(DOWNLOAD_DELEGATE)

    if not c.has_section(DOWNLOAD_DELEGATE):
        c.add_section(DOWNLOAD_DELEGATE)

    for k in DOWNLOAD_DELEGATE_MAP.get(DOWNLOAD_DELEGATE):
        v = globals().get(k, None)
        c.set(DOWNLOAD_DELEGATE, k, v)

    try:
        with open(CONFIG_FILE_PATH, 'w') as f:
            c.write(f)
    except IOError:
        print('[-] Error writing to config file and ignored')

def write_config(config=None, value=None):
    if not os.path.exists(CONFIG_FILE_PATH):
        write_default_config()

    c = configparser.ConfigParser()
    c.read(CONFIG_FILE_PATH)
    if config is not None and config not in __writeable__ and config not in __download_delegate__:
        result = {'status': 'error',
                  'message': '{0} does not exist or not writeable'.format(config)}
        return result

    try:
        # result = {}
        if config is None:
            result = {'status': 'info',
                      'message': print_config()}

        elif value is None:  # config(config, None)
            result = {'status': 'success'}

            if config in __download_delegate__:
                result['message'] = '{0}={1}'.format(config, c.get(DOWNLOAD_DELEGATE, config))
            else:
                result['message'] = '{0}={1}'.format(config, c.get('bgmi', config))

        else:  # config(config, Value)
            if config in __writeable__:
                if config == 'DOWNLOAD_DELEGATE' and value not in DOWNLOAD_DELEGATE_MAP:
                    result = {'status': 'error',
                              'message': '{0} is not a support download_delegate'.format(value)}
                else:
                    c.set('bgmi', config, value)
                    with open(CONFIG_FILE_PATH, 'w') as f:
                        c.write(f)
                    read_config()
                    if config == 'DOWNLOAD_DELEGATE':
                        if not c.has_section(DOWNLOAD_DELEGATE):
                            c.add_section(DOWNLOAD_DELEGATE)
                            for i in DOWNLOAD_DELEGATE_MAP.get(DOWNLOAD_DELEGATE):
                                v = globals().get(i, '')
                                c.set(DOWNLOAD_DELEGATE, i, v)

                            with open(CONFIG_FILE_PATH, 'w') as f:
                                c.write(f)
                    result = {'status': 'success',
                              'message': '{0} has been set to {1}'.format(config, value)}

            elif config in DOWNLOAD_DELEGATE_MAP.get(DOWNLOAD_DELEGATE):
                c.set(DOWNLOAD_DELEGATE, config, value)
                with open(CONFIG_FILE_PATH, 'w') as f:
                    c.write(f)
                result = {'status': 'success',
                          'message': '{0} has been set to {1}'.format(config, value)}
            else:
                result = {'status': 'error',
                          'message': '{0} does not exist or not writeable'.format(config)}

    except configparser.NoOptionError:
        write_default_config()
        result = {'status': 'error', 'message': 'Error in config file, write default config'}

    result['data'] = [{'writable': True, 'name': x, 'value': globals()[x]} for x in __writeable__] + \
                     [{'writable': False, 'name': x, 'value': globals()[x]} for x in __readonly__]
    return result

# --------- Writeable ---------- #
# Setting bangumi.moe url
BANGUMI_MOE_URL = 'https://bangumi.moe'

# Setting share.dmhy.org url
SHARE_DMHY_URL = 'http://share.dmhy.org'

# Setting bangumi.moe url
DATA_SOURCE = 'bangumi_moe'

# BGmi user path
SAVE_PATH = os.path.join(BGMI_PATH, 'bangumi')
FRONT_STATIC_PATH = os.path.join(BGMI_PATH, 'front_static')

# admin token
ADMIN_TOKEN = None

# Xunlei offline download
XUNLEI_LX_PATH = os.path.join(BGMI_PATH, 'bgmi-lx')

# temp path
TMP_PATH = os.path.join(BGMI_PATH, 'tmp')

# Download delegate
DOWNLOAD_DELEGATE = 'aria2-rpc'

# danmaku api url, https://github.com/DIYgod/DPlayer#related-projects
DANMAKU_API_URL = ''

# bangumi cover url
COVER_URL = 'https://bangumi.moe'

# language
LANG = 'zh_cn'

# max page
MAX_PAGE = '3'

# aria2
ARIA2_RPC_URL = 'http://localhost:6800/rpc'
ARIA2_RPC_TOKEN = 'token:'

# path of wget
WGET_PATH = '/usr/bin/wget'

# transmission-rpc
TRANSMISSION_RPC_URL = '127.0.0.1'
TRANSMISSION_RPC_PORT = '9091'

# tag of bangumi on bangumi.moe
BANGUMI_TAG = '549ef207fe682f7549f1ea90'

# ------------------------------ #
# !!! Read config from file and write to globals() !!!
read_config()
# ------------------------------ #

# --------- Read-Only ---------- #
# Python version
IS_PYTHON3 = sys.version_info > (3, 0)

# Detail URL
<commit_msg>change defult config SHARE_DMHY_URL='https://share-dmhy.two.moe'<commit_after># coding=utf-8
from __future__ import unicode_literals

import hashlib
import os
import platform
import random
import sys

try:
    import ConfigParser as configparser
except ImportError:
    import configparser

# download delegate
__wget__ = ('WGET_PATH',)
__thunder__ = ('XUNLEI_LX_PATH',)
__transmission__ = ('TRANSMISSION_RPC_URL', 'TRANSMISSION_RPC_PORT',)
__aria2__ = ('ARIA2_RPC_URL', 'ARIA2_RPC_TOKEN',)

__download_delegate__ = __wget__ + __thunder__ + __aria2__ + __transmission__

# fake __all__
__all__ = ('BANGUMI_MOE_URL', 'SAVE_PATH', 'DOWNLOAD_DELEGATE',
           'MAX_PAGE', 'DATA_SOURCE', 'TMP_PATH', 'DANMAKU_API_URL',
           'LANG', 'FRONT_STATIC_PATH', 'ADMIN_TOKEN', 'SHARE_DMHY_URL')

# cannot be rewrite
__readonly__ = ('BGMI_PATH', 'DB_PATH', 'CONFIG_FILE_PATH',
                'SCRIPT_PATH', 'SCRIPT_DB_PATH', 'FRONT_STATIC_PATH',)

# writeable
__writeable__ = tuple([i for i in __all__ if i not in __readonly__])

# the real __all__
__all__ = __all__ + __download_delegate__ + __readonly__

DOWNLOAD_DELEGATE_MAP = {
    'rr!': __wget__,
    'aria2-rpc': __aria2__,
    'xunlei': __thunder__,
    'transmission-rpc': __transmission__,
}

# --------- Immutable ---------- #
if platform.system() == 'Windows':
    BGMI_PATH = os.path.join(os.environ.get('USERPROFILE', None), '.bgmi')
    if not BGMI_PATH:
        raise SystemExit
else:
    BGMI_PATH = os.path.join(os.environ.get('HOME', '/tmp'), '.bgmi')

DB_PATH = os.path.join(BGMI_PATH, 'bangumi.db')
CONFIG_FILE_PATH = os.path.join(BGMI_PATH, 'bgmi.cfg')

SCRIPT_DB_PATH = os.path.join(BGMI_PATH, 'script.db')
SCRIPT_PATH = os.path.join(BGMI_PATH, 'scripts')

def read_config():
    c = configparser.ConfigParser()
    if not os.path.exists(CONFIG_FILE_PATH):
        write_default_config()
        return
    c.read(CONFIG_FILE_PATH)

    for i in __writeable__:
        if c.has_option('bgmi', i):
            globals().update({i: c.get('bgmi', i)})

    for i in DOWNLOAD_DELEGATE_MAP.get(DOWNLOAD_DELEGATE):
        if c.has_option(DOWNLOAD_DELEGATE, i):
            globals().update({i: c.get(DOWNLOAD_DELEGATE, i)})

def print_config():
    c = configparser.ConfigParser()
    if not os.path.exists(CONFIG_FILE_PATH):
        return

    c.read(CONFIG_FILE_PATH)
    string = ''
    string += '[bgmi]\n'
    for i in __writeable__:
        string += '{0}={1}\n'.format(i, c.get('bgmi', i))

    string += '\n[{0}]\n'.format(DOWNLOAD_DELEGATE)
    for i in DOWNLOAD_DELEGATE_MAP.get(DOWNLOAD_DELEGATE):
        string += '{0}={1}\n'.format(i, c.get(DOWNLOAD_DELEGATE, i))
    return string

def write_default_config():
    c = configparser.ConfigParser()
    if not c.has_section('bgmi'):
        c.add_section('bgmi')

    for k in __writeable__:
        v = globals().get(k, None)
        if k == 'ADMIN_TOKEN' and v is None:
            if sys.version_info > (3, 0):
                v = hashlib.md5(str(random.random()).encode('utf-8')).hexdigest()
            else:
                v = hashlib.md5(str(random.random())).hexdigest()
        c.set('bgmi', k, v)

    if DOWNLOAD_DELEGATE not in DOWNLOAD_DELEGATE_MAP.keys():
        raise Exception(DOWNLOAD_DELEGATE)

    if not c.has_section(DOWNLOAD_DELEGATE):
        c.add_section(DOWNLOAD_DELEGATE)

    for k in DOWNLOAD_DELEGATE_MAP.get(DOWNLOAD_DELEGATE):
        v = globals().get(k, None)
        c.set(DOWNLOAD_DELEGATE, k, v)

    try:
        with open(CONFIG_FILE_PATH, 'w') as f:
            c.write(f)
    except IOError:
        print('[-] Error writing to config file and ignored')

def write_config(config=None, value=None):
    if not os.path.exists(CONFIG_FILE_PATH):
        write_default_config()

    c = configparser.ConfigParser()
    c.read(CONFIG_FILE_PATH)
    if config is not None and config not in __writeable__ and config not in __download_delegate__:
        result = {'status': 'error',
                  'message': '{0} does not exist or not writeable'.format(config)}
        return result

    try:
        # result = {}
        if config is None:
            result = {'status': 'info',
                      'message': print_config()}

        elif value is None:  # config(config, None)
            result = {'status': 'success'}

            if config in __download_delegate__:
                result['message'] = '{0}={1}'.format(config, c.get(DOWNLOAD_DELEGATE, config))
            else:
                result['message'] = '{0}={1}'.format(config, c.get('bgmi', config))

        else:  # config(config, Value)
            if config in __writeable__:
                if config == 'DOWNLOAD_DELEGATE' and value not in DOWNLOAD_DELEGATE_MAP:
                    result = {'status': 'error',
                              'message': '{0} is not a support download_delegate'.format(value)}
                else:
                    c.set('bgmi', config, value)
                    with open(CONFIG_FILE_PATH, 'w') as f:
                        c.write(f)
                    read_config()
                    if config == 'DOWNLOAD_DELEGATE':
                        if not c.has_section(DOWNLOAD_DELEGATE):
                            c.add_section(DOWNLOAD_DELEGATE)
                            for i in DOWNLOAD_DELEGATE_MAP.get(DOWNLOAD_DELEGATE):
                                v = globals().get(i, '')
                                c.set(DOWNLOAD_DELEGATE, i, v)

                            with open(CONFIG_FILE_PATH, 'w') as f:
                                c.write(f)
                    result = {'status': 'success',
                              'message': '{0} has been set to {1}'.format(config, value)}

            elif config in DOWNLOAD_DELEGATE_MAP.get(DOWNLOAD_DELEGATE):
                c.set(DOWNLOAD_DELEGATE, config, value)
                with open(CONFIG_FILE_PATH, 'w') as f:
                    c.write(f)
                result = {'status': 'success',
                          'message': '{0} has been set to {1}'.format(config, value)}
            else:
                result = {'status': 'error',
                          'message': '{0} does not exist or not writeable'.format(config)}

    except configparser.NoOptionError:
        write_default_config()
        result = {'status': 'error', 'message': 'Error in config file, write default config'}

    result['data'] = [{'writable': True, 'name': x, 'value': globals()[x]} for x in __writeable__] + \
                     [{'writable': False, 'name': x, 'value': globals()[x]} for x in __readonly__]
    return result

# --------- Writeable ---------- #
# Setting bangumi.moe url
BANGUMI_MOE_URL = 'https://bangumi.moe'

# Setting share.dmhy.org url
SHARE_DMHY_URL = 'https://share-dmhy.two.moe'

# Setting bangumi.moe url
DATA_SOURCE = 'bangumi_moe'

# BGmi user path
SAVE_PATH = os.path.join(BGMI_PATH, 'bangumi')
FRONT_STATIC_PATH = os.path.join(BGMI_PATH, 'front_static')

# admin token
ADMIN_TOKEN = None

# Xunlei offline download
XUNLEI_LX_PATH = os.path.join(BGMI_PATH, 'bgmi-lx')

# temp path
TMP_PATH = os.path.join(BGMI_PATH, 'tmp')

# Download delegate
DOWNLOAD_DELEGATE = 'aria2-rpc'

# danmaku api url, https://github.com/DIYgod/DPlayer#related-projects
DANMAKU_API_URL = ''

# bangumi cover url
COVER_URL = 'https://bangumi.moe'

# language
LANG = 'zh_cn'

# max page
MAX_PAGE = '3'

# aria2
ARIA2_RPC_URL = 'http://localhost:6800/rpc'
ARIA2_RPC_TOKEN = 'token:'

# path of wget
WGET_PATH = '/usr/bin/wget'

# transmission-rpc
TRANSMISSION_RPC_URL = '127.0.0.1'
TRANSMISSION_RPC_PORT = '9091'

# tag of bangumi on bangumi.moe
BANGUMI_TAG = '549ef207fe682f7549f1ea90'

# ------------------------------ #
# !!! Read config from file and write to globals() !!!
read_config()
# ------------------------------ #

# --------- Read-Only ---------- #
# Python version
IS_PYTHON3 = sys.version_info > (3, 0)

# Detail URL
<|endoftext|>


<commit_before>#!/usr/bin/env python
#
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Builds all Fuchsia artifacts vended by Flutter.
"""

import argparse
import errno
import os
import platform
import shutil
import subprocess
import sys
import tempfile

from gather_flutter_runner_artifacts import GatherArtifacts
from gen_package import CreateFarPackage

_script_dir = os.path.abspath(os.path.join(os.path.realpath(__file__), '..'))
_src_root_dir = os.path.join(_script_dir, '..', '..', '..')
_out_dir = os.path.join(_src_root_dir, 'out')
_bucket_directory = os.path.join(_out_dir, 'fuchsia_bucket')

def IsLinux():
  return platform.system() == 'Linux'

def IsMac():
  return platform.system() == 'Darwin'

def GetPMBinPath():
  # host_os references the gn host_os
  # https://gn.googlesource.com/gn/+/master/docs/reference.md#var_host_os
  host_os = ''
  if IsLinux():
    host_os = 'linux'
  elif IsMac():
    host_os = 'mac'
  else:
    host_os = 'windows'

  return os.path.join(_src_root_dir, 'fuchsia', 'sdk', host_os, 'tools', 'pm')

def RunExecutable(command):
  subprocess.check_call(command, cwd=_src_root_dir)

def RunGN(variant_dir, flags):
  RunExecutable([
      os.path.join('flutter', 'tools', 'gn'),
  ] + flags)

  assert os.path.exists(os.path.join(_out_dir, variant_dir))

def BuildNinjaTargets(variant_dir, targets):
  assert os.path.exists(os.path.join(_out_dir, variant_dir))

  RunExecutable(['autoninja', '-C',
                 os.path.join(_out_dir, variant_dir)] + targets)

def RemoveDirectoryIfExists(path):
  if not os.path.exists(path):
    return

  if os.path.isfile(path) or os.path.islink(path):
    os.unlink(path)
  else:
    shutil.rmtree(path)

def CopyToBucket(source, destination):
  source = os.path.join(_out_dir, source)
  temp_artifact_dir = tempfile.mkdtemp()

  GatherArtifacts(source, temp_artifact_dir)
  pm_bin = GetPMBinPath()
  key_path = os.path.join(_script_dir, 'development.key')

  destination = os.path.join(_bucket_directory, destination)
  CreateFarPackage(pm_bin, temp_artifact_dir, key_path, destination)

def BuildBucket():
  RemoveDirectoryIfExists(_bucket_directory)

  CopyToBucket('fuchsia_debug/', 'flutter/debug/')
  CopyToBucket('fuchsia_profile/', 'flutter/profile/')
  CopyToBucket('fuchsia_release/', 'flutter/release/')

def CopyFiles(source, destination):
  try:
    shutil.copytree(source, destination)
  except OSError as error:
    if error.errno == errno.ENOTDIR:
      shutil.copy(source, destination)
    else:
      raise

def ProcessCIPDPakcage(upload, engine_version):
  # Copy the CIPD YAML template from the source directory to be next to the bucket
  # we are about to package.
  cipd_yaml = os.path.join(_script_dir, 'fuchsia.cipd.yaml')
  CopyFiles(cipd_yaml, os.path.join(_bucket_directory, 'fuchsia.cipd.yaml'))

  if upload and IsLinux():
    command = [
        'cipd', 'create', '-pkg-def', 'fuchsia.cipd.yaml', '-ref', 'latest',
        '-tag',
        'git_revision:%s' % engine_version
    ]
  else:
    command = [
        'cipd', 'pkg-build', '-pkg-def', 'fuchsia.cipd.yaml', '-out',
        os.path.join(_bucket_directory, 'fuchsia.cipd')
    ]

  subprocess.check_call(command, cwd=_bucket_directory)

def main():
  parser = argparse.ArgumentParser()

  parser.add_argument(
      '--upload',
      default=False,
      action='store_true',
      help='If set, uploads the CIPD package and tags it as the latest.')

  parser.add_argument(
      '--engine-version',
      required=True,
      help='Specifies the flutter engine SHA.')

  args = parser.parse_args()

  common_flags = [
      '--fuchsia',
      # The source does not require LTO and LTO is not wired up for targets.
      '--no-lto',
  ]

  RunGN('fuchsia_debug', common_flags + ['--runtime-mode', 'debug'])

  RunGN('fuchsia_profile', common_flags + ['--runtime-mode', 'profile'])

  RunGN('fuchsia_release', common_flags + ['--runtime-mode', 'release'])

  targets_to_build = [
      # The Flutter Runner.
      'flutter/shell/platform/fuchsia/flutter:flutter',

      # The Dart Runner.
      'flutter/shell/platform/fuchsia/dart:dart',

      # The Snapshots.
      'flutter/lib/snapshot:snapshot',
  ]

  BuildNinjaTargets('fuchsia_debug', targets_to_build)
  BuildNinjaTargets('fuchsia_profile', targets_to_build)
  BuildNinjaTargets('fuchsia_release', targets_to_build)

  BuildBucket()

  ProcessCIPDPakcage(args.upload, args.engine_version)

if __name__ == '__main__':
  main()
<commit_msg>Change flutter runner target for LUCI (#10075)<commit_after>#!/usr/bin/env python
#
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Builds all Fuchsia artifacts vended by Flutter.
"""

import argparse
import errno
import os
import platform
import shutil
import subprocess
import sys
import tempfile

from gather_flutter_runner_artifacts import GatherArtifacts
from gen_package import CreateFarPackage

_script_dir = os.path.abspath(os.path.join(os.path.realpath(__file__), '..'))
_src_root_dir = os.path.join(_script_dir, '..', '..', '..')
_out_dir = os.path.join(_src_root_dir, 'out')
_bucket_directory = os.path.join(_out_dir, 'fuchsia_bucket')

def IsLinux():
  return platform.system() == 'Linux'

def IsMac():
  return platform.system() == 'Darwin'

def GetPMBinPath():
  # host_os references the gn host_os
  # https://gn.googlesource.com/gn/+/master/docs/reference.md#var_host_os
  host_os = ''
  if IsLinux():
    host_os = 'linux'
  elif IsMac():
    host_os = 'mac'
  else:
    host_os = 'windows'

  return os.path.join(_src_root_dir, 'fuchsia', 'sdk', host_os, 'tools', 'pm')

def RunExecutable(command):
  subprocess.check_call(command, cwd=_src_root_dir)

def RunGN(variant_dir, flags):
  RunExecutable([
      os.path.join('flutter', 'tools', 'gn'),
  ] + flags)

  assert os.path.exists(os.path.join(_out_dir, variant_dir))

def BuildNinjaTargets(variant_dir, targets):
  assert os.path.exists(os.path.join(_out_dir, variant_dir))

  RunExecutable(['autoninja', '-C',
                 os.path.join(_out_dir, variant_dir)] + targets)

def RemoveDirectoryIfExists(path):
  if not os.path.exists(path):
    return

  if os.path.isfile(path) or os.path.islink(path):
    os.unlink(path)
  else:
    shutil.rmtree(path)

def CopyToBucket(source, destination):
  source = os.path.join(_out_dir, source)
  temp_artifact_dir = tempfile.mkdtemp()

  GatherArtifacts(source, temp_artifact_dir)
  pm_bin = GetPMBinPath()
  key_path = os.path.join(_script_dir, 'development.key')

  destination = os.path.join(_bucket_directory, destination)
  CreateFarPackage(pm_bin, temp_artifact_dir, key_path, destination)

def BuildBucket():
  RemoveDirectoryIfExists(_bucket_directory)

  CopyToBucket('fuchsia_debug/', 'flutter/debug/')
  CopyToBucket('fuchsia_profile/', 'flutter/profile/')
  CopyToBucket('fuchsia_release/', 'flutter/release/')

def CopyFiles(source, destination):
  try:
    shutil.copytree(source, destination)
  except OSError as error:
    if error.errno == errno.ENOTDIR:
      shutil.copy(source, destination)
    else:
      raise

def ProcessCIPDPakcage(upload, engine_version):
  # Copy the CIPD YAML template from the source directory to be next to the bucket
  # we are about to package.
  cipd_yaml = os.path.join(_script_dir, 'fuchsia.cipd.yaml')
  CopyFiles(cipd_yaml, os.path.join(_bucket_directory, 'fuchsia.cipd.yaml'))

  if upload and IsLinux():
    command = [
        'cipd', 'create', '-pkg-def', 'fuchsia.cipd.yaml', '-ref', 'latest',
        '-tag',
        'git_revision:%s' % engine_version
    ]
  else:
    command = [
        'cipd', 'pkg-build', '-pkg-def', 'fuchsia.cipd.yaml', '-out',
        os.path.join(_bucket_directory, 'fuchsia.cipd')
    ]

  subprocess.check_call(command, cwd=_bucket_directory)

def main():
  parser = argparse.ArgumentParser()

  parser.add_argument(
      '--upload',
      default=False,
      action='store_true',
      help='If set, uploads the CIPD package and tags it as the latest.')

  parser.add_argument(
      '--engine-version',
      required=True,
      help='Specifies the flutter engine SHA.')

  args = parser.parse_args()

  common_flags = [
      '--fuchsia',
      # The source does not require LTO and LTO is not wired up for targets.
      '--no-lto',
  ]

  RunGN('fuchsia_debug', common_flags + ['--runtime-mode', 'debug'])

  RunGN('fuchsia_profile', common_flags + ['--runtime-mode', 'profile'])

  RunGN('fuchsia_release', common_flags + ['--runtime-mode', 'release'])

  targets_to_build = [
      # The Flutter Runner.
      'flutter/shell/platform/fuchsia/flutter:flutter_jit_runner',

      # The Dart Runner.
      'flutter/shell/platform/fuchsia/dart:dart',

      # The Snapshots.
      'flutter/lib/snapshot:snapshot',
  ]

  BuildNinjaTargets('fuchsia_debug', targets_to_build)
  BuildNinjaTargets('fuchsia_profile', targets_to_build)
  BuildNinjaTargets('fuchsia_release', targets_to_build)

  BuildBucket()

  ProcessCIPDPakcage(args.upload, args.engine_version)

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


<commit_before>from bgl import *
from .widget import *
from .theme import *
from collections import OrderedDict

class System(Widget):
	"""The main gui system. Add widgets to this and then call the render() method
	draw the gui.

	"""

	normalize_text = True

	def __init__(self, theme=None):
		"""
		:param theme: the path to a theme directory

		"""

		# Size and positions for children to use.
		# The size will the the view port size and
		# the position will be the top left of the screen

		# Get some viewport info
		view_buf = Buffer(GL_INT, 4)
		glGetIntegerv(GL_VIEWPORT, view_buf)
		view = view_buf.list

		# Theming
		self.system = self
		self.theme = Theme(theme) if theme else None
		self.focused_widget = None
		self.lock_focus = False

		Widget.__init__(self, self, "<System>", size=[view[2], view[3]],
					pos=[0, 0], options=0)

	def update_mouse(self, pos, click_state=BGUI_MOUSE_NONE):
		"""Updates the system's mouse data

		:param pos: the mouse position
		:param click_state: the current state of the mouse
		:rtype: None

		"""

		self.cursor_pos = pos

		Widget._handle_mouse(self, pos, click_state)

	def update_keyboard(self, key, is_shifted):
		"""Updates the system's keyboard data

		:param key: the key being input
		:param is_shifted: is the shift key held down?
		:rtype: None

		"""

		if self.focused_widget:
			self.focused_widget._handle_key(key, is_shifted)

	def _attach_widget(self, widget):
		if widget == self:
			return

		Widget._attach_widget(self, widget)
	def render(self):
		"""Renders the GUI system

		:rtype: None

		"""

		# Get some viewport info
		view_buf = Buffer(GL_INT, 4)
		glGetIntegerv(GL_VIEWPORT, view_buf)
		view = view_buf.list

		# Save the state
		glPushAttrib(GL_ALL_ATTRIB_BITS)

		# Disable depth test so we always draw over things
		glDisable(GL_DEPTH_TEST)

		# Disable lighting so everything is shadless
		glDisable(GL_LIGHTING)

		# Unbinding the texture prevents BGUI frames from somehow picking up on
		# color of the last used texture
		glBindTexture(GL_TEXTURE_2D, 0)

		# Make sure we're using smooth shading instead of flat
		glShadeModel(GL_SMOOTH)

		# Setup the matrices
		glMatrixMode(GL_PROJECTION)
		glPushMatrix()
		glLoadIdentity()
		gluOrtho2D(0, view[2], 0, view[3])
		glMatrixMode(GL_MODELVIEW)
		glPushMatrix()
		glLoadIdentity()

		# Update any animations
		Widget._update_anims(self)

		# Render the windows
		Widget._draw(self)

		# Reset the state
		glPopMatrix()
		glMatrixMode(GL_PROJECTION)
		glPopMatrix()
		glPopAttrib()<commit_msg>Removing an import in system.py that's no longer needed.<commit_after>from bgl import *
from .widget import *
from .theme import *

class System(Widget):
	"""The main gui system. Add widgets to this and then call the render() method
	draw the gui.

	"""

	normalize_text = True

	def __init__(self, theme=None):
		"""
		:param theme: the path to a theme directory

		"""

		# Size and positions for children to use.
		# The size will the the view port size and
		# the position will be the top left of the screen

		# Get some viewport info
		view_buf = Buffer(GL_INT, 4)
		glGetIntegerv(GL_VIEWPORT, view_buf)
		view = view_buf.list

		# Theming
		self.system = self
		self.theme = Theme(theme) if theme else None
		self.focused_widget = None
		self.lock_focus = False

		Widget.__init__(self, self, "<System>", size=[view[2], view[3]],
					pos=[0, 0], options=0)

	def update_mouse(self, pos, click_state=BGUI_MOUSE_NONE):
		"""Updates the system's mouse data

		:param pos: the mouse position
		:param click_state: the current state of the mouse
		:rtype: None

		"""

		self.cursor_pos = pos

		Widget._handle_mouse(self, pos, click_state)

	def update_keyboard(self, key, is_shifted):
		"""Updates the system's keyboard data

		:param key: the key being input
		:param is_shifted: is the shift key held down?
		:rtype: None

		"""

		if self.focused_widget:
			self.focused_widget._handle_key(key, is_shifted)

	def _attach_widget(self, widget):
		if widget == self:
			return

		Widget._attach_widget(self, widget)
	def render(self):
		"""Renders the GUI system

		:rtype: None

		"""

		# Get some viewport info
		view_buf = Buffer(GL_INT, 4)
		glGetIntegerv(GL_VIEWPORT, view_buf)
		view = view_buf.list

		# Save the state
		glPushAttrib(GL_ALL_ATTRIB_BITS)

		# Disable depth test so we always draw over things
		glDisable(GL_DEPTH_TEST)

		# Disable lighting so everything is shadless
		glDisable(GL_LIGHTING)

		# Unbinding the texture prevents BGUI frames from somehow picking up on
		# color of the last used texture
		glBindTexture(GL_TEXTURE_2D, 0)

		# Make sure we're using smooth shading instead of flat
		glShadeModel(GL_SMOOTH)

		# Setup the matrices
		glMatrixMode(GL_PROJECTION)
		glPushMatrix()
		glLoadIdentity()
		gluOrtho2D(0, view[2], 0, view[3])
		glMatrixMode(GL_MODELVIEW)
		glPushMatrix()
		glLoadIdentity()

		# Update any animations
		Widget._update_anims(self)

		# Render the windows
		Widget._draw(self)

		# Reset the state
		glPopMatrix()
		glMatrixMode(GL_PROJECTION)
		glPopMatrix()
		glPopAttrib()<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
import time

from syncano.models import Object
from syncano_cli.logger import get_logger
from syncano_cli.parse_to_syncano.config import PARSE_PAGINATION_LIMIT
from syncano_cli.parse_to_syncano.migrations.aggregation import data_aggregate
from syncano_cli.parse_to_syncano.migrations.mixins import PaginationMixin, ParseConnectionMixin, SyncanoConnectionMixin
from syncano_cli.parse_to_syncano.migrations.relation import RelationProcessor
from syncano_cli.parse_to_syncano.processors.klass import ClassProcessor

LOG = get_logger('parse-to-syncano')

class SyncanoTransfer(ParseConnectionMixin, SyncanoConnectionMixin, PaginationMixin):

    def __init__(self, config):
        super(SyncanoTransfer, self).__init__()
        self.data = data_aggregate
        self.data.clear()
        self.syncano_classes = {}
        self.file_descriptors = {}
        self.relations = None
        self.config = config

    def set_relations(self, relations):
        self.relations = relations

    def process_relations(self, instance):
        if self.relations:
            RelationProcessor(relations=self.relations).process(instance=instance, config=self.config)

    def get_syncano_instance(self):
        try:
            instance = self.syncano.Instance.please.get(name=self.config.get('P2S', 'SYNCANO_INSTANCE_NAME'))
        except:
            instance = self.syncano.Instance.please.create(name=self.config.get('P2S', 'SYNCANO_INSTANCE_NAME'))

        return instance

    def transfer_classes(self, instance):
        schemas = self.parse.get_schemas()

        relations = []

        for parse_schema in schemas:
            syncano_schema = ClassProcessor.create_schema(parse_schema)
            self.data.add_class(
                syncano_name=syncano_schema.class_name,
                syncano_schema=syncano_schema.schema,
                parse_name=parse_schema['className'],
                parse_schema=parse_schema
            )

            if syncano_schema.has_relations:
                relations.append(
                    {
                        syncano_schema.class_name: syncano_schema.relations
                    }
                )

        for class_to_process in self.data.sort_classes():
            try:
                instance.classes.create(name=class_to_process.syncano_name, schema=class_to_process.syncano_schema)
            except Exception as e:
                LOG.warning('Class already defined in this instance: {}/{}; Using existing class'.format(
                    class_to_process.syncano_name, instance.name)
                )
                LOG.warning(e)
            time.sleep(1)  # avoid throttling;

        self.set_relations(relations)

    def transfer_objects(self, instance):
        for class_to_process in self.data.sort_classes():
            limit, skip = self.get_limit_and_skip()
            processed = 0

            while True:
                objects = self.parse.get_class_objects(class_to_process.parse_name, limit=limit, skip=skip)
                if not objects['results']:
                    break
                limit += PARSE_PAGINATION_LIMIT
                skip += PARSE_PAGINATION_LIMIT
                objects_to_add, parse_ids = self._clear_data()

                for data_object in objects['results']:
                    s_class = self.get_class(instance=instance, class_name=class_to_process.syncano_name)
                    syncano_object, files = ClassProcessor.process_object(data_object, self.data.reference_map)

                    self._handle_files(files, data_object, class_to_process)

                    if len(objects_to_add) == 10:
                        processed, objects_to_add, parse_ids = self._add_objects(processed, objects_to_add, parse_ids,
                                                                                s_class, class_to_process)

                    batched_syncano_object = s_class.objects.as_batch().create(**syncano_object)
                    objects_to_add.append(batched_syncano_object)
                    parse_ids.append(data_object['objectId'])

                    time.sleep(6)  # avoid throttling;

                # if objects to add is less than < 10 elements
                if objects_to_add:
                    self._add_last_objects(s_class, objects_to_add, parse_ids, class_to_process, processed)

    def transfer_files(self):
        for parse_id, (files, syncano_class_name, parse_class_name) in self.file_descriptors.iteritems():
            Object.please.update(
                class_name=syncano_class_name,
                id=self.data.reference_map[parse_class_name][parse_id],
                files=files
            )
            time.sleep(1)  # avoid throttling;

    def get_class(self, instance, class_name):
        s_class = self.syncano_classes.get(class_name)
        if not s_class:
            s_class = instance.classes.get(name=class_name)
            self.syncano_classes[class_name] = s_class
        return s_class

    def through_the_red_sea(self):
        instance = self.get_syncano_instance()
        self.transfer_classes(instance)
        self.transfer_objects(instance)
        self.transfer_files()
        self.process_relations(instance)
        LOG.info('Transfer completed')

    def _handle_files(self, files, data_object, class_to_process):
        if files:
            self.file_descriptors[data_object['objectId']] = (
                files,
                class_to_process.syncano_name,
                class_to_process.parse_name
            )

    def _add_last_objects(self, s_class, objects_to_add, parse_ids, class_to_process, processed):
        created_objects = s_class.objects.batch(
            *objects_to_add
        )

        self._update_reference_map(
            class_to_process=class_to_process,
            parse_ids=parse_ids,
            created_objects=created_objects
        )
        self._log_processing(processed + len(objects_to_add), class_to_process.syncano_name)

    def _add_objects(self, processed, objects_to_add, parse_ids, s_class, class_to_process):
        processed += 10
        created_objects = s_class.objects.batch(
            *objects_to_add
        )

        self._update_reference_map(
            class_to_process=class_to_process,
            parse_ids=parse_ids,
            created_objects=created_objects
        )

        objects_to_add, parse_ids = self._clear_data_wait_and_log(processed, class_to_process)

        return processed, objects_to_add, parse_ids

    def _update_reference_map(self, class_to_process, parse_ids, created_objects):
        for parse_id, syncano_id in zip(parse_ids, [o.id for o in created_objects]):
            self.data.reference_map[class_to_process.parse_name][parse_id] = syncano_id

    @classmethod
    def _clear_data(cls):
        return [], []

    @classmethod
    def _clear_data_wait_and_log(cls, processed, class_to_process):
        time.sleep(1)
        cls._log_processing(processed, class_to_process.syncano_name)
        return cls._clear_data()

    @classmethod
    def _log_processing(cls, num, class_name):
        LOG.info('Processed {} objects of class {}'.format(num, class_name))
<commit_msg>[LIB-820] change time.sleep value in creating objects;<commit_after># -*- coding: utf-8 -*-
import time

from syncano.models import Object
from syncano_cli.logger import get_logger
from syncano_cli.parse_to_syncano.config import PARSE_PAGINATION_LIMIT
from syncano_cli.parse_to_syncano.migrations.aggregation import data_aggregate
from syncano_cli.parse_to_syncano.migrations.mixins import PaginationMixin, ParseConnectionMixin, SyncanoConnectionMixin
from syncano_cli.parse_to_syncano.migrations.relation import RelationProcessor
from syncano_cli.parse_to_syncano.processors.klass import ClassProcessor

LOG = get_logger('parse-to-syncano')

class SyncanoTransfer(ParseConnectionMixin, SyncanoConnectionMixin, PaginationMixin):

    def __init__(self, config):
        super(SyncanoTransfer, self).__init__()
        self.data = data_aggregate
        self.data.clear()
        self.syncano_classes = {}
        self.file_descriptors = {}
        self.relations = None
        self.config = config

    def set_relations(self, relations):
        self.relations = relations

    def process_relations(self, instance):
        if self.relations:
            RelationProcessor(relations=self.relations).process(instance=instance, config=self.config)

    def get_syncano_instance(self):
        try:
            instance = self.syncano.Instance.please.get(name=self.config.get('P2S', 'SYNCANO_INSTANCE_NAME'))
        except:
            instance = self.syncano.Instance.please.create(name=self.config.get('P2S', 'SYNCANO_INSTANCE_NAME'))

        return instance

    def transfer_classes(self, instance):
        schemas = self.parse.get_schemas()

        relations = []

        for parse_schema in schemas:
            syncano_schema = ClassProcessor.create_schema(parse_schema)
            self.data.add_class(
                syncano_name=syncano_schema.class_name,
                syncano_schema=syncano_schema.schema,
                parse_name=parse_schema['className'],
                parse_schema=parse_schema
            )

            if syncano_schema.has_relations:
                relations.append(
                    {
                        syncano_schema.class_name: syncano_schema.relations
                    }
                )

        for class_to_process in self.data.sort_classes():
            try:
                instance.classes.create(name=class_to_process.syncano_name, schema=class_to_process.syncano_schema)
            except Exception as e:
                LOG.warning('Class already defined in this instance: {}/{}; Using existing class'.format(
                    class_to_process.syncano_name, instance.name)
                )
                LOG.warning(e)
            time.sleep(1)  # avoid throttling;

        self.set_relations(relations)

    def transfer_objects(self, instance):
        for class_to_process in self.data.sort_classes():
            limit, skip = self.get_limit_and_skip()
            processed = 0

            while True:
                objects = self.parse.get_class_objects(class_to_process.parse_name, limit=limit, skip=skip)
                if not objects['results']:
                    break
                limit += PARSE_PAGINATION_LIMIT
                skip += PARSE_PAGINATION_LIMIT
                objects_to_add, parse_ids = self._clear_data()

                for data_object in objects['results']:
                    s_class = self.get_class(instance=instance, class_name=class_to_process.syncano_name)
                    syncano_object, files = ClassProcessor.process_object(data_object, self.data.reference_map)

                    self._handle_files(files, data_object, class_to_process)

                    if len(objects_to_add) == 10:
                        processed, objects_to_add, parse_ids = self._add_objects(processed, objects_to_add, parse_ids,
                                                                                s_class, class_to_process)

                    batched_syncano_object = s_class.objects.as_batch().create(**syncano_object)
                    objects_to_add.append(batched_syncano_object)
                    parse_ids.append(data_object['objectId'])

                    time.sleep(1)  # avoid throttling;

                # if objects to add is less than < 10 elements
                if objects_to_add:
                    self._add_last_objects(s_class, objects_to_add, parse_ids, class_to_process, processed)

    def transfer_files(self):
        for parse_id, (files, syncano_class_name, parse_class_name) in self.file_descriptors.iteritems():
            Object.please.update(
                class_name=syncano_class_name,
                id=self.data.reference_map[parse_class_name][parse_id],
                files=files
            )
            time.sleep(1)  # avoid throttling;

    def get_class(self, instance, class_name):
        s_class = self.syncano_classes.get(class_name)
        if not s_class:
            s_class = instance.classes.get(name=class_name)
            self.syncano_classes[class_name] = s_class
        return s_class

    def through_the_red_sea(self):
        instance = self.get_syncano_instance()
        self.transfer_classes(instance)
        self.transfer_objects(instance)
        self.transfer_files()
        self.process_relations(instance)
        LOG.info('Transfer completed')

    def _handle_files(self, files, data_object, class_to_process):
        if files:
            self.file_descriptors[data_object['objectId']] = (
                files,
                class_to_process.syncano_name,
                class_to_process.parse_name
            )

    def _add_last_objects(self, s_class, objects_to_add, parse_ids, class_to_process, processed):
        created_objects = s_class.objects.batch(
            *objects_to_add
        )

        self._update_reference_map(
            class_to_process=class_to_process,
            parse_ids=parse_ids,
            created_objects=created_objects
        )
        self._log_processing(processed + len(objects_to_add), class_to_process.syncano_name)

    def _add_objects(self, processed, objects_to_add, parse_ids, s_class, class_to_process):
        processed += 10
        created_objects = s_class.objects.batch(
            *objects_to_add
        )

        self._update_reference_map(
            class_to_process=class_to_process,
            parse_ids=parse_ids,
            created_objects=created_objects
        )

        objects_to_add, parse_ids = self._clear_data_wait_and_log(processed, class_to_process)

        return processed, objects_to_add, parse_ids

    def _update_reference_map(self, class_to_process, parse_ids, created_objects):
        for parse_id, syncano_id in zip(parse_ids, [o.id for o in created_objects]):
            self.data.reference_map[class_to_process.parse_name][parse_id] = syncano_id

    @classmethod
    def _clear_data(cls):
        return [], []

    @classmethod
    def _clear_data_wait_and_log(cls, processed, class_to_process):
        time.sleep(1)
        cls._log_processing(processed, class_to_process.syncano_name)
        return cls._clear_data()

    @classmethod
    def _log_processing(cls, num, class_name):
        LOG.info('Processed {} objects of class {}'.format(num, class_name))
<|endoftext|>


<commit_before>
from helpers import *
from card_ranking import RankAgent

class Player:
    VERSION = "ALL IN + some hole card stuff"

    def betRequest(self, game_state):
        my_cards = get_hole_card_ranks(game_state)
        all_cards = get_all_cards(game_state)
        myself = get_myself(game_state)
        current_cash = int(myself["stack"])

        ra = RankAgent(all_cards)
        rank = ra.get_card_rank()
        offer = 0

        if player_count(game_state) > 2 and rank < 4:
            offer = 0
        else:
            minimal_amount = int(game_state["minimum_raise"])
            if is_preflop(game_state):
                if ra._is_high() and is_well_positioned(game_state):
                    offer = minimal_amount
                elif ra._is_pair() and ra._is_high(8):
                    offer = max(current_cash * 0.25, minimal_amount)
            elif rank >= 5:
                offer = current_cash
            else:
                offer = minimal_amount * (1 + rank * 0.1)

        return offer

    def showdown(self, game_state):
        pass
<commit_msg>fix of fix<commit_after>
from helpers import *
from card_ranking import RankAgent

class Player:
    VERSION = "ALL IN + some hole card stuff"

    def betRequest(self, game_state):
        my_cards = get_hole_card_ranks(game_state)
        all_cards = get_all_cards(game_state)
        myself = get_myself(game_state)
        current_cash = int(myself["stack"])

        ra = RankAgent(all_cards)
        rank = ra.get_card_rank()
        offer = 0

        if player_count(game_state) > 2 and rank < 4:
            offer = 0
        else:
            minimal_amount = int(game_state["minimum_raise"])
            if is_preflop(game_state):
                if ra._is_high() and is_well_positioned(game_state):
                    offer = minimal_amount

                if ra._is_pair() and ra._is_high(8):
                    offer = max(current_cash * 0.25, minimal_amount)
                if rank >= 5:
                    offer = max(current_cash * 0.5, minimal_amount)
            else:
                if rank == 0:
                    pass
                elif rank > 0 and rank < 5:
                    offer = max(minimal_amount, current_cash * 0.1)
                else:
                    offer = current_cash

        return offer

    def showdown(self, game_state):
        pass
<|endoftext|>


<commit_before>def r(w, i, d):
    x = w
    found = False
    for k in i:
        if k in x:
            x = x[k]
            found = True
    return x if found else d

class Player(object):
    VERSION = "[DWI] YOLO"

    team_name = "Deal With It"

    def __init__(self, game_state):
        self.game_state = game_state

    def bet_request(self):
        # FOLD in the first X round of the sit n go
        fold_until_round = 5

        if r(self.game_state, ['round'], 0) < fold_until_round:
            return 0

        # get our cards
        our_hand = self.get_cards(self.get_our_player())

        # should we fold
        if self.should_we_fold(our_hand):
            bet = 0
        else:
            bet = self.action_raise(50)

        return bet

    def get_current_bet(self):
        """
        Sum of all the players bets
        :return:
        """
        return r(self.game_state, ['pot'], 0)

    def get_our_money(self):
        """
        Returns the money we haven't BET yet

        :return: int
        """
        return self.get_our_player().get("stack", 0)

    def get_our_bet(self):
        """
        Returns the money we BET so far
        :return:
        """
        return self.get_our_player().get("bet", 0)

    def action_check(self):
        """
        Checks

        :return:
        """
        # current buy in - our chips = check (or fold is there is another raise)
        return r(self.game_state, ['current_buy_in'], 0) - self.get_our_player().get("bet", 0)

    def action_all_in(self):
        """
        ALL IN
        :return:
        """
        # current buy in + all the money we still have
        return r(self.game_state, ['current_buy_in'], 0) + self.get_our_player().get("stack", 0)

    def action_raise(self, amount=0):
        """
        Calls minimal raise + the amouns you give

        :param amount: The amoun you want to raise (will be added to the minimal raise amount)
        :return:
        """
        # current buy in + minimal raise + raise you want to do
        return r(self.game_state, ['current_buy_in'], 0) - self.get_our_player().get("bet", 0) + r(self.game_state,
                                                                                ['minimum_raise'],
                                                                                0) + amount

    def get_our_player(self):
        for player in self.game_state['players']:
            if player["name"] == self.team_name:
                return player

    @staticmethod
    def get_cards(player):
        return player['hole_cards']

    @staticmethod
    def is_pair_in_hand(hand):
        return hand[0]["rank"] == hand[1]["rank"]

    @staticmethod
    def should_we_fold(hand):
        return hand[0]["suit"] != hand[1]["suit"] and hand[0]["rank"] != hand[1]["rank"] and hand[0]["rank"] not in [
            "J", "K", "Q", "A"] and hand[1]["rank"] not in ["J", "K", "Q", "A"]

    def showdown(self):
        print('showdown {}'.format(self.game_state))

<commit_msg>little bugfix<commit_after>def r(w, i, d):
    x = w
    found = False
    for k in i:
        if k in x:
            x = x[k]
            found = True
    return x if found else d

class Player(object):
    VERSION = "[DWI] YOLO"

    team_name = "Deal With It"

    def __init__(self, game_state):
        self.game_state = game_state

    def bet_request(self):
        # FOLD in the first X round of the sit n go
        fold_until_round = 5

        if r(self.game_state, ['round'], 0) < fold_until_round:
            return 0

        # get our cards
        our_hand = self.get_cards(self.get_our_player())

        # should we fold
        if self.should_we_fold(our_hand):
            bet = 0
        else:
            bet = self.action_raise(50)

        return bet

    def get_current_bet(self):
        """
        Sum of all the players bets
        :return:
        """
        return r(self.game_state, ['pot'], 0)

    def get_our_money(self):
        """
        Returns the money we haven't BET yet

        :return: int
        """
        return self.get_our_player().get("stack", 0)

    def get_our_bet(self):
        """
        Returns the money we BET so far
        :return:
        """
        return self.get_our_player().get("bet", 0)

    def action_check(self):
        """
        Checks

        :return:
        """
        # current buy in - our chips = check (or fold is there is another raise)
        return r(self.game_state, ['current_buy_in'], 0) - self.get_our_player().get("bet", 0)

    def action_all_in(self):
        """
        ALL IN
        :return:
        """
        # current buy in + all the money we still have
        return r(self.game_state, ['current_buy_in'], 0) + self.get_our_player().get("stack", 0)

    def action_raise(self, amount=0):
        """
        Calls minimal raise + the amouns you give

        :param amount: The amoun you want to raise (will be added to the minimal raise amount)
        :return:
        """
        # current buy in + minimal raise + raise you want to do
        return r(self.game_state, ['current_buy_in'], 0) - self.get_our_player().get("bet", 0) + r(self.game_state,
                                                                                ['minimum_raise'],
                                                                                0) + amount

    def get_our_player(self):
        for player in self.game_state['players']:
            if player["name"] == self.team_name:
                return player

    @staticmethod
    def get_cards(player):
        return player['hole_cards']

    @staticmethod
    def is_pair_in_hand(hand):
        return hand[0]["rank"] == hand[1]["rank"]

    @staticmethod
    def should_we_fold(hand):
        return hand[0]["rank"] not in ["J", "K", "Q", "A"] and hand[1]["rank"] not in ["J", "K", "Q", "A"]

    def showdown(self):
        print('showdown {}'.format(self.game_state))

<|endoftext|>


<commit_before>#!/usr/bin/env python3

# Copyright 2013 Jussi Pakkanen

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys, os, pickle
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QMainWindow

class MesonGui():
    def __init__(self, build_dir):
        self.build_dir = os.path.join(os.getcwd(), build_dir)
        self.src_dir = os.path.normpath(os.path.join(self.build_dir, '..')) # HACK HACK HACK WRONG!
        uifile = 'mesonmain.ui'
        self.ui = uic.loadUi(uifile)
        self.ui.show()
        self.coredata_file = os.path.join(build_dir, 'meson-private/coredata.dat')
        if not os.path.exists(self.coredata_file):
            printf("Argument is not build directory.")
            sys.exit(1)
        self.coredata = pickle.load(open(self.coredata_file, 'rb'))
        self.fill_data()

    def fill_data(self):
        self.ui.project_label.setText('Hack project')
        self.ui.srcdir_label.setText(self.src_dir)
        self.ui.builddir_label.setText(self.build_dir)
        if self.coredata.cross_file is None:
            btype = 'Native build'
        else:
            btype = 'Cross build'
        self.ui.buildtype_label.setText(btype)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    if len(sys.argv) != 2:
        print(sys.argv[0], "<build dir>")
        sys.exit(1)
    gui = MesonGui(sys.argv[1])
    sys.exit(app.exec_())
<commit_msg>Can use custom tree model in a view.<commit_after>#!/usr/bin/env python3

# Copyright 2013 Jussi Pakkanen

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys, os, pickle
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import QAbstractItemModel, QModelIndex, QVariant
import PyQt5.QtCore

class PathModel(QAbstractItemModel):
    def __init__(self):
        super().__init__()
        self.paths = [('k1', 'v1'), ('k1', 'v2')]

    def flags(self, index):
        return PyQt5.QtCore.Qt.ItemIsSelectable | PyQt5.QtCore.Qt.ItemIsEnabled

    def rowCount(self, index):
        if index.isValid():
            return 0
        return len(self.paths)

    def columnCount(self, index):
        return 2

    def headerData(self, section, orientation, role):
        if section == '1':
            return QVariant('Path')
        return QVariant('Type')

    def data(self, index, role):
        if role != PyQt5.QtCore.Qt.DisplayRole:
            return QVariant()
        return QVariant(self.paths[index.row()][index.column()])

    def index(self, row, column, parent):
        return self.createIndex(row, column)

    def parent(self, index):
        return QModelIndex()

class MesonGui():
    def __init__(self, build_dir):
        self.build_dir = os.path.join(os.getcwd(), build_dir)
        self.src_dir = os.path.normpath(os.path.join(self.build_dir, '..')) # HACK HACK HACK WRONG!
        uifile = 'mesonmain.ui'
        self.ui = uic.loadUi(uifile)
        self.ui.show()
        self.coredata_file = os.path.join(build_dir, 'meson-private/coredata.dat')
        self.path_model = PathModel()
        if not os.path.exists(self.coredata_file):
            printf("Argument is not build directory.")
            sys.exit(1)
        self.coredata = pickle.load(open(self.coredata_file, 'rb'))
        self.fill_data()
        self.ui.path_view.setModel(self.path_model)

    def fill_data(self):
        self.ui.project_label.setText('Hack project')
        self.ui.srcdir_label.setText(self.src_dir)
        self.ui.builddir_label.setText(self.build_dir)
        if self.coredata.cross_file is None:
            btype = 'Native build'
        else:
            btype = 'Cross build'
        self.ui.buildtype_label.setText(btype)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    if len(sys.argv) != 2:
        print(sys.argv[0], "<build dir>")
        sys.exit(1)
    gui = MesonGui(sys.argv[1])
    sys.exit(app.exec_())
<|endoftext|>


<commit_before>#-------------------------------------------------------------------------------
# Name:        Robot Memory
# Purpose:     Stores memory about where robot has been
#
# Author:      Liam McInory
#
# Created:     06/03/2014
# Copyright:   (c) Liam 2014
# Licence:     GNU
#-------------------------------------------------------------------------------
from Myro import *
from math import *

class RobotMemory:
    Plot = [[]]
    Speed = 0.0
    MidpointX = 0
    MidpointY = 0
    Robot = 0
    X = 0
    Y = 0
    TowardsX = 0
    TowardsY = 0
    Scale = 0.0
    def __init__ (robot, length, height, speed = 0.5, scale = 0.5, lookX = 0, lookY = 1):
        Plot = [[0 for x in xrange(length)] for x in xrange(height)]
        Speed = speed
        Robot = robot
        Scale = scale
        X = MidpointX
        Y = MidpointY
        TowardsX = lookX
        TowardsY = lookY

    def Start(x, y):
        MidpointX = x
        MidpointY = y
        X = MidpointX
        Y = MidpointY

    def Turn(degrees, left):
        time90 = 3 * abs(Speed)
        time = Time90 / abs(degrees)
        if (left == 1):
            Robot.turnLeft(time, abs(Speed))
        else:
            Robot.turnRight(time, abs(Speed))
        TowardsX = TowardsX * cos(degrees) + TowardsY * sin(degrees)
        TowardsY = TowardsX * -sin(degrees) + TowardsY * sin(degrees)

    def GoForward(duration):
        slope = (TowardsY - Y) / (TowardsX - X)
        TowardsX += duration
        TowardsY += duration
        Robot.motors(Speed, Speed)
        wait(duration)
        divisible = duration / Scale
        for x in xrange(X, divisible):
            for y in xrange(Y, divisible):
                if (Plot[x][y] == 0):
                    Plot[x][y] = 1
        X += divisible
        Y += divisible

<commit_msg>Update RobotMemory.py<commit_after>#-------------------------------------------------------------------------------

# Name:        Robot Memory

# Purpose:     Stores memory about where robot has been

#

# Author:      Liam McInory

#

# Created:     06/03/2014

# Copyright:   (c) Liam 2014

# Licence:     MIT

#-------------------------------------------------------------------------------

import Myro

from math import *

class RobotMemory:

    Plot = [[]]

    Speed = 0.0

    MidpointX = 0

    MidpointY = 0

    X = 0

    Y = 0

    TowardsX = 0

    TowardsY = 0

    Scale = 0.0

    def __init__ (com = 3, length = 250, height = 250, speed = 0.5, scale = 0.5, lookX = 0, lookY = 1):

        Plot = [[0 for x in xrange(length)] for x in xrange(height)]

        Speed = speed

        Scale = scale

        TowardsX = lookX

        TowardsY = lookY

        #Myro.init("COM" + com)

    def Start(x, y):

        MidpointX = x

        MidpointY = y

        X = MidpointX

        Y = MidpointY

    def Turn(degrees, left):

        time90 = 3 * abs(Speed)

        time = Time90 / abs(degrees)

        if (left == 1):

            Myro.robot.turnLeft(time, abs(Speed))

        else:

            Myro.robot.turnRight(time, abs(Speed))

        TowardsX = TowardsX * cos(degrees) + TowardsY * sin(degrees)

        TowardsY = TowardsX * -sin(degrees) + TowardsY * sin(degrees)

    def GoForward(duration):

        slope = (TowardsY - Y) / (TowardsX - X)

        tempX = X

        tempY = Y

        TowardsX += duration

        TowardsY += duration

        Myro.robot.motors(Speed, Speed)

        wait(duration)

        divisible = duration / Scale

        Xs = []

        Ys = []

        for x in xrange(X, divisible):

            if (slope * x + X % Scale == 0):

                Xs.append(x)

                Ys.append(slope * x + X)

        for x in xrange(len(Xs)):

            for y in xrange(len(Ys)):

                if (Plot[Xs[x]][Ys[y]] == 0):

                    Plot[Xs[x]][Ys[y]] = 1

        X += divisible

        Y += divisible

sim = Myro.Simulation("test", 250, 250, Myro.Color("White"))
r = Myro.makeRobot("SimScribbler", sim)
r.setPose(125, 125, -90)
mem = RobotMemory()
mem.Start(125, 125)
mem.GoForward(1)
<|endoftext|>


<commit_before>#!/usr/bin/env python
from __future__ import print_function
import re
import fileinput

def is_file_line(line):
    return line.startswith('FILE')

file_map = {}

with open('filemap', 'r') as f:
    lines = f.readlines()
    for line in lines:
        split_line = line.split()
        file_map[split_line[0]] = split_line[1]

for line in fileinput.input(inplace=True, backup='.bak'):
    regexp = re.compile("(FILE \d+ )(.*)")
    if is_file_line(line):
        results = regexp.match(line)
        path = results.group(2)
        path = path.replace("c:\\cygwin64\\home\\buildslave\\source\\libo-core\\", "")
        if path in file_map:
            path = file_map[path]
        print("%s %s" % (results.group(1), path))
    else:
        print(line, end="")
<commit_msg>always load the filemap from the same dir as the script<commit_after>#!/usr/bin/env python
from __future__ import print_function
import os
import re
import fileinput

def is_file_line(line):
    return line.startswith('FILE')

file_map = {}

current_dir = os.path.dirname(os.path.abspath(__file__))

with open(os.path.join(current_dir, 'filemap'), 'r') as f:
    lines = f.readlines()
    for line in lines:
        split_line = line.split()
        file_map[split_line[0]] = split_line[1]

for line in fileinput.input(inplace=True, backup='.bak'):
    regexp = re.compile("(FILE \d+ )(.*)")
    if is_file_line(line):
        results = regexp.match(line)
        path = results.group(2)
        path = path.replace("c:\\cygwin64\\home\\buildslave\\source\\libo-core\\", "")
        if path in file_map:
            path = file_map[path]
        print("%s %s" % (results.group(1), path))
    else:
        print(line, end="")
<|endoftext|>


<commit_before>
# [Lecture] CS1F - HCI - Movements and sensors

# [Lecture] CS1F - HCI - Patterns of user interaction

# [Lecture] CS1P - Lab test related review

# [Lecture] CS1P - Functional programming, recursion
<commit_msg>[Lecture] CS1F - Debate on Software Engineering ethics<commit_after>
# [Lecture] CS1F - HCI - Movements and sensors

# [Lecture] CS1F - HCI - Patterns of user interaction

# [Lecture] CS1P - Lab test related review

# [Lecture] CS1P - Functional programming, recursion

# [Lecture] CS1F - Debate on Software Engineering ethics
<|endoftext|>


<commit_before># Coding:utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2016-2018 yutiansut/QUANTAXIS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
QUANTAXIS Log Module
@yutiansut

QA_util_log_x is under [QAStandard#0.0.2@602-x] Protocol
QA_util_log_info()
QA_util_log_debug()
QA_util_log_expection()
"""

import configparser
import datetime
import os
import sys
from zenlog import logging

from QUANTAXIS.QASetting.QALocalize import log_path, setting_path

CONFIGFILE_PATH = '{}{}{}'.format(setting_path, os.sep, 'config.ini')

def get_config():
    config = configparser.ConfigParser()
    if os.path.exists(CONFIGFILE_PATH):
        config.read(CONFIGFILE_PATH)
        try:
            return config.get('LOG', 'path')
        except configparser.NoSectionError:
            config.add_section('LOG')
            config.set('LOG', 'path', log_path)
            return log_path
        except configparser.NoOptionError:
            config.set('LOG', 'path', log_path)
            return log_path
        finally:

            with open(CONFIGFILE_PATH, 'w') as f:
                config.write(f)

    else:
        f = open(CONFIGFILE_PATH, 'w')
        config.add_section('LOG')
        config.set('LOG', 'path', log_path)
        config.write(f)
        f.close()
        return log_path

"""2019-01-03  升级到warning级别 不然大量别的代码的log会批量输出出来
"""
try:
    _name = '{}{}quantaxis_{}-{}-.log'.format(
        get_config(),
        os.sep,
        os.path.basename(sys.argv[0]).split('.py')[0],
        str(datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S'))
    )
except:
    _name = '{}{}quantaxis-{}-.log'.format(
        get_config(),
        os.sep,
        str(datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S'))
    )

logging.basicConfig(
    level=logging.WARNING,
    format='%(asctime)s QUANTAXIS>>> %(message)s',
    datefmt='%H:%M:%S',
    filename=_name,
    filemode='w',
)
console = logging.StreamHandler()
console.setLevel(logging.WARNING)
formatter = logging.Formatter('QUANTAXIS>> %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)

#logging.info('start QUANTAXIS')

def QA_util_log_debug(logs, ui_log=None, ui_progress=None):
    """
    QUANTAXIS Log Module
    @yutiansut

    QA_util_log_x is under [QAStandard#0.0.2@602-x] Protocol
    """
    logging.debug(logs)

def QA_util_log_info(
        logs,
        ui_log=None,
        ui_progress=None,
        ui_progress_int_value=None,
):
    """
    QUANTAXIS Log Module
    @yutiansut

    QA_util_log_x is under [QAStandard#0.0.2@602-x] Protocol
    """
    logging.warning(logs)

    # 给GUI使用，更新当前任务到日志和进度
    if ui_log is not None:
        if isinstance(logs, str):
            ui_log.emit(logs)
        if isinstance(logs, list):
            for iStr in logs:
                ui_log.emit(iStr)

    if ui_progress is not None and ui_progress_int_value is not None:
        ui_progress.emit(ui_progress_int_value)

def QA_util_log_expection(logs, ui_log=None, ui_progress=None):
    """
    QUANTAXIS Log Module
    @yutiansut

    QA_util_log_x is under [QAStandard#0.0.2@602-x] Protocol
    """
    logging.exception(logs)
<commit_msg>#update<commit_after># Coding:utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2016-2018 yutiansut/QUANTAXIS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
QUANTAXIS Log Module
@yutiansut

QA_util_log_x is under [QAStandard#0.0.2@602-x] Protocol
QA_util_log_info()
QA_util_log_debug()
QA_util_log_expection()
"""

import configparser
import datetime
import os
import sys
from zenlog import logging
from multiprocessing import Lock
from QUANTAXIS.QASetting.QALocalize import log_path, setting_path

CONFIGFILE_PATH = '{}{}{}'.format(setting_path, os.sep, 'config.ini')

def get_config():
    config = configparser.ConfigParser()
    L= Lock()
    L.acquire()
    if os.path.exists(CONFIGFILE_PATH):
        config.read(CONFIGFILE_PATH)
        try:
            return config.get('LOG', 'path')
        except configparser.NoSectionError:
            config.add_section('LOG')
            config.set('LOG', 'path', log_path)
            return log_path
        except configparser.NoOptionError:
            config.set('LOG', 'path', log_path)
            return log_path
        finally:

            with open(CONFIGFILE_PATH, 'w') as f:
                config.write(f)

    else:
        f = open(CONFIGFILE_PATH, 'w')
        config.add_section('LOG')
        config.set('LOG', 'path', log_path)
        config.write(f)
        f.close()
        return log_path
    L.release()

"""2019-01-03  升级到warning级别 不然大量别的代码的log会批量输出出来
"""
try:
    _name = '{}{}quantaxis_{}-{}-.log'.format(
        get_config(),
        os.sep,
        os.path.basename(sys.argv[0]).split('.py')[0],
        str(datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S'))
    )
except:
    _name = '{}{}quantaxis-{}-.log'.format(
        get_config(),
        os.sep,
        str(datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S'))
    )

logging.basicConfig(
    level=logging.WARNING,
    format='%(asctime)s QUANTAXIS>>> %(message)s',
    datefmt='%H:%M:%S',
    filename=_name,
    filemode='w',
)
console = logging.StreamHandler()
console.setLevel(logging.WARNING)
formatter = logging.Formatter('QUANTAXIS>> %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)

#logging.info('start QUANTAXIS')

def QA_util_log_debug(logs, ui_log=None, ui_progress=None):
    """
    QUANTAXIS Log Module
    @yutiansut

    QA_util_log_x is under [QAStandard#0.0.2@602-x] Protocol
    """
    logging.debug(logs)

def QA_util_log_info(
        logs,
        ui_log=None,
        ui_progress=None,
        ui_progress_int_value=None,
):
    """
    QUANTAXIS Log Module
    @yutiansut

    QA_util_log_x is under [QAStandard#0.0.2@602-x] Protocol
    """
    logging.warning(logs)

    # 给GUI使用，更新当前任务到日志和进度
    if ui_log is not None:
        if isinstance(logs, str):
            ui_log.emit(logs)
        if isinstance(logs, list):
            for iStr in logs:
                ui_log.emit(iStr)

    if ui_progress is not None and ui_progress_int_value is not None:
        ui_progress.emit(ui_progress_int_value)

def QA_util_log_expection(logs, ui_log=None, ui_progress=None):
    """
    QUANTAXIS Log Module
    @yutiansut

    QA_util_log_x is under [QAStandard#0.0.2@602-x] Protocol
    """
    logging.exception(logs)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
###
# Copyright (c) 2013, spline
# All rights reserved.
#
#
###

# my libs
import re
from collections import defaultdict
try:
    import xml.etree.cElementTree as ElementTree
except ImportError:
    import xml.etree.ElementTree as ElementTree
# supybot libs
import supybot.utils as utils
from supybot.commands import *
import supybot.plugins as plugins
import supybot.ircutils as ircutils
import supybot.callbacks as callbacks
from supybot.i18n import PluginInternationalization, internationalizeDocstring

_ = PluginInternationalization('Wikipedia')

@internationalizeDocstring
class Wikipedia(callbacks.Plugin):
    """Add the help for "@plugin help Wikipedia" here
    This should describe *how* to use this plugin."""
    threaded = True

    def _red(self, string):
        """return a red string."""
        return ircutils.mircColor(string, 'red')

    def _bu(self, string):
        """bold and underline string."""
        return ircutils.bold(ircutils.underline(string))

    def _unicodeurlencode(self, params):
        """
        A unicode aware version of urllib.urlencode.
        Borrowed from pyfacebook :: http://github.com/sciyoshi/pyfacebook/
        """
        if isinstance(params, dict):
            params = params.items()
        return utils.web.urlencode([(k, isinstance(v, unicode) and v.encode('utf-8') or v) for k, v in params])

    def _removeWikiNoise(self, wiki):
        """Remove wikipedia cruft in output to display better."""
        wiki = re.sub(r'(?i)\{\{IPA(\-[^\|\{\}]+)*?\|([^\|\{\}]+)(\|[^\{\}]+)*?\}\}', lambda m: m.group(2), wiki)
        wiki = re.sub(r'(?i)\{\{Lang(\-[^\|\{\}]+)*?\|([^\|\{\}]+)(\|[^\{\}]+)*?\}\}', lambda m: m.group(2), wiki)
        wiki = re.sub(r'Coordinates:.*?\n\n', '',wiki)
        wiki = re.sub(r'\{\{[^\{\}]+\}\}', '', wiki)
        wiki = re.sub(r'(?m)\{\{[^\{\}]+\}\}', '', wiki)
        wiki = re.sub(r'(?m)\{\|[^\{\}]*?\|\}', '', wiki)
        wiki = re.sub(r'\(.?\[Image\].*?\)', '', wiki)
        wiki = re.sub(r'\s\(.*?\[Listen\].*?\)', '', wiki)
        wiki = re.sub(r'(?i)\[\[Image:[^\[\]]*?\]\]', '', wiki)
        wiki = re.sub(r'(?i)\[\[File:[^\[\]]*?\]\]', '', wiki)
        wiki = re.sub(r'\[\[[^\[\]]*?\|([^\[\]]*?)\]\]', lambda m: m.group(1), wiki)
        wiki = re.sub(r'\[\[([^\[\]]+?)\]\]', lambda m: m.group(1), wiki)
        wiki = re.sub(r'\[\[([^\[\]]+?)\]\]', '', wiki)
        wiki = re.sub(r'(?i)File:[^\[\]]*?', '', wiki)
        wiki = re.sub(r'\[[^\[\]]*? ([^\[\]]*?)\]', lambda m: m.group(1), wiki)
        wiki = re.sub(r"''+", '', wiki)
        wiki = re.sub(r'(?m)^\*$', '', wiki)
        #Remove HTML from the text.
        wiki = re.sub(r'(?i) ', ' ', wiki)
        wiki = re.sub(r'(?i)<br[ \\]*?>', '\n', wiki)
        wiki = re.sub(r'(?m)<!--.*?--\s*>', '', wiki)
        wiki = re.sub(r'(?i)<ref[^>]*>[^>]*<\/ ?ref>', '', wiki)
        wiki = re.sub(r'(?m)<.*?>', '', wiki)
        wiki = re.sub(r'(?i)&', '&', wiki)
        #Remove -
        wiki = wiki.replace('–','-')
        #Remove trailing white spaces
        wiki = ' '.join(wiki.split())
        return wiki

    def _wikiquery(self, opttopic):
        """Perform Wikipedia Query."""

        # prep url.
        url = self.registryValue('wikiUrl')
        urlArgs = {'action': 'query', 'prop': 'extracts',
                   'titles': opttopic, 'format': 'xml',
                   'redirects': '1', 'indexpageids': '1',
                   'exintro': '1', 'explaintext': '1',
                   'meta': 'siteinfo'}
        request_url = url + '?' + self._unicodeurlencode(urlArgs)
        headers={'User-agent': 'Mozilla/5.0 (Windows NT 6.1; rv:15.0) Gecko/20120716 Firefox/15.0a2'}

        # try and fetch url.
        try:
            result = utils.web.getUrl(request_url, headers=headers)
        except utils.web.Error as error:
            self.log.info("I could not open {0} error: {1}".format(request_url, error))
            return ('error', error)

        # parse XML.
        try:
            root = ElementTree.fromstring(result)
        except ElementTree.ParseError as error:
            return ('error', "Error parsing {0}: {1}".format(request_url, error))

        # first parse XML for errors.
        if root.find('query/error'):
            self.log.info("ERROR on wikiquery for {0}: {1}".format(opttopic, root.find('query/error/info')))
            return ('error', "{0} :: {1}".format(root.find('query/error/code'), root.find('query/error/info')))

        # grab XML content from MediaWiki API.
        html = root.find('query/pages/page/extract').text
        html = unicode(html).encode('utf-8')
        title = root.find('query/pages/page').attrib['title']
        title = unicode(title).encode('utf-8')
        articleserver = root.find('query/general').attrib['server']
        articlepath = root.find('query/general').attrib['articlepath']
        wikilink = "http:{0}{1}".format(articleserver, articlepath.replace('$1', title.replace(' ', '_')))  # concat wikilink.
        html = self._removeWikiNoise(html)  # clean html.
        outputcontent = {'text': title, 'description': html, 'link': wikilink}
        return ('0', outputcontent)

    def _opensearch(self, opttopic, optnum):
        """Query Mediawiki OpenSearch for topics."""

        # prep url.
        url = self.registryValue('wikiUrl')
        urlArgs = {'action': 'opensearch', 'limit': optnum,
                  'format': 'xml', 'namespace': '0',
                  'search': opttopic}
        request_url = url + '?' + self._unicodeurlencode(urlArgs)
        headers={'User-agent': 'Mozilla/5.0 (Windows NT 6.1; rv:15.0) Gecko/20120716 Firefox/15.0a2'}

        # try and fetch url.
        try:
            result = utils.web.getUrl(request_url, headers=headers)
        except utils.web.Error as error:
            self.log.info("I could not open {0} error: {1}".format(request_url, error))
            return ('error', error)

        # parse XML.
        try:
            root = ElementTree.fromstring(result)
        except ElementTree.ParseError as error:
            return ('error', "Error parsing {0}: {1}".format(request_url, error))

        # find the first item.
        ns = '{http://opensearch.org/searchsuggest2}'
        section = root.find('%sSection' % ns)
        items = section.findall('%sItem' % ns)
        if len(items) < 1:
            return ('error', "No results found for {0}".format(opttopic))
        else:
            items = [{
                'text': unicode(item.find('%sText' % ns).text).encode('utf-8'),
                'description': unicode(item.find('%sDescription' % ns).text).encode('utf-8'),
                'link': unicode(item.find('%sUrl' % ns).text).encode('utf-8')
            } for item in items]

            return ('0', items)

    def wikipedia(self, irc, msg, args, optlist, optinput):
        """[--link] <term>
        Searches Wikipedia for <term>.
        Use --link to display wikipedia link after entry.
        """

        # first, check if we have a url.
        if not self.registryValue('wikiUrl') or self.registryValue('wikiUrl') == "Not set":
            irc.reply("wikipedia URL not set. see 'config help supybot.plugins.Wikipedia.wikiUrl'")
            return

        # handle getopts.
        args = {'link': self.registryValue('showLink')}
        for (key, value) in optlist:
            if key == 'link':
                args['link'] = True

        # do the search.
        results = self._opensearch(optinput, 1)
        if results[0] == 'error':
            irc.reply("ERROR :: {0}".format(results[1]))
            return

        # main logic.
        results = self._wikiquery(results[1][0]['text'])
        if results[0] == 'error':
            irc.reply("ERROR :: {0}".format(results[1]))
            return
        else:
            results = results[1]

        if self.registryValue('disableANSI'):
            irc.reply("{0} :: {1}".format(results['text'], results['description']))
        else:
            irc.reply("{0} :: {1}".format(self._red(results['text']), results['description']))

        if args['link']:
            irc.reply("{0}".format(results['link']))

    wikipedia = wrap(wikipedia, [getopts({'detailed':'', 'link':''}), ('text')])

    def wikisearch(self, irc, msg, args, optlist, optinput):
        """[--num #|--snippets|--link] <term>
        Perform a Wikipedia search for <term>
        Use --num (between 10 and 30) to specify results.
        Use --snippets to display text snippets. (NOTICE: is rather verbose..)
        Use --link to display a link to each article.
        """

        # make sure we have a url.
        url = self.registryValue('wikiUrl')
        if not url or url == "Not set":
            irc.reply("wikipedia URL not set. see 'config help supybot.plugins.Wikipedia.wikiUrl'")
            return

        # arguments for output.
        args = {'num': self.registryValue('numberOfSearchResults'), 'snippets': False, 'link': False}

        # manip args via getopts (optlist)
        if optlist:
            for (key, value) in optlist:
                if key == "num":
                    if 10 <= value <= 30:
                        args['num'] = value
                    else:
                        irc.reply("ERROR: wikisearch --num must be between 10 and 30.")
                        return
                if key == "snippets":
                    args['snippets'] = True
                if key == "link":
                    args['link'] = True

        # do the search.
        results = self._opensearch(optinput, args['num'])
        if results[0] == 'error':
           irc.reply("ERROR :: {0}".format(results[1]))
           return

        # now format the results into a list for output.
        wikiresults = results[1]
        output = []
        for wikiresult in wikiresults:
            tmpstring = wikiresult['text'].encode('utf-8')
            if args['snippets']:
                tmpstring += " - {0}".format(utils.str.normalizeWhitespace(wikiresult['description'].strip()))
            if args['link']:
                tmpstring += " < {0} >".format(wikiresult['link'])
            output.append(tmpstring)

        irc.reply("Search results for {0} :: {1}".format(optinput, " | ".join(output)))

    wikisearch = wrap(wikisearch, [getopts({'num': ('int'), 'link': '', 'snippets': ''}), ('text')])

Class = Wikipedia

# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=250:
<commit_msg>Temp fixes for wikipedia.<commit_after># -*- coding: utf-8 -*-
###
# Copyright (c) 2013, spline
# All rights reserved.
#
#
###

# my libs
import re
from collections import defaultdict
try:
    import xml.etree.cElementTree as ElementTree
except ImportError:
    import xml.etree.ElementTree as ElementTree
# supybot libs
import supybot.utils as utils
from supybot.commands import *
import supybot.plugins as plugins
import supybot.ircutils as ircutils
import supybot.callbacks as callbacks
from supybot.i18n import PluginInternationalization, internationalizeDocstring

_ = PluginInternationalization('Wikipedia')

@internationalizeDocstring
class Wikipedia(callbacks.Plugin):
    """Add the help for "@plugin help Wikipedia" here
    This should describe *how* to use this plugin."""
    threaded = True

    def _red(self, string):
        """return a red string."""
        return ircutils.mircColor(string, 'red')

    def _bu(self, string):
        """bold and underline string."""
        return ircutils.bold(ircutils.underline(string))

    def _unicodeurlencode(self, params):
        """
        A unicode aware version of urllib.urlencode.
        Borrowed from pyfacebook :: http://github.com/sciyoshi/pyfacebook/
        """
        if isinstance(params, dict):
            params = params.items()
        return utils.web.urlencode([(k, isinstance(v, unicode) and v.encode('utf-8') or v) for k, v in params])

    def _removeWikiNoise(self, wiki):
        """Remove wikipedia cruft in output to display better."""
        wiki = re.sub(r'(?i)\{\{IPA(\-[^\|\{\}]+)*?\|([^\|\{\}]+)(\|[^\{\}]+)*?\}\}', lambda m: m.group(2), wiki)
        wiki = re.sub(r'(?i)\{\{Lang(\-[^\|\{\}]+)*?\|([^\|\{\}]+)(\|[^\{\}]+)*?\}\}', lambda m: m.group(2), wiki)
        wiki = re.sub(r'Coordinates:.*?\n\n', '',wiki)
        wiki = re.sub(r'\{\{[^\{\}]+\}\}', '', wiki)
        wiki = re.sub(r'(?m)\{\{[^\{\}]+\}\}', '', wiki)
        wiki = re.sub(r'(?m)\{\|[^\{\}]*?\|\}', '', wiki)
        wiki = re.sub(r'\(.?\[Image\].*?\)', '', wiki)
        wiki = re.sub(r'\s\(.*?\[Listen\].*?\)', '', wiki)
        wiki = re.sub(r'(?i)\[\[Image:[^\[\]]*?\]\]', '', wiki)
        wiki = re.sub(r'(?i)\[\[File:[^\[\]]*?\]\]', '', wiki)
        wiki = re.sub(r'\[\[[^\[\]]*?\|([^\[\]]*?)\]\]', lambda m: m.group(1), wiki)
        wiki = re.sub(r'\[\[([^\[\]]+?)\]\]', lambda m: m.group(1), wiki)
        wiki = re.sub(r'\[\[([^\[\]]+?)\]\]', '', wiki)
        wiki = re.sub(r'(?i)File:[^\[\]]*?', '', wiki)
        wiki = re.sub(r'\[[^\[\]]*? ([^\[\]]*?)\]', lambda m: m.group(1), wiki)
        wiki = re.sub(r"''+", '', wiki)
        wiki = re.sub(r'(?m)^\*$', '', wiki)
        #Remove HTML from the text.
        wiki = re.sub(r'(?i) ', ' ', wiki)
        wiki = re.sub(r'(?i)<br[ \\]*?>', '\n', wiki)
        wiki = re.sub(r'(?m)<!--.*?--\s*>', '', wiki)
        wiki = re.sub(r'(?i)<ref[^>]*>[^>]*<\/ ?ref>', '', wiki)
        wiki = re.sub(r'(?m)<.*?>', '', wiki)
        wiki = re.sub(r'(?i)&', '&', wiki)
        #Remove -
        wiki = wiki.replace('–','-')
        #Remove trailing white spaces
        wiki = ' '.join(wiki.split())
        return wiki

    def _wikiquery(self, opttopic):
        """Perform Wikipedia Query."""

        # prep url.
        url = self.registryValue('wikiUrl')
        urlArgs = {'action': 'query', 'prop': 'extracts',
                   'titles': opttopic, 'format': 'xml',
                   'redirects': '1', 'indexpageids': '1',
                   'exintro': '1', 'explaintext': '1',
                   'meta': 'siteinfo'}
        request_url = url + '?' + self._unicodeurlencode(urlArgs)
        headers={'User-agent': 'Mozilla/5.0 (Windows NT 6.1; rv:15.0) Gecko/20120716 Firefox/15.0a2'}

        # try and fetch url.
        try:
            result = utils.web.getUrl(request_url, headers=headers)
        except utils.web.Error as error:
            self.log.info("I could not open {0} error: {1}".format(request_url, error))
            return ('error', error)

        # parse XML.
        try:
            root = ElementTree.fromstring(result)
        except ElementTree.ParseError as error:
            return ('error', "Error parsing {0}: {1}".format(request_url, error))

        # first parse XML for errors.
        if root.find('query/error'):
            self.log.info("ERROR on wikiquery for {0}: {1}".format(opttopic, root.find('query/error/info')))
            return ('error', "{0} :: {1}".format(root.find('query/error/code'), root.find('query/error/info')))

        # grab XML content from MediaWiki API.
        html = root.find('query/pages/page/extract').text
        html = unicode(html).encode('utf-8')
        title = root.find('query/pages/page').attrib['title']
        title = unicode(title).encode('utf-8')
        articleserver = root.find('query/general').attrib['server']
        articlepath = root.find('query/general').attrib['articlepath']
        wikilink = "http:{0}{1}".format(articleserver, articlepath.replace('$1', title.replace(' ', '_')))  # concat wikilink.
        html = self._removeWikiNoise(html)  # clean html.
        outputcontent = {'text': title, 'description': html, 'link': wikilink}
        return ('0', outputcontent)

    def _opensearch(self, opttopic, optnum):
        """Query Mediawiki OpenSearch for topics."""

        # prep url.
        url = self.registryValue('wikiUrl')
        urlArgs = {'action': 'opensearch', 'limit': optnum,
                  'format': 'xml', 'namespace': '0',
                  'search': opttopic}
        request_url = url + '?' + self._unicodeurlencode(urlArgs)
        headers={'User-agent': 'Mozilla/5.0 (Windows NT 6.1; rv:15.0) Gecko/20120716 Firefox/15.0a2'}
        self.log.info("{0}".format(request_url))

        # try and fetch url.
        try:
            result = utils.web.getUrl(request_url, headers=headers)
        except utils.web.Error as error:
            self.log.info("I could not open {0} error: {1}".format(request_url, error))
            return ('error', error)

        # parse XML.
        try:
            root = ElementTree.fromstring(result)
        except ElementTree.ParseError as error:
            return ('error', "Error parsing {0}: {1}".format(request_url, error))

        # find the first item.
        ns = '{http://opensearch.org/searchsuggest2}'
        section = root.find('%sSection' % ns)
        items = section.findall('%sItem' % ns)
        if len(items) < 1:
            return ('error', "No results found for {0}".format(opttopic))
        else:
            items = [{
                'text': unicode(item.find('%sText' % ns).text).encode('utf-8'),
                #'description': unicode(item.find('%sTe' % ns).text).encode('utf-8'),
                'link': unicode(item.find('%sUrl' % ns).text).encode('utf-8')
            } for item in items]

            return ('0', items)

    def wikipedia(self, irc, msg, args, optlist, optinput):
        """[--link] <term>
        Searches Wikipedia for <term>.
        Use --link to display wikipedia link after entry.
        """

        # first, check if we have a url.
        if not self.registryValue('wikiUrl') or self.registryValue('wikiUrl') == "Not set":
            irc.reply("wikipedia URL not set. see 'config help supybot.plugins.Wikipedia.wikiUrl'")
            return

        # handle getopts.
        args = {'link': self.registryValue('showLink')}
        for (key, value) in optlist:
            if key == 'link':
                args['link'] = True

        # do the search.
        results = self._opensearch(optinput, 1)
        if results[0] == 'error':
            irc.reply("ERROR :: {0}".format(results[1]))
            return

        # main logic.
        results = self._wikiquery(results[1][0]['text'])
        if results[0] == 'error':
            irc.reply("ERROR :: {0}".format(results[1]))
            return
        else:
            results = results[1]

        if self.registryValue('disableANSI'):
            irc.reply("{0} :: {1}".format(results['text'], results['description']))
        else:
            irc.reply("{0} :: {1}".format(self._red(results['text']), results['description']))

        if args['link']:
            irc.reply("{0}".format(results['link']))

    wikipedia = wrap(wikipedia, [getopts({'detailed':'', 'link':''}), ('text')])

    def wikisearch(self, irc, msg, args, optlist, optinput):
        """[--num #|--snippets|--link] <term>
        Perform a Wikipedia search for <term>
        Use --num (between 10 and 30) to specify results.
        Use --snippets to display text snippets. BROKEN
        Use --link to display a link to each article.
        """

        # make sure we have a url.
        url = self.registryValue('wikiUrl')
        if not url or url == "Not set":
            irc.reply("wikipedia URL not set. see 'config help supybot.plugins.Wikipedia.wikiUrl'")
            return

        # arguments for output.
        args = {'num': self.registryValue('numberOfSearchResults'), 'snippets': False, 'link': False}

        # manip args via getopts (optlist)
        if optlist:
            for (key, value) in optlist:
                if key == "num":
                    if 10 <= value <= 30:
                        args['num'] = value
                    else:
                        irc.reply("ERROR: wikisearch --num must be between 10 and 30.")
                        return
                if key == "snippets":
                    args['snippets'] = True
                if key == "link":
                    args['link'] = True

        # do the search.
        results = self._opensearch(optinput, args['num'])
        if results[0] == 'error':
           irc.reply("ERROR :: {0}".format(results[1]))
           return

        # now format the results into a list for output.
        wikiresults = results[1]
        output = []
        for wikiresult in wikiresults:
            tmpstring = wikiresult['text'].encode('utf-8')
            #if args['snippets']:
            #    tmpstring += " - {0}".format(utils.str.normalizeWhitespace(wikiresult['description'].strip()))
            if args['link']:
                tmpstring += " < {0} >".format(wikiresult['link'])
            output.append(tmpstring)

        irc.reply("Search results for {0} :: {1}".format(optinput, " | ".join(output)))

    wikisearch = wrap(wikisearch, [getopts({'num': ('int'), 'link': '', 'snippets': ''}), ('text')])

Class = Wikipedia

# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=250:
<|endoftext|>