blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 616 | content_id stringlengths 40 40 | detected_licenses listlengths 0 112 | license_type stringclasses 2 values | repo_name stringlengths 5 115 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 777 values | visit_date timestamp[us]date 2015-08-06 10:31:46 2023-09-06 10:44:38 | revision_date timestamp[us]date 1970-01-01 02:38:32 2037-05-03 13:00:00 | committer_date timestamp[us]date 1970-01-01 02:38:32 2023-09-06 01:08:06 | github_id int64 4.92k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us]date 2012-06-04 01:52:49 2023-09-14 21:59:50 ⌀ | gha_created_at timestamp[us]date 2008-05-22 07:58:19 2023-08-21 12:35:19 ⌀ | gha_language stringclasses 149 values | src_encoding stringclasses 26 values | language stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 3 10.2M | extension stringclasses 188 values | content stringlengths 3 10.2M | authors listlengths 1 1 | author_id stringlengths 1 132 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f1c575c097cde921b3ca5577df204d7ee4135b08 | 1d9e681b204e6ec2d7a710ef45b7dec082239491 | /venv/Lib/site-packages/test/test_leagues_api.py | 48ffc4664efcaf97941442d25c9aa298f62759cf | [] | no_license | 1chimaruGin/DotaAnalysis | 0e0b85805cc83e4cc491d46f7eadc014e8d6b1f1 | 6a74cde2ee400fc0dc96305203d60c5e56d7ecff | refs/heads/master | 2020-07-21T20:48:07.589295 | 2019-09-07T12:20:15 | 2019-09-07T12:20:15 | 206,972,180 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,134 | py | # coding: utf-8
"""
OpenDota API
# Introduction The OpenDota API provides Dota 2 related data including advanced match data extracted from match replays. Please keep request rate to approximately 1/s. **Begining 4/22/2018, the OpenDota API will be limited to 50,000 free calls per month.** We'll be offering a Premium Tier with unlimited API calls and higher rate limits. Check out the [API page](https://www.opendota.com/api-keys) to learn more.
OpenAPI spec version: 17.6.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
import od_python
from od_python.rest import ApiException
from od_python.apis.leagues_api import LeaguesApi
class TestLeaguesApi(unittest.TestCase):
""" LeaguesApi unit test stubs """
def setUp(self):
self.api = od_python.apis.leagues_api.LeaguesApi()
def tearDown(self):
pass
def test_leagues_get(self):
"""
Test case for leagues_get
GET /leagues
"""
pass
if __name__ == '__main__':
unittest.main()
| [
"kyitharhein18@gmail.com"
] | kyitharhein18@gmail.com |
67617a69add99f64b4ea88a84a7f0b9fc120f187 | ec645951ce4a1f7d404ebca438dfff8fb74cc3f4 | /venv/bin/iptest3 | 211d53b05edeca834eefa92ab64e8d24a7d436dc | [] | no_license | Josue23/scrapy | 695c0e93e6c1f0c0de5a04bd2eaced3e5520801e | 469cc4cff7d986264c4bcc291e9eb5f5a6256da9 | refs/heads/master | 2021-01-09T06:19:59.794012 | 2017-03-04T00:21:52 | 2017-03-04T00:21:52 | 80,957,631 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 271 | #!/home/josh/Documentos/labs/scrapy/venv/bin/python3.5
# -*- coding: utf-8 -*-
import re
import sys
from IPython.testing.iptestcontroller import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())
| [
"josuerodrigues@gmail.com"
] | josuerodrigues@gmail.com | |
ab36dc2d10fb2e290cb55a1c9d512d4acefab8f7 | e7795082c0131682803a09e929a86b2deddeab74 | /common/decorators.py | a2daa4aba896ef449a232fc88e7972e82d3bc2f0 | [
"MIT"
] | permissive | liwanlei/FXTest | 01de3ad55849b16c49d93b58d1aae21fd0fdafa0 | aeda58d01c14194290ca149d411c3a8596cca82d | refs/heads/master | 2023-04-01T15:45:26.668688 | 2023-03-19T05:19:54 | 2023-03-19T05:19:54 | 97,098,845 | 807 | 419 | MIT | 2022-04-23T06:52:16 | 2017-07-13T08:27:48 | Python | UTF-8 | Python | false | false | 342 | py | # -*- coding: utf-8 -*-
# @Date : 2017-08-14 20:58:13
# @Author : lileilei
'''
判断是否是管理员
'''
from flask_login import current_user
def chckuserpermisson():
for rosse in current_user.quanxians:
if int(rosse.rose) == 2 or current_user.is_sper == 1:
return True
else:
return False
| [
"leileili126@163.com"
] | leileili126@163.com |
f89f4f691db9fbfe4b2cf6779786db342fce3ea2 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02921/s097564200.py | ad53f6228a9838cfa0ce0fec43cc2767e79c3fbb | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 123 | py | S=input()
T=input()
count=0
for i in range(3):
if S[i]==T[i]:
count=count+1
else:
pass
print(count) | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
7a4ea1e22297182f60b7f8fb6604fa106b46ffca | 9c5abcd43318ef7553be95a95a859a0f3e41a467 | /easygraphics/_utils/invoke_in_app_thread.py | 14b67c2f87247464ac457fbf9367817f2f21572d | [
"BSD-3-Clause"
] | permissive | xzy103/PyEasyGraphics | d66da503f601868fe39d404a77b3b8d0a43a2e52 | 16bd6f21dd6f3d76edaab2b533500e9aa789c6b2 | refs/heads/master | 2020-05-19T07:31:22.005958 | 2019-02-25T09:54:41 | 2019-02-25T09:54:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,138 | py | #####################################################################
# #
# invoke_in_main.py #
# #
# Copyright 2013, Christopher Billington, Philip Starkey #
# #
# This file is part of the qtutils project #
# (see https://bitbucket.org/philipstarkey/qtutils ) #
# and is licensed under the 2-clause, or 3-clause, BSD License. #
# See the license.txt file in the root of the project #
# for the full license. #
#
# #
#####################################################################
import functools
# tailored and modified by roy
import sys
import threading
import time
from queue import Queue
from PyQt5 import QtWidgets
from PyQt5.QtCore import QEvent, QObject, QCoreApplication
def _reraise(exc_info):
exc_type, value, traceback = exc_info
raise value.with_traceback(traceback)
class CallEvent(QEvent):
"""An event containing a request for a function call."""
EVENT_TYPE = QEvent(QEvent.registerEventType())
def __init__(self, queue, exceptions_in_main, fn, *args, **kwargs):
QEvent.__init__(self, self.EVENT_TYPE)
self.fn = fn
self.args = args
self.kwargs = kwargs
self._returnval = queue
# Whether to raise exceptions in the main thread or store them
# for raising in the calling thread:
self._exceptions_in_main = exceptions_in_main
class Caller(QObject):
"""An event handler which calls the function held within a CallEvent."""
def event(self, event):
event.accept()
exception = None
try:
result = event.fn(*event.args, **event.kwargs)
except Exception:
# Store for re-raising the exception in the calling thread:
exception = sys.exc_info()
result = None
if not event._exceptions_in_main:
raise
finally:
event._returnval.put([result, exception])
return True
_caller = None
def init_invoke_in_app():
global _caller
_caller = Caller()
_wait_for_quit = False
def destroy_invoke_in_app():
global _caller, _wait_for_quit
_caller = None
_wait_for_quit = False
def _start_app_thread():
app = QtWidgets.QApplication([])
font = app.font()
font.setPixelSize(_font_size)
app.setFont(font)
app.setQuitOnLastWindowClosed(False)
init_invoke_in_app()
# init finished, can draw now
return app
_wait_for_quit = False
def wait_for_quit():
global _wait_for_quit
_wait_for_quit = True
_app_lock = threading.Lock()
def invoke_in_app_thread(fn, *args, **kwargs):
"""Queue up the executing of a function in the main thread and return immediately.
This function queues up a custom :code:`QEvent` to the Qt event loop.
This event executes the specified function :code:`fn` in the Python
MainThread with the specified arguments and keyword arguments, and returns
a Python Queue which will eventually hold the result from the executing of
:code:`fn`. To access the result, use :func:`qtutils.invoke_in_main.get_inmain_result`.
This function can be used from the MainThread, but such use will just directly call the function, bypassing the Qt event loop.
Arguments:
fn: A reference to the function or method to run in the MainThread.
*args: Any arguments to pass to :code:`fn` when it is called from the
MainThread.
**kwargs: Any keyword arguments to pass to :code:`fn` when it is called
from the MainThread
Returns:
A Python Queue which will eventually hold the result
:code:`(fn(*args, **kwargs), exception)` where
:code:`exception=[type,value,traceback]`.
"""
_app_lock.acquire()
try:
if _caller is None:
app = _start_app_thread()
ex = None
try:
result = fn(*args, **kwargs)
except Exception as e:
ex = e
destroy_invoke_in_app()
app.quit()
app = None
if ex is not None:
raise ex
return result
elif _wait_for_quit: # the app is quitting. don't show the dialog
return None
result = get_in_app_thread_result(_in_app_thread_later(fn, True, *args, **kwargs))
return result
finally:
_app_lock.release()
def _in_app_thread_later(fn, exceptions_in_main, *args, **kwargs):
"""Asks the mainloop to call a function when it has time. Immediately
returns the queue that was sent to the mainloop. A call to queue.get()
will return a list of [result,exception] where exception=[type,value,traceback]
of the exception. Functions are guaranteed to be called in the order
they were requested."""
queue = Queue()
QCoreApplication.postEvent(_caller, CallEvent(queue, exceptions_in_main, fn, *args, **kwargs))
return queue
def get_in_app_thread_result(queue):
""" Processes the result of :func:`qtutils.invoke_in_main.inmain_later`.
This function takes the queue returned by :code:`inmain_later` and blocks
until a result is obtained. If an exception occurred when executing the
function in the MainThread, it is raised again here (it is also raised in the
MainThread). If no exception was raised, the result from the execution of the
function is returned.
Arguments:
queue: The Python Queue object returned by :code:`inmain_later`
Returns:
The result from executing the function specified in the call to
:code:`inmain_later`
"""
result, exception = queue.get()
if exception is not None:
_reraise(exception)
return result
_font_size = 18
def set_app_font(size: int):
global _font_size
_font_size = size
def invoke_in_thread():
""" A decorator which enforces the execution of the decorated thread to occur in the MainThread.
Returns:
The decorator returns a function that has wrapped the decorated function
in the appropriate call to :code:`inmain` or :code:`inmain_later` (if
you are unfamiliar with how decorators work, please see the Python
documentation).
When calling the decorated function, the result is either the result of
the function executed in the MainThread (if :code:`wait_for_return=True`)
or a Python Queue to be used with
:func:`qtutils.invoke_in_main.get_inmain_result` at a later time.
"""
def wrap(fn):
"""A decorator which sets any function to always run in the main thread."""
@functools.wraps(fn)
def f(*args, **kwargs):
return invoke_in_app_thread(fn, *args, **kwargs)
return f
return wrap
| [
"royqh1979@gmail.com"
] | royqh1979@gmail.com |
5b39c59717642e3776c9379ae915f92588e8e8ca | 2f98aa7e5bfc2fc5ef25e4d5cfa1d7802e3a7fae | /python/python_775.py | f4cd2428ed5c0bb83dce326182cd87d37d738fb8 | [] | no_license | AK-1121/code_extraction | cc812b6832b112e3ffcc2bb7eb4237fd85c88c01 | 5297a4a3aab3bb37efa24a89636935da04a1f8b6 | refs/heads/master | 2020-05-23T08:04:11.789141 | 2015-10-22T19:19:40 | 2015-10-22T19:19:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 70 | py | # Basic Python dictionary question
d = {'key' : ('value1', 'value2')}
| [
"ubuntu@ip-172-31-7-228.us-west-2.compute.internal"
] | ubuntu@ip-172-31-7-228.us-west-2.compute.internal |
9b62265c950d228138e345f64bc1748cedad187d | eb48c29693a3be2df788215f36dcc0ecc08dd961 | /contrib/gitian-build.py | a0c26e8dcbde687cc992571987143ab5783218d8 | [
"MIT"
] | permissive | CREDIT-2-0/TerraCredit | 787b14d7a5366d22827efd03853ac3f1f69fd234 | ebe035cd4eeab006928e931c33db7b025cdea340 | refs/heads/master | 2022-12-08T23:24:52.343819 | 2020-09-08T02:47:20 | 2020-09-08T02:47:20 | 271,811,497 | 4 | 5 | null | null | null | null | UTF-8 | Python | false | false | 21,287 | py | #!/usr/bin/env python3
# Copyright (c) 2018-2019 The Bitcoin Core developers
# Copyright (c) 2019 The PIVX developers
# Copyright (c) 2019-2020 The TERRACREDIT developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import argparse
import os
import subprocess
import sys
def setup_linux():
global args, workdir
if os.path.isfile('/usr/bin/apt-get'):
programs = ['ruby', 'git', 'make', 'wget', 'curl']
if args.kvm:
programs += ['apt-cacher-ng', 'python-vm-builder', 'qemu-kvm', 'qemu-utils']
elif args.docker:
if not os.path.isfile('/lib/systemd/system/docker.service'):
dockers = ['docker.io', 'docker-ce']
for i in dockers:
return_code = subprocess.call(['sudo', 'apt-get', 'install', '-qq', i])
if return_code == 0:
subprocess.check_call(['sudo', 'usermod', '-aG', 'docker', os.environ['USER']])
print('Docker installed, restart your computer and re-run this script to continue the setup process.')
sys.exit(0)
if return_code != 0:
print('Cannot find any way to install Docker.', file=sys.stderr)
sys.exit(1)
else:
programs += ['apt-cacher-ng', 'lxc', 'debootstrap']
subprocess.check_call(['sudo', 'apt-get', 'install', '-qq'] + programs)
setup_repos()
elif args.is_fedora:
pkgmgr = 'dnf'
repourl = 'https://download.docker.com/linux/fedora/docker-ce.repo'
elif args.is_centos:
pkgmgr = 'yum'
repourl = 'https://download.docker.com/linux/centos/docker-ce.repo'
if args.is_fedora or args.is_centos:
programs = ['ruby', 'make', 'wget', 'curl']
if args.kvm:
print('KVM not supported with Fedora/CentOS yet.')
sys.exit(1)
elif args.docker:
if not os.path.isfile('/lib/systemd/system/docker.service'):
user = os.environ['USER']
dockers = ['docker-ce', 'docker-ce-cli', 'containerd.io']
if args.is_fedora:
subprocess.check_call(['sudo', pkgmgr, 'install', '-y', 'dnf-plugins-core'])
subprocess.check_call(['sudo', pkgmgr, 'config-manager', '--add-repo', repourl])
elif args.is_centos:
reqs = ['yum-utils', 'device-mapper-persistent-data', 'lvm2']
subprocess.check_call(['sudo', pkgmgr, 'install', '-y'] + reqs)
subprocess.check_call(['sudo', 'yum-config-manager', '--add-repo', repourl])
subprocess.check_call(['sudo', pkgmgr, 'install', '-y'] + dockers)
subprocess.check_call(['sudo', 'usermod', '-aG', 'docker', user])
subprocess.check_call(['sudo', 'systemctl', 'enable', 'docker'])
print('Docker installed, restart your computer and re-run this script to continue the setup process.')
sys.exit(0)
subprocess.check_call(['sudo', 'systemctl', 'start', 'docker'])
else:
print('LXC not supported with Fedora/CentOS yet.')
sys.exit(1)
if args.is_fedora:
programs += ['git']
if args.is_centos:
# CentOS ships with an insanely outdated version of git that is no longer compatible with gitian builds
# Check current version and update if necessary
oldgit = b'2.' not in subprocess.check_output(['git', '--version'])
if oldgit:
subprocess.check_call(['sudo', pkgmgr, 'remove', '-y', 'git*'])
subprocess.check_call(['sudo', pkgmgr, 'install', '-y', 'https://centos7.iuscommunity.org/ius-release.rpm'])
programs += ['git2u-all']
subprocess.check_call(['sudo', pkgmgr, 'install', '-y'] + programs)
setup_repos()
else:
print('Unsupported system/OS type.')
sys.exit(1)
def setup_darwin():
global args, workdir
programs = []
if not os.path.isfile('/usr/local/bin/wget'):
programs += ['wget']
if not os.path.isfile('/usr/local/bin/git'):
programs += ['git']
if not os.path.isfile('/usr/local/bin/gsha256sum'):
programs += ['coreutils']
if args.docker:
print('Experimental setup for macOS host')
if len(programs) > 0:
subprocess.check_call(['brew', 'install'] + programs)
os.environ['PATH'] = '/usr/local/opt/coreutils/libexec/gnubin' + os.pathsep + os.environ['PATH']
elif args.kvm or not args.docker:
print('KVM and LXC are not supported under macOS at this time.')
sys.exit(0)
setup_repos()
def setup_repos():
if not os.path.isdir('gitian.sigs'):
subprocess.check_call(['git', 'clone', 'https://github.com/terracredit-Project/gitian.sigs.git'])
if not os.path.isdir('terracredit-detached-sigs'):
subprocess.check_call(['git', 'clone', 'https://github.com/terracredit-Project/terracredit-detached-sigs.git'])
if not os.path.isdir('gitian-builder'):
subprocess.check_call(['git', 'clone', 'https://github.com/devrandom/gitian-builder.git'])
if not os.path.isdir('terracredit'):
subprocess.check_call(['git', 'clone', 'https://github.com/terracredit-Project/terracredit.git'])
os.chdir('gitian-builder')
make_image_prog = ['bin/make-base-vm', '--suite', 'bionic', '--arch', 'amd64']
if args.docker:
make_image_prog += ['--docker']
elif not args.kvm:
make_image_prog += ['--lxc']
if args.host_os == 'darwin':
subprocess.check_call(['sed', '-i.old', '/50cacher/d', 'bin/make-base-vm'])
if args.host_os == 'linux':
if args.is_fedora or args.is_centos:
subprocess.check_call(['sed', '-i', '/50cacher/d', 'bin/make-base-vm'])
subprocess.check_call(make_image_prog)
subprocess.check_call(['git', 'checkout', 'bin/make-base-vm'])
os.chdir(workdir)
if args.host_os == 'linux':
if args.is_bionic and not args.kvm and not args.docker:
subprocess.check_call(['sudo', 'sed', '-i', 's/lxcbr0/br0/', '/etc/default/lxc-net'])
print('Reboot is required')
print('Setup complete!')
sys.exit(0)
def build():
global args, workdir
os.makedirs('terracredit-binaries/' + args.version, exist_ok=True)
print('\nBuilding Dependencies\n')
os.chdir('gitian-builder')
os.makedirs('inputs', exist_ok=True)
subprocess.check_call(['wget', '-N', '-P', 'inputs', 'https://downloads.sourceforge.net/project/osslsigncode/osslsigncode/osslsigncode-1.7.1.tar.gz'])
subprocess.check_call(['wget', '-N', '-P', 'inputs', 'https://bitcoincore.org/cfields/osslsigncode-Backports-to-1.7.1.patch'])
subprocess.check_call(["echo 'a8c4e9cafba922f89de0df1f2152e7be286aba73f78505169bc351a7938dd911 inputs/osslsigncode-Backports-to-1.7.1.patch' | sha256sum -c"], shell=True)
subprocess.check_call(["echo 'f9a8cdb38b9c309326764ebc937cba1523a3a751a7ab05df3ecc99d18ae466c9 inputs/osslsigncode-1.7.1.tar.gz' | sha256sum -c"], shell=True)
subprocess.check_call(['make', '-C', '../terracredit/depends', 'download', 'SOURCES_PATH=' + os.getcwd() + '/cache/common'])
if args.linux:
print('\nCompiling ' + args.version + ' Linux')
subprocess.check_call(['bin/gbuild', '-j', args.jobs, '-m', args.memory, '--commit', 'terracredit='+args.commit, '--url', 'terracredit='+args.url, '../terracredit/contrib/gitian-descriptors/gitian-linux.yml'])
subprocess.check_call(['bin/gsign', '-p', args.sign_prog, '--signer', args.signer, '--release', args.version+'-linux', '--destination', '../gitian.sigs/', '../terracredit/contrib/gitian-descriptors/gitian-linux.yml'])
subprocess.check_call('mv build/out/terracredit-*.tar.gz build/out/src/terracredit-*.tar.gz ../terracredit-binaries/'+args.version, shell=True)
if args.windows:
print('\nCompiling ' + args.version + ' Windows')
subprocess.check_call(['bin/gbuild', '-j', args.jobs, '-m', args.memory, '--commit', 'terracredit='+args.commit, '--url', 'terracredit='+args.url, '../terracredit/contrib/gitian-descriptors/gitian-win.yml'])
subprocess.check_call(['bin/gsign', '-p', args.sign_prog, '--signer', args.signer, '--release', args.version+'-win-unsigned', '--destination', '../gitian.sigs/', '../terracredit/contrib/gitian-descriptors/gitian-win.yml'])
subprocess.check_call('mv build/out/terracredit-*-win-unsigned.tar.gz inputs/', shell=True)
subprocess.check_call('mv build/out/terracredit-*.zip build/out/terracredit-*.exe build/out/src/terracredit-*.tar.gz ../terracredit-binaries/'+args.version, shell=True)
if args.macos:
print('\nCompiling ' + args.version + ' MacOS')
subprocess.check_call(['bin/gbuild', '-j', args.jobs, '-m', args.memory, '--commit', 'terracredit='+args.commit, '--url', 'terracredit='+args.url, '../terracredit/contrib/gitian-descriptors/gitian-osx.yml'])
subprocess.check_call(['bin/gsign', '-p', args.sign_prog, '--signer', args.signer, '--release', args.version+'-osx-unsigned', '--destination', '../gitian.sigs/', '../terracredit/contrib/gitian-descriptors/gitian-osx.yml'])
subprocess.check_call('mv build/out/terracredit-*-osx-unsigned.tar.gz inputs/', shell=True)
subprocess.check_call('mv build/out/terracredit-*.tar.gz build/out/terracredit-*.dmg build/out/src/terracredit-*.tar.gz ../terracredit-binaries/'+args.version, shell=True)
os.chdir(workdir)
if args.commit_files:
print('\nCommitting '+args.version+' Unsigned Sigs\n')
os.chdir('gitian.sigs')
subprocess.check_call(['git', 'add', args.version+'-linux/'+args.signer])
subprocess.check_call(['git', 'add', args.version+'-win-unsigned/'+args.signer])
subprocess.check_call(['git', 'add', args.version+'-osx-unsigned/'+args.signer])
subprocess.check_call(['git', 'commit', '-m', 'Add '+args.version+' unsigned sigs for '+args.signer])
os.chdir(workdir)
def sign():
global args, workdir
os.chdir('gitian-builder')
# TODO: Skip making signed windows sigs until we actually start producing signed windows binaries
#print('\nSigning ' + args.version + ' Windows')
#subprocess.check_call('cp inputs/terracredit-' + args.version + '-win-unsigned.tar.gz inputs/terracredit-win-unsigned.tar.gz', shell=True)
#subprocess.check_call(['bin/gbuild', '--skip-image', '--upgrade', '--commit', 'signature='+args.commit, '../terracredit/contrib/gitian-descriptors/gitian-win-signer.yml'])
#subprocess.check_call(['bin/gsign', '-p', args.sign_prog, '--signer', args.signer, '--release', args.version+'-win-signed', '--destination', '../gitian.sigs/', '../terracredit/contrib/gitian-descriptors/gitian-win-signer.yml'])
#subprocess.check_call('mv build/out/terracredit-*win64-setup.exe ../terracredit-binaries/'+args.version, shell=True)
#subprocess.check_call('mv build/out/terracredit-*win32-setup.exe ../terracredit-binaries/'+args.version, shell=True)
print('\nSigning ' + args.version + ' MacOS')
subprocess.check_call('cp inputs/terracredit-' + args.version + '-osx-unsigned.tar.gz inputs/terracredit-osx-unsigned.tar.gz', shell=True)
subprocess.check_call(['bin/gbuild', '--skip-image', '--upgrade', '--commit', 'signature='+args.commit, '../terracredit/contrib/gitian-descriptors/gitian-osx-signer.yml'])
subprocess.check_call(['bin/gsign', '-p', args.sign_prog, '--signer', args.signer, '--release', args.version+'-osx-signed', '--destination', '../gitian.sigs/', '../terracredit/contrib/gitian-descriptors/gitian-osx-signer.yml'])
subprocess.check_call('mv build/out/terracredit-osx-signed.dmg ../terracredit-binaries/'+args.version+'/terracredit-'+args.version+'-osx.dmg', shell=True)
os.chdir(workdir)
if args.commit_files:
os.chdir('gitian.sigs')
commit = False
if os.path.isfile(args.version+'-win-signed/'+args.signer+'/terracredit-win-signer-build.assert.sig'):
subprocess.check_call(['git', 'add', args.version+'-win-signed/'+args.signer])
commit = True
if os.path.isfile(args.version+'-osx-signed/'+args.signer+'/terracredit-dmg-signer-build.assert.sig'):
subprocess.check_call(['git', 'add', args.version+'-osx-signed/'+args.signer])
commit = True
if commit:
print('\nCommitting '+args.version+' Signed Sigs\n')
subprocess.check_call(['git', 'commit', '-a', '-m', 'Add '+args.version+' signed binary sigs for '+args.signer])
else:
print('\nNothing to commit\n')
os.chdir(workdir)
def verify():
global args, workdir
rc = 0
os.chdir('gitian-builder')
print('\nVerifying v'+args.version+' Linux\n')
if subprocess.call(['bin/gverify', '-v', '-d', '../gitian.sigs/', '-r', args.version+'-linux', '../terracredit/contrib/gitian-descriptors/gitian-linux.yml']):
print('Verifying v'+args.version+' Linux FAILED\n')
rc = 1
print('\nVerifying v'+args.version+' Windows\n')
if subprocess.call(['bin/gverify', '-v', '-d', '../gitian.sigs/', '-r', args.version+'-win-unsigned', '../terracredit/contrib/gitian-descriptors/gitian-win.yml']):
print('Verifying v'+args.version+' Windows FAILED\n')
rc = 1
print('\nVerifying v'+args.version+' MacOS\n')
if subprocess.call(['bin/gverify', '-v', '-d', '../gitian.sigs/', '-r', args.version+'-osx-unsigned', '../terracredit/contrib/gitian-descriptors/gitian-osx.yml']):
print('Verifying v'+args.version+' MacOS FAILED\n')
rc = 1
# TODO: Skip checking signed windows sigs until we actually start producing signed windows binaries
#print('\nVerifying v'+args.version+' Signed Windows\n')
#if subprocess.call(['bin/gverify', '-v', '-d', '../gitian.sigs/', '-r', args.version+'-win-signed', '../terracredit/contrib/gitian-descriptors/gitian-win-signer.yml']):
# print('Verifying v'+args.version+' Signed Windows FAILED\n')
# rc = 1
print('\nVerifying v'+args.version+' Signed MacOS\n')
if subprocess.call(['bin/gverify', '-v', '-d', '../gitian.sigs/', '-r', args.version+'-osx-signed', '../terracredit/contrib/gitian-descriptors/gitian-osx-signer.yml']):
print('Verifying v'+args.version+' Signed MacOS FAILED\n')
rc = 1
os.chdir(workdir)
return rc
def main():
global args, workdir
parser = argparse.ArgumentParser(description='Script for running full Gitian builds.')
parser.add_argument('-c', '--commit', action='store_true', dest='commit', help='Indicate that the version argument is for a commit or branch')
parser.add_argument('-p', '--pull', action='store_true', dest='pull', help='Indicate that the version argument is the number of a github repository pull request')
parser.add_argument('-u', '--url', dest='url', default='https://github.com/terracredit-Project/terracredit', help='Specify the URL of the repository. Default is %(default)s')
parser.add_argument('-v', '--verify', action='store_true', dest='verify', help='Verify the Gitian build')
parser.add_argument('-b', '--build', action='store_true', dest='build', help='Do a Gitian build')
parser.add_argument('-s', '--sign', action='store_true', dest='sign', help='Make signed binaries for Windows and MacOS')
parser.add_argument('-B', '--buildsign', action='store_true', dest='buildsign', help='Build both signed and unsigned binaries')
parser.add_argument('-o', '--os', dest='os', default='lwm', help='Specify which Operating Systems the build is for. Default is %(default)s. l for Linux, w for Windows, m for MacOS')
parser.add_argument('-j', '--jobs', dest='jobs', default='2', help='Number of processes to use. Default %(default)s')
parser.add_argument('-m', '--memory', dest='memory', default='2000', help='Memory to allocate in MiB. Default %(default)s')
parser.add_argument('-k', '--kvm', action='store_true', dest='kvm', help='Use KVM instead of LXC')
parser.add_argument('-d', '--docker', action='store_true', dest='docker', help='Use Docker instead of LXC')
parser.add_argument('-S', '--setup', action='store_true', dest='setup', help='Set up the Gitian building environment. Only works on Debian-based systems (Ubuntu, Debian)')
parser.add_argument('-D', '--detach-sign', action='store_true', dest='detach_sign', help='Create the assert file for detached signing. Will not commit anything.')
parser.add_argument('-n', '--no-commit', action='store_false', dest='commit_files', help='Do not commit anything to git')
parser.add_argument('signer', nargs='?', help='GPG signer to sign each build assert file')
parser.add_argument('version', nargs='?', help='Version number, commit, or branch to build. If building a commit or branch, the -c option must be specified')
args = parser.parse_args()
workdir = os.getcwd()
args.host_os = sys.platform
if args.host_os == 'win32' or args.host_os == 'cygwin':
raise Exception('Error: Native Windows is not supported by this script, use WSL')
if args.host_os == 'linux':
if os.environ['USER'] == 'root':
raise Exception('Error: Do not run this script as the root user')
args.is_bionic = False
args.is_fedora = False
args.is_centos = False
if os.path.isfile('/usr/bin/lsb_release'):
args.is_bionic = b'bionic' in subprocess.check_output(['lsb_release', '-cs'])
if os.path.isfile('/etc/fedora-release'):
args.is_fedora = True
if os.path.isfile('/etc/centos-release'):
args.is_centos = True
if args.kvm and args.docker:
raise Exception('Error: cannot have both kvm and docker')
# Ensure no more than one environment variable for gitian-builder (USE_LXC, USE_VBOX, USE_DOCKER) is set as they
# can interfere (e.g., USE_LXC being set shadows USE_DOCKER; for details see gitian-builder/libexec/make-clean-vm).
os.environ['USE_LXC'] = ''
os.environ['USE_VBOX'] = ''
os.environ['USE_DOCKER'] = ''
if args.docker:
os.environ['USE_DOCKER'] = '1'
elif not args.kvm:
os.environ['USE_LXC'] = '1'
if 'GITIAN_HOST_IP' not in os.environ.keys():
os.environ['GITIAN_HOST_IP'] = '10.0.3.1'
if 'LXC_GUEST_IP' not in os.environ.keys():
os.environ['LXC_GUEST_IP'] = '10.0.3.5'
if args.setup:
if args.host_os == 'linux':
setup_linux()
elif args.host_os == 'darwin':
setup_darwin()
if args.buildsign:
args.build = True
args.sign = True
if not args.build and not args.sign and not args.verify:
sys.exit(0)
if args.host_os == 'darwin':
os.environ['PATH'] = '/usr/local/opt/coreutils/libexec/gnubin' + os.pathsep + os.environ['PATH']
args.linux = 'l' in args.os
args.windows = 'w' in args.os
args.macos = 'm' in args.os
# Disable for MacOS if no SDK found
if args.macos and not os.path.isfile('gitian-builder/inputs/MacOSX10.11.sdk.tar.gz'):
print('Cannot build for MacOS, SDK does not exist. Will build for other OSes')
args.macos = False
args.sign_prog = 'true' if args.detach_sign else 'gpg --detach-sign'
if args.detach_sign:
args.commit_files = False
script_name = os.path.basename(sys.argv[0])
if not args.signer:
print(script_name+': Missing signer')
print('Try '+script_name+' --help for more information')
sys.exit(1)
if not args.version:
print(script_name+': Missing version')
print('Try '+script_name+' --help for more information')
sys.exit(1)
# Add leading 'v' for tags
if args.commit and args.pull:
raise Exception('Cannot have both commit and pull')
args.commit = ('' if args.commit else 'v') + args.version
os.chdir('terracredit')
if args.pull:
subprocess.check_call(['git', 'fetch', args.url, 'refs/pull/'+args.version+'/merge'])
if not os.path.isdir('../gitian-builder/inputs/terracredit'):
os.makedirs('../gitian-builder/inputs/terracredit')
os.chdir('../gitian-builder/inputs/terracredit')
if not os.path.isdir('.git'):
subprocess.check_call(['git', 'init'])
subprocess.check_call(['git', 'fetch', args.url, 'refs/pull/'+args.version+'/merge'])
args.commit = subprocess.check_output(['git', 'show', '-s', '--format=%H', 'FETCH_HEAD'], universal_newlines=True, encoding='utf8').strip()
args.version = 'pull-' + args.version
print(args.commit)
subprocess.check_call(['git', 'fetch'])
subprocess.check_call(['git', 'checkout', args.commit])
os.chdir(workdir)
os.chdir('gitian-builder')
subprocess.check_call(['git', 'pull'])
os.chdir(workdir)
if args.build:
build()
if args.sign:
sign()
if args.verify:
os.chdir('gitian.sigs')
subprocess.check_call(['git', 'pull'])
os.chdir(workdir)
sys.exit(verify())
if __name__ == '__main__':
main()
| [
"alonewolf2ksk@gmail.com"
] | alonewolf2ksk@gmail.com |
d576ee243987e026e7db286752d55ddc344a1942 | 8cdad42543eb9d6a3c3a9ddf5a3d768a09aef78d | /lesson3/visual_optimizer/example_0.py | 1026e1151f0da929d1dfc302dc63cbde89018b05 | [] | no_license | SoulDuck/Edu_DL | b81b4ac871864440210b109c7fc76c7cc2c54391 | 3ab10fa147bb6282517a413a5c2c465f0277cebe | refs/heads/master | 2022-11-27T08:18:39.676980 | 2019-03-17T14:44:27 | 2019-03-17T14:44:27 | 155,827,188 | 0 | 1 | null | 2022-11-01T20:28:40 | 2018-11-02T07:04:08 | Jupyter Notebook | UTF-8 | Python | false | false | 2,289 | py | import matplotlib.pyplot as plt
import autograd.numpy as np
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import LogNorm
from matplotlib import animation
from IPython.display import HTML
from autograd import elementwise_grad, value_and_grad
from scipy.optimize import minimize
from collections import defaultdict
from itertools import zip_longest
from functools import partial
f = lambda x, y: (1.5 - x + x*y)**2 + (2.25 - x + x*y**2)**2 + (2.625 - x + x*y**3)**2
xmin, xmax, xstep = -4.5, 4.5, .2
ymin, ymax, ystep = -4.5, 4.5, .2
x, y = np.meshgrid(np.arange(xmin, xmax + xstep, xstep), np.arange(ymin, ymax + ystep, ystep))
z = f(x, y)
minima = np.array([3., .5]) # minima 인 곳을 별로 표시함
f(*minima) # minima value : 0
minima_ = minima.reshape(-1, 1)
fig = plt.figure(figsize=(8, 5))
ax = plt.axes(projection='3d', elev=50, azim=-50)
ax.plot(*minima_, f(*minima_), 'r*', markersize=10)
ax.plot_surface(x, y, z, norm=LogNorm(), rstride=1, cstride=1,
edgecolor='c', alpha=0.5, cmap=plt.cm.jet, linewidth=0.5)
ax.view_init(30, 10)
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
ax.set_zlabel('$z$')
ax.set_xlim((xmin, xmax))
ax.set_ylim((ymin, ymax))
plt.show()
plt.close()
# Optimizer
x0 = np.array([3., 4.])
func = value_and_grad(lambda args: f(*args))
def make_minimize_cb(path=[]):
def minimize_cb(xk):
# note that we make a deep copy of xk
path.append(np.copy(xk))
return minimize_cb
path_ = [x0]
res = minimize(func, x0=x0, method='Newton-CG',
jac=True, tol=1e-20, callback=make_minimize_cb(path_))
print(path_)
path_ = np.asarray(path_)
path = path_.T
fig = plt.figure(figsize=(8, 5))
ax = plt.axes(projection='3d', elev=50, azim=-50)
# logNorm -> Normalize a given value to the 0-1 range on a log scale
ax.plot_surface(x, y, z, norm=LogNorm(), rstride=2, cstride=2, edgecolor='none', alpha=0.5, cmap=plt.cm.jet)
ax.quiver(path[0,:-1], path[1,:-1], f(*path[::,:-1]),
path[0,1:] - path[0,:-1], path[1,1:] - path[1,:-1], f(*(path[::,1:] - path[::,:-1])),
color='k')
ax.plot(*minima_, f(*minima_), 'r*', markersize=10)
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
ax.set_zlabel('$z$')
ax.set_xlim((xmin, xmax))
ax.set_ylim((ymin, ymax))
plt.show()
plt.close()
| [
"plznw4me@naver.com"
] | plznw4me@naver.com |
26313529fa41479b7cac8f822e78c9ce13050b70 | a5b66100762c0ca7076de26645ef1b732e0ee2d8 | /test_python_toolbox/test_cute_iter_tools/test_iterate_overlapping_subsequences.py | acddca4ead74e7042a28fa22d1433a03de3ae3e3 | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | permissive | cool-RR/python_toolbox | 63400bbc004c63b32fe421b668a64bede4928e90 | cb9ef64b48f1d03275484d707dc5079b6701ad0c | refs/heads/master | 2022-01-26T14:41:29.194288 | 2021-12-25T06:49:40 | 2021-12-25T06:49:40 | 3,066,283 | 130 | 15 | NOASSERTION | 2021-12-25T06:49:41 | 2011-12-29T01:39:51 | Python | UTF-8 | Python | false | false | 5,491 | py | # Copyright 2009-2017 Ram Rachum.
# This program is distributed under the MIT license.
'''Testing module for `cute_iter_tools.iterate_overlapping_subsequences`.'''
import collections
from python_toolbox import gc_tools
from python_toolbox import nifty_collections
from python_toolbox import cute_testing
from python_toolbox import sequence_tools
from python_toolbox.cute_iter_tools import iterate_overlapping_subsequences
def test_length_2():
# `iterate_overlapping_subsequences` returns an iterator, not a sequence:
assert not isinstance(
iterate_overlapping_subsequences(list(range(4))),
collections.abc.Sequence
)
assert tuple(iterate_overlapping_subsequences(list(range(4)))) == \
tuple(iterate_overlapping_subsequences(range(4))) == \
((0, 1), (1, 2), (2, 3))
assert tuple(iterate_overlapping_subsequences(list(range(4)),
wrap_around=True)) == \
tuple(iterate_overlapping_subsequences(range(4),
wrap_around=True)) ==\
((0, 1), (1, 2), (2, 3), (3, 0))
assert tuple(iterate_overlapping_subsequences('meow')) == \
(('m', 'e'), ('e', 'o'), ('o', 'w'))
def test_iterable_too_short():
with cute_testing.RaiseAssertor(NotImplementedError):
tuple(iterate_overlapping_subsequences([1], wrap_around=True))
def test_various_lengths():
assert tuple(iterate_overlapping_subsequences(range(7), length=3)) == \
((0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6))
assert tuple(iterate_overlapping_subsequences(range(7), length=4)) == \
((0, 1, 2, 3), (1, 2, 3, 4), (2, 3, 4, 5), (3, 4, 5, 6))
assert tuple(iterate_overlapping_subsequences(range(7), length=5)) == \
((0, 1, 2, 3, 4), (1, 2, 3, 4, 5), (2, 3, 4, 5, 6))
assert tuple(iterate_overlapping_subsequences(range(7), length=1)) == \
tuple(range(7))
assert tuple(iterate_overlapping_subsequences(range(7), length=4,
wrap_around=True)) == ((0, 1, 2, 3), (1, 2, 3, 4), (2, 3, 4, 5),
(3, 4, 5, 6), (4, 5, 6, 0), (5, 6, 0, 1), (6, 0, 1, 2))
assert tuple(iterate_overlapping_subsequences(range(7), length=5,
wrap_around=True)) == ((0, 1, 2, 3, 4), (1, 2, 3, 4, 5),
(2, 3, 4, 5, 6), (3, 4, 5, 6, 0), (4, 5, 6, 0, 1), (5, 6, 0, 1, 2),
(6, 0, 1, 2, 3))
def test_lazy_tuple():
lazy_tuple = \
iterate_overlapping_subsequences(range(7), length=3, lazy_tuple=True)
assert isinstance(lazy_tuple, nifty_collections.LazyTuple)
assert not lazy_tuple.collected_data
assert lazy_tuple == \
((0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6))
def test_garbage_collection():
garbage_collected = set()
class GarbageNoter:
def __init__(self, n):
assert isinstance(n, int)
self.n = n
def __del__(self):
garbage_collected.add(self.n)
iterable = (GarbageNoter(i) for i in range(7))
consecutive_subsequences_iterator = \
iterate_overlapping_subsequences(iterable, length=3)
def assert_garbage_collected(indexes):
gc_tools.collect()
assert set(indexes) == garbage_collected
assert_garbage_collected(())
next(consecutive_subsequences_iterator)
assert_garbage_collected(())
next(consecutive_subsequences_iterator)
assert_garbage_collected((0,))
next(consecutive_subsequences_iterator)
assert_garbage_collected((0, 1))
next(consecutive_subsequences_iterator)
assert_garbage_collected((0, 1, 2))
next(consecutive_subsequences_iterator)
assert_garbage_collected((0, 1, 2, 3))
with cute_testing.RaiseAssertor(StopIteration):
next(consecutive_subsequences_iterator)
assert_garbage_collected((0, 1, 2, 3, 4, 5, 6))
def test_garbage_collection_wrap_around():
garbage_collected = set()
class GarbageNoter:
def __init__(self, n):
assert isinstance(n, int)
self.n = n
def __del__(self):
garbage_collected.add(self.n)
iterable = (GarbageNoter(i) for i in range(7))
consecutive_subsequences_iterator = \
iterate_overlapping_subsequences(iterable, length=3, wrap_around=True)
def assert_garbage_collected(indexes):
gc_tools.collect()
assert set(indexes) == garbage_collected
assert_garbage_collected(())
next(consecutive_subsequences_iterator)
assert_garbage_collected(())
next(consecutive_subsequences_iterator)
assert_garbage_collected(())
next(consecutive_subsequences_iterator)
assert_garbage_collected(())
next(consecutive_subsequences_iterator)
assert_garbage_collected((2,))
next(consecutive_subsequences_iterator)
assert_garbage_collected((2, 3))
next(consecutive_subsequences_iterator)
assert_garbage_collected((2, 3, 4))
next(consecutive_subsequences_iterator)
assert_garbage_collected((2, 3, 4, 5))
with cute_testing.RaiseAssertor(StopIteration):
next(consecutive_subsequences_iterator)
assert_garbage_collected((0, 1, 2, 3, 4, 5, 6))
def test_short_iterables():
assert tuple(iterate_overlapping_subsequences([1])) == ()
assert tuple(iterate_overlapping_subsequences([1], length=7)) == ()
| [
"ram@rachum.com"
] | ram@rachum.com |
02fee580a449534a696d8a009b72407c8e92397c | 487ce91881032c1de16e35ed8bc187d6034205f7 | /codes/CodeJamCrawler/16_0_3_neat/16_0_3_SGer_coinjam.py | ddadbc4f209398f6d0184b2127b91ea3acef6fb2 | [] | no_license | DaHuO/Supergraph | 9cd26d8c5a081803015d93cf5f2674009e92ef7e | c88059dc66297af577ad2b8afa4e0ac0ad622915 | refs/heads/master | 2021-06-14T16:07:52.405091 | 2016-08-21T13:39:13 | 2016-08-21T13:39:13 | 49,829,508 | 2 | 0 | null | 2021-03-19T21:55:46 | 2016-01-17T18:23:00 | Python | UTF-8 | Python | false | false | 1,674 | py | import sys
def primeCheck(n):
# sieve holds all the numbers that still can be divisors
upperBorder = int(n**0.5)+1
sieve = [True]*upperBorder
sieve[0] = False
sieve[1] = False
for i in xrange(upperBorder):
# If we already know that the number is not a divisor, just skip it
if (sieve[i] == False):
continue
# Return divisor
if (n % i == 0):
return i
# Eliminate all multiples of the non-divisor
else:
for j in xrange(i, int(upperBorder / i), i):
sieve[j] = False
return None
if (len(sys.argv) < 2):
print "Need inputfile as argument"
exit(1)
#read file
input = list()
with open(sys.argv[1], 'r') as f:
input = f.read().splitlines()
input.pop(0)
#convert to int list
input = map(lambda s: map(int, s.split(' ')), input)
def listToStr(indexList):
indexListStr = ""
for index in indexList:
indexListStr += str(index)+" "
indexListStr = indexListStr[:-1]
return indexListStr
#compute
output = list()
for (N, J) in input:
for i in xrange(int("1"+"0"*(N-2),2), int("1"*(N-1),2)+1):
if (len(output) >= J):
break
bitString = bin(i)[2:]+"1"
isPrime = False
divisors = list()
# Find Divisors or that one of the interpretations is prime
for base in range(2,11):
n = int(bitString,base)
divisor = primeCheck(n)
if (divisor is None):
isPrime = True
break
else:
divisors.append(divisor)
print "n: "+str(n)+" d: "+str(divisor)
# If none of the interpretations were prime, we found a jamcoin
if (not isPrime):
output.append(str(bitString)+" "+listToStr(divisors))
#write file
with open('output_coinjam.txt', 'w') as f:
f.write("Case #1:\n")
for line in output:
f.write(line+"\n")
| [
"[dhuo@tcd.ie]"
] | [dhuo@tcd.ie] |
3976434872d602cbd85f8af7adc7780d589d700f | 0806d939ef0e8218c0f727e025eb0b3bb328d343 | /vote/polls/settings.py | 57025f38b164cace2fa091fd11f661cd86271aaf | [] | no_license | aiegoo/django-web | bcd89687d951e0877000c23230661ce566144e78 | 5476ed77cf95919d9b825f4cef03d42f217768ce | refs/heads/master | 2021-07-17T01:20:24.279227 | 2020-09-27T05:15:05 | 2020-09-27T05:15:05 | 215,240,173 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,156 | py | """
Django settings for polls project.
Generated by 'django-admin startproject' using Django 2.2.6.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'j^7=0_6j4v3nqf3sodtvmra8f7r76d872&b6()b@ie9k6lpdna'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['178.128.223.232', 'localhost', '127.0.0.0']
# Application definition
INSTALLED_APPS = [
'vote.apps.VoteConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'polls.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'polls.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
| [
"eozz21@gmail.com"
] | eozz21@gmail.com |
7c5f7ab7b3a9edaffcf8c46037bdc4f1be5a349d | 871e1b0295c0fbbfca8191236d674866cf62ff01 | /TrainB7_NAR1_noisy-student.py | 6eee387bf281a62a200d38e6acdd02993bd6a410 | [] | no_license | Peckkie/USAI_ABnormal_Screening | ce31a813e9303a7d43def912ab731cc633268cb7 | 82cd63ac9ab72fbe68eae254c15c7bf7ef906022 | refs/heads/master | 2023-02-16T13:32:33.678500 | 2021-01-07T02:36:35 | 2021-01-07T02:36:35 | 277,981,638 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,082 | py | import PIL
from keras import models
from keras import layers
from tensorflow.keras import optimizers
import os
import glob
import shutil
import sys
import numpy as np
from skimage.io import imread
import matplotlib.pyplot as plt
import os
from tensorflow.keras import callbacks
import pandas as pd
from keras.utils import generic_utils
os.environ["CUDA_VISIBLE_DEVICES"]="0"
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
batch_size = 32
epochs = 200
#Train
dataframe = pd.read_csv( '/media/tohn/SSD/ImageForTrainTest/train.csv')
base_dir = '/media/tohn/SSD/ImageForTrainTest/'
os.chdir(base_dir)
train_dir = os.path.join(base_dir, 'train')
#validation
valframe = pd.read_csv( '/media/tohn/SSD/ImageForTrainTest/validation.csv')
validation_dir = os.path.join(base_dir, 'validation')
from efficientnet.keras import EfficientNetB7 as Net
from efficientnet.keras import center_crop_and_resize, preprocess_input
conv_base = Net(weights='noisy-student')
height = width = conv_base.input_shape[1]
input_shape = (height, width, 3)
# loading pretrained conv base model
conv_base = Net(weights='noisy-student', include_top=False, input_shape=input_shape)
# create new model with a new classification layer
x = conv_base.output
global_average_layer = layers.GlobalAveragePooling2D(name = 'head_pooling')(x)
dropout_layer_1 = layers.Dropout(0.50,name = 'head_dropout')(global_average_layer)
prediction_layer = layers.Dense(2, activation='softmax',name = 'prediction_layer')(dropout_layer_1)
model = models.Model(inputs= conv_base.input, outputs=prediction_layer)
model.summary()
#showing before&after freezing
print('This is the number of trainable layers '
'before freezing the conv base:', len(model.trainable_weights))
#conv_base.trainable = False # freeze เพื่อรักษา convolutional base's weight
for layer in conv_base.layers:
layer.trainable = False
print('This is the number of trainable layers '
'after freezing the conv base:', len(model.trainable_weights)) #freez แล้วจะเหลือ max pool and dense
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=30,
width_shift_range=0.2,
height_shift_range=0.2,
brightness_range=[0.5,1.5],
shear_range=0.4,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest')
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_dataframe(
dataframe = dataframe,
directory = train_dir,
x_col = 'Path Crop',
y_col = 'Class',
target_size = (height, width),
batch_size=batch_size,
color_mode= 'rgb',
class_mode='categorical')
test_generator = test_datagen.flow_from_dataframe(
dataframe = valframe,
directory = validation_dir,
x_col = 'Path Crop',
y_col = 'Class',
target_size = (height, width),
batch_size=batch_size,
color_mode= 'rgb',
class_mode='categorical')
os.chdir('/media/tohn/SSD/trainEffbyB/R1')
root_logdir = '/media/tohn/SSD/trainEffbyB/R1/my_logs_B7noisy'
def get_run_logdir():
import time
run_id = time.strftime("run_%Y_%m_%d_%H_%M_%S")
return os.path.join(root_logdir,run_id)
run_logdir = get_run_logdir()
tensorboard_cb = callbacks.TensorBoard(log_dir = run_logdir)
# os.makedirs("./models", exist_ok=True)
def avoid_error(gen):
while True:
try:
data, labels = next(gen)
yield data, labels
except:
pass
#Training
model.compile(loss='categorical_crossentropy',
optimizer=optimizers.RMSprop(lr=2e-5),
metrics=['acc'])
history = model.fit_generator(
avoid_error(train_generator),
steps_per_epoch= len(dataframe)//batch_size,
epochs=epochs,
validation_data=avoid_error(test_generator),
validation_steps= len(valframe) //batch_size,
callbacks = [tensorboard_cb])
model.save('./models/B7_R1_noisy.h5')
| [
"w_yupaporn@kkumail.com"
] | w_yupaporn@kkumail.com |
c4658453b2716be727acbcdafee395d3b540e6a5 | ccbfc7818c0b75929a1dfae41dc061d5e0b78519 | /aliyun-openapi-python-sdk-master/aliyun-python-sdk-imm/aliyunsdkimm/request/v20170906/ListTagSetsRequest.py | 47f868aa7d94a71b6c0a79b6e8e4d3a9862ff1f7 | [
"Apache-2.0"
] | permissive | P79N6A/dysms_python | 44b634ffb2856b81d5f79f65889bfd5232a9b546 | f44877b35817e103eed469a637813efffa1be3e4 | refs/heads/master | 2020-04-28T15:25:00.368913 | 2019-03-13T07:52:34 | 2019-03-13T07:52:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,404 | py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
from aliyunsdkcore.request import RpcRequest
class ListTagSetsRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'imm', '2017-09-06', 'ListTagSets','imm')
def get_MaxKeys(self):
return self.get_query_params().get('MaxKeys')
def set_MaxKeys(self,MaxKeys):
self.add_query_param('MaxKeys',MaxKeys)
def get_Marker(self):
return self.get_query_params().get('Marker')
def set_Marker(self,Marker):
self.add_query_param('Marker',Marker)
def get_Project(self):
return self.get_query_params().get('Project')
def set_Project(self,Project):
self.add_query_param('Project',Project) | [
"1478458905@qq.com"
] | 1478458905@qq.com |
6f7210e36bf9be6421624a8552e233ad0d6289cc | 3b979bbed493ac72a5a3bd50209f6c2132fe7e46 | /shinobu/database.py | a2870b1e7ad4a3cdb58d7de635c77df13ca6ee10 | [] | no_license | 3jackdaws/shinobu2 | b8ba6f081ce2f309a38b834aad6b2f8d11baebff | eb5d1dd9667f66cf3acc2394be0ec5402aee4218 | refs/heads/master | 2021-01-20T06:38:41.529998 | 2017-12-11T04:16:49 | 2017-12-11T04:16:49 | 89,904,844 | 1 | 2 | null | null | null | null | UTF-8 | Python | false | false | 20 | py | from peewee import * | [
"3jackdaws@gmail.com"
] | 3jackdaws@gmail.com |
b5b926c106c60946a48179e4795ab856cd8820bb | ac4b9385b7ad2063ea51237fbd8d1b74baffd016 | /.history/google/gmail_extract_20210219015211.py | c4d7dfe90ce25f2f1ff0dd84344c6a9d2cfe242a | [] | no_license | preethanpa/ssoemprep | 76297ef21b1d4893f1ac2f307f60ec72fc3e7c6f | ce37127845253c768d01aeae85e5d0d1ade64516 | refs/heads/main | 2023-03-09T00:15:55.130818 | 2021-02-20T06:54:58 | 2021-02-20T06:54:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,993 | py | from __future__ import print_function
import pickle
import os.path
import io
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.http import MediaIoBaseDownload
from oauth2client.service_account import ServiceAccountCredentials
from google.oauth2 import service_account
import googleapiclient.discovery
import inspect
import sys
import json
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'
]
# The ID of a sample document.
# DOCUMENT_ID = '1bQkFcQrWFHGlte8oTVtq_zyKGIgpFlWAS5_5fi8OzjY'
DOCUMENT_ID = '1sXQie19gQBRHODebxBZv4xUCJy-9rGpnlpM7_SUFor4'
# SERVICE_ACCOUNT_FILE = '/home/dsie/Developer/sandbox/3ray/3rml/kbc_process/google/domain-wide-credentials-gdrive.json'
SERVICE_ACCOUNT_FILE = '/home/dsie/Developer/sandbox/3ray/3rml/kbc_process/google/app-automation-service-account-thirdrayai-1612747564720-415d6ebd6001.json'
UPLOAD_FILE_LOCATION = '/home/dsie/Developer/sandbox/3ray/3rml/kbc_process/documents/pdf/'
doc_types = {
"application/vnd.google-apps.document": "gdoc",
# "application/vnd.google-apps.folder": "folder",
"application/vnd.google-apps.spreadsheet": "gsheet",
"application/vnd.google-apps.presentation": "gslide",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx"
}
drive_files_list = [] if (sys.argv is None or sys.argv[1] is None) else json.loads(sys.argv[1])
job_id = drive_files_list.get("job_id")
email_id = None if (sys.argv is None or sys.argv[1] is None) else json.loads(sys.argv[1]).email_id
document_id = ''
def get_resource(domain_wide_delegate=False, user_to_impersonate=None):
"""Prepare a Google Drive resource object based on credentials.
"""
credentials = None
# use subject in case of domain-wide delegation
if domain_wide_delegate:
if user_to_impersonate is not None:
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES, subject=user_to_impersonate)
else:
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
if credentials is None:
return credentials
else:
drive_service = build('drive', 'v3', credentials=credentials)
return drive_service
def download_drive_file(resource=None, document_id=None, google_file_type='gdoc', target_type=None, target_location=None):
"""Downloads a Google Drive file using the provided resource.
If google_file_type is passed as None, then 'gdoc' / Google Doc is default.
If target_type is passed as None, then 'application/pdf' is default.
If location is none, then use environment variable UPLOAD_FILE_LOCATION as default
"""
# print(dir(resource.files())) #Get resource methods with dir.
if resource is None:
raise Exception('Invalid credentials. Provide subject email addredd for Drive-wide delegation')
else:
extension, mimeType = extension_mime_type(google_file_type, target_type)
try:
content = resource.files().export(fileId=document_id, mimeType=mimeType).execute()
try:
with open(target_location+google_file_type+'-'+document_id+extension, "wb") as file:
file.write(content)
return {"file": google_file_type+'-'+document_id+extension}
except Exception as exc_in:
return
# return {"document_id": document_id, "status": "Exception in with open", "message": exc_in}
except Exception as exc_out:
return
# return {"document_id": document_id, "status": "Exception in content = resource_files...", "message": exc_out}
def extension_mime_type(google_file_ext=None, format=None):
export_type = None
if google_file_ext is not None:
if google_file_ext == 'gdoc':
if format == 'docx':
export_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
elif format == 'epub':
export_type = 'application/epub+zip'
elif format == 'html':
export_type = 'text/html'
elif format == 'odt':
export_type = 'application/vnd.oasis.opendocument.text'
elif format == 'pdf':
export_type = 'application/pdf'
elif format == 'rtf':
export_type = 'application/rtf'
elif format == 'tex':
export_type = 'application/zip'
elif format == 'txt':
export_type = 'text/plain'
elif format == 'html.zip':
export_type = 'application/zip'
else:
raise Exception('Unknown format "{}"'.format(format))
elif google_file_ext == 'gsheet':
if format == 'csv':
export_type = 'text/csv'
elif format == 'html.zip':
export_type = 'application/zip'
elif format == 'ods':
export_type = 'application/x-vnd.oasis.opendocument.spreadsheet'
elif format == 'pdf':
export_type = 'application/pdf'
elif format == 'tsv':
export_type = 'text/tab-separated-values'
elif format == 'xlsx':
export_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
else:
raise Exception('Unknown format "{}"'.format(format))
elif google_file_ext == 'gslide':
if format == 'odp':
export_type = 'application/vnd.oasis.opendocument.presentation'
elif format == 'pdf':
export_type = 'application/pdf'
elif format == 'pptx':
export_type = 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
elif format == 'txt':
export_type = 'text/plain'
else:
raise Exception('Unknown format "{}"'.format(format))
else:
raise Exception('Unknown Google document extension "{}"'.format(google_file_ext))
return '.'+format, export_type
def get_email_labels(user, creds):
"""Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
service = build('gmail', 'v1', credentials=creds)
# Call the Gmail API
results = service.users().labels().list(userId=user).execute()
labels = results.get('labels', [])
if not labels:
print('No labels found.')
else:
print('Labels:')
for label in labels:
print(label['name'])
if email_id is not None:
pass
if drive_files_list == []:
print(json.dumps(drive_files_list))
else:
location = os.path.join('/home/dsie/Developer/sandbox/3ray/3rml/kbc_process/drive_documents/', job_id+'/pdf/')
os.makedirs(location)
location_html = os.path.join('/home/dsie/Developer/sandbox/3ray/3rml/kbc_process/drive_documents/', job_id+'/html/')
os.makedirs(location_html)
response_message = {
"job_id": job_id,
"status": "OK",
"processed_files": []
}
for index, item in enumerate(drive_files_list.get('files')):
try:
google_file_type = doc_types[item.get('mimeType')]
drive_document_id = item.get('id')
target_file_type = "pdf"
dl_response = download_drive_file(resource=get_resource(domain_wide_delegate=False), document_id=drive_document_id, google_file_type=google_file_type, target_type=target_file_type, target_location=location)
response_message["processed_files"].append(dl_response)
except KeyError as ke:
pass
print(json.dumps(response_message))
# print(download_drive_file(resource=get_resource(domain_wide_delegate=False)), google_file_type=google_file_type, target_type=target_file_type, target_location=location) | [
"{abhi@third-ray.com}"
] | {abhi@third-ray.com} |
aff1b4c074ab609ca6ddccae8c356a723e774856 | ed98f15f0daf3a9a0cb033bded3b97207b6a3382 | /pylonsprojectjp/apps/admin/__init__.py | 59a11c4220e220e1545a4c57f14f03913d4fde95 | [] | no_license | knzm/pylonsprojectjp_site | 56b4b3eb400f3588a97c1898759a53abca553635 | 4b2fd1875ab1c4e4d2e5a2ba946b6c462bc2d90e | refs/heads/master | 2021-01-19T11:17:30.521824 | 2014-01-24T15:00:30 | 2014-01-24T15:00:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 194 | py | # -*- coding: utf-8 -*-
from .utils import admin_config, ListColumn
__all__ = ['admin_config', 'ListColumn']
def includeme(config):
config.add_directive('add_admin', '.utils.add_admin')
| [
"nozom.kaneko@gmail.com"
] | nozom.kaneko@gmail.com |
ac840a5275bbbdffb5197eccb724645e65106c64 | b7e9057d7083759cf5193083b4864f6ca9dd9144 | /Longest_Increasing_Subsequence.py | 469379278526ef4b76f1ab1bd58b65c543a7cf66 | [] | no_license | vishalagrawalit/Competitive-Programming | 21a5c63de4fdbe8cbbfeb8b62d62af3c79972cad | b34faafd15f3e97050a8e2c39e3358e7a8ffdc5a | refs/heads/master | 2021-12-24T08:58:20.269152 | 2017-12-14T17:59:05 | 2017-12-14T17:59:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 609 | py | def search(arr,l,r,key):
while(r-l>1):
m = l+(r-l)//2
if (arr[m] >= key):
r = m
else:
l = m
return r
def sequence(arr):
if len(arr)==0:
return 0
tail = [0]*len(arr)
length = 1
tail[0] = arr[0]
for i in range(1,len(arr)):
if arr[i] < tail[0]:
tail[0] = arr[i]
elif arr[i] > tail[length - 1]:
tail[length]=arr[i]
length +=1
else:
tail[search(tail, -1, length-1, arr[i])] = arr[i]
return length
arr = [2,5,3,7,11,8,10,13,6,75]
print(sequence(arr))
| [
"vishvishu14@gmail.com"
] | vishvishu14@gmail.com |
a0598efb487953b92293d2f61626bf178d0b4e7d | c2df9e04adec78e789d1fbdb0711c45e5b9263a7 | /venv/Lib/site-packages/mpl_toolkits/axisartist/clip_path.py | d494365ef3c9347f3cdc5882e5efd8a907ad1b7f | [
"MIT",
"BSD-3-Clause"
] | permissive | AdarshSai/Final_Project | 433009a2f416e894ee3be85cd9317cb8e8df5516 | f966834ca72dd232102ed500ef47ef2b3bdbed5b | refs/heads/main | 2023-01-23T12:21:41.342074 | 2020-11-19T22:24:15 | 2020-11-19T22:24:15 | 308,898,012 | 0 | 1 | MIT | 2020-11-19T22:24:17 | 2020-10-31T14:19:58 | Python | UTF-8 | Python | false | false | 3,895 | py | import numpy as np
from math import degrees
from matplotlib import cbook
import math
def atan2(dy, dx):
if dx == 0 and dy == 0:
cbook._warn_external("dx and dy are 0")
return 0
else:
return math.atan2(dy, dx)
# FIXME : The current algorithm seems to return incorrect angle when the line
# ends at the boundary.
def clip(xlines, ylines, x0, clip="right", xdir=True, ydir=True):
clipped_xlines = []
clipped_ylines = []
_pos_angles = []
xsign = 1 if xdir else -1
ysign = 1 if ydir else -1
for x, y in zip(xlines, ylines):
if clip in ["up", "right"]:
b = (x < x0).astype("i")
db = b[1:] - b[:-1]
else:
b = (x > x0).astype("i")
db = b[1:] - b[:-1]
if b[0]:
ns = 0
else:
ns = -1
segx, segy = [], []
for (i,) in np.argwhere(db):
c = db[i]
if c == -1:
dx = (x0 - x[i])
dy = (y[i+1] - y[i]) * (dx / (x[i+1] - x[i]))
y0 = y[i] + dy
clipped_xlines.append(np.concatenate([segx, x[ns:i+1], [x0]]))
clipped_ylines.append(np.concatenate([segy, y[ns:i+1], [y0]]))
ns = -1
segx, segy = [], []
if dx == 0. and dy == 0:
dx = x[i+1] - x[i]
dy = y[i+1] - y[i]
a = degrees(atan2(ysign*dy, xsign*dx))
_pos_angles.append((x0, y0, a))
elif c == 1:
dx = (x0 - x[i])
dy = (y[i+1] - y[i]) * (dx / (x[i+1] - x[i]))
y0 = y[i] + dy
segx, segy = [x0], [y0]
ns = i+1
if dx == 0. and dy == 0:
dx = x[i+1] - x[i]
dy = y[i+1] - y[i]
a = degrees(atan2(ysign*dy, xsign*dx))
_pos_angles.append((x0, y0, a))
if ns != -1:
clipped_xlines.append(np.concatenate([segx, x[ns:]]))
clipped_ylines.append(np.concatenate([segy, y[ns:]]))
return clipped_xlines, clipped_ylines, _pos_angles
def clip_line_to_rect(xline, yline, bbox):
x0, y0, x1, y1 = bbox.extents
xdir = x1 > x0
ydir = y1 > y0
if x1 > x0:
lx1, ly1, c_right_ = clip([xline], [yline], x1,
clip="right", xdir=xdir, ydir=ydir)
lx2, ly2, c_left_ = clip(lx1, ly1, x0,
clip="left", xdir=xdir, ydir=ydir)
else:
lx1, ly1, c_right_ = clip([xline], [yline], x0,
clip="right", xdir=xdir, ydir=ydir)
lx2, ly2, c_left_ = clip(lx1, ly1, x1,
clip="left", xdir=xdir, ydir=ydir)
if y1 > y0:
ly3, lx3, c_top_ = clip(ly2, lx2, y1,
clip="right", xdir=ydir, ydir=xdir)
ly4, lx4, c_bottom_ = clip(ly3, lx3, y0,
clip="left", xdir=ydir, ydir=xdir)
else:
ly3, lx3, c_top_ = clip(ly2, lx2, y0,
clip="right", xdir=ydir, ydir=xdir)
ly4, lx4, c_bottom_ = clip(ly3, lx3, y1,
clip="left", xdir=ydir, ydir=xdir)
c_left = [((x, y), (a + 90) % 180 - 90) for x, y, a in c_left_
if bbox.containsy(y)]
c_bottom = [((x, y), (90 - a) % 180) for y, x, a in c_bottom_
if bbox.containsx(x)]
c_right = [((x, y), (a + 90) % 180 + 90) for x, y, a in c_right_
if bbox.containsy(y)]
c_top = [((x, y), (90 - a) % 180 + 180) for y, x, a in c_top_
if bbox.containsx(x)]
return list(zip(lx4, ly4)), [c_left, c_bottom, c_right, c_top]
| [
"adarshsaig@gmail.com"
] | adarshsaig@gmail.com |
d264afccd70fdf9c18c2efb1cf3cc64e43bb66bf | 8b56726a0e92d1d9cdb0516a7ba441927a6f934c | /mezzanine_slides/admin.py | c75871a2726c7d7202c494ec7cf7142dc3e42e02 | [
"BSD-2-Clause"
] | permissive | kklimonda/mezzanine-slides | bf360ece7a576af40c9eee9cc3e3c3a586920bb3 | 6eea964c3cea7e7b9cd2e4ea4df87e02904b2bf8 | refs/heads/master | 2021-01-18T13:18:52.982969 | 2014-03-31T12:45:37 | 2014-03-31T12:45:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,335 | py | from copy import deepcopy
from django.contrib import admin
from django.conf import settings
from mezzanine.pages.models import RichTextPage
from mezzanine.core.admin import TabularDynamicInlineAdmin
from mezzanine.pages.admin import PageAdmin
from mezzanine.forms.admin import FormAdmin
from mezzanine.galleries.admin import GalleryAdmin
if "cartridge.shop" in settings.INSTALLED_APPS:
from cartridge.shop.models import Category
from cartridge.shop.admin import CategoryAdmin
cartridge = True
else:
cartridge = False
from .models import Slide
"""
We do what we do here instead of just attaching it to PageAdmin because more
things then just pages inherit PageAdmin and if we just inject it into PageAdmin
I've had some very bad things happen. Thus I inject it into each page type
individually in a way that best suits it.
"""
class SlideInline(TabularDynamicInlineAdmin):
model = Slide
class RichTextPageAdmin(PageAdmin):
inlines = (SlideInline,)
admin.site.unregister(RichTextPage)
admin.site.register(RichTextPage, RichTextPageAdmin)
FormAdmin.inlines += (SlideInline,)
GalleryAdmin.inlines += (SlideInline,)
if cartridge:
class CategoryAdminInline(CategoryAdmin):
inlines = (SlideInline,)
admin.site.unregister(Category)
admin.site.register(Category, CategoryAdminInline)
| [
"isaac@bythewood.me"
] | isaac@bythewood.me |
4f639435ccaf5bbdd3a526cbc08cbd897e67d235 | 8968a2696cea58d7b04cb59c2525e89cf6f88a0a | /train_albert_en.py | 975c64c91313071f1de25f3be32ad0b6ee582502 | [] | no_license | Vottivott/swedsquad | a739c7aa938a5db381e2bda9e047c8db93390a90 | 5ed279f166d26b45228501012fbb8817d1c5ae11 | refs/heads/master | 2020-09-26T21:02:36.342548 | 2020-02-09T01:39:38 | 2020-02-09T01:39:38 | 226,342,459 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 955 | py | import run_squad_v2_3
args = """--model_type albert
--model_name_or_path albert-xxlarge-v2
--do_train
--do_eval
--version_2_with_negative
--train_file train-v2.0.json
--predict_file dev-v2.0.json
--learning_rate 3e-5
--num_train_epochs 2
--max_seq_length 384
--doc_stride 128
--output_dir albert_en
--per_gpu_eval_batch_size=3
--per_gpu_train_batch_size=3
--overwrite_cache
--save_steps=10000
""".split() # --eval_all_checkpoints
import os
import __main__ as main
print("Script: " + os.path.basename(main.__file__))
print(args)
results = run_squad_v2_3.main(args=args)
import json
import datetime
date = datetime.datetime.now().strftime("%I.%M.%S.%f %p on %B %d, %Y")
outname = "results " + os.path.basename(main.__file__)[:-3] + " " + date
with open(outname + ".json", "w") as out:
json.dump(results, out)
print(args)
print("Script: " + os.path.basename(main.__file__)) | [
"hannes.von.essen@gmail.com"
] | hannes.von.essen@gmail.com |
9c282bcc9395d5eda1043828a607d89c7e437cc1 | 2d196f23088be902bc7eba837c1bc7d238d3a4dc | /takmyo_app/migrations/0016_auto_20190701_1939.py | 6b08d6a79f663352837bb158cdd003025f4efcb8 | [] | no_license | SimJunSik/takmyo | 9015bb6359e55b2cc6a3bda6a3b60c3a74c5293e | 719c2953e46be0fd35d18ed61137e54510854234 | refs/heads/master | 2020-05-31T16:07:54.001559 | 2019-07-10T13:22:27 | 2019-07-10T13:22:27 | 190,373,741 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,519 | py | # Generated by Django 2.1.4 on 2019-07-01 19:39
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('takmyo_app', '0015_auto_20190630_2023'),
]
operations = [
migrations.AddField(
model_name='catsitterreview',
name='catee',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='catee_reviews', to='takmyo_app.Catee'),
),
migrations.AlterField(
model_name='cateetocatsitterform',
name='place',
field=models.CharField(choices=[('visit', 'Visit'), ('consignment', 'Consignment')], default='', max_length=20),
),
migrations.AlterField(
model_name='cateetocatsitterform',
name='state',
field=models.CharField(choices=[('unrecognized', 'Unrecognized'), ('progress', 'Progress'), ('recognized', 'Recognized')], default='', max_length=50),
),
migrations.AlterField(
model_name='catsitter',
name='available_day',
field=models.CharField(choices=[('both', 'Both'), ('weekday', 'Weekday'), ('weekend', 'Weekend')], default='', max_length=10),
),
migrations.AlterField(
model_name='catsitter',
name='available_place',
field=models.CharField(choices=[('visit', 'Visit'), ('both', 'Both'), ('consignment', 'Consignment')], default='', max_length=20),
),
migrations.AlterField(
model_name='catsitter',
name='available_weekday_time',
field=models.CharField(choices=[('am', 'Am'), ('both', 'Both'), ('pm', 'Pm')], default='', max_length=10),
),
migrations.AlterField(
model_name='catsitter',
name='available_weekend_time',
field=models.CharField(choices=[('am', 'Am'), ('both', 'Both'), ('pm', 'Pm')], default='', max_length=10),
),
migrations.AlterField(
model_name='catsitterreview',
name='catsitter',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='catsitter_reviews', to='takmyo_app.Catsitter'),
),
migrations.AlterField(
model_name='notification',
name='category',
field=models.CharField(choices=[('form', 'Form'), ('review', 'Review')], max_length=30, null=True),
),
]
| [
"wnstlr24@naver.com"
] | wnstlr24@naver.com |
95faa95eeff801f7dab139c5085f5900338d891f | 41d4f53b7f23639c1e2bbf75f06b77b544b5e8ca | /docs/fragments/feature-engineering-guide-second-feature.py | e70345c620ad6fb8637ac8f6c9d859035d9a1e71 | [
"MIT"
] | permissive | fagan2888/ballet | d010ad5e8158417cd75b73fe67c758e6423cbb35 | 38b156e04e5ae1497e943a8c954606c9a9b5dd83 | refs/heads/master | 2023-03-05T13:41:32.953107 | 2021-02-02T16:58:37 | 2021-02-02T16:58:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 240 | py | from ballet import Feature
from ballet.eng.sklearn import SimpleImputer
input = ["Lot Frontage"]
transformer = SimpleImputer(strategy="mean")
name = "Imputed Lot Frontage"
feature = Feature(input=input, transformer=transformer, name=name)
| [
"micahjsmith@gmail.com"
] | micahjsmith@gmail.com |
5bee3b9aec06a6a7c4e1632997945279f6255fb2 | 68dee0c48a0527d56e74c2cd9bd35e73f360d233 | /hydrus/client/gui/search/ClientGUISearch.py | eb99331cd64aa8594cd0709a12efafe1790405b2 | [
"WTFPL"
] | permissive | pokeball99/hydrus | a9a10c9c7dfb751a308de22ac4a3000f71a27454 | e939c11b7ad5071b88b9cc310cda9fb9f2dc68e4 | refs/heads/master | 2022-10-06T23:43:39.656510 | 2022-09-17T20:56:42 | 2022-09-17T20:56:42 | 46,509,660 | 0 | 0 | null | 2015-11-19T17:44:48 | 2015-11-19T17:44:46 | null | UTF-8 | Python | false | false | 44,007 | py | import os
import typing
from qtpy import QtCore as QC
from qtpy import QtWidgets as QW
from hydrus.core import HydrusConstants as HC
from hydrus.core import HydrusExceptions
from hydrus.core import HydrusGlobals as HG
from hydrus.client import ClientConstants as CC
from hydrus.client import ClientSearch
from hydrus.client.gui import ClientGUICore as CGC
from hydrus.client.gui import ClientGUIFunctions
from hydrus.client.gui import ClientGUIMenus
from hydrus.client.gui import ClientGUIScrolledPanels
from hydrus.client.gui import ClientGUIShortcuts
from hydrus.client.gui import QtPorting as QP
from hydrus.client.gui.search import ClientGUIPredicatesMultiple
from hydrus.client.gui.search import ClientGUIPredicatesSingle
from hydrus.client.gui.search import ClientGUIPredicatesOR
from hydrus.client.gui.widgets import ClientGUICommon
EDIT_PRED_TYPES = {
ClientSearch.PREDICATE_TYPE_SYSTEM_AGE,
ClientSearch.PREDICATE_TYPE_SYSTEM_LAST_VIEWED_TIME,
ClientSearch.PREDICATE_TYPE_SYSTEM_MODIFIED_TIME,
ClientSearch.PREDICATE_TYPE_SYSTEM_HEIGHT,
ClientSearch.PREDICATE_TYPE_SYSTEM_WIDTH,
ClientSearch.PREDICATE_TYPE_SYSTEM_RATIO,
ClientSearch.PREDICATE_TYPE_SYSTEM_NUM_PIXELS,
ClientSearch.PREDICATE_TYPE_SYSTEM_DURATION,
ClientSearch.PREDICATE_TYPE_SYSTEM_FRAMERATE,
ClientSearch.PREDICATE_TYPE_SYSTEM_NUM_FRAMES,
ClientSearch.PREDICATE_TYPE_SYSTEM_FILE_SERVICE,
ClientSearch.PREDICATE_TYPE_SYSTEM_KNOWN_URLS,
ClientSearch.PREDICATE_TYPE_SYSTEM_HASH,
ClientSearch.PREDICATE_TYPE_SYSTEM_LIMIT,
ClientSearch.PREDICATE_TYPE_SYSTEM_MIME,
ClientSearch.PREDICATE_TYPE_SYSTEM_RATING,
ClientSearch.PREDICATE_TYPE_SYSTEM_NUM_TAGS,
ClientSearch.PREDICATE_TYPE_SYSTEM_NUM_NOTES,
ClientSearch.PREDICATE_TYPE_SYSTEM_HAS_NOTE_NAME,
ClientSearch.PREDICATE_TYPE_SYSTEM_NUM_WORDS,
ClientSearch.PREDICATE_TYPE_SYSTEM_SIMILAR_TO,
ClientSearch.PREDICATE_TYPE_SYSTEM_SIZE,
ClientSearch.PREDICATE_TYPE_SYSTEM_TAG_AS_NUMBER,
ClientSearch.PREDICATE_TYPE_SYSTEM_FILE_RELATIONSHIPS_COUNT,
ClientSearch.PREDICATE_TYPE_SYSTEM_FILE_VIEWING_STATS,
ClientSearch.PREDICATE_TYPE_OR_CONTAINER
}
FLESH_OUT_SYSTEM_PRED_TYPES = {
ClientSearch.PREDICATE_TYPE_SYSTEM_NUM_TAGS,
ClientSearch.PREDICATE_TYPE_SYSTEM_LIMIT,
ClientSearch.PREDICATE_TYPE_SYSTEM_SIZE,
ClientSearch.PREDICATE_TYPE_SYSTEM_DIMENSIONS,
ClientSearch.PREDICATE_TYPE_SYSTEM_AGE,
ClientSearch.PREDICATE_TYPE_SYSTEM_MODIFIED_TIME,
ClientSearch.PREDICATE_TYPE_SYSTEM_KNOWN_URLS,
ClientSearch.PREDICATE_TYPE_SYSTEM_HASH,
ClientSearch.PREDICATE_TYPE_SYSTEM_DURATION,
ClientSearch.PREDICATE_TYPE_SYSTEM_HAS_AUDIO,
ClientSearch.PREDICATE_TYPE_SYSTEM_HAS_ICC_PROFILE,
ClientSearch.PREDICATE_TYPE_SYSTEM_NUM_WORDS,
ClientSearch.PREDICATE_TYPE_SYSTEM_MIME,
ClientSearch.PREDICATE_TYPE_SYSTEM_RATING,
ClientSearch.PREDICATE_TYPE_SYSTEM_SIMILAR_TO,
ClientSearch.PREDICATE_TYPE_SYSTEM_FILE_SERVICE,
ClientSearch.PREDICATE_TYPE_SYSTEM_TAG_AS_NUMBER,
ClientSearch.PREDICATE_TYPE_SYSTEM_FILE_RELATIONSHIPS,
ClientSearch.PREDICATE_TYPE_SYSTEM_NOTES,
ClientSearch.PREDICATE_TYPE_SYSTEM_TIME,
ClientSearch.PREDICATE_TYPE_SYSTEM_FILE_VIEWING_STATS
}
def EditPredicates( widget: QW.QWidget, predicates: typing.Collection[ ClientSearch.Predicate ] ) -> typing.List[ ClientSearch.Predicate ]:
( editable_predicates, non_editable_predicates ) = GetEditablePredicates( predicates )
window = widget.window()
from hydrus.client.gui import ClientGUITopLevelWindowsPanels
if len( editable_predicates ) == 1 and editable_predicates[0].IsInvertible():
result = list( non_editable_predicates )
result.append( editable_predicates[0].GetInverseCopy() )
return result
elif len( editable_predicates ) > 0:
title = 'edit predicates'
if len( editable_predicates ) == 1:
if list( editable_predicates )[0].GetType() == ClientSearch.PREDICATE_TYPE_OR_CONTAINER:
title = 'edit OR predicate'
with ClientGUITopLevelWindowsPanels.DialogEdit( window, title ) as dlg:
panel = EditPredicatesPanel( dlg, predicates )
dlg.SetPanel( panel )
if dlg.exec() == QW.QDialog.Accepted:
edited_predicates = panel.GetValue()
HG.client_controller.new_options.PushRecentPredicates( edited_predicates )
result = list( non_editable_predicates )
result.extend( edited_predicates )
return result
raise HydrusExceptions.CancelledException()
def FilterAndConvertLabelPredicates( predicates: typing.Collection[ ClientSearch.Predicate ] ) -> typing.List[ ClientSearch.Predicate ]:
good_predicates = []
for predicate in predicates:
predicate = predicate.GetCountlessCopy()
predicate_type = predicate.GetType()
if predicate_type in ( ClientSearch.PREDICATE_TYPE_LABEL, ClientSearch.PREDICATE_TYPE_PARENT ):
continue
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_UNTAGGED:
predicate = ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_NUM_TAGS, ( None, '=', 0 ) )
good_predicates.append( predicate )
return good_predicates
def FleshOutPredicates( widget: QW.QWidget, predicates: typing.Collection[ ClientSearch.Predicate ] ) -> typing.List[ ClientSearch.Predicate ]:
window = None
predicates = FilterAndConvertLabelPredicates( predicates )
good_predicates = []
for predicate in predicates:
value = predicate.GetValue()
predicate_type = predicate.GetType()
if value is None and predicate_type in FLESH_OUT_SYSTEM_PRED_TYPES:
if window is None:
if QP.isValid( widget ):
window = widget.window()
from hydrus.client.gui import ClientGUITopLevelWindowsPanels
with ClientGUITopLevelWindowsPanels.DialogEdit( window, 'input predicate', hide_buttons = True ) as dlg:
panel = FleshOutPredicatePanel( dlg, predicate )
dlg.SetPanel( panel )
if dlg.exec() == QW.QDialog.Accepted:
preds = panel.GetValue()
HG.client_controller.new_options.PushRecentPredicates( preds )
good_predicates.extend( preds )
else:
good_predicates.append( predicate )
return good_predicates
def GetEditablePredicates( predicates: typing.Collection[ ClientSearch.Predicate ] ):
editable_predicates = [ predicate for predicate in predicates if predicate.GetType() in EDIT_PRED_TYPES or predicate.IsInvertible() ]
non_editable_predicates = [ predicate for predicate in predicates if predicate not in editable_predicates ]
return ( editable_predicates, non_editable_predicates )
class EditPredicatesPanel( ClientGUIScrolledPanels.EditPanel ):
def __init__( self, parent, predicates: typing.Collection[ ClientSearch.Predicate ] ):
ClientGUIScrolledPanels.EditPanel.__init__( self, parent )
predicates = list( predicates )
predicates.sort( key = lambda p: p.ToString( with_count = False ) )
self._uneditable_predicates = []
self._invertible_pred_buttons = []
self._editable_pred_panels = []
rating_preds = []
# I hate this pred comparison stuff, but let's hang in there until we split this stuff up by type mate
# then we can just have a dict type->panel_class lookup or whatever
# also it would be nice to have proper rating editing here, think about it
AGE_DELTA_PRED = ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_AGE, ( '>', 'delta', ( 2000, 1, 1, 1 ) ) )
LAST_VIEWED_DELTA_PRED = ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_LAST_VIEWED_TIME, ( '>', 'delta', ( 2000, 1, 1, 1 ) ) )
MODIFIED_DELTA_PRED = ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_MODIFIED_TIME, ( '>', 'delta', ( 2000, 1, 1, 1 ) ) )
KNOWN_URL_EXACT = ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_KNOWN_URLS, ( True, 'exact_match', '', '' ) )
KNOWN_URL_DOMAIN = ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_KNOWN_URLS, ( True, 'domain', '', '' ) )
KNOWN_URL_REGEX = ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_KNOWN_URLS, ( True, 'regex', '', '' ) )
FILE_VIEWS_PRED = ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_FILE_VIEWING_STATS, ( 'views', ( 'media', ), '>', 0 ) )
for predicate in predicates:
predicate_type = predicate.GetType()
if predicate_type == ClientSearch.PREDICATE_TYPE_OR_CONTAINER:
self._editable_pred_panels.append( ClientGUIPredicatesOR.ORPredicateControl( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_AGE:
if predicate.IsUIEditable( AGE_DELTA_PRED ):
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemAgeDelta( self, predicate ) )
else:
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemAgeDate( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_LAST_VIEWED_TIME:
if predicate.IsUIEditable( LAST_VIEWED_DELTA_PRED ):
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemLastViewedDelta( self, predicate ) )
else:
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemLastViewedDate( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_MODIFIED_TIME:
if predicate.IsUIEditable( MODIFIED_DELTA_PRED ):
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemModifiedDelta( self, predicate ) )
else:
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemModifiedDate( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_HEIGHT:
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemHeight( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_WIDTH:
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemWidth( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_RATIO:
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemRatio( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_NUM_PIXELS:
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemNumPixels( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_DURATION:
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemDuration( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_FRAMERATE:
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemFramerate( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_NUM_FRAMES:
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemNumFrames( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_FILE_SERVICE:
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemFileService( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_KNOWN_URLS:
if predicate.IsUIEditable( KNOWN_URL_EXACT ):
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemKnownURLsExactURL( self, predicate ) )
elif predicate.IsUIEditable( KNOWN_URL_DOMAIN ):
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemKnownURLsDomain( self, predicate ) )
elif predicate.IsUIEditable( KNOWN_URL_REGEX ):
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemKnownURLsRegex( self, predicate ) )
else:
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemKnownURLsURLClass( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_HASH:
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemHash( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_LIMIT:
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemLimit( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_MIME:
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemMime( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_NUM_TAGS:
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemNumTags( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_NUM_NOTES:
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemNumNotes( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_HAS_NOTE_NAME:
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemHasNoteName( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_NUM_WORDS:
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemNumWords( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_SIMILAR_TO:
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemSimilarTo( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_SIZE:
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemSize( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_TAG_AS_NUMBER:
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemTagAsNumber( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_FILE_RELATIONSHIPS_COUNT:
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemDuplicateRelationships( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_FILE_VIEWING_STATS:
if predicate.IsUIEditable( FILE_VIEWS_PRED ):
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemFileViewingStatsViews( self, predicate ) )
else:
self._editable_pred_panels.append( ClientGUIPredicatesSingle.PanelPredicateSystemFileViewingStatsViewtime( self, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_RATING:
rating_preds.append( predicate )
elif predicate.IsInvertible():
self._invertible_pred_buttons.append( ClientGUIPredicatesSingle.InvertiblePredicateButton( self, predicate ) )
else:
self._uneditable_predicates.append( predicate )
if len( rating_preds ) > 0:
self._editable_pred_panels.append( ClientGUIPredicatesMultiple.PanelPredicateSystemRating( self, rating_preds ) )
vbox = QP.VBoxLayout()
for button in self._invertible_pred_buttons:
QP.AddToLayout( vbox, button, CC.FLAGS_EXPAND_PERPENDICULAR )
for panel in self._editable_pred_panels:
if isinstance( panel, ClientGUIPredicatesOR.ORPredicateControl ):
flags = CC.FLAGS_EXPAND_BOTH_WAYS
else:
flags = CC.FLAGS_EXPAND_PERPENDICULAR
QP.AddToLayout( vbox, panel, flags )
self.widget().setLayout( vbox )
def CheckValid( self ):
for panel in self._editable_pred_panels:
panel.CheckValid()
def GetValue( self ):
return_predicates = list( self._uneditable_predicates )
for button in self._invertible_pred_buttons:
return_predicates.append( button.GetPredicate() )
for panel in self._editable_pred_panels:
return_predicates.extend( panel.GetPredicates() )
return return_predicates
class FleshOutPredicatePanel( ClientGUIScrolledPanels.EditPanel ):
def __init__( self, parent, predicate: ClientSearch.Predicate ):
ClientGUIScrolledPanels.EditPanel.__init__( self, parent )
predicate_type = predicate.GetType()
self._predicates = []
label = None
page_name = 'page'
pages = []
recent_predicate_types = [ predicate_type ]
static_pred_buttons = []
editable_pred_panels = []
if predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_AGE:
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_AGE, ( '<', 'delta', ( 0, 0, 1, 0 ) ) ), ) ) )
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_AGE, ( '<', 'delta', ( 0, 0, 7, 0 ) ) ), ) ) )
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_AGE, ( '<', 'delta', ( 0, 1, 0, 0 ) ) ), ) ) )
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemAgeDelta, predicate ) )
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemAgeDate, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_MODIFIED_TIME:
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemModifiedDelta, predicate ) )
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemModifiedDate, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_TIME:
recent_predicate_types = [ ClientSearch.PREDICATE_TYPE_SYSTEM_AGE ]
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_AGE, ( '<', 'delta', ( 0, 0, 1, 0 ) ) ), ) ) )
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_AGE, ( '<', 'delta', ( 0, 0, 7, 0 ) ) ), ) ) )
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_AGE, ( '<', 'delta', ( 0, 1, 0, 0 ) ) ), ) ) )
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemAgeDelta, predicate ) )
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemAgeDate, predicate ) )
pages.append( ( 'import', recent_predicate_types, static_pred_buttons, editable_pred_panels ) )
recent_predicate_types = [ ClientSearch.PREDICATE_TYPE_SYSTEM_MODIFIED_TIME ]
static_pred_buttons = []
editable_pred_panels = []
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemModifiedDelta, predicate ) )
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemModifiedDate, predicate ) )
pages.append( ( 'modified', recent_predicate_types, static_pred_buttons, editable_pred_panels ) )
recent_predicate_types = [ ClientSearch.PREDICATE_TYPE_SYSTEM_LAST_VIEWED_TIME ]
static_pred_buttons = []
editable_pred_panels = []
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemLastViewedDelta, predicate ) )
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemLastViewedDate, predicate ) )
page_name = 'last viewed'
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_DIMENSIONS:
recent_predicate_types = [ ClientSearch.PREDICATE_TYPE_SYSTEM_HEIGHT, ClientSearch.PREDICATE_TYPE_SYSTEM_WIDTH, ClientSearch.PREDICATE_TYPE_SYSTEM_RATIO, ClientSearch.PREDICATE_TYPE_SYSTEM_NUM_PIXELS ]
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_RATIO, ( '=', 16, 9 ) ), ) ) )
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_RATIO, ( '=', 9, 16 ) ), ) ) )
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_RATIO, ( '=', 4, 3 ) ), ) ) )
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_RATIO, ( '=', 1, 1 ) ), ) ) )
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_WIDTH, ( '=', 1920 ) ), ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_HEIGHT, ( '=', 1080 ) ) ), forced_label = '1080p' ) )
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_WIDTH, ( '=', 1280 ) ), ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_HEIGHT, ( '=', 720 ) ) ), forced_label = '720p' ) )
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_WIDTH, ( '=', 3840 ) ), ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_HEIGHT, ( '=', 2160 ) ) ), forced_label = '4k' ) )
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemHeight, predicate ) )
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemWidth, predicate ) )
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemRatio, predicate ) )
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemNumPixels, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_DURATION:
recent_predicate_types = [ ClientSearch.PREDICATE_TYPE_SYSTEM_DURATION, ClientSearch.PREDICATE_TYPE_SYSTEM_FRAMERATE, ClientSearch.PREDICATE_TYPE_SYSTEM_NUM_FRAMES ]
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_DURATION, ( '>', 0 ) ), ) ) )
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_DURATION, ( '=', 0 ) ), ) ) )
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_FRAMERATE, ( '=', 30 ) ), ) ) )
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_FRAMERATE, ( '=', 60 ) ), ) ) )
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemDuration, predicate ) )
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemFramerate, predicate ) )
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemNumFrames, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_FILE_SERVICE:
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemFileService, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_KNOWN_URLS:
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemKnownURLsExactURL, predicate ) )
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemKnownURLsDomain, predicate ) )
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemKnownURLsRegex, predicate ) )
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemKnownURLsURLClass, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_HAS_AUDIO:
recent_predicate_types = []
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_HAS_AUDIO, True ), ) ) )
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_HAS_AUDIO, False ), ) ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_HAS_ICC_PROFILE:
recent_predicate_types = []
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_HAS_ICC_PROFILE, True ), ) ) )
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_HAS_ICC_PROFILE, False ), ) ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_HASH:
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemHash, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_LIMIT:
label = 'system:limit clips a large search result down to the given number of files. It is very useful for processing in smaller batches.'
label += os.linesep * 2
label += 'For all the simpler sorts (filesize, duration, etc...), it will select the n largest/smallest in the result set appropriate for that sort. For complicated sorts like tags, it will sample randomly.'
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_LIMIT, 64 ), ) ) )
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_LIMIT, 256 ), ) ) )
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_LIMIT, 1024 ), ) ) )
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemLimit, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_MIME:
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemMime, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_NUM_TAGS:
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_NUM_TAGS, ( None, '>', 0 ) ), ) ) )
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_NUM_TAGS, ( None, '=', 0 ) ), ) ) )
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemNumTags, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_NOTES:
recent_predicate_types = [ ClientSearch.PREDICATE_TYPE_SYSTEM_NUM_NOTES, ClientSearch.PREDICATE_TYPE_SYSTEM_HAS_NOTE_NAME ]
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_NUM_NOTES, ( '>', 0 ) ), ) ) )
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_NUM_NOTES, ( '=', 0 ) ), ) ) )
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemNumNotes, predicate ) )
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemHasNoteName, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_NUM_WORDS:
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemNumWords, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_RATING:
services_manager = HG.client_controller.services_manager
ratings_services = services_manager.GetServices( ( HC.LOCAL_RATING_LIKE, HC.LOCAL_RATING_NUMERICAL ) )
if len( ratings_services ) > 0:
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesMultiple.PanelPredicateSystemRating, ( predicate, ) ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_SIMILAR_TO:
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemSimilarTo, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_SIZE:
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemSize, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_TAG_AS_NUMBER:
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemTagAsNumber, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_FILE_RELATIONSHIPS:
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_FILE_RELATIONSHIPS_KING, False ), ) ) )
static_pred_buttons.append( ClientGUIPredicatesSingle.StaticSystemPredicateButton( self, self, ( ClientSearch.Predicate( ClientSearch.PREDICATE_TYPE_SYSTEM_FILE_RELATIONSHIPS_KING, True ), ) ) )
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemDuplicateRelationships, predicate ) )
elif predicate_type == ClientSearch.PREDICATE_TYPE_SYSTEM_FILE_VIEWING_STATS:
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemFileViewingStatsViews, predicate ) )
editable_pred_panels.append( self._PredOKPanel( self, ClientGUIPredicatesSingle.PanelPredicateSystemFileViewingStatsViewtime, predicate ) )
pages.append( ( page_name, recent_predicate_types, static_pred_buttons, editable_pred_panels ) )
vbox = QP.VBoxLayout()
if label is not None:
st = ClientGUICommon.BetterStaticText( self, label = label )
st.setWordWrap( True )
QP.AddToLayout( vbox, st, CC.FLAGS_EXPAND_PERPENDICULAR )
page_parent = self
if len( pages ) > 1:
self._notebook = ClientGUICommon.BetterNotebook( self )
QP.AddToLayout( vbox, self._notebook, CC.FLAGS_EXPAND_BOTH_WAYS )
page_parent = self._notebook
for ( i, ( page_name, recent_predicate_types, static_pred_buttons, editable_pred_panels ) ) in enumerate( pages ):
page_panel = QW.QWidget( page_parent )
page_vbox = QP.VBoxLayout()
recent_predicates = []
if len( recent_predicate_types ) > 0:
recent_predicates = HG.client_controller.new_options.GetRecentPredicates( recent_predicate_types )
if len( recent_predicates ) > 0:
recent_predicates_box = ClientGUICommon.StaticBox( page_panel, 'recent' )
for recent_predicate in recent_predicates:
button = ClientGUIPredicatesSingle.StaticSystemPredicateButton( recent_predicates_box, self, ( recent_predicate, ) )
recent_predicates_box.Add( button, CC.FLAGS_EXPAND_PERPENDICULAR )
QP.AddToLayout( page_vbox, recent_predicates_box, CC.FLAGS_EXPAND_PERPENDICULAR )
for button in static_pred_buttons:
QP.AddToLayout( page_vbox, button, CC.FLAGS_EXPAND_PERPENDICULAR )
for panel in editable_pred_panels:
QP.AddToLayout( page_vbox, panel, CC.FLAGS_EXPAND_PERPENDICULAR )
page_panel.setLayout( page_vbox )
if i == 0 and len( static_pred_buttons ) > 0 and len( editable_pred_panels ) == 0:
ClientGUIFunctions.SetFocusLater( static_pred_buttons[0] )
if len( pages ) > 1:
self._notebook.addTab( page_panel, page_name )
else:
QP.AddToLayout( vbox, page_panel, CC.FLAGS_EXPAND_BOTH_WAYS )
self.widget().setLayout( vbox )
def GetValue( self ):
return self._predicates
def SubPanelOK( self, predicates ):
self._predicates = predicates
self.parentWidget().DoOK()
class _PredOKPanel( QW.QWidget ):
def __init__( self, parent, predicate_panel_class, predicate ):
QW.QWidget.__init__( self, parent )
self._defaults_button = ClientGUICommon.BetterBitmapButton( self, CC.global_pixmaps().star, self._DefaultsMenu )
self._defaults_button.setToolTip( 'Set a new default.' )
self._predicate_panel = predicate_panel_class( self, predicate )
self._parent = parent
self._ok = QW.QPushButton( 'ok', self )
self._ok.clicked.connect( self._DoOK )
self._ok.setObjectName( 'HydrusAccept' )
hbox = QP.HBoxLayout()
QP.AddToLayout( hbox, self._defaults_button, CC.FLAGS_CENTER_PERPENDICULAR )
QP.AddToLayout( hbox, self._predicate_panel, CC.FLAGS_EXPAND_SIZER_BOTH_WAYS )
QP.AddToLayout( hbox, self._ok, CC.FLAGS_CENTER_PERPENDICULAR )
self.setLayout( hbox )
ClientGUIFunctions.SetFocusLater( self._ok )
def _DefaultsMenu( self ):
menu = QW.QMenu()
ClientGUIMenus.AppendMenuItem( menu, 'set this as new default', 'Set the current value of this as the new default for this predicate.', self._predicate_panel.SaveCustomDefault )
if self._predicate_panel.UsesCustomDefault():
ClientGUIMenus.AppendSeparator( menu )
ClientGUIMenus.AppendMenuItem( menu, 'reset to original default', 'Clear the custom default value for this predicate.', self._predicate_panel.ClearCustomDefault )
CGC.core().PopupMenu( self, menu )
def _DoOK( self ):
try:
self._predicate_panel.CheckValid()
except Exception as e:
QW.QMessageBox.warning( self, 'Predicate not valid!', str( e ) )
return
predicates = self._predicate_panel.GetPredicates()
self._parent.SubPanelOK( predicates )
def keyPressEvent( self, event ):
( modifier, key ) = ClientGUIShortcuts.ConvertKeyEventToSimpleTuple( event )
if key in ( QC.Qt.Key_Enter, QC.Qt.Key_Return ):
self._DoOK()
else:
event.ignore()
class TagContextButton( ClientGUICommon.BetterButton ):
valueChanged = QC.Signal( ClientSearch.TagContext )
def __init__( self, parent: QW.QWidget, tag_context: ClientSearch.TagContext, use_short_label = False ):
self._tag_context = ClientSearch.TagContext()
self._use_short_label = use_short_label
ClientGUICommon.BetterButton.__init__( self, parent, 'initialising', self._Edit )
self.SetValue( tag_context )
def _Edit( self ):
services_manager = HG.client_controller.services_manager
service_types_in_order = [ HC.LOCAL_TAG, HC.TAG_REPOSITORY, HC.COMBINED_TAG ]
services = services_manager.GetServices( service_types_in_order )
menu = QW.QMenu()
for service in services:
tag_context = ClientSearch.TagContext( service_key = service.GetServiceKey() )
ClientGUIMenus.AppendMenuItem( menu, service.GetName(), 'Change the current tag domain to {}.'.format( service.GetName() ), self.SetValue, tag_context )
CGC.core().PopupMenu( self, menu )
def GetValue( self ) -> ClientSearch.TagContext:
return self._tag_context
def SetValue( self, tag_context: ClientSearch.TagContext ):
original_tag_context = self._tag_context
tag_context = tag_context.Duplicate()
tag_context.FixMissingServices( HG.client_controller.services_manager.FilterValidServiceKeys )
self._tag_context = tag_context
label = self._tag_context.ToString( HG.client_controller.services_manager.GetName )
if self._use_short_label:
self.setText( 'tags' )
else:
self.setText( label )
self.setToolTip( label )
if self._tag_context != original_tag_context:
self.valueChanged.emit( self._tag_context )
| [
"hydrus.admin@gmail.com"
] | hydrus.admin@gmail.com |
a8afe8fe90cb44885e1a8de0926880ca20e883b6 | 36957a9ce540846d08f151b6a2c2d582cff1df47 | /VR/Python/Python36/Lib/site-packages/django/contrib/messages/storage/fallback.py | d1e59e7381a074e84dc617160fe1188be756bcf0 | [] | no_license | aqp1234/gitVR | 60fc952307ef413e396d31e0d136faffe087ed2b | e70bd82c451943c2966b8ad1bee620a0ee1080d2 | refs/heads/master | 2022-12-29T15:30:12.540947 | 2020-10-07T15:26:32 | 2020-10-07T15:26:32 | 290,163,043 | 0 | 1 | null | 2020-08-25T09:15:40 | 2020-08-25T08:47:36 | C# | UTF-8 | Python | false | false | 129 | py | version https://git-lfs.github.com/spec/v1
oid sha256:21bcb2660f1c4d4fb5f5979183a2e774b7d12b44a87af0f0a8ab6bab3855a7a7
size 2095
| [
"aqp1234@naver.com"
] | aqp1234@naver.com |
511ea27f7502976ed688dd2cdd273ad0cfd53fbe | e815fd9fbc703ce43d94fba6e53c86b898e32977 | /llia/synths/controlmixer/controlmixer_proxy.py | 33161f517185689a07627bddbc820d2b9f087313 | [] | no_license | kaos/Llia | 0cdedc13d84ce86034287fba00ec0b169fbd87b1 | b2aaa163c4ada3b446a7c3701e3f05c0f8406d6e | refs/heads/master | 2020-12-28T19:23:48.480608 | 2017-03-27T05:51:14 | 2017-03-27T05:51:14 | 64,940,263 | 0 | 0 | null | 2016-08-04T14:13:13 | 2016-08-04T14:13:13 | null | UTF-8 | Python | false | false | 1,651 | py | # llia.synths.controlmixer.ghost_proxy
from __future__ import print_function
import llia.constants
from llia.gui.pallet import default_pallet, Pallet
from llia.synth_proxy import SynthSpecs, SynthProxy
from llia.synths.controlmixer.controlmixer_data import program_bank, pp
specs = SynthSpecs("ControlMixer")
class ControlmixerProxy(SynthProxy):
def __init__(self, app):
super(ControlmixerProxy, self).__init__(app, specs, program_bank)
self.app = app
def create_subeditors(self):
pass
gui = self.app.config["gui"].upper()
if gui == "TK":
from llia.synths.controlmixer.tk.editor import create_editor
appwin = self.app.main_window()
parent_editor = appwin[self.sid]
create_editor(parent_editor)
controlmixer_pallet = Pallet(default_pallet)
controlmixer_pallet["SLIDER-TROUGH"] = "#432703"
controlmixer_pallet["SLIDER-OUTLINE"] = "#42033E"
specs["constructor"] = ControlmixerProxy
specs["description"] = "Combines up to 4 control signals"
specs["keymodes"] = ("EFX", )
specs["pretty-printer"] = pp
#specs["program-generator"] =
specs["is-efx"] = True
specs["is-controller"] = True
specs["help"] = "Controlmixer"
specs["pallet"] = controlmixer_pallet
specs["control-input-buses"] = [["inbusA","null_sink"],
["inbusB","null_sink"],
["inbusC","null_sink"],
["inbusD","null_sink"]]
specs["control-output-buses"] = [["outbus","null_source"]]
print("\t%s" % specs["format"])
llia.constants.CONTROLLER_SYNTH_TYPES.append(specs["format"])
| [
"plewto@gmail.com"
] | plewto@gmail.com |
e2f183fd355accbc9b143c35bd7aefc489038f85 | 8ee6d008fdaea9bb738ab4d6cb4971789934c03e | /case/zlywtest.py | 09debf978965b3567bea364443f721f5dcc3c096 | [] | no_license | Pactortester/QDS_old_company | 32d3499d955e127a69c6e9e15ec3f3661ca9cef1 | 0a3d0688cd6ec0c1e6fedd62f94867f97045deb8 | refs/heads/master | 2020-03-27T17:47:53.042670 | 2018-09-07T02:55:42 | 2018-09-07T02:55:42 | 146,869,723 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 76,486 | py |
# coding=utf-8
import time
import logging
from selenium.webdriver import ActionChains
from utils.mytestcase import MyTestCase
from utils.logincookie import dengLuPage
from utils.screenshort import get_screenshort
class ZlYwTest(MyTestCase):
"""专利业务测试集"""
def test_zljs(self):
"""专利查新检索(报告)测试"""
dl = dengLuPage(self.driver)
dl.dengLu()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
ActionChains(self.driver).release()
self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(1) > dd > a").click()
time.sleep(3)
# 获取打开的多个窗口句柄
windows = self.driver.window_handles
# 切换到当前最新打开的窗口
self.driver.switch_to.window(windows[-1])
self.assertIn("专利查新检索(报告)_权大师",self.driver.title)
print(self.driver.title)
for a in self.driver.find_elements_by_css_selector("#total-price"):
print("费用总计:"+a.text)
aa=a.text
self.driver.find_element_by_css_selector(
"body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
get_screenshort(self.driver, "test_zljs.png")
for i in self.driver.find_elements_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
print("总价:" + i.text)
ii = i.text
self.assertIn(aa, ii)
print("价格一致")
self.driver.find_element_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
for o in self.driver.find_elements_by_class_name("payable"):
print("订单提交成功,应付金额:" + o.text)
oo = o.text
self.assertIn(oo, ii)
print("测试通过")
self.driver.find_element_by_css_selector("#alisubmit").click()
# com-navbar > div > div.drop-nav > div > ul > li:nth-child(2) > div > dl:nth-child(3) > dd > a:nth-child(1)
def test_cpwgbz_1(self):
"""产品外观标准_单个申请人减缓测试"""
dl = dengLuPage(self.driver)
dl.dengLu()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
ActionChains(self.driver).release()
self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(3) > dd > a:nth-child(1)").click()
time.sleep(3)
# 获取打开的多个窗口句柄
windows = self.driver.window_handles
# 切换到当前最新打开的窗口
self.driver.switch_to.window(windows[-1])
self.assertIn("外观设计专利标准申请|专利申请|专利查询|权大师",self.driver.title)
print(self.driver.title)
self.driver.find_element_by_css_selector("#slowItems > label.label.active").click() # 单个申请人减缓
self.driver.find_element_by_css_selector("#serviceName > li.list.active").click() # 标准
for a in self.driver.find_elements_by_css_selector("#total-price"):
print("费用总计:"+a.text)
aa=a.text
self.driver.find_element_by_css_selector(
"body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
get_screenshort(self.driver, "test_cpwgbz_1.png")
for i in self.driver.find_elements_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
print("总价:" + i.text)
ii = i.text
self.assertIn(aa, ii)
print("价格一致")
self.driver.find_element_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
for o in self.driver.find_elements_by_class_name("payable"):
print("订单提交成功,应付金额:" + o.text)
oo = o.text
self.assertIn(oo, ii)
print("测试通过")
self.driver.find_element_by_css_selector("#alisubmit").click()
def test_cpwgbz_2(self):
"""产品外观标准_多个申请人减缓测试"""
dl = dengLuPage(self.driver)
dl.dengLu()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
ActionChains(self.driver).release()
self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(3) > dd > a:nth-child(1)").click()
time.sleep(3)
# 获取打开的多个窗口句柄
windows = self.driver.window_handles
# 切换到当前最新打开的窗口
self.driver.switch_to.window(windows[-1])
self.assertIn("外观设计专利标准申请|专利申请|专利查询|权大师", self.driver.title)
print(self.driver.title)
self.driver.find_element_by_css_selector("#slowItems > label:nth-child(2)").click() # 多个申请人减缓
self.driver.find_element_by_css_selector("#serviceName > li.list.active").click() # 标准
for a in self.driver.find_elements_by_css_selector("#total-price"):
print("费用总计:" + a.text)
aa = a.text
self.driver.find_element_by_css_selector(
"body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
get_screenshort(self.driver, "test_cpwgbz_2.png")
for i in self.driver.find_elements_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
print("总价:" + i.text)
ii = i.text
self.assertIn(aa, ii)
print("价格一致")
self.driver.find_element_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
for o in self.driver.find_elements_by_class_name("payable"):
print("订单提交成功,应付金额:" + o.text)
oo = o.text
self.assertIn(oo, ii)
print("测试通过")
self.driver.find_element_by_css_selector("#alisubmit").click()
def test_cpwgbz_3(self):
"""产品外观标准_不减缓测试"""
dl = dengLuPage(self.driver)
dl.dengLu()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
ActionChains(self.driver).release()
self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(3) > dd > a:nth-child(1)").click()
time.sleep(3)
# 获取打开的多个窗口句柄
windows = self.driver.window_handles
# 切换到当前最新打开的窗口
self.driver.switch_to.window(windows[-1])
self.assertIn("外观设计专利标准申请|专利申请|专利查询|权大师", self.driver.title)
print(self.driver.title)
self.driver.find_element_by_css_selector("#slowItems > label:nth-child(3)").click() # 不减缓
self.driver.find_element_by_css_selector("#serviceName > li.list.active").click() # 标准
for a in self.driver.find_elements_by_css_selector("#total-price"):
print("费用总计:" + a.text)
aa = a.text
self.driver.find_element_by_css_selector(
"body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
get_screenshort(self.driver, "test_cpwgbz_3.png")
for i in self.driver.find_elements_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
print("总价:" + i.text)
ii = i.text
self.assertIn(aa, ii)
print("价格一致")
self.driver.find_element_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
for o in self.driver.find_elements_by_class_name("payable"):
print("订单提交成功,应付金额:" + o.text)
oo = o.text
self.assertIn(oo, ii)
print("测试通过")
self.driver.find_element_by_css_selector("#alisubmit").click()
def test_cpwgdb_1(self):
"""产品外观担保_单个申请人减缓测试"""
dl = dengLuPage(self.driver)
dl.dengLu()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
ActionChains(self.driver).release()
self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(3) > dd > a:nth-child(1)").click()
time.sleep(3)
# 获取打开的多个窗口句柄
windows = self.driver.window_handles
# 切换到当前最新打开的窗口
self.driver.switch_to.window(windows[-1])
self.assertIn("外观设计专利标准申请|专利申请|专利查询|权大师", self.driver.title)
print(self.driver.title)
self.driver.find_element_by_css_selector("#serviceName > li:nth-child(2)").click() # 担保
time.sleep(2)
self.driver.find_element_by_css_selector("#slowItems > label.label.active").click() # 单个申请人减缓
for a in self.driver.find_elements_by_css_selector("#total-price"):
print("费用总计:" + a.text)
aa = a.text
self.driver.find_element_by_css_selector(
"body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
get_screenshort(self.driver, "test_cpwgdb_1.png")
for i in self.driver.find_elements_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
print("总价:" + i.text)
ii = i.text
self.assertIn(aa, ii)
print("价格一致")
self.driver.find_element_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
for o in self.driver.find_elements_by_class_name("payable"):
print("订单提交成功,应付金额:" + o.text)
oo = o.text
self.assertIn(oo, ii)
print("测试通过")
self.driver.find_element_by_css_selector("#alisubmit").click()
def test_cpwgdb_2(self):
"""产品外观担保_多个申请人减缓测试"""
dl = dengLuPage(self.driver)
dl.dengLu()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
ActionChains(self.driver).release()
self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(3) > dd > a:nth-child(1)").click()
time.sleep(3)
# 获取打开的多个窗口句柄
windows = self.driver.window_handles
# 切换到当前最新打开的窗口
self.driver.switch_to.window(windows[-1])
self.assertIn("外观设计专利标准申请|专利申请|专利查询|权大师", self.driver.title)
print(self.driver.title)
self.driver.find_element_by_css_selector("#serviceName > li:nth-child(2)").click() # 担保
time.sleep(2)
self.driver.find_element_by_css_selector("#slowItems > label:nth-child(2)").click() # 多个申请人减缓
for a in self.driver.find_elements_by_css_selector("#total-price"):
print("费用总计:" + a.text)
aa = a.text
self.driver.find_element_by_css_selector(
"body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
get_screenshort(self.driver, "test_cpwgdb_2.png")
for i in self.driver.find_elements_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
print("总价:" + i.text)
ii = i.text
self.assertIn(aa, ii)
print("价格一致")
self.driver.find_element_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
for o in self.driver.find_elements_by_class_name("payable"):
print("订单提交成功,应付金额:" + o.text)
oo = o.text
self.assertIn(oo, ii)
print("测试通过")
self.driver.find_element_by_css_selector("#alisubmit").click()
def test_cpwgdb_3(self):
"""产品外观担保_不减缓测试"""
dl = dengLuPage(self.driver)
dl.dengLu()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
ActionChains(self.driver).release()
self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(3) > dd > a:nth-child(1)").click()
time.sleep(3)
# 获取打开的多个窗口句柄
windows = self.driver.window_handles
# 切换到当前最新打开的窗口
self.driver.switch_to.window(windows[-1])
self.assertIn("外观设计专利标准申请|专利申请|专利查询|权大师", self.driver.title)
print(self.driver.title)
self.driver.find_element_by_css_selector("#serviceName > li:nth-child(2)").click() # 担保
time.sleep(2)
self.driver.find_element_by_css_selector("#slowItems > label:nth-child(3)").click() # 不减缓
time.sleep(2)
for a in self.driver.find_elements_by_css_selector("#total-price"):
print("费用总计:" + a.text)
aa = a.text
self.driver.find_element_by_css_selector(
"body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
get_screenshort(self.driver, "test_cpwgdb_3.png")
for i in self.driver.find_elements_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
print("总价:" + i.text)
ii = i.text
self.assertIn(aa, ii)
print("价格一致")
self.driver.find_element_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
for o in self.driver.find_elements_by_class_name("payable"):
print("订单提交成功,应付金额:" + o.text)
oo = o.text
self.assertIn(oo, ii)
print("测试通过")
self.driver.find_element_by_css_selector("#alisubmit").click()
def test_guibz_1(self):
"""GUI标准_单个申请人减缓"""
dl = dengLuPage(self.driver)
dl.dengLu()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
ActionChains(self.driver).release()
self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(3) > dd > a:nth-child(2)").click()
time.sleep(3)
# 获取打开的多个窗口句柄
windows = self.driver.window_handles
# 切换到当前最新打开的窗口
self.driver.switch_to.window(windows[-1])
self.assertIn("GUI及系列产品标准申请|专利申请|专利查询|权大师",self.driver.title)
print(self.driver.title)
self.driver.find_element_by_css_selector("#slowItems > label.label.active").click() # 单个申请人减缓
self.driver.find_element_by_css_selector("#serviceName > li.list.active").click() # 标准
for a in self.driver.find_elements_by_css_selector("#total-price"):
print("费用总计:"+a.text)
aa=a.text
self.driver.find_element_by_css_selector(
"body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
get_screenshort(self.driver, "test_guibz_1.png")
for i in self.driver.find_elements_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
print("总价:" + i.text)
ii = i.text
self.assertIn(aa, ii)
print("价格一致")
self.driver.find_element_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
for o in self.driver.find_elements_by_class_name("payable"):
print("订单提交成功,应付金额:" + o.text)
oo = o.text
self.assertIn(oo, ii)
print("测试通过")
self.driver.find_element_by_css_selector("#alisubmit").click()
def test_guibz_2(self):
"""GUI标准_多个申请人减缓"""
dl = dengLuPage(self.driver)
dl.dengLu()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
ActionChains(self.driver).release()
self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(3) > dd > a:nth-child(2)").click()
time.sleep(3)
# 获取打开的多个窗口句柄
windows = self.driver.window_handles
# 切换到当前最新打开的窗口
self.driver.switch_to.window(windows[-1])
self.assertIn("GUI及系列产品标准申请|专利申请|专利查询|权大师",self.driver.title)
print(self.driver.title)
self.driver.find_element_by_css_selector("#slowItems > label:nth-child(2)").click() # 多个申请人减缓
self.driver.find_element_by_css_selector("#serviceName > li.list.active").click() # 标准
for a in self.driver.find_elements_by_css_selector("#total-price"):
print("费用总计:"+a.text)
aa=a.text
self.driver.find_element_by_css_selector(
"body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
get_screenshort(self.driver, "test_guibz_2.png")
for i in self.driver.find_elements_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
print("总价:" + i.text)
ii = i.text
self.assertIn(aa, ii)
print("价格一致")
self.driver.find_element_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
for o in self.driver.find_elements_by_class_name("payable"):
print("订单提交成功,应付金额:" + o.text)
oo = o.text
self.assertIn(oo, ii)
print("测试通过")
self.driver.find_element_by_css_selector("#alisubmit").click()
def test_guibz_3(self):
"""GUI标准_不减缓"""
dl = dengLuPage(self.driver)
dl.dengLu()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
ActionChains(self.driver).release()
self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(3) > dd > a:nth-child(2)").click()
time.sleep(3)
# 获取打开的多个窗口句柄
windows = self.driver.window_handles
# 切换到当前最新打开的窗口
self.driver.switch_to.window(windows[-1])
self.assertIn("GUI及系列产品标准申请|专利申请|专利查询|权大师",self.driver.title)
print(self.driver.title)
self.driver.find_element_by_css_selector("#slowItems > label:nth-child(3)").click() # 不减缓
self.driver.find_element_by_css_selector("#serviceName > li.list.active").click() # 标准
for a in self.driver.find_elements_by_css_selector("#total-price"):
print("费用总计:"+a.text)
aa=a.text
self.driver.find_element_by_css_selector(
"body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
get_screenshort(self.driver, "test_guibz_3.png")
for i in self.driver.find_elements_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
print("总价:" + i.text)
ii = i.text
self.assertIn(aa, ii)
print("价格一致")
self.driver.find_element_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
for o in self.driver.find_elements_by_class_name("payable"):
print("订单提交成功,应付金额:" + o.text)
oo = o.text
self.assertIn(oo, ii)
print("测试通过")
self.driver.find_element_by_css_selector("#alisubmit").click()
def test_guidb_1(self):
"""GUI担保_单个申请人减缓"""
dl = dengLuPage(self.driver)
dl.dengLu()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
ActionChains(self.driver).release()
self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(3) > dd > a:nth-child(2)").click()
time.sleep(3)
# 获取打开的多个窗口句柄
windows = self.driver.window_handles
# 切换到当前最新打开的窗口
self.driver.switch_to.window(windows[-1])
self.assertIn("GUI及系列产品标准申请|专利申请|专利查询|权大师",self.driver.title)
print(self.driver.title)
self.driver.find_element_by_css_selector("#serviceName > li:nth-child(2)").click() # 担保
time.sleep(2)
self.driver.find_element_by_css_selector("#slowItems > label.label.active").click() # 单个申请人减缓
for a in self.driver.find_elements_by_css_selector("#total-price"):
print("费用总计:"+a.text)
aa=a.text
self.driver.find_element_by_css_selector(
"body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
get_screenshort(self.driver, "test_guidb_1.png")
for i in self.driver.find_elements_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
print("总价:" + i.text)
ii = i.text
self.assertIn(aa, ii)
print("价格一致")
self.driver.find_element_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
for o in self.driver.find_elements_by_class_name("payable"):
print("订单提交成功,应付金额:" + o.text)
oo = o.text
self.assertIn(oo, ii)
print("测试通过")
self.driver.find_element_by_css_selector("#alisubmit").click()
def test_guidb_2(self):
"""GUI担保_多个申请人减缓"""
dl = dengLuPage(self.driver)
dl.dengLu()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
ActionChains(self.driver).release()
self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(3) > dd > a:nth-child(2)").click()
time.sleep(3)
# 获取打开的多个窗口句柄
windows = self.driver.window_handles
# 切换到当前最新打开的窗口
self.driver.switch_to.window(windows[-1])
self.assertIn("GUI及系列产品标准申请|专利申请|专利查询|权大师",self.driver.title)
print(self.driver.title)
self.driver.find_element_by_css_selector("#serviceName > li:nth-child(2)").click() # 担保
time.sleep(2)
self.driver.find_element_by_css_selector("#slowItems > label:nth-child(2)").click() # 多个申请人减缓
for a in self.driver.find_elements_by_css_selector("#total-price"):
print("费用总计:"+a.text)
aa=a.text
self.driver.find_element_by_css_selector(
"body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
get_screenshort(self.driver, "test_guidb_2.png")
for i in self.driver.find_elements_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
print("总价:" + i.text)
ii = i.text
self.assertIn(aa, ii)
print("价格一致")
self.driver.find_element_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
for o in self.driver.find_elements_by_class_name("payable"):
print("订单提交成功,应付金额:" + o.text)
oo = o.text
self.assertIn(oo, ii)
print("测试通过")
self.driver.find_element_by_css_selector("#alisubmit").click()
def test_guidb_3(self):
"""GUI担保_不减缓"""
dl = dengLuPage(self.driver)
dl.dengLu()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
ActionChains(self.driver).release()
self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(3) > dd > a:nth-child(2)").click()
time.sleep(3)
# 获取打开的多个窗口句柄
windows = self.driver.window_handles
# 切换到当前最新打开的窗口
self.driver.switch_to.window(windows[-1])
self.assertIn("GUI及系列产品标准申请|专利申请|专利查询|权大师",self.driver.title)
print(self.driver.title)
self.driver.find_element_by_css_selector("#serviceName > li:nth-child(2)").click() # 担保
time.sleep(2)
self.driver.find_element_by_css_selector("#slowItems > label:nth-child(3)").click() # 不减缓
for a in self.driver.find_elements_by_css_selector("#total-price"):
print("费用总计:"+a.text)
aa=a.text
self.driver.find_element_by_css_selector(
"body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
get_screenshort(self.driver, "test_guidb_3.png")
for i in self.driver.find_elements_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
print("总价:" + i.text)
ii = i.text
self.assertIn(aa, ii)
print("价格一致")
self.driver.find_element_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
for o in self.driver.find_elements_by_class_name("payable"):
print("订单提交成功,应付金额:" + o.text)
oo = o.text
self.assertIn(oo, ii)
print("测试通过")
self.driver.find_element_by_css_selector("#alisubmit").click()
def test_syzlbz_1(self):
"""标准型-单个申请人减缓"""
# logging.basicConfig(filename='../LOG/' + __name__ + '.log',
# format='[%(asctime)s-%(filename)s-%(levelname)s: %(message)s]', level=logging.DEBUG,
# filemode='a', datefmt='%Y-%m-%d%I:%M:%S %p')
dl = dengLuPage(self.driver)
dl.dengLu()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
ActionChains(self.driver).release()
self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(4) > dd > a:nth-child(1)").click()
time.sleep(2)
self.assertIn("实用新型专利标准申请|专利申请|专利查询|权大师", self.driver.title)
print(self.driver.title)
self.driver.find_element_by_css_selector("#slowItems > label.label.active").click() # 单个申请人减缓
# self.driver.find_element_by_css_selector("#slowItems > label:nth-child(2) > input[type=\"checkbox\"]") #多个申请人减缓
# self.driver.find_element_by_css_selector("#slowItems > label:nth-child(3) > input[type=\"checkbox\"]") #不减缓
self.driver.find_element_by_css_selector("#serviceName > li.list.active").click()
for a in self.driver.find_elements_by_css_selector("#total-price"):
print("费用总计:" + a.text)
aa = a.text
self.driver.find_element_by_css_selector(
"body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
get_screenshort(self.driver, "test_syzlbz_1.png")
for i in self.driver.find_elements_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
print("总价:" + i.text)
ii = i.text
self.assertIn(aa, ii)
print("价格一致")
self.driver.find_element_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
for o in self.driver.find_elements_by_class_name("payable"):
print("订单提交成功,应付金额:" + o.text)
oo = o.text
self.assertIn(oo, ii)
print("测试通过")
self.driver.find_element_by_css_selector("#alisubmit").click()
def test_syzlbz_2(self):
"""标准型-多个申请人减缓"""
# logging.basicConfig(filename='../LOG/' + __name__ + '.log',
# format='[%(asctime)s-%(filename)s-%(levelname)s: %(message)s]', level=logging.DEBUG,
# filemode='a', datefmt='%Y-%m-%d%I:%M:%S %p')
dl = dengLuPage(self.driver)
dl.dengLu()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
ActionChains(self.driver).release()
self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(4) > dd > a:nth-child(1)").click()
time.sleep(2)
self.assertIn("实用新型专利标准申请|专利申请|专利查询|权大师", self.driver.title)
print(self.driver.title)
# self.driver.find_element_by_css_selector("#slowItems > label.label.active > input[type=\"checkbox\"]") #单个申请人减缓
self.driver.find_element_by_css_selector("#slowItems > label:nth-child(2)").click() # 多个申请人减缓
# self.driver.find_element_by_css_selector("#slowItems > label:nth-child(3) > input[type=\"checkbox\"]") #不减缓
self.driver.find_element_by_css_selector("#serviceName > li.list.active").click()
for a in self.driver.find_elements_by_css_selector("#total-price"):
print("费用总计:" + a.text)
aa = a.text
self.driver.find_element_by_css_selector(
"body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
get_screenshort(self.driver, "test_syzlbz_2.png")
for i in self.driver.find_elements_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
print("总价:" + i.text)
ii = i.text
self.assertIn(aa, ii)
print("价格一致")
self.driver.find_element_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
for o in self.driver.find_elements_by_class_name("payable"):
print("订单提交成功,应付金额:" + o.text)
oo = o.text
self.assertIn(oo, ii)
print("测试通过")
self.driver.find_element_by_css_selector("#alisubmit").click()
def test_syzlbz_3(self):
"""标准型-不减缓"""
# logging.basicConfig(filename='../LOG/' + __name__ + '.log',
# format='[%(asctime)s-%(filename)s-%(levelname)s: %(message)s]', level=logging.DEBUG,
# filemode='a', datefmt='%Y-%m-%d%I:%M:%S %p')
dl = dengLuPage(self.driver)
dl.dengLu()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
ActionChains(self.driver).release()
self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(4) > dd > a:nth-child(1)").click()
time.sleep(2)
self.assertIn("实用新型专利标准申请|专利申请|专利查询|权大师", self.driver.title)
print(self.driver.title)
# self.driver.find_element_by_css_selector("#slowItems > label.label.active > input[type=\"checkbox\"]") #单个申请人减缓
# self.driver.find_element_by_css_selector("#slowItems > label:nth-child(2) > input[type=\"checkbox\"]") #多个申请人减缓
self.driver.find_element_by_css_selector("#slowItems > label:nth-child(3)").click() # 不减缓
self.driver.find_element_by_css_selector("#serviceName > li.list.active").click()
for a in self.driver.find_elements_by_css_selector("#total-price"):
print("费用总计:" + a.text)
aa = a.text
self.driver.find_element_by_css_selector(
"body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
get_screenshort(self.driver, "test_syzlbz_3.png")
for i in self.driver.find_elements_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
print("总价:" + i.text)
ii = i.text
self.assertIn(aa, ii)
print("价格一致")
self.driver.find_element_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
for o in self.driver.find_elements_by_class_name("payable"):
print("订单提交成功,应付金额:" + o.text)
oo = o.text
self.assertIn(oo, ii)
print("测试通过")
self.driver.find_element_by_css_selector("#alisubmit").click()
def test_syzldb_1(self):
"""担保型-单个申请人减缓"""
# logging.basicConfig(filename='../LOG/' + __name__ + '.log',
# format='[%(asctime)s-%(filename)s-%(levelname)s: %(message)s]', level=logging.DEBUG,
# filemode='a', datefmt='%Y-%m-%d%I:%M:%S %p')
dl = dengLuPage(self.driver)
dl.dengLu()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
ActionChains(self.driver).release()
self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(4) > dd > a:nth-child(2)").click()
time.sleep(2)
self.assertIn("实用新型专利担保申请|专利申请|专利查询|权大师", self.driver.title)
print(self.driver.title)
self.driver.find_element_by_css_selector("#slowItems > label.label.active").click() # 单个申请人减缓
# self.driver.find_element_by_css_selector("#slowItems > label:nth-child(2) > input[type=\"checkbox\"]") #多个申请人减缓
# self.driver.find_element_by_css_selector("#slowItems > label:nth-child(3) > input[type=\"checkbox\"]") #不减缓
self.driver.find_element_by_css_selector("#serviceName > li.list.active").click()
for a in self.driver.find_elements_by_css_selector("#total-price"):
print("费用总计:" + a.text)
aa = a.text
self.driver.find_element_by_css_selector(
"body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
get_screenshort(self.driver, "test_syzldb_1.png")
for i in self.driver.find_elements_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
print("总价:" + i.text)
ii = i.text
self.assertIn(aa, ii)
print("价格一致")
self.driver.find_element_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
for o in self.driver.find_elements_by_class_name("payable"):
print("订单提交成功,应付金额:" + o.text)
oo = o.text
self.assertIn(oo, ii)
print("测试通过")
self.driver.find_element_by_css_selector("#alisubmit").click()
def test_syzldb_2(self):
"""担保型-多个申请人减缓"""
# logging.basicConfig(filename='../LOG/' + __name__ + '.log',
# format='[%(asctime)s-%(filename)s-%(levelname)s: %(message)s]', level=logging.DEBUG,
# filemode='a', datefmt='%Y-%m-%d%I:%M:%S %p')
dl = dengLuPage(self.driver)
dl.dengLu()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
ActionChains(self.driver).release()
self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(4) > dd > a:nth-child(2)").click()
time.sleep(2)
self.assertIn("实用新型专利担保申请|专利申请|专利查询|权大师", self.driver.title)
print(self.driver.title)
# self.driver.find_element_by_css_selector("#slowItems > label.label.active > input[type=\"checkbox\"]") #单个申请人减缓
self.driver.find_element_by_css_selector("#slowItems > label:nth-child(2)").click() # 多个申请人减缓
# self.driver.find_element_by_css_selector("#slowItems > label:nth-child(3) > input[type=\"checkbox\"]") #不减缓
self.driver.find_element_by_css_selector("#serviceName > li.list.active").click()
for a in self.driver.find_elements_by_css_selector("#total-price"):
print("费用总计:" + a.text)
aa = a.text
self.driver.find_element_by_css_selector(
"body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
get_screenshort(self.driver, "test_syzldb_2.png")
for i in self.driver.find_elements_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
print("总价:" + i.text)
ii = i.text
self.assertIn(aa, ii)
print("价格一致")
self.driver.find_element_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
for o in self.driver.find_elements_by_class_name("payable"):
print("订单提交成功,应付金额:" + o.text)
oo = o.text
self.assertIn(oo, ii)
print("测试通过")
self.driver.find_element_by_css_selector("#alisubmit").click()
def test_syzldb_3(self):
"""担保型-不减缓"""
# logging.basicConfig(filename='../LOG/' + __name__ + '.log',
# format='[%(asctime)s-%(filename)s-%(levelname)s: %(message)s]', level=logging.DEBUG,
# filemode='a', datefmt='%Y-%m-%d%I:%M:%S %p')
dl = dengLuPage(self.driver)
dl.dengLu()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
ActionChains(self.driver).release()
self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(4) > dd > a:nth-child(2)").click()
time.sleep(2)
self.assertIn("实用新型专利担保申请|专利申请|专利查询|权大师", self.driver.title)
print(self.driver.title)
# self.driver.find_element_by_css_selector("#slowItems > label.label.active > input[type=\"checkbox\"]") #单个申请人减缓
# self.driver.find_element_by_css_selector("#slowItems > label:nth-child(2) > input[type=\"checkbox\"]") #多个申请人减缓
self.driver.find_element_by_css_selector("#slowItems > label:nth-child(3)").click() # 不减缓
self.driver.find_element_by_css_selector("#serviceName > li.list.active").click()
for a in self.driver.find_elements_by_css_selector("#total-price"):
print("费用总计:" + a.text)
aa = a.text
self.driver.find_element_by_css_selector(
"body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
get_screenshort(self.driver, "test_syzldb_3.png")
for i in self.driver.find_elements_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
print("总价:" + i.text)
ii = i.text
self.assertIn(aa, ii)
print("价格一致")
self.driver.find_element_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
for o in self.driver.find_elements_by_class_name("payable"):
print("订单提交成功,应付金额:" + o.text)
oo = o.text
self.assertIn(oo, ii)
print("测试通过")
self.driver.find_element_by_css_selector("#alisubmit").click()
"""旧版专利商品"""
# def test_syxxjc(self):
# """实用新型专利基础版"""
#
# dl = dengLuPage(self.driver)
# dl.dengLu()
# time.sleep(2)
# ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
# "body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
# time.sleep(2)
# ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
# "body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
# ActionChains(self.driver).release()
# self.driver.find_element_by_css_selector(
# "body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(4) > dd > a:nth-child(1)").click()
#
# time.sleep(3)
#
# # 获取打开的多个窗口句柄
# windows = self.driver.window_handles
# # 切换到当前最新打开的窗口
# self.driver.switch_to.window(windows[-1])
# self.assertIn("实用新型专利基础版_权大师",self.driver.title)
# print(self.driver.title)
#
# for a in self.driver.find_elements_by_css_selector("#total-price"):
# print("费用总计:"+a.text)
# aa=a.text
#
# self.driver.find_element_by_css_selector(
# "body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
# self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
# self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
# self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
# self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
#
# get_screenshort(self.driver, "test_syxxjc.png")
#
# for i in self.driver.find_elements_by_css_selector(
# "body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
# print("总价:" + i.text)
# ii = i.text
#
# self.assertIn(aa, ii)
# print("价格一致")
#
# self.driver.find_element_by_css_selector(
# "body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
#
# for o in self.driver.find_elements_by_class_name("payable"):
# print("订单提交成功,应付金额:" + o.text)
# oo = o.text
#
# self.assertIn(oo, ii)
#
# print("测试通过")
#
# self.driver.find_element_by_css_selector("#alisubmit").click()
#
# def test_syxxzl(self):
# """实用新型专利卓越版"""
#
# dl = dengLuPage(self.driver)
# dl.dengLu()
# time.sleep(2)
# ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
# "body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
# time.sleep(2)
# ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
# "body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
# ActionChains(self.driver).release()
# self.driver.find_element_by_css_selector(
# "body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(4) > dd > a:nth-child(2)").click()
#
# time.sleep(3)
#
# # 获取打开的多个窗口句柄
# windows = self.driver.window_handles
# # 切换到当前最新打开的窗口
# self.driver.switch_to.window(windows[-1])
# self.assertIn("实用新型专利卓越版_权大师", self.driver.title)
# print(self.driver.title)
#
# for a in self.driver.find_elements_by_css_selector("#total-price"):
# print("费用总计:" + a.text)
# aa = a.text
#
# self.driver.find_element_by_css_selector(
# "body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
# self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
# self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
# self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
# self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
#
# get_screenshort(self.driver, "test_syxxzl.png")
#
# for i in self.driver.find_elements_by_css_selector(
# "body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
# print("总价:" + i.text)
# ii = i.text
#
# self.assertIn(aa, ii)
# print("价格一致")
#
# self.driver.find_element_by_css_selector(
# "body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
#
# for o in self.driver.find_elements_by_class_name("payable"):
# print("订单提交成功,应付金额:" + o.text)
# oo = o.text
#
# self.assertIn(oo, ii)
#
# print("测试通过")
#
# self.driver.find_element_by_css_selector("#alisubmit").click()
def test_zlbh(self):
"""专利驳回复审测试"""
dl = dengLuPage(self.driver)
dl.dengLu()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
ActionChains(self.driver).release()
self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(5) > dd > a:nth-child(1)").click()
time.sleep(3)
# 获取打开的多个窗口句柄
windows = self.driver.window_handles
# 切换到当前最新打开的窗口
self.driver.switch_to.window(windows[-1])
self.assertIn("发明专利驳回复审_权大师", self.driver.title)
print(self.driver.title)
for a in self.driver.find_elements_by_css_selector("#total-price"):
print("费用总计:" + a.text)
aa = a.text
self.driver.find_element_by_css_selector(
"body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
get_screenshort(self.driver, "test_zlbh.png")
for i in self.driver.find_elements_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
print("总价:" + i.text)
ii = i.text
self.assertIn(aa, ii)
print("价格一致")
self.driver.find_element_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
for o in self.driver.find_elements_by_class_name("payable"):
print("订单提交成功,应付金额:" + o.text)
oo = o.text
self.assertIn(oo, ii)
print("测试通过")
self.driver.find_element_by_css_selector("#alisubmit").click()
def test_zlxg(self):
""" 专利无效宣告测试"""
dl = dengLuPage(self.driver)
dl.dengLu()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
ActionChains(self.driver).release()
self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(5) > dd > a:nth-child(2)").click()
time.sleep(3)
# 获取打开的多个窗口句柄
windows = self.driver.window_handles
# 切换到当前最新打开的窗口
self.driver.switch_to.window(windows[-1])
self.assertIn("专利无效宣告_权大师", self.driver.title)
print(self.driver.title)
for a in self.driver.find_elements_by_css_selector("#total-price"):
print("费用总计:" + a.text)
aa = a.text
self.driver.find_element_by_css_selector(
"body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
get_screenshort(self.driver, "test_zlxg.png")
for i in self.driver.find_elements_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
print("总价:" + i.text)
ii = i.text
self.assertIn(aa, ii)
print("价格一致")
self.driver.find_element_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
for o in self.driver.find_elements_by_class_name("payable"):
print("订单提交成功,应付金额:" + o.text)
oo = o.text
self.assertIn(oo, ii)
print("测试通过")
self.driver.find_element_by_css_selector("#alisubmit").click()
def test_zldb(self):
"""发明专利无效答辩测试"""
dl = dengLuPage(self.driver)
dl.dengLu()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
ActionChains(self.driver).release()
self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(5) > dd > a:nth-child(3)").click()
time.sleep(3)
# 获取打开的多个窗口句柄
windows = self.driver.window_handles
# 切换到当前最新打开的窗口
self.driver.switch_to.window(windows[-1])
self.assertIn("发明专利无效答辩_权大师", self.driver.title)
print(self.driver.title)
for a in self.driver.find_elements_by_css_selector("#total-price"):
print("费用总计:" + a.text)
aa = a.text
self.driver.find_element_by_css_selector(
"body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
get_screenshort(self.driver, "test_zldb.png")
for i in self.driver.find_elements_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
print("总价:" + i.text)
ii = i.text
self.assertIn(aa, ii)
print("价格一致")
self.driver.find_element_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
for o in self.driver.find_elements_by_class_name("payable"):
print("订单提交成功,应付金额:" + o.text)
oo = o.text
self.assertIn(oo, ii)
print("测试通过")
self.driver.find_element_by_css_selector("#alisubmit").click()
def test_nfjn(self):
"""年费缴纳测试"""
dl = dengLuPage(self.driver)
dl.dengLu()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
ActionChains(self.driver).release()
self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(6) > dd > a:nth-child(1)").click()
time.sleep(3)
# 获取打开的多个窗口句柄
windows = self.driver.window_handles
# 切换到当前最新打开的窗口
self.driver.switch_to.window(windows[-1])
self.assertIn("发明专利年费缴纳-权大师", self.driver.title)
print(self.driver.title)
for a in self.driver.find_elements_by_css_selector("#total-price"):
print("费用总计:" + a.text)
aa = a.text
self.driver.find_element_by_css_selector(
"body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
get_screenshort(self.driver, "test_nfjn.png")
for i in self.driver.find_elements_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
print("总价:" + i.text)
ii = i.text
self.assertIn(aa, ii)
print("价格一致")
self.driver.find_element_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
for o in self.driver.find_elements_by_class_name("payable"):
print("订单提交成功,应付金额:" + o.text)
oo = o.text
self.assertIn(oo, ii)
print("测试通过")
self.driver.find_element_by_css_selector("#alisubmit").click()
def test_zlbg(self):
"""专利著录项变更测试"""
dl = dengLuPage(self.driver)
dl.dengLu()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > h3 > span")).perform()
time.sleep(2)
ActionChains(self.driver).move_to_element(self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > h3 > a")).perform()
ActionChains(self.driver).release()
self.driver.find_element_by_css_selector(
"body > div.section-banner > div.public-navbar > div > div > div > ul:nth-child(1) > li:nth-child(2) > div > dl:nth-child(6) > dd > a:nth-child(2)").click()
time.sleep(3)
# 获取打开的多个窗口句柄
windows = self.driver.window_handles
# 切换到当前最新打开的窗口
self.driver.switch_to.window(windows[-1])
self.assertIn("专利著录项变更-权大师", self.driver.title)
print(self.driver.title)
for a in self.driver.find_elements_by_css_selector("#total-price"):
print("费用总计:" + a.text)
aa = a.text
self.driver.find_element_by_css_selector(
"body > div.section-product.width1200 > dl > dd > div.cont-btnBuy > a.btn.btn-next.buynow").click()
self.driver.find_element_by_name("ownerContactPerson").send_keys("全大师")
self.driver.find_element_by_name("ownerContactPhone").send_keys("15624992498")
self.driver.find_element_by_name("contactMail").send_keys("145647@qq.com")
self.driver.find_element_by_css_selector("#remark").send_keys(time.strftime("%Y-%m-%d_%H-%M-%S") + "测试订单")
get_screenshort(self.driver, "test_zlbg.png")
for i in self.driver.find_elements_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-sense > em > i"):
print("总价:" + i.text)
ii = i.text
self.assertIn(aa, ii)
print("价格一致")
self.driver.find_element_by_css_selector(
"body > div.section-myorder.width1200 > div > div > ul > li.row-step > a.btn-next.submitOrder").click()
for o in self.driver.find_elements_by_class_name("payable"):
print("订单提交成功,应付金额:" + o.text)
oo = o.text
self.assertIn(oo, ii)
print("测试通过")
self.driver.find_element_by_css_selector("#alisubmit").click()
| [
"1456470136@qq.com"
] | 1456470136@qq.com |
d87e6b7190ffd9f4f1c99b2383a7d2ac3e2c9173 | f36f17f00d02198c851a4fcc7680aa4a3fa2397e | /riko/modules/refind.py | d20944d580c5018a127c1e4cef366804efff1063 | [
"MIT"
] | permissive | HKCaesar/riko | c0a9fe597e137b2512c12e6444c8b4645eaf1b63 | 2ad4cb372a784dca4fbce68d71171bd8e6a0e8ae | refs/heads/master | 2020-06-17T16:35:46.594452 | 2017-05-22T17:59:39 | 2017-05-22T17:59:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,711 | py | # -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
riko.modules.refind
~~~~~~~~~~~~~~~~~~~
Provides functions for finding text located before, after, at, or between
substrings using regular expressions, a powerful type of pattern matching.
Examples:
basic usage::
>>> from riko.modules.refind import pipe
>>> conf = {'rule': {'find': '[aiou]'}}
>>> item = {'content': 'hello world'}
>>> next(pipe(item, conf=conf))['refind'] == 'hell'
True
Attributes:
OPTS (dict): The default pipe options
DEFAULTS (dict): The default parser options
"""
from __future__ import (
absolute_import, division, print_function, unicode_literals)
import re
import pygogo as gogo
from functools import reduce
from builtins import *
from . import processor
from riko.bado import coroutine, return_value, itertools as ait
OPTS = {
'listize': True, 'ftype': 'text', 'field': 'content', 'extract': 'rule'}
DEFAULTS = {}
logger = gogo.Gogo(__name__, monolog=True).logger
PARAMS = {
'first': lambda word, rule: re.split(rule.find, word, maxsplit=1),
'last': lambda word, rule: re.split(rule.find, word)}
AT_PARAMS = {
'first': lambda word, rule: re.search(rule.find, word),
'last': lambda word, rule: re.findall(rule.find, word)}
OPS = {
'before': lambda splits, rule: rule.find.join(splits[:len(splits) - 1]),
'after': lambda splits, rule: splits[-1],
'at': lambda splits, rule: splits,
}
def reducer(word, rule):
param = rule.param or 'first'
default = rule.default or ''
if rule.location == 'at':
result = AT_PARAMS.get(param, AT_PARAMS['first'])(word, rule)
if result and param == 'first':
splits = result.group(0)
elif result and param == 'last':
splits = result[-1]
else:
splits = default
else:
splits = PARAMS.get(param, PARAMS['first'])(word, rule)
return OPS.get(rule.location, OPS['before'])(splits, rule).strip()
@coroutine
def async_parser(word, rules, skip=False, **kwargs):
""" Asynchronously parses the pipe content
Args:
word (str): The string to transform
rules (List[obj]): the parsed rules (Objectify instances).
skip (bool): Don't parse the content
kwargs (dict): Keyword arguments
Kwargs:
assign (str): Attribute to assign parsed content (default: refind)
stream (dict): The original item
Returns:
Deferred: twisted.internet.defer.Deferred item
Examples:
>>> from riko.bado import react
>>> from riko.bado.mock import FakeReactor
>>> from meza.fntools import Objectify
>>>
>>> def run(reactor):
... item = {'content': 'hello world'}
... conf = {'rule': {'find': '[aiou]'}}
... rule = Objectify(conf['rule'])
... kwargs = {'stream': item, 'conf': conf}
... d = async_parser(item['content'], [rule], **kwargs)
... return d.addCallbacks(print, logger.error)
>>>
>>> try:
... react(run, _reactor=FakeReactor())
... except SystemExit:
... pass
...
hell
"""
if skip:
value = kwargs['stream']
else:
value = yield ait.coop_reduce(reducer, rules, word)
return_value(value)
def parser(word, rules, skip=False, **kwargs):
""" Parses the pipe content
Args:
word (str): The string to transform
rules (List[obj]): the parsed rules (Objectify instances).
skip (bool): Don't parse the content
kwargs (dict): Keyword arguments
Kwargs:
assign (str): Attribute to assign parsed content (default: refind)
stream (dict): The original item
Returns:
dict: The item
Examples:
>>> from meza.fntools import Objectify
>>>
>>> item = {'content': 'hello world'}
>>> conf = {'rule': {'find': '[aiou]'}}
>>> rule = Objectify(conf['rule'])
>>> args = item['content'], [rule], False
>>> kwargs = {'stream': item, 'conf': conf}
>>> parser(*args, **kwargs) == 'hell'
True
"""
return kwargs['stream'] if skip else reduce(reducer, rules, word)
@processor(DEFAULTS, isasync=True, **OPTS)
def async_pipe(*args, **kwargs):
"""A processor module that asynchronously finds text within the field of an
item using regex.
Args:
item (dict): The entry to process
kwargs (dict): The keyword arguments passed to the wrapper
Kwargs:
conf (dict): The pipe configuration. Must contain the key 'rule'.
rule (dict): can be either a dict or list of dicts. Must contain
the key 'find'. May contain the keys 'location' or 'param'.
find (str): The string to find.
location (str): Direction of the substring to return. Must be
either 'before', 'after', or 'at' (default: 'before').
param (str): The type of replacement. Must be either 'first'
or 'last' (default: 'first').
assign (str): Attribute to assign parsed content (default: refind)
field (str): Item attribute to operate on (default: 'content')
Returns:
Deferred: twisted.internet.defer.Deferred item with transformed content
Examples:
>>> from riko.bado import react
>>> from riko.bado.mock import FakeReactor
>>>
>>> def run(reactor):
... callback = lambda x: print(next(x)['refind'])
... conf = {'rule': {'find': '[aiou]'}}
... d = async_pipe({'content': 'hello world'}, conf=conf)
... return d.addCallbacks(callback, logger.error)
>>>
>>> try:
... react(run, _reactor=FakeReactor())
... except SystemExit:
... pass
...
hell
"""
return async_parser(*args, **kwargs)
@processor(**OPTS)
def pipe(*args, **kwargs):
"""A processor that finds text within the field of an item using regex.
Args:
item (dict): The entry to process
kwargs (dict): The keyword arguments passed to the wrapper
Kwargs:
conf (dict): The pipe configuration. Must contain the key 'rule'.
rule (dict): can be either a dict or list of dicts. Must contain
the key 'find'. May contain the keys 'location' or 'param'.
find (str): The string to find.
location (str): Direction of the substring to return. Must be
either 'before', 'after', or 'at' (default: 'before').
param (str): The type of replacement. Must be either 'first'
or 'last' (default: 'first').
assign (str): Attribute to assign parsed content (default: refind)
field (str): Item attribute to operate on (default: 'content')
Yields:
dict: an item with transformed content
Examples:
>>> conf = {'rule': {'find': '[aiou]'}}
>>> item = {'content': 'hello world'}
>>> next(pipe(item, conf=conf))['refind'] == 'hell'
True
>>> conf = {'rule': {'find': 'w', 'location': 'after'}}
>>> kwargs = {'conf': conf, 'field': 'title', 'assign': 'result'}
>>> item = {'title': 'hello world'}
>>> next(pipe(item, **kwargs))['result'] == 'orld'
True
>>> conf = {
... 'rule': [
... {'find': 'o([a-z])', 'location': 'after'}, {'find': 'd'}]}
>>> item = {'content': 'hello world'}
>>> next(pipe(item, conf=conf))['refind'] == 'l'
True
"""
return parser(*args, **kwargs)
| [
"reubano@gmail.com"
] | reubano@gmail.com |
f9a72eee61a1e1d65d6dc7b03850dbac62117f60 | 2c8d3e341e813c1b1b88ae824edeaadb366aec0a | /Parser/SW4/SW4/bin/Debug/smo2-24-path-21.py | 841db219d8a8c33e60c22140d5e2345cc3e775d3 | [] | no_license | kiriphorito/MoveAndTag-Manticore | 2e24a958f4941556b2d2714563718069cc5b208f | d07a3d8c0bacf34cf5f433384a6fd45170896b7a | refs/heads/master | 2021-01-20T11:40:49.232449 | 2017-02-26T14:08:48 | 2017-02-26T14:08:48 | 82,548,310 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 34,552 | py | #!/usr/bin/python
# -*- coding: utf-8 -*-
u"""
@brief: Path Planning Sample Code with Randamized Rapidly-Exploring Random Trees (RRT)
@author: AtsushiSakai
@license: MIT
"""
import shapely
from shapely.geometry import Polygon, LineString, Point, MultiPoint, GeometryCollection
import matplotlib.pyplot as plt
from ast import literal_eval
import datetime
import random
import math
import copy
def drawRobots(robots):
for (x,y) in robots:
plt.plot(x,y,"o")
def drawPolygonNoFill(points,color):
polygon = plt.Polygon(points,color=color,fill=False)
plt.gca().add_patch(polygon)
def drawPolygon(points):
polygon = plt.Polygon(points)
plt.gca().add_patch(polygon)
def drawPolygons(polygons):
try:
for xs in polygons:
drawPolygon(xs)
except ValueError:
print ("no polygons specified")
def drawPolygonNoFill(points,color):
polygon = plt.Polygon(points,color=color,fill=False)
plt.gca().add_patch(polygon)
def drawPolygonsNoFill(polygons):
try:
for xs in polygons:
drawPolygonNoFill(xs,'red')
except ValueError:
print ("no polygons specified")
class RRT():
u"""
Class for RRT Planning
"""
def __init__(self, start, goal, obstacleList,randArea,expandDis=1.0,goalSampleRate=5,maxIter=500):
u"""
Setting Parameter
start:Start Position [x,y]
goal:Goal Position [x,y]
obstacleList:obstacle Positions [[x,y,size],...]
randArea:Ramdom Samping Area [min,max]
"""
self.start=Node(start[0],start[1])
self.end=Node(goal[0],goal[1])
self.minrand = randArea[0]
self.maxrand = randArea[1]
self.expandDis = expandDis
self.goalSampleRate = goalSampleRate
self.maxIter = maxIter
def Planning(self,animation=True):
u"""
Pathplanning
animation: flag for animation on or off
"""
self.nodeList = [self.start]
while True:
# Random Sampling
if random.randint(0, 100) > self.goalSampleRate:
rnd = [random.uniform(self.minrand, self.maxrand), random.uniform(self.minrand, self.maxrand)]
else:
rnd = [self.end.x, self.end.y]
# Find nearest node
nind = self.GetNearestListIndex(self.nodeList, rnd)
# print(nind)
# expand tree
nearestNode =self.nodeList[nind]
theta = math.atan2(rnd[1] - nearestNode.y, rnd[0] - nearestNode.x)
newNode = copy.deepcopy(nearestNode)
newNode.x += self.expandDis * math.cos(theta)
newNode.y += self.expandDis * math.sin(theta)
newNode.parent = nind
if not self.__CollisionCheck(newNode, obstacleList,nearestNode):
continue
self.nodeList.append(newNode)
# check goal
dx = newNode.x - self.end.x
dy = newNode.y - self.end.y
d = math.sqrt(dx * dx + dy * dy)
if d <= self.expandDis:
if not self.__CollisionCheck(newNode, obstacleList,self.end):
continue
else:
#print("Goal!!")
break
if animation:
self.DrawGraph(rnd)
path=[[self.end.x,self.end.y]]
lastIndex = len(self.nodeList) - 1
while self.nodeList[lastIndex].parent is not None:
node = self.nodeList[lastIndex]
path.append([node.x,node.y])
lastIndex = node.parent
path.append([self.start.x, self.start.y])
return path
def DrawGraph(self,rnd=None):
u"""
Draw Graph
"""
import matplotlib.pyplot as plt
plt.clf()
if rnd is not None:
plt.plot(rnd[0], rnd[1], "^k")
for node in self.nodeList:
if node.parent is not None:
plt.plot([node.x, self.nodeList[node.parent].x], [node.y, self.nodeList[node.parent].y], "-g")
# plt.plot([ox for (ox,oy,size) in obstacleList],[oy for (ox,oy,size) in obstacleList], "ok", ms=size * 20)
drawPolygons(obstacleList)
plt.plot(self.start.x, self.start.y, "xr")
plt.plot(self.end.x, self.end.y, "xr")
plt.axis()
plt.grid(True)
plt.pause(0.01)
def GetNearestListIndex(self, nodeList, rnd):
dlist = [(node.x - rnd[0]) ** 2 + (node.y - rnd[1]) ** 2 for node in nodeList]
minind = dlist.index(min(dlist))
return minind
def __CollisionCheck(self, node,obstacleList,nearestNode):
x1 = nearestNode.x
y1 = nearestNode.y
x2 = node.x
y2 = node.y
first = [x1,y1]
second = [x2,y2]
return LineCollisionCheck(first,second,obstacleList)
def LineCollisionCheck(first,second, obstacleList):
from shapely import geometry,wkt
EPS = 1.2e-16 #======= may need to change this value depending on precision
x1 = first[0]
y1 = first[1]
x2 = second[0]
y2 = second[1]
line = geometry.LineString([(x1,y1),(x2,y2)])
#============ changed here =======
# for p1 in obstacleList:
#
# poly = geometry.Polygon(p1)
# ips = line.intersection(poly.boundary)
## print ips
# if type(ips) is Point:
## print "hello"
# if ips.distance(poly) < EPS:
## print "INTERSECT"
# return False
# elif type(ips) is MultiPoint:
# for i in ips:
# if (i.distance(poly) <EPS):
## print "INTERSECT2"
# return False
# elif type(ips) is GeometryCollection:
# continue
# else:
# print (ips,type(ips))
# return False
# return True
#============ changed here =======
for poly in obstacleList:
p1 = Polygon(poly)
if p1.buffer(EPS).intersects(line):
# print "collision"
return False
# print "safe"
return True
#============ changed here =======
def supersmoothie(smoothie,obstacleList):
path = smoothie
state = True
counter1 = 0
counter2 = len(path)-1
while state:
counter2 = len(path)-1
if counter1 == counter2:
state = False
break
coord1 = path[counter1]
for counter in range(counter2,0,-1):
coord2 = path[counter]
if LineCollisionCheck(coord1,coord2,obstacleList): #if no obstacle
del path[(counter1+1):(counter)]
break
counter1 += 1
return path
class Node():
u"""
RRT Node
"""
def __init__(self, x, y):
self.x = x
self.y = y
self.parent = None
def rrtpath(obstacles,startcoord,goalcoord,randAreas):
rrt = RRT(start=startcoord, goal=goalcoord,randArea = randAreas, obstacleList=obstacles)
path= rrt.Planning(animation=False)
# rrt.DrawGaph()
# plt.plot([x for (x,y) in path], [y for (x,y) in path],'-r')
# print path
smoothiePath = supersmoothie(path,obstacles)
plt.plot([x for (x,y) in smoothiePath], [y for (x,y) in smoothiePath],'-r')
smoothiePath.reverse()
#print smoothiePath
return smoothiePath
obstacleList = [[(0.10887588040823118,0.09142047210771191),(1.1039623485842764,-0.007589228694404357),(0.905942946980044,-1.997762165046495),(-3.074402925724136,-1.601723361838031),(-3.1734126265262517,-2.596809830014076),(-1.1832396901741624,-2.794829231618308),(-1.282249390976279,-3.789915699794353),(-13.223287009088821,-2.6017992901689646),(-13.42130641069305,-4.591972226521057),(-12.426219942517006,-4.690981927323172),(-13.0202781473297,-10.66150073637944),(-12.025191679153657,-10.760510437181557),(-11.431133474340962,-4.789991628125285),(-1.4802687925805116,-5.780088636146442),(-1.5792784933826283,-6.7751751043224875),(-0.5841920252065823,-6.874184805124604),(-0.18815322199811743,-2.8938389324204237),(0.8069332461779276,-2.99284863322254),(0.5099041437715794,-5.978108037750675),(1.5049906119476242,-6.077117738552792),(1.6040003127497404,-5.082031270376746),(2.599086780925785,-5.181040971178863),(1.2129509696961562,-19.112251525643497),(-4.75756783936011,-18.518193320830797),(-4.9555872409643476,-20.50836625718289),(1.0149315680919284,-21.102424461995586),(0.8169121664876853,-23.092597398347678),(3.8021715710158395,-23.389626500754026),(4.000190972620064,-21.399453564401938),(39.82330382695769,-24.963802793278123),(40.41736203177039,-18.993283984221858),(4.594249177432759,-15.428934755345662),(5.584346185453922,-5.47807007358521),(7.574519121806013,-5.676089475189441),(7.6735288226081275,-4.681003007013399),(10.658788227136265,-4.978032109419745),(10.757797927938379,-3.9829456412437065),(7.772538523410243,-3.6859165388373536),(7.8715482242123604,-2.6908300706613093),(1.9010294151560894,-2.0967718658486114),(2.0990488167603214,-0.10659892949652063),(3.0941352849363666,-0.2056086302986369),(3.1931449857384826,0.7894778378774103),(10.158750262970798,0.09640993226260114),(10.257759963772914,1.0914964004386465),(8.267587027420824,1.2895158020428774),(8.36659672822294,2.2846022702189224),(14.33711553727921,1.6905440654062291),(14.436125238081328,2.685630533582274),(8.465606429025057,3.2796887383949676),(8.56461612982717,4.274775206571014),(24.485999620643895,2.6906199937371635),(24.684019022248126,4.680792930089255),(8.762635531431403,6.264948142923105),(8.960654933035634,8.255121079275195),(7.965568464859588,8.354130780077309),(7.767549063255357,6.3639578437252196),(6.772462595079312,6.462967544527336),(7.168501398287773,10.443313417231517),(5.178328461935683,10.641332818835748),(4.78228965872722,6.660986946131567),(3.7872031905511765,6.759996646933682),(3.6881934897490614,5.764910178757638),(7.668539362453242,5.368871375549174),(7.47051996084901,3.378698439197083),(5.480347024496919,3.576717840801315),(5.3813373236948046,2.58163137262527),(7.371510260046895,2.3836119710210384),(7.272500559244779,1.388525502844993),(3.2921546865405977,1.7845643060534553),(3.3911643873427133,2.7796507742295002),(2.3960779191666686,2.8786604750316163),(3.1881555255835923,10.839352220439979),(2.193069057407549,10.938361921242095),(1.9950496558033173,8.948188984890006),(0.004876719451224712,9.146208386494235),(0.4999252234618028,14.12164072737446),(-0.4951612447142417,14.220650428176578),(-0.9902097487248201,9.245218087296351),(-1.9852962169008654,9.344227788098467),(-1.2922283112860569,16.309833065330782),(2.688117561418126,15.913794262122323),(2.7871272622202405,16.908880730298367),(-1.1932186104839406,17.304919533506826),(-0.9951992088797089,19.29509246985892),(19.90161662281724,17.21588875301449),(20.000626323619358,18.210975221190534),(27.961318069027723,17.418897614773613),(28.060327769829833,18.413984082949657),(20.09963602442147,19.20606168936658),(20.19864572522359,20.201148157542626),(-0.6981701064733642,22.280351874387055),(-0.4011410040670157,25.26561127891519),(-4.3814868767711985,25.661650082123654),(-5.965642089605046,9.740266591306927),(-6.960728557781089,9.839276292109044),(-1.4161853128626316,65.56411850996759),(-9.376877058270994,66.3561961163845),(-14.921420303189453,10.63135389852597),(-18.901766175893634,11.02739270173443),(-18.208698270278827,17.99299797896674),(-19.20378473845487,18.092007679768855),(-19.89685264406968,11.126402402536549),(-21.887025580421767,11.324421804140776),(-22.28306438363023,7.344075931436599),(1.599010852594854,4.967843112185823),(1.4009914509906234,2.9776701758337323),(0.4059049828145781,3.076679876635848),(0.30689528201246247,2.0815934084598027),(-6.658709995219853,2.774661314074613),(-6.75771969602197,1.7795748458985678),(0.20788558121034684,1.0865069402837573)],[(-24.246837974034875,-28.490829719121777),(-24.743325915820897,-29.358873337646244),(-27.34745677139434,-27.869409512288186),(-27.843944713180363,-28.737453130812685),(-26.97590109465588,-29.2339410725987),(-29.458340803586015,-33.574159165221104),(-28.590297185061505,-34.07064710700715),(-26.107857476131404,-29.730429014384715),(-25.23981385760692,-30.226916956170736),(-25.736301799392958,-31.094960574695207),(-24.868258180868466,-31.591448516481243),(-25.861234064440506,-33.32753575353023),(-24.993190445916074,-33.82402369531623),(-24.000214562343995,-32.087936458267265),(-23.1321709438195,-32.584424400053294),(-22.63568300203349,-31.716380781528816),(-21.76763938350899,-32.212868723314834),(-23.75359115065313,-35.685043197412774),(-26.35772200622651,-34.1955793720547),(-26.85420994801257,-35.063622990579184),(-24.250079092439112,-36.553086815937256),(-24.74656703422513,-37.42113043446172),(-23.01047979717619,-38.41410631803377),(-22.51399185539019,-37.54606269950931),(-21.64594823686566,-38.04255064129532),(-22.63892412043774,-39.778637878344306),(-24.37501135748671,-38.785661994772234),(-24.871499299272728,-39.65370561329672),(-23.135412062223804,-40.64668149686878),(-23.63190000400979,-41.514725115393276),(-22.76385638548528,-42.01121305717929),(-20.777904618341182,-38.53903858308134),(-19.90986099981669,-39.03552652486735),(-22.392300708746866,-43.37574461748979),(-31.072736893991625,-38.41086519962956),(-32.06571277756373,-40.14695243667849),(-23.385276592318977,-45.111831854538735),(-24.378252475890957,-46.847919091587706),(-28.718470568513336,-44.3654793826576),(-29.21495851029926,-45.23352300118211),(-27.478871273250494,-46.22649888475411),(-27.975359215036338,-47.094542503278625),(-31.447533689134232,-45.10859073613457),(-31.944021630920307,-45.97663435465901),(-30.20793439387137,-46.96961023823104),(-30.704422335657462,-47.83765385675554),(-35.04464042827985,-45.35521414782542),(-34.051664544707755,-43.619126910776444),(-34.91970816323219,-43.1226389689905),(-35.912684046804266,-44.85872620603948),(-36.78072766532869,-44.362238264253435),(-37.277215607114755,-45.230281882777916),(-36.4091719885903,-45.726769824563874),(-37.402147872162224,-47.46285706161295),(-45.21454043888265,-42.994465585538705),(-45.711028380668665,-43.86250920406323),(-50.05124647329119,-41.38006949513293),(-50.54773441507729,-42.24811311365735),(-46.20751632245484,-44.73055282258757),(-46.70400426424072,-45.59859644111208),(-38.8916116975204,-50.066987917186374),(-39.38809963930646,-50.935031535710806),(-41.12418687635535,-49.942055652138826),(-41.620674818141424,-50.81009927066326),(-39.88458758109249,-51.80307515423527),(-40.38107552287865,-52.671118772759655),(-39.51303190435404,-53.16760671454575),(-35.54112837006582,-46.2232577663499),(-34.673084751541374,-46.71974570813593),(-36.65903651868551,-50.191920182233844),(-34.92294928163646,-51.184896065805916),(-32.93699751449242,-47.712721591707975),(-31.2009102774434,-48.70569747528002),(-32.19388616101542,-50.441784712329),(-31.325842542490946,-50.93827265411502),(-29.339890775346838,-47.466098180017084),(-28.47184715682239,-47.962586121803085),(-28.968335098608424,-48.830629740327595),(-28.10029148008388,-49.327117682113595),(-26.610827654725956,-46.72298682654018),(-24.874740417676946,-47.715962710112194),(-25.867716301248908,-49.45204994716118),(-24.13162906419995,-50.44502583073324),(-23.635141122414055,-49.576982212208726),(-21.89905388536502,-50.56995809578078),(-22.892029768937146,-52.30604533282974),(-22.023986150412732,-52.8025332746158),(-21.031010266840603,-51.06644603756682),(-20.162966648316164,-51.562933979352835),(-19.169990764744092,-49.8268467423039),(-22.642165238842082,-47.8408949751598),(-18.17377376276776,-40.02850240843944),(-16.437686525718796,-41.021478292011466),(-19.41661417643492,-46.229740003158376),(-18.548570557910452,-46.72622794494441),(-15.569642907194252,-41.51796623379748),(-14.701599288669806,-42.01445417558353),(-18.673502822957982,-48.9588031237794),(-17.805459204433493,-49.45529106556539),(-16.81248332086139,-47.7192038285164),(-15.944439702336968,-48.215691770302485),(-20.412831178411377,-56.028084337022875),(-17.808700322837804,-57.51754816238086),(-13.340308846763563,-49.70515559566057),(-12.472265228239134,-50.201643537446586),(-16.444168762527234,-57.14599248564241),(-14.708081525478326,-58.13896836921445),(-12.722129758334253,-54.66679389511654),(-2.3056063360404835,-60.62464919654888),(-1.3126304524683619,-58.88856195949985),(-11.729153874762188,-52.930706658067635),(-10.736177991190118,-51.19461942101867),(-9.868134372665613,-51.691107362804615),(-9.371646430879542,-50.82306374428009),(-16.31599537907546,-46.85116020999197),(-15.323019495503349,-45.11507297294297),(-6.642583310258633,-50.07995239080324),(-5.649607426686526,-48.34386515375431),(-14.330043611931314,-43.37898573589403),(-13.833555670145318,-42.51094211736956),(-8.62529395899841,-45.48986976808571),(-7.632318075426419,-43.75378253103675),(-21.521015971818098,-35.80997546246032),(-21.0245280300321,-34.941931843935855),(-18.420397174458653,-36.43139566929394),(-17.923909232672553,-35.56335205076942),(-20.528040088246062,-34.073888225411395),(-20.031552146460037,-33.2058446068869),(-15.69133405383761,-35.688284315816986),(-15.194846112051579,-34.82024069729252),(-16.06288973057603,-34.32375275550647),(-15.069913847004027,-32.58766551845756),(-9.861652135857122,-35.566593169173736),(-10.854628019429134,-37.30268040622266),(-9.986584400904718,-37.79916834800872),(-8.993608517332634,-36.063081110959686),(-8.125564898808125,-36.559569052745694),(-7.629076957022125,-35.69152543422122),(-14.573425905217983,-31.71962189993304),(-13.58045002164594,-29.983534662884065),(-8.372188310499041,-32.96246231360016),(-7.875700368713023,-32.09441869507579),(-10.479831224286471,-30.60495486971766),(-9.486855340714438,-28.868867632668607),(-10.35489895923891,-28.37237969088267),(-11.347874842810956,-30.108466927931588),(-13.083962079859937,-29.115491044359608),(-12.090986196287885,-27.379403807310606),(-13.82707343333683,-26.386427923738584),(-13.330585491550817,-25.51838430521413),(-8.12232378040396,-28.497311955930265),(-7.129347896831874,-26.76122471888129),(-12.33760960797881,-23.78229706816507),(-11.841121666192787,-22.91425344964059),(1.1795326116744818,-30.361572576431005),(0.18655672810243829,-32.09765981347989),(-1.5495305089465425,-31.104683929907907),(-2.0460184507325394,-31.972727548432406),(-0.3099312136836119,-32.96570343200437),(-1.3029070972557086,-34.70179066905344),(-6.511168808402523,-31.72286301833727),(-7.0076567501885485,-32.59090663686165),(-1.7993950390416522,-35.56983428757784),(-2.295882980827667,-36.43787790610241),(-1.427839362303235,-36.934365847888465),(1.0546003466269305,-32.59414775526602),(3.658731202200382,-34.08361158062402),(4.155219143986418,-33.215567962099534),(1.5510882884129416,-31.726104136741554),(2.04757623019902,-30.858060518217),(6.387794322821403,-33.34050022714716),(6.884282264607407,-32.47245660862261),(11.224500357229893,-34.954896317552745),(11.720988299015872,-34.086852699028185),(7.380770206393517,-31.604412990098258),(7.8772581481793935,-30.736369371573765),(-10.351657840834768,-20.310122594067117),(-9.85516989904869,-19.44207897554267),(-10.723213517573202,-18.9455910337566),(-11.219701459359246,-19.813634652281053),(-47.67753343738744,1.0388589027317927),(-50.65646108810366,-4.1694028084151675),(-14.198629110075316,-25.021896363428016),(-14.695117051861338,-25.889939981952526),(-15.563160670385818,-25.393452040166505),(-16.05964861217184,-26.26149565869102),(-29.948346508563603,-18.31768859011467),(-30.941322392135604,-20.053775827163616),(-17.052624495743892,-27.997582895739992),(-19.535064204674015,-32.33780098836241),(-20.403107823198514,-31.84131304657641),(-19.41013193962644,-30.105225809527415),(-20.27817555815091,-29.60873786774138),(-21.27115144172298,-31.344825104790367),(-22.13919506024745,-30.848337163004338),(-21.642707118461438,-29.98029354447985),(-22.510750736985923,-29.48380560269384),(-21.02128691162784,-26.87967474712036),(-21.88933053015232,-26.38318680533435),(-22.385818471938343,-27.25123042385883),(-24.121905708987317,-26.25825454028678),(-24.61839365077332,-27.12629815881128),(-22.88230641372437,-28.11927404238332),(-23.378794355510404,-28.98731766090781)],[(45.20081810829839,2.198693603713543),(46.17018887941854,1.9530916735543375),(45.18778115878171,-1.9243914109262543),(46.157151929901886,-2.169993341085459),(47.13955965053867,1.7074897433951215),(48.108930421658826,1.4618878132359123),(48.354532351818044,2.431258584356081),(55.14012774965909,0.7120450732416423),(55.385729679818304,1.681415844361834),(53.446988137577996,2.1726197046802467),(54.42939585821482,6.050102789160792),(68.0005866538969,2.6116757669319846),(49.334839961797165,-71.06050283819941),(54.18169381739828,-72.28851248899544),(50.25206293485121,-87.79844482691769),(58.00702910381231,-89.7632602681915),(61.93665998635927,-74.25332793026902),(62.906030757479854,-74.49892986042826),(56.02917671302153,-101.64131145179253),(59.906659797502286,-102.62371917242933),(60.88906751813935,-98.7462360879487),(91.90893219398414,-106.60549785304322),(92.8913399146206,-102.72801476856276),(61.871475238776185,-94.868753003468),(66.78351384196029,-75.48133758106509),(67.7528846130803,-75.72693951122432),(86.41863130517979,-2.0547609060927727),(95.14296824526107,-4.265178277525488),(96.86218175637549,2.5204171203155603),(56.14860936932918,12.835698187001881),(56.88541515980677,15.74381050036238),(54.94667361756656,16.235014360680704),(51.508246595337695,2.6638235649986415),(48.60013428197725,3.400629355476238),(48.84573621213646,4.370000126596378),(47.8763654410163,4.615602056755581),(48.367569301334704,6.554343598995885),(50.306310843575005,6.063139738677501),(50.55191277373424,7.0325105097976),(48.613171231493894,7.523714370116037),(48.858773161653104,8.493085141236191),(47.88940239053292,8.738687071395411),(47.64380046037377,7.76931630027523),(46.67442968925359,8.01491823043444),(47.16563354957203,9.95365977267471),(46.196262778451874,10.199261702833924),(45.705058918133474,8.260520160593641),(44.73568814701327,8.506122090752836),(48.910920959719704,24.985425199795415),(60.54337021316148,22.03820203788503),(61.03457407347996,23.976943580125287),(63.94268638684039,23.240137789647708),(64.18828831699955,24.20950856076788),(61.280176003639134,24.94631435124549),(61.52577793379831,25.915685122365513),(49.89332868035652,28.862908284276024),(50.63013447083407,31.77102059763644),(49.66076369971399,32.01662252779561),(50.39756949019143,34.92473484115609),(49.428198719071446,35.1703367713153),(48.69139292859387,32.26222445795486),(47.72202215747368,32.50782638811402),(47.47642022731442,31.53845561699389),(23.242150949310854,37.678503870974),(22.014141298514563,32.8316500153731),(46.2484105765184,26.691601761393162),(45.26600285588167,22.814118676912575),(29.756070517959312,26.74374955945985),(27.79125507668565,18.988783390498536),(43.30118741460808,15.059152507951346),(42.56438162413046,12.151040194590916),(36.748156997409545,13.624651775546113),(36.50255506725035,12.655281004425955),(42.31877969397127,11.181669423470737),(41.82757583365285,9.242927881230445),(39.88883429141257,9.73413174154887),(39.64323236125336,8.764760970428723),(47.398198530214565,6.799945529155094),(46.906994669896164,4.8612039869147825),(45.937623898775996,5.1068059170739915),(45.6920219686168,4.137435145953841),(41.81453888413622,5.119842866590661),(41.568936953976994,4.150472095470501),(45.4464200384576,3.168064374833683)],[(-34.470071299470696,16.54613794841084),(-35.058908409090435,17.354389677969554),(-33.442404949972996,18.532063897209046),(-34.03124205959274,19.340315626767772),(-35.64774551871018,18.16264140752828),(-36.236582628329906,18.970893137087007),(-38.66133781700609,17.20438180822779),(-38.072500707386354,16.39613007866905),(-39.689004166503764,15.218455859429536),(-49.110397920419764,28.15048353236913),(-37.79487370659765,36.39420306704554),(-23.073945966104,16.18790982807754),(-19.0326873183104,19.132095376176387),(-33.75361505880397,39.338388615144254),(-32.137111599686655,40.516062834383746),(-32.725948709306316,41.324314563942494),(-31.10944525018884,42.50198878318193),(-31.69828235980868,43.31024051274066),(-33.31478581892613,42.1325662935012),(-33.90362292854584,42.94081802305989),(-50.876909249278924,30.575238721045288),(-51.46574635889863,31.38349045060414),(-53.082249818016166,30.205816231364473),(-57.204109585354246,35.863578338275644),(-58.012361314913115,35.274741228655756),(-56.834687095673615,33.65823776953829),(-60.067694013908444,31.302889331059422),(-64.77839089086649,37.76890316752914),(-65.58664262042525,37.18006605790926),(-60.87594574346719,30.71405222143965),(-62.49244920258464,29.536378002200134),(-61.90361209296492,28.728126272641532),(-56.24584998605381,32.84998603997967),(-55.06817576681435,31.233482580862223),(-57.49293095549058,29.466971252002843),(-56.90409384587082,28.65871952244413),(-54.479338657194624,30.425230851303468),(-53.89050154757489,29.6169791217447),(-54.69875327713352,29.028142012125006),(-42.922011084738635,12.863107420950525),(-43.73026281429737,12.274270311330774),(-43.141425704677594,11.466018581772055),(-40.716670516001486,13.232529910631323),(-36.00597363904339,6.7665160741615615),(-34.389470179925986,7.944190293401066),(-39.100167056884025,14.410204129870817),(-37.483663597766586,15.58787834911033),(-36.89482648814685,14.779626619551598),(-36.08657475858812,15.36846372917135),(-33.73122632010911,12.13545681093646),(-32.92297459055042,12.724293920556219),(-34.100648809789924,14.340797379673642),(-30.059390161996323,17.284982927772393),(-30.648227271616072,18.09323465733113),(-34.68948591940967,15.14904910923237),(-35.278323029029416,15.957300838791099)],[(10.627782914793798,-49.8988543995859),(11.159320827873213,-50.74588890122038),(9.465251824604236,-51.8089647273792),(7.339100172286599,-48.420826720841255),(6.492065670652125,-48.95236463392063),(7.555141496810892,-50.64643363718961),(5.861072493541947,-51.709509463348496),(6.392610406621339,-52.556543964982936),(8.08667940989033,-51.49346813882412),(8.618217322969738,-52.34050264045863),(7.7711828213352545,-52.872040553538035),(8.302720734414669,-53.71907505517252),(9.14975523604913,-53.18753714209307),(10.744368975287435,-55.728640646996574),(6.509196467115033,-58.38633021239367),(7.040734380194433,-59.23336471402817),(11.275906888366897,-56.57567514863104),(11.807444801446287,-57.422709650265524),(3.337099785101419,-62.738088781059695),(4.4001756112602575,-64.43215778432868),(12.870520627605195,-59.11677865353448),(13.933596453763963,-60.81084765680346),(12.239527450494982,-61.873923482962304),(12.77106536357442,-62.720957984596794),(14.46513436684336,-61.657882158437936),(14.99667227992279,-62.50491666007247),(-5.3321557593048095,-75.26182657397844),(-4.800617846225377,-76.10886107561296),(-5.6476523478599105,-76.64039898869238),(-6.710728174018566,-74.94632998542353),(-7.557762675653134,-75.47786789850284),(-6.494686849494283,-77.17193690177166),(-8.188755852763244,-78.23501272793068),(-9.783369592001527,-75.69390922302719),(-10.630404093636024,-76.22544713610667),(-9.035790354397978,-78.76655064100991),(-11.576893859301194,-80.36116438024834),(-11.04535594622184,-81.2081988818828),(-4.269079933145939,-76.95589557724749),(-3.737542020066501,-77.80293007888193),(11.509079009354028,-68.23524764345244),(12.040616922433557,-69.08228214508685),(9.499513417530245,-70.67689588432515),(10.031051330609444,-71.52393038595963),(10.87808583224389,-70.9923924728802),(11.941161658402773,-72.68646147614916),(12.788196160037426,-72.15492356306973),(11.725120333878444,-70.46085455980082),(12.572154835513047,-69.92931664672136),(13.103692748592517,-70.77635114835587),(13.950727250226974,-70.24481323527642),(12.35611351098867,-67.70370973037298),(13.203148012623139,-67.17217181729359),(15.860837578020202,-71.40734432546598),(-15.479438982455584,-91.07424710940448),(-16.542514808614435,-89.38017810613539),(-8.072169792269815,-84.06479897534123),(-9.135245618428367,-82.37072997207241),(-11.676349123331942,-83.9653437113106),(-15.397114514887974,-78.03610219986919),(-16.24414901652243,-78.5676401129486),(-12.523383624966357,-84.49688162438997),(-13.37041812660102,-85.02841953746949),(-17.622721431236283,-78.25214352439353),(-10.846445418160403,-73.99984021975813),(-11.909521244319315,-72.30577121648932),(-18.685797257395127,-76.5580745211246),(-19.74887308355403,-74.86400551785552),(-22.28997658845745,-76.45861925709389),(-15.911521631504414,-86.62303327670764),(-17.60559063477342,-87.68610910286644),(-18.668666460932066,-85.99204009959763),(-21.209769965835616,-87.58665383883576),(-18.020542487359048,-92.66886084864277),(-23.94978399880044,-96.38962624019877),(-53.715907131248144,-48.95569414866712),(-59.64514864268929,-52.67645954022305),(-29.879025510241938,-100.11039163175451),(-31.573094513511123,-101.17346745791325),(-29.446942861192838,-104.56160546445153),(-34.529149871000286,-107.75083294292766),(-33.9976119579205,-108.59786744456235),(-28.91540494811376,-105.40863996608584),(-27.852329121955044,-107.10270896935472),(19.58160296957632,-77.3365858369073),(20.644678795735004,-79.03065484017638),(22.338747799003976,-77.96757901401747),(14.897217015892071,-66.10909599113474),(16.59128601916107,-65.04602016497589),(17.65436184531997,-66.74008916824482),(19.348430848588798,-65.67701334208603),(18.285355022430068,-63.982944338817134),(19.132389524064386,-63.45140642573755),(31.889299437970685,-83.78023446496515),(34.43040294287405,-82.18562072572686),(21.67349302896802,-61.85679268649932),(22.520527530602457,-61.325254773419914),(28.898982487555504,-71.48966879303374),(30.593051490824465,-70.42659296687485),(26.872286099268496,-64.4973514554335),(30.260424105806496,-62.371199803115694),(29.19734827964763,-60.677130799846815),(25.809210273109628,-62.80328245216454),(24.214596533871443,-60.26217894726105),(33.531976051850705,-54.41526190338752),(33.0004381387713,-53.568227401753),(37.23561064694367,-50.91053783635592),(36.704072733864294,-50.063503334721396),(35.857038232229826,-50.59504124780089),(33.73088657991208,-47.20690324126298),(32.883852078277684,-47.73844115434232),(35.01000373059533,-51.12657916088025),(34.16296922896085,-51.658117073959744),(30.442203837404936,-45.72887556251833),(29.595169335770443,-46.26041347559776),(33.315934727326336,-52.18965498703921),(32.46890022569187,-52.72119290011854),(31.937362312612482,-51.87415839848412),(16.6907412831918,-61.441840833913616),(15.627665457032936,-59.74777183064464),(29.18021748318467,-51.24316522137395),(27.05406583086698,-47.85502721483602),(13.501513804715252,-56.35963382410671),(10.843824239318108,-52.124461315934276),(11.690858740952606,-51.59292340285486),(12.22239665403203,-52.43995790448935),(13.06943115566651,-51.908419991409936),(14.132506981825376,-53.602488994678886),(14.979541483459844,-53.07095108159949),(13.91646565730101,-51.376882078330524),(14.763500158935507,-50.8453441652511),(14.231962245856105,-49.99830966361662),(15.926031249125057,-48.93523383745781),(18.052182901442713,-52.323371843995716),(19.746251904711695,-51.260296017836865),(19.214713991632273,-50.41326151620239),(21.755817496535748,-48.818647776964106),(21.224279583456287,-47.9716132753296),(18.683176078552805,-49.56622701456792),(17.620100252394014,-47.87215801129895),(20.16120375729747,-46.2775442720607),(19.62966584421806,-45.43050977042622),(18.782631342583592,-45.96204768350566),(17.71955551642473,-44.26797868023668),(19.413624519693684,-43.20490285407781),(22.071314085090815,-47.44007536225024),(22.918348586725273,-46.908537449170794),(22.386810673645847,-46.06150294753635),(24.92791417854935,-44.46688920829816),(26.52252791778753,-47.00799271320142),(27.369562419422017,-46.47645480012204),(25.77494868018381,-43.93535129521869),(26.621983181818237,-43.403813382139205),(27.685059007977063,-45.09788238540818),(28.53209350961162,-44.56634447232869),(27.46901768345273,-42.87227546905981),(29.163086686721766,-41.80919964290105),(28.631548773642415,-40.96216514126659),(25.24341076710428,-43.08831679358423),(20.991107462469074,-36.312040780508354),(20.144072960834606,-36.84357869358779),(24.396376265469925,-43.619854706663666),(21.85527276056645,-45.2144684459019),(21.32373484748704,-44.36743394426742),(23.017803850755957,-43.304358118108546),(22.486265937676553,-42.45732361647409),(20.792196934407578,-43.52039944263289),(20.26065902132818,-42.673364940998404),(21.10769352296263,-42.14182702791897),(20.576155609883262,-41.29479252628457),(17.188017603345365,-43.42094417860225),(16.656479690265904,-42.573909676967716),(15.809445188631472,-43.10544759004716),(17.93559684094908,-46.493585596585056),(17.088562339314596,-47.02512350966448),(14.430872773917537,-42.7899510014921),(20.360114285358936,-39.06918560993616),(19.828576372279564,-38.22215110830167),(16.440438365741606,-40.34830276061938),(12.71967297418571,-34.41906124917794),(11.872638472551193,-34.95059916225735),(15.593403864107128,-40.87984067369881),(13.899334860838144,-41.942916499857574),(13.36779694775875,-41.09588199822308),(12.52076244612426,-41.62741991130251),(16.24152783768012,-47.55666142274392),(15.394493336045642,-48.08819933582332),(14.33141750988683,-46.39413033255436),(13.484383008252314,-46.925668245633744),(14.547458834411149,-48.61973724890274),(13.700424332776656,-49.15127516198211),(13.168886419697259,-48.30424066034767),(12.321851918062766,-48.835778573427106),(9.13262443958629,-43.75357156362015),(8.28558993795181,-44.285109476699574),(11.474817416428296,-49.36731648650649)]]
rand = (-120,107)
content = ""
starttime = datetime.datetime.now()
print "Path 21 of 111"
path = []
start = (-22.391522819322645,-77.04046549591655)
goal = (-11.26585765401034,-80.92416469298728)
print " Node 1 and 2 of 6"
path += rrtpath(obstacleList,start,goal,rand)
start = (-11.26585765401034,-80.92416469298728)
goal = (7.608419833556212,-89.08072326685475)
print " Node 2 and 3 of 6"
path += rrtpath(obstacleList,start,goal,rand)[1:]
start = (7.608419833556212,-89.08072326685475)
goal = (10.952382104555241,-91.03511609426907)
print " Node 3 and 4 of 6"
path += rrtpath(obstacleList,start,goal,rand)[1:]
start = (10.952382104555241,-91.03511609426907)
goal = (19.94952534224403,-91.84261723683866)
print " Node 4 and 5 of 6"
path += rrtpath(obstacleList,start,goal,rand)[1:]
start = (19.94952534224403,-91.84261723683866)
goal = (69.56419206774986,-103.33062783874577)
print " Node 5 and 6 of 6"
path += rrtpath(obstacleList,start,goal,rand)[1:]
pathStr = str(path)[1:-1] + ";"
pathStr = pathStr.replace("[", "(")
pathStr = pathStr.replace("]", ")")
f = open('smo2sol-24-path-21.txt', 'a+')
f.write(pathStr)
f.close
| [
"zcabwhy@ucl.ac.uk"
] | zcabwhy@ucl.ac.uk |
2c3e86903090f4e9df6b6db7b7638629a05d5502 | be4d32d35fd4af3cf4ecf3736c8e879d50b8ae37 | /Python/Django/belt2_exam/belt2_exam/wsgi.py | 35143390e13c3eca0342994133978c7b178f5e20 | [] | no_license | yangluo0901/CodingDojo_Assignment | f09bbec26f87b5b276fd6ef3c77f27d13518937e | 44ccb5158b12c1656793bac76f1a7a707b147982 | refs/heads/master | 2021-10-11T21:12:14.889189 | 2019-01-29T19:52:56 | 2019-01-29T19:52:56 | 105,716,841 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 414 | py | """
WSGI config for belt2_exam project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "belt2_exam.settings")
application = get_wsgi_application()
| [
"yangluo0901@gmail.com"
] | yangluo0901@gmail.com |
05d3dc754c74f90311c58a36f4604e7c832de9a1 | c838b6a37a7499e184bb892cd40f2f1fbb79002d | /Conceitos Básicos/modulos, pacotes e imports/foo.py | 2b9d3cf30fbb032711cba46d8b4463005d34598e | [] | no_license | danbailo/Python | f2920dd420a9ead29e6f38b64f0b38af0d1b5dbf | 3e3113d26bf9aee39e1ab4a3b2881c4c328143f3 | refs/heads/master | 2021-07-24T02:13:41.612337 | 2020-05-14T22:58:32 | 2020-05-14T22:58:32 | 169,300,125 | 1 | 1 | null | 2019-09-03T15:20:29 | 2019-02-05T19:35:09 | Python | UTF-8 | Python | false | false | 105 | py | import math
#raiz quadrada
print(5 ** 0.5)
print(math.sqrt(5))
from math import sqrt
print(sqrt(5))
| [
"danbailoufms@gmail.com"
] | danbailoufms@gmail.com |
ef2d337b974ef2e91f0a09d2fb51bc1e027a2c04 | 361b96b81858a0f620da36ec20da0ec22fc84fec | /hypercallgen.py | 32b30daa878fe82428cbc87da17c6bb939b0f0ef | [
"BSD-2-Clause"
] | permissive | daeken/Zookeeper | 88738beaa2eb8870d746981469b5e76df6266534 | b27f4bd17af1f5e1c7bbdd4a18017458822de648 | refs/heads/master | 2021-01-17T20:06:27.984878 | 2016-06-04T22:50:30 | 2016-06-04T22:50:30 | 37,281,709 | 37 | 2 | null | 2016-05-20T15:48:30 | 2015-06-11T19:31:08 | C++ | UTF-8 | Python | false | false | 3,977 | py | from yaml import load
calls = load(file('hypercalls.yaml'))
nhc = file('NightBeliever/Hypercall.cpp', 'w')
print >>nhc, '// Automatically generated by hypercallgen.py'
print >>nhc, '#include "NightBeliever.hpp"'
print >>nhc, '#include "../Hypercalls.hpp"'
print >>nhc
nhh = file('NightBeliever/Hypercall.hpp', 'w')
print >>nhh, '// Automatically generated by hypercallgen.py'
print >>nhh, '#pragma once'
print >>nhh, '#include "NightBeliever.hpp"'
print >>nhh, '#include "HypercallSupport.hpp"'
print >>nhh
zhc = file('HypercallDispatch.cpp', 'w')
print >>zhc, '// Automatically generated by hypercallgen.py'
print >>zhc, '#include "Zookeeper.hpp"'
print >>zhc
print >>zhc, 'void hypercall_dispatch(uint32_t call, uint32_t addr) {'
print >>zhc, '\tswitch(call) {'
zhh = file('Hypercalls.hpp', 'w')
print >>zhh, '// Automatically generated by hypercallgen.py'
print >>zhh, '#pragma once'
print >>zhh
zhl = file('Hypercall.hpp', 'w')
print >>zhl, '// Automatically generated by hypercallgen.py'
print >>zhl, '#pragma once'
print >>zhl, '#include "Zookeeper.hpp"'
print >>zhl, '#include "Hypercalls.hpp"'
print >>zhl
print >>zhl, 'void hypercall_dispatch(uint32_t call, uint32_t addr);'
print >>zhl
print >>zhl, 'class Hypercall {'
print >>zhl, 'public:'
def typemap(type):
if '*' in type or type == 'thread_ep_t':
return 'uint32_t'
else:
return type
def cast(a, b):
if a == b:
return ''
return '(%s) ' % b
for i, (name, args) in enumerate(calls.items()):
args = args if args is not None else []
ret = ''
nret = ''
rettype = 'void'
if args and 'return' in args[0]:
rettype = args[0]['return']
ret = 'auto ret = %s' % (cast(typemap(rettype), 'uint32_t'))
nret = 'return %s' % (cast('uint32_t', rettype))
del args[0]
args = [(an, at, typemap(at)) for x in args for (an, at) in x.items()]
print >>zhc, '\t\tcase %i: { // %s' % (i, name)
if len(args) > 1:
print >>zhh, 'typedef struct __attribute__((packed)) hypercall_%s {' % name
for arg, type, mapped in args:
print >>zhh, '\t%s %s;' % (mapped, arg)
print >>zhh, '} hypercall_%s_t;' % name
print >>zhh
print >>zhc, '\t\t\tauto sarg = box->cpu->read_memory<hypercall_%s_t>(addr);' % (name)
print >>zhc, '\t\t\t%sbox->hypercall->%s(%s);' % (ret, name, ', '.join('sarg.' + arg for arg, _, _ in args))
if rettype != 'void':
print >>zhc, '\t\t\tbox->cpu->hv->reg(EAX, ret);'
print >>zhl, '\t%s %s(%s);' % (typemap(rettype), name, ', '.join('%s %s' % (mapped, name) for name, _, mapped in args))
print >>nhh, '%s %s(%s);' % (rettype, name, ', '.join(type for _, type, _ in args))
print >>nhc, '%s %s(%s) {' % (rettype, name, ', '.join('%s %s' % (type, name) for name, type, _ in args))
print >>nhc, '\tvolatile hypercall_%s_t _sarg;' % name
for arg, type, mapped in args:
print >>nhc, '\t_sarg.%s = %s%s;' % (arg, cast(type, mapped), arg)
print >>nhc, '\t%svmcall(%i, (uint32_t) &_sarg);' % (nret, i)
print >>nhc, '}'
print >>nhc
elif len(args) == 1:
print >>zhc, '\t\t\t%sbox->hypercall->%s(%saddr);' % (ret, name, cast('uint32_t', args[0][2]))
if rettype != 'void':
print >>zhc, '\t\t\tbox->cpu->hv->reg(EAX, ret);'
print >>zhl, '\t%s %s(%s %s);' % (typemap(rettype), name, args[0][2], args[0][0])
print >>nhh, '%s %s(%s);' % (rettype, name, args[0][1])
print >>nhc, '%s %s(%s arg) {' % (rettype, name, args[0][1])
print >>nhc, '\t%svmcall(%i, %sarg);' % (nret, i, cast(args[0][1], 'uint32_t'))
print >>nhc, '}'
print >>nhc
else:
print >>zhc, '\t\t\t%sbox->hypercall->%s();' % (ret, name)
if rettype != 'void':
print >>zhc, '\t\t\tbox->cpu->hv->reg(EAX, ret);'
print >>zhl, '\t%s %s();' % (typemap(rettype), name)
print >>nhh, '%s %s();' % (rettype, name)
print >>nhc, '%s %s() {' % (rettype, name)
print >>nhc, '\t%svmcall(%i, NULL);' % (nret, i)
print >>nhc, '}'
print >>nhc
print >>zhc, '\t\t\tbreak;'
print >>zhc, '\t\t}'
print >>zhc, '\t}'
print >>zhc, '}'
print >>zhc
print >>zhl, '};'
print >>zhl
| [
"cody.brocious@gmail.com"
] | cody.brocious@gmail.com |
ad385490ca92fa12443faef3fbd626e74dcad0cb | f0d713996eb095bcdc701f3fab0a8110b8541cbb | /SFAjxGWk9AbfwbXFN_9.py | ec4e643e07b51a271e0aff50e66352e44bf41ae3 | [] | no_license | daniel-reich/turbo-robot | feda6c0523bb83ab8954b6d06302bfec5b16ebdf | a7a25c63097674c0a81675eed7e6b763785f1c41 | refs/heads/main | 2023-03-26T01:55:14.210264 | 2021-03-23T16:08:01 | 2021-03-23T16:08:01 | 350,773,815 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 540 | py | """
Create a function that will find all primes below a given number. Return the
result as a list.
### Examples
primes_below_num(5) ➞ [2, 3, 5]
primes_below_num(10) ➞ [2, 3, 5, 7]
primes_below_num(20) ➞ [2, 3, 5, 7, 11, 13, 17, 19]
### Notes
If `n` is a prime, it is included in the list.
"""
def is_prime(num):
for i in range(2, int(num ** 0.5)+1):
if num % i == 0:
return False
else:
return True
def primes_below_num(n):
return [num for num in range(2,n+1) if is_prime(num)]
| [
"daniel.reich@danielreichs-MacBook-Pro.local"
] | daniel.reich@danielreichs-MacBook-Pro.local |
5c85dad1f51e149d019abbd4bd4632e8fb570871 | 4a73648ecd3951b802e89e83a3bd9ef5b063af3d | /python_part/Leetcode/Data Structure/BinaryTree/easy/100. Same Tree/Solution.py | c61f1ad568845f63c4619fd72896ce1389db1f89 | [] | no_license | Allen-C-Guan/Leetcode-Answer | f5f9ee1348b86da914a564b7d23bf8904d5aa27f | f6e1374ef567590fee15ba6d1d6d65891233b5e1 | refs/heads/master | 2023-08-17T18:18:00.581743 | 2021-10-10T15:24:07 | 2021-10-10T15:24:07 | 257,017,331 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,228 | py | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
'''
写递归还是那个最重要思路:
在写递归的时候,一定要时刻记得,子问题已经被我的递归解决掉了。我不要去考虑如何去解决子问题的事情。我要做的就是如何利用子问题搞好当前的问题。
那么子问题到底怎么去得到? 我们只考虑递归出口处的最基本的子问题的结果就行了。其他非最基本子问题都会自然得以解决。
'''
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: # 递归功能判定当前位置及以下是否是相同的
if p is None and q is None: return True # 若q和p都是None,说明都到底了。而且还是相同的
if p is None or q is None: return False # 有且只有一个是None,不用继续判定了,直接就是False
return q.val == p.val and self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
# 剩下的是q和p都不是none的情况 需要左右子树都是相同的,自己也相同才是相同的
| [
"54201792+Allen-C-Guan@users.noreply.github.com"
] | 54201792+Allen-C-Guan@users.noreply.github.com |
d5aec38822b3b128eeaf56abe575341e4218020a | 5917a63a6d16de893f54e86a70f5d881648112c1 | /Py1_spc-master/Lec13/main3.py | 6b43b167c5bbb78d74f14b4340ee7242ebe54db7 | [] | no_license | litded/lessons | f14e8e68577d417fc87eaca1c426f535baa04e8b | af2e0f6cae61878a833a7eebd7c2509d930ede48 | refs/heads/master | 2023-08-22T00:49:50.362770 | 2021-10-16T20:33:01 | 2021-10-16T20:33:01 | 417,940,562 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 688 | py | """
Возвращаемые значения. Часть 2.
"""
def get_name():
name = "Alice"
return name
def get_void():
print("This function without RETURN!")
# Если функция не имеет при себе явно описанного блока return....
# то функция по умолчанию возвращает None
# Синтаксический сахар - можно написать голый return
return
if get_void() is None:
# Проверка на None
print()
ans1 = get_name()
print("From get_name():", ans1)
ans2 = get_void()
print("From get_void():", ans2)
# """
# В Java
# """
# void MyFunc(){
# } | [
"i.ivlev@westwing.ru"
] | i.ivlev@westwing.ru |
9fa5d51a54777a623a4635f83371d802bf01eef2 | 73189d4d0b39efe5864d25aff07d8338ab8f3110 | /build/geometry2-melodic-devel/tf2_ros/catkin_generated/pkg.develspace.context.pc.py | 61eafca3339558f2801d2b75f77e862900bdfb75 | [] | no_license | jungwoohan72/Multi_Robot_Search_And_Rescue | a64590a0f899682c2429400c5cb6d4d8a7d7fd99 | 3e70f9e9b895a96e045f19a05780b091c16f2e60 | refs/heads/main | 2023-07-06T14:03:58.980624 | 2021-08-01T05:15:02 | 2021-08-01T05:15:02 | 379,856,303 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 606 | py | # generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/morin-sol/ME652/src/geometry2-melodic-devel/tf2_ros/include".split(';') if "/home/morin-sol/ME652/src/geometry2-melodic-devel/tf2_ros/include" != "" else []
PROJECT_CATKIN_DEPENDS = "actionlib;actionlib_msgs;geometry_msgs;message_filters;roscpp;rosgraph;tf2;tf2_msgs;tf2_py".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "-ltf2_ros".split(';') if "-ltf2_ros" != "" else []
PROJECT_NAME = "tf2_ros"
PROJECT_SPACE_DIR = "/home/morin-sol/ME652/devel"
PROJECT_VERSION = "0.6.7"
| [
"dream4future@kaist.ac.kr"
] | dream4future@kaist.ac.kr |
0e163fba7e7b98551f709ab3c3c7d44014488322 | 26d6c34df00a229dc85ad7326de6cb5672be7acc | /msgraph-cli-extensions/beta/usersactions_beta/azext_usersactions_beta/vendored_sdks/usersactions/operations/_users_outlook_task_groups_task_folders_tasks_operations.py | 3fd9123f0a63d2df59395ed32b06612e15190636 | [
"MIT"
] | permissive | BrianTJackett/msgraph-cli | 87f92471f68f85e44872939d876b9ff5f0ae6b2c | 78a4b1c73a23b85c070fed2fbca93758733f620e | refs/heads/main | 2023-06-23T21:31:53.306655 | 2021-07-09T07:58:56 | 2021-07-09T07:58:56 | 386,993,555 | 0 | 0 | NOASSERTION | 2021-07-17T16:56:05 | 2021-07-17T16:56:05 | null | UTF-8 | Python | false | false | 5,104 | py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Callable, Dict, Generic, List, Optional, TypeVar
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
class UsersOutlookTaskGroupsTaskFoldersTasksOperations(object):
"""UsersOutlookTaskGroupsTaskFoldersTasksOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~users_actions.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def complete(
self,
user_id, # type: str
outlook_task_group_id, # type: str
outlook_task_folder_id, # type: str
outlook_task_id, # type: str
**kwargs # type: Any
):
# type: (...) -> List["models.MicrosoftGraphOutlookTask"]
"""Invoke action complete.
Invoke action complete.
:param user_id: key: id of user.
:type user_id: str
:param outlook_task_group_id: key: id of outlookTaskGroup.
:type outlook_task_group_id: str
:param outlook_task_folder_id: key: id of outlookTaskFolder.
:type outlook_task_folder_id: str
:param outlook_task_id: key: id of outlookTask.
:type outlook_task_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: list of MicrosoftGraphOutlookTask, or the result of cls(response)
:rtype: list[~users_actions.models.MicrosoftGraphOutlookTask]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[List["models.MicrosoftGraphOutlookTask"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
accept = "application/json"
# Construct URL
url = self.complete.metadata['url'] # type: ignore
path_format_arguments = {
'user-id': self._serialize.url("user_id", user_id, 'str'),
'outlookTaskGroup-id': self._serialize.url("outlook_task_group_id", outlook_task_group_id, 'str'),
'outlookTaskFolder-id': self._serialize.url("outlook_task_folder_id", outlook_task_folder_id, 'str'),
'outlookTask-id': self._serialize.url("outlook_task_id", outlook_task_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.post(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize(models.OdataError, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('[MicrosoftGraphOutlookTask]', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
complete.metadata = {'url': '/users/{user-id}/outlook/taskGroups/{outlookTaskGroup-id}/taskFolders/{outlookTaskFolder-id}/tasks/{outlookTask-id}/microsoft.graph.complete'} # type: ignore
| [
"japhethobalak@gmail.com"
] | japhethobalak@gmail.com |
82955319c63241b4f150c0b4add43218c218c9b3 | 97dfda123c402f814986784dc2bf25d78431bece | /bizaarproject/wsgi.py | f19099b762b73612c3682fc2488f554d1297937f | [] | no_license | danmcc3557/CA1 | 729ecfd6163520ff642a58e8ef3abc41571ea71c | 343acc5d1aa5ca5ffc43db2ab832475664ecfc48 | refs/heads/master | 2023-09-05T09:36:29.972906 | 2021-11-16T15:57:33 | 2021-11-16T15:57:33 | 426,693,075 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 403 | py | """
WSGI config for bizaarproject project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bizaarproject.settings')
application = get_wsgi_application()
| [
"="
] | = |
bd718c714e5759b6c8cb8d801d9ce9a6f8eb29ce | a1716a6ef649a843260fbfa4a66ccd8a6439094c | /Keras_L2_CNN/Week1_CNNclassification.py | 9484010243270d43cec294cc819919b4669e3534 | [] | no_license | pondjames007/TensorflowPractice | e28a8933303210c81c1c03edafe5036bff12f1b4 | e67df557cf383d74c7ec8a8cd009411b7cc5fd91 | refs/heads/master | 2020-07-12T10:59:01.284550 | 2020-01-15T20:41:56 | 2020-01-15T20:41:56 | 204,799,228 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,878 | py | """
Use CNN to do Classification
"""
import subprocess
subprocess.check_output(['wget', '--no-check-certificate',
'https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip',
'-O', './cats_and_dogs_filtered.zip'])
import os
import zipfile
import tensorflow as tf
from tensorflow._api.v1.keras.optimizers import RMSprop
from tensorflow._api.v1.keras.preprocessing.image import ImageDataGenerator
# The same as usual
local_zip = './cats_and_dogs_filtered.zip'
zip_ref = zipfile.ZipFile(local_zip, 'r')
zip_ref.extractall('./')
zip_ref.close()
base_dir = './cats_and_dogs_filtered'
train_dir = os.path.join(base_dir, 'train')
validation_dir = os.path.join(base_dir, 'validation')
# Directory with our training cat pictures
train_cats_dir = os.path.join(train_dir, 'cats')
# Directory with our training dog pictures
train_dogs_dir = os.path.join(train_dir, 'dogs')
# Directory with our validation cat pictures
validation_cats_dir = os.path.join(validation_dir, 'cats')
# Directory with our validation dog pictures
validation_dogs_dir = os.path.join(validation_dir, 'dogs')
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(150, 150, 3)),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(loss='binary_crossentropy',
optimizer=RMSprop(lr=1e-4),
metrics=['acc'])
##########################################
# Data Preprocessing
train_datagen = ImageDataGenerator(rescale = 1/255)
test_datagen = ImageDataGenerator(rescale= 1/255)
# Flow training images in batches of 20 using train_datagen generator
train_generator = train_datagen.flow_from_directory(
train_dir, # This is the source directory for training images
target_size= (150,150), # All images will be resized to 150x150
batch_size= 20,
class_mode= 'binary' # Since we use binary_crossentropy loss, we need binary labels
)
# Flow validation images in batches of 20 using test_datagen generator
validation_generator = test_datagen.flow_from_directory(
validation_dir,
target_size= (150,150),
batch_size= 20,
class_mode= 'binary'
)
history = model.fit_generator(
train_generator,
steps_per_epoch= 100, # 2000 images = batch_size * steps
epochs= 100,
validation_data= validation_generator,
validation_steps= 50, # 1000 images = batch_size * steps
verbose= 2
)
| [
"jameshuang@nyu.edu"
] | jameshuang@nyu.edu |
11dc59a1ed4fe55de8ea9b04875b8c923a194556 | 04a540847c1333c987a1957fd8d31197c594f6bb | /leetcode/617. Merge Two Binary Trees_1.py | 7f7c1b449e5502e4774a62f6c638faff9feb4958 | [] | no_license | k8440009/Algorithm | fd148269b264b580876c7426e19dbe2425ddc1ab | a48eba0ac5c9f2e10f3c509ce9d349c8a1dc3f0c | refs/heads/master | 2023-04-02T16:06:10.260768 | 2023-04-02T11:04:32 | 2023-04-02T11:04:32 | 200,506,643 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 671 | py | """
두 이진 트리 병합
- 재귀 탐색
"""
from typing import Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
if root1 and root2:
node = TreeNode(root1.val + root2.val)
node.left = self.mergeTrees(root1.left, root2.left)
node.right = self.mergeTrees(root1.right, root2.right)
return node
else:
return root1 or root2
| [
"k8440009@gmail.com"
] | k8440009@gmail.com |
ca14c4c9f925a129d4c8ddd3de75b5fb3e4c8267 | 3b1dc61a5d5f35e3e1ea612e21b160ce737dc85a | /dataprocess/transforms_v2.py | 22517d391bd2c6e4e88bc2f68cbf5b4fd43c1e43 | [] | no_license | ainklain/a_alloc | 2757c71347937c8ca62819bffca3a06506684851 | f9275d1bdf2a549e1d7fc4190e7fcfbe4526914a | refs/heads/master | 2023-05-09T14:16:29.509485 | 2021-06-01T06:11:06 | 2021-06-01T06:11:06 | 263,553,676 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,630 | py |
from abc import ABCMeta, abstractmethod
from functools import partial
import pandas as pd
import numpy as np
class BaseTransform:
@abstractmethod
def forward(self, x):
"""
x : [n_timesteps, n_features]
"""
pass
def __call__(self, x):
return self.forward(x)
class ToNumpy(BaseTransform):
def forward(self, x):
return np.array(x)
class RandomLike(BaseTransform):
def forward(self, x):
return np.random.randn(*x.shape)
class ToDataFrame(BaseTransform):
def __init__(self, idx, columns):
self.idx = idx
self.columns = columns
def forward(self, x):
return pd.DataFrame(x, index=self.idx, columns=self.columns)
class Rolling(BaseTransform):
def __init__(self, window):
self.window = window
def rolling(self, func, x):
n_timesteps, n_features = x.shape
y = np.zeros_like(x)
for i in range(n_timesteps):
y[i, :] = func(x[max(0, i-self.window):(i+1)])
return y
class RollingMean(Rolling):
def __init__(self, window=500):
super(RollingMean, self).__init__(window)
def forward(self, x):
return self.rolling(partial(np.nanmean, axis=0), x)
class RollingStd(Rolling):
def __init__(self, window=500):
super(RollingStd, self).__init__(window)
def forward(self, x):
return self.rolling(partial(np.nanstd, ddof=1, axis=0), x)
class RollingMeanReturn(Rolling):
def __init__(self, window=500):
super(RollingMeanReturn, self).__init__(window)
def forward(self, x):
return RollingMean(self.window)(RollingReturn(1)(x))
class RollingStdReturn(Rolling):
def __init__(self, window=500):
super(RollingStdReturn, self).__init__(window)
def forward(self, x):
return RollingStd(self.window)(RollingReturn(1)(x))
class RollingSharpe(Rolling):
def __init__(self, window=500):
super(RollingSharpe, self).__init__(window)
def forward(self, x):
func = lambda x: np.nanmean(x, axis=0) / np.nanstd(x, ddof=1, axis=0)
return self.rolling(func, x)
class RollingNormalize(Rolling):
def __init__(self, window=500):
super(RollingNormalize, self).__init__(window)
def forward(self, x):
func = lambda x: ((x - np.nanmean(x, axis=0)) / (np.nanstd(x, ddof=1, axis=0) + 1e-6))[-1, :]
return self.rolling(func, x)
class RollingReturn(Rolling):
def __init__(self, window=20):
super(RollingReturn, self).__init__(window)
def forward(self, x):
func = lambda x: x[-1, :] / x[0, :] - 1.
return self.rolling(func, x)
class RollingLogReturn(Rolling):
def __init__(self, window=20):
super(RollingLogReturn, self).__init__(window)
def forward(self, x):
func = lambda x: np.log(x[-1, :] / x[0, :])
return self.rolling(func, x)
class Transforms:
def __init__(self, transforms_list=[]):
self.transforms_list = transforms_list
def sequential(self, x):
for transforms_func, suffix in self.transforms_list:
x = transforms_func(x)
return x
def apply(self, x, columns, reduce='none'):
assert reduce in ['none', 'concat']
y = []
new_columns = []
for transforms_func, suffix in self.transforms_list:
y.append(transforms_func(x))
new_columns.append(["{}_{}".format(c, suffix) for c in columns])
if reduce == 'concat':
y = np.concatenate(y, axis=-1)
new_columns = sum(new_columns, [])
return y, new_columns
| [
"ainklain@gmail.com"
] | ainklain@gmail.com |
01bf709b05693158964bc867aa127048a38a2d94 | caa16eb083841e91a70603653928564f9fd3fed2 | /Python/permutations.py | f224894c8305bff31d52e3959b9957db1d273725 | [] | no_license | guker/letcode | ea5198a3678c5f6ab2aebd61dc882153a4af1199 | a8c93ead3db7fe86c66b4aee9a8c67cc71cf95ec | refs/heads/master | 2021-01-24T04:08:33.839243 | 2015-08-11T11:19:24 | 2015-08-11T11:19:24 | 40,593,439 | 3 | 3 | null | null | null | null | UTF-8 | Python | false | false | 926 | py | # Time: O(n!)
# Space: O(n)
#
# Given a collection of numbers, return all possible permutations.
#
# For example,
# [1,2,3] have the following permutations:
# [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
#
class Solution:
# @param num, a list of integer
# @return a list of lists of integers
def permute(self, num):
result = []
used = [False] * len(num)
self.permuteRecu(result, used, [], num)
return result
def permuteRecu(self, result, used, cur, num):
if len(cur) == len(num):
result.append(cur + [])
return
for i in xrange(len(num)):
if not used[i]:
used[i] = True
cur.append(num[i])
self.permuteRecu(result, used, cur, num)
cur.pop()
used[i] = False
if __name__ == "__main__":
print Solution().permute([1, 2, 3])
| [
"kamyu104@gmail.com"
] | kamyu104@gmail.com |
ed287ca023d35de1bf3c0f11d9c35b191d78a610 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03148/s414464368.py | d15bae3c7da7d8ff9d5dcb931e8bf5def1b30313 | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 762 | py |
n, k = list(map(int, input().split()))
sushi = []
for i in range(n):
sushi.append(list(map(int, input().split())))
point = 0
sushi_kind = set()
duplication = []
sushi.sort(key=lambda x: x[1],reverse = True)
for i in range(k):
point += sushi[i][1]
if sushi[i][0] in sushi_kind:
duplication.append(sushi[i])
else:
sushi_kind.add(sushi[i][0])
ans = point + pow(len(sushi_kind),2)
dup_index = len(duplication) - 1
for i in range(k,n):
if sushi[i][0] in sushi_kind:
continue
else:
if dup_index >= 0:
point -= duplication[dup_index][1]
dup_index -= 1
point += sushi[i][1]
sushi_kind.add(sushi[i][0])
ans = max(ans, point + pow(len(sushi_kind),2))
print(ans)
| [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
90aeaf2daeadbe22cf82d1503865189d04b0c0b9 | 905a113a02171b1f63beae3701b2e16ff9d6fdc8 | /examples/cache_performance.py | 126339c01359ffcb2c4eab5a35010c057b3fd0c2 | [
"MIT"
] | permissive | oldas1/beem | ff177aa502d96759f448aa85a7b53d689fa5da30 | d0b9642bfe5f5df3004a59d4923ea497e3a944b3 | refs/heads/master | 2022-04-23T05:07:20.532355 | 2020-04-26T22:16:42 | 2020-04-26T22:16:42 | 259,263,705 | 1 | 0 | NOASSERTION | 2020-04-27T09:15:44 | 2020-04-27T09:15:43 | null | UTF-8 | Python | false | false | 2,120 | py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
from datetime import datetime, timedelta
import time
import io
import logging
from beem.blockchain import Blockchain
from beem.block import Block
from beem.steem import Steem
from beem.utils import parse_time, formatTimedelta
from beem.nodelist import NodeList
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def stream_votes(stm, threading, thread_num):
b = Blockchain(steem_instance=stm)
opcount = 0
start_time = time.time()
for op in b.stream(start=23483000, stop=23485000, threading=threading, thread_num=thread_num,
opNames=['vote']):
sys.stdout.write("\r%s" % op['block_num'])
opcount += 1
now = time.time()
total_duration = now - start_time
print(" votes: %d, time %.2f" % (opcount, total_duration))
return opcount, total_duration
if __name__ == "__main__":
node_setup = 1
threading = True
thread_num = 8
timeout = 10
nodes = NodeList()
nodes.update_nodes(weights={"block": 1})
node_list = nodes.get_nodes()[:5]
vote_result = []
duration = []
stm = Steem(node=node_list, timeout=timeout)
b = Blockchain(steem_instance=stm)
block = b.get_current_block()
block.set_cache_auto_clean(False)
opcount, total_duration = stream_votes(stm, threading, thread_num)
print("Finished!")
block.set_cache_auto_clean(True)
cache_len = len(list(block._cache))
start_time = time.time()
block.clear_cache_from_expired_items()
clear_duration = time.time() - start_time
time.sleep(5)
cache_len_after = len(list(block._cache))
start_time = time.time()
print(str(block._cache))
clear_duration2 = time.time() - start_time
print("Results:")
print("%d Threads with https duration: %.2f s - votes: %d" % (thread_num, total_duration, opcount))
print("Clear %d items in %.3f s (%.3f s) (%d remaining)" % (cache_len, clear_duration, clear_duration2, cache_len_after))
| [
"holger@nahrstaedt.de"
] | holger@nahrstaedt.de |
519fb1f5952ab59f10dda6bdb75ef1f9cc40f907 | 4926667354fa1f5c8a93336c4d6e2b9f6630836e | /386.py | d21bb225b2d9bed78f30995e890cbafa6d2da357 | [] | no_license | nascarsayan/lintcode | 343b3f6e7071479f0299dd1dd1d8068cbd7a7d9e | 4da24b9f5f182964a1bdf4beaa8afc17eb7a70f4 | refs/heads/master | 2021-07-13T12:31:45.883179 | 2020-07-20T02:27:53 | 2020-07-20T02:27:53 | 185,825,565 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 626 | py | from collections import Counter
class Solution:
"""
@param s: A string
@param k: An integer
@return: An integer
"""
def lengthOfLongestSubstringKDistinct(self, s, k):
# write your code here
cnt, size, uniq, mx, st = Counter(), len(s), 0, 0, 0
if size == 0 or k == 0:
return 0
for fl in range(size):
cnt[s[fl]] += 1
if cnt[s[fl]] == 1:
uniq += 1
while (uniq > k):
cnt[s[st]] -= 1
if cnt[s[st]] == 0:
uniq -= 1
st += 1
mx = max(mx, fl - st + 1)
return mx
print(Solution().lengthOfLongestSubstringKDistinct("WORLD", 4))
| [
"nascarsayan@iitkgp.ac.in"
] | nascarsayan@iitkgp.ac.in |
49e56700e079ebb78c2d0034ded05de5131a63af | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02396/s429895421.py | 15b5b0136224eed7d5a04e6c701cea8d06421db2 | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 117 | py | x = 0
while True:
x += 1
n = input()
if int(n) == 0:
break
print("Case " + str(x) + ": " + n) | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
dffc7c9ec4364d54acd835e17b75c92f69201249 | f21452fada48d27d06bbb47dd934043e0f2e3fcf | /tests/algos/torch/test_utility.py | 16773faf5216c73f27814b698b138afd1dae7943 | [
"MIT"
] | permissive | kintatta/d3rl | ff72d794f42af7218df73c2102bc1a56e5cfa688 | 0674c4898927a53f36c5c875d8f217337f22d364 | refs/heads/master | 2022-12-26T05:20:55.280102 | 2020-10-09T14:29:11 | 2020-10-09T14:29:11 | 302,816,163 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,181 | py | import numpy as np
import torch
import pytest
import copy
from unittest.mock import Mock
from d3rlpy.algos.torch.utility import soft_sync, hard_sync
from d3rlpy.algos.torch.utility import set_eval_mode, set_train_mode
from d3rlpy.algos.torch.utility import freeze, unfreeze
from d3rlpy.algos.torch.utility import torch_api, train_api, eval_api
from d3rlpy.algos.torch.utility import map_location
from d3rlpy.algos.torch.utility import get_state_dict, set_state_dict
from d3rlpy.algos.torch.utility import compute_augemtation_mean
@pytest.mark.parametrize('tau', [0.05])
@pytest.mark.parametrize('input_size', [32])
@pytest.mark.parametrize('output_size', [32])
def test_soft_sync(tau, input_size, output_size):
module = torch.nn.Linear(input_size, output_size)
targ_module = torch.nn.Linear(input_size, output_size)
original = copy.deepcopy(targ_module)
soft_sync(targ_module, module, tau)
module_params = module.parameters()
targ_params = targ_module.parameters()
original_params = original.parameters()
for p, targ_p, orig_p in zip(module_params, targ_params, original_params):
assert torch.allclose(p * tau + orig_p * (1.0 - tau), targ_p)
@pytest.mark.parametrize('input_size', [32])
@pytest.mark.parametrize('output_size', [32])
def test_hard_sync(input_size, output_size):
module = torch.nn.Linear(input_size, output_size)
targ_module = torch.nn.Linear(input_size, output_size)
hard_sync(targ_module, module)
for p, targ_p in zip(module.parameters(), targ_module.parameters()):
assert torch.allclose(targ_p, p)
def test_map_location_with_cpu():
assert map_location('cpu:0') == 'cpu'
def test_map_location_with_cuda():
fn = map_location('cuda:0')
dummy = Mock()
dummy.cuda = Mock()
fn(dummy, '')
dummy.cuda.assert_called_with('cuda:0')
class DummyImpl:
def __init__(self):
self.fc1 = torch.nn.Linear(100, 100)
self.fc2 = torch.nn.Linear(100, 100)
self.optim = torch.optim.Adam(self.fc1.parameters())
self.device = 'cpu:0'
@torch_api
def torch_api_func(self, x):
assert isinstance(x, torch.Tensor)
@train_api
def train_api_func(self):
assert self.fc1.training
assert self.fc2.training
@eval_api
def eval_api_func(self):
assert not self.fc1.training
assert not self.fc2.training
def check_if_same_dict(a, b):
for k, v in a.items():
if isinstance(v, torch.Tensor):
assert (b[k] == v).all()
else:
assert b[k] == v
def test_get_state_dict():
impl = DummyImpl()
state_dict = get_state_dict(impl)
check_if_same_dict(state_dict['fc1'], impl.fc1.state_dict())
check_if_same_dict(state_dict['fc2'], impl.fc2.state_dict())
check_if_same_dict(state_dict['optim'], impl.optim.state_dict())
def test_set_state_dict():
impl1 = DummyImpl()
impl2 = DummyImpl()
impl1.optim.step()
assert not (impl1.fc1.weight == impl2.fc1.weight).all()
assert not (impl1.fc1.bias == impl2.fc1.bias).all()
assert not (impl1.fc2.weight == impl2.fc2.weight).all()
assert not (impl1.fc2.bias == impl2.fc2.bias).all()
chkpt = get_state_dict(impl1)
set_state_dict(impl2, chkpt)
assert (impl1.fc1.weight == impl2.fc1.weight).all()
assert (impl1.fc1.bias == impl2.fc1.bias).all()
assert (impl1.fc2.weight == impl2.fc2.weight).all()
assert (impl1.fc2.bias == impl2.fc2.bias).all()
def test_eval_mode():
impl = DummyImpl()
impl.fc1.train()
impl.fc2.train()
set_eval_mode(impl)
assert not impl.fc1.training
assert not impl.fc2.training
def test_train_mode():
impl = DummyImpl()
impl.fc1.eval()
impl.fc2.eval()
set_train_mode(impl)
assert impl.fc1.training
assert impl.fc2.training
@pytest.mark.skip(reason='no way to test this')
def test_to_cuda():
pass
@pytest.mark.skip(reason='no way to test this')
def test_to_cpu():
pass
def test_freeze():
impl = DummyImpl()
freeze(impl)
for p in impl.fc1.parameters():
assert not p.requires_grad
for p in impl.fc2.parameters():
assert not p.requires_grad
def test_unfreeze():
impl = DummyImpl()
freeze(impl)
unfreeze(impl)
for p in impl.fc1.parameters():
assert p.requires_grad
for p in impl.fc2.parameters():
assert p.requires_grad
def test_compute_augmentation_mean():
class DummyAugmentation:
def __init__(self):
self.n = 1
def transform(self, x):
y = x + self.n
self.n += 1
return y
aug = DummyAugmentation()
def func(x):
return x
x = np.random.random((100, 100))
y = compute_augemtation_mean(aug, 2, func, {'x': x}, 'x')
assert np.allclose(y, x + 1.5)
def test_torch_api():
impl = DummyImpl()
x = np.random.random((100, 100))
impl.torch_api_func(x)
def test_train_api():
impl = DummyImpl()
impl.fc1.eval()
impl.fc2.eval()
impl.train_api_func()
def test_eval_api():
impl = DummyImpl()
impl.fc1.train()
impl.fc2.train()
impl.eval_api_func()
| [
"takuma.seno@gmail.com"
] | takuma.seno@gmail.com |
d3d06096d1defdb26c8a4c8b37f08dd6a66326a9 | 31900bdf5648061a3093230711c5394e20b90436 | /usr/lib/enigma2/python/Plugins/Extensions/MediaPortal/resources/hosters/nowvideo.py | ce787e3da4c15042643933229ca18cdc3e5ba3fe | [] | no_license | linuxbox10/enigma2-plugin-extensions-mediaportal | aa6f14ecfc42ce91e22c487070541459a1ab820c | e6b388918c186442718e7200e03c83d0db260831 | refs/heads/master | 2021-05-01T18:50:50.332850 | 2018-02-10T11:33:48 | 2018-02-10T11:33:48 | 121,009,954 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,007 | py | # -*- coding: utf-8 -*-
from Plugins.Extensions.MediaPortal.plugin import _
from Plugins.Extensions.MediaPortal.resources.imports import *
from Plugins.Extensions.MediaPortal.resources.messageboxext import MessageBoxExt
def nowvideo(self, data, url, ck):
dataPost = {}
r = re.findall('input type="hidden".*?name="(.*?)".*?value="(.*?)"', data, re.S)
if r:
for name, value in r:
dataPost[name] = value
dataPost['submit'] = 'submit'
spezialagent = 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0'
getPage(url, method='POST', agent=spezialagent, cookies=ck, postdata=urlencode(dataPost), headers={'Content-Type':'application/x-www-form-urlencoded'}).addCallback(self.nowvideo_postData).addErrback(self.errorload)
else:
self.stream_not_found()
def nowvideo_postData(self, data):
stream_url = re.findall('<source src="(.*?\.mp4)" type=\'video/mp4\'>', data)
if stream_url:
print stream_url
self._callback(stream_url[-1])
else:
self.stream_not_found() | [
"jaysmith940@hotmail.co.uk"
] | jaysmith940@hotmail.co.uk |
12ced604368191dd1c0e6232d77673496d0d2e8e | 41f5fb2b76efe6f7a10c96ff197b0785e247ca12 | /gather/gathered/broward_dbhydro_get_reclen.py | e8dd4e3f83dbf8d3d9fc6b3de457931dcff8f266 | [
"BSD-2-Clause",
"BSD-Advertising-Acknowledgement"
] | permissive | jtwhite79/my_python_junk | 2f33d102e0e2875cf617b11dc31127678e9e9756 | 2ee0044f9b455d40e3b1967081aa7ac2dbfa64c9 | refs/heads/master | 2021-01-23T05:45:21.432421 | 2014-07-01T17:30:40 | 2014-07-01T17:30:40 | 4,587,435 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 321 | py | import os
import pestUtil as pu
import dbhydro_util
stg_dir = 'SW\\STG\\'
stg_files = os.listdir(stg_dir)
nrecs = 0
for file in stg_files:
#dbhydro_util.load_series(stg_dir+file)
#smp = pu.smp(stg_dir+file,load=True)
f = open(stg_dir+file,'r')
for line in f:
nrecs += 1
f.close()
print nrecs | [
"jtwhite79@yahoo.com"
] | jtwhite79@yahoo.com |
d0d3f1cddb1938eaf9cec4e4ac808a6f018b3dbc | d66818f4b951943553826a5f64413e90120e1fae | /hackerearth/Data Structures/Advanced Data Structures/Segment Trees/Binary Modulo (P2SME)/test.py | 38cf14c43973f5afa31a8065faaa7db712143015 | [
"MIT"
] | permissive | HBinhCT/Q-project | 0f80cd15c9945c43e2e17072416ddb6e4745e7fa | 19923cbaa3c83c670527899ece5c3ad31bcebe65 | refs/heads/master | 2023-08-30T08:59:16.006567 | 2023-08-29T15:30:21 | 2023-08-29T15:30:21 | 247,630,603 | 8 | 1 | MIT | 2020-07-22T01:20:23 | 2020-03-16T06:48:02 | Python | UTF-8 | Python | false | false | 657 | py | import io
import unittest
from contextlib import redirect_stdout
from unittest.mock import patch
class TestQ(unittest.TestCase):
@patch('sys.stdin.readline', side_effect=[
'1',
'01010101',
'5',
'0 1 3',
'1 2 1',
'0 2 5',
'1 3 1',
'0 0 7',
])
def test_case_0(self, input_mock=None):
text_trap = io.StringIO()
with redirect_stdout(text_trap):
import solution
self.assertEqual(text_trap.getvalue(),
'0\n' +
'3\n' +
'2\n')
if __name__ == '__main__':
unittest.main()
| [
"hbinhct@gmail.com"
] | hbinhct@gmail.com |
ff08e3a26e3fa26128b8e411866fcd197ff044bd | b33ad1c8560fc22a7e4ae9dec7f3c778b70941fa | /abc148/d.py | 14f317ce9ff9e5e018c034d644fb0d879fbef9bc | [] | no_license | Tommy-somen/atcoder_record | 36f226ffe6465dd5f8ae4986195510d00da46ffb | 0e549a72cec3b87accefc52d5cd56420251361b9 | refs/heads/master | 2023-08-16T10:23:39.609512 | 2021-09-27T11:38:57 | 2021-09-27T11:38:57 | 410,585,072 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 183 | py | n = int(input())
a = list(map(int,input().split()))
inx,cnt = 1,0
for i in range(n):
if a[i] != inx:
cnt += 1
else:
inx += 1
if n == cnt:
print(-1)
else:
print(cnt)
| [
"tomohiro1015w@gmail.com"
] | tomohiro1015w@gmail.com |
071da57b138d2467b16c09c78c676eae75380f31 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5706278382862336_1/Python/ashashwat/1.py | 302bf631a7f5094ce06dd7172c1f76cddcd563ad | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | Python | false | false | 645 | py | #!/usr/bin/env python
#-*- coding: utf-8 -*-
from collections import defaultdict
from math import factorial as f
from fractions import gcd as g
from fractions import Fraction as F
import math
T = int (raw_input ())
for t in range (1, T + 1):
a, b = [int (i) for i in raw_input ().split ('/')]
x = F (a, b)
ret = 0
cnt = 1
for i in range (100005):
if F (cnt * a, b) >= F (1, 1):
break
ret += 1
cnt *= 2
if x.denominator != 2 ** int (math.log (x.denominator, 2)): ret = -1
if ret != -1: print ("Case #{0}: {1}".format (t, ret))
else: print ("Case #{0}: impossible".format (t))
| [
"eewestman@gmail.com"
] | eewestman@gmail.com |
b17624f67c8834b65ec80699a3b2dde49b37c721 | cd77df7e0adf69f78cd86e0b09ffeba7acd7e1ba | /utilspy/diff.py | 184e637a7b20471b9bf5db2d6674cc8dc2076d0f | [] | no_license | huletlab/apparatus3-seq | 963b6ded59f53ae6ad714569559fe6f2cd08b610 | 3520f243c1d6d47dcf126cd4aa9e0f6cdaf2fb9a | refs/heads/master | 2021-01-25T04:53:00.095687 | 2014-02-21T04:42:41 | 2014-02-21T04:42:41 | 3,621,818 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 841 | py | import numpy
y1= numpy.fromfile('L:/software/apparatus3/seq/seqstxt/before_before.txt',dtype=float, sep=',')
y2= numpy.fromfile('L:/software/apparatus3/seq/seqstxt/before.txt',dtype=float, sep=',')
print y1.size, y2.size
f1 = open('L:/software/apparatus3/seq/seqstxt/before_before.txt','r')
f2 = open('L:/software/apparatus3/seq/seqstxt/before.txt','r')
fout = open('L:/software/apparatus3/seq/seqstxt/diffout.txt','w')
nchar=0
while 1:
char1 = f1.read(1)
char2 = f2.read(1)
fout.write(char1)
nchar = nchar + 1
if not char1: break
if char1 != char2:
print str(nchar), char1,char2
print f1.read(1)+f1.read(1)+f1.read(1)+f1.read(1)+f1.read(1)+f1.read(1)+f1.read(1)+f1.read(1)
break
f1.close()
f2.close()
fout.close()
| [
"pmd323@gmail.com"
] | pmd323@gmail.com |
dba3a1ea0b29976b73df3803a0788b26e7188cd7 | 163bbb4e0920dedd5941e3edfb2d8706ba75627d | /Code/CodeRecords/2749/60705/296130.py | c93d946e9c9cedca80126c57852ea83ad445ce2b | [] | no_license | AdamZhouSE/pythonHomework | a25c120b03a158d60aaa9fdc5fb203b1bb377a19 | ffc5606817a666aa6241cfab27364326f5c066ff | refs/heads/master | 2022-11-24T08:05:22.122011 | 2020-07-28T16:21:24 | 2020-07-28T16:21:24 | 259,576,640 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 18 | py | print(1 5 4 2 3)
| [
"1069583789@qq.com"
] | 1069583789@qq.com |
9b2fc253941199b259b7d2f419738079ede02bdd | 945890345cd16accfc1f47d717cfbf2c8f7165c0 | /src/dc/services/WalletAPIService.py | b7fbc768703609c724e52cf461bb430433a195c9 | [
"MIT"
] | permissive | dc-blockchain/dc-core | 658fc096c8eb628c61d763d1ebdb48fe23b97ac0 | fc6af8ce04d7b52f94c069f6ec05b0e419e07d70 | refs/heads/main | 2022-12-20T14:35:15.837056 | 2020-10-15T03:57:37 | 2020-10-15T03:57:37 | 304,181,968 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 20,068 | py | # coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
from pydclib.pydclib import bin2hstr
from dc.generated import dcwallet_pb2
from dc.generated.dcwallet_pb2_grpc import WalletAPIServicer
from dc.services.grpcHelper import GrpcExceptionWrapper
class WalletAPIService(WalletAPIServicer):
MAX_REQUEST_QUANTITY = 100
# TODO: Separate the Service from the node model
def __init__(self, walletd):
self._walletd = walletd
@GrpcExceptionWrapper(dcwallet_pb2.AddNewAddressResp)
def AddNewAddress(self, request: dcwallet_pb2.AddNewAddressReq, context) -> dcwallet_pb2.AddNewAddressResp:
resp = dcwallet_pb2.AddNewAddressResp()
try:
resp.address = self._walletd.add_new_address(request.height, request.hash_function.lower())
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.AddNewAddressResp)
def AddNewAddressWithSlaves(self, request: dcwallet_pb2.AddNewAddressWithSlavesReq, context) -> dcwallet_pb2.AddNewAddressResp:
resp = dcwallet_pb2.AddNewAddressResp()
try:
resp.address = self._walletd.add_new_address_with_slaves(request.height,
request.number_of_slaves,
request.hash_function.lower())
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.AddAddressFromSeedResp)
def AddAddressFromSeed(self, request: dcwallet_pb2.AddAddressFromSeedReq, context) -> dcwallet_pb2.AddAddressFromSeedResp:
resp = dcwallet_pb2.AddAddressFromSeedResp()
try:
resp.address = self._walletd.add_address_from_seed(seed=request.seed)
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.ListAddressesResp)
def ListAddresses(self, request: dcwallet_pb2.ListAddressesReq, context) -> dcwallet_pb2.ListAddressesResp:
resp = dcwallet_pb2.ListAddressesResp()
try:
resp.addresses.extend(self._walletd.list_address())
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.RemoveAddressResp)
def RemoveAddress(self, request: dcwallet_pb2.RemoveAddressReq, context) -> dcwallet_pb2.RemoveAddressResp:
resp = dcwallet_pb2.RemoveAddressResp()
try:
if not self._walletd.remove_address(request.address):
resp.code = 1
resp.error = "No such address found"
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.ValidAddressResp)
def IsValidAddress(self, request: dcwallet_pb2.ValidAddressReq, context) -> dcwallet_pb2.ValidAddressResp:
resp = dcwallet_pb2.ValidAddressResp()
try:
if not self._walletd.validate_address(request.address):
resp.code = 1
resp.error = "Invalid dc Address"
resp.valid = "False"
else:
resp.valid = "True"
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.GetRecoverySeedsResp)
def GetRecoverySeeds(self, request: dcwallet_pb2.GetRecoverySeedsReq, context) -> dcwallet_pb2.GetRecoverySeedsResp:
resp = dcwallet_pb2.GetRecoverySeedsResp()
try:
resp.hexseed, resp.mnemonic = self._walletd.get_recovery_seeds(request.address)
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.GetWalletInfoResp)
def GetWalletInfo(self, request: dcwallet_pb2.GetWalletInfoReq, context) -> dcwallet_pb2.GetWalletInfoResp:
resp = dcwallet_pb2.GetWalletInfoResp()
try:
resp.version, resp.address_count, resp.is_encrypted = self._walletd.get_wallet_info()
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.RelayTxnResp)
def RelayTransferTxn(self, request: dcwallet_pb2.RelayTransferTxnReq, context) -> dcwallet_pb2.RelayTxnResp:
resp = dcwallet_pb2.RelayTxnResp()
try:
resp.tx.MergeFrom(self._walletd.relay_transfer_txn(request.addresses_to,
request.amounts,
request.fee,
request.master_address,
request.signer_address,
request.ots_index))
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.RelayTxnResp)
def RelayTransferTxnBySlave(self,
request: dcwallet_pb2.RelayTransferTxnBySlaveReq,
context) -> dcwallet_pb2.RelayTxnResp:
resp = dcwallet_pb2.RelayTxnResp()
try:
resp.tx.MergeFrom(self._walletd.relay_transfer_txn_by_slave(request.addresses_to,
request.amounts,
request.fee,
request.master_address))
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.RelayTxnResp)
def RelayMessageTxn(self, request: dcwallet_pb2.RelayMessageTxnReq, context) -> dcwallet_pb2.RelayTxnResp:
resp = dcwallet_pb2.RelayTxnResp()
try:
resp.tx.MergeFrom(self._walletd.relay_message_txn(request.message,
request.fee,
request.master_address,
request.signer_address,
request.ots_index))
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.RelayTxnResp)
def RelayMessageTxnBySlave(self,
request: dcwallet_pb2.RelayMessageTxnBySlaveReq,
context) -> dcwallet_pb2.RelayTxnResp:
resp = dcwallet_pb2.RelayTxnResp()
try:
resp.tx.MergeFrom(self._walletd.relay_message_txn_by_slave(request.message,
request.fee,
request.master_address))
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.RelayTxnResp)
def RelayTokenTxn(self, request: dcwallet_pb2.RelayTokenTxnReq, context) -> dcwallet_pb2.RelayTxnResp:
resp = dcwallet_pb2.RelayTxnResp()
try:
resp.tx.MergeFrom(self._walletd.relay_token_txn(request.symbol,
request.name,
request.owner,
request.decimals,
request.addresses,
request.amounts,
request.fee,
request.master_address,
request.signer_address,
request.ots_index))
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.RelayTxnResp)
def RelayTokenTxnBySlave(self,
request: dcwallet_pb2.RelayTokenTxnBySlaveReq,
context) -> dcwallet_pb2.RelayTxnResp:
resp = dcwallet_pb2.RelayTxnResp()
try:
resp.tx.MergeFrom(self._walletd.relay_token_txn_by_slave(request.symbol,
request.name,
request.owner,
request.decimals,
request.addresses,
request.amounts,
request.fee,
request.master_address))
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.RelayTxnResp)
def RelayTransferTokenTxn(self, request: dcwallet_pb2.RelayTransferTokenTxnReq, context) -> dcwallet_pb2.RelayTxnResp:
resp = dcwallet_pb2.RelayTxnResp()
try:
resp.tx.MergeFrom(self._walletd.relay_transfer_token_txn(request.addresses_to,
request.amounts,
request.token_txhash,
request.fee,
request.master_address,
request.signer_address,
request.ots_index))
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.RelayTxnResp)
def RelayTransferTokenTxnBySlave(self,
request: dcwallet_pb2.RelayTransferTokenTxnBySlaveReq,
context) -> dcwallet_pb2.RelayTxnResp:
resp = dcwallet_pb2.RelayTxnResp()
try:
resp.tx.MergeFrom(self._walletd.relay_transfer_token_txn_by_slave(request.addresses_to,
request.amounts,
request.token_txhash,
request.fee,
request.master_address))
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.RelayTxnResp)
def RelaySlaveTxn(self, request: dcwallet_pb2.RelaySlaveTxnReq, context) -> dcwallet_pb2.RelayTxnResp:
resp = dcwallet_pb2.RelayTxnResp()
try:
resp.tx.MergeFrom(self._walletd.relay_slave_txn(request.slave_pks,
request.access_types,
request.fee,
request.master_address,
request.signer_address,
request.ots_index))
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.RelayTxnResp)
def RelaySlaveTxnBySlave(self, request: dcwallet_pb2.RelaySlaveTxnBySlaveReq, context) -> dcwallet_pb2.RelayTxnResp:
resp = dcwallet_pb2.RelayTxnResp()
try:
resp.tx.MergeFrom(self._walletd.relay_slave_txn_by_slave(request.slave_pks,
request.access_types,
request.fee,
request.master_address))
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.EncryptWalletResp)
def EncryptWallet(self, request: dcwallet_pb2.EncryptWalletReq, context) -> dcwallet_pb2.EncryptWalletResp:
resp = dcwallet_pb2.EncryptWalletResp()
try:
self._walletd.encrypt_wallet(request.passphrase)
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.LockWalletResp)
def LockWallet(self, request: dcwallet_pb2.LockWalletReq, context) -> dcwallet_pb2.LockWalletResp:
resp = dcwallet_pb2.LockWalletResp()
try:
self._walletd.lock_wallet()
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.UnlockWalletResp)
def UnlockWallet(self, request: dcwallet_pb2.UnlockWalletReq, context) -> dcwallet_pb2.UnlockWalletResp:
resp = dcwallet_pb2.UnlockWalletResp()
try:
self._walletd.unlock_wallet(request.passphrase)
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.ChangePassphraseResp)
def ChangePassphrase(self,
request: dcwallet_pb2.ChangePassphraseReq,
context) -> dcwallet_pb2.ChangePassphraseResp:
resp = dcwallet_pb2.ChangePassphraseResp()
try:
self._walletd.change_passphrase(request.oldPassphrase, request.newPassphrase)
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.TransactionsByAddressResp)
def GetTransactionsByAddress(self,
request: dcwallet_pb2.TransactionsByAddressReq,
context) -> dcwallet_pb2.TransactionsByAddressResp:
resp = dcwallet_pb2.TransactionsByAddressResp()
try:
mini_transactions, balance = self._walletd.get_mini_transactions_by_address(qaddress=request.address,
item_per_page=1000000,
page_number=1)
resp.mini_transactions.extend(mini_transactions)
resp.balance = balance
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.TransactionResp)
def GetTransaction(self, request: dcwallet_pb2.TransactionReq, context) -> dcwallet_pb2.TransactionResp:
resp = dcwallet_pb2.TransactionResp()
try:
tx, confirmations, block_number, block_header_hash = self._walletd.get_transaction(request.tx_hash)
resp.tx.MergeFrom(tx)
resp.confirmations = confirmations
resp.block_number = block_number
if block_header_hash:
resp.block_header_hash = block_header_hash
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.BalanceResp)
def GetBalance(self, request: dcwallet_pb2.BalanceReq, context) -> dcwallet_pb2.BalanceResp:
resp = dcwallet_pb2.BalanceResp()
try:
resp.balance = str(self._walletd.get_balance(request.address))
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.TotalBalanceResp)
def GetTotalBalance(self, request: dcwallet_pb2.TotalBalanceReq, context) -> dcwallet_pb2.TotalBalanceResp:
resp = dcwallet_pb2.TotalBalanceResp()
try:
resp.balance = str(self._walletd.get_total_balance())
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.OTSResp)
def GetOTS(self, request: dcwallet_pb2.OTSReq, context) -> dcwallet_pb2.OTSResp:
try:
ots_bitfield_by_page, next_unused_ots_index, unused_ots_index_found = self._walletd.get_ots(request.address)
resp = dcwallet_pb2.OTSResp(ots_bitfield_by_page=ots_bitfield_by_page,
next_unused_ots_index=next_unused_ots_index,
unused_ots_index_found=unused_ots_index_found)
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.HeightResp)
def GetHeight(self, request: dcwallet_pb2.HeightReq, context) -> dcwallet_pb2.HeightResp:
resp = dcwallet_pb2.HeightResp()
try:
resp.height = self._walletd.get_height()
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.BlockResp)
def GetBlock(self, request: dcwallet_pb2.BlockReq, context) -> dcwallet_pb2.BlockResp:
resp = dcwallet_pb2.BlockResp()
try:
resp.block.MergeFrom(self._walletd.get_block(request.header_hash))
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.BlockResp)
def GetBlockByNumber(self, request: dcwallet_pb2.BlockByNumberReq, context) -> dcwallet_pb2.BlockResp:
resp = dcwallet_pb2.BlockResp()
try:
resp.block.MergeFrom(self._walletd.get_block_by_number(request.block_number))
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.AddressFromPKResp)
def GetAddressFromPK(self, request: dcwallet_pb2.AddressFromPKReq, context) -> dcwallet_pb2.AddressFromPKResp:
resp = dcwallet_pb2.AddressFromPKResp()
try:
resp.address = self._walletd.get_address_from_pk(request.pk)
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
@GrpcExceptionWrapper(dcwallet_pb2.NodeInfoResp)
def GetNodeInfo(self, request: dcwallet_pb2.NodeInfoReq, context) -> dcwallet_pb2.NodeInfoResp:
resp = dcwallet_pb2.NodeInfoResp()
try:
node_info = self._walletd.get_node_info()
resp.version = node_info.info.version
resp.num_connections = str(node_info.info.num_connections)
resp.num_known_peers = str(node_info.info.num_known_peers)
resp.uptime = node_info.info.uptime
resp.block_height = node_info.info.block_height
resp.block_last_hash = bin2hstr(node_info.info.block_last_hash)
resp.network_id = node_info.info.network_id
except Exception as e:
resp.code = 1
resp.error = str(e)
return resp
| [
"72899004+dc-blockchain@users.noreply.github.com"
] | 72899004+dc-blockchain@users.noreply.github.com |
9f66cea721ed94503a91abf4e5c2522493626856 | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/303/usersdata/279/104634/submittedfiles/testes.py | 53b97a94b5771c022b839733178b493b365d624b | [] | no_license | rafaelperazzo/programacao-web | 95643423a35c44613b0f64bed05bd34780fe2436 | 170dd5440afb9ee68a973f3de13a99aa4c735d79 | refs/heads/master | 2021-01-12T14:06:25.773146 | 2017-12-22T16:05:45 | 2017-12-22T16:05:45 | 69,566,344 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,123 | py | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
import random
a=0
resultado='S'
escolha=['X','O']
imagem=[[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']]
posicao=[['00','01','02'],['10','11','12'],['20','21','22']]
while(True):
simbolo=(input('Qual simbolo deseja utilizar ? '))
if simbolo=='X' or simbolo=='O':
break
else :
print('Digite X ou O ')
sorteio=random.choice(escolha)
print(sorteio)
while(True):
if sorteio==simbolo :
while(True):
jogada=(int(input('Qual sua jogada ')))
for i in range (0,3,1):
for j in range (0,3,1):
if jogada==posicao[i][j] :
if imagem[i][j]==" " :
a=a+1
break
if sorteio=='O' :
sorteio='X'
else:
sorteio='O'
break
else:
while(True) :
jogada=random.choice(random.choice(posicao))
| [
"rafael.mota@ufca.edu.br"
] | rafael.mota@ufca.edu.br |
36954674c2332ab102d6485a7b8bd1c425885caa | 55faff05d101b7dc0a46669c3f8f2ae8e65d4ada | /hypnobox/migrations/0002_auto_20160909_1835.py | 869565d6f3ff28c8174c4217997b7c472317bd38 | [
"MIT"
] | permissive | fgmacedo/hypnobox-django | e1e81277b0e7ebc8b98b242b006d1148169ee88a | 6e4a5c4d1ec4c8b8931e6da91efb3a82320ca648 | refs/heads/develop | 2023-01-06T22:10:35.240230 | 2016-11-21T19:37:50 | 2016-11-21T19:37:50 | 67,744,850 | 0 | 0 | MIT | 2022-12-26T20:29:21 | 2016-09-08T22:30:01 | Python | UTF-8 | Python | false | false | 594 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-09-09 21:35
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hypnobox', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='lead',
name='phone_number',
field=models.CharField(max_length=9, validators=[django.core.validators.RegexValidator('^[\\d\\-]+$', message='Only numbers.')], verbose_name='phone number'),
),
]
| [
"fgmacedo@gmail.com"
] | fgmacedo@gmail.com |
206b925b820fcacb27ff7857bd5288f6fc093a32 | d4b344780e893a19d44aed51ebfe514c91e920c2 | /aliyun-python-sdk-ccc/aliyunsdkccc/request/v20170705/PublishSurveyRequest.py | 96cb91e4fea7a055ba9e817d8e78cb7f5fd0c69a | [
"Apache-2.0"
] | permissive | WenONGs/aliyun-openapi-python-sdk | 6d164160eac7a8020e3b8d1960d170e08d2c8f23 | b6de95a32030b421665c0833c9d64d92fcaf81c8 | refs/heads/master | 2023-04-28T06:36:51.740098 | 2021-05-17T09:37:00 | 2021-05-17T09:37:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,768 | py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
from aliyunsdkcore.request import RpcRequest
from aliyunsdkccc.endpoint import endpoint_data
class PublishSurveyRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'CCC', '2017-07-05', 'PublishSurvey','CCC')
self.set_method('POST')
if hasattr(self, "endpoint_map"):
setattr(self, "endpoint_map", endpoint_data.getEndpointMap())
if hasattr(self, "endpoint_regional"):
setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional())
def get_SurveyId(self):
return self.get_query_params().get('SurveyId')
def set_SurveyId(self,SurveyId):
self.add_query_param('SurveyId',SurveyId)
def get_InstanceId(self):
return self.get_query_params().get('InstanceId')
def set_InstanceId(self,InstanceId):
self.add_query_param('InstanceId',InstanceId)
def get_ScenarioId(self):
return self.get_query_params().get('ScenarioId')
def set_ScenarioId(self,ScenarioId):
self.add_query_param('ScenarioId',ScenarioId) | [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
532bd882071670d5c3b497865fb66647b7960f75 | bb71c03639010a22688a2955d6cd80ce3bf51a88 | /menu/migrations/0003_auto_20180918_1130.py | 895a760633b46be57554ed886e943970dd2a77f5 | [] | no_license | jhoover4/improve-a-django-project | 217732cf50eb48915b2566d657e67cd89551c5af | a9b35e708ca0fc72b4b7ee696631c233a718d820 | refs/heads/master | 2020-03-28T07:09:52.763927 | 2018-09-19T17:21:42 | 2018-09-21T02:36:42 | 147,884,443 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,070 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2018-09-18 18:30
from __future__ import unicode_literals
from django.db import migrations, models
import datetime
def update_expired_date(apps, schema_editor):
Menu = apps.get_model('menu', 'Menu')
for menu in Menu.objects.all():
try:
menu.expiration_date = datetime.datetime.strftime(menu.expiration_date, "%Y-%m-%d")
except TypeError:
menu.expiration_date = None
menu.save()
class Migration(migrations.Migration):
dependencies = [
('menu', '0002_auto_20160406_1554'),
]
operations = [
migrations.AlterField(
model_name='item',
name='ingredients',
field=models.ManyToManyField(related_name='ingredients', to='menu.Ingredient'),
),
migrations.AlterField(
model_name='menu',
name='expiration_date',
field=models.DateField(blank=True, help_text='MM/DD/YYYY', null=True),
),
migrations.RunPython(update_expired_date),
]
| [
"jordan@hoovermld.com"
] | jordan@hoovermld.com |
f8d5e32469f4508fc5b8a02b2e779ba4a9a468b7 | 8b8f1fceb9e72b385d269e2f8f0c2d49030064c1 | /ray/__init__.py | ffb599a385863b6dc59e332c58bcc886f3c23015 | [
"MIT"
] | permissive | pirica/ray | c93e82d20e6b919f1653d351f68ea18cbc521fe9 | b97583cd957fcdbaed0fd51ea0975ec5a63c27cf | refs/heads/master | 2021-10-22T04:40:20.123182 | 2019-03-08T05:39:50 | 2019-03-08T05:39:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 84 | py | from .http import HTTPClient as Client
__version__ = '0.0.1'
__author__ = 'mental'
| [
"m3nta1@yahoo.com"
] | m3nta1@yahoo.com |
8f7e3dc695f84d0a4697961f552a156a71ee55ad | 536538af28cfe40e10ff1ce469cd0f81e8b3a8fe | /binary_tree_zigzag_level_order_traversal.py | 347c5f2fa6f17ff8536a1eba3ab6e897881a62d2 | [] | no_license | ShunKaiZhang/LeetCode | 7e10bb4927ba8581a3a7dec39171eb821c258c34 | ede2a2e19f27ef4adf6e57d6692216b8990cf62b | refs/heads/master | 2021-09-01T07:41:03.255469 | 2017-12-25T19:22:18 | 2017-12-25T19:22:18 | 104,136,129 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,253 | py | # python3
# Given a binary tree, return the zigzag level order traversal of its nodes' values.
# (ie, from left to right, then right to left for the next level and alternate between).
# For example:
# Given binary tree [3,9,20,null,null,15,7],
# 3
# / \
# 9 20
# / \
# 15 7
# return its zigzag level order traversal as:
# [
# [3],
# [20,9],
# [15,7]
# ]
# My solution
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
out = []
def search(root, level):
if root is None:
return
if len(out) == level:
out.append([root.val])
else:
out[level].append(root.val)
search(root.left, level + 1)
search(root.right, level + 1)
return
search(root, 0)
for i in range(len(out)):
if i % 2 == 1:
out[i] = out[i][::-1]
return out
| [
"noreply@github.com"
] | ShunKaiZhang.noreply@github.com |
c8bb87201dfc25e8bc7419858495d30883748a4e | 768a6a9db5b2824f1e895b8b8e8047294806e80a | /Spider/Spider/tools/ip_clean.py | 94ee9c4afd45c8edcae74b7ed9d56b5fd20541ce | [] | no_license | heqiang/SearchEngine | 8ffb974ba33aa9ccc306de1caf4e7a3c5f4ca0ad | ccaa17d350fb34a0b0e984951bd8d82588f0a181 | refs/heads/master | 2023-05-28T13:05:34.568652 | 2022-03-10T07:46:13 | 2022-03-10T07:46:13 | 192,917,599 | 1 | 0 | null | 2023-05-22T22:17:35 | 2019-06-20T12:39:01 | Python | UTF-8 | Python | false | false | 1,508 | py | import pymysql
from fake_useragent import UserAgent
import requests
import threading
# import ThreadClass
conn=pymysql.connect(
host='localhost',
user='root',
password='1422127065',
db='bishe',
charset='utf8'
)
cursor=conn.cursor()
ua=UserAgent()
def delete(ip):
print("-|开始删除无用ip:{0}".format(ip))
delete_sql = 'delete from proxy_ip where ip="{0}"'.format(ip)
cursor.execute(delete_sql)
conn.commit()
return True
def jundge_ip(ip, port, category):
print("开始判断ip:{}".format(ip))
http_url = "https://www.baidu.com/"
proxy_url = "{0}://{1}:{2}".format(category, ip, port)
try:
proxy_dict = {
"http": proxy_url,
"https": proxy_url
}
res = requests.get(http_url, proxies=proxy_dict, timeout=3)
except Exception as e:
delete(ip)
return False
else:
code = res.status_code
if code == 200:
print("-|可用ip:{0}".format(ip))
return True
else:
print("-|不可用ip:{0}".format(ip))
delete(ip)
def clean_ip():
get_all_ip="select ip,port,category from proxy_ip "
result=cursor.execute(get_all_ip)
for res in cursor.fetchall():
ip = res[0]
port = res[1]
category = res[2]
# return ip,port,category
jundge_ip(ip, port, category)
# threads=[]
# clean_ip_threading=threading.Thread(target=clean_ip)
if __name__ == '__main__':
clean_ip() | [
"1422127065@qq.com"
] | 1422127065@qq.com |
bc7ad473abe58d55e81ef30ef051d12a3b8cd654 | 338c1ed5683f2195d86cab0cab521b95efd8cae8 | /easy/query_board.py | 44a9c550707f9cec6137c0bf74f63b6134863cca | [] | no_license | michaelrbock/codeeval | 59c1a7f531d8fdaeb609f269c1f3f93732825ec5 | 6239aaff776fad98971d40b00940bff60fb255c8 | refs/heads/master | 2020-05-04T22:26:29.937075 | 2014-07-26T19:03:01 | 2014-07-26T19:03:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 953 | py | import sys
# read in from file
input = open(sys.argv[1], 'r')
lines = []
for line in input:
lines.append(line.strip())
input.close()
board = []
for i in xrange(256):
board.append([0]*256)
for i, line in enumerate(lines):
command = line.split()
if command[0] == 'SetRow':
for j in xrange(256):
board[int(command[1])][j] = int(command[2])
elif command[0] == 'SetCol':
for j in xrange(256):
board[j][int(command[1])] = int(command[2])
elif command[0] == 'QueryRow':
sum = 0
for j in xrange(256):
sum += board[int(command[1])][j]
sys.stdout.write(str(sum))
if i != len(lines) - 1:
sys.stdout.write('\n')
elif command[0] == 'QueryCol':
sum = 0
for j in xrange(256):
sum += board[j][int(command[1])]
sys.stdout.write(str(sum))
if i != len(lines) - 1:
sys.stdout.write('\n')
| [
"mykel.bock@gmail.com"
] | mykel.bock@gmail.com |
d8c9abd59b7dc3024979c75851ef7bea79ed60de | 7620ded9ed5281d3d291972e908116168d03964f | /gram/migrations/0005_editor_bio.py | 6cd8819e795190f844390d4a5d6b4936f48b198d | [] | no_license | vincentmuya/the-gram | bd7da7e3e717101cfac72b1943dc198694d87527 | fa82a0ceb2aeb196ef420e5175e656fba0eda958 | refs/heads/master | 2021-01-25T13:17:17.195984 | 2018-03-14T11:42:01 | 2018-03-14T11:42:01 | 123,543,736 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 452 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-03-05 07:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gram', '0004_auto_20180305_0001'),
]
operations = [
migrations.AddField(
model_name='editor',
name='bio',
field=models.CharField(max_length=50, null=True),
),
]
| [
"vincentmuya13@gmail.com"
] | vincentmuya13@gmail.com |
7771c610ac7b1f571f35e1ba919e376887bf8d68 | c51eef37bb983a9c35635c7ccc96a0cf689a7438 | /sites/naver_finance/12_parse_bps.py | 93ac1878afb03ecae05b2298dbefd3fe31e7a43d | [] | no_license | Kyeongrok/python_crawler | 0a717b43be36584af1b0f7c1ad0c79108a5d11e0 | 5a5da8af7bb080f752a9a066741ac8adab136a3a | refs/heads/master | 2022-09-13T03:15:08.053639 | 2022-08-02T15:45:03 | 2022-08-02T15:45:03 | 124,719,435 | 40 | 34 | null | 2019-02-27T08:29:52 | 2018-03-11T03:20:32 | HTML | UTF-8 | Python | false | false | 2,685 | py | from libs.crawler import crawl
from bs4 import BeautifulSoup
import requests, re
'''
1.매출액-시총 >=0
2.(영업이익*10)배 - 시총 >=0
3.bps >=0 --- 0
4.bps-현재가 >=0 --- 0
5.(유보율:부채비율 = 5:1)<= 20%
6.이익잉여금 >=0
7.이익잉여금-시총 >=0
8.영업이익증가율 >=0
9.per <=10
10.roe >=0
11.roa >=0
12.pbr <=1
13.eps >=0
'''
url = 'https://finance.naver.com/item/main.nhn?code=005930'
# string = crawl(url)
# open('005930.html', 'w+').write(requests.get(url).text)
string = open('target_site_file/005930.html', encoding='utf-8').read()
replace_space = lambda x: re.sub("(\n|\t|\\xa0|,)", "", x)
def parse(string):
bsobj = BeautifulSoup(string, 'html.parser')
aside = bsobj.find('div', {'id':'aside'})
tab_con1 = aside.find('div', {'id':'tab_con1'})
pbr = 0
bps = 0
price_today = 0
sales = 0
net_income = 0
market_cap = 0
operating_profit = 0
# 최근 연간 매출
cop_analysis = bsobj.find('div', {'class':'section cop_analysis'})
tr_t_line = cop_analysis.find('thead').find_all('tr')[1].find_all('th')[2].text
last_year = replace_space(tr_t_line)
tbody_trs = cop_analysis.find('tbody').find_all('tr')
tbody_first_tr_tds = tbody_trs[0].find_all('td')
tbody_second_tr_tds = tbody_trs[1].find_all('td')
tbody_third_tr_tds = tbody_trs[2].find_all('td')
sales = float(replace_space(tbody_first_tr_tds[2].text))
# operating profit 영업이익
operating_profit = float(replace_space(tbody_second_tr_tds[2].text))
# 당기순이익
net_income = float(replace_space(tbody_third_tr_tds[2].text))
# 시가총액
div_first_tbody_trs = tab_con1.find('div', {'class':'first'}).find_all('tr')
market_cap = re.sub('(\t|\n)','',div_first_tbody_trs[0].find('td').text)
print(market_cap)
# 현재가sdf
try:
price_today = bsobj.find('p', {'class':'no_today'}).find('span', {'class':'blind'}).text.replace(',','')
price_today = float(price_today)
except Exception as e:
print(e)
try:
per_table = tab_con1.find('table', {'class': 'per_table'})
per_table_trs = per_table.find_all('tr')
ems = per_table_trs[2].find_all('em')
pbr = float(ems[0].text)
bps = float(ems[1].text.replace(',', ''))
except Exception as e:
print(e)
# 전년도 매출
return {'price_today':price_today, 'bps':bps, 'pbr':pbr, 'bps_minus_today_price':bps - price_today,
'sales{}'.format(last_year):sales*pow(10, 8), 'operating_profit{}'.format(last_year):
operating_profit * pow(10, 8), 'net_income':net_income * pow(10, 8)}
print(parse(string)) | [
"oceanfog1@gmail.com"
] | oceanfog1@gmail.com |
95157c9156dc3020513173a363cd01d4530d332b | 498fd33fcb93ea53ae8b55565a3cfac0d80ad424 | /bokeh/tests/test_resources.py | 7ce32ce4690d703e8eb5b44383cfe9d63b561639 | [] | no_license | HyperionAnalytics/bokeh | c23104978988a507e08dcf70894258bcd3562274 | 7d889505a2ec069041dbfa3daf70395e473c3bac | refs/heads/master | 2020-04-06T06:27:08.442860 | 2014-08-26T14:29:06 | 2014-08-26T14:29:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,223 | py | import unittest
import bokeh
import bokeh.resources as resources
WRAPPER = """$(function() {
foo
});"""
WRAPPER_DEV = '''require(["jquery", "main"], function($, Bokeh) {
$(function() {
foo
});
});'''
class TestResources(unittest.TestCase):
def test_basic(self):
r = resources.Resources()
self.assertEqual(r.mode, "inline")
def test_module_attrs(self):
self.assertEqual(resources.CDN.mode, "cdn")
self.assertEqual(resources.INLINE.mode, "inline")
def test_inline(self):
r = resources.Resources(mode="inline")
self.assertEqual(r.mode, "inline")
self.assertEqual(r.dev, False)
self.assertEqual(len(r.js_raw), 1)
self.assertEqual(len(r.css_raw), 1)
self.assertEqual(r.messages, [])
def test_cdn(self):
resources.__version__ = "1.0"
r = resources.Resources(mode="cdn", version="1.0")
self.assertEqual(r.mode, "cdn")
self.assertEqual(r.dev, False)
self.assertEqual(r.js_raw, [])
self.assertEqual(r.css_raw, [])
self.assertEqual(r.messages, [])
resources.__version__ = "1.0-1-abc"
r = resources.Resources(mode="cdn", version="1.0")
self.assertEqual(r.messages, [
{'text': "Requesting CDN BokehJS version '1.0' from Bokeh development version '1.0-1-abc'. This configuration is unsupported and may not work!",
'type': 'warn'}
])
def test_server(self):
r = resources.Resources(mode="server")
self.assertEqual(r.mode, "server")
self.assertEqual(r.dev, False)
self.assertEqual(r.js_raw, [])
self.assertEqual(r.css_raw, [])
self.assertEqual(r.messages, [])
def test_server_dev(self):
r = resources.Resources(mode="server-dev")
self.assertEqual(r.mode, "server")
self.assertEqual(r.dev, True)
self.assertEqual(len(r.js_raw), 1)
self.assertEqual(r.css_raw, [])
self.assertEqual(r.messages, [])
def test_relative(self):
r = resources.Resources(mode="relative")
self.assertEqual(r.mode, "relative")
self.assertEqual(r.dev, False)
self.assertEqual(r.js_raw, [])
self.assertEqual(r.css_raw, [])
self.assertEqual(r.messages, [])
def test_relative_dev(self):
r = resources.Resources(mode="relative-dev")
self.assertEqual(r.mode, "relative")
self.assertEqual(r.dev, True)
self.assertEqual(len(r.js_raw), 1)
self.assertEqual(r.css_raw, [])
self.assertEqual(r.messages, [])
def test_absolute(self):
r = resources.Resources(mode="absolute")
self.assertEqual(r.mode, "absolute")
self.assertEqual(r.dev, False)
self.assertEqual(r.js_raw, [])
self.assertEqual(r.css_raw, [])
self.assertEqual(r.messages, [])
def test_absolute_dev(self):
r = resources.Resources(mode="absolute-dev")
self.assertEqual(r.mode, "absolute")
self.assertEqual(r.dev, True)
self.assertEqual(len(r.js_raw), 1)
self.assertEqual(r.css_raw, [])
self.assertEqual(r.messages, [])
def test_argument_checks(self):
self.assertRaises(ValueError, resources.Resources, "foo")
for mode in ("inline", "cdn", "server", "server-dev", "absolute", "absolute-dev"):
self.assertRaises(ValueError, resources.Resources, mode, root_dir="foo")
for mode in ("inline", "server", "server-dev", "relative", "relative-dev", "absolute", "absolute-dev"):
self.assertRaises(ValueError, resources.Resources, mode, version="foo")
for mode in ("inline", "cdn", "relative", "relative-dev", "absolute", "absolute-dev"):
self.assertRaises(ValueError, resources.Resources, mode, root_url="foo")
def test_js_wrapper(self):
for mode in ("inline", "server", "cdn", "relative", "absolute"):
r = resources.Resources(mode)
self.assertEqual(r.js_wrapper("foo"), WRAPPER)
for mode in ("server-dev", "relative-dev", "absolute-dev"):
r = resources.Resources(mode)
self.assertEqual(r.js_wrapper("foo"), WRAPPER_DEV)
| [
"bryanv@continuum.io"
] | bryanv@continuum.io |
76cd8a5c69e8f31902f6c1f1bcebb1090e76716d | 24d8cf871b092b2d60fc85d5320e1bc761a7cbe2 | /eXe/rev3426-3457/left-trunk-3457/exe/webui/truefalseelement.py | f15603272a78cf3bc88de0f0603722b248534298 | [] | no_license | joliebig/featurehouse_fstmerge_examples | af1b963537839d13e834f829cf51f8ad5e6ffe76 | 1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad | refs/heads/master | 2016-09-05T10:24:50.974902 | 2013-03-28T16:28:47 | 2013-03-28T16:28:47 | 9,080,611 | 3 | 2 | null | null | null | null | UTF-8 | Python | false | false | 7,531 | py | """
TrueFalseElement is responsible for a block of question. Used by TrueFalseBlock.
"""
import logging
from exe.webui import common
from exe.webui.element import TextAreaElement
log = logging.getLogger(__name__)
class TrueFalseElement(object):
"""
TrueFalseElement is responsible for a block of question.
Used by TrueFalseBlock.
"""
def __init__(self, index, idevice, question):
"""
Initialize
"""
self.index = index
self.id = unicode(index) + "b" + idevice.id
self.idevice = idevice
self.question = question
if question.questionTextArea.idevice is None:
question.questionTextArea.idevice = idevice
if question.feedbackTextArea.idevice is None:
question.feedbackTextArea.idevice = idevice
if question.hintTextArea.idevice is None:
question.hintTextArea.idevice = idevice
self.question_question = TextAreaElement(question.questionTextArea)
self.question_feedback = TextAreaElement(question.feedbackTextArea)
self.question_hint = TextAreaElement(question.hintTextArea)
self.questionId = "question"+ unicode(index) + "b" + idevice.id
self.question_question.id = self.questionId
self.feedbackId = "feedback" + unicode(index) + "b" + idevice.id
self.question_feedback.id = self.feedbackId
self.hintId = "hint" + unicode(index) + "b" + idevice.id
self.question_hint.id = self.hintId
self.keyId = "Key" + unicode(index) + "b" + idevice.id
def process(self, request):
"""
Process arguments from the web server. Return any which apply to this
element.
"""
log.debug("process " + repr(request.args))
if self.questionId in request.args:
self.question_question.process(request)
if self.hintId in request.args:
self.question_hint.process(request)
if self.keyId in request.args:
if request.args[self.keyId][0] == "true":
self.question.isCorrect = True
log.debug("question " + repr(self.question.isCorrect))
else:
self.question.isCorrect = False
if self.feedbackId in request.args:
self.question_feedback.process(request)
if "action" in request.args and request.args["action"][0] == self.id:
for q_field in self.question.getRichTextFields():
q_field.ReplaceAllInternalAnchorsLinks()
q_field.RemoveAllInternalLinks()
self.idevice.questions.remove(self.question)
def renderEdit(self):
"""
Returns an XHTML string for editing this option element
"""
html = self.question_question.renderEdit()
html += _("True") + " "
html += common.option(self.keyId, self.question.isCorrect, "true")
html += _("False") + " "
html += common.option(self.keyId, not self.question.isCorrect, "false")
html += "<br/><br/>\n"
html += common.elementInstruc(self.idevice.keyInstruc)
html += self.question_feedback.renderEdit()
html += self.question_hint.renderEdit()
html += common.submitImage(self.id, self.idevice.id,
"/images/stock-cancel.png",
_("Delete question"))
html += "<br/><br/>\n"
return html
def renderQuestionView(self):
"""
Returns an XHTML string for viewing this question element
"""
is_preview = 0
html = self.renderQuestion(is_preview)
if self.question.hintTextArea.content<>"":
html += u'<span '
html += u'style="background-image:url(\'panel-amusements.png\');">'
html += u'\n<a onmousedown="Javascript:updateCoords(event);'
html += u'showMe(\'%s\', 350, 100);" ' % self.hintId
html += u'style="cursor:help;align:center;vertical-align:middle;" '
html += u'title="%s" \n' % _(u"Hint")
html += u'href="javascript:void(0);"> </a>'
html += u'</span>'
html += u'<div id="'+self.hintId+'" '
html += u'style="display:none; z-index:99;">'
html += u'<div style="float:right;" >'
html += u'<img alt="%s" ' % _('Close')
html += u'src="stock-stop.png" title="%s"' % _('Close')
html += u" onmousedown=\"Javascript:hideMe();\"/></div>"
html += u'<div class="popupDivLabel">'
html += _(u"Hint")
html += u'</div>\n'
html += self.question_hint.renderView()
html += u"</div>\n"
return html
def renderQuestionPreview(self):
"""
Returns an XHTML string for previewing this question element
"""
is_preview = 1
html = self.renderQuestion(is_preview)
html += " \n"
html += common.elementInstruc(self.question_hint.field.content,
"panel-amusements.png", "Hint")
return html
def renderQuestion(self, is_preview):
"""
Returns an XHTML string for viewing and previewing this question element
"""
log.debug("renderPreview called in the form of renderQuestion")
html = u"<br/><br/>"
if is_preview:
html += self.question_question.renderPreview() + "<br/>"
else:
html += self.question_question.renderView() + "<br/>"
html += _("True") + " "
html += self.__option(0, 2, "true") + " \n"
html += _("False") + " "
html += self.__option(1, 2, "false") + "\n"
return html
def __option(self, index, length, true):
"""Add a option input"""
html = u'<input type="radio" name="option%s" ' % self.id
html += u'id="%s%s" ' % (true, self.id)
html += u'onclick="getFeedback(%d,%d,\'%s\',\'truefalse\')"/>' % (
index, length, self.id)
return html
def renderFeedbackPreview(self):
"""
Merely a front-end to renderFeedbackView(), setting preview mode.
Note: this won't really matter all that much, since these won't yet
show up in exported printouts, BUT the image paths will be correct.
"""
return self.renderFeedbackView(is_preview=True)
def renderFeedbackView(self, is_preview=False):
"""
return xhtml string for display this option's feedback
"""
feedbackStr1 = _(u"Correct!") + " "
feedbackStr2 = _(u"Incorrect!") + " "
if not self.question.isCorrect:
feedbackStr1, feedbackStr2 = feedbackStr2, feedbackStr1
feedbackId1 = "0" + "b" + self.id
feedbackId2 = "1" + "b" + self.id
html = u'<div id="s%s" style="color: rgb(0, 51, 204);' % feedbackId1
html += u'display: none;">'
html += feedbackStr1 + '</div>\n'
html += u'<div id="s%s" style="color: rgb(0, 51, 204);' % feedbackId2
html += u'display: none;">'
html += feedbackStr2 + '</div>\n'
html += u'<div id="sfbk%s" style="color: rgb(0, 51, 204);' % self.id
html += u'display: none;">'
if is_preview:
html += self.question_feedback.renderPreview()
else:
html += self.question_feedback.renderView()
html += u'</div>\n'
return html
| [
"joliebig@fim.uni-passau.de"
] | joliebig@fim.uni-passau.de |
ea506ef01a97b930d0c98568de59edafa60481e6 | 7c7a0c7a3c52f1c3b8a504a7ed671647695137e0 | /venv/Scripts/pip-script.py | df90d1ed47de1a88d92f27de1c497534c8d75080 | [] | no_license | mdShakilHossainNsu2018/official_django | 6fd7ee8673c35ddcd1f9d5a89fac4f32b19ac27c | bfb1bbd198888abcd84dffc4d7e83faeb448b1e2 | refs/heads/master | 2022-04-26T10:37:05.521377 | 2020-04-29T21:20:29 | 2020-04-29T21:20:29 | 259,578,229 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 419 | py | #!C:\Users\shaki\PycharmProjects\official_django\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip'
__requires__ = 'pip==19.0.3'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('pip==19.0.3', 'console_scripts', 'pip')()
)
| [
"shakilnsu2018@gmail.com"
] | shakilnsu2018@gmail.com |
ebc4b94e23735fca73c40dd699aadcd0f48b36a6 | d2845579ea6aa51a2e150f0ffe6ccfda85d035ce | /kernel/components/intersection/param.py | 48273264044662812c515f52aad72fe6bbcc4fbf | [
"Apache-2.0"
] | permissive | as23187/WeFe | d8de9ff626f9f3e5d98e0850b0b717a80fd73e72 | ba92871d4b1d2eef6c606c34795f4575e84703bd | refs/heads/main | 2023-08-22T12:01:06.718246 | 2021-10-28T01:54:05 | 2021-10-28T01:54:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,315 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2021 Tianmian Tech. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Copyright 2019 The FATE Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
from common.python.utils.log_utils import get_logger
from kernel.base.params.base_param import BaseParam
from kernel.utils import consts
LOGGER = get_logger()
class EncodeParam(BaseParam):
"""
Define the encode method
Parameters
----------
salt: the src data string will be str = str + salt, default by empty string
encode_method: str, the encode method of src data string, it support md5, sha1, sha224, sha256, sha384, sha512,
default by None
base64: bool, if True, the result of encode will be changed to base64, default by False
"""
def __init__(self, salt='', encode_method='none', base64=False):
super().__init__()
self.salt = salt
self.encode_method = encode_method
self.base64 = base64
def check(self):
if type(self.salt).__name__ != "str":
raise ValueError(
"encode param's salt {} not supported, should be str type".format(
self.salt))
descr = "encode param's "
self.encode_method = self.check_and_change_lower(self.encode_method,
["none", "md5", "sha1", "sha224", "sha256", "sha384",
"sha512"],
descr)
if type(self.base64).__name__ != "bool":
raise ValueError(
"encode param's base64 {} not supported, should be bool type".format(self.base64))
LOGGER.debug("Finish encode parameter check!")
return True
class IntersectCache(BaseParam):
def __init__(self, use_cache=False, id_type=consts.PHONE, encrypt_type=consts.SHA256):
super().__init__()
self.use_cache = use_cache
self.id_type = id_type
self.encrypt_type = encrypt_type
def check(self):
if type(self.use_cache).__name__ != "bool":
raise ValueError(
"encode param's salt {} not supported, should be bool type".format(
self.use_cache))
descr = "intersect cache param's "
self.check_and_change_lower(self.id_type,
[consts.PHONE, consts.IMEI],
descr)
self.check_and_change_lower(self.encrypt_type,
[consts.MD5, consts.SHA256],
descr)
class IntersectParam(BaseParam):
"""
Define the intersect method
Parameters
----------
intersect_method: str, it supports 'rsa' and 'raw', default by 'raw'
random_bit: positive int, it will define the encrypt length of rsa algorithm. It effective only for
intersect_method is rsa
sync_intersect_ids: bool. In rsa, 'synchronize_intersect_ids' is True means promoter or provider will send
intersect results to the others, and False will not. while in raw, 'synchronize_intersect_ids' is
True means the role of "join_role" will send intersect results and the others will get them.
Default by True.
join_role: str, it supports "promoter" and "provider" only and effective only for raw. If it is "promoter",
the provider will send its ids to promoter and find the intersection of
ids in promoter; if it is "provider", the promoter will send its ids. Default by "promoter".
with_encode: bool, if True, it will use encode method for intersect ids. It effective only for "raw".
encode_params: EncodeParam, it effective only for with_encode is True
only_output_key: bool, if false, the results of intersection will include key and value which from input data;
if true, it will just include key from input data and the value will be empty or some useless
character like "intersect_id"
repeated_id_process: bool, if true, intersection will process the ids which can be repeatable
repeated_id_owner: str, which role has the repeated ids
"""
def __init__(self, intersect_method=consts.DH, random_bit=128, sync_intersect_ids=True, join_role="promoter",
with_encode=False, only_output_key=False, encode_params=EncodeParam(),
intersect_cache_param=IntersectCache(), repeated_id_process=False, repeated_id_owner="promoter",
with_label=False, save_dataset=False):
super().__init__()
self.intersect_method = intersect_method
self.random_bit = random_bit
self.sync_intersect_ids = sync_intersect_ids
self.join_role = join_role
self.with_encode = with_encode
self.encode_params = copy.deepcopy(encode_params)
self.only_output_key = only_output_key
self.intersect_cache_param = intersect_cache_param
self.repeated_id_process = repeated_id_process
self.repeated_id_owner = repeated_id_owner
self.with_label = with_label
self.save_dataset = save_dataset
def check(self):
descr = "intersect param's"
self.intersect_method = self.check_and_change_lower(self.intersect_method,
[consts.DH],
descr)
if type(self.random_bit).__name__ not in ["int"]:
raise ValueError("intersect param's random_bit {} not supported, should be positive integer".format(
self.random_bit))
if type(self.sync_intersect_ids).__name__ != "bool":
raise ValueError(
"intersect param's sync_intersect_ids {} not supported, should be bool type".format(
self.sync_intersect_ids))
self.join_role = self.check_and_change_lower(self.join_role,
[consts.PROMOTER, consts.PROVIDER],
descr)
if type(self.with_encode).__name__ != "bool":
raise ValueError(
"intersect param's with_encode {} not supported, should be bool type".format(
self.with_encode))
if type(self.only_output_key).__name__ != "bool":
raise ValueError(
"intersect param's only_output_key {} not supported, should be bool type".format(
self.only_output_key))
if type(self.repeated_id_process).__name__ != "bool":
raise ValueError(
"intersect param's repeated_id_process {} not supported, should be bool type".format(
self.repeated_id_process))
self.repeated_id_owner = self.check_and_change_lower(self.repeated_id_owner,
[consts.PROMOTER],
descr)
self.encode_params.check()
LOGGER.debug("Finish intersect parameter check!")
return True
| [
"winter.zou@welab-inc.com"
] | winter.zou@welab-inc.com |
9b17f09e95d1c31eb22816739bc460fffcf1885d | 21f98d8bb31264c94e7a98fb8eb806d7f5bd396e | /322_Coin_Change.py | 78e841de38e65f2f56347f24746e9b37d96a52fe | [] | no_license | mcfair/Algo | e1500d862a685e598ab85e8ed5b68170632fdfd0 | 051e2a9f6c918907cc8b665353c46042e7674e66 | refs/heads/master | 2021-10-31T01:25:46.917428 | 2021-10-08T04:52:44 | 2021-10-08T04:52:44 | 141,460,584 | 2 | 2 | null | null | null | null | UTF-8 | Python | false | false | 513 | py | class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
#unlimited coin change
#need[b] := #of coins to make a change 'b'
need =[0] + [float('inf')]*amount
for c in coins:
for b in range(c, amount+1):
need[b] = min(need[b], need[b-c]+1)
return need[amount] if need[amount] < float('inf') else -1
| [
"noreply@github.com"
] | mcfair.noreply@github.com |
23df93d317d5228698133b7e6d3e0235c71ba6cc | 5bd5de114f8a0721cee58bb3eb9d993095fd0876 | /stock_custom/wizard_product_mutation.py | 9261875ecf31147486afcafadbedbf20feee8f14 | [] | no_license | hendrasaputra0501/o7kite_dmst | 35ce25494cf536873f3b6eaffc4a78bf02ddeb42 | e8ea609541b831511ba1f3f688d97732dfa879da | refs/heads/master | 2020-04-25T01:31:33.471461 | 2019-02-25T01:48:07 | 2019-02-25T01:48:07 | 172,410,746 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,857 | py | from openerp.osv import fields,osv
import openerp.addons.decimal_precision as dp
from tools.translate import _
from lxml import etree
from openerp.osv.orm import setup_modifiers
from datetime import datetime
import time
class wizard_product_mutation(osv.osv_memory):
_inherit = "wizard.product.mutation"
def action_open_window(self, cr, uid, ids, context=None):
""" To open products mutation to given duration/period
@param self: The object pointer.
@param cr: A database cursor
@param uid: ID of the user currently logged in
@param ids: An ID or list of IDs (but only the first ID will be processed)
@param context: A standard dictionary
@return: dictionary of action act_window product
"""
if context is None:
context = {}
wizard = self.read(cr, uid, ids, ['from_date', 'to_date','product_type'], context=context)
if wizard:
data_obj = self.pool.get('ir.model.data')
domain = []
if wizard[0]['product_type']=='finish_good':
res_model = 'product.blend'
result = data_obj._get_id(cr, uid, 'stock_custom', 'view_product_blend_tree2_mutation')
elif wizard[0]['product_type']=='raw_material':
res_model = 'product.rm.category'
result = data_obj._get_id(cr, uid, 'stock_custom', 'view_product_rm_category_tree2_mutation')
else:
res_model = 'product.product'
result = data_obj._get_id(cr, uid, 'master_data_custom', 'view_product_tree2_mutation')
domain = [('product_type','=',wizard[0]['product_type']),('type','<>','service')]
view_id = data_obj.browse(cr, uid, result).res_id
from_date = wizard[0]['from_date']!=False and \
datetime.strptime(wizard[0]['from_date'],'%Y-%m-%d').strftime('%Y-%m-%d 00:00:00') or False
to_date = wizard[0]['to_date'] and \
datetime.strptime(wizard[0]['to_date'],'%Y-%m-%d').strftime('%Y-%m-%d 23:59:59') or False
return {
'name': _('Laporan Pertanggungjawaban Mutasi'),
'view_type': 'form',
'view_mode': 'tree',
'res_model': res_model,
'view_id':[view_id],
'type': 'ir.actions.act_window',
'context': {'from_date': from_date or False,
'to_date': to_date or False,},
"domain":domain,
}
def export_excel(self, cr, uid, ids, context=None):
if context is None:
context = {}
wizard = self.browse(cr,uid,ids,context)[0]
datas = {
'model': 'wizard.product.mutation',
'from_date' : wizard.from_date,
'to_date' : wizard.to_date,
'product_type':wizard.product_type,
}
if wizard.product_type=='finish_good':
report_name = 'blend.mutation.report.xls'
elif wizard.product_type=='raw_material':
report_name = 'rm.categ.mutation.report.xls'
else:
report_name = 'product.mutation.report.xls'
return {
'type': 'ir.actions.report.xml',
'report_name': report_name,
'report_type': 'xls',
'datas': datas,
}
wizard_product_mutation() | [
"hendrasaputra0501@gmail.com"
] | hendrasaputra0501@gmail.com |
8a84fe7bc3c0fc0894fde1bfc9b969fb327fa136 | 34de2b3ef4a2478fc6a03ea3b5990dd267d20d2d | /Python/_python_modules/unittest/fibonacci.py | e9cb48c6099d63569124520d21159f163deb6452 | [
"MIT"
] | permissive | bhishanpdl/Programming | d4310f86e1d9ac35483191526710caa25b5f138e | 9654c253c598405a22cc96dfa1497406c0bd0990 | refs/heads/master | 2020-03-26T06:19:01.588451 | 2019-08-21T18:09:59 | 2019-08-21T18:09:59 | 69,140,073 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 496 | py | #!python
# -*- coding: utf-8 -*-
#
# Author : Bhishan Poudel, Physics PhD Student, Ohio University
# Date : Jul 21, 2017 Fri
# Last update :
#
# Imports
import doctest
def fib(n):
"""
Calculates the n-th Fibonacci number iteratively
>>> fib(0)
0
>>> fib(1)
1
>>> fib(10)
55
>>> fib(15)
6100
>>>
"""
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
if __name__ == "__main__":
doctest.testmod()
| [
"bhishantryphysics@gmail.com"
] | bhishantryphysics@gmail.com |
f18dea1a75df79cf2877cb6103f8e810fec51ba9 | 648f742d6db2ea4e97b83c99b6fc49abd59e9667 | /common/test_utils/contracts/simulation/mock_product/supervised_savings_deposit_account.py | 8d66f952dab8adf48c532ee676c7a27f0999f380 | [] | no_license | jmiller-tm/replit | c56ce63718f6eb2d9b53bd09d3f7b3ef3496cb86 | c8e6af3268c4ef8da66516154850919ea79055dc | refs/heads/main | 2023-08-30T00:49:35.738089 | 2021-11-16T23:09:08 | 2021-11-16T23:09:08 | 428,809,777 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 46,182 | py | # Copyright @ 2020 Thought Machine Group Limited. All rights reserved.
"""
This is a contract for testing vault caller, sourced from:
/projects/goldfinger/contracts/savings_deposit_account.py
"""
api = "3.4.0"
version = "1.0.4"
display_name = "Supervised US Savings Deposit Account"
summary = "Savings Deposit Account: A bank account that lets you put money away and receive interest on the balance. The balance is instantly accessible when you need to withdraw money. This account includes monthly transaction limits."
tside = Tside.LIABILITY
LimitsShape = NumberShape(
kind=NumberKind.MONEY,
min_value=0,
step=0.01,
)
MoneyShape = NumberShape(kind=NumberKind.MONEY, min_value=0, max_value=10000, step=0.01)
InterestRateShape = NumberShape(
kind=NumberKind.PERCENTAGE, min_value=0, max_value=1, step=0.0001
)
event_types = [
EventType(name="ACCRUE_INTEREST"),
EventType(name="APPLY_ACCRUED_INTEREST"),
EventType(name="CHECK_MAINTENANCE_FEE"),
EventType(name="PUBLISH_EXTRACT"),
]
parameters = [
Parameter(
name="interest_application_day",
level=Level.INSTANCE,
description="The day of the month upon which interest is paid. By default you'll get paid on the same day of the month as the account open date.",
display_name="Elected day of month to pay interest on",
shape=NumberShape(
min_value=1,
max_value=28,
step=1,
),
update_permission=UpdatePermission.USER_EDITABLE,
default_value=Decimal("28"),
),
Parameter(
name="linked_current_account",
level=Level.INSTANCE,
description="Linked current account if this account is used as offset overdraft account. Requires the linked current account to also be linked to this account",
display_name="Linked current account",
shape=OptionalShape(AccountIdShape),
update_permission=UpdatePermission.OPS_EDITABLE,
default_value=OptionalValue("00000000-0000-0000-0000-000000000000"),
),
Parameter(
name="promotion_start_date",
level=Level.INSTANCE,
description="Promotional rate start date. The promotional rate is applied on this day, and on subsequent days",
display_name="Promotional rate start date (inclusive)",
shape=OptionalShape(
DateShape(
min_date=datetime.min,
max_date=datetime.max,
)
),
update_permission=UpdatePermission.OPS_EDITABLE,
default_value=OptionalValue(datetime.min),
),
Parameter(
name="promotion_end_date",
level=Level.INSTANCE,
description="Promotional rate end date. The promotional rate is applied up to, but not including, this day",
display_name="Promotional rate end date (exclusive)",
shape=OptionalShape(
DateShape(
min_date=datetime.min,
max_date=datetime.max,
)
),
update_permission=UpdatePermission.OPS_EDITABLE,
default_value=OptionalValue(datetime.min),
),
Parameter(
name="denomination",
shape=DenominationShape,
level=Level.TEMPLATE,
description="What denomination should the account use?",
display_name="Denomination",
update_permission=UpdatePermission.FIXED,
default_value="USD",
),
Parameter(
name="monthly_transaction_notification_limit",
level=Level.TEMPLATE,
description="The number of monthly transactions allowed before a notification is sent",
display_name="Monthly transactions allowed before notification",
shape=NumberShape(
min_value=1,
max_value=100,
step=1,
),
default_value=Decimal("4"),
),
Parameter(
name="monthly_transaction_soft_limit",
level=Level.TEMPLATE,
description="The number of monthly transactions allowed before charges apply",
display_name="Monthly transactions soft limit before charges",
shape=NumberShape(
min_value=1,
max_value=100,
step=1,
),
default_value=Decimal("5"),
),
Parameter(
name="monthly_transaction_hard_limit",
level=Level.TEMPLATE,
description="The maximum number of transactions allowed in a given month (hard limit)",
display_name="Monthly transaction hard limit",
shape=NumberShape(
min_value=1,
max_value=100,
step=1,
),
default_value=Decimal("6"),
),
Parameter(
name="monthly_transaction_charge",
level=Level.TEMPLATE,
description="The per transaction charge when over the monthly transaction soft limit",
display_name="Transaction charge",
shape=NumberShape(
min_value=1,
max_value=100,
step=1,
),
default_value=Decimal("15"),
),
# Parameter(
# name='gross_interest_rate',
# level=Level.TEMPLATE,
# description='Gross interest rate',
# display_name='Gross interest rate',
# shape=InterestRateShape,
# default_value=Decimal('0.0149')
# ),
Parameter(
name="gross_interest_rate_tiers",
level=Level.TEMPLATE,
description="Gross interest rate tiered by customer status",
display_name="Gross interest rate tiers",
shape=StringShape,
default_value=json_dumps(
{
"customer_tier_high": "0.15",
"customer_tier_medium": "0.10",
"customer_tier_low": "0.01",
"DEFAULT": "0.01",
}
),
),
Parameter(
name="check_hold_percentage_tiers",
level=Level.TEMPLATE,
description="Check hold percentage tiered by customer status",
display_name="Check hold percentage tiers",
shape=StringShape,
default_value=json_dumps(
{
"customer_tier_high": "0.40",
"customer_tier_medium": "0.50",
"customer_tier_low": "0.60",
"DEFAULT": "0.60",
}
),
),
Parameter(
name="minimum_deposit",
level=Level.TEMPLATE,
description="Minimum amount for a single deposit.",
display_name="Minimum deposit amount",
shape=MoneyShape,
default_value=Decimal("0.01"),
),
Parameter(
name="maximum_balance",
level=Level.TEMPLATE,
description="Maximum balance amount.",
display_name="Maximum balance amount",
shape=LimitsShape,
default_value=Decimal("100000"),
),
Parameter(
name="maximum_daily_deposit",
level=Level.TEMPLATE,
description="Maximum daily deposit amount.",
display_name="Maximum daily deposit amount",
shape=LimitsShape,
default_value=Decimal("2000"),
),
Parameter(
name="maximum_daily_withdrawal",
level=Level.TEMPLATE,
description="Maximum daily withdrawal amount.",
display_name="Maximum daily withdrawal amount",
shape=LimitsShape,
default_value=Decimal("1000"),
),
Parameter(
name="minimum_withdrawal",
level=Level.TEMPLATE,
description="Minimum amount for a single withdrawal",
display_name="Minimum withdrawal amount",
shape=LimitsShape,
default_value=Decimal("0.01"),
),
Parameter(
name="promotion_rate",
level=Level.TEMPLATE,
description="Promotional bonus interest rate",
display_name="Promotion interest rate",
shape=InterestRateShape,
default_value=Decimal("0.15"),
),
]
PNL_ACCOUNT = "1"
HARD_TRANSACTION_LIMIT_TYPE = "Hard Transaction Limit"
SOFT_TRANSACTION_LIMIT_TYPE = "Soft (Charge) Transaction Limit"
NOTIFICATION_TRANSACTION_LIMIT_TYPE = "Notification Transaction Limit"
@requires(parameters=True)
def execution_schedules():
interest_application_day = vault.get_parameter_timeseries(
name="interest_application_day"
).latest()
# start_date = vault.get_account_creation_date()
# enddate = start_date + timedelta(hours=1)
return (
("ACCRUE_INTEREST", {"hour": "0"}),
(
"APPLY_ACCRUED_INTEREST",
{"day": str(interest_application_day), "hour": "0", "minute": "1"},
),
("CHECK_MAINTENANCE_FEE", {"day": "28", "hour": "23", "minute": "55"}),
(
"PUBLISH_EXTRACT",
{
"hour": "23",
"minute": "59",
"second": "0"
# 'minute': '*/2',
# 'second': '0',
# 'end_date': str(enddate)
},
),
)
@requires(event_type="ACCRUE_INTEREST", parameters=True, balances="1 day", flags=True)
@requires(event_type="APPLY_ACCRUED_INTEREST", parameters=True, balances="1 day")
@requires(
event_type="CHECK_MAINTENANCE_FEE",
parameters=True,
balances="1 month",
postings="1 month",
)
@requires(
event_type="PUBLISH_EXTRACT",
parameters=True,
balances="1 day live",
last_execution_time=["PUBLISH_EXTRACT"],
postings="2 days",
)
def scheduled_code(event_type, effective_date):
if event_type == "ACCRUE_INTEREST":
end_of_day = effective_date - timedelta(microseconds=1)
_accrue_interest(vault, end_of_day)
elif event_type == "APPLY_ACCRUED_INTEREST":
start_of_day = datetime(
year=effective_date.year, month=effective_date.month, day=effective_date.day
)
_apply_accrued_interest(vault, start_of_day)
elif event_type == "CHECK_MAINTENANCE_FEE":
# Handled in supervisor
pass
elif event_type == "PUBLISH_EXTRACT":
_publish_extract(vault, effective_date)
@requires(parameters=True, last_execution_time=["APPLY_ACCRUED_INTEREST"])
def post_parameter_change_code(old_parameters, new_parameters, effective_date):
if _has_parameter_value_changed(
"interest_application_day", old_parameters, new_parameters
):
schedule_time = {"hour": "0", "minute": "1"}
new_schedule = {
"day": str(new_parameters.get("interest_application_day")),
**schedule_time,
}
vault.amend_schedule(
event_type="APPLY_ACCRUED_INTEREST", new_schedule=new_schedule
)
@requires(parameters=True, balances="latest live", postings="1 month")
def pre_posting_code(postings, effective_date):
# Allow overriding any contract restrictions
if postings.batch_details.get("withdrawal_override") == "true":
return
denomination = vault.get_parameter_timeseries(name="denomination").latest()
balances = vault.get_balance_timeseries().latest()
max_balance = vault.get_parameter_timeseries(name="maximum_balance").latest()
minimum_deposit = vault.get_parameter_timeseries(name="minimum_deposit").latest()
maximum_daily_deposit = vault.get_parameter_timeseries(
name="maximum_daily_deposit"
).latest()
minimum_withdrawal = vault.get_parameter_timeseries(
name="minimum_withdrawal"
).latest()
maximum_daily_withdrawal = vault.get_parameter_timeseries(
name="maximum_daily_withdrawal"
).latest()
monthly_transaction_hard_limit = vault.get_parameter_timeseries(
name="monthly_transaction_hard_limit"
).latest()
latest_outgoing_available_balance = sum(
balance.net
for ((address, asset, denom, phase), balance) in balances.items()
if address == DEFAULT_ADDRESS
and asset == DEFAULT_ASSET
and phase != Phase.PENDING_IN
and denom == denomination
)
latest_incoming_available_balance = sum(
balance.net
for ((address, asset, denom, phase), balance) in balances.items()
if address == DEFAULT_ADDRESS
and asset == DEFAULT_ASSET
and phase != Phase.PENDING_OUT
and denom == denomination
)
proposed_amount = sum(
(1 if post.credit else -1) * post.amount
for post in postings
if post.account_address == DEFAULT_ADDRESS
)
# Validate denomination
if postings[0].denomination != denomination:
raise Rejected(
"Cannot make transactions in given denomination; "
"transactions must be in {}".format(denomination),
reason_code=RejectedReason.WRONG_DENOMINATION,
)
# Check proposed balance is positive or at least more than the current balance
proposed_outgoing_balance = latest_outgoing_available_balance + proposed_amount
if (
proposed_outgoing_balance < 0
and proposed_outgoing_balance < latest_outgoing_available_balance
):
raise Rejected(
"Insufficient funds for transaction.",
reason_code=RejectedReason.INSUFFICIENT_FUNDS,
)
# Check proposed balance is less than max allowed balance or at least less than current balance
proposed_incoming_balance = latest_incoming_available_balance + proposed_amount
if (
proposed_incoming_balance > max_balance
and proposed_incoming_balance > latest_incoming_available_balance
):
raise Rejected(
"Posting would cause the maximum balance to be exceeded.",
reason_code=RejectedReason.AGAINST_TNC,
)
# track and limit transactions in month, ignoring interest and fee accrual applications
client_transactions = vault.get_client_transactions()
if (
_count_client_transactions(client_transactions, denomination)
> monthly_transaction_hard_limit
):
raise Rejected(
"Hard limit of allowed client transactions in 1 month for the account reached",
reason_code=RejectedReason.AGAINST_TNC,
)
for posting in postings:
client_transaction = client_transactions.get(
(posting.client_id, posting.client_transaction_id)
)
amount_authed = max(
abs(
client_transaction.effects()[
(DEFAULT_ADDRESS, DEFAULT_ASSET, denomination)
].authorised
- client_transaction.effects()[
(DEFAULT_ADDRESS, DEFAULT_ASSET, denomination)
].released
),
abs(
client_transaction.effects()[
(DEFAULT_ADDRESS, DEFAULT_ASSET, denomination)
].settled
),
)
# amount_deposit is +ve. amount_withdrawal is -ve.
amount_deposit, amount_withdrawal = _sum_without_current_client_trans(
client_transactions,
posting.client_transaction_id,
datetime.combine(effective_date, datetime.min.time()),
denomination,
)
# Check limits for single transaction
if not posting.credit: # It's an outgoing posting
if posting.amount < minimum_withdrawal:
raise Rejected(
"Transaction amount is less than the minimum withdrawal amount %s %s."
% (minimum_withdrawal, denomination),
reason_code=RejectedReason.AGAINST_TNC,
)
# Check daily withdrawal limit
if amount_authed - amount_withdrawal > maximum_daily_withdrawal:
raise Rejected(
f"Transaction would cause the maximum daily withdrawal limit of "
f"{maximum_daily_withdrawal} {denomination} to be exceeded.",
reason_code=RejectedReason.AGAINST_TNC,
)
if posting.credit:
if posting.amount < minimum_deposit:
raise Rejected(
f"Transaction amount is less than the minimum deposit amount "
f"{minimum_deposit} {denomination}.",
reason_code=RejectedReason.AGAINST_TNC,
)
# Check daily deposit limit
if abs(amount_deposit + amount_authed) > maximum_daily_deposit:
raise Rejected(
f"Transaction would cause the maximum daily deposit limit of "
f"{maximum_daily_deposit} {denomination} to be exceeded.",
reason_code=RejectedReason.AGAINST_TNC,
)
@requires(parameters=True, balances="latest", postings="1 month", flags=True)
def post_posting_code(postings, effective_date):
denomination = vault.get_parameter_timeseries(name="denomination").latest()
monthly_transaction_hard_limit = vault.get_parameter_timeseries(
name="monthly_transaction_hard_limit"
).latest()
monthly_transaction_soft_limit = vault.get_parameter_timeseries(
name="monthly_transaction_soft_limit"
).latest()
monthly_transaction_notification_limit = vault.get_parameter_timeseries(
name="monthly_transaction_notification_limit"
).latest()
monthly_transaction_charge = vault.get_parameter_timeseries(
name="monthly_transaction_charge"
).latest()
# charge withdrawal transaction fee if charge limit exceeded and send appropriate notifications
client_transactions = vault.get_client_transactions()
client_transactions_count = _count_client_transactions(
client_transactions, denomination
)
last_client_transaction = client_transactions.get(
(postings[0].client_id, postings[0].client_transaction_id)
)
last_client_txn_amount = last_client_transaction.effects()[
(DEFAULT_ADDRESS, DEFAULT_ASSET, denomination)
].settled
if (
client_transactions_count > monthly_transaction_soft_limit
and last_client_txn_amount < 0
):
posting_ins = vault.make_internal_transfer_instructions(
amount=monthly_transaction_charge,
denomination=denomination,
from_account_id=vault.account_id,
from_account_address="TRANSACTION_FEE",
to_account_id=PNL_ACCOUNT,
to_account_address=DEFAULT_ADDRESS,
asset=DEFAULT_ASSET,
override_all_restrictions=True,
pics=[],
client_transaction_id="APPLY_TRANSACTION_FEE_{}_{}_INTERNAL".format(
vault.get_hook_execution_id(), denomination
),
instruction_details={
"description": "Transaction fee applied",
"event": "ACCRUE_FEES",
},
)
vault.instruct_posting_batch(
posting_instructions=posting_ins, effective_date=effective_date
)
# generate workflow notification - customer has been charged
vault.start_workflow(
workflow="NOTIFY_TRANSACTION_LIMIT_REACHED",
context={
"account_id": str(vault.account_id),
"limit_type": SOFT_TRANSACTION_LIMIT_TYPE,
"limit": str(monthly_transaction_soft_limit),
"value": str(client_transactions_count),
"message": "Alert: Monthly withdrawal transaction limit reached - charges have been"
" applied",
},
)
elif (
client_transactions_count > monthly_transaction_notification_limit
and last_client_txn_amount < 0
):
# generate workflow notification - customer near to exceeding limit
vault.start_workflow(
workflow="NOTIFY_TRANSACTION_LIMIT_REACHED",
context={
"account_id": str(vault.account_id),
"limit_type": NOTIFICATION_TRANSACTION_LIMIT_TYPE,
"limit": str(monthly_transaction_notification_limit),
"value": str(client_transactions_count),
"message": "Warning: Close to exceeding monthly withdrawal transaction limit, "
"charges will be applied for the next transaction",
},
)
# Make mirror posting of posting instruction batch from savings.reverse_mirror to current.savings_register
linked_current_account_param = vault.get_parameter_timeseries(
name="linked_current_account"
).at(timestamp=effective_date)
pib_net_amount = postings.balances()[
DEFAULT_ADDRESS, DEFAULT_ASSET, denomination, Phase.COMMITTED
].net
if _valid_linked_account(linked_current_account_param) and abs(pib_net_amount) > 0:
if pib_net_amount > 0:
vault.instruct_posting_batch(
posting_instructions=vault.make_internal_transfer_instructions(
amount=pib_net_amount,
denomination=denomination,
from_account_id=vault.account_id,
from_account_address="SAVINGS_REGISTER",
to_account_id=linked_current_account_param.value,
to_account_address="SAVINGS_REGISTER",
asset=DEFAULT_ASSET,
override_all_restrictions=True,
pics=[],
client_transaction_id=f"SAVINGS_BALANCE_REGISTER_"
f"{vault.get_hook_execution_id()}",
instruction_details={
"description": f"Updating savings account mirror for PIB {postings.client_batch_id}",
"event": "SAVINGS_REGISTER",
},
),
effective_date=effective_date,
)
else:
vault.instruct_posting_batch(
posting_instructions=vault.make_internal_transfer_instructions(
amount=abs(pib_net_amount),
denomination=denomination,
from_account_id=linked_current_account_param.value,
from_account_address="SAVINGS_REGISTER",
to_account_id=vault.account_id,
to_account_address="SAVINGS_REGISTER",
asset=DEFAULT_ASSET,
override_all_restrictions=True,
pics=[],
client_transaction_id=f"SAVINGS_BALANCE_REGISTER_"
f"{vault.get_hook_execution_id()}",
instruction_details={
"description": f"Updating savings account mirror for PIB {postings.client_batch_id}",
"event": "SAVINGS_REGISTER",
},
),
effective_date=effective_date,
)
@requires(parameters=True, balances="latest")
def close_code(effective_date):
_apply_accrued_interest(vault, effective_date)
def _accrue_interest(vault, effective_date):
denomination = vault.get_parameter_timeseries(name="denomination").latest()
balances = vault.get_balance_timeseries().at(timestamp=effective_date)
effective_balance = (
balances[(DEFAULT_ADDRESS, DEFAULT_ASSET, denomination, Phase.COMMITTED)].net
+ balances[
(DEFAULT_ADDRESS, DEFAULT_ASSET, denomination, Phase.PENDING_OUT)
].net
)
if effective_balance <= 0:
return
promotion_start_date = _get_param_value(vault, "promotion_start_date")
promotion_end_date = _get_param_value(vault, "promotion_end_date")
if _check_if_in_promotion_window(
effective_date, promotion_start_date, promotion_end_date
):
gross_interest_rate = vault.get_parameter_timeseries(name="promotion_rate").at(
timestamp=effective_date
)
else:
gross_interest_rate_tiers = json_loads(
vault.get_parameter_timeseries(name="gross_interest_rate_tiers").at(
timestamp=effective_date
)
)
gross_interest_rate = _get_customer_interest_rate(
vault, gross_interest_rate_tiers, effective_date
)
daily_rate = _yearly_to_daily_rate(gross_interest_rate)
daily_rate_percent = daily_rate * 100
interest = effective_balance * daily_rate
if interest > 0:
amount_to_accrue = _precision_accrual(interest)
if amount_to_accrue > 0:
posting_ins = vault.make_internal_transfer_instructions(
amount=amount_to_accrue,
denomination=denomination,
client_transaction_id=vault.get_hook_execution_id(),
from_account_id=PNL_ACCOUNT,
from_account_address="ACCRUED_OUTGOING",
to_account_id=vault.account_id,
to_account_address="ACCRUED_INCOMING",
asset=DEFAULT_ASSET,
override_all_restrictions=True,
instruction_details={
"description": "Daily interest accrued at %0.5f%% on balance of %0.2f"
% (daily_rate_percent, effective_balance),
"event": "ACCRUE_INTEREST",
},
)
vault.instruct_posting_batch(
posting_instructions=posting_ins, effective_date=effective_date
)
else:
# Negative interest
amount_to_accrue = _precision_accrual(interest)
if amount_to_accrue > 0:
posting_ins = vault.make_internal_transfer_instructions(
amount=amount_to_accrue,
denomination=denomination,
client_transaction_id=vault.get_hook_execution_id(),
from_account_id=vault.account_id,
from_account_address="ACCRUED_OUTGOING",
to_account_id=PNL_ACCOUNT,
to_account_address="ACCRUED_INCOMING",
asset=DEFAULT_ASSET,
override_all_restrictions=True,
instruction_details={
"description": "Daily negative interest accrued at %0.5f%% on balance of %0.2f"
% (daily_rate_percent, effective_balance),
"event": "ACCRUE_NEGATIVE_INTEREST",
},
)
vault.instruct_posting_batch(
posting_instructions=posting_ins, effective_date=effective_date
)
def _apply_accrued_interest(vault, effective_date):
denomination = vault.get_parameter_timeseries(name="denomination").latest()
linked_current_account_param = vault.get_parameter_timeseries(
name="linked_current_account"
).at(timestamp=effective_date)
balances = vault.get_balance_timeseries().at(timestamp=effective_date)
accrued_incoming_balance = balances[
("ACCRUED_INCOMING", DEFAULT_ASSET, denomination, Phase.COMMITTED)
].net
# to support negative interest
accrued_outgoing_balance = balances[
("ACCRUED_OUTGOING", DEFAULT_ASSET, denomination, Phase.COMMITTED)
].net
transaction_fee_balance = balances[
("TRANSACTION_FEE", DEFAULT_ASSET, denomination, Phase.COMMITTED)
].net
accrued_incoming_fulfillment = _precision_fulfillment(accrued_incoming_balance)
accrued_outgoing_fulfillment = _precision_fulfillment(accrued_outgoing_balance)
posting_ins = []
transaction_fee_fulfillment = _precision_fulfillment(transaction_fee_balance)
mirror_posting_ins = []
if accrued_incoming_fulfillment > 0:
posting_ins.extend(
vault.make_internal_transfer_instructions(
amount=accrued_incoming_fulfillment,
denomination=denomination,
from_account_id=vault.account_id,
from_account_address="ACCRUED_INCOMING",
to_account_id=vault.account_id,
to_account_address=DEFAULT_ADDRESS,
asset=DEFAULT_ASSET,
override_all_restrictions=True,
client_transaction_id="APPLY_ACCRUED_INTEREST_{}_{}_CUSTOMER".format(
vault.get_hook_execution_id(), denomination
),
instruction_details={
"description": "Interest Applied",
"event": "APPLY_ACCRUED_INTEREST",
},
)
)
if _valid_linked_account(linked_current_account_param):
mirror_posting_ins.extend(
vault.make_internal_transfer_instructions(
amount=accrued_incoming_fulfillment,
denomination=denomination,
from_account_id=vault.account_id,
from_account_address="SAVINGS_REGISTER",
to_account_id=linked_current_account_param.value,
to_account_address="SAVINGS_REGISTER",
asset=DEFAULT_ASSET,
override_all_restrictions=True,
client_transaction_id="REGISTER_APPLY_ACCRUED_INTEREST_{}_{}_CUSTOMER".format(
vault.get_hook_execution_id(), denomination
),
instruction_details={
"description": "Mirroring Interest Applied",
"event": "SAVINGS_REGISTER",
},
)
)
posting_ins.extend(
vault.make_internal_transfer_instructions(
amount=accrued_incoming_fulfillment,
denomination=denomination,
from_account_id=PNL_ACCOUNT,
from_account_address=DEFAULT_ADDRESS,
to_account_id=PNL_ACCOUNT,
to_account_address="ACCRUED_OUTGOING",
asset=DEFAULT_ASSET,
override_all_restrictions=True,
client_transaction_id="APPLY_ACCRUED_INTEREST_{}_{}_INTERNAL".format(
vault.get_hook_execution_id(), denomination
),
instruction_details={
"description": "Interest Applied",
"event": "APPLY_ACCRUED_INTEREST",
},
)
)
# negative interest
if accrued_outgoing_fulfillment > 0:
posting_ins.extend(
vault.make_internal_transfer_instructions(
amount=accrued_outgoing_fulfillment,
denomination=denomination,
from_account_id=vault.account_id,
from_account_address=DEFAULT_ADDRESS,
to_account_id=vault.account_id,
to_account_address="ACCRUED_OUTGOING",
asset=DEFAULT_ASSET,
override_all_restrictions=True,
client_transaction_id="APPLY_ACCRUED_NEGATIVE_INTEREST_{}_{}_CUSTOMER".format(
vault.get_hook_execution_id(), denomination
),
instruction_details={
"description": "Negative Interest Applied",
"event": "APPLY_NEGATIVE_ACCRUED_INTEREST",
},
)
)
if _valid_linked_account(linked_current_account_param):
mirror_posting_ins.extend(
vault.make_internal_transfer_instructions(
amount=accrued_outgoing_fulfillment,
denomination=denomination,
from_account_id=linked_current_account_param.value,
from_account_address="SAVINGS_REGISTER",
to_account_id=vault.account_id,
to_account_address="SAVINGS_REGISTER",
asset=DEFAULT_ASSET,
override_all_restrictions=True,
client_transaction_id="REGISTER_APPLY_ACCRUED_NEGATIVE_INTEREST_{}_{}_CUSTOMER".format(
vault.get_hook_execution_id(), denomination
),
instruction_details={
"description": "Mirroring Interest Applied",
"event": "SAVINGS_REGISTER",
},
)
)
posting_ins.extend(
vault.make_internal_transfer_instructions(
amount=accrued_outgoing_fulfillment,
denomination=denomination,
from_account_id=PNL_ACCOUNT,
from_account_address="ACCRUED_INCOMING",
to_account_id=PNL_ACCOUNT,
to_account_address=DEFAULT_ADDRESS,
asset=DEFAULT_ASSET,
override_all_restrictions=True,
client_transaction_id="APPLY_ACCRUED_NEGATIVE_INTEREST_{}_{}_INTERNAL".format(
vault.get_hook_execution_id(), denomination
),
instruction_details={
"description": "Negative Interest Applied",
"event": "APPLY_NEGATIVE_ACCRUED_INTEREST",
},
)
)
if transaction_fee_fulfillment > 0:
posting_ins.extend(
vault.make_internal_transfer_instructions(
amount=transaction_fee_fulfillment,
denomination=denomination,
from_account_id=vault.account_id,
from_account_address=DEFAULT_ADDRESS,
to_account_id=vault.account_id,
to_account_address="TRANSACTION_FEE",
asset=DEFAULT_ASSET,
override_all_restrictions=True,
pics=[],
client_transaction_id="APPLY_ACCRUED_TRANSACTION_FEE_{}_{}_CUSTOMER".format(
vault.get_hook_execution_id(), denomination
),
instruction_details={
"description": "Transaction fees applied",
"event": "APPLY_ACCRUED_INTEREST",
},
)
)
if _valid_linked_account(linked_current_account_param):
mirror_posting_ins.extend(
vault.make_internal_transfer_instructions(
amount=transaction_fee_fulfillment,
denomination=denomination,
from_account_id=linked_current_account_param.value,
from_account_address="SAVINGS_REGISTER",
to_account_id=vault.account_id,
to_account_address="SAVINGS_REGISTER",
asset=DEFAULT_ASSET,
override_all_restrictions=True,
client_transaction_id="REGISTER_ACCRUED_TRANSACTION_FEE_{}_{}_CUSTOMER".format(
vault.get_hook_execution_id(), denomination
),
instruction_details={
"description": "Mirroring Transaction fees applied",
"event": "SAVINGS_REGISTER",
},
)
)
remainder = accrued_incoming_balance - accrued_incoming_fulfillment
if remainder > 0:
posting_ins.extend(
vault.make_internal_transfer_instructions(
amount=abs(remainder),
denomination=denomination,
from_account_id=vault.account_id,
from_account_address="ACCRUED_INCOMING",
to_account_id=PNL_ACCOUNT,
to_account_address="ACCRUED_OUTGOING",
asset=DEFAULT_ASSET,
override_all_restrictions=True,
client_transaction_id="REVERSE_ACCRUE_INTEREST_{}_{}".format(
vault.get_hook_execution_id(), denomination
),
instruction_details={
"description": "Reversing accrued interest after application",
"event": "APPLY_ACCRUED_INTEREST",
},
)
)
if remainder < 0:
posting_ins.extend(
vault.make_internal_transfer_instructions(
amount=abs(remainder),
denomination=denomination,
from_account_id=PNL_ACCOUNT,
from_account_address="ACCRUED_OUTGOING",
to_account_id=vault.account_id,
to_account_address="ACCRUED_INCOMING",
asset=DEFAULT_ASSET,
override_all_restrictions=True,
client_transaction_id="REVERSE_ACCRUE_INTEREST_{}_{}".format(
vault.get_hook_execution_id(), denomination
),
instruction_details={
"description": "Reversing accrued interest after application",
"event": "APPLY_ACCRUED_INTEREST",
},
)
)
negative_interest_remainder = (
accrued_outgoing_balance + accrued_outgoing_fulfillment
)
if negative_interest_remainder > 0:
posting_ins.extend(
vault.make_internal_transfer_instructions(
amount=abs(negative_interest_remainder),
denomination=denomination,
from_account_id=vault.account_id,
from_account_address="ACCRUED_OUTGOING",
to_account_id=PNL_ACCOUNT,
to_account_address="ACCRUED_INCOMING",
asset=DEFAULT_ASSET,
override_all_restrictions=True,
client_transaction_id="REVERSE_ACCRUE_NEGATIVE_INTEREST_{}_{}".format(
vault.get_hook_execution_id(), denomination
),
instruction_details={
"description": "Reversing accrued negative interest after application",
"event": "APPLY_ACCRUED_INTEREST",
},
)
)
if negative_interest_remainder < 0:
posting_ins.extend(
vault.make_internal_transfer_instructions(
amount=abs(negative_interest_remainder),
denomination=denomination,
from_account_id=PNL_ACCOUNT,
from_account_address="ACCRUED_INCOMING",
to_account_id=vault.account_id,
to_account_address="ACCRUED_OUTGOING",
asset=DEFAULT_ASSET,
override_all_restrictions=True,
client_transaction_id="REVERSE_ACCRUE_NEGATIVE_INTEREST_{}_{}".format(
vault.get_hook_execution_id(), denomination
),
instruction_details={
"description": "Reversing accrued negative interest after application",
"event": "APPLY_ACCRUED_INTEREST",
},
)
)
if posting_ins:
vault.instruct_posting_batch(
posting_instructions=posting_ins,
effective_date=effective_date,
client_batch_id="APPLY_ACCRUED_INTEREST_AND_FEES_{}_{}".format(
vault.get_hook_execution_id(), denomination
),
)
if mirror_posting_ins:
vault.instruct_posting_batch(
posting_instructions=mirror_posting_ins,
effective_date=effective_date,
client_batch_id=f"REGISTER_APPLY_ACCRUED_INTEREST_AND_FEES"
f"_{vault.get_hook_execution_id()}",
)
def _publish_extract(vault, effective_date):
denomination = vault.get_parameter_timeseries(name="denomination").at(
timestamp=effective_date
)
balance_timeseries = vault.get_balance_timeseries()
last_extract_exec = vault.get_last_execution_time(event_type="PUBLISH_EXTRACT")
if last_extract_exec:
end_of_last_extract = last_extract_exec
else:
end_of_last_extract = vault.get_account_creation_date()
batches = vault.get_posting_batches() or []
pib_data = {
str(pib.value_timestamp): [
pib.batch_id,
"%0.2f" % _get_altered_balance(pib.balances(), denomination),
"%0.2f"
% _get_phase_balance(
balance_timeseries.at(timestamp=pib.value_timestamp), denomination
),
]
for pib in batches
if end_of_last_extract <= pib.value_timestamp < effective_date
}
opening_balances = balance_timeseries.at(timestamp=end_of_last_extract)
opening_committed_bal = _get_phase_balance(opening_balances, denomination)
closing_balances = balance_timeseries.at(timestamp=effective_date)
closing_available_bal = _get_available_balance(closing_balances, denomination)
closing_committed_bal = _get_phase_balance(closing_balances, denomination)
closing_pending_in_bal = _get_phase_balance(
closing_balances, denomination, Phase.PENDING_IN
)
closing_pending_out_bal = _get_phase_balance(
closing_balances, denomination, Phase.PENDING_OUT
)
vault.start_workflow(
workflow="PUBLISH_EXTRACT_DATA",
context={
"account_id": str(vault.account_id),
"extract_date": str(effective_date),
"available_balance": "%0.2f" % closing_available_bal,
"opening_balance": "%0.2f" % opening_committed_bal,
"closing_balance": "%0.2f" % closing_committed_bal,
"pending_in_balance": "%0.2f" % closing_pending_in_bal,
"pending_out_balance": "%0.2f" % closing_pending_out_bal,
"extract_data": str(pib_data).replace('"', '\\"').replace("'", '"'),
},
)
def _sum_without_current_client_trans(
client_transactions, client_transaction_id, cutoff_timestamp, denomination
):
amount_withdrawal = 0
amount_deposit = 0
for (client_id, transaction_id), transaction in client_transactions.items():
if transaction_id == client_transaction_id:
continue
if transaction.cancelled:
continue
amount_now = (
transaction.effects()[
(DEFAULT_ADDRESS, DEFAULT_ASSET, denomination)
].settled
+ transaction.effects()[
(DEFAULT_ADDRESS, DEFAULT_ASSET, denomination)
].unsettled
)
amount_before_cutoff = (
transaction.effects(timestamp=cutoff_timestamp)[
(DEFAULT_ADDRESS, DEFAULT_ASSET, denomination)
].settled
+ transaction.effects(timestamp=cutoff_timestamp)[
(DEFAULT_ADDRESS, DEFAULT_ASSET, denomination)
].unsettled
)
amount = amount_now - amount_before_cutoff
if amount > 0:
amount_deposit += amount
else:
amount_withdrawal += amount
return amount_deposit, amount_withdrawal
def _get_available_balance(balances, denomination):
committed_balance_net = balances[
(DEFAULT_ADDRESS, DEFAULT_ASSET, denomination, Phase.COMMITTED)
].net
# Pending out is -ve
pending_out_balance_net = balances[
(DEFAULT_ADDRESS, DEFAULT_ASSET, denomination, Phase.PENDING_OUT)
].net
return committed_balance_net + pending_out_balance_net
def _get_phase_balance(balances, denomination, phase=Phase.COMMITTED):
return balances[(DEFAULT_ADDRESS, DEFAULT_ASSET, denomination, phase)].net
def _get_altered_balance(balances, denomination):
return sum(
balance.net
for ((address, asset, denom, phase), balance) in balances.items()
if asset == DEFAULT_ASSET and denom == denomination
)
def _yearly_to_daily_rate(yearly_rate):
days_in_year = 365
return yearly_rate / days_in_year
def _precision_accrual(amount):
return amount.copy_abs().quantize(Decimal(".00001"), rounding=ROUND_HALF_UP)
def _precision_fulfillment(amount):
return amount.copy_abs().quantize(Decimal(".01"), rounding=ROUND_HALF_UP)
def _has_parameter_value_changed(
parameter_name, old_parameter_values, updated_parameter_values
):
"""
Determines if a parameter has changed. To be used within post-parameter change hook
:param parameter_name: str, name of the parameter
:param old_parameter_values: dict, map of parameter name -> old parameter value
:param updated_parameter_values: dict, map of parameter name -> new parameter value
:return: bool, True if parameter value has changed, False otherwise
"""
if parameter_name not in updated_parameter_values:
return False
if old_parameter_values[parameter_name] == updated_parameter_values[parameter_name]:
return False
return True
def _count_client_transactions(client_transactions, denomination):
# count withdrawal transactions only, excludes 'APPLY_ACCRUED_' transaction ids
txns_this_month = []
for (client_id, client_txn_id) in client_transactions:
client_txn = client_transactions.get((client_id, client_txn_id))
if client_txn.effects()[(DEFAULT_ADDRESS, DEFAULT_ASSET, denomination)].settled:
if (
client_txn.effects()[
(DEFAULT_ADDRESS, DEFAULT_ASSET, denomination)
].settled
< 0
):
if "APPLY_ACCRUED_" not in client_txn_id:
txns_this_month.append(client_txn_id)
return len(txns_this_month)
def _check_if_in_promotion_window(
effective_date, promotion_start_date, promotion_end_date
):
in_promo = False
if promotion_start_date and promotion_end_date:
in_promo = (
effective_date > promotion_start_date
and effective_date <= promotion_end_date
)
return in_promo
def _get_customer_interest_rate(vault, gross_interest_rate_tiers, effective_date):
tier_found = False
for tier in gross_interest_rate_tiers.keys():
if vault.get_flag_timeseries(flag=tier).at(timestamp=effective_date):
customer_interest_rate = Decimal(gross_interest_rate_tiers[tier])
tier_found = True
break
if not tier_found:
customer_interest_rate = Decimal(gross_interest_rate_tiers["DEFAULT"])
return customer_interest_rate
def _valid_linked_account(linked_account_id_param):
if (
linked_account_id_param.is_set()
and linked_account_id_param.value != "00000000-0000-0000-0000-000000000000"
):
return True
else:
return False
def _get_param_value(vault, param_name, default_value=None):
param = vault.get_parameter_timeseries(name=param_name).latest()
param_value = param.value if param.is_set() else default_value
return param_value
# flake8: noqa: F821
| [
"jmiller@jmiller-tm00769-mbp.nomad.thomac.net"
] | jmiller@jmiller-tm00769-mbp.nomad.thomac.net |
59448244030550a58a263906206bc941679ee131 | be084131635850062abd17cdb037e1161725f56c | /Wrapping/Python/vtkvtg/hybrid.py | 04d45a20d6423b8e7e85073c18afbe7c0ddb846e | [] | no_license | emonson/vtkVTG | 177a80820e27aad7fc9fb1d7b14cee4155166d00 | 767f35ae18142133f7ffd1a9ea6c22dfd59acac7 | refs/heads/master | 2016-09-10T00:53:25.613217 | 2012-06-05T14:45:12 | 2012-06-05T14:45:12 | 699,786 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 235 | py | """ This module loads all the classes from the VTK Hybrid library into its
namespace. This is a required module."""
import os
if os.name == 'posix':
from libvtkvtgHybridPython import *
else:
from vtkvtgHybridPython import *
| [
"emonson@cs.duke.edu"
] | emonson@cs.duke.edu |
a665cbf59a3147d170e05d21793e326740771fb1 | f9d564f1aa83eca45872dab7fbaa26dd48210d08 | /huaweicloud-sdk-iotanalytics/huaweicloudsdkiotanalytics/v1/model/node_content_req.py | 7ecc68c267ff4a458e37e65c2f437fbb9f4b3b61 | [
"Apache-2.0"
] | permissive | huaweicloud/huaweicloud-sdk-python-v3 | cde6d849ce5b1de05ac5ebfd6153f27803837d84 | f69344c1dadb79067746ddf9bfde4bddc18d5ecf | refs/heads/master | 2023-09-01T19:29:43.013318 | 2023-08-31T08:28:59 | 2023-08-31T08:28:59 | 262,207,814 | 103 | 44 | NOASSERTION | 2023-06-22T14:50:48 | 2020-05-08T02:28:43 | Python | UTF-8 | Python | false | false | 3,960 | py | # coding: utf-8
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class NodeContentReq:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'site_id': 'str',
'sqllist': 'list[str]'
}
attribute_map = {
'site_id': 'site_id',
'sqllist': 'sqllist'
}
def __init__(self, site_id=None, sqllist=None):
"""NodeContentReq
The model defined in huaweicloud sdk
:param site_id: 节点实例ID
:type site_id: str
:param sqllist: SQL列表,将指定边缘平台节点的数字孪生模型实例数据转发到中心平台节点。
:type sqllist: list[str]
"""
self._site_id = None
self._sqllist = None
self.discriminator = None
self.site_id = site_id
self.sqllist = sqllist
@property
def site_id(self):
"""Gets the site_id of this NodeContentReq.
节点实例ID
:return: The site_id of this NodeContentReq.
:rtype: str
"""
return self._site_id
@site_id.setter
def site_id(self, site_id):
"""Sets the site_id of this NodeContentReq.
节点实例ID
:param site_id: The site_id of this NodeContentReq.
:type site_id: str
"""
self._site_id = site_id
@property
def sqllist(self):
"""Gets the sqllist of this NodeContentReq.
SQL列表,将指定边缘平台节点的数字孪生模型实例数据转发到中心平台节点。
:return: The sqllist of this NodeContentReq.
:rtype: list[str]
"""
return self._sqllist
@sqllist.setter
def sqllist(self, sqllist):
"""Sets the sqllist of this NodeContentReq.
SQL列表,将指定边缘平台节点的数字孪生模型实例数据转发到中心平台节点。
:param sqllist: The sqllist of this NodeContentReq.
:type sqllist: list[str]
"""
self._sqllist = sqllist
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
import simplejson as json
if six.PY2:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)
def __repr__(self):
"""For `print`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, NodeContentReq):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"hwcloudsdk@huawei.com"
] | hwcloudsdk@huawei.com |
3f23307214e7a4e5dcc595c860deb926e71ab218 | 7437e6b58750275933939321b6b9dc5eb6891a1c | /biothings/hub/api/handlers/source.py | 0750920b7dd125ff13da9436d4c14eedf13e5bc6 | [
"Apache-2.0"
] | permissive | Quiltomics/biothings.api | b6caa939a90e0fd1db35124b64ecdc34babdf5c7 | ab54243e8833888e0331a988a2a13907d17442ad | refs/heads/master | 2020-04-23T12:54:16.731641 | 2019-02-16T17:43:28 | 2019-02-16T19:07:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,801 | py | import asyncio
import logging
import tornado.web
from collections import OrderedDict
from .base import BaseHandler
from biothings.utils.dataload import to_boolean
class SourceHandler(BaseHandler):
def sumup_source(self,src):
"""Return minimal info about src"""
mini = OrderedDict()
mini["name"] = src["name"]
mini["release"] = src.get("release")
if src.get("download"):
mini["download"] = {
"status" : src["download"].get("status"),
"time" : src["download"].get("time"),
"started_at" : src["download"].get("started_at")
}
mini["download"]["dumper"] = src["download"].get("dumper",{})
if src["download"].get("err"):
mini["download"]["error"] = src["download"]["err"]
count = 0
if src.get("upload"):
mini["upload"] = {}
all_status = set()
if len(src["upload"]["jobs"]) > 1:
for job,info in src["upload"]["jobs"].items():
mini["upload"][job] = {
"time" : info.get("time"),
"status" : info.get("status"),
"count" : info.get("count"),
"started_at" : info.get("started_at")
}
count += info.get("count") or 0
all_status.add(info["status"])
if len(all_status) == 1:
mini["upload"]["status"] = all_status.pop()
elif "uploading" in all_status:
mini["upload"]["status"] = "uploading"
else:
job,info = list(src["upload"]["jobs"].items())[0]
mini["upload"][job] = {
"time" : info.get("time"),
"status" : info.get("status"),
"count" : info.get("count"),
"started_at" : info.get("started_at")
}
count += info.get("count") or 0
mini["upload"]["status"] = info.get("status")
if src["upload"].get("err"):
mini["upload"]["error"] = src["upload"]["err"]
if src.get("locked"):
mini["locked"] = src["locked"]
mini["count"] = count
return mini
def get_sources(self,debug=False):
dm = self.managers.get("dump_manager")
um = self.managers.get("upload_manager")
sources = {}
if dm:
srcs = dm.source_info()
if debug:
for src in srcs:
sources[src["name"]] = src
else:
for src in srcs:
sources[src["name"]] = self.sumup_source(src)
# complete with uploader info
if um:
srcs = um.source_info()
dsrcs = dict([(src["name"],src) for src in srcs])
for src_name in um.register.keys():
# collection-only source don't have dumpers and only exist in
# the uploader manager
up_info = dsrcs.get(src_name,{"name":src_name})
if not src_name in dm.register:
sources[src_name] = self.sumup_source(up_info)
if up_info.get("upload"):
for subname in up_info["upload"].get("jobs",{}):
sources[up_info["name"]].setdefault("upload",{}).setdefault(subname,{})
sources[up_info["name"]]["upload"][subname]["uploader"] = up_info["upload"]["jobs"][subname]["uploader"]
return list(sources.values())
def get_source(self,name,debug=False):
dm = self.managers.get("dump_manager")
um = self.managers.get("upload_manager")
m = dm or um # whatever available
if m:
src = m.source_info(name)
if not src:
raise tornado.web.HTTPError(404,reason="No such datasource")
else:
return src
else:
raise tornado.web.HTTPError(500,reason="No manager available to fetch information")
@asyncio.coroutine
def get(self,name=None):
debug = to_boolean(self.get_query_argument("debug",False))
if name:
self.write(self.get_source(name,debug))
else:
self.write(self.get_sources(debug))
class DumpSourceHandler(BaseHandler):
def post(self,name):
dm = self.managers.get("dump_manager")
dm.dump_src(name)
self.write({"dump" : name})
class UploadSourceHandler(BaseHandler):
def post(self,name):
um = self.managers.get("upload_manager")
um.upload_src(name)
self.write({"upload" : name})
| [
"slelong@scripps.edu"
] | slelong@scripps.edu |
4f69bce313f30ba5697091f2746782807a09ad1d | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/adjectives/_winded.py | a4f8fd77780cbfc22bfc25f69c08d1918a504218 | [
"MIT"
] | permissive | cash2one/xai | de7adad1758f50dd6786bf0111e71a903f039b64 | e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6 | refs/heads/master | 2021-01-19T12:33:54.964379 | 2017-01-28T02:00:50 | 2017-01-28T02:00:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 460 | py |
#calss header
class _WINDED():
def __init__(self,):
self.name = "WINDED"
self.definitions = [u'temporarily unable to breathe, either when hit in the stomach or after taking hard physical exercise: ']
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.specie = 'adjectives'
def run(self, obj1, obj2):
self.jsondata[obj2] = {}
self.jsondata[obj2]['properties'] = self.name.lower()
return self.jsondata
| [
"xingwang1991@gmail.com"
] | xingwang1991@gmail.com |
28c1a389ae191a498b40a324ed913a9489f19eda | a3283e723b9711779a4f6485dbbaf58f8b86cda1 | /d3rlpy/algos/bcq.py | 29b1ea67d350e223f4dc177a31dcf308e585a06d | [
"MIT"
] | permissive | ritou11/d3rlpy | 50ed48af10aa57c0e0b966c2ff52a5d62ba97a48 | ce18c8584723faf4d5c3d3221b6122f923162987 | refs/heads/master | 2023-02-12T04:07:02.996827 | 2021-01-08T14:42:04 | 2021-01-08T14:42:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 18,540 | py | from typing import Any, List, Optional, Sequence, Union
import numpy as np
from .base import AlgoBase, DataGenerator
from .torch.bcq_impl import BCQImpl, DiscreteBCQImpl
from ..augmentation import AugmentationPipeline
from ..optimizers import OptimizerFactory, AdamFactory
from ..encoders import EncoderFactory
from ..dataset import TransitionMiniBatch
from ..q_functions import QFunctionFactory
from ..gpu import Device
from ..argument_utility import check_encoder, EncoderArg
from ..argument_utility import check_use_gpu, UseGPUArg
from ..argument_utility import check_augmentation, AugmentationArg
from ..argument_utility import check_q_func, QFuncArg
from ..argument_utility import ScalerArg
class BCQ(AlgoBase):
r"""Batch-Constrained Q-learning algorithm.
BCQ is the very first practical data-driven deep reinforcement learning
lgorithm.
The major difference from DDPG is that the policy function is represented
as combination of conditional VAE and perturbation function in order to
remedy extrapolation error emerging from target value estimation.
The encoder and the decoder of the conditional VAE is represented as
:math:`E_\omega` and :math:`D_\omega` respectively.
.. math::
L(\omega) = E_{s_t, a_t \sim D} [(a - \tilde{a})^2
+ D_{KL}(N(\mu, \sigma)|N(0, 1))]
where :math:`\mu, \sigma = E_\omega(s_t, a_t)`,
:math:`\tilde{a} = D_\omega(s_t, z)` and :math:`z \sim N(\mu, \sigma)`.
The policy function is represented as a residual function
with the VAE and the perturbation function represented as
:math:`\xi_\phi (s, a)`.
.. math::
\pi(s, a) = a + \Phi \xi_\phi (s, a)
where :math:`a = D_\omega (s, z)`, :math:`z \sim N(0, 0.5)` and
:math:`\Phi` is a perturbation scale designated by `action_flexibility`.
Although the policy is learned closely to data distribution, the
perturbation function can lead to more rewarded states.
BCQ also leverages twin Q functions and computes weighted average over
maximum values and minimum values.
.. math::
L(\theta_i) = \mathbb{E}_{s_t, a_t, r_{t+1}, s_{t+1} \sim D}
[(y - Q_{\theta_i}(s_t, a_t))^2]
.. math::
y = r_{t+1} + \gamma \max_{a_i} [
\lambda \min_j Q_{\theta_j'}(s_{t+1}, a_i)
+ (1 - \lambda) \max_j Q_{\theta_j'}(s_{t+1}, a_i)]
where :math:`\{a_i \sim D(s_{t+1}, z), z \sim N(0, 0.5)\}_{i=1}^n`.
The number of sampled actions is designated with `n_action_samples`.
Finally, the perturbation function is trained just like DDPG's policy
function.
.. math::
J(\phi) = \mathbb{E}_{s_t \sim D, a_t \sim D_\omega(s_t, z),
z \sim N(0, 0.5)}
[Q_{\theta_1} (s_t, \pi(s_t, a_t))]
At inference time, action candidates are sampled as many as
`n_action_samples`, and the action with highest value estimation is taken.
.. math::
\pi'(s) = \text{argmax}_{\pi(s, a_i)} Q_{\theta_1} (s, \pi(s, a_i))
Note:
The greedy action is not deterministic because the action candidates
are always randomly sampled. This might affect `save_policy` method and
the performance at production.
References:
* `Fujimoto et al., Off-Policy Deep Reinforcement Learning without
Exploration. <https://arxiv.org/abs/1812.02900>`_
Args:
actor_learning_rate (float): learning rate for policy function.
critic_learning_rate (float): learning rate for Q functions.
imitator_learning_rate (float): learning rate for Conditional VAE.
actor_optim_factory (d3rlpy.optimizers.OptimizerFactory):
optimizer factory for the actor.
critic_optim_factory (d3rlpy.optimizers.OptimizerFactory):
optimizer factory for the critic.
imitator_optim_factory (d3rlpy.optimizers.OptimizerFactory):
optimizer factory for the conditional VAE.
actor_encoder_factory (d3rlpy.encoders.EncoderFactory or str):
encoder factory for the actor.
critic_encoder_factory (d3rlpy.encoders.EncoderFactory or str):
encoder factory for the critic.
imitator_encoder_factory (d3rlpy.encoders.EncoderFactory or str):
encoder factory for the conditional VAE.
q_func_factory (d3rlpy.q_functions.QFunctionFactory or str):
Q function factory.
batch_size (int): mini-batch size.
n_frames (int): the number of frames to stack for image observation.
n_steps (int): N-step TD calculation.
gamma (float): discount factor.
tau (float): target network synchronization coefficiency.
n_critics (int): the number of Q functions for ensemble.
bootstrap (bool): flag to bootstrap Q functions.
share_encoder (bool): flag to share encoder network.
update_actor_interval (int): interval to update policy function.
lam (float): weight factor for critic ensemble.
n_action_samples (int): the number of action samples to estimate
action-values.
action_flexibility (float): output scale of perturbation function
represented as :math:`\Phi`.
rl_start_epoch (int): epoch to start to update policy function and Q
functions. If this is large, RL training would be more stabilized.
latent_size (int): size of latent vector for Conditional VAE.
beta (float): KL reguralization term for Conditional VAE.
use_gpu (bool, int or d3rlpy.gpu.Device):
flag to use GPU, device ID or device.
scaler (d3rlpy.preprocessing.Scaler or str): preprocessor.
The available options are `['pixel', 'min_max', 'standard']`
augmentation (d3rlpy.augmentation.AugmentationPipeline or list(str)):
augmentation pipeline.
generator (d3rlpy.algos.base.DataGenerator): dynamic dataset generator
(e.g. model-based RL).
impl (d3rlpy.algos.torch.bcq_impl.BCQImpl): algorithm implementation.
"""
_actor_learning_rate: float
_critic_learning_rate: float
_imitator_learning_rate: float
_actor_optim_factory: OptimizerFactory
_critic_optim_factory: OptimizerFactory
_imitator_optim_factory: OptimizerFactory
_actor_encoder_factory: EncoderFactory
_critic_encoder_factory: EncoderFactory
_imitator_encoder_factory: EncoderFactory
_q_func_factory: QFunctionFactory
_tau: float
_n_critics: int
_bootstrap: bool
_share_encoder: bool
_update_actor_interval: int
_lam: float
_n_action_samples: int
_action_flexibility: float
_rl_start_epoch: int
_latent_size: int
_beta: float
_augmentation: AugmentationPipeline
_use_gpu: Optional[Device]
_impl: Optional[BCQImpl]
def __init__(
self,
*,
actor_learning_rate: float = 1e-3,
critic_learning_rate: float = 1e-3,
imitator_learning_rate: float = 1e-3,
actor_optim_factory: OptimizerFactory = AdamFactory(),
critic_optim_factory: OptimizerFactory = AdamFactory(),
imitator_optim_factory: OptimizerFactory = AdamFactory(),
actor_encoder_factory: EncoderArg = "default",
critic_encoder_factory: EncoderArg = "default",
imitator_encoder_factory: EncoderArg = "default",
q_func_factory: QFuncArg = "mean",
batch_size: int = 100,
n_frames: int = 1,
n_steps: int = 1,
gamma: float = 0.99,
tau: float = 0.005,
n_critics: int = 2,
bootstrap: bool = False,
share_encoder: bool = False,
update_actor_interval: int = 1,
lam: float = 0.75,
n_action_samples: int = 100,
action_flexibility: float = 0.05,
rl_start_epoch: int = 0,
latent_size: int = 32,
beta: float = 0.5,
use_gpu: UseGPUArg = False,
scaler: ScalerArg = None,
augmentation: AugmentationArg = None,
generator: Optional[DataGenerator] = None,
impl: Optional[BCQImpl] = None,
**kwargs: Any
):
super().__init__(
batch_size=batch_size,
n_frames=n_frames,
n_steps=n_steps,
gamma=gamma,
scaler=scaler,
generator=generator,
)
self._actor_learning_rate = actor_learning_rate
self._critic_learning_rate = critic_learning_rate
self._imitator_learning_rate = imitator_learning_rate
self._actor_optim_factory = actor_optim_factory
self._critic_optim_factory = critic_optim_factory
self._imitator_optim_factory = imitator_optim_factory
self._actor_encoder_factory = check_encoder(actor_encoder_factory)
self._critic_encoder_factory = check_encoder(critic_encoder_factory)
self._imitator_encoder_factory = check_encoder(imitator_encoder_factory)
self._q_func_factory = check_q_func(q_func_factory)
self._tau = tau
self._n_critics = n_critics
self._bootstrap = bootstrap
self._share_encoder = share_encoder
self._update_actor_interval = update_actor_interval
self._lam = lam
self._n_action_samples = n_action_samples
self._action_flexibility = action_flexibility
self._rl_start_epoch = rl_start_epoch
self._latent_size = latent_size
self._beta = beta
self._augmentation = check_augmentation(augmentation)
self._use_gpu = check_use_gpu(use_gpu)
self._impl = impl
def create_impl(
self, observation_shape: Sequence[int], action_size: int
) -> None:
self._impl = BCQImpl(
observation_shape=observation_shape,
action_size=action_size,
actor_learning_rate=self._actor_learning_rate,
critic_learning_rate=self._critic_learning_rate,
imitator_learning_rate=self._imitator_learning_rate,
actor_optim_factory=self._actor_optim_factory,
critic_optim_factory=self._critic_optim_factory,
imitator_optim_factory=self._imitator_optim_factory,
actor_encoder_factory=self._actor_encoder_factory,
critic_encoder_factory=self._critic_encoder_factory,
imitator_encoder_factory=self._imitator_encoder_factory,
q_func_factory=self._q_func_factory,
gamma=self._gamma,
tau=self._tau,
n_critics=self._n_critics,
bootstrap=self._bootstrap,
share_encoder=self._share_encoder,
lam=self._lam,
n_action_samples=self._n_action_samples,
action_flexibility=self._action_flexibility,
latent_size=self._latent_size,
beta=self._beta,
use_gpu=self._use_gpu,
scaler=self._scaler,
augmentation=self._augmentation,
)
self._impl.build()
def update(
self, epoch: int, total_step: int, batch: TransitionMiniBatch
) -> List[Optional[float]]:
assert self._impl is not None
imitator_loss = self._impl.update_imitator(
batch.observations, batch.actions
)
if epoch >= self._rl_start_epoch:
critic_loss = self._impl.update_critic(
batch.observations,
batch.actions,
batch.next_rewards,
batch.next_observations,
batch.terminals,
batch.n_steps,
)
if total_step % self._update_actor_interval == 0:
actor_loss = self._impl.update_actor(batch.observations)
self._impl.update_actor_target()
self._impl.update_critic_target()
else:
actor_loss = None
else:
critic_loss = None
actor_loss = None
return [critic_loss, actor_loss, imitator_loss]
def sample_action(self, x: Union[np.ndarray, List[Any]]) -> np.ndarray:
"""BCQ does not support sampling action."""
raise NotImplementedError("BCQ does not support sampling action.")
def _get_loss_labels(self) -> List[str]:
return ["critic_loss", "actor_loss", "imitator_loss"]
class DiscreteBCQ(AlgoBase):
r"""Discrete version of Batch-Constrained Q-learning algorithm.
Discrete version takes theories from the continuous version, but the
algorithm is much simpler than that.
The imitation function :math:`G_\omega(a|s)` is trained as supervised
learning just like Behavior Cloning.
.. math::
L(\omega) = \mathbb{E}_{a_t, s_t \sim D}
[-\sum_a p(a|s_t) \log G_\omega(a|s_t)]
With this imitation function, the greedy policy is defined as follows.
.. math::
\pi(s_t) = \text{argmax}_{a|G_\omega(a|s_t)
/ \max_{\tilde{a}} G_\omega(\tilde{a}|s_t) > \tau}
Q_\theta (s_t, a)
which eliminates actions with probabilities :math:`\tau` times smaller
than the maximum one.
Finally, the loss function is computed in Double DQN style with the above
constrained policy.
.. math::
L(\theta) = \mathbb{E}_{s_t, a_t, r_{t+1}, s_{t+1} \sim D} [(r_{t+1}
+ \gamma Q_{\theta'}(s_{t+1}, \pi(s_{t+1}))
- Q_\theta(s_t, a_t))^2]
References:
* `Fujimoto et al., Off-Policy Deep Reinforcement Learning without
Exploration. <https://arxiv.org/abs/1812.02900>`_
* `Fujimoto et al., Benchmarking Batch Deep Reinforcement Learning
Algorithms. <https://arxiv.org/abs/1910.01708>`_
Args:
learning_rate (float): learning rate.
optim_factory (d3rlpy.optimizers.OptimizerFactory): optimizer factory.
encoder_factory (d3rlpy.encoders.EncoderFactory or str):
encoder factory.
q_func_factory (d3rlpy.q_functions.QFunctionFactory or str):
Q function factory.
batch_size (int): mini-batch size.
n_frames (int): the number of frames to stack for image observation.
n_steps (int): N-step TD calculation.
gamma (float): discount factor.
n_critics (int): the number of Q functions for ensemble.
bootstrap (bool): flag to bootstrap Q functions.
share_encoder (bool): flag to share encoder network.
action_flexibility (float): probability threshold represented as
:math:`\tau`.
beta (float): reguralization term for imitation function.
target_update_interval (int): interval to update the target network.
use_gpu (bool, int or d3rlpy.gpu.Device):
flag to use GPU, device ID or device.
scaler (d3rlpy.preprocessing.Scaler or str): preprocessor.
The available options are `['pixel', 'min_max', 'standard']`
augmentation (d3rlpy.augmentation.AugmentationPipeline or list(str)):
augmentation pipeline.
generator (d3rlpy.algos.base.DataGenerator): dynamic dataset generator
(e.g. model-based RL).
impl (d3rlpy.algos.torch.bcq_impl.DiscreteBCQImpl):
algorithm implementation.
"""
_learning_rate: float
_optim_factory: OptimizerFactory
_encoder_factory: EncoderFactory
_q_func_factory: QFunctionFactory
_n_critics: int
_bootstrap: bool
_share_encoder: bool
_action_flexibility: float
_beta: float
_target_update_interval: int
_augmentation: AugmentationPipeline
_use_gpu: Optional[Device]
_impl: Optional[DiscreteBCQImpl]
def __init__(
self,
*,
learning_rate: float = 6.25e-5,
optim_factory: OptimizerFactory = AdamFactory(),
encoder_factory: EncoderArg = "default",
q_func_factory: QFuncArg = "mean",
batch_size: int = 32,
n_frames: int = 1,
n_steps: int = 1,
gamma: float = 0.99,
n_critics: int = 1,
bootstrap: bool = False,
share_encoder: bool = False,
action_flexibility: float = 0.3,
beta: float = 0.5,
target_update_interval: int = 8000,
use_gpu: UseGPUArg = False,
scaler: ScalerArg = None,
augmentation: AugmentationArg = None,
generator: Optional[DataGenerator] = None,
impl: Optional[DiscreteBCQImpl] = None,
**kwargs: Any
):
super().__init__(
batch_size=batch_size,
n_frames=n_frames,
n_steps=n_steps,
gamma=gamma,
scaler=scaler,
generator=generator,
)
self._learning_rate = learning_rate
self._optim_factory = optim_factory
self._encoder_factory = check_encoder(encoder_factory)
self._q_func_factory = check_q_func(q_func_factory)
self._n_critics = n_critics
self._bootstrap = bootstrap
self._share_encoder = share_encoder
self._action_flexibility = action_flexibility
self._beta = beta
self._target_update_interval = target_update_interval
self._augmentation = check_augmentation(augmentation)
self._use_gpu = check_use_gpu(use_gpu)
self._impl = impl
def create_impl(
self, observation_shape: Sequence[int], action_size: int
) -> None:
self._impl = DiscreteBCQImpl(
observation_shape=observation_shape,
action_size=action_size,
learning_rate=self._learning_rate,
optim_factory=self._optim_factory,
encoder_factory=self._encoder_factory,
q_func_factory=self._q_func_factory,
gamma=self._gamma,
n_critics=self._n_critics,
bootstrap=self._bootstrap,
share_encoder=self._share_encoder,
action_flexibility=self._action_flexibility,
beta=self._beta,
use_gpu=self._use_gpu,
scaler=self._scaler,
augmentation=self._augmentation,
)
self._impl.build()
def update(
self, epoch: int, total_step: int, batch: TransitionMiniBatch
) -> List[Optional[float]]:
assert self._impl is not None
loss = self._impl.update(
batch.observations,
batch.actions,
batch.next_rewards,
batch.next_observations,
batch.terminals,
batch.n_steps,
)
if total_step % self._target_update_interval == 0:
self._impl.update_target()
return [loss]
def _get_loss_labels(self) -> List[str]:
return ["loss"]
| [
"takuma.seno@gmail.com"
] | takuma.seno@gmail.com |
feadd1b682627b154efe8b4af6e59c03c941920b | c0344beb70872a4efb097fa3cf39cc1e8d01dd89 | /neural_networks_from_scratch/chap_2.py | a134de791eedf26841bc93dd12ee68e466930106 | [] | no_license | szhongren/nnfs | cb3b819a509545cf7d5d78e18b053b0a238d4f8a | 8e6783745d0d42dcf50f2347d5175857bf290890 | refs/heads/main | 2023-02-16T04:22:04.734752 | 2020-12-11T02:47:01 | 2020-12-11T02:47:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,313 | py | import numpy as np
def main():
print("chap_2")
single_neuron()
single_neuron_alt()
three_neurons()
three_neurons_loop()
dot_product()
single_neuron_numpy()
three_neurons_numpy()
matrix_product()
three_neurons_batched_numpy()
print("=" * 100)
def single_neuron():
inputs = [1, 2, 3]
weights = [0.2, 0.8, -0.5]
bias = 2
# outputs = (
# inputs[0] * weights[0] + inputs[1] * weights[1] + inputs[2] * weights[2] + bias
# )
outputs = sum(map(lambda tup: tup[0] * tup[1], zip(inputs, weights))) + bias
print(outputs)
def single_neuron_alt():
inputs = [1.0, 2.0, 3.0, 2.5]
weights = [0.2, 0.8, -0.5, 1.0]
bias = 2.0
# outputs = (
# inputs[0] * weights[0] + inputs[1] * weights[1] + inputs[2] * weights[2] + bias
# )
outputs = sum(map(lambda tup: tup[0] * tup[1], zip(inputs, weights))) + bias
print(outputs)
def three_neurons():
inputs = [1, 2, 3, 2.5]
weights1 = [0.2, 0.8, -0.5, 1]
weights2 = [0.5, -0.91, 0.26, -0.5]
weights3 = [-0.26, -0.27, 0.17, 0.87]
bias1 = 2
bias2 = 3
bias3 = 0.5
outputs = [
# Neuron 1:
sum(map(lambda tup: tup[0] * tup[1], zip(inputs, weights1))) + bias1,
# Neuron 2:
sum(map(lambda tup: tup[0] * tup[1], zip(inputs, weights2))) + bias2,
# Neuron 3:
sum(map(lambda tup: tup[0] * tup[1], zip(inputs, weights3))) + bias3,
]
print(outputs)
def three_neurons_loop():
inputs = [1, 2, 3, 2.5]
weights = [
[0.2, 0.8, -0.5, 1],
[0.5, -0.91, 0.26, -0.5],
[-0.26, -0.27, 0.17, 0.87],
]
biases = [2, 3, 0.5]
layer_outputs = []
for neuron_weights, neuron_bias in zip(weights, biases):
neuron_output = 0
for n_input, n_weight in zip(inputs, neuron_weights):
neuron_output += n_input * n_weight
neuron_output += neuron_bias
layer_outputs.append(neuron_output)
print(layer_outputs)
def dot_product():
a = [1, 2, 3]
b = [2, 3, 4]
dot_product_result = sum(map(lambda tup: tup[0] * tup[1], zip(a, b)))
print(dot_product_result)
def single_neuron_numpy():
inputs = [1.0, 2.0, 3.0, 2.5]
weights = [0.2, 0.8, -0.5, 1.0]
bias = 2.0
outputs = np.dot(weights, inputs) + bias
print(outputs)
def three_neurons_numpy():
inputs = [1.0, 2.0, 3.0, 2.5]
weights = [
[0.2, 0.8, -0.5, 1],
[0.5, -0.91, 0.26, -0.5],
[-0.26, -0.27, 0.17, 0.87],
]
biases = [2.0, 3.0, 0.5]
# np.dot(weights, inputs) = [
# np.dot(weights[0], inputs),
# np.dot(weights[1], inputs),
# np.dot(weights[2], inputs),
# ]
layer_outputs = np.dot(weights, inputs) + biases
print(layer_outputs)
def matrix_product():
a = [1, 2, 3]
b = [2, 3, 4]
a = np.array([a])
b = np.array([b]).T
result = np.dot(a, b)
print(result)
def three_neurons_batched_numpy():
inputs = [[1.0, 2.0, 3.0, 2.5], [2.0, 5.0, -1.0, 2.0], [-1.5, 2.7, 3.3, -0.8]]
weights = [
[0.2, 0.8, -0.5, 1.0],
[0.5, -0.91, 0.26, -0.5],
[-0.26, -0.27, 0.17, 0.87],
]
biases = [2.0, 3.0, 0.5]
layer_outputs = np.dot(inputs, np.array(weights).T) + biases
print(layer_outputs)
| [
"shao.zhongren@gmail.com"
] | shao.zhongren@gmail.com |
cb83f3868e5f1ba544615d3cbf9eae9e7a063a65 | 861d25fe3985340dae621d179f7af368e0dd7f39 | /stockweb/stock/maintest.py | b0e4d03f456e78a8ad2feb9e649b08d85c6fec21 | [] | no_license | zhuwei302/python | 1ebcfac3e4f208ba81af93d13b8857bea9497862 | dfad635149b8f307ae0eb5b2b8c348843de663bb | refs/heads/master | 2021-01-19T18:44:32.843216 | 2018-09-18T15:17:21 | 2018-09-18T15:17:21 | 101,160,521 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 518 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2016/12/20 0020 17:36
# @Author : Aries
# @Site :
# @File : maintest.py
# @Software: PyCharm
if __name__=='__main__':
dic = {'000001':1.32,'20002':1.24,'60003':1.0,'60005':2.1}
new_dic = {}
l = sorted(dic.iteritems(), key=lambda d: d[1], reverse=False)
for i in range(len(l)):
if len(l[i])==2:
new_dic[str(i)+'--'+l[i][0]] = l[i][1]
for key in new_dic.keys():
print new_dic.get(key)
print new_dic | [
"244840434@qq.com"
] | 244840434@qq.com |
7c1956434714aa0adb907492eb23dcfe1ac80279 | 9f5c2728b1ab844bf3110cce78e4083283943ebb | /DataVisualization/chapter_15/dice_visual.py | dc0f108511ae1e6222c4a75f07bb80d88ee689de | [] | no_license | leetuckert10/CrashCourse | 9838448e75636132169498f152200651a05181c4 | 3f35958de497026da5e7d0d0a52fe3f20f2ef196 | refs/heads/master | 2023-05-01T11:56:27.382141 | 2020-04-02T19:11:07 | 2020-04-02T19:11:07 | 249,979,785 | 0 | 0 | null | 2023-04-21T20:48:10 | 2020-03-25T13:01:08 | Python | UTF-8 | Python | false | false | 1,857 | py | # dice_visual.py
# This version and the Die class have enhancements beyond what was laid out
# in Crash Course such that rolling multiple dice is made much easier. You
# only change the number of dice in one place.
from typing import List, Dict
from plotly.graph_objects import Bar, Layout # type: ignore
from plotly import offline # type: ignore
from die import Die
# Create multi-sided dice.
num_dice: int = 6
num_sides: int = 6
num_rolls: int = 500_000
max_result: int = 0
for x in range(1, num_dice + 1):
die = Die(num_sides)
max_result = max_result + die.num_sides
# We roll the number dice 1,000 times and then we store the sum of the dice
# in a list.
results: List[int] = []
result: int = 0
for roll in range(1, num_rolls + 1):
for die in Die.instances:
result = result + die.roll()
results.append(result)
result = 0
# Analyze the results. Bar() needs a list of values in the call to it.
frequencies: List[int] = []
for value in range(num_dice, max_result + 1):
frequencies.append(results.count(value))
# The sum of all sides is the maximum number that can be returned and the
# minimum number that can only be 1 times the number of dice.
# Convert the range of sides to a list for the call to Bar().
x_values: List[int] = list(range(num_dice, max_result + 1))
data: List[Bar] = [Bar(x=x_values, y=frequencies)]
# The 'dtick' dictionary argument tells Plotly to label every tick mark.
x_axis_config: Dict = {'title': 'Result', 'dtick': 1}
y_axis_config: Dict = {'title': 'Frequency of Result'}
title_str: str = f"Results of rolling {num_dice} D{num_sides} {num_rolls} " \
f"times."
my_layout: Layout = Layout(title=title_str, xaxis=x_axis_config,
yaxis=y_axis_config)
offline.plot({'data': data, 'layout': my_layout}, filename='d6_d6.html')
| [
"n4tlt.radio@gmail.com"
] | n4tlt.radio@gmail.com |
c16f345b9e70eca292351541d6fcb0f362b90723 | 2c4763aa544344a3a615f9a65d1ded7d0f59ae50 | /waflib/Tools/compiler_fc.py | a2a3032ab4e091a185ac288c0cd38ca181ebc167 | [] | no_license | afeldman/waf | 572bf95d6b11571bbb2941ba0fe463402b1e39f3 | 4c489b38fe1520ec1bc0fa7e1521f7129c20f8b6 | refs/heads/master | 2021-05-09T18:18:16.598191 | 2019-03-05T06:33:42 | 2019-03-05T06:33:42 | 58,713,085 | 0 | 0 | null | 2016-05-13T07:34:33 | 2016-05-13T07:34:33 | null | UTF-8 | Python | false | false | 2,235 | py | #!/usr/bin/env python
# encoding: utf-8
import re
from waflib import Utils, Logs
from waflib.Tools import fc
fc_compiler = {
'win32' : ['gfortran','ifort'],
'darwin' : ['gfortran', 'g95', 'ifort'],
'linux' : ['gfortran', 'g95', 'ifort'],
'java' : ['gfortran', 'g95', 'ifort'],
'default': ['gfortran'],
'aix' : ['gfortran']
}
"""
Dict mapping the platform names to lists of names of Fortran compilers to try, in order of preference::
from waflib.Tools.compiler_c import c_compiler
c_compiler['linux'] = ['gfortran', 'g95', 'ifort']
"""
def default_compilers():
build_platform = Utils.unversioned_sys_platform()
possible_compiler_list = fc_compiler.get(build_platform, fc_compiler['default'])
return ' '.join(possible_compiler_list)
def configure(conf):
"""
Detects a suitable Fortran compiler
:raises: :py:class:`waflib.Errors.ConfigurationError` when no suitable compiler is found
"""
try:
test_for_compiler = conf.options.check_fortran_compiler or default_compilers()
except AttributeError:
conf.fatal("Add options(opt): opt.load('compiler_fc')")
for compiler in re.split('[ ,]+', test_for_compiler):
conf.env.stash()
conf.start_msg('Checking for %r (Fortran compiler)' % compiler)
try:
conf.load(compiler)
except conf.errors.ConfigurationError as e:
conf.env.revert()
conf.end_msg(False)
Logs.debug('compiler_fortran: %r', e)
else:
if conf.env.FC:
conf.end_msg(conf.env.get_flat('FC'))
conf.env.COMPILER_FORTRAN = compiler
conf.env.commit()
break
conf.env.revert()
conf.end_msg(False)
else:
conf.fatal('could not configure a Fortran compiler!')
def options(opt):
"""
This is how to provide compiler preferences on the command-line::
$ waf configure --check-fortran-compiler=ifort
"""
test_for_compiler = default_compilers()
opt.load_special_tools('fc_*.py')
fortran_compiler_opts = opt.add_option_group('Configuration options')
fortran_compiler_opts.add_option('--check-fortran-compiler', default=None,
help='list of Fortran compiler to try [%s]' % test_for_compiler,
dest="check_fortran_compiler")
for x in test_for_compiler.split():
opt.load('%s' % x)
| [
"anton.feldmann@outlook.de"
] | anton.feldmann@outlook.de |
fbe16676768a4832f58e641a6e26c7336eb8ee39 | 321b4ed83b6874eeb512027eaa0b17b0daf3c289 | /1029/1029.two-city-scheduling.233252483.Accepted.leetcode.py | ff9ecc8ea5b98d76c93e827e263c8240e0de39b0 | [] | no_license | huangyingw/submissions | 7a610613bdb03f1223cdec5f6ccc4391149ca618 | bfac1238ecef8b03e54842b852f6fec111abedfa | refs/heads/master | 2023-07-25T09:56:46.814504 | 2023-07-16T07:38:36 | 2023-07-16T07:38:36 | 143,352,065 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 343 | py | class Solution(object):
def twoCitySchedCost(self, costs):
result = 0
costs = sorted(costs, key=lambda x: x[0] - x[1])
for index in range(len(costs)):
if index < len(costs) // 2:
result += costs[index][0]
else:
result += costs[index][1]
return result
| [
"huangyingw@gmail.com"
] | huangyingw@gmail.com |
8db86b66c9fff23e9398a22702a42bbb242c2967 | 8ef5a09d76a11c56963f18e6a08474a1a8bafe3c | /leet_code/371. Sum of Two Integers.py | de6f6d30d4cd6e9f11ea559e4459cd6409de9100 | [] | no_license | roiei/algo | 32c4677649c7666db148f6183fbfbf66c8b1969f | ae8bb8bf4ae4026ccaf1dce323b4098547dd35ec | refs/heads/master | 2022-04-01T19:21:27.768675 | 2022-02-19T06:15:29 | 2022-02-19T06:15:29 | 169,021,154 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 585 | py | import time
from util.util_list import *
from util.util_tree import *
import copy
import collections
import heapq
from typing import List
class Solution:
def getSum(self, a: int, b: int) -> int:
while b != 0:
a = (a ^ b) & 0X1FFFFFFFF
b = ((a & b) << 1) & 0X1FFFFFFFF
if a < 0XFFFFFFFF:
return a
return ~((~a) & 0XFFFFFFFF)
stime = time.time()
print(3 == Solution().getSum(a = 1, b = 2))
print(1 == Solution().getSum(a = -2, b = 3))
print('elapse time: {} sec'.format(time.time() - stime))
| [
"hyoukjea.son@hyundai.com"
] | hyoukjea.son@hyundai.com |
341fc784d325d2865edbc349b267f8280aaf7129 | d2aae22870acefa1353dca86351ae94217d0f026 | /12.reinforcement_learning_with_mario_bros/2023/hard_coding/2.0.clustering_images.py | 952824e83fbf69324924dfe264774515a1224b4f | [
"MIT"
] | permissive | yingshaoxo/ML | 9c3169f2f8c7e98e0ad5ddc56fe81797a10df420 | 038fb5afe017b82334ad39a256531d2c4e9e1e1a | refs/heads/master | 2023-08-03T10:51:30.779007 | 2023-08-02T17:45:30 | 2023-08-02T17:45:30 | 137,086,679 | 5 | 1 | MIT | 2023-05-16T10:31:28 | 2018-06-12T14:49:58 | Python | UTF-8 | Python | false | false | 1,810 | py | from auto_everything.disk import Disk
disk = Disk()
from sewar.full_ref import msssim, uqi
import cv2
current_folder = disk.get_directory_path(__file__)
output_folder = disk.join_paths(current_folder, "seperated_classes")
disk.create_a_folder(output_folder)
#images = disk.get_files(folder=disk.join_paths(current_folder, "raw_seperate_images"))
images = disk.get_files(folder=disk.join_paths(current_folder, "raw_images"))
images_dict = {image_path:cv2.imread(image_path) for image_path in images}
relation_rate = 0.95
classes = {}
index = 0
for image_path_1 in list(images_dict.keys()).copy():
if image_path_1 not in images_dict.keys():
continue
image_1 = images_dict[image_path_1]
for image_path_2 in list(images_dict.keys()).copy():
if image_path_2 not in images_dict.keys():
continue
if image_path_1 != image_path_2:
image_2 = images_dict[image_path_2]
similarity = msssim(image_1, image_2)
# print(similarity)
if similarity >= relation_rate:
# print("found")
# print(image_path_1)
# print(image_path_2)
# exit()
if index not in classes.keys():
classes[index] = []
classes[index].append(image_path_2)
del images_dict[image_path_2]
if index in classes.keys():
classes[index].append(image_path_1)
del images_dict[image_path_1]
# copy images to related folder
for path in classes[index]:
disk.copy_a_file(path, disk.join_paths(output_folder, str(index), disk.get_file_name(path)) )
print(f"index {index} done.")
index += 1
else:
# finished
break
print("Done.") | [
"yingshaoxo@gmail.com"
] | yingshaoxo@gmail.com |
cafdf9e580d62bc12021c2f8ceb4516dfe36b24a | 3d0a2390047e0ede5df661255f6e72fab5d534f2 | /blog/urls.py | 9ddb0b0677e59536ec59685841269e5d21058474 | [] | no_license | sompodsign/Django_Personal_portfolio | 5f932e3ba27f802768735d6f91ef105ad168289a | 9e833a7728f46cd33c2f512a3840e70f49a2dd08 | refs/heads/master | 2022-12-12T01:59:14.770507 | 2020-08-31T07:45:41 | 2020-08-31T07:45:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 197 | py |
from django.urls import path
from blog import views
app_name = 'blog'
urlpatterns = [
path('', views.all_blogs, name='all_blogs'),
path('<int:blog_id>/', views.detail, name='detail'),
]
| [
"sompodsign@gmail.com"
] | sompodsign@gmail.com |
134719d8c196e98b85190c6ef8ddb801276374aa | 8acb7f5f98217fc3aacaaefa104c499627e90aae | /0x0B_redis_basic/exercise.py | cd0c1f852150144cd3eb35a5847e233b07baeb49 | [] | no_license | zulsb/holbertonschool-web_back_end | cb756386382eaaff373a37732247ca8d2c5f7a18 | 15931a555a28ed3bed5822d0f8b4b4c9a5f6a985 | refs/heads/main | 2023-05-06T00:52:40.278552 | 2021-05-22T21:33:15 | 2021-05-22T21:33:15 | 305,504,958 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,870 | py | #!/usr/bin/env python3
""" Redis module.
"""
import redis
import uuid
from functools import wraps
from sys import byteorder
from typing import Union, Optional, Callable
def count_calls(method: Callable) -> Callable:
""" Method that count calls.
"""
key = method.__qualname__
@wraps(method)
def wrapper(self, *args, **keywords):
""" Method wrapper.
"""
self._redis.incr(key)
return method(self, *args, **keywords)
return wrapper
def call_history(method: Callable) -> Callable:
""" Method that store the history of inputs and outputs
for a particular function.
"""
key = method.__qualname__
@wraps(method)
def wrapper(self, *args):
""" Method wrapper.
"""
self._redis.rpush("{}:inputs".format(key), str(args))
history = method(self, *args)
self._redis.rpush("{}:outputs".format(key),
str(history))
return history
return wrapper
def replay(method: Callable):
""" Method that display the history of calls
of a particular function.
"""
r = method.__self__._redis
keys = method.__qualname__
inputs = r.lrange("{}:inputs".format(keys), 0, -1)
outputs = r.lrange("{}:outputs".format(keys), 0, -1)
print("{} was called {} times:".format(keys,
r.get(keys).decode("utf-8")))
for i, j in list(zip(inputs, outputs)):
print("{}(*{}) -> {}".format(keys, i.decode("utf-8"),
j.decode("utf-8")))
class Cache:
""" Cache class.
"""
def __init__(self):
""" Initializer.
"""
self._redis = redis.Redis()
self._redis.flushdb()
@count_calls
@call_history
def store(self, data: Union[str, bytes, int, float]) -> str:
""" Method that generate a random key,
store the input data in Redis using the random key.
Arg:
data: Can be a str, bytes, int or float.
Return:
The key as string.
"""
key = str(uuid.uuid4())
self._redis.set(key, data)
return key
def get(self, key: str, fn: Optional[Callable] = None):
""" This callable will be used to convert
the data back to the desired format.
Args:
key: string type.
fn: Optional[Callable].
Return:
The convert data.
"""
data = self._redis.get(key)
return fn(data) if fn else data
def get_str(self, data: bytes) -> str:
""" Method that get a string from bytes.
"""
return data.decode("utf-8")
def get_int(self, data: bytes) -> int:
""" Method that get a int from bytes.
"""
return int.from_bytes(data, byteorder)
| [
"zulsb2093@gmail.com"
] | zulsb2093@gmail.com |
a7735f2687501d0c866a019685343953dd831d98 | aca209472c7288d69adf57124c197baf98c7a6e7 | /OpenCV讀者資源/讀者資源/程式實例/ch9/ch9_12.py | 100c8a3ac4fffab2f56bfd9d003d3496ab4b1ea9 | [] | no_license | Hank-Liao-Yu-Chih/document | 712790325e48b9d8115d04b5cc2a90cd78431e61 | fafe616678cd224e70936296962dcdbbf55e38b3 | refs/heads/master | 2022-09-22T12:40:33.284033 | 2022-09-08T00:33:41 | 2022-09-08T00:33:41 | 102,203,601 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 355 | py | # ch9_12.py
import cv2
import numpy as np
thresh = 127 # 定義閾值
maxval = 255 # 定義像素最大值
src = np.random.randint(0,256,size=[3,5],dtype=np.uint8)
ret, dst = cv2.threshold(src,thresh,maxval,cv2.THRESH_TOZERO)
print(f"src =\n {src}")
print(f"threshold = {ret}")
print(f"dst =\n {dst}")
| [
"hank.liao@vicorelogic.com"
] | hank.liao@vicorelogic.com |
ffd1dd4408a8e7560f6281565bad2cef09a337d5 | 56cce3fee2e3d69d60958eb2aacc4f65fc3d2230 | /tests/test_graph_view.py | 2bcd8da7e69e4d68de3118a177d781ae621ceca7 | [
"BSD-3-Clause"
] | permissive | nokia/PyBGL | 52c2f175d1dbccb15519f8a16de141845d0abaf3 | 707f2df32ede7d9a992ea217a4791da34f13e138 | refs/heads/master | 2023-08-08T04:46:24.931627 | 2023-08-03T16:31:35 | 2023-08-03T16:31:35 | 148,536,169 | 12 | 3 | BSD-3-Clause | 2023-08-03T16:31:36 | 2018-09-12T20:11:36 | Python | UTF-8 | Python | false | false | 3,228 | py | #!/usr/bin/env pytest-3
# -*- coding: utf-8 -*-
from pybgl.graph import DirectedGraph
from pybgl.graph_view import GraphView
from pybgl.html import html
from pybgl.ipynb import ipynb_display_graph
from pybgl.property_map import make_func_property_map
def make_graph() -> DirectedGraph:
g = DirectedGraph(10)
for u in g.vertices():
if u < g.num_vertices() - 1:
g.add_edge(u, u + 1)
return g
def test_graph_view_default():
print("test_graph_view_default")
g = make_graph()
gv = GraphView(g)
e = next(iter(gv.edges()))
print(e)
assert gv.source(e) == 0
assert gv.target(e) == 1
html("gv")
ipynb_display_graph(gv)
assert set(g.vertices()) == set(gv.vertices())
assert set(g.edges()) == set(gv.edges())
assert set(g.out_edges(0)) == set(gv.out_edges(0))
assert g.out_degree(0) == gv.out_degree(0)
gv1 = GraphView(
g,
pmap_vrelevant=make_func_property_map(
lambda u: bool(u % 3 != 0)
)
)
html("gv1")
ipynb_display_graph(gv1)
assert gv1.num_vertices() == 6
assert gv1.num_edges() == 3
gv2 = GraphView(
g,
pmap_erelevant=make_func_property_map(
lambda e: bool(gv.source(e) % 2)
)
)
html("gv2")
ipynb_display_graph(gv2)
assert set(g.vertices()) == set(gv2.vertices())
assert set(g.edges()) != set(gv2.edges())
assert gv2.num_vertices() == g.num_vertices()
assert gv2.num_edges() == 4
def test_graph_view_or():
print("test_graph_view_or")
g = make_graph()
gv1 = GraphView(g, pmap_vrelevant=make_func_property_map(lambda u: u < 5))
gv2 = GraphView(g, pmap_vrelevant=make_func_property_map(lambda u: u > 5))
gv = gv1 | gv2
html("gv1")
ipynb_display_graph(gv1)
html("gv2")
ipynb_display_graph(gv2)
html("gv1 | gv2")
ipynb_display_graph(gv)
assert gv.num_vertices() == 9
assert gv.num_edges() == 7
def test_graph_view_and():
g = make_graph()
gv1 = GraphView(g, pmap_vrelevant=make_func_property_map(lambda u: u > 2))
gv2 = GraphView(g, pmap_vrelevant=make_func_property_map(lambda u: u < 6))
gv = gv1 & gv2
html("gv1")
ipynb_display_graph(gv1)
html("gv2")
ipynb_display_graph(gv2)
html("gv1 & gv2")
ipynb_display_graph(gv)
assert set(g.vertices()) != set(gv.vertices())
assert set(g.edges()) != set(gv.edges())
assert set(g.out_edges(2)) != set(gv.out_edges(2))
assert set(g.out_edges(3)) == set(gv.out_edges(3))
assert set(g.out_edges(4)) == set(gv.out_edges(4))
assert set(g.out_edges(5)) != set(gv.out_edges(5))
assert gv.num_vertices() == 3
assert gv.num_edges() == 2
def test_graph_view_sub():
g = make_graph()
gv1 = GraphView(g, pmap_vrelevant=make_func_property_map(lambda u: u > 2))
gv2 = GraphView(g, pmap_vrelevant=make_func_property_map(lambda u: u > 6))
gv = gv1 - gv2
html("gv1")
ipynb_display_graph(gv1)
html("gv2")
ipynb_display_graph(gv2)
html("gv1 - gv2")
ipynb_display_graph(gv)
assert set(g.vertices()) != set(gv.vertices())
assert set(g.edges()) != set(gv.edges())
assert gv.num_vertices() == 4
assert gv.num_edges() == 3
| [
"marc-olivier.buob@nokia-bell-labs.com"
] | marc-olivier.buob@nokia-bell-labs.com |
8ec471298a63dfdfc9cd0c0c354b374d006f7b57 | 0760fb4901a75766921a205b55686d6d6f049b30 | /rllib/connectors/tests/test_agent.py | dde14a136e0f64cd4504f560ded13a42f648203a | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | permissive | ray-project/ray | a4bb6940b08b59a61ef0b8e755a52d8563a2f867 | edba68c3e7cf255d1d6479329f305adb7fa4c3ed | refs/heads/master | 2023-08-31T03:36:48.164405 | 2023-08-31T03:20:38 | 2023-08-31T03:20:38 | 71,932,349 | 29,482 | 5,669 | Apache-2.0 | 2023-09-14T21:48:14 | 2016-10-25T19:38:30 | Python | UTF-8 | Python | false | false | 23,424 | py | import gymnasium as gym
from gymnasium.spaces import Box
import numpy as np
import tree # pip install dm_tree
import unittest
from ray.rllib.algorithms.ppo.ppo import PPOConfig
from ray.rllib.connectors.agent.clip_reward import ClipRewardAgentConnector
from ray.rllib.connectors.agent.lambdas import FlattenDataAgentConnector
from ray.rllib.connectors.agent.obs_preproc import ObsPreprocessorConnector
from ray.rllib.connectors.agent.pipeline import AgentConnectorPipeline
from ray.rllib.connectors.agent.state_buffer import StateBufferConnector
from ray.rllib.connectors.agent.view_requirement import ViewRequirementAgentConnector
from ray.rllib.connectors.connector import ConnectorContext
from ray.rllib.connectors.registry import get_connector
from ray.rllib.policy.view_requirement import ViewRequirement
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.utils.test_utils import check
from ray.rllib.utils.typing import (
ActionConnectorDataType,
AgentConnectorDataType,
AgentConnectorsOutput,
)
from ray.rllib.connectors.agent.mean_std_filter import (
MeanStdObservationFilterAgentConnector,
)
class TestAgentConnector(unittest.TestCase):
def test_connector_pipeline(self):
ctx = ConnectorContext()
connectors = [ClipRewardAgentConnector(ctx, False, 1.0)]
pipeline = AgentConnectorPipeline(ctx, connectors)
name, params = pipeline.to_state()
restored = get_connector(name, ctx, params)
self.assertTrue(isinstance(restored, AgentConnectorPipeline))
self.assertTrue(isinstance(restored.connectors[0], ClipRewardAgentConnector))
def test_obs_preprocessor_connector(self):
obs_space = gym.spaces.Dict(
{
"a": gym.spaces.Box(low=0, high=1, shape=(1,)),
"b": gym.spaces.Tuple(
[gym.spaces.Discrete(2), gym.spaces.MultiDiscrete(nvec=[2, 3])]
),
}
)
ctx = ConnectorContext(config={}, observation_space=obs_space)
c = ObsPreprocessorConnector(ctx)
name, params = c.to_state()
restored = get_connector(name, ctx, params)
self.assertTrue(isinstance(restored, ObsPreprocessorConnector))
obs = obs_space.sample()
# Fake deterministic data.
obs["a"][0] = 0.5
obs["b"] = (1, np.array([0, 2]))
d = AgentConnectorDataType(
0,
1,
{
SampleBatch.OBS: obs,
},
)
preprocessed = c([d])
# obs is completely flattened.
self.assertTrue(
(preprocessed[0].data[SampleBatch.OBS] == [0.5, 0, 1, 1, 0, 0, 0, 1]).all()
)
def test_clip_reward_connector(self):
ctx = ConnectorContext()
c = ClipRewardAgentConnector(ctx, limit=2.0)
name, params = c.to_state()
self.assertEqual(name, "ClipRewardAgentConnector")
self.assertAlmostEqual(params["limit"], 2.0)
restored = get_connector(name, ctx, params)
self.assertTrue(isinstance(restored, ClipRewardAgentConnector))
d = AgentConnectorDataType(
0,
1,
{
SampleBatch.REWARDS: 5.8,
},
)
clipped = restored([d])
self.assertEqual(len(clipped), 1)
self.assertEqual(clipped[0].data[SampleBatch.REWARDS], 2.0)
def test_flatten_data_connector(self):
ctx = ConnectorContext()
c = FlattenDataAgentConnector(ctx)
name, params = c.to_state()
restored = get_connector(name, ctx, params)
self.assertTrue(isinstance(restored, FlattenDataAgentConnector))
sample_batch = {
SampleBatch.NEXT_OBS: {
"sensor1": [[1, 1], [2, 2]],
"sensor2": 8.8,
},
SampleBatch.REWARDS: 5.8,
SampleBatch.ACTIONS: [[1, 1], [2]],
SampleBatch.INFOS: {"random": "info"},
}
d = AgentConnectorDataType(
0,
1,
# FlattenDataAgentConnector does NOT touch raw_dict,
# so simply pass None here.
AgentConnectorsOutput(None, sample_batch),
)
flattened = c([d])
self.assertEqual(len(flattened), 1)
batch = flattened[0].data.sample_batch
self.assertTrue((batch[SampleBatch.NEXT_OBS] == [1, 1, 2, 2, 8.8]).all())
self.assertEqual(batch[SampleBatch.REWARDS][0], 5.8)
# Not flattened.
self.assertEqual(len(batch[SampleBatch.ACTIONS]), 2)
self.assertEqual(batch[SampleBatch.INFOS]["random"], "info")
def test_state_buffer_connector(self):
ctx = ConnectorContext(
action_space=gym.spaces.Box(low=-1.0, high=1.0, shape=(3,)),
)
c = StateBufferConnector(ctx)
# Reset without any buffered data should do nothing.
c.reset(env_id=0)
d = AgentConnectorDataType(
0,
1,
{
SampleBatch.NEXT_OBS: {
"sensor1": [[1, 1], [2, 2]],
"sensor2": 8.8,
},
},
)
with_buffered = c([d])
self.assertEqual(len(with_buffered), 1)
self.assertTrue((with_buffered[0].data[SampleBatch.ACTIONS] == [0, 0, 0]).all())
c.on_policy_output(ActionConnectorDataType(0, 1, {}, ([1, 2, 3], [], {})))
with_buffered = c([d])
self.assertEqual(len(with_buffered), 1)
self.assertEqual(with_buffered[0].data[SampleBatch.ACTIONS], [1, 2, 3])
def test_mean_std_observation_filter_connector(self):
for bounds in [
(-1, 1), # normalized
(-2, 2), # scaled
(0, 2), # shifted
(0, 4), # scaled and shifted
]:
print("Testing uniform sampling with bounds: {}".format(bounds))
observation_space = Box(bounds[0], bounds[1], (3, 64, 64))
ctx = ConnectorContext(observation_space=observation_space)
filter_connector = MeanStdObservationFilterAgentConnector(ctx)
# Warm up Mean-Std filter
for i in range(1000):
obs = observation_space.sample()
sample_batch = {
SampleBatch.NEXT_OBS: obs,
}
ac = AgentConnectorDataType(0, 0, sample_batch)
filter_connector.transform(ac)
# Create another connector to set state to
_, state = filter_connector.to_state()
another_filter_connector = (
MeanStdObservationFilterAgentConnector.from_state(ctx, state)
)
another_filter_connector.in_eval()
# Collect transformed observations
transformed_observations = []
for i in range(1000):
obs = observation_space.sample()
sample_batch = {
SampleBatch.NEXT_OBS: obs,
}
ac = AgentConnectorDataType(0, 0, sample_batch)
connector_output = another_filter_connector.transform(ac)
transformed_observations.append(
connector_output.data[SampleBatch.NEXT_OBS]
)
# Check if transformed observations are actually mean-std filtered
self.assertTrue(np.isclose(np.mean(transformed_observations), 0, atol=0.1))
self.assertTrue(np.isclose(np.var(transformed_observations), 1, atol=0.1))
# Check if filter parameters where frozen because we are not training
self.assertTrue(
filter_connector.filter.running_stats.num_pushes
== another_filter_connector.filter.running_stats.num_pushes,
)
self.assertTrue(
np.all(
filter_connector.filter.running_stats.mean_array
== another_filter_connector.filter.running_stats.mean_array,
)
)
self.assertTrue(
np.all(
filter_connector.filter.running_stats.std_array
== another_filter_connector.filter.running_stats.std_array,
)
)
self.assertTrue(
filter_connector.filter.buffer.num_pushes
== another_filter_connector.filter.buffer.num_pushes,
)
self.assertTrue(
np.all(
filter_connector.filter.buffer.mean_array
== another_filter_connector.filter.buffer.mean_array,
)
)
self.assertTrue(
np.all(
filter_connector.filter.buffer.std_array
== another_filter_connector.filter.buffer.std_array,
)
)
class TestViewRequirementAgentConnector(unittest.TestCase):
def test_vr_connector_respects_training_or_inference_vr_flags(self):
"""Tests that the connector respects the flags within view_requirements (i.e.
used_for_training, used_for_compute_actions).
the returned data is the input dict itself, which the policy collector in
env_runner will use to construct the episode, and a SampleBatch that can be
used to run corresponding policy.
"""
view_rq_dict = {
"both": ViewRequirement(
"obs", used_for_training=True, used_for_compute_actions=True
),
"only_inference": ViewRequirement(
"obs", used_for_training=False, used_for_compute_actions=True
),
"none": ViewRequirement(
"obs", used_for_training=False, used_for_compute_actions=False
),
"only_training": ViewRequirement(
"obs", used_for_training=True, used_for_compute_actions=False
),
}
obs_arr = np.array([0, 1, 2, 3])
agent_data = {SampleBatch.NEXT_OBS: obs_arr}
data = AgentConnectorDataType(0, 1, agent_data)
config = PPOConfig().to_dict()
ctx = ConnectorContext(
view_requirements=view_rq_dict,
config=config,
is_policy_recurrent=True,
)
sample_batch_expected = SampleBatch(
{
"both": obs_arr[None],
# Output in training model as well.
"only_inference": obs_arr[None],
"seq_lens": np.array([1]),
}
)
c = ViewRequirementAgentConnector(ctx)
c.in_training()
processed = c([data])
raw_dict = processed[0].data.raw_dict
sample_batch = processed[0].data.sample_batch
check(raw_dict, agent_data)
check(sample_batch, sample_batch_expected)
def test_vr_connector_shift_by_one(self):
"""Test that the ViewRequirementAgentConnector can handle shift by one correctly and
can ignore future referencing view_requirements to respect causality"""
view_rq_dict = {
"state": ViewRequirement("obs"),
"next_state": ViewRequirement(
"obs", shift=1, used_for_compute_actions=False
),
"prev_state": ViewRequirement("obs", shift=-1),
}
obs_arrs = np.arange(10)[:, None] + 1
config = PPOConfig().to_dict()
ctx = ConnectorContext(
view_requirements=view_rq_dict, config=config, is_policy_recurrent=True
)
c = ViewRequirementAgentConnector(ctx)
# keep a running list of observations
obs_list = []
for t, obs in enumerate(obs_arrs):
# t=0 is the next state of t=-1
data = AgentConnectorDataType(0, 1, {SampleBatch.NEXT_OBS: obs})
processed = c([data]) # env.reset() for t == -1 else env.step()
sample_batch = processed[0].data.sample_batch
# add cur obs to the list
obs_list.append(obs)
if t == 0:
check(sample_batch["prev_state"], sample_batch["state"])
else:
# prev state should be equal to the prev time step obs
check(sample_batch["prev_state"], obs_list[-2][None])
def test_vr_connector_causal_slice(self):
"""Test that the ViewRequirementAgentConnector can handle slice shifts."""
view_rq_dict = {
"state": ViewRequirement("obs"),
# shift array should be [-2, -1, 0]
"prev_states": ViewRequirement("obs", shift="-2:0"),
# shift array should be [-4, -2, 0]
"prev_strided_states_even": ViewRequirement("obs", shift="-4:0:2"),
# shift array should be [-3, -1]
"prev_strided_states_odd": ViewRequirement("obs", shift="-3:0:2"),
}
obs_arrs = np.arange(10)[:, None] + 1
config = PPOConfig().to_dict()
ctx = ConnectorContext(
view_requirements=view_rq_dict, config=config, is_policy_recurrent=True
)
c = ViewRequirementAgentConnector(ctx)
# keep a queue of observations
obs_list = []
for t, obs in enumerate(obs_arrs):
# t=0 is the next state of t=-1
data = AgentConnectorDataType(0, 1, {SampleBatch.NEXT_OBS: obs})
processed = c([data])
sample_batch = processed[0].data.sample_batch
if t == 0:
obs_list.extend([obs for _ in range(5)])
else:
# remove the first obs and add the current obs to the end
obs_list.pop(0)
obs_list.append(obs)
# check state
check(sample_batch["state"], obs[None])
# check prev_states
check(
sample_batch["prev_states"],
np.stack(obs_list)[np.array([-3, -2, -1])][None],
)
# check prev_strided_states_even
check(
sample_batch["prev_strided_states_even"],
np.stack(obs_list)[np.array([-5, -3, -1])][None],
)
check(
sample_batch["prev_strided_states_odd"],
np.stack(obs_list)[np.array([-4, -2])][None],
)
def test_vr_connector_with_multiple_buffers(self):
"""Test that the ViewRequirementAgentConnector can handle slice shifts correctly
when it has multiple buffers to shift."""
context_len = 5
# This view requirement simulates the use-case of a decision transformer
# without reward-to-go.
view_rq_dict = {
# obs[t-context_len+1:t]
"context_obs": ViewRequirement(
"obs",
shift=f"-{context_len-1}:0",
space=Box(-np.inf, np.inf, shape=(1,), dtype=np.float64),
),
# next_obs[t-context_len+1:t]
"context_next_obs": ViewRequirement(
"obs",
shift=f"-{context_len}:1",
used_for_compute_actions=False,
space=Box(-np.inf, np.inf, shape=(1,), dtype=np.float64),
),
# act[t-context_len+1:t]
"context_act": ViewRequirement(
SampleBatch.ACTIONS,
shift=f"-{context_len-1}:-1",
space=Box(-np.inf, np.inf, shape=(1,)),
),
}
obs_arrs = np.arange(10)[:, None] + 1
act_arrs = (np.arange(10)[:, None] + 1) * 100
n_steps = obs_arrs.shape[0]
config = PPOConfig().to_dict()
ctx = ConnectorContext(
view_requirements=view_rq_dict, config=config, is_policy_recurrent=True
)
c = ViewRequirementAgentConnector(ctx)
# keep a queue of length ctx_len of observations
obs_list, act_list = [], []
for t in range(n_steps):
# next state and action at time t-1 are the following
timestep_data = {
SampleBatch.NEXT_OBS: obs_arrs[t],
}
if t > 0:
timestep_data[SampleBatch.ACTIONS] = act_arrs[t - 1]
data = AgentConnectorDataType(0, 1, timestep_data)
processed = c([data])
sample_batch = processed[0].data.sample_batch
if t == 0:
obs_list.extend([obs_arrs[0] for _ in range(context_len)])
act_list.extend(
[np.zeros_like(act_arrs[0]) for _ in range(context_len)]
)
else:
obs_list.pop(0)
act_list.pop(0)
obs_list.append(obs_arrs[t])
act_list.append(act_arrs[t - 1])
self.assertTrue("context_next_obs" not in sample_batch)
# We should have the 5 (context_len) most recent observations here
check(sample_batch["context_obs"], np.stack(obs_list)[None])
# The context for actions is [t-context_len+1:t]. Since we build sample
# batch for inference in ViewRequirementAgentConnector, it always
# includes everything up until the last action (at t-1), but not the
# action current action (at t).
check(sample_batch["context_act"], np.stack(act_list[1:])[None])
def test_connector_pipline_with_view_requirement(self):
"""A very minimal test that checks wheter pipeline connectors work in a
simulation rollout."""
# TODO: make this test beefier and more comprehensive
config = (
PPOConfig()
.framework("torch")
.environment(env="CartPole-v1")
.rollouts(create_env_on_local_worker=True)
)
env = gym.make("CartPole-v1")
policy = config.build().get_policy()
REQUIRED_KEYS = {
SampleBatch.OBS,
SampleBatch.NEXT_OBS,
SampleBatch.REWARDS,
SampleBatch.TERMINATEDS,
SampleBatch.TRUNCATEDS,
SampleBatch.INFOS,
SampleBatch.ACTIONS,
}
policy.view_requirements = {
k: v for k, v in policy.view_requirements.items() if k in REQUIRED_KEYS
}
# create a connector context
ctx = ConnectorContext(
view_requirements=policy.view_requirements,
config=policy.config,
initial_states=policy.get_initial_state(),
is_policy_recurrent=policy.is_recurrent(),
observation_space=policy.observation_space,
action_space=policy.action_space,
)
# build chain of connectors
connectors = [
ObsPreprocessorConnector(ctx),
StateBufferConnector(ctx),
ViewRequirementAgentConnector(ctx),
]
agent_connector = AgentConnectorPipeline(ctx, connectors)
name, params = agent_connector.to_state()
restored = get_connector(name, ctx, params)
self.assertTrue(isinstance(restored, AgentConnectorPipeline))
for cidx, c in enumerate(connectors):
check(restored.connectors[cidx].to_state(), c.to_state())
# simulate a rollout
n_steps = 10
obs, info = env.reset()
env_out = AgentConnectorDataType(
0, 1, {SampleBatch.NEXT_OBS: obs, SampleBatch.T: -1}
)
agent_obs = agent_connector([env_out])[0]
t = 0
total_rewards = 0
while t < n_steps:
policy_output = policy.compute_actions_from_input_dict(
agent_obs.data.sample_batch
)
# Removes batch dimension
policy_output = tree.map_structure(lambda x: x[0], policy_output)
agent_connector.on_policy_output(
ActionConnectorDataType(0, 1, {}, policy_output)
)
action = policy_output[0]
next_obs, rewards, terminateds, truncateds, info = env.step(action)
env_out_dict = {
SampleBatch.NEXT_OBS: next_obs,
SampleBatch.REWARDS: rewards,
SampleBatch.TERMINATEDS: terminateds,
SampleBatch.TRUNCATEDS: truncateds,
SampleBatch.INFOS: info,
SampleBatch.ACTIONS: action,
# state_out
}
env_out = AgentConnectorDataType(0, 1, env_out_dict)
agent_obs = agent_connector([env_out])[0]
total_rewards += rewards
t += 1
print(total_rewards)
def test_vr_connector_only_keeps_useful_timesteps(self):
"""Tests that the connector respects the flags within view_requirements (i.e.
used_for_training, used_for_compute_actions).
the returned data is the input dict itself, which the policy collector in
env_runner will use to construct the episode, and a SampleBatch that can be
used to run corresponding policy.
"""
view_rqs = {
"obs": ViewRequirement(
None, used_for_training=True, used_for_compute_actions=True
),
}
config = PPOConfig().to_dict()
ctx = ConnectorContext(
view_requirements=view_rqs,
config=config,
is_policy_recurrent=False,
)
c = ViewRequirementAgentConnector(ctx)
c.in_training()
for i in range(5):
obs_arr = np.array([0, 1, 2, 3]) + i
agent_data = {SampleBatch.NEXT_OBS: obs_arr}
data = AgentConnectorDataType(0, 1, agent_data)
# Feed ViewRequirementAgentConnector 5 samples.
c([data])
obs_data = c.agent_collectors[0][1].buffers["obs"][0]
# Only keep data for the last timestep.
self.assertEqual(len(obs_data), 1)
# Data matches the latest timestep.
self.assertTrue(np.array_equal(obs_data[0], np.array([4, 5, 6, 7])))
def test_vr_connector_default_agent_collector_is_empty(self):
"""Tests that after reset() the view_requirement connector will
create a fresh new agent collector.
"""
view_rqs = {
"obs": ViewRequirement(
None, used_for_training=True, used_for_compute_actions=True
),
}
config = PPOConfig().to_dict()
ctx = ConnectorContext(
view_requirements=view_rqs,
config=config,
is_policy_recurrent=False,
)
c = ViewRequirementAgentConnector(ctx)
c.in_training()
for i in range(5):
obs_arr = np.array([0, 1, 2, 3]) + i
agent_data = {SampleBatch.NEXT_OBS: obs_arr}
data = AgentConnectorDataType(0, 1, agent_data)
# Feed ViewRequirementAgentConnector 5 samples.
c([data])
# 1 init_obs, plus 4 agent steps.
self.assertEqual(c.agent_collectors[0][1].agent_steps, 4)
# Reset.
c.reset(0) # env_id = 0
# Process a new timestep.
obs_arr = np.array([0, 1, 2, 3]) + i
agent_data = {SampleBatch.NEXT_OBS: obs_arr}
data = AgentConnectorDataType(0, 1, agent_data)
# Feed ViewRequirementAgentConnector 5 samples.
c([data])
# Start fresh with 0 agent step.
self.assertEqual(c.agent_collectors[0][1].agent_steps, 0)
if __name__ == "__main__":
import sys
import pytest
sys.exit(pytest.main(["-v", __file__]))
| [
"noreply@github.com"
] | ray-project.noreply@github.com |
99575b5054b6865d2ef7c17006529adf4923af07 | b683c8f1942a1ab35062620c6013b1e223c09e92 | /Python-Files/Day-3/Question-10.py | 726a1add98af17a4907c45fa6b21b3af0c4245a1 | [] | no_license | nihathalici/Break-The-Ice-With-Python | 601e1c0f040e02fe64103c77795deb2a5d8ff00a | ef5b9dd961e8e0802eee171f2d54cdb92f2fdbe8 | refs/heads/main | 2023-07-18T01:13:27.277935 | 2021-08-27T08:19:44 | 2021-08-27T08:19:44 | 377,414,827 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 722 | py | """
Question 10
Question
Write a program that accepts a sequence of whitespace separated words as input and
prints the words after removing all duplicate words and sorting them alphanumerically.
Suppose the following input is supplied to the program:
hello world and practice makes perfect and hello world again
Then, the output should be:
again and hello makes perfect practice world
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.We use set container to remove duplicated data automatically and then use sorted() to sort the data.
"""
word = input().split()
for i in word:
if word.count(i) > 1:
word.remove(i)
word.sort()
print(" ".join(word))
| [
"noreply@github.com"
] | nihathalici.noreply@github.com |
b7f8fb45004f490bc91705b637f9448cc14d0759 | be84495751737bbf0a8b7d8db2fb737cbd9c297c | /sdl/strs.py | a1108190826b28e5da74d01537208ba9591cddbd | [] | no_license | mario007/renmas | 5e38ff66cffb27b3edc59e95b7cf88906ccc03c9 | bfb4e1defc88eb514e58bdff7082d722fc885e64 | refs/heads/master | 2021-01-10T21:29:35.019792 | 2014-08-17T19:11:51 | 2014-08-17T19:11:51 | 1,688,798 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,024 | py |
class Attribute:
"""
Class represents attribute(filed) in structure.
"""
def __init__(self, name, path):
self.name = name # name of struct
self.path = path # path to member in struct
class Callable:
"""
Class represents function in shading language.
"""
def __init__(self, name, args):
self.name = name
self.args = args
class Const:
"""
Class represents constant(int, float).
Also const can hold tuple of constants.
"""
def __init__(self, const):
self.const = const
class Name:
"""
Class represents name(variable) in shading language.
"""
def __init__(self, name):
self.name = name
class Subscript:
"""
Class represents item in array.
"""
def __init__(self, name, index, path=None):
self.name = name
self.index = index
#if we have path than this is array in struct
self.path = path # path to member in struct
class NoOp:
"""
In arithmetic and conditions, with this class we indicate that we are
missing left or right operand.
"""
pass
class Operation:
"""
Class that represent simple arithmetic operation.
"""
def __init__(self, left, operator, right):
self.left = left
self.operator = operator
self.right = right
class Operations:
"""
Class that holds list of arithmetic operations.
"""
def __init__(self, operations):
self.operations = operations
class Condition:
"""
Class that one simple logic condition
"""
def __init__(self, left, operator, right):
self.left = left
self.operator = operator
self.right = right
class Conditions:
"""
Class that holds list of logic conditions.
"""
def __init__(self, conditions, logic_ops):
assert len(conditions) == len(logic_ops) + 1
self.conditions = conditions
self.logic_ops = logic_ops
| [
"mvidov@yahoo.com"
] | mvidov@yahoo.com |
fd397767b61c74e568de01a0df54cfa6a3e26aa6 | e9e71b4ae8985a7eb1850e69891510cb7f9865aa | /django/squawker/squawker/wsgi.py | b5c6b09499f7152c283b2d642b59b27966eae72d | [] | no_license | robertjohnson1986/python_stack1 | 34b4e97c6ed967ed01fb58cd1bc4c75eb759b16f | a801ce5a41d0cd01113500b4ff2b24e01ffb8d33 | refs/heads/main | 2023-06-23T00:07:41.610694 | 2021-07-21T22:21:13 | 2021-07-21T22:21:13 | 372,145,763 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 393 | py | """
WSGI config for squawker project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'squawker.settings')
application = get_wsgi_application()
| [
"83429757+robertjohnson1986@users.noreply.github.com"
] | 83429757+robertjohnson1986@users.noreply.github.com |
4af5f80e69b143b0cc55b7068cfba069e26fd17c | cdf969cadf53489b9c3d96a122232de947abc8a6 | /compute_video_frames_info.py | e0f4240fdcd0c6f26667fe0b5e9c9b40a39172b4 | [] | no_license | achalddave/charades-scripts | 021a0d2f2d2d4f41ba2c43fedf24b080c848ae34 | 9ec5bb3f1197a65a5a140242ba24a2c40074c8f4 | refs/heads/master | 2021-01-01T16:18:41.139194 | 2017-07-20T07:41:34 | 2017-07-20T07:41:34 | 97,805,792 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,566 | py | """Output frames per second, number of frames for each video.
Output is a CSV file containing the entries
video,fps,num_frames
where video is the name of the video file without the extension.
"""
import argparse
import csv
import os
from moviepy.editor import VideoFileClip
from tqdm import tqdm
def main(video_paths_list, output_csv_path):
with open(video_paths_list) as f:
video_paths = [line.strip() for line in f]
with open(output_csv_path, 'w') as output:
field_names = ['video', 'fps', 'num_frames']
writer = csv.DictWriter(output, fieldnames=field_names)
writer.writeheader()
for video_path in tqdm(video_paths):
clip = VideoFileClip(video_path)
frames_per_second = clip.fps
num_frames = int(clip.fps * clip.duration)
file_basename = os.path.splitext(os.path.basename(video_path))[0]
writer.writerow({'video': file_basename,
'fps': frames_per_second,
'num_frames': num_frames})
if __name__ == "__main__":
# Use first line of file docstring as description if a file docstring
# exists.
parser = argparse.ArgumentParser(
description=__doc__.split('\n')[0] if __doc__ else '',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'video_list',
help='File containing new-line separated paths to videos.')
parser.add_argument('output_csv')
args = parser.parse_args()
main(args.video_list, args.output_csv)
| [
"achalddave@live.com"
] | achalddave@live.com |
c7654bcbf74e5ac7a50f79cc4d50fe959e0ae817 | a25aa09af984d08084a395f9b6df427d3756f11a | /diary/0826.py | 8dea9397a029b60bffa7bed54f684ceab3cd8574 | [] | no_license | luyihsien/leetcodepy | 31971e851a4ae77942a5d9e3ff07faea6e504c66 | a54bd09f4b28f106196a6cd8a0f9c056bcd237e6 | refs/heads/master | 2020-05-19T13:21:57.854086 | 2019-10-16T14:23:00 | 2019-10-16T14:23:00 | 185,037,569 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 778 | py | import sys
a=[1,2,3,4]
print(id(a))
b=a
b=b+[5]
b.append(5)
print(a,id(a))
print(b,id(b))
a=5
b=a
print(id(a),id(b))
b+=1
print(id(b))
print(id(a))
print(a,b)
class ListNode:
def __init__(self,val):
self.val=val
self.next=None
a=ListNode(5)
b=a
print(sys.getsizeof(a))
print(sys.getsizeof(a.val))
print(sys.getsizeof(a.next))
b.next=ListNode(400000)
print(sys.getsizeof(a))
print(sys.getsizeof(a.next.val))
b=b.next
print('b',sys.getsizeof(b))
b.next=ListNode(3000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000)
print(sys.getsizeof(a))
a=100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
print(sys.getsizeof(a))
a=1000#與a=1同
print(sys.getsizeof(a)) | [
"luyihsien@gmail.com"
] | luyihsien@gmail.com |
2a214d889b2a7bcb00a0468a849d3bb7ef09b25d | 905020fce75b4b63517ec31c601e721f5c260cd1 | /Круглые.py | a81a0e58e8bea35664bc00748a84aa55a09b5dac | [] | no_license | Dimaed90800/Python_Y | 7858ad46309281a89c5c1e83a0f09030996182a4 | 04092b854605cb05df439eeeb52003e585bb5a29 | refs/heads/main | 2023-01-24T04:11:17.858281 | 2020-11-17T20:42:45 | 2020-11-17T20:42:45 | 313,731,672 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 69 | py | number=int(input())
while number % 10 == 0:
number=int(input()) | [
"noreply@github.com"
] | Dimaed90800.noreply@github.com |
421d09d35a9eb0d59a9fb4ec23cb7ad8804bd30a | 9f2f386a692a6ddeb7670812d1395a0b0009dad9 | /python/paddle/fluid/tests/unittests/test_softmax_mask_fuse_upper_triangle_op.py | a73ebd73e4946caa50030b52544a3c5a35a5c8d2 | [
"Apache-2.0"
] | permissive | sandyhouse/Paddle | 2f866bf1993a036564986e5140e69e77674b8ff5 | 86e0b07fe7ee6442ccda0aa234bd690a3be2cffa | refs/heads/develop | 2023-08-16T22:59:28.165742 | 2022-06-03T05:23:39 | 2022-06-03T05:23:39 | 181,423,712 | 0 | 7 | Apache-2.0 | 2022-08-15T08:46:04 | 2019-04-15T06:15:22 | C++ | UTF-8 | Python | false | false | 4,087 | py | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import unittest
import numpy as np
import paddle.fluid.core as core
from op_test import OpTest
import paddle
import paddle.fluid as fluid
import paddle.incubate as incubate
paddle.enable_static()
def _get_softmax_upper(x, fp16=True):
x_lower = np.tril(x)
masked_x = np.where(x_lower == 0, -10000.0, x_lower).astype("float32")
max_value = np.max(masked_x, axis=-1, keepdims=True)
before_exp = masked_x - max_value
exp = np.exp(before_exp)
exp_sum = np.sum(exp, axis=-1, keepdims=True)
rst = exp / exp_sum
if fp16:
rst = rst.astype("float16")
return rst
@unittest.skipIf(not core.is_compiled_with_cuda(),
"core is not compiled with CUDA")
class TestSoftmaxMaskFuseOp(OpTest):
def setUp(self):
self.op_type = "fused_softmax_mask_upper_triangle"
x = np.random.random((1, 4, 32, 32)).astype("float16")
self.inputs = {'X': x}
rst = _get_softmax_upper(x)
self.outputs = {'Out': rst}
def test_check_output(self):
self.check_output_with_place(core.CUDAPlace(0))
def test_check_grad(self):
self.check_grad_with_place(core.CUDAPlace(0), ["X"], "Out")
@unittest.skipIf(not core.is_compiled_with_cuda(),
"core is not compiled with CUDA")
class TestSoftmaxMaskFuseOp1(OpTest):
def setUp(self):
self.op_type = "fused_softmax_mask_upper_triangle"
x = np.random.random((1, 4, 32, 32))
self.inputs = {'X': x}
rst = _get_softmax_upper(x)
self.outputs = {'Out': rst}
def test_check_output(self):
try:
self.check_output_with_place(core.CPUPlace())
except NotImplementedError:
pass
def test_check_grad(self):
try:
self.check_grad_with_place(core.CPUPlace(), ["X"], "Out")
except NotImplementedError:
pass
@unittest.skipIf(not core.is_compiled_with_cuda(),
"core is not compiled with CUDA")
class TestDropoutBiasFuseOp2(unittest.TestCase):
# test the python side API for softmax_mask_fuse op
def setUp(self):
np.random.seed(123)
self.dtypes = ['float16', 'float32']
def test_static(self):
for dtype in self.dtypes:
with fluid.program_guard(fluid.Program(), fluid.Program()):
input_x = fluid.data(
name="x", shape=[1, 4, 32, 32], dtype=dtype)
rst = incubate.softmax_mask_fuse_upper_triangle(input_x)
x_in_np = np.random.random((1, 4, 32, 32)).astype(dtype)
rst_np = _get_softmax_upper(x_in_np, dtype == 'float16')
exe = fluid.Executor(fluid.CUDAPlace(0))
fetches = exe.run(fluid.default_main_program(),
feed={"x": x_in_np},
fetch_list=[rst])
self.assertTrue(np.allclose(fetches[0], rst_np))
def test_dygraph(self):
for dtype in self.dtypes:
with fluid.dygraph.guard(fluid.CUDAPlace(0)):
x_in_np = np.random.random((1, 4, 32, 32)).astype(dtype)
rst_np = _get_softmax_upper(x_in_np, dtype == 'float16')
input_x = fluid.dygraph.to_variable(x_in_np)
rst = incubate.softmax_mask_fuse_upper_triangle(input_x)
self.assertTrue(np.allclose(rst, rst_np))
if __name__ == '__main__':
unittest.main()
| [
"noreply@github.com"
] | sandyhouse.noreply@github.com |
c0a1cc5932507c02c45d2174440b4aa654fad2f9 | f7abecb2826760ce2ce6d022bd2d2225efd5416d | /company/migrations/0002_auto_20180323_1956.py | bab0547c5b00f2cdb63b4bc65d8061f5c712c85f | [] | no_license | vintkor/django_ppf | 2b8e20a016314e6934ccdb2e6723faf7e62a66b4 | 50737517049fdc806ecd3e2fc7757588e7cfcb7b | refs/heads/master | 2022-12-09T12:37:24.508027 | 2020-04-06T20:23:44 | 2020-04-06T20:23:44 | 112,515,920 | 0 | 1 | null | 2022-12-01T22:24:06 | 2017-11-29T19:03:53 | Python | UTF-8 | Python | false | false | 2,982 | py | # Generated by Django 2.0.3 on 2018-03-23 17:56
from django.db import migrations, models
import django.db.models.deletion
import sorl.thumbnail.fields
class Migration(migrations.Migration):
dependencies = [
('company', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Gallery',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True, verbose_name='Дата создания')),
('updated', models.DateTimeField(auto_now=True, verbose_name='Дата обновления')),
('image', sorl.thumbnail.fields.ImageField(upload_to='images', verbose_name='Изображение')),
('alt', models.CharField(blank=True, max_length=255, null=True, verbose_name='SEO Alt')),
],
options={
'verbose_name': 'Office gallery',
'verbose_name_plural': 'Office galleries',
},
),
migrations.RemoveField(
model_name='officegallery',
name='office',
),
migrations.AlterModelOptions(
name='company',
options={'verbose_name': 'Компания', 'verbose_name_plural': 'Компании'},
),
migrations.AlterModelOptions(
name='office',
options={'verbose_name': 'Офис', 'verbose_name_plural': 'Офисы'},
),
migrations.RemoveField(
model_name='company',
name='logo',
),
migrations.AlterField(
model_name='company',
name='name',
field=models.CharField(max_length=250, verbose_name='Название компании'),
),
migrations.AlterField(
model_name='office',
name='address',
field=models.CharField(max_length=255, verbose_name='Адрес'),
),
migrations.AlterField(
model_name='office',
name='company',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='company.Company', verbose_name='Компания'),
),
migrations.AlterField(
model_name='office',
name='coordinates',
field=models.CharField(max_length=50, verbose_name='Координаты'),
),
migrations.AlterField(
model_name='office',
name='region',
field=models.ForeignKey(on_delete=None, to='geo.Region', verbose_name='Страна'),
),
migrations.DeleteModel(
name='OfficeGallery',
),
migrations.AddField(
model_name='gallery',
name='office',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='company.Office', verbose_name='Офис'),
),
]
| [
"alkv84@yandex.ru"
] | alkv84@yandex.ru |
69a39a410162d7228cbdda1169b643378eecf6aa | 2be2b1daea464c6b48706c6b2696a94af1b2439b | /lesson7'/4.py | 4eecf7173de71093f181cd7da70d3cf04cf250d1 | [] | no_license | kirigaikabuto/pythonlessons1400 | 584fbef15802accd10b21cd33fbd8aa7900e19f3 | af1df1f4b238e9e4476c75cb25a03f92957bc156 | refs/heads/main | 2023-07-12T19:06:08.117125 | 2021-08-14T08:09:11 | 2021-08-14T08:09:11 | 386,884,757 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 987 | py | s = "Modern Singapore was founded in 1819 by Sir Stamford Raffles as a trading post of the British Empire. In 1867, the colonies in Southeast Asia were reorganised and Singapore came under the direct control of Britain as part of the Straits Settlements. During the Second World War, Singapore was occupied by Japan in 1942, and returned to British control as a separate crown colony following Japan's surrender in 1945. Singapore gained self-governance in 1959 and in 1963 became part of the new federation of Malaysia, alongside Malaya, North Borneo, and Sarawak. Ideological differences led to Singapore being expelled from the federation two years later and it became an independent country."
s = s.replace(",", "")
s = s.replace(".", "")
words = s.split(" ")
alpha = []
numbers = []
others = []
for i in words:
if i.isalpha():
alpha.append(i)
elif i.isnumeric():
numbers.append(i)
else:
others.append(i)
print(alpha)
print(numbers)
print(others)
| [
"tleugazy98@gmail.com"
] | tleugazy98@gmail.com |
f24751a0aa719ae0e2a5030802510b8a72c06f93 | eec1f3a9a31a61b74d8ace96301653bef87c456e | /bigfish/segmentation/test/test_nuc_segmentation.py | cc3fae3d8803440c507226847bda4180aea3ccdf | [
"BSD-3-Clause",
"Python-2.0"
] | permissive | fish-quant/big-fish | 843ca1b4731afce738d6d557249475482a6870ef | e951ea850b18be4be70c5d0a419ba524c3a59ada | refs/heads/master | 2023-08-25T04:19:14.376366 | 2022-04-25T22:51:57 | 2022-04-25T22:51:57 | 162,127,052 | 43 | 22 | BSD-3-Clause | 2023-07-02T23:29:41 | 2018-12-17T12:26:09 | Python | UTF-8 | Python | false | false | 430 | py | # -*- coding: utf-8 -*-
# Author: Arthur Imbert <arthur.imbert.pro@gmail.com>
# License: BSD 3 clause
"""
Unitary tests for bigfish.segmentation.nuc_segmentation module.
"""
# TODO add test for bigfish.segmentation.remove_segmented_nuc
# TODO add test for bigfish.segmentation.unet_3_classes_nuc
# TODO add test for bigfish.segmentation.apply_unet_3_classes
# TODO add test for bigfish.segmentation.from_3_classes_to_instances
| [
"arthur.imbert.pro@gmail.com"
] | arthur.imbert.pro@gmail.com |
61269609d910c84387be9e4eb94204f60e28e97b | 5b6b2018ab45cc4710cc5146040bb917fbce985f | /11_search-range-in-binary-search-tree/search-range-in-binary-search-tree.py | addadc00c229ca4127059cd113b672daa90df11d | [] | no_license | ultimate010/codes_and_notes | 6d7c7d42dcfd84354e6fcb5a2c65c6029353a328 | 30aaa34cb1c840f7cf4e0f1345240ac88b8cb45c | refs/heads/master | 2021-01-11T06:56:11.401869 | 2016-10-30T13:46:39 | 2016-10-30T13:46:39 | 72,351,982 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,062 | py | # coding:utf-8
'''
@Copyright:LintCode
@Author: ultimate010
@Problem: http://www.lintcode.com/problem/search-range-in-binary-search-tree
@Language: Python
@Datetime: 16-06-11 15:21
'''
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of the binary search tree.
@param k1 and k2: range k1 to k2.
@return: Return all keys that k1<=key<=k2 in ascending order.
"""
def searchRange(self, root, k1, k2):
# write your code here
# inorder traver
if root is None:
return []
ret = []
stack = []
while root or len(stack) > 0:
if root:
stack.append(root)
root = root.left
else:
root = stack.pop()
if root.val <= k2 and root.val >= k1:
ret.append(root.val)
root = root.right
return ret | [
"ultimate010@gmail.com"
] | ultimate010@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.