blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 616 | content_id stringlengths 40 40 | detected_licenses listlengths 0 69 | license_type stringclasses 2
values | repo_name stringlengths 5 118 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 63 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 2.91k 686M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 220
values | src_encoding stringclasses 30
values | language stringclasses 1
value | is_vendor bool 2
classes | is_generated bool 2
classes | length_bytes int64 2 10.3M | extension stringclasses 257
values | content stringlengths 2 10.3M | authors listlengths 1 1 | author_id stringlengths 0 212 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ab08841831bc3435f4fd676c5bc2d514ae282892 | ca6173bd7600d269cdc1e18da0d7a1fbe4e0f31f | /rsys/rblog/urls.py | 049f945156ad311f232d75e5be1cd7d794b0d02a | [] | no_license | dgscharan/django-rsys | 299409705a537233e35af589254acdd08696375a | 9485183c9e6f34d6c1d5547ec8275904fb752ecb | refs/heads/master | 2023-01-04T00:00:50.388278 | 2020-11-02T06:39:15 | 2020-11-02T06:39:15 | 309,279,890 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 334 | py |
from django.urls import path, include
from . import views
from .views import HomePage, ArticleDetailView, AddPostView
urlpatterns = [
path('', HomePage.as_view(), name='Home'),
path('article/<int:pk>', ArticleDetailView.as_view(), name='article-details'),
path('add_post/', AddPostView.as_view(), name = 'add_post'),
]
| [
"sricharan@beezlabs.com"
] | sricharan@beezlabs.com |
8725abdd6d54053715a6c6250547207cdaa688e2 | d8506b53c20768591024efe23a8d949f90a7d304 | /venv/Scripts/easy_install-script.py | da9dff5dff56b5bd232a6838105fb7f5724da605 | [] | no_license | undercookie/Python_Game | 3efa22562faa0632470f64b06d9b734ee33b54fd | 13d05ae5a17ae197c12144f20e9124a75cad4ae4 | refs/heads/master | 2022-09-08T17:49:05.081795 | 2020-05-25T18:50:37 | 2020-05-25T18:50:37 | 263,611,143 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 450 | py | #!C:\Users\p\PycharmProjects\Python_Game\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==40.8.0','console_scripts','easy_install'
__requires__ = 'setuptools==40.8.0'
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('setuptools==40.8.0', 'console_scripts', 'easy_install')()
)
| [
"jamie.seckinger@web.de"
] | jamie.seckinger@web.de |
7942e8232444511231b96ddaa7360ebcd0efa788 | 1e963eae16ad14c9043cb5fb4ca2e1fc83ffe6c9 | /01.DeepLearning/01.captcha/01.Captcha.py | dbc11d5343b4d5afe8161f1b7165bc635914469a | [] | no_license | johnsondiao0521/MachineLearningInAction | 5b65842b28762d6947b54f9294d8f4d2c468e87f | 13a6de20fdfa7de36aaf0379db20e69997483164 | refs/heads/master | 2020-03-31T12:07:14.664977 | 2019-05-31T08:30:57 | 2019-05-31T08:30:57 | 152,203,987 | 5 | 1 | null | 2018-11-06T07:17:34 | 2018-10-09T07:06:49 | Jupyter Notebook | UTF-8 | Python | false | false | 17 | py | #encoding:utf-8
| [
"332886494@qq.com"
] | 332886494@qq.com |
4b8524cc460faabc41efc6e9ca0584712bb5bfd6 | ab69c2e3e4ec895fc533a4d37768aab517f86722 | /tests/structures/test_comparisons.py | 995b3acc05d605970a8217e4e74851e623881818 | [
"BSD-3-Clause",
"MIT"
] | permissive | pranavmodx/batavia | 9cf7d7528cb88b16d5b33b64481281b60e84cbec | 084d78eb553f21c787009e1141638e810fcc654f | refs/heads/master | 2020-08-07T19:08:36.105839 | 2019-10-08T06:32:23 | 2019-10-08T06:32:23 | 213,560,529 | 1 | 0 | NOASSERTION | 2019-10-08T06:01:52 | 2019-10-08T06:01:50 | null | UTF-8 | Python | false | false | 5,319 | py | from ..utils import TranspileTestCase
class ComparisonTests(TranspileTestCase):
def test_is(self):
self.assertCodeExecution("""
x = 1
if x is 1:
print('Correct')
else:
print('Incorrect')
print('Done.')
""")
self.assertCodeExecution("""
x = 1
if x is 5:
print('Incorrect')
else:
print('Correct')
print('Done.')
""")
self.assertCodeExecution("""
x = None
if x is None:
print('Correct')
else:
print('Incorrect')
print('Done.')
""")
self.assertCodeExecution("""
x = 1
if x is None:
print('Incorrect')
else:
print('Correct')
print('Done.')
""")
def test_is_not(self):
self.assertCodeExecution("""
x = 1
if x is not 5:
print('Correct')
else:
print('Incorrect')
print('Done.')
""")
self.assertCodeExecution("""
x = 1
if x is not 1:
print('Correct')
else:
print('Incorrect')
print('Done.')
""")
self.assertCodeExecution("""
x = 1
if x is not None:
print('Correct')
else:
print('Incorrect')
print('Done.')
""")
self.assertCodeExecution("""
x = None
if x is not None:
print('Incorrect')
else:
print('Correct')
print('Done.')
""")
def test_lt(self):
self.assertCodeExecution("""
x = 1
if x < 5:
print('Correct')
else:
print('Incorrect')
print('Done.')
""")
self.assertCodeExecution("""
x = 5
if x < 5:
print('Incorrect')
else:
print('Correct')
print('Done.')
""")
self.assertCodeExecution("""
x = 10
if x < 5:
print('Correct')
else:
print('Incorrect')
print('Done.')
""")
def test_le(self):
self.assertCodeExecution("""
x = 1
if x <= 5:
print('Correct')
else:
print('Incorrect')
print('Done.')
""")
self.assertCodeExecution("""
x = 5
if x <= 5:
print('Correct')
else:
print('Incorrect')
print('Done.')
""")
self.assertCodeExecution("""
x = 10
if x <= 5:
print('Correct')
else:
print('Incorrect')
print('Done.')
""")
def test_gt(self):
self.assertCodeExecution("""
x = 10
if x > 5:
print('Correct')
else:
print('Incorrect')
print('Done.')
""")
self.assertCodeExecution("""
x = 5
if x > 5:
print('Incorrect')
else:
print('Correct')
print('Done.')
""")
self.assertCodeExecution("""
x = 1
if x > 5:
print('Correct')
else:
print('Incorrect')
print('Done.')
""")
def test_ge(self):
self.assertCodeExecution("""
x = 10
if x >= 5:
print('Correct')
else:
print('Incorrect')
print('Done.')
""")
self.assertCodeExecution("""
x = 5
if x >= 5:
print('Correct')
else:
print('Incorrect')
print('Done.')
""")
self.assertCodeExecution("""
x = 1
if x >= 5:
print('Correct')
else:
print('Incorrect')
print('Done.')
""")
def test_eq(self):
self.assertCodeExecution("""
x = 10
if x == 5:
print('Correct')
else:
print('Incorrect')
print('Done.')
""")
self.assertCodeExecution("""
x = 5
if x == 5:
print('Correct')
else:
print('Incorrect')
print('Done.')
""")
def test_ne(self):
self.assertCodeExecution("""
x = 5
if x == 5:
print('Correct')
else:
print('Incorrect')
print('Done.')
""")
self.assertCodeExecution("""
x = 10
if x == 5:
print('Correct')
else:
print('Incorrect')
print('Done.')
""")
| [
"russell@keith-magee.com"
] | russell@keith-magee.com |
eda77b3fb111fdadddce59be538af5500de1b8e4 | e9abcb6021cc6fcc15ef2258f09812492b4e093d | /ironic/drivers/modules/pxe_auto_deploy.py | e710fc477b8a458092f3fcfad209f81f16a14b57 | [
"Apache-2.0"
] | permissive | ericxiett/ironic-customized | e6df6a62840ae34180b8004c98ac56790462408b | 3a2ad13969e1497889a0c3be80f9f5f671ff4d1b | refs/heads/master | 2020-07-16T08:29:03.447845 | 2019-09-02T01:31:58 | 2019-09-02T01:31:58 | 205,754,554 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,371 | py | import os
import socket
from shutil import rmtree
import jinja2
import time
from oslo_log import log
from oslo_utils import fileutils
from ironic_lib import utils as ironic_utils
from ironic.common import exception, pxe_utils, boot_devices, states
from ironic.common import utils
from ironic.common.i18n import _, _LE, _LI, _LW
from ironic.common.pxe_utils import get_root_dir
from ironic.conductor import task_manager
from ironic.conductor import utils as manager_utils
from ironic.conf import CONF
from ironic.drivers import base
from ironic.drivers.modules import deploy_utils
LOG = log.getLogger(__name__)
REQUIRED_PROPERTIES = ['user_kernel',
'user_ramdisk',
'management_ip',
'management_netmask',
'management_gateway']
PXE_CFG_DIR_NAME = 'pxelinux.cfg'
HOSTNAME_PREFIX = 'Host-'
AUTO_FILE_DIR = "/var/www/html/auto/"
class PXEAutoDeploy(base.DeployInterface):
def __init__(self):
pass
def clean_up(self, task):
extra_info = task.node.extra
pxe_boot_interface_mac = extra_info.get('boot_detailed').get('pxe_interface')
pxe_boot_interface_mac.replace('-', ':')
for port in task.ports:
if port.address == pxe_boot_interface_mac:
client_id = port.extra.get('client-id')
ironic_utils.unlink_without_raise(self._get_pxe_mac_path(port.address, client_id=client_id))
pxe_config_file_path = pxe_utils.get_pxe_config_file_path(task.node.uuid)
fileutils.delete_if_exists(pxe_config_file_path)
if os.path.exists(os.path.join(CONF.pxe.tftp_root, task.node.uuid)):
rmtree(os.path.join(CONF.pxe.tftp_root, task.node.uuid))
auto_file_name = task.node.uuid + '_auto.cfg'
fileutils.delete_if_exists(AUTO_FILE_DIR + auto_file_name)
@task_manager.require_exclusive_lock
def deploy(self, task):
manager_utils.node_power_action(task, states.REBOOT)
return states.DEPLOYWAIT
def get_properties(self):
pass
@task_manager.require_exclusive_lock
def prepare(self, task):
# No need to update dhcp with standalone mode
self._create_auto_config(task)
self._create_pxe_config(task)
deploy_utils.try_set_boot_device(task, boot_devices.PXE)
def _create_auto_config(self, task):
auto_info = {}
managemenet_ip = task.node.instance_info.get('management_ip')
auto_info['management_ip'] = managemenet_ip
auto_info['management_netmask'] = \
task.node.instance_info.get('management_netmask')
auto_info['management_gateway'] = \
task.node.instance_info.get('management_gateway')
auto_info['hostname'] = \
HOSTNAME_PREFIX + managemenet_ip.replace('.', '-')
auto_info['os_ver'] = \
task.node.instance_info.get('os_ver')
auto_info['server_ip'] = CONF.my_ip
extra_info = task.node.extra
pxe_boot_interface_mac = self._get_boot_interface_mac(task)
for nic in extra_info.get('nic_detailed'):
address = nic.get('mac_address')
LOG.info('address: %s', address)
if nic.get('mac_address') == pxe_boot_interface_mac:
auto_info['management_port'] = nic.get('name')
break
fileutils.ensure_tree(AUTO_FILE_DIR)
auto_file_name = task.node.uuid + '_auto.cfg'
auto_file_path = AUTO_FILE_DIR + auto_file_name
tmpl_path, tmpl_file = os.path.split(CONF.pxe_auto.pxe_auto_template)
env = jinja2.Environment(loader=jinja2.FileSystemLoader(tmpl_path))
template = env.get_template(tmpl_file)
auto_info = template.render({'auto_info': auto_info,
'server_ip': CONF.my_ip,
'repo_server_ip': CONF.pxe_auto.repo_server,
'UUID': task.node.uuid,
})
utils.write_to_file(auto_file_path, auto_info)
def _get_boot_interface_mac(self, task):
extra_info = task.node.extra
# pxe_interface like '01-6c-92-bf-0c-9c-d9'. '01-' is not needed.
pxe_interface = extra_info.get('boot_detailed').get('pxe_interface')[3:]
return pxe_interface.replace('-', ':')
def _create_pxe_config(self, task):
pxe_options = self._build_pxe_options(task.node)
pxe_config_template = CONF.pxe.pxe_config_template
node_uuid = task.node.uuid
root_dir = CONF.pxe.tftp_root
fileutils.ensure_tree(os.path.join(root_dir, node_uuid))
fileutils.ensure_tree(os.path.join(root_dir, PXE_CFG_DIR_NAME))
pxe_config_file_path = pxe_utils.get_pxe_config_file_path(node_uuid)
tmpl_path, tmpl_file = os.path.split(pxe_config_template)
env = jinja2.Environment(loader=jinja2.FileSystemLoader(tmpl_path))
template = env.get_template(tmpl_file)
pxe_config = template.render({'pxe_options': pxe_options,
'server_ip': CONF.my_ip,
'UUID': node_uuid,
})
utils.write_to_file(pxe_config_file_path, pxe_config)
self._link_mac_pxe_configs(task)
def _get_pxe_mac_path(self, mac, delimiter='-', client_id=None):
"""Convert a MAC address into a PXE config file name.
:param mac: A MAC address string in the format xx:xx:xx:xx:xx:xx.
:param delimiter: The MAC address delimiter. Defaults to dash ('-').
:param client_id: client_id indicate InfiniBand port.
Defaults is None (Ethernet)
:returns: the path to the config file.
"""
mac_file_name = mac.replace(':', delimiter).lower()
if not CONF.pxe.ipxe_enabled:
hw_type = '01-'
if client_id:
hw_type = '20-'
mac_file_name = hw_type + mac_file_name
return os.path.join(get_root_dir(), PXE_CFG_DIR_NAME, mac_file_name)
def _link_mac_pxe_configs(self, task):
def create_link(mac_path):
ironic_utils.unlink_without_raise(mac_path)
relative_source_path = os.path.relpath(
pxe_config_file_path, os.path.dirname(mac_path))
utils.create_link_without_raise(relative_source_path, mac_path)
pxe_config_file_path = pxe_utils.get_pxe_config_file_path(task.node.uuid)
pxe_boot_interface_mac = self._get_boot_interface_mac(task)
LOG.info("pxe_boot_interface_mac: %s", pxe_boot_interface_mac)
for port in task.ports:
LOG.info("port.address: %s", port.address)
if port.address == pxe_boot_interface_mac:
client_id = port.extra.get('client-id')
create_link(self._get_pxe_mac_path(port.address, client_id=client_id))
def _build_pxe_options(self, node):
pxe_info = {}
root_dir = pxe_utils.get_root_dir()
for label in ('user_kernel', 'user_ramdisk'):
pxe_info[label] = \
os.path.join(root_dir, node.instance_info.get(label))
return pxe_info
def take_over(self, task):
pass
def tear_down(self, task):
manager_utils.node_power_action(task, states.POWER_OFF)
def validate(self, task):
info = task.node.instance_info
for item in REQUIRED_PROPERTIES:
if not info.get(item):
error_msg = _("Cannot validate driver deploy. Some parameters were missing"
" in node's instance_info")
exc_msg = _("%(error_msg)s. Missing are: %(missing_info)s")
raise exception.MissingParameterValue(
exc_msg % {'error_msg': error_msg, 'missing_info': item})
def pxeauto(self, task, data):
task.upgrade_lock()
node = task.node
LOG.info('Pxeauto info for node %(node)s with '
'progress info %(data)s',
{'node': node.uuid, 'data': data})
# Parse progress info
title = data['Title']
progress = float(data['InstallProgress']) * 100
LOG.info('data[\'InstallProgress\']: %s', data['InstallProgress'])
LOG.info('progress: %f', progress)
if progress == 60:
task.process_event('resume')
LOG.info('resume...')
if progress == 100:
deploy_utils.try_set_boot_device(task, boot_devices.DISK)
manager_utils.node_power_action(task, states.REBOOT)
ret = self.check_conn(node.instance_info.get('management_ip'), 22)
if ret == 'success':
task.process_event('done')
LOG.info(_LI('Deployment to node %s done'), task.node.uuid)
def check_conn(self, address, port):
sock = socket.socket()
frequency = 0
while True:
try:
sock.connect((address, port))
LOG.info("Connected to %s on port %s", address, port)
return "success"
except socket.error, e:
LOG.info("Connection to %s on port %s failed: %s,"
" already wait: %s s", address, port, e, frequency*3)
frequency += 1
time.sleep(3)
| [
"eric_xiett@163.com"
] | eric_xiett@163.com |
e7ef8ab3673ccb8b8ad875387a5ce492d1062396 | e3f30481111e0a91abc55d591647b758bf78b890 | /albums/wsgi.py | e02d0ccbb59c91f5dd81681da5b9e36c55d4d8bd | [] | no_license | raviteja91/albums | 84e78693bff0f3e66698245713dd29ee5691b785 | e56f4a00684bcfed9f99353106a7b22ca89d3a76 | refs/heads/master | 2020-05-14T14:27:56.050896 | 2015-07-16T06:19:23 | 2015-07-16T06:19:23 | 39,179,923 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,419 | py | """
WSGI config for albums project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "albums.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "albums.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
| [
"ravi@gmail.com"
] | ravi@gmail.com |
359382acb24cd83e62add5654614e219cc603ace | 264c35aa1a7a5a71e1b3b4e92ece8fb63bc4bde2 | /bin/pilfont.py | a42088009a4c006dd28e5685f015b7b81697b89e | [] | no_license | muhiza/demp | f0ae15874690e1c7801bd1402c663f21c237b4a7 | 77f29ac541fa6ecb43d51a3c91abe49f56fa2045 | refs/heads/master | 2020-07-17T01:13:26.218907 | 2016-12-03T10:25:50 | 2016-12-03T10:25:50 | 73,937,337 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,049 | py | #!/home/muhiza/sem/market/src/bin/python
#
# The Python Imaging Library
# $Id$
#
# PIL raster font compiler
#
# history:
# 1997-08-25 fl created
# 2002-03-10 fl use "from PIL import"
#
from __future__ import print_function
VERSION = "0.4"
import glob
import sys
# drivers
from PIL import BdfFontFile
from PIL import PcfFontFile
if len(sys.argv) <= 1:
print("PILFONT", VERSION, "-- PIL font compiler.")
print()
print("Usage: pilfont fontfiles...")
print()
print("Convert given font files to the PIL raster font format.")
print("This version of pilfont supports X BDF and PCF fonts.")
sys.exit(1)
files = []
for f in sys.argv[1:]:
files = files + glob.glob(f)
for f in files:
print(f + "...", end=' ')
try:
fp = open(f, "rb")
try:
p = PcfFontFile.PcfFontFile(fp)
except SyntaxError:
fp.seek(0)
p = BdfFontFile.BdfFontFile(fp)
p.save(f)
except (SyntaxError, IOError):
print("failed")
else:
print("OK")
| [
"muhizafrank@gmail.com"
] | muhizafrank@gmail.com |
4d73f1009f9545a495de388d2b5332138d8fc0d7 | 237162607427106ae9564670d47427a62356861f | /users/migrations/0040_auto_20190426_1040.py | 477aac69c7a6db31f52e331f91b20015a89d3272 | [] | no_license | pitipund/basecore | 8648c1f4fa37b6e6075fd710ca422fe159ba930e | a0c20cec1e17dd0eb6abcaaa7d2623e38b60318b | refs/heads/master | 2020-09-13T20:16:02.622903 | 2019-11-20T09:07:15 | 2019-11-20T09:07:15 | 221,885,342 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 524 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2019-04-26 10:40
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0039_applicationdefaultrole'),
]
operations = [
migrations.AlterModelOptions(
name='applicationdefaultrole',
options={'ordering': ('id',), 'verbose_name': 'Application Default Role', 'verbose_name_plural': 'Application Default Roles'},
),
]
| [
"longman_694@hotmail.com"
] | longman_694@hotmail.com |
3cdf23ebb4b45ecc30c12028629a839c476eebad | 437f05765c4f8c4cccbbaf10d9d6551e7e0df60a | /shop/views.py | 2648f4e43fba119f88bdaa4ac57388a8587be729 | [] | no_license | akhilprakash634/Aqua | 6668944b619ed979ad25417547eaf4004782cba8 | 657ba3829996ab0fc691f7fd0b9b45ce4a3d8b9d | refs/heads/master | 2023-08-05T11:43:13.423955 | 2021-09-14T08:04:48 | 2021-09-14T08:04:48 | 406,276,489 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,454 | py | from django.shortcuts import render,get_object_or_404
from.models import *
from django.db.models import Q
from django.core.paginator import Paginator,EmptyPage,InvalidPage
# Create your views here.
def home(request,c_slug=None):
c_page=None
prodt=None
if c_slug != None:
c_page = get_object_or_404(categ, slug=c_slug)
prodt = products.objects.filter(category=c_page, available=True)
else:
prodt = products.objects.all().filter(available=True)
cat = categ.objects.all()
paginator=Paginator(prodt,4)
try:
page=int(request.GET.get('page','1'))
except:
page=1
try:
pro=paginator.page(page)
except(EmptyPage,InvalidPage):
pro=Paginator.page(Paginator.num_pages)
return render(request, 'index.html', {'pr': prodt,'ct':cat,'pg':pro})
def prodetails(request,c_slug,product_slug):
try:
prodt=products.objects.get(category__slug=c_slug,slug=product_slug)
except Exception as e:
raise e
return render(request,'products.html', {'pr':prodt})
def about(request):
return render(request,'about.html')
def search(request):
prod=None
query=None
if 'q' in request.GET:
query=request.GET.get('q')
prod=products.objects.all().filter(Q(name__contains=query)|Q(desc__contains=query))
return render(request,'search.html',{'qr':query,'pr':prod})
def contact(request):
return render(request,'contact.html')
| [
"akhilprakash634@gmai.com"
] | akhilprakash634@gmai.com |
bf28587cc995e0346c99fca4c63a858116550ef6 | 9562a72a5c5e8647a9bc6442bdb556ddbb13c908 | /Charlotte_Notes/dynamic_steps/autoregressive model.py | b8345f45c212597b08b58ed02e8f78f06223806e | [] | no_license | BIAPT/Scripts | e7529c99bf744967beb7ce3a02d311ac31578ca9 | 9ee5016c79b4768dd44492136a3c020516cc43e5 | refs/heads/master | 2022-11-27T06:16:06.184576 | 2022-01-05T02:00:24 | 2022-01-05T02:00:24 | 193,906,623 | 8 | 5 | null | 2022-11-22T04:58:19 | 2019-06-26T13:09:29 | Jupyter Notebook | UTF-8 | Python | false | false | 5,263 | py | import matplotlib
matplotlib.use('Qt5Agg')
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.decomposition import PCA
import pandas as pd
from sklearn.cluster import KMeans
import matplotlib.backends.backend_pdf
from sklearn import preprocessing
from clustering import create_image
def build_time_delay_matrices(x, r):
"""
Builds x1 and x2 for regression
Args:
x (numpy array of floats): data to be auto regressed
r (scalar): order of Autoregression model
Returns:
(numpy array of floats) : to predict "x2"
(numpy array of floats) : predictors of size [r,n-r], "x1"
"""
# construct the time-delayed data matrices for order-r AR model
x1 = np.ones(len(x)-r)
x1 = np.vstack((x1, x[0:-r]))
xprime = x
for i in range(r-1):
xprime = np.roll(xprime, -1)
x1 = np.vstack((x1, xprime[0:-r]))
x2 = x[r:]
return x1, x2
def AR_model(x, r):
"""
Solves Autoregression problem of order (r) for x
Args:
x (numpy array of floats): data to be auto regressed
r (scalar): order of Autoregression model
Returns:
(numpy array of floats) : to predict "x2"
(numpy array of floats) : predictors of size [r,n-r], "x1"
(numpy array of floats): coefficients of length [r] for prediction after
solving the regression problem "p"
"""
x1, x2 = build_time_delay_matrices(x, r)
# solve for an estimate of lambda as a linear regression problem
p, res, rnk, s = np.linalg.lstsq(x1.T, x2, rcond=None)
return x1, x2, p
def AR_prediction(x_test, p):
"""
Returns the prediction for test data "x_test" with the regression
coefficients p
Args:
x_test (numpy array of floats): test data to be predicted
p (numpy array of floats): regression coefficients of size [r] after
solving the autoregression (order r) problem on train data
Returns:
(numpy array of floats): Predictions for test data. +1 if positive and -1
if negative.
"""
x1, x2 = build_time_delay_matrices(x_test, len(p)-1)
# Evaluating the AR_model function fit returns a number.
# We take the sign (- or +) of this number as the model's guess.
return (np.dot(x1.T, p))
def error_rate(x_test, p):
"""
Returns the error of the Autoregression model. Error is the number of
mismatched predictions divided by total number of test points.
Args:
x_test (numpy array of floats): data to be predicted
p (numpy array of floats): regression coefficients of size [r] after
solving the autoregression (order r) problem on train data
Returns:
(float): Error (percentage).
"""
x1, x2 = build_time_delay_matrices(x_test, len(p)-1)
return np.sum(abs(x2 - AR_prediction(x_test, p)))
def plot_residual_histogram(res):
"""Helper function for Exercise 4A"""
fig = plt.figure()
plt.hist(res)
plt.xlabel('error in linear model')
plt.title('stdev of errors = {std:.4f}'.format(std=res.std()))
plt.show()
def plot_training_fit(x1, x2, p):
"""Helper function for Exercise 4B"""
fig = plt.figure()
plt.scatter(x2 + np.random.standard_normal(len(x2))*0.02,
np.dot(x1.T, p), alpha=0.2)
plt.title('Training fit, order {r:d} AR model'.format(r=r))
plt.xlabel('x')
plt.ylabel('estimated x')
plt.show()
healthy_data=pd.read_pickle('data/HEALTHY_Part_WholeBrain_wPLI_10_1_alpha.pickle')
doc_data=pd.read_pickle('data/New_Part_WholeBrain_wPLI_10_1_alpha.pickle')
import seaborn as sns
data=pd.DataFrame(np.row_stack((doc_data,healthy_data)))
data.columns=healthy_data.columns
X=data.iloc[:,4:]
areas= X.columns
Phase=['Base']
Part = ['S02', 'S05', 'S07', 'S09', 'S10', 'S11', 'S12', 'S13', 'S15','S16','S17',
'S18', 'S19', 'S20', 'S22', 'S23',
'W03', 'W04', 'W08', 'W22', 'W28','W31', 'W34', 'W36',
'A03', 'A05', 'A06', 'A07', 'A10', 'A11', 'A12', 'A15', 'A17']
Part_heal = ['A03', 'A05', 'A06', 'A07', 'A10', 'A11', 'A12', 'A15', 'A17']
Part_nonr = ['S05', 'S10', 'S11', 'S12', 'S13', 'S15', 'S16', 'S17',
'S18', 'S22', 'S23', 'W04', 'W08', 'W28', 'W31', 'W34', 'W36']
Part_reco=['S02', 'S07', 'S09', 'S19', 'S20', 'W03', 'W22']
#monkey_at_typewriter = '10010101001101000111001010110001100101000101101001010010101010001101101001101000011110100011011010010011001101000011101001110000011111011101000011110000111101001010101000111100000011111000001010100110101001011010010100101101000110010001100011100011100011100010110010111000101'
#x = np.array([0,0,0,0,0,1,0,1,0,1])
x=np.array(X.loc[1:150 ,areas[0]], dtype='float')
test=np.array(X.loc[150:300 ,areas[0]], dtype='float')
r = 5 # remove later
x1, x2, p = AR_model(x, r)
with plt.xkcd():
plot_training_fit(x1, x2, p)
# range of r's to try
r = np.arange(1, 21)
err = np.ones_like(r) * 1.0
for i, rr in enumerate(r):
# fitting the model on training data
x1, x2, p = AR_model(x, rr)
# computing and storing the test error
test_error = error_rate(test, p)
err[i] = test_error
fig = plt.figure()
plt.plot(r, err, '.-')
#plt.plot([1, r[-1]], [0.5, 0.5], c='r', label='random chance')
plt.xlabel('Order r of AR model')
plt.ylabel('Test error')
plt.xticks(np.arange(0, 25, 5))
plt.legend()
plt.show() | [
"55599742+CharlotteMaschke@users.noreply.github.com"
] | 55599742+CharlotteMaschke@users.noreply.github.com |
bc1eca6413b63ee747fbdc5ce978fea9d29c9081 | b7ddbfdc0b7bf2eb2fcbbcd2cfa8dccf6af58d7a | /src/words/main.py | 9fff5e544b66128a30010a85ff9a77155af2a951 | [] | no_license | Naerriel/popular-words | 29050bc7ee73184f182fd3632d2e4b1f59a06170 | fd7647758bedcf70809de0dabd438bd12737239c | refs/heads/master | 2023-07-13T07:38:11.664806 | 2021-08-18T18:21:14 | 2021-08-18T18:21:14 | 296,834,385 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 329 | py | from src.words.frequencies import get_relative_frequencies
# book[0] - book title, book[1] - book words array
def create_chart(books):
relative_frequencies = get_relative_frequencies(books)
result = []
for (i, book) in enumerate(books):
result.append((book[0], relative_frequencies[i]))
return result | [
"naerriel@gmail.com"
] | naerriel@gmail.com |
f8fd4511a108b8fa1fb60b90cb489e7232eb676d | 9e988c0dfbea15cd23a3de860cb0c88c3dcdbd97 | /sdBs/AllRun/galex_j032139.63+472718.83/sdB_galex_j032139.63+472718.83_coadd.py | 7700527b519c981826539b80b5486dc86e5c9e84 | [] | no_license | tboudreaux/SummerSTScICode | 73b2e5839b10c0bf733808f4316d34be91c5a3bd | 4dd1ffbb09e0a599257d21872f9d62b5420028b0 | refs/heads/master | 2021-01-20T18:07:44.723496 | 2016-08-08T16:49:53 | 2016-08-08T16:49:53 | 65,221,159 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 489 | py | from gPhoton.gMap import gMap
def main():
gMap(band="NUV", skypos=[50.415125,47.455231], skyrange=[0.0333333333333,0.0333333333333], stepsz = 30., cntfile="/data2/fleming/GPHOTON_OUTPUT/LIGHTCURVES/sdBs/sdB_galex_j032139.63+472718.83/sdB_galex_j032139.63+472718.83_movie_count.fits", cntcoaddfile="/data2/fleming/GPHOTON_OUTPUT/LIGHTCURVES/sdB/sdB_galex_j032139.63+472718.83/sdB_galex_j032139.63+472718.83_count_coadd.fits", overwrite=True, verbose=3)
if __name__ == "__main__":
main()
| [
"thomas@boudreauxmail.com"
] | thomas@boudreauxmail.com |
63093190ee20e10698bd99dcea94ccf5d076a006 | 04803c70bb97012b7d500a177ac0240fb2ddbe38 | /1heptane/pdep/network4267_1.py | 8a706002eeed10a53d67be4e75593936ac4c0251 | [] | no_license | shenghuiqin/chpd | 735e0415f6688d88579fc935459c1b0f53596d1d | 396ba54629036e3f2be0b3fabe09b78c90d56939 | refs/heads/master | 2023-03-01T23:29:02.118150 | 2019-10-05T04:02:23 | 2019-10-05T04:02:23 | 192,084,217 | 0 | 0 | null | 2019-06-18T18:33:13 | 2019-06-15T13:52:28 | HTML | UTF-8 | Python | false | false | 69,142 | py | species(
label = 'C=C([CH]C)C(=C)[CH]C(24182)',
structure = SMILES('[CH2]C(=CC)C([CH2])=CC'),
E0 = (249.687,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([325,375,415,465,420,450,1700,1750,2750,2770,2790,2810,2830,2850,1350,1400,1450,1500,700,800,1000,1100,1350,1400,900,1100,3000,3033.33,3066.67,3100,415,465,780,850,1435,1475,900,1100,2995,3025,975,1000,1300,1375,400,500,1630,1680,180],'cm^-1')),
HinderedRotor(inertia=(0.735277,'amu*angstrom^2'), symmetry=1, barrier=(16.9055,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.0632434,'amu*angstrom^2'), symmetry=1, barrier=(29.514,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.737545,'amu*angstrom^2'), symmetry=1, barrier=(16.9576,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.732781,'amu*angstrom^2'), symmetry=1, barrier=(16.8481,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.739219,'amu*angstrom^2'), symmetry=1, barrier=(16.9961,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (108.181,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.384005,0.0840749,-5.09991e-05,5.50851e-09,4.14197e-12,30198.9,28.4131], Tmin=(100,'K'), Tmax=(1039.09,'K')), NASAPolynomial(coeffs=[18.1326,0.0354522,-1.35159e-05,2.44392e-09,-1.69358e-13,25127.7,-67.5143], Tmin=(1039.09,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(249.687,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(461.453,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-CdsCsH) + group(Cds-CdsCsH) + radical(Allyl_P) + radical(Allyl_P)"""),
)
species(
label = 'CH3CHCCH2(18175)',
structure = SMILES('C=C=CC'),
E0 = (145.615,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2950,3100,1380,975,1025,1650,540,610,2055,2750,2800,2850,1350,1500,750,1050,1375,1000,3010,987.5,1337.5,450,1655],'cm^-1')),
HinderedRotor(inertia=(0.759584,'amu*angstrom^2'), symmetry=1, barrier=(17.4643,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (54.0904,'amu'),
collisionModel = TransportData(shapeIndex=2, epsilon=(2996.71,'J/mol'), sigma=(5.18551,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0, comment="""Epsilon & sigma estimated with Tc=468.08 K, Pc=48.77 bar (from Joback method)"""),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.74635,0.0218189,8.22353e-06,-2.14768e-08,8.55624e-12,17563.6,12.7381], Tmin=(100,'K'), Tmax=(1025.6,'K')), NASAPolynomial(coeffs=[6.82078,0.0192338,-7.45622e-06,1.36536e-09,-9.53195e-14,16028,-10.4333], Tmin=(1025.6,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(145.615,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(228.648,'J/(mol*K)'), label="""CH3CHCCH2""", comment="""Thermo library: DFT_QCI_thermo"""),
)
species(
label = '[CH2]C1([CH]C)CC1=CC(25275)',
structure = SMILES('[CH2]C1([CH]C)CC1=CC'),
E0 = (462.221,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (108.181,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.263258,0.0692237,-2.26363e-05,-1.35463e-08,8.13734e-12,55737.7,31.4039], Tmin=(100,'K'), Tmax=(1105.46,'K')), NASAPolynomial(coeffs=[15.171,0.0400578,-1.66801e-05,3.13624e-09,-2.2049e-13,50927.8,-48.8594], Tmin=(1105.46,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(462.221,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(465.61,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)CsCsCs) + group(Cs-CsCsHH) + group(Cs-(Cds-Cds)CsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsCs) + group(Cds-CdsCsH) + ring(Methylene_cyclopropane) + radical(Neopentyl) + radical(Cs_S)"""),
)
species(
label = 'C=[C][CH]C(18176)',
structure = SMILES('[CH2][C]=CC'),
E0 = (361.056,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([1685,370,2750,2800,2850,1350,1500,750,1050,1375,1000,3000,3100,440,815,1455,1000,3010,987.5,1337.5,450,1655],'cm^-1')),
HinderedRotor(inertia=(0.352622,'amu*angstrom^2'), symmetry=1, barrier=(8.10748,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.828631,'amu*angstrom^2'), symmetry=1, barrier=(19.0519,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (54.0904,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.42015,0.030446,-1.69076e-05,4.64684e-09,-5.12013e-13,43485.7,14.8304], Tmin=(100,'K'), Tmax=(2065.83,'K')), NASAPolynomial(coeffs=[10.7464,0.014324,-5.20136e-06,8.69079e-10,-5.48385e-14,40045.6,-31.3799], Tmin=(2065.83,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(361.056,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(274.378,'J/(mol*K)'), comment="""Thermo library: DFT_QCI_thermo + radical(Cds_S) + radical(Allyl_P)"""),
)
species(
label = '[CH2]C(=CC)C(C)=[C]C(25412)',
structure = SMILES('[CH2]C(=CC)C(C)=[C]C'),
E0 = (336.03,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([325,375,415,465,420,450,1700,1750,1685,370,2750,2762.5,2775,2787.5,2800,2812.5,2825,2837.5,2850,1350,1380,1410,1440,1470,1500,700,750,800,1000,1050,1100,1350,1375,1400,900,1000,1100,3000,3100,440,815,1455,1000,3010,987.5,1337.5,450,1655,222.04],'cm^-1')),
HinderedRotor(inertia=(0.395973,'amu*angstrom^2'), symmetry=1, barrier=(13.8694,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.396086,'amu*angstrom^2'), symmetry=1, barrier=(13.8683,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.395737,'amu*angstrom^2'), symmetry=1, barrier=(13.8691,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.395039,'amu*angstrom^2'), symmetry=1, barrier=(13.8689,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.395901,'amu*angstrom^2'), symmetry=1, barrier=(13.8689,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (108.181,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.116365,0.0876489,-7.20737e-05,3.21805e-08,-5.96317e-12,40565.5,28.3373], Tmin=(100,'K'), Tmax=(1264.63,'K')), NASAPolynomial(coeffs=[14.5979,0.041109,-1.68732e-05,3.08148e-09,-2.10818e-13,36843.8,-46.1055], Tmin=(1264.63,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(336.03,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(461.453,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-CdsCsH) + group(Cds-CdsCsH) + radical(Cds_S) + radical(Allyl_P)"""),
)
species(
label = '[CH2]C(=[C]C)C(C)=CC(25413)',
structure = SMILES('[CH2]C(=[C]C)C(C)=CC'),
E0 = (336.03,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([325,375,415,465,420,450,1700,1750,1685,370,2750,2762.5,2775,2787.5,2800,2812.5,2825,2837.5,2850,1350,1380,1410,1440,1470,1500,700,750,800,1000,1050,1100,1350,1375,1400,900,1000,1100,3000,3100,440,815,1455,1000,3010,987.5,1337.5,450,1655,222.04],'cm^-1')),
HinderedRotor(inertia=(0.395973,'amu*angstrom^2'), symmetry=1, barrier=(13.8694,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.396086,'amu*angstrom^2'), symmetry=1, barrier=(13.8683,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.395737,'amu*angstrom^2'), symmetry=1, barrier=(13.8691,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.395039,'amu*angstrom^2'), symmetry=1, barrier=(13.8689,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.395901,'amu*angstrom^2'), symmetry=1, barrier=(13.8689,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (108.181,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.116365,0.0876489,-7.20737e-05,3.21805e-08,-5.96317e-12,40565.5,28.3373], Tmin=(100,'K'), Tmax=(1264.63,'K')), NASAPolynomial(coeffs=[14.5979,0.041109,-1.68732e-05,3.08148e-09,-2.10818e-13,36843.8,-46.1055], Tmin=(1264.63,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(336.03,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(461.453,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-CdsCsH) + group(Cds-CdsCsH) + radical(Allyl_P) + radical(Cds_S)"""),
)
species(
label = '[CH2]C(=CC)[C](C)C=C(24605)',
structure = SMILES('[CH2]C=C(C)C([CH2])=CC'),
E0 = (216.244,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([325,375,415,465,420,450,1700,1750,2750,2770,2790,2810,2830,2850,1350,1400,1450,1500,700,800,1000,1100,1350,1400,900,1100,3000,3033.33,3066.67,3100,415,465,780,850,1435,1475,900,1100,2995,3025,975,1000,1300,1375,400,500,1630,1680,180],'cm^-1')),
HinderedRotor(inertia=(0.712083,'amu*angstrom^2'), symmetry=1, barrier=(16.3722,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.555659,'amu*angstrom^2'), symmetry=1, barrier=(96.3851,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.0202512,'amu*angstrom^2'), symmetry=1, barrier=(16.3711,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.712008,'amu*angstrom^2'), symmetry=1, barrier=(16.3705,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(4.19211,'amu*angstrom^2'), symmetry=1, barrier=(96.3849,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (108.181,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.0883175,0.0775021,-3.58132e-05,-7.55711e-09,8.27771e-12,26166.1,29.3215], Tmin=(100,'K'), Tmax=(1017.17,'K')), NASAPolynomial(coeffs=[16.4341,0.0376674,-1.41425e-05,2.53759e-09,-1.75328e-13,21504.4,-57.0638], Tmin=(1017.17,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(216.244,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(461.453,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-CdsCsH) + group(Cds-CdsCsH) + radical(Allyl_P) + radical(C=CC=CCJ)"""),
)
species(
label = '[CH2][C](C=C)C(C)=CC(24606)',
structure = SMILES('[CH2]C=C([CH2])C(C)=CC'),
E0 = (216.244,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (108.181,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.0883175,0.0775021,-3.58132e-05,-7.55711e-09,8.27771e-12,26166.1,29.3215], Tmin=(100,'K'), Tmax=(1017.17,'K')), NASAPolynomial(coeffs=[16.4341,0.0376674,-1.41425e-05,2.53759e-09,-1.75328e-13,21504.4,-57.0638], Tmin=(1017.17,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(216.244,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(461.453,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-CdsCsH) + group(Cds-CdsCsH) + radical(Allyl_P) + radical(C=CC=CCJ)"""),
)
species(
label = '[CH2]C(=CC)[C]1CC1C(25414)',
structure = SMILES('[CH2]C(=CC)[C]1CC1C'),
E0 = (289.9,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (108.181,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.71289,0.0520158,3.84829e-05,-8.55933e-08,3.61457e-11,35003.5,26.4903], Tmin=(100,'K'), Tmax=(968.714,'K')), NASAPolynomial(coeffs=[16.7686,0.0352996,-1.24057e-05,2.26286e-09,-1.62921e-13,29566.5,-62.466], Tmin=(968.714,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(289.9,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(465.61,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-CsCsCsH) + group(Cs-(Cds-Cds)CsCsH) + group(Cs-CsCsHH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsCs) + group(Cds-CdsCsH) + ring(Cyclopropane) + radical(Allyl_T) + radical(Allyl_P)"""),
)
species(
label = '[CH2][C]1C(=CC)CC1C(25415)',
structure = SMILES('[CH2]C1=C([CH]C)CC1C'),
E0 = (304.572,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (108.181,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.583091,0.0531885,4.0938e-05,-9.08388e-08,3.83549e-11,36774.2,26.4705], Tmin=(100,'K'), Tmax=(972.301,'K')), NASAPolynomial(coeffs=[18.2947,0.0339462,-1.21014e-05,2.24934e-09,-1.64353e-13,30795.4,-71.5147], Tmin=(972.301,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(304.572,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(465.61,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)CsCsH) + group(Cs-(Cds-Cds)CsHH) + group(Cs-(Cds-Cds)CsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsCs) + group(Cds-CdsCsCs) + ring(Cyclobutene) + radical(Allyl_P) + radical(Allyl_S)"""),
)
species(
label = 'CH2(S)(23)',
structure = SMILES('[CH2]'),
E0 = (419.862,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([1369.36,2789.41,2993.36],'cm^-1')),
],
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (14.0266,'amu'),
collisionModel = TransportData(shapeIndex=2, epsilon=(1197.29,'J/mol'), sigma=(3.8,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0.0, comment="""GRI-Mech"""),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[4.19195,-0.00230793,8.0509e-06,-6.60123e-09,1.95638e-12,50484.3,-0.754589], Tmin=(200,'K'), Tmax=(1000,'K')), NASAPolynomial(coeffs=[2.28556,0.00460255,-1.97412e-06,4.09548e-10,-3.34695e-14,50922.4,8.67684], Tmin=(1000,'K'), Tmax=(3000,'K'))], Tmin=(200,'K'), Tmax=(3000,'K'), E0=(419.862,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(58.2013,'J/(mol*K)'), label="""CH2(S)""", comment="""Thermo library: Klippenstein_Glarborg2016"""),
)
species(
label = '[CH2]C(=C)C([CH2])=CC(25416)',
structure = SMILES('[CH2]C(=C)C([CH2])=CC'),
E0 = (285.713,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([325,375,415,465,420,450,1700,1750,2950,3100,1380,975,1025,1650,2750,2800,2850,1350,1500,750,1050,1375,1000,3000,3033.33,3066.67,3100,415,465,780,850,1435,1475,900,1100,3010,987.5,1337.5,450,1655,311.383],'cm^-1')),
HinderedRotor(inertia=(0.327475,'amu*angstrom^2'), symmetry=1, barrier=(22.5291,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.327466,'amu*angstrom^2'), symmetry=1, barrier=(22.5294,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.327318,'amu*angstrom^2'), symmetry=1, barrier=(22.5272,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.327483,'amu*angstrom^2'), symmetry=1, barrier=(22.5297,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (94.1543,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.335271,0.0676667,-2.76626e-05,-1.62749e-08,1.21982e-11,34506.8,24.024], Tmin=(100,'K'), Tmax=(980.594,'K')), NASAPolynomial(coeffs=[17.5531,0.0266059,-9.47854e-06,1.70194e-09,-1.19937e-13,29727.4,-65.8563], Tmin=(980.594,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(285.713,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(390.78,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-CdsCsH) + group(Cds-CdsHH) + radical(Allyl_P) + radical(Allyl_P)"""),
)
species(
label = 'C=C([CH]C)C[C]=CC(24184)',
structure = SMILES('[CH2]C(=CC)C[C]=CC'),
E0 = (366.985,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2995,3025,975,1000,1300,1375,400,500,1630,1680,2750,2770,2790,2810,2830,2850,1350,1400,1450,1500,700,800,1000,1100,1350,1400,900,1100,1685,370,350,440,435,1725,2750,2850,1437.5,1250,1305,750,350,3000,3100,440,815,1455,1000,180,579.702],'cm^-1')),
HinderedRotor(inertia=(0.147406,'amu*angstrom^2'), symmetry=1, barrier=(3.38916,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.64226,'amu*angstrom^2'), symmetry=1, barrier=(14.7668,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.64164,'amu*angstrom^2'), symmetry=1, barrier=(14.7526,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.643937,'amu*angstrom^2'), symmetry=1, barrier=(14.8054,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.145327,'amu*angstrom^2'), symmetry=1, barrier=(3.34136,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (108.181,'amu'),
collisionModel = TransportData(shapeIndex=2, epsilon=(3683.66,'J/mol'), sigma=(6.4482,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0, comment="""Epsilon & sigma estimated with Tc=575.38 K, Pc=31.18 bar (from Joback method)"""),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.29648,0.0786067,-5.42868e-05,1.96375e-08,-2.97459e-12,44273.2,31.2372], Tmin=(100,'K'), Tmax=(1490.43,'K')), NASAPolynomial(coeffs=[13.9025,0.0420909,-1.75363e-05,3.199e-09,-2.17227e-13,40217.5,-39.8334], Tmin=(1490.43,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(366.985,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(461.453,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)(Cds-Cds)HH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsCs) + group(Cds-CdsCsH) + group(Cds-CdsCsH) + group(Cds-CdsCsH) + radical(Cds_S) + radical(Allyl_P)"""),
)
species(
label = 'CC=C1CCC1=CC(25269)',
structure = SMILES('CC=C1CCC1=CC'),
E0 = (114.107,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (108.181,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.677799,0.0585738,5.80411e-06,-4.1598e-08,1.78951e-11,13856,25.5085], Tmin=(100,'K'), Tmax=(1034.79,'K')), NASAPolynomial(coeffs=[13.4814,0.0415234,-1.65073e-05,3.07348e-09,-2.16896e-13,9469.28,-45.0922], Tmin=(1034.79,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(114.107,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(473.925,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)CsHH) + group(Cs-(Cds-Cds)CsHH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-CdsCsH) + group(Cds-CdsCsH) + ring(12methylenecyclobutane)"""),
)
species(
label = 'CH2(19)',
structure = SMILES('[CH2]'),
E0 = (381.563,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([1032.72,2936.3,3459],'cm^-1')),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (14.0266,'amu'),
collisionModel = TransportData(shapeIndex=2, epsilon=(1197.29,'J/mol'), sigma=(3.8,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0.0, comment="""GRI-Mech"""),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[3.8328,0.000224446,4.68033e-06,-6.04743e-09,2.59009e-12,45920.8,1.40666], Tmin=(200,'K'), Tmax=(1000,'K')), NASAPolynomial(coeffs=[3.16229,0.00281798,-7.56235e-07,5.05446e-11,5.65236e-15,46099.1,4.77656], Tmin=(1000,'K'), Tmax=(3000,'K'))], Tmin=(200,'K'), Tmax=(3000,'K'), E0=(381.563,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(58.2013,'J/(mol*K)'), label="""CH2""", comment="""Thermo library: Klippenstein_Glarborg2016"""),
)
species(
label = '[CH2]C([C]=CC)=CC(25417)',
structure = SMILES('[CH2]C([C]=CC)=CC'),
E0 = (334.774,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([350,440,435,1725,1685,370,2750,2770,2790,2810,2830,2850,1350,1400,1450,1500,700,800,1000,1100,1350,1400,900,1100,3000,3100,440,815,1455,1000,2995,3025,975,1000,1300,1375,400,500,1630,1680,180],'cm^-1')),
HinderedRotor(inertia=(0.7606,'amu*angstrom^2'), symmetry=1, barrier=(17.4877,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.760854,'amu*angstrom^2'), symmetry=1, barrier=(17.4935,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.760586,'amu*angstrom^2'), symmetry=1, barrier=(17.4874,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(2.15146,'amu*angstrom^2'), symmetry=1, barrier=(49.4663,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (94.1543,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.352604,0.0734369,-5.91187e-05,2.57941e-08,-4.60694e-12,40400.9,25.1788], Tmin=(100,'K'), Tmax=(1327.42,'K')), NASAPolynomial(coeffs=[14.2321,0.0316126,-1.18565e-05,2.05761e-09,-1.36512e-13,36716.1,-45.7131], Tmin=(1327.42,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(334.774,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(390.78,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-CdsCsH) + group(Cds-CdsCsH) + group(Cds-Cds(Cds-Cds)H) + radical(C=CJC=C) + radical(Allyl_P)"""),
)
species(
label = '[CH2]C1([CH]C)C(=C)C1C(25296)',
structure = SMILES('[CH2]C1([CH]C)C(=C)C1C'),
E0 = (466.494,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (108.181,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.29276,0.0655305,-4.50464e-06,-3.74661e-08,1.7759e-11,56253.7,30.0992], Tmin=(100,'K'), Tmax=(1027.4,'K')), NASAPolynomial(coeffs=[16.6435,0.0372633,-1.49065e-05,2.81296e-09,-2.01072e-13,51026,-58.316], Tmin=(1027.4,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(466.494,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(465.61,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)CsCsCs) + group(Cs-(Cds-Cds)CsCsH) + group(Cs-CsCsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cds-CdsCsCs) + group(Cds-CdsHH) + ring(Methylene_cyclopropane) + radical(Neopentyl) + radical(Cs_S)"""),
)
species(
label = 'H(3)',
structure = SMILES('[H]'),
E0 = (211.792,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (1.00794,'amu'),
collisionModel = TransportData(shapeIndex=0, epsilon=(1205.6,'J/mol'), sigma=(2.05,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0.0, comment="""GRI-Mech"""),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.5,9.24385e-15,-1.3678e-17,6.66185e-21,-1.00107e-24,25472.7,-0.459566], Tmin=(100,'K'), Tmax=(3459.6,'K')), NASAPolynomial(coeffs=[2.5,9.20456e-12,-3.58608e-15,6.15199e-19,-3.92042e-23,25472.7,-0.459566], Tmin=(3459.6,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(211.792,'kJ/mol'), Cp0=(20.7862,'J/(mol*K)'), CpInf=(20.7862,'J/(mol*K)'), label="""H""", comment="""Thermo library: BurkeH2O2"""),
)
species(
label = '[CH2]C(=CC)C(=C)C=C(24604)',
structure = SMILES('[CH2]C(=CC)C(=C)C=C'),
E0 = (242.677,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([325,375,415,465,420,450,1700,1750,2950,3000,3050,3100,1330,1430,900,1050,1000,1050,1600,1700,2750,2800,2850,1350,1500,750,1050,1375,1000,3000,3100,440,815,1455,1000,2995,3025,975,1000,1300,1375,400,500,1630,1680,181.962,683.313],'cm^-1')),
HinderedRotor(inertia=(0.669842,'amu*angstrom^2'), symmetry=1, barrier=(19.1337,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.0582339,'amu*angstrom^2'), symmetry=1, barrier=(19.1767,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.83204,'amu*angstrom^2'), symmetry=1, barrier=(19.1302,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(4.52237,'amu*angstrom^2'), symmetry=1, barrier=(104.569,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 2,
opticalIsomers = 1,
molecularWeight = (107.173,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.293043,0.0682771,-2.00337e-05,-2.05401e-08,1.21516e-11,29332.3,27.0261], Tmin=(100,'K'), Tmax=(1018.57,'K')), NASAPolynomial(coeffs=[15.7386,0.0358123,-1.37404e-05,2.51366e-09,-1.76142e-13,24723.4,-54.9529], Tmin=(1018.57,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(242.677,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(440.667,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-Cds(Cds-Cds)(Cds-Cds)) + group(Cds-CdsCsH) + group(Cds-Cds(Cds-Cds)H) + group(Cds-CdsHH) + group(Cds-CdsHH) + radical(Allyl_P)"""),
)
species(
label = '[CH2]CC(=C)C([CH2])=CC(25418)',
structure = SMILES('[CH2]CC(=C)C([CH2])=CC'),
E0 = (316.814,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3010,987.5,1337.5,450,1655,2750,2800,2850,1350,1500,750,1050,1375,1000,2950,3100,1380,975,1025,1650,325,375,415,465,420,450,1700,1750,2750,2850,1437.5,1250,1305,750,350,3000,3033.33,3066.67,3100,415,465,780,850,1435,1475,900,1100,180,180],'cm^-1')),
HinderedRotor(inertia=(0.0368535,'amu*angstrom^2'), symmetry=1, barrier=(17.9864,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.00736317,'amu*angstrom^2'), symmetry=1, barrier=(3.60618,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.781153,'amu*angstrom^2'), symmetry=1, barrier=(17.9602,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.779478,'amu*angstrom^2'), symmetry=1, barrier=(17.9217,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.781104,'amu*angstrom^2'), symmetry=1, barrier=(17.9591,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (108.181,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.348925,0.0836004,-5.1879e-05,7.14877e-09,3.44908e-12,38270.9,31.5928], Tmin=(100,'K'), Tmax=(1044.14,'K')), NASAPolynomial(coeffs=[17.9255,0.0352115,-1.34219e-05,2.42456e-09,-1.67785e-13,33276.3,-63.0036], Tmin=(1044.14,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(316.814,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(461.453,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)CsHH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-CdsCsH) + group(Cds-CdsHH) + radical(RCCJ) + radical(Allyl_P)"""),
)
species(
label = '[CH]=C(CC)C([CH2])=CC(25419)',
structure = SMILES('[CH]=C(CC)C([CH2])=CC'),
E0 = (358.664,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3120,650,792.5,1650,3010,987.5,1337.5,450,1655,2750,2770,2790,2810,2830,2850,1350,1400,1450,1500,700,800,1000,1100,1350,1400,900,1100,325,375,415,465,420,450,1700,1750,2750,2850,1437.5,1250,1305,750,350,3000,3100,440,815,1455,1000,180],'cm^-1')),
HinderedRotor(inertia=(0.701639,'amu*angstrom^2'), symmetry=1, barrier=(16.1321,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.344302,'amu*angstrom^2'), symmetry=1, barrier=(16.1602,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.0492932,'amu*angstrom^2'), symmetry=1, barrier=(16.1378,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.702005,'amu*angstrom^2'), symmetry=1, barrier=(16.1405,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.702379,'amu*angstrom^2'), symmetry=1, barrier=(16.1491,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (108.181,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.468616,0.0864938,-5.84569e-05,1.27697e-08,1.75707e-12,43308.4,30.6389], Tmin=(100,'K'), Tmax=(1047.28,'K')), NASAPolynomial(coeffs=[18.4195,0.034593,-1.31104e-05,2.35762e-09,-1.62637e-13,38242.2,-66.6572], Tmin=(1047.28,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(358.664,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(461.453,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)CsHH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-CdsCsH) + group(Cds-CdsHH) + radical(Allyl_P) + radical(Cds_P)"""),
)
species(
label = '[CH2]C(=[C]C)C(=C)CC(25420)',
structure = SMILES('[CH2]C(=[C]C)C(=C)CC'),
E0 = (349.41,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([1685,370,2750,2770,2790,2810,2830,2850,1350,1400,1450,1500,700,800,1000,1100,1350,1400,900,1100,2950,3100,1380,975,1025,1650,325,375,415,465,420,450,1700,1750,2750,2850,1437.5,1250,1305,750,350,3000,3100,440,815,1455,1000,180,180],'cm^-1')),
HinderedRotor(inertia=(0.159905,'amu*angstrom^2'), symmetry=1, barrier=(15.9368,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.693159,'amu*angstrom^2'), symmetry=1, barrier=(15.9371,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.693127,'amu*angstrom^2'), symmetry=1, barrier=(15.9364,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.693165,'amu*angstrom^2'), symmetry=1, barrier=(15.9372,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.0150632,'amu*angstrom^2'), symmetry=1, barrier=(15.9371,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (108.181,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.583231,0.089245,-7.16619e-05,3.00631e-08,-5.07891e-12,42198.9,31.1306], Tmin=(100,'K'), Tmax=(1412.15,'K')), NASAPolynomial(coeffs=[19.0319,0.0336833,-1.2643e-05,2.20036e-09,-1.46165e-13,36659.1,-70.2702], Tmin=(1412.15,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(349.41,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(461.453,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)CsHH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-CdsCsH) + group(Cds-CdsHH) + radical(Allyl_P) + radical(Cds_S)"""),
)
species(
label = '[CH]=C([CH]C)C(C)=CC(25421)',
structure = SMILES('[CH]C(=CC)C(C)=CC'),
E0 = (317.373,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([325,375,415,465,420,450,1700,1750,2750,2762.5,2775,2787.5,2800,2812.5,2825,2837.5,2850,1350,1380,1410,1440,1470,1500,700,750,800,1000,1050,1100,1350,1375,1400,900,1000,1100,2995,3025,975,1000,1300,1375,400,500,1630,1680,200,800,1200,1600],'cm^-1')),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (108.181,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.247945,0.0873521,-6.16843e-05,2.31486e-08,-3.62747e-12,38328.8,29.1665], Tmin=(100,'K'), Tmax=(1460.93,'K')), NASAPolynomial(coeffs=[15.297,0.0447902,-1.7984e-05,3.20673e-09,-2.14924e-13,33786.8,-51.7212], Tmin=(1460.93,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(317.373,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(461.453,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-CdsCsH) + group(Cds-CdsCsH) + radical(AllylJ2_triplet)"""),
)
species(
label = '[CH2][C](C=C)C(=C)CC(24623)',
structure = SMILES('[CH2]C(C=C)=C([CH2])CC'),
E0 = (228.159,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (108.181,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.0497728,0.0733281,-1.6094e-05,-3.35123e-08,1.88363e-11,27601.1,30.4448], Tmin=(100,'K'), Tmax=(975.095,'K')), NASAPolynomial(coeffs=[18.3695,0.0342638,-1.21408e-05,2.16747e-09,-1.52112e-13,22274,-66.8493], Tmin=(975.095,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(228.159,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(461.453,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)CsHH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsCs) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-Cds(Cds-Cds)H) + group(Cds-CdsHH) + radical(C=CC=CCJ) + radical(Allyl_P)"""),
)
species(
label = 'C[CH][C]1CCC1=CC(25422)',
structure = SMILES('C[CH]C1CCC=1[CH]C'),
E0 = (303.292,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (108.181,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.788866,0.0500701,4.22235e-05,-8.64809e-08,3.53174e-11,36611.5,25.2586], Tmin=(100,'K'), Tmax=(987.239,'K')), NASAPolynomial(coeffs=[16.2187,0.0373502,-1.4111e-05,2.65357e-09,-1.92503e-13,31138.2,-61.2734], Tmin=(987.239,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(303.292,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(465.61,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)CsHH) + group(Cs-(Cds-Cds)CsHH) + group(Cs-(Cds-Cds)CsHH) + group(Cs-(Cds-Cds)CsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cds-CdsCsCs) + group(Cds-CdsCsCs) + ring(Cyclobutene) + radical(Allyl_S) + radical(Allyl_S)"""),
)
species(
label = '[CH2][C]1C(=C)C(C)C1C(25423)',
structure = SMILES('[CH2]C1=C([CH2])C(C)C1C'),
E0 = (305.852,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (108.181,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.377097,0.0563026,3.9705e-05,-9.53284e-08,4.14811e-11,36937,26.2973], Tmin=(100,'K'), Tmax=(959.735,'K')), NASAPolynomial(coeffs=[20.4056,0.0304853,-1.006e-05,1.83774e-09,-1.35603e-13,30437.2,-83.3398], Tmin=(959.735,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(305.852,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(465.61,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)CsCsH) + group(Cs-(Cds-Cds)CsCsH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsCs) + group(Cds-CdsCsCs) + ring(Cyclobutene) + radical(Allyl_P) + radical(Allyl_P)"""),
)
species(
label = 'C=CC(=C)C(C)=CC(24616)',
structure = SMILES('C=CC(=C)C(C)=CC'),
E0 = (91.1774,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (108.181,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.236638,0.0713806,-3.04205e-05,-5.26762e-09,5.54498e-12,11111.2,26.9518], Tmin=(100,'K'), Tmax=(1093.32,'K')), NASAPolynomial(coeffs=[14.1536,0.040705,-1.6104e-05,2.93544e-09,-2.02595e-13,6858.32,-46.9636], Tmin=(1093.32,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(91.1774,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(465.61,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-Cds(Cds-Cds)(Cds-Cds)) + group(Cds-CdsCsH) + group(Cds-Cds(Cds-Cds)H) + group(Cds-CdsHH) + group(Cds-CdsHH)"""),
)
species(
label = 'C=[C]C(C)C(=C)[CH]C(24183)',
structure = SMILES('[CH2]C(=CC)C(C)[C]=C'),
E0 = (369.44,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([1685,370,3010,987.5,1337.5,450,1655,2750,2770,2790,2810,2830,2850,1350,1400,1450,1500,700,800,1000,1100,1350,1400,900,1100,2950,3100,1380,975,1025,1650,1380,1390,370,380,2900,435,350,440,435,1725,3000,3100,440,815,1455,1000,345.333,347.343],'cm^-1')),
HinderedRotor(inertia=(0.119405,'amu*angstrom^2'), symmetry=1, barrier=(9.93037,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.281457,'amu*angstrom^2'), symmetry=1, barrier=(24.022,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.116909,'amu*angstrom^2'), symmetry=1, barrier=(9.94809,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.117447,'amu*angstrom^2'), symmetry=1, barrier=(9.9744,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.116555,'amu*angstrom^2'), symmetry=1, barrier=(9.93684,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (108.181,'amu'),
collisionModel = TransportData(shapeIndex=2, epsilon=(3625.33,'J/mol'), sigma=(6.4092,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0, comment="""Epsilon & sigma estimated with Tc=566.27 K, Pc=31.24 bar (from Joback method)"""),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.299693,0.0839308,-6.74533e-05,3.06742e-08,-6.02582e-12,44564.4,29.0122], Tmin=(100,'K'), Tmax=(1163.73,'K')), NASAPolynomial(coeffs=[10.857,0.0476425,-2.06788e-05,3.8782e-09,-2.69295e-13,42107.3,-23.5217], Tmin=(1163.73,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(369.44,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(461.453,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)(Cds-Cds)CsH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsCs) + group(Cds-CdsCsH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + radical(Allyl_P) + radical(Cds_S)"""),
)
species(
label = 'C=C1C(=CC)CC1C(25265)',
structure = SMILES('C=C1C(=CC)CC1C'),
E0 = (118.381,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (108.181,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.689924,0.0550304,2.3689e-05,-6.56265e-08,2.77602e-11,14372.8,24.9628], Tmin=(100,'K'), Tmax=(993.204,'K')), NASAPolynomial(coeffs=[15.3775,0.0380508,-1.43595e-05,2.66472e-09,-1.90565e-13,9375.16,-56.2678], Tmin=(993.204,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(118.381,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(473.925,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)CsCsH) + group(Cs-(Cds-Cds)CsHH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-CdsCsH) + group(Cds-CdsHH) + ring(12methylenecyclobutane)"""),
)
species(
label = 'CHCH3(T)(95)',
structure = SMILES('[CH]C'),
E0 = (343.893,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2750,2800,2850,1350,1500,750,1050,1375,1000,592.414,4000],'cm^-1')),
HinderedRotor(inertia=(0.00438699,'amu*angstrom^2'), symmetry=1, barrier=(26.7685,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (28.0532,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[3.82363,-0.000909515,3.2138e-05,-3.7348e-08,1.3309e-11,41371.4,7.10948], Tmin=(100,'K'), Tmax=(960.812,'K')), NASAPolynomial(coeffs=[4.30487,0.00943069,-3.27559e-06,5.95121e-10,-4.27307e-14,40709.1,1.84202], Tmin=(960.812,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(343.893,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(128.874,'J/(mol*K)'), label="""CHCH3(T)""", comment="""Thermo library: DFT_QCI_thermo"""),
)
species(
label = '[CH2]C([C]=C)=CC(24774)',
structure = SMILES('[CH2]C([C]=C)=CC'),
E0 = (370.8,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([1685,370,2750,2800,2850,1350,1500,750,1050,1375,1000,3010,987.5,1337.5,450,1655,2950,3100,1380,975,1025,1650,350,440,435,1725,3000,3100,440,815,1455,1000,180],'cm^-1')),
HinderedRotor(inertia=(1.17315,'amu*angstrom^2'), symmetry=1, barrier=(26.9731,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(1.17496,'amu*angstrom^2'), symmetry=1, barrier=(27.0146,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(1.1727,'amu*angstrom^2'), symmetry=1, barrier=(26.9626,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (80.1277,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.0818,0.0569416,-3.56598e-05,4.1841e-09,3.20998e-12,44708.4,20.7527], Tmin=(100,'K'), Tmax=(982.69,'K')), NASAPolynomial(coeffs=[12.9204,0.0239405,-8.46845e-06,1.46434e-09,-9.91425e-14,41648.3,-39.886], Tmin=(982.69,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(370.8,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(320.107,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-CdsCsH) + group(Cds-Cds(Cds-Cds)H) + group(Cds-CdsHH) + radical(C=CJC=C) + radical(Allyl_P)"""),
)
species(
label = '[CH]=C([CH]C)C(=C)CC(25424)',
structure = SMILES('[CH]C(=CC)C(=C)CC'),
E0 = (330.753,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2750,2850,1437.5,1250,1305,750,350,2950,3100,1380,975,1025,1650,3010,987.5,1337.5,450,1655,2750,2770,2790,2810,2830,2850,1350,1400,1450,1500,700,800,1000,1100,1350,1400,900,1100,325,375,415,465,420,450,1700,1750,200,800,1066.67,1333.33,1600],'cm^-1')),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (108.181,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.442166,0.0858934,-5.1432e-05,9.5936e-09,1.54315e-12,39950.3,30.9724], Tmin=(100,'K'), Tmax=(1106.5,'K')), NASAPolynomial(coeffs=[16.3579,0.0427111,-1.66841e-05,2.99222e-09,-2.04007e-13,35158.1,-56.633], Tmin=(1106.5,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(330.753,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(461.453,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)CsHH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-CdsCsH) + group(Cds-CdsHH) + radical(AllylJ2_triplet)"""),
)
species(
label = 'C=CC(=C)C(=C)CC(24630)',
structure = SMILES('C=CC(=C)C(=C)CC'),
E0 = (104.558,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (108.181,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.296747,0.0670054,-1.0269e-05,-3.13536e-08,1.59568e-11,12721.3,27.8384], Tmin=(100,'K'), Tmax=(1010.3,'K')), NASAPolynomial(coeffs=[15.6889,0.0379462,-1.44599e-05,2.64736e-09,-1.86033e-13,7984.11,-54.6302], Tmin=(1010.3,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(104.558,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(465.61,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)CsHH) + group(Cs-CsHHH) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-Cds(Cds-Cds)(Cds-Cds)) + group(Cds-Cds(Cds-Cds)H) + group(Cds-CdsHH) + group(Cds-CdsHH) + group(Cds-CdsHH)"""),
)
species(
label = 'C=C1C(=C)C(C)C1C(25274)',
structure = SMILES('C=C1C(=C)C(C)C1C'),
E0 = (122.654,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (108.181,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.691732,0.0515838,4.13669e-05,-8.96066e-08,3.77135e-11,14890,23.0693], Tmin=(100,'K'), Tmax=(969.873,'K')), NASAPolynomial(coeffs=[17.4573,0.0342784,-1.20439e-05,2.21718e-09,-1.61071e-13,9199.74,-69.8715], Tmin=(969.873,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(122.654,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(473.925,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)CsCsH) + group(Cs-(Cds-Cds)CsCsH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-Cds(Cds-Cds)Cs) + group(Cds-CdsHH) + group(Cds-CdsHH) + ring(12methylenecyclobutane)"""),
)
species(
label = 'N2',
structure = SMILES('N#N'),
E0 = (-8.69489,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (28.0135,'amu'),
collisionModel = TransportData(shapeIndex=1, epsilon=(810.913,'J/mol'), sigma=(3.621,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(1.76,'angstroms^3'), rotrelaxcollnum=4.0, comment="""PrimaryTransportLibrary"""),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[3.61263,-0.00100893,2.49898e-06,-1.43376e-09,2.58636e-13,-1051.1,2.6527], Tmin=(100,'K'), Tmax=(1817.04,'K')), NASAPolynomial(coeffs=[2.9759,0.00164141,-7.19722e-07,1.25378e-10,-7.91526e-15,-1025.84,5.53757], Tmin=(1817.04,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-8.69489,'kJ/mol'), Cp0=(29.1007,'J/(mol*K)'), CpInf=(37.4151,'J/(mol*K)'), label="""N2""", comment="""Thermo library: BurkeH2O2"""),
)
species(
label = 'Ne',
structure = SMILES('[Ne]'),
E0 = (-6.19738,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (20.1797,'amu'),
collisionModel = TransportData(shapeIndex=0, epsilon=(1235.53,'J/mol'), sigma=(3.758e-10,'m'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0, comment="""Epsilon & sigma estimated with fixed Lennard Jones Parameters. This is the fallback method! Try improving transport databases!"""),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.5,0,0,0,0,-745.375,3.35532], Tmin=(200,'K'), Tmax=(1000,'K')), NASAPolynomial(coeffs=[2.5,0,0,0,0,-745.375,3.35532], Tmin=(1000,'K'), Tmax=(6000,'K'))], Tmin=(200,'K'), Tmax=(6000,'K'), E0=(-6.19738,'kJ/mol'), Cp0=(20.7862,'J/(mol*K)'), CpInf=(20.7862,'J/(mol*K)'), label="""Ne""", comment="""Thermo library: primaryThermoLibrary"""),
)
transitionState(
label = 'TS1',
E0 = (291.23,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS2',
E0 = (462.221,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS3',
E0 = (538.699,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS4',
E0 = (497.951,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS5',
E0 = (380.338,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS6',
E0 = (399.474,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS7',
E0 = (350.103,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS8',
E0 = (722.113,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS9',
E0 = (343.259,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS10',
E0 = (380.132,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS11',
E0 = (705.575,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS12',
E0 = (537.022,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS13',
E0 = (257.971,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS14',
E0 = (716.337,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS15',
E0 = (466.494,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS16',
E0 = (454.469,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS17',
E0 = (430.619,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS18',
E0 = (503.849,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS19',
E0 = (393.718,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS20',
E0 = (361.682,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS21',
E0 = (350.103,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS22',
E0 = (380.132,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS23',
E0 = (375.044,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS24',
E0 = (274.66,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS25',
E0 = (463.915,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS26',
E0 = (257.971,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS27',
E0 = (714.692,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS28',
E0 = (375.062,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS29',
E0 = (258.055,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS30',
E0 = (257.971,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
reaction(
label = 'reaction1',
reactants = ['C=C([CH]C)C(=C)[CH]C(24182)'],
products = ['CH3CHCCH2(18175)', 'CH3CHCCH2(18175)'],
transitionState = 'TS1',
kinetics = Arrhenius(A=(5e+12,'s^-1'), n=0, Ea=(41.5431,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(1500,'K'), comment="""Exact match found for rate rule [RJJ]
Euclidian distance = 0
family: 1,4_Linear_birad_scission
Ea raised from 0.0 to 41.5 kJ/mol to match endothermicity of reaction."""),
)
reaction(
label = 'reaction2',
reactants = ['C=C([CH]C)C(=C)[CH]C(24182)'],
products = ['[CH2]C1([CH]C)CC1=CC(25275)'],
transitionState = 'TS2',
kinetics = Arrhenius(A=(3.36e+09,'s^-1'), n=0.84, Ea=(212.534,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(2500,'K'), comment="""Estimated using template [R4_S_D;doublebond_intra_HNd;radadd_intra_cs2H] for rate rule [R4_S_(Cd)_D;doublebond_intra_HNd;radadd_intra_cs2H]
Euclidian distance = 2.0
Multiplied by reaction path degeneracy 2.0
family: Intra_R_Add_Exocyclic
Ea raised from 210.2 to 212.5 kJ/mol to match endothermicity of reaction."""),
)
reaction(
label = 'reaction3',
reactants = ['CH3CHCCH2(18175)', 'C=[C][CH]C(18176)'],
products = ['C=C([CH]C)C(=C)[CH]C(24182)'],
transitionState = 'TS3',
kinetics = Arrhenius(A=(0.00086947,'m^3/(mol*s)'), n=2.67356, Ea=(32.0272,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [Ca_Cds-HH;CJ]
Euclidian distance = 0
family: R_Addition_MultipleBond"""),
)
reaction(
label = 'reaction4',
reactants = ['[CH2]C(=CC)C(C)=[C]C(25412)'],
products = ['C=C([CH]C)C(=C)[CH]C(24182)'],
transitionState = 'TS4',
kinetics = Arrhenius(A=(7.74e+09,'s^-1'), n=1.08, Ea=(161.921,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(1500,'K'), comment="""From training reaction 198 used for R3H_DS;Cd_rad_out_Cs;Cs_H_out_2H
Exact match found for rate rule [R3H_DS;Cd_rad_out_Cs;Cs_H_out_2H]
Euclidian distance = 0
Multiplied by reaction path degeneracy 3.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction5',
reactants = ['[CH2]C(=[C]C)C(C)=CC(25413)'],
products = ['C=C([CH]C)C(=C)[CH]C(24182)'],
transitionState = 'TS5',
kinetics = Arrhenius(A=(111300,'s^-1'), n=2.23, Ea=(44.3086,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R4H_DSS;Cd_rad_out_single;Cs_H_out] for rate rule [R4H_DSS;Cd_rad_out_Cs;Cs_H_out_2H]
Euclidian distance = 2.2360679775
Multiplied by reaction path degeneracy 3.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction6',
reactants = ['C=C([CH]C)C(=C)[CH]C(24182)'],
products = ['[CH2]C(=CC)[C](C)C=C(24605)'],
transitionState = 'TS6',
kinetics = Arrhenius(A=(1.6e+06,'s^-1'), n=1.81, Ea=(149.787,'kJ/mol'), T0=(1,'K'), comment="""From training reaction 101 used for R4H_SDS;C_rad_out_2H;Cs_H_out_2H
Exact match found for rate rule [R4H_SDS;C_rad_out_2H;Cs_H_out_2H]
Euclidian distance = 0
Multiplied by reaction path degeneracy 6.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction7',
reactants = ['C=C([CH]C)C(=C)[CH]C(24182)'],
products = ['[CH2][C](C=C)C(C)=CC(24606)'],
transitionState = 'TS7',
kinetics = Arrhenius(A=(6.66e+06,'s^-1'), n=1.64, Ea=(100.416,'kJ/mol'), T0=(1,'K'), comment="""From training reaction 96 used for R5H_SS(D)MS;C_rad_out_2H;Cs_H_out_2H
Exact match found for rate rule [R5H_SS(D)MS;C_rad_out_2H;Cs_H_out_2H]
Euclidian distance = 0
Multiplied by reaction path degeneracy 6.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction8',
reactants = ['C=[C][CH]C(18176)', 'C=[C][CH]C(18176)'],
products = ['C=C([CH]C)C(=C)[CH]C(24182)'],
transitionState = 'TS8',
kinetics = Arrhenius(A=(3.73038e+06,'m^3/(mol*s)'), n=0.027223, Ea=(0,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [Y_rad;Y_rad]
Euclidian distance = 0
family: R_Recombination
Ea raised from -14.4 to 0 kJ/mol."""),
)
reaction(
label = 'reaction9',
reactants = ['C=C([CH]C)C(=C)[CH]C(24182)'],
products = ['[CH2]C(=CC)[C]1CC1C(25414)'],
transitionState = 'TS9',
kinetics = Arrhenius(A=(7.36786e+12,'s^-1'), n=-0.105173, Ea=(93.5715,'kJ/mol'), T0=(1,'K'), Tmin=(303.03,'K'), Tmax=(2000,'K'), comment="""Estimated using template [R3_D;doublebond_intra;radadd_intra_cs2H] for rate rule [R3_D;doublebond_intra_secDe_HNd;radadd_intra_cs2H]
Euclidian distance = 2.0
Multiplied by reaction path degeneracy 2.0
family: Intra_R_Add_Endocyclic"""),
)
reaction(
label = 'reaction10',
reactants = ['C=C([CH]C)C(=C)[CH]C(24182)'],
products = ['[CH2][C]1C(=CC)CC1C(25415)'],
transitionState = 'TS10',
kinetics = Arrhenius(A=(6.43734e+08,'s^-1'), n=0.926191, Ea=(130.445,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [R4_S_D;doublebond_intra;radadd_intra_cs2H]
Euclidian distance = 0
Multiplied by reaction path degeneracy 2.0
family: Intra_R_Add_Endocyclic"""),
)
reaction(
label = 'reaction11',
reactants = ['CH2(S)(23)', '[CH2]C(=C)C([CH2])=CC(25416)'],
products = ['C=C([CH]C)C(=C)[CH]C(24182)'],
transitionState = 'TS11',
kinetics = Arrhenius(A=(7.94e+13,'cm^3/(mol*s)','*|/',0.25), n=-0.324, Ea=(0,'kJ/mol'), T0=(1,'K'), comment="""From training reaction 4 used for carbene;Cd_pri
Exact match found for rate rule [carbene;Cd_pri]
Euclidian distance = 0
Multiplied by reaction path degeneracy 4.0
family: 1,2_Insertion_carbene
Ea raised from -3.9 to 0 kJ/mol."""),
)
reaction(
label = 'reaction23',
reactants = ['C=C([CH]C)C[C]=CC(24184)'],
products = ['C=C([CH]C)C(=C)[CH]C(24182)'],
transitionState = 'TS12',
kinetics = Arrhenius(A=(1.74842e+09,'s^-1'), n=1.084, Ea=(170.038,'kJ/mol'), T0=(1,'K'), comment="""Estimated using average of templates [cCsCJ;CdsJ;C] + [cCs(-HH)CJ;CJ;C] for rate rule [cCs(-HH)CJ;CdsJ;C]
Euclidian distance = 1.0
family: 1,2_shiftC"""),
)
reaction(
label = 'reaction13',
reactants = ['C=C([CH]C)C(=C)[CH]C(24182)'],
products = ['CC=C1CCC1=CC(25269)'],
transitionState = 'TS13',
kinetics = Arrhenius(A=(1.62e+12,'s^-1'), n=-0.305, Ea=(8.28432,'kJ/mol'), T0=(1,'K'), Tmin=(600,'K'), Tmax=(2000,'K'), comment="""From training reaction 2 used for R4_SSS;C_rad_out_2H;Cpri_rad_out_2H
Exact match found for rate rule [R4_SSS;C_rad_out_2H;Cpri_rad_out_2H]
Euclidian distance = 0
family: Birad_recombination"""),
)
reaction(
label = 'reaction14',
reactants = ['CH2(19)', '[CH2]C([C]=CC)=CC(25417)'],
products = ['C=C([CH]C)C(=C)[CH]C(24182)'],
transitionState = 'TS14',
kinetics = Arrhenius(A=(1.06732e+06,'m^3/(mol*s)'), n=0.472793, Ea=(0,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [Y_rad;Birad] for rate rule [Cd_rad/OneDe;Birad]
Euclidian distance = 3.0
family: Birad_R_Recombination
Ea raised from -3.5 to 0 kJ/mol."""),
)
reaction(
label = 'reaction15',
reactants = ['C=C([CH]C)C(=C)[CH]C(24182)'],
products = ['[CH2]C1([CH]C)C(=C)C1C(25296)'],
transitionState = 'TS15',
kinetics = Arrhenius(A=(6.72658e+10,'s^-1'), n=0.535608, Ea=(216.807,'kJ/mol'), T0=(1,'K'), comment="""Estimated using average of templates [R4_S_D;doublebond_intra;radadd_intra_csHNd] + [R4_S_D;doublebond_intra_HNd;radadd_intra_cs] for rate rule [R4_S_(Cd)_D;doublebond_intra_HNd;radadd_intra_csHNd]
Euclidian distance = 2.2360679775
Multiplied by reaction path degeneracy 2.0
family: Intra_R_Add_Exocyclic
Ea raised from 214.2 to 216.8 kJ/mol to match endothermicity of reaction."""),
)
reaction(
label = 'reaction16',
reactants = ['H(3)', '[CH2]C(=CC)C(=C)C=C(24604)'],
products = ['C=C([CH]C)C(=C)[CH]C(24182)'],
transitionState = 'TS16',
kinetics = Arrhenius(A=(2.31e+08,'cm^3/(mol*s)'), n=1.64, Ea=(0,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(1500,'K'), comment="""From training reaction 2544 used for Cds-HH_Cds-CdH;HJ
Exact match found for rate rule [Cds-HH_Cds-CdH;HJ]
Euclidian distance = 0
family: R_Addition_MultipleBond
Ea raised from -2.0 to 0 kJ/mol."""),
)
reaction(
label = 'reaction17',
reactants = ['[CH2]CC(=C)C([CH2])=CC(25418)'],
products = ['C=C([CH]C)C(=C)[CH]C(24182)'],
transitionState = 'TS17',
kinetics = Arrhenius(A=(1.72e+06,'s^-1'), n=1.99, Ea=(113.805,'kJ/mol'), T0=(1,'K'), comment="""From training reaction 84 used for R2H_S;C_rad_out_2H;Cs_H_out_H/Cd
Exact match found for rate rule [R2H_S;C_rad_out_2H;Cs_H_out_H/Cd]
Euclidian distance = 0
Multiplied by reaction path degeneracy 2.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction18',
reactants = ['[CH]=C(CC)C([CH2])=CC(25419)'],
products = ['C=C([CH]C)C(=C)[CH]C(24182)'],
transitionState = 'TS18',
kinetics = Arrhenius(A=(1.846e+10,'s^-1'), n=0.74, Ea=(145.185,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(1500,'K'), comment="""From training reaction 194 used for R3H_DS;Cd_rad_out_singleH;Cs_H_out_H/NonDeC
Exact match found for rate rule [R3H_DS;Cd_rad_out_singleH;Cs_H_out_H/NonDeC]
Euclidian distance = 0
Multiplied by reaction path degeneracy 2.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction19',
reactants = ['[CH2]C(=[C]C)C(=C)CC(25420)'],
products = ['C=C([CH]C)C(=C)[CH]C(24182)'],
transitionState = 'TS19',
kinetics = Arrhenius(A=(74200,'s^-1'), n=2.23, Ea=(44.3086,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R4H_DSS;Cd_rad_out_single;Cs_H_out_1H] for rate rule [R4H_DSS;Cd_rad_out_Cs;Cs_H_out_H/NonDeC]
Euclidian distance = 2.2360679775
Multiplied by reaction path degeneracy 2.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction20',
reactants = ['[CH]=C([CH]C)C(C)=CC(25421)'],
products = ['C=C([CH]C)C(=C)[CH]C(24182)'],
transitionState = 'TS20',
kinetics = Arrhenius(A=(111300,'s^-1'), n=2.23, Ea=(44.3086,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R4H_DSS;Cd_rad_out_singleH;Cs_H_out] for rate rule [R4H_DSS;Cd_rad_out_singleH;Cs_H_out_2H]
Euclidian distance = 1.0
Multiplied by reaction path degeneracy 3.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction21',
reactants = ['C=C([CH]C)C(=C)[CH]C(24182)'],
products = ['[CH2][C](C=C)C(=C)CC(24623)'],
transitionState = 'TS21',
kinetics = Arrhenius(A=(6.66e+06,'s^-1'), n=1.64, Ea=(100.416,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R5H_SS(D)MS;C_rad_out_single;Cs_H_out_2H] for rate rule [R5H_SS(D)MS;C_rad_out_H/NonDeC;Cs_H_out_2H]
Euclidian distance = 2.0
Multiplied by reaction path degeneracy 6.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction22',
reactants = ['C=C([CH]C)C(=C)[CH]C(24182)'],
products = ['C[CH][C]1CCC1=CC(25422)'],
transitionState = 'TS22',
kinetics = Arrhenius(A=(3.21867e+08,'s^-1'), n=0.926191, Ea=(130.445,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [R4_S_D;doublebond_intra;radadd_intra_cs2H]
Euclidian distance = 0
family: Intra_R_Add_Endocyclic"""),
)
reaction(
label = 'reaction23',
reactants = ['C=C([CH]C)C(=C)[CH]C(24182)'],
products = ['[CH2][C]1C(=C)C(C)C1C(25423)'],
transitionState = 'TS23',
kinetics = Arrhenius(A=(5.16207e+08,'s^-1'), n=0.911389, Ea=(125.357,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [R4_S_D;doublebond_intra;radadd_intra_csHCs]
Euclidian distance = 0
family: Intra_R_Add_Endocyclic"""),
)
reaction(
label = 'reaction24',
reactants = ['C=C([CH]C)C(=C)[CH]C(24182)'],
products = ['C=CC(=C)C(C)=CC(24616)'],
transitionState = 'TS24',
kinetics = Arrhenius(A=(1.27566e+10,'s^-1'), n=0.137, Ea=(24.9733,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R5;Y_rad;XH_Rrad] for rate rule [R5radEndo;Y_rad;XH_Rrad]
Euclidian distance = 1.0
Multiplied by reaction path degeneracy 6.0
family: Intra_Disproportionation"""),
)
reaction(
label = 'reaction24',
reactants = ['C=[C]C(C)C(=C)[CH]C(24183)'],
products = ['C=C([CH]C)C(=C)[CH]C(24182)'],
transitionState = 'TS25',
kinetics = Arrhenius(A=(8.66e+11,'s^-1'), n=0.438, Ea=(94.4747,'kJ/mol'), T0=(1,'K'), comment="""From training reaction 5 used for cCs(-HC)CJ;CdsJ;C
Exact match found for rate rule [cCs(-HC)CJ;CdsJ;C]
Euclidian distance = 0
family: 1,2_shiftC"""),
)
reaction(
label = 'reaction26',
reactants = ['C=C([CH]C)C(=C)[CH]C(24182)'],
products = ['C=C1C(=CC)CC1C(25265)'],
transitionState = 'TS26',
kinetics = Arrhenius(A=(3.24e+12,'s^-1'), n=-0.305, Ea=(8.28432,'kJ/mol'), T0=(1,'K'), Tmin=(600,'K'), Tmax=(2000,'K'), comment="""Estimated using template [R4_SSS;C_rad_out_2H;Cpri_rad_out_single] for rate rule [R4_SSS;C_rad_out_2H;Cpri_rad_out_H/NonDeC]
Euclidian distance = 2.0
Multiplied by reaction path degeneracy 2.0
family: Birad_recombination"""),
)
reaction(
label = 'reaction27',
reactants = ['CHCH3(T)(95)', '[CH2]C([C]=C)=CC(24774)'],
products = ['C=C([CH]C)C(=C)[CH]C(24182)'],
transitionState = 'TS27',
kinetics = Arrhenius(A=(1.06732e+06,'m^3/(mol*s)'), n=0.472793, Ea=(0,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [Y_rad;Birad] for rate rule [Cd_rad/OneDe;Birad]
Euclidian distance = 3.0
family: Birad_R_Recombination
Ea raised from -3.5 to 0 kJ/mol."""),
)
reaction(
label = 'reaction28',
reactants = ['[CH]=C([CH]C)C(=C)CC(25424)'],
products = ['C=C([CH]C)C(=C)[CH]C(24182)'],
transitionState = 'TS28',
kinetics = Arrhenius(A=(74200,'s^-1'), n=2.23, Ea=(44.3086,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R4H_DSS;Cd_rad_out_singleH;Cs_H_out_1H] for rate rule [R4H_DSS;Cd_rad_out_singleH;Cs_H_out_H/NonDeC]
Euclidian distance = 1.0
Multiplied by reaction path degeneracy 2.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction29',
reactants = ['C=C([CH]C)C(=C)[CH]C(24182)'],
products = ['C=CC(=C)C(=C)CC(24630)'],
transitionState = 'TS29',
kinetics = Arrhenius(A=(1.926e+10,'s^-1'), n=0.137, Ea=(8.368,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(1500,'K'), comment="""Estimated using template [R5;Y_rad_NDe;XH_Rrad] for rate rule [R5radEndo;Y_rad_NDe;XH_Rrad]
Euclidian distance = 1.0
Multiplied by reaction path degeneracy 6.0
family: Intra_Disproportionation"""),
)
reaction(
label = 'reaction30',
reactants = ['C=C([CH]C)C(=C)[CH]C(24182)'],
products = ['C=C1C(=C)C(C)C1C(25274)'],
transitionState = 'TS30',
kinetics = Arrhenius(A=(1.62e+12,'s^-1'), n=-0.305, Ea=(8.28432,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R4_SSS;C_rad_out_single;Cpri_rad_out_single] for rate rule [R4_SSS;C_rad_out_H/NonDeC;Cpri_rad_out_H/NonDeC]
Euclidian distance = 2.82842712475
family: Birad_recombination"""),
)
network(
label = '4267',
isomers = [
'C=C([CH]C)C(=C)[CH]C(24182)',
],
reactants = [
('CH3CHCCH2(18175)', 'CH3CHCCH2(18175)'),
],
bathGas = {
'N2': 0.5,
'Ne': 0.5,
},
)
pressureDependence(
label = '4267',
Tmin = (300,'K'),
Tmax = (2000,'K'),
Tcount = 8,
Tlist = ([302.47,323.145,369.86,455.987,609.649,885.262,1353.64,1896.74],'K'),
Pmin = (0.01,'bar'),
Pmax = (100,'bar'),
Pcount = 5,
Plist = ([0.0125282,0.0667467,1,14.982,79.8202],'bar'),
maximumGrainSize = (0.5,'kcal/mol'),
minimumGrainCount = 250,
method = 'modified strong collision',
interpolationModel = ('Chebyshev', 6, 4),
activeKRotor = True,
activeJRotor = True,
rmgmode = True,
)
| [
"qin.she@husky.neu.edu"
] | qin.she@husky.neu.edu |
f9b3d7f8b37f4afc692c782c12a1ff0d80cf01ad | b1a2a7910198c56bb6fe94ceaad32fb2a99dec2c | /Quiz 7.2.py | 5738c936b7e70a6417c8e8b10d8e63aa4eb1a584 | [] | no_license | rodyholland/Python-Udacity | 1cd4dd3e99cc343337915f0c663f9c914d2b03e0 | 1bc04d04bc88f5b784e5388ee403b73248a7e8e0 | refs/heads/master | 2020-04-15T00:36:12.210899 | 2019-01-05T21:29:11 | 2019-01-05T21:29:11 | 164,246,243 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,423 | py | import pandas as pd
from ggplot import *
def lineplot_compare(hr_by_team_year_sf_la_csv):
# Write a function, lineplot_compare, that will read a csv file
# called hr_by_team_year_sf_la.csv and plot it using pandas and ggplot.
#
# This csv file has three columns: yearID, HR, and teamID. The data in the
# file gives the total number of home runs hit each year by the SF Giants
# (teamID == 'SFN') and the LA Dodgers (teamID == "LAN"). Produce a
# visualization comparing the total home runs by year of the two teams.
#
# You can see the data in hr_by_team_year_sf_la_csv
# at the link below:
# https://www.dropbox.com/s/wn43cngo2wdle2b/hr_by_team_year_sf_la.csv
#
# Note that to differentiate between multiple categories on the
# same plot in ggplot, we can pass color in with the other arguments
# to aes, rather than in our geometry functions. For example,
# ggplot(data, aes(xvar, yvar, color=category_var)). This should help you
# in this exercise.
data = pd.read_csv(hr_by_team_year_sf_la_csv)
gg = ggplot(data, aes('yearID', 'HR', color='teamID')) + geom_point() + geom_line() \
+ ggtitle('Home Runs by Year') + xlab('Year') + ylab('Home Runs')
return gg
hr_by_team_year_sf_la_csv = './data/hr_by_team_year_sf_la.csv'
%matplotlib inline
lineplot_compare(hr_by_team_year_sf_la_csv)
| [
"noreply@github.com"
] | rodyholland.noreply@github.com |
91271ead575e6c8ddbb5fe997bcaef60aee8dbff | c91aecb334bf18812e29b7336a8d9d8d9799efa1 | /setup.py | 719f8b200b3ccde8e203084111980db03e31fad7 | [
"CC-BY-4.0",
"Apache-2.0"
] | permissive | Rishit-dagli/isab | 5037603bb6a3be7f7e48459eb0e1470aacef804c | 6caa92f25ccd0fdcb88ec3148a88412efa716223 | refs/heads/main | 2023-04-17T06:26:14.210341 | 2023-01-01T03:41:25 | 2023-01-01T03:41:25 | 583,542,754 | 9 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,310 | py | import os.path
from setuptools import find_packages, setup
def read(rel_path: str) -> str:
here = os.path.abspath(os.path.dirname(__file__))
# intentionally *not* adding an encoding option to open
with open(os.path.join(here, rel_path)) as fp:
return fp.read()
def get_version(rel_path: str) -> str:
for line in read(rel_path).splitlines():
if line.startswith("__version__"):
# __version__ = "0.9"
delim = '"' if '"' in line else "'"
return line.split(delim)[1]
raise RuntimeError("Unable to find version string.")
this_directory = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(this_directory, "README.md"), encoding="utf-8") as f:
long_description = f.read()
setup(
name="isab",
version=get_version("isab/version.py"),
description="An implementation of Set Transformer: A Framework for Attention-based Permutation-Invariant Neural Networks in TensorFlow",
packages=find_packages(),
long_description=long_description,
long_description_content_type="text/markdown",
classifiers=[
"Development Status :: 4 - Beta",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"License :: OSI Approved :: MIT License",
"Intended Audience :: Developers",
"Intended Audience :: Education",
"Intended Audience :: Science/Research",
"Topic :: Scientific/Engineering",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
"Topic :: Software Development",
"Topic :: Software Development :: Libraries",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Scientific/Engineering :: Mathematics",
],
url="https://github.com/Rishit-dagli/ISAB",
author="Rishit Dagli",
author_email="rishit.dagli@gmail.com",
install_requires=[
"tensorflow >= 2.5.0",
"einops ~= 0.3.0",
],
extras_require={
"dev": [
"check-manifest",
"twine",
"numpy",
"black",
"pytest",
],
},
)
| [
"rishit.dagli@gmail.com"
] | rishit.dagli@gmail.com |
5b57c80425c7a2bc8858c206e234cb38b942af96 | 2e538c87783a371a994cba27acbcb8951ed827ae | /recommender/urls.py | 4c01e49104967c1709b5d83f75f721c7cc1124ef | [] | no_license | egilabert/marketplace | 6b2c0699553885393ab1b9c6ba50a9eef0b2efb9 | 4a476e18bdda6a53d039056598bbbf3cd6d4e313 | refs/heads/master | 2020-07-05T16:31:29.491668 | 2017-07-11T08:31:30 | 2017-07-11T08:31:30 | 74,110,995 | 0 | 0 | null | 2017-07-11T08:31:31 | 2016-11-18T08:38:13 | JavaScript | UTF-8 | Python | false | false | 805 | py | from django.conf.urls import url
from django.contrib import admin
from .views import (SearchView,
HomeView,
ClientView,
ProviderView,
EmpresaDetailView,
OpportunityClientsView,
OpportunityProviderView)
urlpatterns = [
url(r'^$', HomeView, name='home'),
url(r'^search/$', SearchView, name='search'),
url(r'^clients/$', ClientView, name='clients'),
url(r'^(?P<pk>\d+)/$', EmpresaDetailView, name='detail'),
url(r'^providers/$', ProviderView, name='providers'),
url(r'^client_oportunities/$', OpportunityClientsView, name='client_opportunities'),
url(r'^provider_oportunities/$', OpportunityProviderView, name='provider_opportunities'),
] | [
"gilabert.enric@gmail.com"
] | gilabert.enric@gmail.com |
56f5127fe5a3d3278623e616dd17c1d07308518f | 61a8c6219a49a24c3691f579e4400a66207e26e7 | /Blog/migrations/0008_auto_20170709_2333.py | 15f6f73f15f40ccb9caaff6802efebb175fc46e0 | [] | no_license | oleoneto/EKLETIK-V1 | 0348499ead4a1dff509e40bcf81ddf4b6273e211 | 1720da9b3fb73a5434500529c7b76436e284897c | refs/heads/master | 2021-09-18T10:34:47.646694 | 2018-07-13T02:46:19 | 2018-07-13T02:46:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 474 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-07-09 23:33
from __future__ import unicode_literals
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('Blog', '0007_auto_20170707_1719'),
]
operations = [
migrations.AlterField(
model_name='artigo',
name='slug',
field=models.SlugField(default=uuid.uuid1, unique=True),
),
]
| [
"csneto@L13.local"
] | csneto@L13.local |
fb09bbf045dde145556337fcce8727a7953af5f7 | bd5803e5f12a35dd6783c3bb6b8314b0f094baf6 | /profiles/migrations/0001_initial.py | 8014d655afea5e749f1ea528486d082ef631c26f | [] | no_license | Farrrukh/Django-Bootcamp | c56503631c05193aacd54456d5e5f5ec28b2daf0 | 59491cd778563fad4ac0ecb8270d4a225ab73dcc | refs/heads/main | 2023-03-18T17:19:51.063074 | 2021-02-27T05:42:04 | 2021-02-27T05:42:04 | 342,779,375 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 498 | py | # Generated by Django 3.1.6 on 2021-02-13 20:10
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Profiles',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('content', models.TextField()),
],
),
]
| [
"farrukhkhan30@hotmail.com"
] | farrukhkhan30@hotmail.com |
a7c12c0c81879fc2ae0d9f7d163beeef16b99619 | 4b70a23e74a332c54e70fe33c9b0fe79bb328d85 | /WGB/tests.py | 150266ac3a772eb5520f7750260a12777f21311c | [] | no_license | tevawolf/wgb | 3b095897cbdc9b71c4b233f6b755f65f2693d582 | f30be8575b03f24bf797b305e34b7fda866fa0c0 | refs/heads/master | 2022-12-10T23:18:04.175394 | 2021-01-29T06:40:01 | 2021-01-29T06:40:01 | 159,421,804 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 400 | py | from django.test import TestCase
from . import models
class UserAccountTests(TestCase):
def test_blank_icon(self):
account = models.UserAccount()
account.username = 'test'
account.password = 'test'
account.nickname = 'test'
account.save()
saved = models.UserAccount.objects.get(username='test')
self.assertEqual(saved.username, 'test')
| [
"tevawolf@yahoo.co.jp"
] | tevawolf@yahoo.co.jp |
700fa75fb3bd427c2ace99115edf7c741cc1a10c | 9449368b4a4100f1ef6dd0f4a845faad6f1161a4 | /models/Qaw_reactnet_18_bf.py | 658a6b782cca02444f3726bafd5009b17e234335 | [
"MIT"
] | permissive | TrendingTechnology/BNN_NoBN | b6a770fb176a9881d22ccea20381084b4abc0bcc | d2777845d04449cabfcfc5ce72738e1e6287f633 | refs/heads/main | 2023-06-17T13:38:26.296326 | 2021-04-21T22:28:49 | 2021-04-21T22:28:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,526 | py | '''
React-birealnet-18(modified from resnet)
BN setting: remove all BatchNorm layers
Conv setting: replace conv2d with ScaledstdConv2d (add alpha beta each blocks)
Binary setting: only activation are binarized
'''
import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import torch.nn.functional as F
from layers import *
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return ScaledStdConv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
def conv1x1(in_planes, out_planes, stride=1):
"""1x1 convolution"""
return ScaledStdConv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
def binaryconv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return HardBinaryScaledStdConv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1)
def binaryconv1x1(in_planes, out_planes, stride=1):
"""1x1 convolution"""
return HardBinaryScaledStdConv2d(in_planes, out_planes, kernel_size=1, stride=stride, padding=0)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, alpha, beta, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.alpha = alpha
self.beta = beta
self.move0 = LearnableBias(inplanes)
self.binary_activation = BinaryActivation()
self.binary_conv = binaryconv3x3(inplanes, planes, stride=stride)
self.move1 = LearnableBias(planes)
self.prelu = nn.PReLU(planes)
self.move2 = LearnableBias(planes)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
x_in = x*self.beta
out = self.move0(x_in)
out = self.binary_activation(out)
out = self.binary_conv(out)
if self.downsample is not None:
residual = self.downsample(x_in)
out = out*self.alpha + residual
out = self.move1(out)
out = self.prelu(out)
out = self.move2(out)
return out
class BiRealNet(nn.Module):
def __init__(self, block, layers, imagenet=True, alpha=0.2, num_classes=1000):
super(BiRealNet, self).__init__()
self.inplanes = 64
if imagenet:
self.conv1 = ScaledStdConv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
else:
self.conv1 = ScaledStdConv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.maxpool = nn.Identity()
expected_var = 1.0
self.layer1, expected_var = self._make_layer(block, 64, layers[0], alpha, expected_var)
self.layer2, expected_var = self._make_layer(block, 128, layers[1], alpha, expected_var, stride=2)
self.layer3, expected_var = self._make_layer(block, 256, layers[2], alpha, expected_var, stride=2)
self.layer4, expected_var = self._make_layer(block, 512, layers[3], alpha, expected_var, stride=2)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(512 * block.expansion, num_classes)
def _make_layer(self, block, planes, blocks, alpha, expected_var, stride=1):
beta = 1. / expected_var ** 0.5
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.AvgPool2d(kernel_size=2, stride=stride),
binaryconv1x1(self.inplanes, planes * block.expansion)
)
# Reset expected var at a transition block
expected_var = 1.0
layers = []
layers.append(block(self.inplanes, planes, alpha, beta, stride, downsample))
self.inplanes = planes * block.expansion
for _ in range(1, blocks):
beta = 1. / expected_var ** 0.5
layers.append(block(self.inplanes, planes, alpha, beta))
expected_var += alpha ** 2
return nn.Sequential(*layers), expected_var
def forward(self, x):
x = self.conv1(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
def birealnet18(pretrained=False, **kwargs):
"""Constructs a BiRealNet-18 model. """
model = BiRealNet(BasicBlock, [4, 4, 4, 4], **kwargs)
return model
| [
"wiwjp619@gmail.com"
] | wiwjp619@gmail.com |
566d9229e5df35820ffbd6103a0ba793ed993eae | c38fdf616d465b80f21b6f407476a1e849f4598e | /steven/python/personal_workshop/containers/dictionary.py | 956c036c455e26f9a03f2f89d709d64a30168bf9 | [] | no_license | crazyguy106/cfclinux | fd3b910302dbeaa940284e4a54ccb8514d15920a | a5748dff5f34254f5780daa87619037b357aa59b | refs/heads/main | 2023-07-31T20:14:07.276695 | 2021-09-24T15:40:07 | 2021-09-24T15:40:07 | 399,391,445 | 0 | 0 | null | 2021-08-30T05:39:38 | 2021-08-24T08:31:31 | Shell | UTF-8 | Python | false | false | 393 | py | #!/usr/bin/python3
dictionary = {'my_string': 'Steven Chia', 50: 'I am number fifty'}
# Get data
var = dictionary['my_string']
print(var)
# Update data
dictionary['my_string'] = 'I have been changed'
print(dictionary)
# Delete data (pop)
dictionary.pop('my_string')
print('After deleting', dictionary)
# add data
# Questions
value_from_50 = dictionary['50']
print('test', value_from_50)
| [
"stevenchia56@gmail.com"
] | stevenchia56@gmail.com |
4d4dfa1fce2d0ec301b8527dca38e03ba0e4b365 | e371a21cc31c0616da346e386fea411f39dd0f7b | /LAB04/02-CloudAlbum-Chalice/cloudalbum/chalicelib/config.py | 525345eb14cc26298fa3b523b0b550141477e306 | [
"MIT"
] | permissive | aws-kr-tnc/moving-to-serverless-renew | c0152763de822cea64a862cd395f4f940d2e4e03 | 312248c689a19ea9b589025c82f880593fc70f82 | refs/heads/master | 2023-03-21T19:59:23.717295 | 2022-03-12T15:38:59 | 2022-03-12T15:38:59 | 199,081,822 | 6 | 4 | MIT | 2023-03-07T10:02:25 | 2019-07-26T21:26:02 | Python | UTF-8 | Python | false | false | 1,530 | py | """
cloudalbum/chalicelib/cognito.py
~~~~~~~~~~~~~~~~~~~~~~~
Configurations for application.
:description: CloudAlbum is a fully featured sample application for 'Moving to AWS serverless' training course
:copyright: © 2019 written by Dayoungle Jun, Sungshik Jou.
:license: MIT, see LICENSE for more details.
"""
import boto3
from chalice import CORSConfig
from aws_parameter_store import AwsParameterStore
def get_param_path(param_path):
"""
Retrieve all key:values in the Parameter Store.
:param param_path:
:return:
"""
region = boto3.session.Session().region_name
store = AwsParameterStore(region)
return store.get_parameters_dict(param_path)
# store configuration values for Cloudalbum
conf = get_param_path('/cloudalbum/')
def get_param(param_name):
"""
This function reads a secure parameter from AWS' SSM service.
The request must be passed a valid parameter name, as well as
temporary credentials which can be used to access the parameter.
The parameter's value is returned.
"""
# Create the SSM Client
ssm = boto3.client('ssm')
# Get the requested parameter
response = ssm.get_parameters(
Names=[param_name, ], WithDecryption=True
)
# Store the credentials in a variable
result = response['Parameters'][0]['Value']
return result
cors_config = CORSConfig(
allow_origin='*',
allow_headers=['*'],
max_age=600,
expose_headers=['X-Special-Header'],
allow_credentials=True
)
| [
"liks79@gmail.com"
] | liks79@gmail.com |
f8a37192cc9531db7d44401ceba6f80cc0088655 | 5bd9bcbeef293e95b8d404e2ff6c6883e74ea75e | /general_tools/__init__.py | 93a094701ed594231b0ac14de87e5463b3f33081 | [] | no_license | yayatab/physics_python_tools | bade02fa8de62d80da8e253c06ac11488404848a | 6cb52aa730e3516247e7f96b23257ca4bb5e8b9f | refs/heads/master | 2020-04-19T09:57:43.334790 | 2019-06-10T06:57:48 | 2019-06-10T06:57:48 | 168,125,619 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 239 | py | from general_tools.convertions import *
from general_tools.general_math import *
from general_tools.histogram import *
# from general_tools.lab import *
from general_tools.statistics.statistics import *
from general_tools.vectors import *
| [
"taboch.yair@gmail.com"
] | taboch.yair@gmail.com |
d05fea8f51d2ceb6bb397c133a35c1c2656f42c6 | 212696828a60c0d633d4d720d32de84002cbc238 | /Controller/CRUD_Controller/CrudController.py | 91f137259afe29f286964bd3ade55477f15c80e6 | [] | no_license | ankitbasarkar/CS297-Console-Application | 15874a7229b07eea173ce332eb2230ca9f215a54 | 0536e77c2d582d1228d3deeadfde61f90bf90c40 | refs/heads/master | 2021-01-18T22:16:30.694786 | 2016-11-29T05:35:38 | 2016-11-29T05:35:38 | 72,370,321 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,271 | py | import time
import sys
from View.CRUDAnalysisSpecView import CRUDAnalysisSpecView
class CRUDController:
def __init__(self):
self.renderCRUDOptions()
self.getCRUDViewOptions()
def renderCRUDOptions(self):
CRUDView = CRUDAnalysisSpecView()
CRUDView.renderView()
def getCRUDViewOptions(self):
Selection = raw_input("Please select a number/letter corresponding to the desired action.\n")
self.handleCRUDViewOptions(Selection)
def handleCRUDViewOptions(self,Selection):
if (Selection == 'q' or Selection == 'Q'):
print "Exiting System"
from ProcessPkg.RunningAnalysisProcesses import RunningAnalysisProcesses
RunningAnalysisProcesses.terminateAll()
time.sleep(3)
sys.exit()
if (Selection == 'b' or Selection == 'B'):
from Controller.Landing_Controller.LandingController import LandingController
LandingControllerObj = LandingController()
if (Selection == '1'):
from Controller.CRUD_Controller.CreateSpecController import CreateSpecController
createSpecController = CreateSpecController()
else:
self.renderCRUDOptions()
self.getCRUDViewOptions() | [
"ankit.basarkar@gmail.com"
] | ankit.basarkar@gmail.com |
95c60f0c1f2feba7d1b4731c4a3380a16d56e159 | 7bcb5328193d0f05a4eaec8dce2248ac1c5e1c79 | /weighter/aggregate_results.py | 4a67e637e683f8bc2a0d75812581ee2bb238eaf7 | [] | no_license | olantwin/muon_shield_optimisation | 904eedacda73ff60f2bdc7873c023a6f89679bdb | 7a2a97802f6b4811169f6e286bf1cfc14057aed4 | refs/heads/disneyland | 2021-09-08T07:18:06.608722 | 2018-03-08T10:21:45 | 2018-03-08T10:22:06 | 82,297,983 | 3 | 5 | null | 2018-03-03T21:33:06 | 2017-02-17T13:03:27 | Python | UTF-8 | Python | false | false | 1,904 | py | import numpy as np
import re
import os
import argparse
from utils import loss
def get_xs_path(tag, id):
return os.path.join("/input", "xs_" + tag + str(id) + '.npy')
def get_indeces_path(tag, id):
return os.path.join("/input", "index_" + tag + str(id) + '.npy')
def get_number(filename):
return re.findall(r'\d+', filename)[0]
def load_previous_cumulative_arrays():
cum_loss = np.load("/input/cumloss.npy")
cum_indeces = np.load("/input/cumindeces.npy")
return cum_loss, cum_indeces
def load_previous_results(tag):
'''
This function should load all the previous results from eos and calculate the mean over each muon.
'''
prev_results = []
prev_indeces = []
files = os.listdir("/input")
for filename in files:
if "xs_" + tag in filename:
number = get_number(filename)
xs = np.load(get_xs_path(tag, number))
prev_results.append(loss(np.array(xs)))
indeces = np.load(get_indeces_path(tag, number))
prev_indeces.append(indeces)
return prev_results, prev_indeces
def calculate_cuminfo(muon_loss, muon_indeces, old_cumloss, old_cumindeces):
'''
Function accumulates new results.
'''
for i in range(len(muon_loss)):
old_cumloss[muon_indeces[i]] += muon_loss[i]
old_cumindeces[muon_indeces[i]] += 1
return old_cumloss, old_cumindeces
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'--tag',
default='')
args = parser.parse_args()
cum_loss, cum_indeces = load_previous_cumulative_arrays()
prev_loss, prev_indeces = load_previous_results(args.tag)
cum_loss, cum_indeces = calculate_cuminfo(prev_loss, prev_indeces, cum_loss, cum_indeces)
np.save("/output/cumloss.npy", cum_loss)
np.save("/output/cumindeces.npy", cum_indeces)
if __name__ == "__main__":
main()
| [
"oliver@lantwin.de"
] | oliver@lantwin.de |
50b6541a87ce1981e8124b7c49f7a80e0dd3e1d1 | 90d48bd593d755ead347ef1c35efa032246ec301 | /app/main/forms.py | ad18abdd8acaf9316c0752c443f4e2386a4e3eef | [] | no_license | TarEnethil/trivia | f95aac8a5599cf1d1e8c5e3bc8621d9a3a06fe24 | 6118633f66564ab63ff8fcb219dfe20fa40f0d72 | refs/heads/master | 2023-08-02T18:36:31.201369 | 2023-06-24T13:49:25 | 2023-06-24T13:49:25 | 142,294,955 | 0 | 1 | null | 2023-07-25T21:29:28 | 2018-07-25T12:11:13 | Python | UTF-8 | Python | false | false | 983 | py | from app import db
from flask_login import current_user
from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, PasswordField, BooleanField, SubmitField, SelectMultipleField, BooleanField
from wtforms.validators import DataRequired, Length, EqualTo
class LoginForm(FlaskForm):
username = StringField("Username", validators=[DataRequired()])
password = PasswordField("Password", validators=[DataRequired()])
remember_me = BooleanField("Member me?")
submit = SubmitField("Sign in ")
class SettingsForm(FlaskForm):
title = StringField("Title", validators=[Length(max=64)])
submit = SubmitField("Submit")
class InstallForm(FlaskForm):
admin_name = StringField("Admin username", validators=[DataRequired()])
admin_password = PasswordField("Password", validators=[DataRequired(), EqualTo("admin_password2")])
admin_password2 = PasswordField("Password again", validators=[DataRequired()])
submit = SubmitField("Submit")
| [
"thorbenroemer@t-online.de"
] | thorbenroemer@t-online.de |
fe02328eeb7bc12489a814ca22c9097a2349e9af | 25ce3a4d8156f417a9bf3dfcef3888e8a0ce12c1 | /yourenv/bin/easy_install | efb81ccc74b0753f20ae7072a5b62924b25eccac | [] | no_license | prajvalgupta/PickupSports_Project | 6e0b544ece7a1f7ee1fb28adc0eeddf71982c3c7 | eec874848f0c840018d59553122e78ea7fa8794c | refs/heads/master | 2020-06-30T05:19:06.408909 | 2019-08-05T18:58:23 | 2019-08-05T18:58:23 | 200,734,693 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 271 | #!/Users/prajvalgupta/apad_project/yourenv/bin/python3.7
# -*- coding: utf-8 -*-
import re
import sys
from setuptools.command.easy_install import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())
| [
"prajvalgupta@utexas.edu"
] | prajvalgupta@utexas.edu | |
eba0648acc9316ce39061499fa08bb07bd36bf3e | 55c250525bd7198ac905b1f2f86d16a44f73e03a | /Python/Scripts/pyinstaller/PyInstaller/hooks/hook-PyQt5.QtQuickWidgets.py | 5bfdb0b29bff0c35d055c5b3a918351177aeea00 | [] | no_license | NateWeiler/Resources | 213d18ba86f7cc9d845741b8571b9e2c2c6be916 | bd4a8a82a3e83a381c97d19e5df42cbababfc66c | refs/heads/master | 2023-09-03T17:50:31.937137 | 2023-08-28T23:50:57 | 2023-08-28T23:50:57 | 267,368,545 | 2 | 1 | null | 2022-09-08T15:20:18 | 2020-05-27T16:18:17 | null | UTF-8 | Python | false | false | 129 | py | version https://git-lfs.github.com/spec/v1
oid sha256:46db77cbf463b412fb237dd8420a2e12c39b4b5c5fd0cc8d34382ca45cfc9ae0
size 1992
| [
"nateweiler84@gmail.com"
] | nateweiler84@gmail.com |
fa1decabdc9cfeaae56d5aa526045977eb82c6ac | 27b39add06235b1c32ea792186ed4d576cbe5dc0 | /ski_resort/migrations/0004_auto_20210428_1631.py | 97a00359e28f0d289852c6b30879669af3729a76 | [] | no_license | StefSmlk/rest_center | ddc5bd92664cadd281b0df0b4040607ef1bda0c1 | 93a1d2c71343d697e80442f673995d6a708018d2 | refs/heads/main | 2023-04-26T15:53:28.444508 | 2021-05-25T14:05:53 | 2021-05-25T14:05:53 | 360,866,985 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 400 | py | # Generated by Django 3.1.7 on 2021-04-28 13:31
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ski_resort', '0003_auto_20210428_1630'),
]
operations = [
migrations.AlterModelOptions(
name='choices',
options={'verbose_name': 'размер', 'verbose_name_plural': 'размеры'},
),
]
| [
"gsstteeff7777@gmail.com"
] | gsstteeff7777@gmail.com |
43660d881616d308e9b8c0860549c6bf81f808e5 | ab3d361d784ee2bf066802f9942371625f6b5b6d | /untitled/venv/Scripts/easy_install-script.py | acdcc9176bab9448fd3d4efdac30187d1eb5d519 | [] | no_license | patricia8229/Dictionery | 9b74cdc990604007ead8952bd4ce390749ba679b | 8e5ec7a1510f6b53bd2ab0273d8f84a3e0d8a180 | refs/heads/master | 2020-08-17T04:22:03.811513 | 2019-10-25T18:00:57 | 2019-10-25T18:00:57 | 215,606,877 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 448 | py | #!C:\Users\HP\PycharmProjects\untitled\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==39.1.0','console_scripts','easy_install'
__requires__ = 'setuptools==39.1.0'
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('setuptools==39.1.0', 'console_scripts', 'easy_install')()
)
| [
"patricia.kibunja@gmail.com"
] | patricia.kibunja@gmail.com |
87c8c170ef802ad2829ca7d65d50f6db98b5fe4f | 67205c9dc9c806fc83615cdfa92239270c2a2f35 | /dialog_duzelt_dograma.py | 2d3c7fe7989f7a78ff8cb369317407b224b84699 | [] | no_license | gsimin/mtrakv2 | e73e594ca2fcde2d417fb25557a2ccf136f6c60b | 79bdf0a55ab206b973fa1fae0a30fa78f9e74165 | refs/heads/master | 2020-06-07T14:45:04.337061 | 2019-06-21T06:30:09 | 2019-06-21T06:30:09 | 193,043,316 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,864 | py | import sys
from PyQt5.QtWidgets import *
from dialog_mesaj import uyari_ver, dograma_veri_kontrol
# Seçilen doğramada düzeltme yapmayı sağlayan arayüz
class DialogDuzeltDograma(QDialog):
def __init__(self, tip, depo):
"""
Input:
tip: (str) Doğrama tipi
"""
super().__init__()
self.tip = tip
self.baslik = f"{self.tip} Düzelt"
self.depo = depo
self.gecici = {}
self.init_ui()
def init_ui(self):
#etiket oluştur (QLabel)
etiket_dograma = QLabel(f"{self.tip}")
etiket_ozellik = QLabel("Özellikleri :")
etiket_ad = QLabel(f"{self.tip} Adı")
etiket_malzeme = QLabel("Malzemesi")
etiket_en = QLabel("Eni (m)")
etiket_boy = QLabel("Boyu (m)")
etiket_bosluk = QLabel(" ")
# veri giriş alanlarını oluştur (QLineEdit - QCombobox)
self.giris_dograma = QComboBox()
self.giris_ad = QLineEdit()
self.giris_malzeme = QLineEdit()
self.giris_en = QLineEdit()
self.giris_boy = QLineEdit()
# buton oluştur (QPushButton)
buton_sec = QPushButton("Seç")
buton_kapat = QPushButton("Kapat")
buton_duzelt = QPushButton("Düzelt")
# layout oluştur
layout_veri = QGridLayout()
layout_buton = QHBoxLayout()
self.layout = QVBoxLayout()
# widget ekle
layout_veri.addWidget(etiket_dograma, 0, 0)
layout_veri.addWidget(self.giris_dograma, 0, 1)
layout_veri.addWidget(buton_sec, 0, 2)
layout_veri.addWidget(etiket_bosluk, 1, 0)
layout_veri.addWidget(etiket_ozellik, 2, 0)
layout_veri.addWidget(etiket_ad, 3, 0)
layout_veri.addWidget(self.giris_ad, 3, 1)
layout_veri.addWidget(etiket_malzeme, 4, 0)
layout_veri.addWidget(self.giris_malzeme, 4, 1)
layout_veri.addWidget(etiket_en, 3, 2)
layout_veri.addWidget(self.giris_en, 3, 3)
layout_veri.addWidget(etiket_boy, 4, 2)
layout_veri.addWidget(self.giris_boy, 4, 3)
layout_buton.addWidget(buton_duzelt)
layout_buton.addWidget(buton_kapat)
self.layout.addLayout(layout_veri)
self.layout.addLayout(layout_buton)
# doğrama seçeneklerinin oluşturulması
self.giris_dograma.addItems(self.depo.dograma_listesi[self.tip].keys())
# buton fonksiyonları
buton_kapat.clicked.connect(self.close)
buton_sec.clicked.connect(self.sec)
buton_duzelt.clicked.connect(self.duzelt)
# pencere ayarları
self.setWindowTitle(self.baslik)
self.setLayout(self.layout)
# seçilen doğramanın verilerini aktarır
def sec(self):
secim = self.giris_dograma.currentText()
self.gecici = self.depo.dograma_verilerini_dondur(secim, self.tip)
self.giris_ad.setText(self.gecici["Ad"])
self.giris_malzeme.setText(self.gecici["Malzeme"])
self.giris_en.setText(str(self.gecici["En"]))
self.giris_boy.setText(str(self.gecici["Boy"]))
# seçilen dograma verilerini duzeltir
def duzelt(self):
yeni_ad = self.giris_ad.text()
yeni_malzeme = self.giris_malzeme.text()
yeni_en = self.giris_en.text()
yeni_boy = self.giris_boy.text()
duzeltilsin = dograma_veri_kontrol(yeni_ad, yeni_malzeme, yeni_en, yeni_boy)
if duzeltilsin:
islem = False
if self.giris_dograma.findText(yeni_ad) == 1 and yeni_ad != self.gecici["Ad"]:
uyari_ver(f"{yeni_ad} mevcut")
else:
if self.giris_dograma.findText(yeni_ad) == -1:
self.depo.duzelt_dograma(self.tip, self.gecici["Ad"], "Ad", yeni_ad)
self.giris_dograma.clear()
self.giris_dograma.addItems(self.depo.dograma_listesi[self.tip].keys())
islem = True
if self.gecici["Malzeme"] != yeni_malzeme:
self.depo.duzelt_dograma(self.tip, yeni_ad, "Malzeme", yeni_malzeme)
islem = True
if str(self.gecici["En"]) != yeni_en:
self.depo.duzelt_dograma(self.tip, yeni_ad, "En", yeni_en)
islem = True
if str(self.gecici["Boy"]) != yeni_boy:
self.depo.duzelt_dograma(self.tip, yeni_ad, "Boy", yeni_boy)
islem = True
if islem:
self.temizle()
def temizle(self):
self.giris_ad.clear()
self.giris_malzeme.clear()
self.giris_en.clear()
self.giris_boy.clear()
# test için
def main():
app = QApplication(sys.argv)
dialog = DialogDuzeltDograma("Pencere")
dialog.show()
dialog.raise_()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
| [
"simingurdal@gmail.com"
] | simingurdal@gmail.com |
2f38fcb8e531ceded0274df3d91c710c99137c53 | 7ed033f04bfc94b60292a0eb11de8d0e1f762873 | /src/deep_dialog/agents/agent_baselines.py | fcda9ccc5f7aa77b7e9de45ae53022bf188429da | [
"MIT"
] | permissive | tanayz/TC-Bot-py3 | 70ef42039d52fd52c2533c87d0b11229f60e24d6 | 048aca2fe58ced780baa0b24390cb44ce5ef6850 | refs/heads/master | 2022-07-29T23:31:23.938555 | 2020-05-26T15:27:19 | 2020-05-26T15:27:19 | 266,559,884 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 6,408 | py | """
Created on May 25, 2016
@author: xiul, t-zalipt
"""
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))
import copy, random
from deep_dialog import dialog_config
from deep_dialog.agents.agent import Agent
class InformAgent(Agent):
""" A simple agent to test the system. This agent should simply inform all the slots and then issue: taskcomplete. """
def initialize_episode(self):
self.state = {}
self.state['diaact'] = ''
self.state['inform_slots'] = {}
self.state['request_slots'] = {}
self.state['turn'] = -1
self.current_slot_id = 0
def state_to_action(self, state):
""" Run current policy on state and produce an action """
self.state['turn'] += 2
if self.current_slot_id < len(self.slot_set.keys()):
slot = self.slot_set.keys()[self.current_slot_id]
self.current_slot_id += 1
act_slot_response = {}
act_slot_response['diaact'] = "inform"
act_slot_response['inform_slots'] = {slot: "PLACEHOLDER"}
act_slot_response['request_slots'] = {}
act_slot_response['turn'] = self.state['turn']
else:
act_slot_response = {'diaact': "thanks", 'inform_slots': {}, 'request_slots': {}, 'turn': self.state['turn']}
return {'act_slot_response': act_slot_response, 'act_slot_value_response': None}
class RequestAllAgent(Agent):
""" A simple agent to test the system. This agent should simply request all the slots and then issue: thanks(). """
def initialize_episode(self):
self.state = {}
self.state['diaact'] = ''
self.state['inform_slots'] = {}
self.state['request_slots'] = {}
self.state['turn'] = -1
self.current_slot_id = 0
def state_to_action(self, state):
""" Run current policy on state and produce an action """
self.state['turn'] += 2
if self.current_slot_id < len(dialog_config.sys_request_slots):
slot = dialog_config.sys_request_slots[self.current_slot_id]
self.current_slot_id += 1
act_slot_response = {}
act_slot_response['diaact'] = "request"
act_slot_response['inform_slots'] = {}
act_slot_response['request_slots'] = {slot: "PLACEHOLDER"}
act_slot_response['turn'] = self.state['turn']
else:
act_slot_response = {'diaact': "thanks", 'inform_slots': {}, 'request_slots': {}, 'turn': self.state['turn']}
return {'act_slot_response': act_slot_response, 'act_slot_value_response': None}
class RandomAgent(Agent):
""" A simple agent to test the interface. This agent should choose actions randomly. """
def initialize_episode(self):
self.state = {}
self.state['diaact'] = ''
self.state['inform_slots'] = {}
self.state['request_slots'] = {}
self.state['turn'] = -1
def state_to_action(self, state):
""" Run current policy on state and produce an action """
self.state['turn'] += 2
act_slot_response = copy.deepcopy(random.choice(dialog_config.feasible_actions))
act_slot_response['turn'] = self.state['turn']
return {'act_slot_response': act_slot_response, 'act_slot_value_response': None}
class EchoAgent(Agent):
""" A simple agent that informs all requested slots, then issues inform(taskcomplete) when the user stops making requests. """
def initialize_episode(self):
self.state = {}
self.state['diaact'] = ''
self.state['inform_slots'] = {}
self.state['request_slots'] = {}
self.state['turn'] = -1
def state_to_action(self, state):
""" Run current policy on state and produce an action """
user_action = state['user_action']
self.state['turn'] += 2
act_slot_response = {}
act_slot_response['inform_slots'] = {}
act_slot_response['request_slots'] = {}
########################################################################
# find out if the user is requesting anything
# if so, inform it
########################################################################
if user_action['diaact'] == 'request':
requested_slot = user_action['request_slots'].keys()[0]
act_slot_response['diaact'] = "inform"
act_slot_response['inform_slots'][requested_slot] = "PLACEHOLDER"
else:
act_slot_response['diaact'] = "thanks"
act_slot_response['turn'] = self.state['turn']
return {'act_slot_response': act_slot_response, 'act_slot_value_response': None}
class RequestBasicsAgent(Agent):
""" A simple agent to test the system. This agent should simply request all the basic slots and then issue: thanks(). """
def initialize_episode(self):
self.state = {}
self.state['diaact'] = 'UNK'
self.state['inform_slots'] = {}
self.state['request_slots'] = {}
self.state['turn'] = -1
self.current_slot_id = 0
self.request_set = ['moviename', 'starttime', 'city', 'date', 'theater', 'numberofpeople']
self.phase = 0
def state_to_action(self, state):
""" Run current policy on state and produce an action """
self.state['turn'] += 2
if self.current_slot_id < len(self.request_set):
slot = self.request_set[self.current_slot_id]
self.current_slot_id += 1
act_slot_response = {}
act_slot_response['diaact'] = "request"
act_slot_response['inform_slots'] = {}
act_slot_response['request_slots'] = {slot: "UNK"}
act_slot_response['turn'] = self.state['turn']
elif self.phase == 0:
act_slot_response = {'diaact': "inform", 'inform_slots': {'taskcomplete': "PLACEHOLDER"}, 'request_slots': {}, 'turn':self.state['turn']}
self.phase += 1
elif self.phase == 1:
act_slot_response = {'diaact': "thanks", 'inform_slots': {}, 'request_slots': {}, 'turn': self.state['turn']}
else:
raise Exception("THIS SHOULD NOT BE POSSIBLE (AGENT CALLED IN UNANTICIPATED WAY)")
return {'act_slot_response': act_slot_response, 'act_slot_value_response': None}
| [
"zmiao@mail.ustc.edu.cn"
] | zmiao@mail.ustc.edu.cn |
acf8780a7e3c34f862cb116e10f719a9e4a6f1f7 | 3ace5e6ab1bf36dceeef2a5362a04d1e39f2c680 | /DjangoSintactico/DjangoSintactico/urls.py | 69ac0875e5f3ea5f4232e1caf3826b3c49d08f7e | [] | no_license | Yesker/SegundoParcial | 256eed72c3e0af8876ff276987a3748a02f20144 | 41dbb7cf4d6f951da83dd91e616d7d92aa6dc292 | refs/heads/main | 2023-01-30T23:30:43.926017 | 2020-12-17T21:11:59 | 2020-12-17T21:11:59 | 322,413,773 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,170 | py | """DjangoSintactico URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from MiAppSintactico import views
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.home , name = 'home'),
path('cancer/',views.cancer , name = 'cancer'),
path('sintomas/',views.sintomas , name = 'sintomas'),
path('prevenir/',views.prevenir , name = 'prevenir'),
path('contacto/',views.contacto , name = 'contacto'),
path('tabla/', views.VistaTabla, name = 'Procesa'),
path('grafo/',views.grafo, name ='grafo1'),
]
| [
"52689644+Yesker@users.noreply.github.com"
] | 52689644+Yesker@users.noreply.github.com |
1dcf4dd502ff5b8c72cdbeb598b1de71aedd20de | 3320c0e111cd6dbbbbd1d9a30b485d17c39276cb | /funusecmd.py | 28db40310cc6ca405f3c8b0d5d857c4f68ddbdf7 | [] | no_license | INeedHealingWQ/funuse | 9a2219102b4999202a1a985207b60e65f9c0347e | 25e776d4a419d1de368b78e03fc1b2cd5b5f1731 | refs/heads/master | 2020-12-06T18:26:21.083411 | 2020-03-06T01:27:01 | 2020-03-06T01:27:01 | 232,525,583 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,537 | py | import sys
import os
from pathlib import Path
import getopt
from gvars import *
from parameterobj import *
import copy
class CmdParseObj:
def __init__(self, argv):
self.__argv = argv[1:]
self.__parameter_obj = ParameterObj()
self.help_message = r'''
Usage: funuse <option(s)> <path>
All the following switches must be given:
-t, --dumptool=<path> Gnu binutil objdump tool path, this should be a system-wide path.
-x, --executable=<path> The executable file path, this should be a system-wide path.
-d, --directory=<path> Count definitions under the directory.
The following switches are optional:
-m, --module Count only a single module, then the -d option should followed by module path.
-s, --simple Brief output, only the top-level directories.
-q, --quick Quick mode, not write data to disk, this will use more memory.
-v, --variable Count the global variables which are not used.
-f, --function Count the function definition which are not used.
-h, --help Show help
'''
def elf_check(self):
pass
def start_parse(self):
options_args, left_arguments = self.parse_opt(self.__argv)
for o, a in options_args:
if o in ['-t', '--dumptool']:
self.__parameter_obj.objdump_tool = a
elif o in ['-x', ['-executable']]:
exe_str = os.path.abspath(os.path.expanduser(a))
exe = Path(exe_str)
if exe.is_file() is False or exe.suffix != '.exe':
print('%s should be an ELF-executable')
self.usage()
sys.exit()
self.__parameter_obj.executable = exe
elif o in ['-d', ['--directory']]:
path_str = os.path.abspath(os.path.expanduser(a))
path = Path(path_str)
if path.is_dir() is False:
print('%s is not a directory.' % a)
self.usage()
sys.exit(0)
# Transfer to absolute directory for further processing.
self.__parameter_obj.directory = path
elif o in ['-s', ['--simple']]:
self.__parameter_obj.output_simple = True
elif o in ['-v', '--variable']:
self.__parameter_obj.count_variable = True
self.__parameter_obj.count_function = False
elif o in ['-f', '--function']:
self.__parameter_obj.count_function = True
self.__parameter_obj.count_variable = False
elif o in ['-m', '--module']:
self.__parameter_obj.count_module = True
elif o in ['-h', '--help']:
self.usage()
sys.exit(0)
elif o in ['-q', '--quick']:
self.__parameter_obj.quick_mode = True
else:
assert False, 'unrecognized option\n'
if self.__parameter_obj.update() is False:
self.usage()
sys.exit()
return copy.deepcopy(self.__parameter_obj)
def usage(self):
print(self.help_message)
def parse_opt(self, arg_list):
try:
opts_args, left_args = getopt.getopt(arg_list, g_short_options, g_long_options)
except getopt.GetoptError as err:
print(err)
self.usage()
sys.exit(2)
return opts_args, left_args
| [
"qiangwang@nettech-global.com"
] | qiangwang@nettech-global.com |
a3f2478c50b69e79db6f319da77c3bf63634a403 | 1791cbad7764758651d1d1770955482d477d842d | /src/magnets/consts.py | f8fd5898ba2a3702af9e56d042f14f8d8b696686 | [] | no_license | maor10/magnets-server | d05539b1fb2e66d0e2ad80e0f818792bea91cdd5 | 8ba3975704af4943b731bc73e596a008712ff1fe | refs/heads/master | 2022-04-16T04:08:48.548899 | 2020-04-15T09:39:38 | 2020-04-15T09:39:38 | 254,864,909 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 101 | py | import os
UPLOAD_FOLDER = "C:\\Temp\\magnets\\photos" if os.name == 'nt' else '/etc/magnets/photos'
| [
"kern@adaptive-shield.com"
] | kern@adaptive-shield.com |
d37e237bfb76097bacca622b5cb294c75c3dc0a2 | 192da4ad4b065d460632dd968206ecde4b1c4864 | /mfeatures.py | ff073d478c1762e795c6f4788a65022d89d95713 | [] | no_license | Meetkumar1/Speaker-Recognition | 2481bc0db8c441a85ea0f0081ef29b7a153e43ac | ca5346a6e1247ffaaa3db949cb82a8328e556a69 | refs/heads/master | 2020-07-14T08:42:12.636489 | 2019-08-30T02:35:29 | 2019-08-30T02:35:29 | 205,285,820 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,194 | py | import numpy as np
from sklearn import preprocessing
import features_extraction as mfcc
def calculate_delta(array):
"""Calculate and returns the delta of given feature vector matrix"""
rows,cols = array.shape
deltas = np.zeros((rows,20))
N = 2
for i in range(rows):
index = []
j = 1
while j <= N:
if i-j < 0:
first = 0
else:
first = i-j
if i+j > rows-1:
second = rows-1
else:
second = i+j
index.append((second,first))
j+=1
deltas[i] = ( array[index[0][0]]-array[index[0][1]] + (2 * (array[index[1][0]]-array[index[1][1]])) ) / 10
return deltas
def extract_features(audio,rate):
"""extract 20 dim mfcc features from an audio, performs CMS and combines
delta to make it 40 dim feature vector"""
mfcc_feat = mfcc.mfcc(audio,rate, 0.025, 0.01,20,appendEnergy = True)
mfcc_feat = preprocessing.scale(mfcc_feat)
delta = calculate_delta(mfcc_feat)
combined = np.hstack((mfcc_feat,delta))
return combined | [
"noreply@github.com"
] | Meetkumar1.noreply@github.com |
04bc708a8398d75edd4c95abe4ac6891383e4858 | ed9025b0b5b4815ca86e4956a6cf9ee3f5606105 | /ColorSelect.py | b4b8e0f24fe732564abe9335bf059957df0bcd45 | [
"Apache-2.0"
] | permissive | damay27/GB_Tile_Maker | af55add047e8d1a2f66ac816cde323999347cc1e | 44e94580966d4337bf008e987ad4fffba31bef0f | refs/heads/main | 2023-08-07T18:36:50.826261 | 2021-08-21T22:58:15 | 2021-08-21T22:58:15 | 398,668,993 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,824 | py | import pygame
from Colors import *
class ColorSelect:
def __init__(self, x, y, square_size):
self.x = x
self.y = y
self.square_size = square_size
self.selected_value = 3
self.square_list = []
for i in range(4):
self.square_list.append(pygame.Rect(x + i * self.square_size, y, self.square_size, self.square_size))
def draw(self, surface):
pygame.draw.rect(surface, LIGHTEST_GREEN, self.square_list[0])
pygame.draw.rect(surface, LIGHT_GREEN, self.square_list[1])
pygame.draw.rect(surface, DARK_GREEN, self.square_list[2])
pygame.draw.rect(surface, DARKEST_GREEN, self.square_list[3])
pygame.draw.rect(surface, (0, 0, 0), self.square_list[self.selected_value], width = 4)
# Draw the vertical lines that divide the squares
for i in range(1, 4):
pygame.draw.line(surface, (0, 0, 0), (self.x + i*self.square_size, self.y), (self.x + i*self.square_size, self.y + self.square_size - 1), 1)
def handle_mouse_input(self, mouse_pos, event):
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
index = 0
while index < len(self.square_list):
if self.square_list[index].collidepoint(mouse_pos):
if index == 0:
self.selected_value = LIGHTEST_GREEN_VAL
elif index == 1:
self.selected_value = LIGHT_GREEN_VAL
elif index == 2:
self.selected_value = DARK_GREEN_VAL
elif index == 3:
self.selected_value = DARKEST_GREEN_VAL
break
index += 1
def get_selected_value(self):
return self.selected_value | [
"damay27@outlook.com"
] | damay27@outlook.com |
ac201c32c190e05228316b6f02938c7fff0898f6 | 2b99c11477778b07078a8611e2e2b6a5f4e9d6a4 | /app/accounts/urls.py | 5c83ba4d6032b4ec4b8556a00fe1835c4bc4be8c | [] | no_license | ParsiSrijay/FinalProject | e6f43cb047771f8c69c1985b2f0ac1afa3e8132f | fb423769f01a60184504c488286d752063600c71 | refs/heads/master | 2022-12-03T20:32:46.502835 | 2020-08-28T09:10:54 | 2020-08-28T09:10:54 | 291,000,150 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 626 | py | from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.FinRecords,name ='fr'),
path("first",views.first,name='first'),
path('display',views.disp,name="display"),
path('edit',views.edit,name="edit"),
path('receipt/',views.receipts,name='receipts'),
path('receipt/display',views.RandPDisplay,name="r&pd"),
path('iedisp',views.IandEDisplay,name="iande"),
path('balsheet',views.BalanceSheet,name="bs"),
path('cashAcc',views.CashAccountDisp,name="cs"),
path('pdf',views.generatepdf,name='pdf'),
]
| [
"parsi.srijay@gmail.com"
] | parsi.srijay@gmail.com |
4eff612830ab9f15f6735835500fc1eaeb948fc7 | 1ea992a40e0320223d6a991eac305681ae30778b | /Euler005.py | 4f36fa18064e4c9f1c1692a9e9c3ce302639fd50 | [] | no_license | FionnMarf/ProjectEuler | 8cf0f775e523c93a678acaf6ca45ed54b8e717b3 | 165d6b89b45b7b750b9ed191062b50d7af20de3a | refs/heads/master | 2021-07-25T16:18:13.003373 | 2017-11-07T11:50:04 | 2017-11-07T11:50:04 | 107,702,861 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 366 | py | def main():
p = 2*3*5*7*11*13*17*19
finished = False
increment = 1
while not finished:
finished = True
for i in range(1, 20):
if p%i != 0:
finished = False
if finished == True:
print p
increment += 1
p *= increment
if __name__ == '__main__':
main()
| [
"noreply@github.com"
] | FionnMarf.noreply@github.com |
4e50d964d1988184ce87c9853b5c8d6ac4fc84be | d4d8d848f6dede33173dc92c13f8ba19cabee8e0 | /delphi/condition/test_auc_condition.py | 456c1b18286cb43df06e089263e844902ac5a302 | [] | no_license | a4anna/delphi-cvat | dba066dfd9cff6018e9031ce83c587f84212f5c8 | 019fd518af259e54259ae19f1621a3ea896a10d6 | refs/heads/main | 2023-03-23T06:55:54.915302 | 2021-02-03T15:48:36 | 2021-02-03T15:48:36 | 310,442,361 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 678 | py | from typing import Dict, Optional
from delphi.condition.model_condition import ModelCondition
from delphi.model_trainer import ModelTrainer
from delphi.proto.delphi_pb2 import ModelStats
class TestAucCondition(ModelCondition):
def __init__(self, threshold: float, trainer: ModelTrainer):
super().__init__()
self._threshold = threshold
self._trainer = trainer
def is_satisfied(self, example_counts: Dict[str, int], last_statistics: Optional[ModelStats]) -> bool:
return last_statistics.auc > self._threshold
def close(self) -> None:
pass
@property
def trainer(self) -> ModelTrainer:
return self._trainer
| [
"shilpag@cloudlet027.maas"
] | shilpag@cloudlet027.maas |
6301edb7062fa45ed01d04ba326e978ab1a9c163 | 6fcfb638fa725b6d21083ec54e3609fc1b287d9e | /python/n1nj4sec_pupy/pupy-master/pupy/modules/screenshot.py | 1a3055e23702c2b625f5306a537f0e3d8a04c751 | [] | no_license | LiuFang816/SALSTM_py_data | 6db258e51858aeff14af38898fef715b46980ac1 | d494b3041069d377d6a7a9c296a14334f2fa5acc | refs/heads/master | 2022-12-25T06:39:52.222097 | 2019-12-12T08:49:07 | 2019-12-12T08:49:07 | 227,546,525 | 10 | 7 | null | 2022-12-19T02:53:01 | 2019-12-12T07:29:39 | Python | UTF-8 | Python | false | false | 3,976 | py | # -*- coding: utf-8 -*-
# --------------------------------------------------------------
# Copyright (c) 2015, Nicolas VERDIER (contact@n1nj4.eu) All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE
# --------------------------------------------------------------
from pupylib.PupyModule import *
from os import path
import time
import datetime
import subprocess
__class_name__="screenshoter"
@config(cat="gather")
class screenshoter(PupyModule):
""" take a screenshot :) """
dependencies = ['mss', 'screenshot']
def init_argparse(self):
self.arg_parser = PupyArgumentParser(prog='screenshot', description=self.__doc__)
self.arg_parser.add_argument('-e', '--enum', action='store_true', help='enumerate screen')
self.arg_parser.add_argument('-s', '--screen', type=int, default=None, help='take a screenshot on a specific screen (default all screen on one screenshot)')
self.arg_parser.add_argument('-v', '--view', action='store_true', help='directly open the default image viewer on the screenshot for preview')
def run(self, args):
rscreenshot = self.client.conn.modules['screenshot']
if args.enum:
self.rawlog('{:>2} {:>9} {:>9}\n'.format('IDX', 'SIZE', 'LEFT'))
for i, screen in enumerate(rscreenshot.screens()):
if not (screen['width'] and screen['height']):
continue
self.rawlog('{:>2}: {:>9} {:>9}\n'.format(
i,
'{}x{}'.format(screen['width'], screen['height']),
'({}x{})'.format(screen['top'], screen['left'])))
return
screenshots, error = rscreenshot.screenshot(args.screen)
if not screenshots:
self.error(error)
else:
self.success('number of monitor detected: %s' % str(len(screenshots)))
for screenshot in screenshots:
filepath = path.join("data","screenshots","scr_"+self.client.short_name()+"_"+str(datetime.datetime.now()).replace(" ","_").replace(":","-")+".png")
with open(filepath, 'w') as out:
out.write(screenshot)
# sleep used to be sure the file name will be different between 2 differents screenshots
time.sleep(1)
self.success(filepath)
# if args.view:
# viewer = config.get('default_viewers', 'image_viewer')
# subprocess.Popen([viewer, output])
| [
"659338505@qq.com"
] | 659338505@qq.com |
153038b998ce42a5b1773cd540aba540aa79ed90 | 4cae91877e1a47858e3f218d6b94ba34435d7351 | /Chapter2/hello_world.py | 28c1fb5e65eb200161cd8f0c834a8128dd373259 | [] | no_license | czer0/python_work | a2e99a362ea0d992d09cf72c856d13141337e171 | bec45f742ecee4a6d4d21bd52bb6a05c4fb82667 | refs/heads/master | 2021-01-20T14:36:13.495235 | 2017-06-07T15:29:38 | 2017-06-07T15:29:38 | 90,636,246 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 172 | py | message = "Hello Python world!"
print(message)
message = "Hello Python Crash Course world!"
print(message)
message = "Hello Python CrasH Course reader!"
print = (mesage)
| [
"clint.mk@gmail.com"
] | clint.mk@gmail.com |
3152ceb7f390a21f795d30bcba482e89cf743ba0 | 55951cd3e6a8dcd24247588a7f8918c29254f794 | /book_manager/apps/accounts/models.py | 5e989dea650393c226f6b59848e4a827fec3f3e9 | [
"MIT"
] | permissive | uoshvis/book-manager | dd63da99223cb637d1921a8c083d3cab05b7c29d | cd9d2b17ce3e786e2fd5319be5c34c3503cc2930 | refs/heads/main | 2023-07-12T01:11:24.448066 | 2021-08-14T13:35:58 | 2021-08-14T13:35:58 | 392,918,443 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,921 | py | from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin, UserManager
from django.contrib.auth.validators import ASCIIUsernameValidator
from django.contrib.postgres.fields import CICharField, CIEmailField
from django.core.mail import send_mail
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
class CustomUser(AbstractBaseUser, PermissionsMixin):
"""
Custom implementation of AbstractUser
Custom base class implementing a fully featured User model with
admin-compliant permissions.
Username and password are required. Other fields are optional.
username is only from ASCII letters
username is not case-sensitive
email is mandatory and not case-sensitive
"""
username_validator = ASCIIUsernameValidator()
username = CICharField(
_('username'),
max_length=150,
unique=True,
help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
validators=[username_validator],
error_messages={
'unique': _("A user with that username already exists."),
},
)
first_name = models.CharField(_('first name'), max_length=150, blank=True)
last_name = models.CharField(_('last name'), max_length=150, blank=True)
email = CIEmailField(
_("email address"),
unique=True,
error_messages={
"unique": _("A user with that email address already exists."),
},
)
is_staff = models.BooleanField(
_('staff status'),
default=False,
help_text=_('Designates whether the user can log into this admin site.'),
)
is_active = models.BooleanField(
_('active'),
default=True,
help_text=_(
'Designates whether this user should be treated as active. '
'Unselect this instead of deleting accounts.'
),
)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
objects = UserManager()
EMAIL_FIELD = 'email'
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def clean(self):
super().clean()
self.email = self.__class__.objects.normalize_email(self.email)
def get_full_name(self):
"""
Return the first_name plus the last_name, with a space in between.
"""
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
"""Return the short name for the user."""
return self.first_name
def email_user(self, subject, message, from_email=None, **kwargs):
"""Send an email to this user."""
send_mail(subject, message, from_email, [self.email], **kwargs)
| [
"uoshvis@gmail.com"
] | uoshvis@gmail.com |
5791ebb116ef3d5e6f93c11b93c8d18411fc5370 | 58f7505f698e868798a9bb640a0e3dc72af76b53 | /app.py | bb24f710e1665a8765e4cd209193e87f3f32ce30 | [
"MIT"
] | permissive | sosudo/graphing-the-weather | f0916a8d60626af1af73f41dc22402e2232d0eef | c0fef44b28fdbcff0cdf4adc8377c2924a4a90b6 | refs/heads/master | 2022-04-08T18:10:11.688264 | 2020-02-10T00:41:42 | 2020-02-10T00:41:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 557 | py | from requests import get
import matplotlib.pyplot as plt
from dateutil import parser
url = 'https://apex.oracle.com/pls/apex/raspberrypi/weatherstation/getallmeasurements/2801460'
weather = get(url).json()
temperatures = []
for record in weather['items']:
temperature = record['ambient_temp']
temperatures.append(temperature)
timestamps = []
for record in weather['items']:
timestamp = parser.parse(record['reading_timestamp'])
timestamps.append(timestamp)
plt.plot(timestamps, temperatures)
plt.ylabel("Temperature")
plt.xlabel("Timestamp")
plt.show()
| [
"noreply@github.com"
] | sosudo.noreply@github.com |
9343a0cea27c110bb7b85dddee1c08f2ef5c37f8 | 3e46f70ace83a5e0d1fc4078d906a721988b9398 | /Largest_Number.py | 19deab55a27eec87148e3272d31af6ba189ade6b | [] | no_license | ZamanbekNuridinov/Algorithms | 3a687a32f054b3def8b3c387852909d52e58e01b | 907ed758790ebb36f1877623650cac7f15d16060 | refs/heads/master | 2022-12-19T10:55:08.779951 | 2020-09-17T15:30:59 | 2020-09-17T15:30:59 | 296,365,139 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 303 | py | n=int(input())
a=[]
for i in range(n):
l=input()
a.append(l)
b=[]
max=a[0]
while len(a)>0:
for i in range(len(a)):
if a[i]>max:
max=a[i]
b.append(a[i])
a.remove(a[i])
print(f"Max element in this list is: {max}")
print(f"Largest number of some digits is: {b}")
| [
"nuridinov.zamanbek.911@gmail.com"
] | nuridinov.zamanbek.911@gmail.com |
c9d9d4bf240b7da78e89c784bec95b7431fbc94b | 1ffebb705e252d0f2f7ad9c573585dba9f65aa57 | /app.py | 3960d00169f7a10de7bfc95d47b068a39540b145 | [] | no_license | Cyrill98/Flask_Blog | 9b130db521055a23f382654a228de83d1cca7f42 | f6c569618275f821e7aabe047f2c55abefce37d9 | refs/heads/master | 2023-09-01T22:31:25.265449 | 2021-09-21T08:40:41 | 2021-09-21T08:40:41 | 408,695,243 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,605 | py | import sqlite3
from flask import Flask, render_template, request, url_for, flash, redirect
from werkzeug.exceptions import abort
app = Flask(__name__)
app.config['SECRET_KEY'] = 'mysecretkey'
def get_db_connection():
conn = sqlite3.connect('database.db')
conn.row_factory = sqlite3.Row
return conn
def get_post(post_id):
conn = get_db_connection()
post = conn.execute('SELECT * FROM posts WHERE id = ?',
(post_id,)).fetchone()
conn.close()
if post is None:
abort(404)
return post
def get_post(post_id):
conn = get_db_connection()
post = conn.execute('SELECT * FROM posts WHERE id = ?',
(post_id,)).fetchone()
conn.close()
if post is None:
abort(404)
return post
@app.route('/')
def index():
conn = get_db_connection()
posts = conn.execute('SELECT * FROM posts').fetchall()
conn.close()
return render_template('index.html', posts=posts)
@app.route('/create', methods=('GET', 'POST'))
def create():
if request.method == 'POST':
title = request.form['title']
content = request.form['content']
if not title:
flash('Title is required!')
else:
conn = get_db_connection()
conn.execute('INSERT INTO posts (title, content) VALUES (?, ?)',
(title, content))
conn.commit()
conn.close()
return redirect(url_for('index'))
return render_template('create.html')
@app.route('/<int:id>/edit', methods=('GET', 'POST'))
def edit(id):
post = get_post(id)
if request.method == 'POST':
title = request.form['title']
content = request.form['content']
if not title:
flash('Title is required!')
else:
conn = get_db_connection()
conn.execute('UPDATE posts SET title = ?, content = ?'
' WHERE id = ?',
(title, content, id))
conn.commit()
conn.close()
return redirect(url_for('index'))
return render_template('edit.html', post=post)
@app.route('/<int:id>/delete', methods=('POST',))
def delete(id):
post = get_post(id)
conn = get_db_connection()
conn.execute('DELETE FROM posts WHERE id = ?', (id,))
conn.commit()
conn.close()
flash('"{}" was successfully deleted!'.format(post['title']))
return redirect(url_for('index'))
@app.route('/<int:post_id>')
def post(post_id):
post = get_post(post_id)
return render_template('post.html', post=post) | [
"cyrillanwar98@gmail.com"
] | cyrillanwar98@gmail.com |
7defb7e409f5c5289b0e5425ea3683d8825b4f0d | 96543443202bb30332f97007d8d0a027356b813d | /dictionary.py | c912341d03d5822a7bcb9fd0336354936a2c0a36 | [] | no_license | JovanDel/August | 4451a7bbb7d67f365eb26bce06d39c57d81a1ffd | 0f65f21c23e8e7e597b5406074652b9117264630 | refs/heads/master | 2022-12-10T02:40:06.973909 | 2020-09-02T07:47:23 | 2020-09-02T07:47:23 | 292,213,881 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 475 | py | gpas = {
"Mark Lassof" :3.45,
"Fred Smith" :2.99,
"Mary Johnson" :2.55,
"John Hadley" :1.95,
"Louis Lane" :3.15,
"Brett Smith" :4.0,
}
print ("The GPA is:", (gpas["Mark Lassof"]))
print ("The GPA is:", (gpas["Fred Smith"]))
gpas ["Louis Lane"] = 2.75
gpas ["Thomas Smith"] = 2.61
del gpas ["Fred Smith"]
if gpas in("Mark Lassof"):
print ("Mark is present")
| [
"noreply@github.com"
] | JovanDel.noreply@github.com |
a0c2872edf9c53827783de141070af4c60b0b066 | 3b4c766ed91d0b7b5244df0b9cf2b66215e7f280 | /sns/migrations/0001_initial.py | 1a87e863bcb429c33ea2c613d3a94e793aa80c5b | [] | no_license | shake551/SNS_wannabe | d36c0e0907a7c53476e441cb096b103c15c2c787 | 562adafdf4157fc58d5b10a2a71bfe33baa0918d | refs/heads/main | 2023-02-21T06:55:43.569986 | 2021-01-05T07:00:33 | 2021-01-05T07:00:33 | 324,520,697 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,727 | py | # Generated by Django 3.1.1 on 2021-01-01 05:33
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Group',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100)),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='group_owner', to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Message',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('content', models.TextField(max_length=1000)),
('shsre_id', models.IntegerField(default=-1)),
('good_count', models.IntegerField(default=0)),
('share_count', models.IntegerField(default=0)),
('pub_date', models.DateTimeField(auto_now_add=True)),
('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='sns.group')),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='message_owner', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ('-pub_date',),
},
),
migrations.CreateModel(
name='Good',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('message', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='sns.message')),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='good_owner', to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Friend',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='sns.group')),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='friend_owner', to=settings.AUTH_USER_MODEL)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| [
"hiroki.yamako@ezweb.ne.jp"
] | hiroki.yamako@ezweb.ne.jp |
4b21a0a6b7c713016c63c6be1178fc15c4ec5993 | 76ec6b4fb847b46f6bec2872ed6b2ee24a426fd4 | /CMPE-275-Project/bloomfilter.py | c52b66a3c0c5c9ce800c0183430b02696ffa27c6 | [] | no_license | aasthakumar/Flask-RestAPI | 8137e249c4ee6fea721ee56da29df107ae650efc | 52ca1d6ff47f855ab9216fd6327b5eb0049f06cf | refs/heads/master | 2020-03-07T20:02:53.578684 | 2018-04-02T01:54:08 | 2018-04-02T01:54:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,649 | py | # Python 3 program to build Bloom Filter
# Install mmh3 and bitarray 3rd party module first
# pip install mmh3
# pip install bitarray
import math
import mmh3
from bitarray import bitarray
class BloomFilter(object):
'''
Class for Bloom filter, using murmur3 hash function
'''
def __init__(self, items_count,fp_prob):
'''
items_count : int
Number of items expected to be stored in bloom filter
fp_prob : float
False Positive probability in decimal
'''
# False posible probability in decimal
self.fp_prob = fp_prob
# Size of bit array to use
self.size = self.get_size(items_count,fp_prob)
# number of hash functions to use
self.hash_count = self.get_hash_count(self.size,items_count)
# Bit array of given size
self.bit_array = bitarray(self.size)
# initialize all bits as 0
self.bit_array.setall(0)
def add(self, item):
'''
Add an item in the filter
'''
digests = []
for i in range(self.hash_count):
# create digest for given item.
# i work as seed to mmh3.hash() function
# With different seed, digest created is different
digest = mmh3.hash(item,i) % self.size
digests.append(digest)
# set the bit True in bit_array
self.bit_array[digest] = True
def check(self, item):
'''
Check for existence of an item in filter
'''
for i in range(self.hash_count):
digest = mmh3.hash(item,i) % self.size
if self.bit_array[digest] == False:
# if any of bit is False then,its not present
# in filter
# else there is probability that it exist
return False
return True
@classmethod
def get_size(self,n,p):
'''
Return the size of bit array(m) to used using
following formula
m = -(n * lg(p)) / (lg(2)^2)
n : int
number of items expected to be stored in filter
p : float
False Positive probability in decimal
'''
m = -(n * math.log(p))/(math.log(2)**2)
return int(m)
@classmethod
def get_hash_count(self, m, n):
'''
Return the hash function(k) to be used using
following formula
k = (m/n) * lg(2)
m : int
size of bit array
n : int
number of items expected to be stored in filter
'''
k = (m/n) * math.log(2)
return int(k) | [
"aastha.kumar@sjsu.edu"
] | aastha.kumar@sjsu.edu |
727d7ace2d7e5bb03b05240b8fb2e711a818186e | 09e5cfe06e437989a2ccf2aeecb9c73eb998a36c | /modules/cctbx_project/xfel/ui/components/xfel_gui_controls.py | 3d08fe4ffe7f49a0c8341e17313896eb3ca5a7db | [
"BSD-3-Clause",
"BSD-3-Clause-LBNL"
] | permissive | jorgediazjr/dials-dev20191018 | b81b19653624cee39207b7cefb8dfcb2e99b79eb | 77d66c719b5746f37af51ad593e2941ed6fbba17 | refs/heads/master | 2020-08-21T02:48:54.719532 | 2020-01-25T01:41:37 | 2020-01-25T01:41:37 | 216,089,955 | 0 | 1 | BSD-3-Clause | 2020-01-25T01:41:39 | 2019-10-18T19:03:17 | Python | UTF-8 | Python | false | false | 29,197 | py | from __future__ import absolute_import, division, print_function
import six
'''
Author : Lyubimov, A.Y.
Created : 06/03/2016
Last Changed: 06/03/2016
Description : XFEL UI Custom Widgets and Controls
'''
import os
import wx
import wx.lib.agw.floatspin as fs
from wxtbx import metallicbutton as mb
# Platform-specific stuff
# TODO: Will need to test this on Windows at some point
if wx.Platform == '__WXGTK__':
norm_font_size = 10
button_font_size = 12
LABEL_SIZE = 14
CAPTION_SIZE = 12
elif wx.Platform == '__WXMAC__':
norm_font_size = 12
button_font_size = 14
LABEL_SIZE = 14
CAPTION_SIZE = 12
elif (wx.Platform == '__WXMSW__'):
norm_font_size = 9
button_font_size = 11
LABEL_SIZE = 11
CAPTION_SIZE = 9
icons = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'icons/')
# --------------------------------- Buttons ---------------------------------- #
class GradButton(mb.MetallicButton):
def __init__(self, parent, label='', bmp=None, size=wx.DefaultSize,
style=mb.MB_STYLE_BOLD_LABEL, handler_function=None,
user_data=None, start_color=(218, 218, 218),
gradient_percent=0, highlight_color=(230, 230, 230),
label_size=LABEL_SIZE, caption_size=CAPTION_SIZE,
button_margin=4, disable_after_click=0) :
if isinstance(bmp, str) :
bmp = self.StandardBitmap(bmp)
bmp_size = bmp.GetSize()
if bmp_size > size[1]:
size = (size[0], 1.5 * bmp_size[1])
mb.MetallicButton.__init__(self,
parent=parent,
label=label,
bmp=bmp,
size=size,
style=style,
name=str(user_data),
start_color=start_color,
gradient_percent=gradient_percent,
highlight_color=highlight_color,
label_size=label_size,
caption_size=caption_size,
button_margin=button_margin,
disable_after_click=disable_after_click
)
if handler_function is not None:
self.bind_event(wx.EVT_BUTTON, handler_function)
def StandardBitmap(img_name, size=None):
img_path = img_name
img = wx.Image(img_path, type=wx.BITMAP_TYPE_ANY, index=-1)
if size is not None:
(w, h) = size
img.Rescale(w, h)
bmp = img.ConvertToBitmap()
return bmp
class RunBlockButton(GradButton):
def __init__(self, parent, block, size=wx.DefaultSize):
self.block = block
db = block.app
self.rnum = block.rungroup_id
self.first_run, self.last_run = block.get_first_and_last_runs()
self.use_ids = db.params.facility.name not in ['lcls']
GradButton.__init__(self, parent=parent, label='',
size=size)
self.update_label()
def update_label(self):
if self.first_run is None:
first = ' ...'
else:
if self.use_ids:
first = self.first_run.id
else:
first = self.first_run.run
if self.last_run is None:
last = ' ...'
else:
last = ' - {}'.format(self.last_run.id if self.use_ids else self.last_run.run)
self.block_label = '[{}] runs {}{}'.format(self.rnum, first, last)
self.SetLabel(self.block_label)
self.Refresh()
class TagButton(GradButton):
def __init__(self, parent, run, size=wx.DefaultSize):
self.run = run
self.tags = self.run.tags
self.parent = parent
GradButton.__init__(self, parent=parent, size=size)
self.update_label()
def update_label(self):
label = ', '.join([i.name for i in self.tags])
self.SetLabel(label)
self.SetFont(wx.Font(button_font_size, wx.DEFAULT, wx.NORMAL, wx.NORMAL))
self.Refresh()
def change_tags(self):
''' Calls dialog with tag options for all runs; user will select tags
for this specific run
'''
all_tags = self.run.app.get_all_tags()
all_tag_names = [t.name for t in all_tags]
tag_dlg = wx.MultiChoiceDialog(self,
message='Available sample tags',
caption='Sample Tags',
choices=all_tag_names)
# Get indices of selected items (if any) and set them to checked
local_tag_names = [i.name for i in self.tags]
indices = [all_tag_names.index(i) for i in all_tag_names if i in local_tag_names]
tag_dlg.SetSelections(indices)
tag_dlg.Fit()
if (tag_dlg.ShowModal() == wx.ID_OK):
tag_indices = tag_dlg.GetSelections()
self.tags = [i for i in all_tags if all_tags.index(i) in
tag_indices]
old_tags = self.run.tags
old_tag_names = [t.name for t in old_tags]
new_tag_names = [t.name for t in self.tags]
for new_tag in self.tags:
if new_tag.name not in old_tag_names:
self.run.add_tag(new_tag)
for old_tag in old_tags:
if old_tag.name not in new_tag_names:
self.run.remove_tag(old_tag)
# re-synchronize, just in case
self.tags = self.run.tags
self.update_label()
# --------------------------------- Controls --------------------------------- #
class CtrlBase(wx.Panel):
''' Control panel base class '''
def __init__(self,
parent,
label_style='normal',
content_style='normal',
size=wx.DefaultSize):
wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY, size=size)
if label_style == 'normal':
self.font = wx.Font(norm_font_size, wx.DEFAULT, wx.NORMAL, wx.NORMAL)
elif label_style == 'bold':
self.font = wx.Font(norm_font_size, wx.DEFAULT, wx.NORMAL, wx.BOLD)
elif label_style == 'italic':
self.font = wx.Font(norm_font_size, wx.DEFAULT, wx.ITALIC, wx.NORMAL)
elif label_style == 'italic_bold':
self.font = wx.Font(norm_font_size, wx.DEFAULT, wx.ITALIC, wx.BOLD)
if content_style == 'normal':
self.cfont = wx.Font(norm_font_size, wx.DEFAULT, wx.NORMAL, wx.NORMAL)
elif content_style == 'bold':
self.cfont = wx.Font(norm_font_size, wx.DEFAULT, wx.NORMAL, wx.BOLD)
elif content_style == 'italic':
self.cfont = wx.Font(norm_font_size, wx.DEFAULT, wx.ITALIC, wx.NORMAL)
elif content_style == 'italic_bold':
self.cfont = wx.Font(norm_font_size, wx.DEFAULT, wx.ITALIC, wx.BOLD)
class InputCtrl(CtrlBase):
''' Generic panel that will place a text control, with a label and an
optional Browse / magnifying-glass buttons into a window'''
def __init__(self, parent,
label='', label_size=(100, -1),
label_style='normal',
button=False, value=''):
CtrlBase.__init__(self, parent=parent, label_style=label_style)
output_box = wx.FlexGridSizer(1, 4, 0, 10)
self.txt = wx.StaticText(self, label=label, size=label_size)
self.txt.SetFont(self.font)
output_box.Add(self.txt)
self.ctr = wx.TextCtrl(self) #, size=ctr_size)
self.ctr.SetValue(value)
output_box.Add(self.ctr, flag=wx.EXPAND)
self.btn_browse = wx.Button(self, label='Browse...')
self.btn_mag = wx.BitmapButton(self,
bitmap=wx.Bitmap('{}/16x16/viewmag.png'
''.format(icons)))
output_box.Add(self.btn_browse, flag=wx.RESERVE_SPACE_EVEN_IF_HIDDEN)
output_box.Add(self.btn_mag, flag=wx.RESERVE_SPACE_EVEN_IF_HIDDEN)
if not button:
self.btn_browse.Hide()
self.btn_mag.Hide()
output_box.AddGrowableCol(1, 1)
self.SetSizer(output_box)
class TextCtrl(CtrlBase):
''' Generic panel placing only a text box'''
def __init__(self, parent,
ctrl_size=(200, -1),
value=''):
CtrlBase.__init__(self, parent=parent)
output_box = wx.FlexGridSizer(1, 4, 0, 10)
self.txt = wx.StaticText(self)
self.txt.SetFont(self.font)
output_box.Add(self.txt)
self.ctr = wx.TextCtrl(self, size=ctrl_size)
self.ctr.SetValue(value)
output_box.Add(self.ctr, flag=wx.EXPAND)
self.SetSizer(output_box)
class TextButtonCtrl(CtrlBase):
''' Generic panel that will place a text control, with a label and an
optional large button, and an optional bitmap button'''
def __init__(self, parent,
label='', label_size=(100, -1),
label_style='normal',
text_style=wx.TE_LEFT,
ctrl_size=(200, -1),
big_button=False,
big_button_label='Browse...',
big_button_size=wx.DefaultSize,
ghost_button=True,
value=''):
CtrlBase.__init__(self, parent=parent, label_style=label_style)
output_box = wx.FlexGridSizer(1, 4, 0, 10)
self.txt = wx.StaticText(self, label=label, size=label_size)
self.txt.SetFont(self.font)
output_box.Add(self.txt)
self.ctr = wx.TextCtrl(self, style=text_style, size=ctrl_size)
self.ctr.SetValue(value)
output_box.Add(self.ctr, flag=wx.EXPAND)
self.btn_big = wx.Button(self, label=big_button_label, size=big_button_size)
if ghost_button:
output_box.Add(self.btn_big, flag=wx.RESERVE_SPACE_EVEN_IF_HIDDEN)
else:
output_box.Add(self.btn_big)
if not big_button:
self.btn_big.Hide()
output_box.AddGrowableCol(1, 1)
self.SetSizer(output_box)
class TwoButtonCtrl(CtrlBase):
''' Generic panel that will place a text control, with a label and an
optional large button, and an optional bitmap button'''
def __init__(self, parent,
label='', label_size=(100, -1),
label_style='normal',
text_style=wx.TE_LEFT,
button1=False,
button1_label='Browse...',
button1_size=wx.DefaultSize,
button2=False,
button2_label='Default',
button2_size=wx.DefaultSize,
value=''):
CtrlBase.__init__(self, parent=parent, label_style=label_style)
output_box = wx.FlexGridSizer(1, 5, 0, 10)
self.txt = wx.StaticText(self, label=label, size=label_size)
self.txt.SetFont(self.font)
output_box.Add(self.txt)
self.ctr = wx.TextCtrl(self, style=text_style)
self.ctr.SetValue(value)
output_box.Add(self.ctr, flag=wx.EXPAND)
if button1:
self.button1 = wx.Button(self, label=button1_label, size=button1_size)
output_box.Add(self.button1)
if button2:
self.button2 = wx.Button(self, label=button2_label, size=button2_size)
output_box.Add(self.button2)
output_box.AddGrowableCol(1, 1)
self.SetSizer(output_box)
class OptionCtrl(CtrlBase):
''' Generic panel will place a text control w/ label '''
def __init__(self, parent, items,
label='',
label_size=(100, -1),
label_style='normal',
sub_labels=[],
ctrl_size=(300, -1)):
CtrlBase.__init__(self, parent=parent, label_style=label_style)
if label != '':
opt_box = wx.FlexGridSizer(1, len(items) * 2 + 1, 0, 10)
self.txt = wx.StaticText(self, label=label, size=label_size)
self.txt.SetFont(self.font)
opt_box.Add(self.txt, flag=wx.ALIGN_CENTER_VERTICAL)
else:
opt_box = wx.FlexGridSizer(1, len(items) * 2, 0, 10)
for key, value in items:
if sub_labels != []:
sub_label = sub_labels[items.index((key, value))].decode('utf-8')
else:
sub_label = key
if len(items) > 1:
opt_label = wx.StaticText(self, id=wx.ID_ANY, label=sub_label)
opt_box.Add(opt_label, flag=wx.ALIGN_CENTER_VERTICAL)
item = wx.TextCtrl(self, id=wx.ID_ANY, size=ctrl_size,
style=wx.TE_PROCESS_ENTER)
item.SetValue(str(value))
opt_box.Add(item, flag=wx.ALIGN_CENTER_VERTICAL)
self.__setattr__(key, item)
self.SetSizer(opt_box)
class VerticalOptionCtrl(CtrlBase):
''' Generic panel will place a text control w/ label in column'''
def __init__(self, parent, items,
label='',
label_size=(100, -1),
label_style='normal',
sub_labels=[],
ctrl_size=(300, -1)):
CtrlBase.__init__(self, parent=parent, label_style=label_style)
if label != '':
opt_box = wx.FlexGridSizer(len(items) * 2 + 1, 2, 10, 10)
self.txt = wx.StaticText(self, label=label, size=label_size)
self.txt.SetFont(self.font)
opt_box.Add(self.txt, flag=wx.ALIGN_CENTER_VERTICAL)
opt_box.Add((0, 0))
else:
opt_box = wx.FlexGridSizer(len(items) * 2, 2, 10, 10)
for key, value in items:
if sub_labels != []:
sub_label = sub_labels[items.index((key, value))].decode('utf-8')
else:
sub_label = key
if len(items) > 1:
opt_label = wx.StaticText(self, id=wx.ID_ANY, label=sub_label)
opt_box.Add(opt_label, flag=wx.ALIGN_CENTER_VERTICAL)
item = wx.TextCtrl(self, id=wx.ID_ANY, size=ctrl_size,
style=wx.TE_PROCESS_ENTER)
item.SetValue(str(value))
opt_box.Add(item, flag=wx.ALIGN_CENTER_VERTICAL)
self.__setattr__(key, item)
self.SetSizer(opt_box)
class IntFloatSpin(fs.FloatSpin):
def GetValue(self):
float_value = super(IntFloatSpin, self).GetValue()
int_value = int(round(float_value))
return int_value
class SpinCtrl(CtrlBase):
''' Generic panel will place a spin control w/ label '''
def __init__(self, parent,
label='',
label_size=(200, -1),
label_style='normal',
ctrl_size=(60, -1),
ctrl_value='3',
ctrl_max=10,
ctrl_min=0,
ctrl_step=1,
ctrl_digits=0):
CtrlBase.__init__(self, parent=parent, label_style=label_style)
ctr_box = wx.FlexGridSizer(1, 3, 0, 10)
self.txt = wx.StaticText(self, label=label.decode('utf-8'),
size=label_size)
self.txt.SetFont(self.font)
floatspin_class = IntFloatSpin if ctrl_digits == 0 else fs.FloatSpin
self.ctr = floatspin_class(self, value=ctrl_value, max_val=(ctrl_max),
min_val=(ctrl_min), increment=ctrl_step,
digits=ctrl_digits, size=ctrl_size)
ctr_box.Add(self.txt, flag=wx.ALIGN_CENTER_VERTICAL)
ctr_box.Add(self.ctr, flag=wx.ALIGN_CENTER_VERTICAL)
self.SetSizer(ctr_box)
class ChoiceCtrl(CtrlBase):
''' Generic panel will place a choice control w/ label '''
def __init__(self, parent,
choices,
label='',
label_size=(200, -1),
label_style='normal',
ctrl_size=(100, -1)):
CtrlBase.__init__(self, parent=parent, label_style=label_style)
ctr_box = wx.FlexGridSizer(1, 3, 0, 10)
self.txt = wx.StaticText(self, label=label, size=label_size)
self.txt.SetFont(self.font)
# Check if choices are tuples, extract data and assign to items if so
if all(isinstance(i, tuple) for i in choices):
items = [i[0] for i in choices]
self.ctr = wx.Choice(self, size=ctrl_size, choices=items)
for choice in choices:
item_idx = self.ctr.FindString(choice[0])
self.ctr.SetClientData(item_idx, choice[1])
else:
self.ctr = wx.Choice(self, size=ctrl_size, choices=choices)
ctr_box.Add(self.txt, flag=wx.ALIGN_CENTER_VERTICAL)
ctr_box.Add(self.ctr, flag=wx.ALIGN_CENTER_VERTICAL)
self.SetSizer(ctr_box)
class CheckListCtrl(CtrlBase):
def __init__(self, parent,
choices,
label='',
label_size=(200, -1),
label_style='normal',
ctrl_size=(150, -1),
direction='horizontal'):
CtrlBase.__init__(self, parent=parent, label_style=label_style)
self.txt = wx.StaticText(self, label=label, size=label_size)
self.txt.SetFont(self.font)
self.ctr = wx.CheckListBox(self, size=ctrl_size, choices=choices)
if label == '':
ctr_box = wx.BoxSizer(wx.VERTICAL)
else:
if direction == 'horizontal':
ctr_box = wx.FlexGridSizer(1, 2, 0, 10)
elif direction == 'vertical':
ctr_box = wx.FlexGridSizer(2, 1, 10, 0)
ctr_box.Add(self.txt, flag=wx.ALIGN_CENTER_VERTICAL)
ctr_box.Add(self.ctr, proportion=1,
flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
self.SetSizer(ctr_box)
class MultiChoiceCtrl(CtrlBase):
''' Generic panel with multiple choice controls / labels '''
def __init__(self, parent, items,
label='',
label_size=(200, -1),
label_style='normal',
ctrl_size=(100, -1)):
CtrlBase.__init__(self, parent=parent, label_style=label_style)
choice_box = wx.FlexGridSizer(1, len(items) * 2 + 1, 0, 10)
self.txt = wx.StaticText(self, label=label, size=label_size)
self.txt.SetFont(self.font)
choice_box.Add(self.txt, flag=wx.ALIGN_CENTER_VERTICAL)
for key, choices in six.iteritems(items):
if len(items) > 1:
ch_label =wx.StaticText(self, id=wx.ID_ANY, label=key)
choice_box.Add(ch_label, flag=wx.ALIGN_CENTER_VERTICAL)
item = wx.Choice(self, id=wx.ID_ANY, size=ctrl_size, choices=choices)
choice_box.Add(item, flag=wx.ALIGN_CENTER_VERTICAL)
self.__setattr__(key, item)
self.SetSizer(choice_box)
class TableCtrl(CtrlBase):
''' Generic panel will place a table w/ x and y labels
Data must be a list of lists for multi-column tables '''
def __init__(self, parent,
clabels=[],
clabel_size=(200, -1),
rlabels=[],
rlabel_size=(200, -1),
contents=[],
label_style='normal',
content_style='normal'):
CtrlBase.__init__(self, parent=parent, label_style=label_style,
content_style=content_style)
nrows = len(rlabels) + 1
if len(clabels) == 0:
ncols = 2
else:
ncols = len(clabels) + 1
self.sizer = wx.FlexGridSizer(nrows, ncols, 10, 10)
# add column labels (xlabels)
if len(clabels) > 0:
self.sizer.Add(wx.StaticText(self, label=''))
for item in column_labels:
clabel = wx.StaticText(self, label=i.decode('utf-8'), size=clabel_size)
clabel.SetFont(self.font)
self.sizer.Add(clabel)
# add row labels and row contents
for l in rlabels:
row_label = wx.StaticText(self, label=l.decode('utf-8'), size=rlabel_size)
row_label.SetFont(self.font)
self.sizer.Add(row_label)
# Add data to table
c_index = rlabels.index(l)
for item in contents[c_index]:
cell = wx.StaticText(self, label=item.decode('utf-8'))
cell.SetFont(self.cfont)
self.sizer.Add(cell)
self.SetSizer(self.sizer)
class RadioCtrl(CtrlBase):
'''Generic panel with multiple radio buttons.'''
def __init__(self, parent,
label='',
label_size=(200, -1),
label_style='normal',
ctrl_size=(100, -1),
direction='horizontal',
items={}):
CtrlBase.__init__(self, parent=parent, label_style=label_style)
if direction == 'horizontal':
radio_group = wx.FlexGridSizer(1, len(items) + 1, 0, 10)
else:
radio_group = wx.FlexGridSizer(len(items) + 1, 1, 0, 10)
if label != '':
self.txt = wx.StaticText(self, label=label, size=label_size)
self.txt.SetFont(self.font)
radio_group.Add(self.txt, flag=wx.ALIGN_CENTER_VERTICAL)
for key, value in six.iteritems(items):
button = wx.RadioButton(self, id=wx.ID_ANY, label=value)
radio_group.Add(button)
self.__setattr__(key, button)
self.SetSizer(radio_group)
# Use a mixin to support sorting by columns
import wx.lib.mixins.listctrl as listmix
class SortableListCtrl(wx.ListCtrl, listmix.ColumnSorterMixin):
def __init__(self, parent, style=wx.LC_ICON):
self.parent = parent
self.sortable_mixin = listmix
wx.ListCtrl.__init__(self, parent, style=style)
def initialize_sortable_columns(self, n_col=0, itemDataMap={}):
self.itemDataMap = itemDataMap
self.sortable_mixin.ColumnSorterMixin.__init__(self, n_col)
sortable_list = self.GetListCtrl()
if sortable_list:
sortable_list.Bind(wx.EVT_LIST_COL_CLICK, self.__OnColClick, sortable_list)
def __OnColClick(self, e):
self._col = e.GetColumn()
self._colSortFlag[self._col] = int(not self._colSortFlag[self._col])
self.GetListCtrl().SortItems(self.GetColumnSorter())
self.OnSortOrderChanged()
if hasattr(self.parent, 'onColClick'):
self.parent.onColClick(e)
def RestoreSortOrder(self, col, colSortFlag):
self._col = col
self._colSortFlag = colSortFlag
self.GetListCtrl().SortItems(self.GetColumnSorter())
self.OnSortOrderChanged()
def GetListCtrl(self):
return self
# ------------------------------- UI Elements -------------------------------- #
class RunBlock(CtrlBase):
def __init__(self, parent, block,
label_style='normal',
content_style='normal'):
self.block = block
CtrlBase.__init__(self, parent=parent, label_style=label_style,
content_style=content_style)
self.sizer = wx.FlexGridSizer(1, 2, 0, 5)
self.new_runblock = RunBlockButton(self, size=(200, 30), block=block)
# self.del_runblock = wx.BitmapButton(self,
# bitmap=wx.Bitmap('{}/16x16/delete.png'.format(icons)))
self.sizer.Add(self.new_runblock)
# self.sizer.Add(self.del_runblock)
self.SetSizer(self.sizer)
class PHILBox(CtrlBase):
def __init__(self, parent,
btn_import=True,
btn_import_size=(120, -1),
btn_import_label='Import PHIL',
btn_export=False,
btn_export_size=(120, -1),
btn_export_label='Export PHIL',
btn_default=True,
btn_default_size=(120, -1),
btn_default_label='Default PHIL',
ctr_size=(-1, 125),
ctr_value='',
label_style='normal',
content_style='normal'):
CtrlBase.__init__(self, parent=parent, label_style=label_style,
content_style=content_style)
self.sizer = wx.GridBagSizer(5, 5)
self.SetSizer(self.sizer)
self.ctr = wx.richtext.RichTextCtrl(self,
size=ctr_size,
style=wx.VSCROLL,
value=ctr_value)
span_counter = 0
if btn_import:
self.btn_import = wx.Button(self,
label=btn_import_label,
size=btn_import_size)
self.sizer.Add(self.btn_import, pos=(span_counter, 0))
span_counter += 1
if btn_export:
self.btn_export = wx.Button(self,
label=btn_export_label,
size=btn_export_size)
self.sizer.Add(self.btn_export, pos=(span_counter, 0))
span_counter += 1
if btn_default:
self.btn_default = wx.Button(self,
label=btn_default_label,
size=btn_default_size)
self.sizer.Add(self.btn_default, pos=(span_counter, 0))
span_counter += 1
if span_counter > 0:
self.sizer.Add(self.ctr, pos=(0, 1), span=(span_counter + 1, 1),
flag=wx.EXPAND)
self.sizer.AddGrowableRow(span_counter)
elif span_counter == 0:
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.ctr, 1, flag=wx.EXPAND)
self.sizer.AddGrowableCol(1)
class GaugeBar(CtrlBase):
def __init__(self, parent,
label='',
label_size=(80, -1),
label_style='normal',
content_style='normal',
gauge_size=(250, 15),
button=False,
button_label='View Stats',
button_size=wx.DefaultSize,
choice_box=True,
choice_label='',
choice_label_size=(120, -1),
choice_size=(100, -1),
choice_style='normal',
choices=[],
gauge_max=100):
CtrlBase.__init__(self, parent=parent, label_style=label_style,
content_style=content_style)
self.sizer = wx.FlexGridSizer(1, 6, 0, 10)
self.sizer.AddGrowableCol(3)
self.bar = wx.Gauge(self, range=gauge_max, size=gauge_size)
if choice_box:
self.bins = ChoiceCtrl(self,
label=choice_label,
label_size=choice_label_size,
label_style=choice_style,
ctrl_size=choice_size,
choices=choices)
self.txt_iso = wx.StaticText(self, label=label, size=label_size)
self.txt_max = wx.StaticText(self, label=str(gauge_max))
self.txt_min = wx.StaticText(self, label='0')
self.sizer.Add(self.txt_iso)
self.sizer.Add(self.txt_min)
self.sizer.Add(self.bar)
self.sizer.Add(self.txt_max)
self.sizer.Add(self.bins)
if button:
self.btn = wx.Button(self, label=button_label, size=button_size)
self.sizer.Add(self.btn, 1, wx.ALIGN_RIGHT | wx.ALIGN_CENTER)
self.SetSizer(self.sizer)
tp_EVT_STATUS_CHANGE = wx.NewEventType()
EVT_STATUS_CHANGE = wx.PyEventBinder(tp_EVT_STATUS_CHANGE, 1)
class StatusChange(wx.PyCommandEvent):
''' Send event when status light is updated '''
def __init__(self, etype, eid, status=None):
wx.PyCommandEvent.__init__(self, etype, eid)
self.status = status
def GetValue(self):
return self.status
class SentinelStatus(CtrlBase):
def __init__(self, parent,
label='',
label_size=(120, -1),
label_style='normal',
content_style='normal'):
self.label = label
self.label_size = label_size
CtrlBase.__init__(self, parent=parent, label_style=label_style,
content_style=content_style, size=(-1, 24))
bmp = wx.Bitmap('{}/16x16/led_off.png'.format(icons))
self.light = wx.StaticBitmap(self, -1, bmp)
self.sizer = wx.FlexGridSizer(1, 2, 0, 10)
self.sizer.Add(self.light)
self.sizer.Add(wx.StaticText(self, label=self.label, size=self.label_size))
self.SetSizer(self.sizer)
self.Bind(EVT_STATUS_CHANGE, self.onChangeStatus)
def change_status(self, status):
evt = StatusChange(tp_EVT_STATUS_CHANGE, -1, status)
wx.PostEvent(self, evt)
def onChangeStatus(self, evt):
status = evt.GetValue()
if status == 'on':
bmp = wx.Bitmap('{}/16x16/led_on.png'.format(icons))
elif status == 'off':
bmp = wx.Bitmap('{}/16x16/led_off.png'.format(icons))
elif status == 'idle':
bmp = wx.Bitmap('{}/16x16/led_idle.png'.format(icons))
elif status == 'alert':
bmp = wx.Bitmap('{}/16x16/led_alert.png'.format(icons))
self.light.SetBitmap(bmp)
class IsoformInfoCtrl(CtrlBase):
def __init__(self, parent,
label_style='normal',
content_style='normal'):
CtrlBase.__init__(self, parent=parent, label_style=label_style,
content_style=content_style)
self.uc_values = None
self.sizer = wx.FlexGridSizer(1, 9, 0, 10)
self.sizer.AddGrowableCol(7)
self.txt_iso = wx.StaticText(self, label='Isoform')
self.txt_pg = wx.StaticText(self, label='Point Group')
self.txt_num = wx.StaticText(self, label='No. Images')
self.txt_uc = wx.StaticText(self, label='Unit Cell')
self.ctr_iso = wx.TextCtrl(self, size=(30, -1), style=wx.TE_READONLY)
self.ctr_pg = wx.TextCtrl(self, size=(50, -1), style=wx.TE_READONLY)
self.ctr_num = wx.TextCtrl(self, size=(50, -1), style=wx.TE_READONLY)
self.ctr_uc = wx.TextCtrl(self, size=(200, -1), style=wx.TE_READONLY)
self.btn_hist = wx.Button(self, label='Histogram')
self.sizer.Add(self.txt_iso, flag=wx.ALIGN_CENTER_VERTICAL)
self.sizer.Add(self.ctr_iso, flag=wx.ALIGN_CENTER_VERTICAL)
self.sizer.Add(self.txt_pg, flag=wx.ALIGN_CENTER_VERTICAL)
self.sizer.Add(self.ctr_pg, flag=wx.ALIGN_CENTER_VERTICAL)
self.sizer.Add(self.txt_num, flag=wx.ALIGN_CENTER_VERTICAL)
self.sizer.Add(self.ctr_num, flag=wx.ALIGN_CENTER_VERTICAL)
self.sizer.Add(self.txt_uc, flag=wx.ALIGN_CENTER_VERTICAL)
self.sizer.Add(self.ctr_uc, flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
self.sizer.Add(self.btn_hist, flag=wx.ALIGN_CENTER_VERTICAL)
self.Bind(wx.EVT_BUTTON, self.onClusterHistogram, self.btn_hist)
self.SetSizer(self.sizer)
def onClusterHistogram(self, e):
if self.uc_values is not None:
import xfel.ui.components.xfel_gui_plotter as pltr
plotter = pltr.PopUpCharts()
plotter.plot_uc_histogram(info_list=[self.uc_values], legend_list=[])
plotter.plt.show()
| [
"jorge7soccer@gmail.com"
] | jorge7soccer@gmail.com |
3e4a8653ecc75f1f157f55c060ab43aaddc1ebc2 | 780a52dfb9d3465243e916861aae6a78ae54ae8c | /templates/mysql_config.py | 8d0e7659cc21bdf319b05ab199f39ce600d8ae6c | [] | no_license | yx287618817/NewSchoolSystem | 6eae2c61ac3323fb65d86a10d5b37f13417be905 | 740f99ce59f829b578cef622f9adc2e0b84abb0e | refs/heads/master | 2022-12-15T19:56:21.485873 | 2019-09-05T09:53:34 | 2019-09-05T09:53:34 | 182,994,152 | 0 | 1 | null | 2022-12-08T05:04:56 | 2019-04-23T10:45:38 | JavaScript | UTF-8 | Python | false | false | 230 | py | # -*- coding: utf-8 -*-
# @Time : 2019-05-22 08:57
# @Author : Paul
# @Email : 287618817@qq.com
# @File : sql.config.py
# @Software: PyCharm
LOCALHOST = 'localhost'
USER = 'root'
PASSWORD = 'yx123456'
DATABASE = 'School' | [
"287618817@qq.com"
] | 287618817@qq.com |
337d27c4666d08ff02e5ac3fb7470dae4cbe5a9c | 2e682fd72e3feaa70e3f7bf2a3b83c50d783ec02 | /PyTorch/contrib/cv/detection/SSD/mmdet/models/roi_heads/point_rend_roi_head.py | 3642628ea91a376a39ce5e5813e50509d0ea712a | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later"
] | permissive | Ascend/ModelZoo-PyTorch | 4c89414b9e2582cef9926d4670108a090c839d2d | 92acc188d3a0f634de58463b6676e70df83ef808 | refs/heads/master | 2023-07-19T12:40:00.512853 | 2023-07-17T02:48:18 | 2023-07-17T02:48:18 | 483,502,469 | 23 | 6 | Apache-2.0 | 2022-10-15T09:29:12 | 2022-04-20T04:11:18 | Python | UTF-8 | Python | false | false | 10,905 | py | # Copyright 2021 Huawei Technologies Co., Ltd
#
# 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.
# Modified from https://github.com/facebookresearch/detectron2/tree/master/projects/PointRend # noqa
import torch
import torch.nn.functional as F
from mmcv.ops import point_sample, rel_roi_point_to_rel_img_point
from mmdet.core import bbox2roi, bbox_mapping, merge_aug_masks
from .. import builder
from ..builder import HEADS
from .standard_roi_head import StandardRoIHead
@HEADS.register_module()
class PointRendRoIHead(StandardRoIHead):
"""`PointRend <https://arxiv.org/abs/1912.08193>`_."""
def __init__(self, point_head, *args, **kwargs):
super().__init__(*args, **kwargs)
assert self.with_bbox and self.with_mask
self.init_point_head(point_head)
def init_point_head(self, point_head):
"""Initialize ``point_head``"""
self.point_head = builder.build_head(point_head)
def init_weights(self, pretrained):
"""Initialize the weights in head.
Args:
pretrained (str, optional): Path to pre-trained weights.
"""
super().init_weights(pretrained)
self.point_head.init_weights()
def _mask_forward_train(self, x, sampling_results, bbox_feats, gt_masks,
img_metas):
"""Run forward function and calculate loss for mask head and point head
in training."""
mask_results = super()._mask_forward_train(x, sampling_results,
bbox_feats, gt_masks,
img_metas)
if mask_results['loss_mask'] is not None:
loss_point = self._mask_point_forward_train(
x, sampling_results, mask_results['mask_pred'], gt_masks,
img_metas)
mask_results['loss_mask'].update(loss_point)
return mask_results
def _mask_point_forward_train(self, x, sampling_results, mask_pred,
gt_masks, img_metas):
"""Run forward function and calculate loss for point head in
training."""
pos_labels = torch.cat([res.pos_gt_labels for res in sampling_results])
rel_roi_points = self.point_head.get_roi_rel_points_train(
mask_pred, pos_labels, cfg=self.train_cfg)
rois = bbox2roi([res.pos_bboxes for res in sampling_results])
fine_grained_point_feats = self._get_fine_grained_point_feats(
x, rois, rel_roi_points, img_metas)
coarse_point_feats = point_sample(mask_pred, rel_roi_points)
mask_point_pred = self.point_head(fine_grained_point_feats,
coarse_point_feats)
mask_point_target = self.point_head.get_targets(
rois, rel_roi_points, sampling_results, gt_masks, self.train_cfg)
loss_mask_point = self.point_head.loss(mask_point_pred,
mask_point_target, pos_labels)
return loss_mask_point
def _get_fine_grained_point_feats(self, x, rois, rel_roi_points,
img_metas):
"""Sample fine grained feats from each level feature map and
concatenate them together."""
num_imgs = len(img_metas)
fine_grained_feats = []
for idx in range(self.mask_roi_extractor.num_inputs):
feats = x[idx]
spatial_scale = 1. / float(
self.mask_roi_extractor.featmap_strides[idx])
point_feats = []
for batch_ind in range(num_imgs):
# unravel batch dim
feat = feats[batch_ind].unsqueeze(0)
inds = (rois[:, 0].long() == batch_ind)
if inds.any():
rel_img_points = rel_roi_point_to_rel_img_point(
rois[inds], rel_roi_points[inds], feat.shape[2:],
spatial_scale).unsqueeze(0)
point_feat = point_sample(feat, rel_img_points)
point_feat = point_feat.squeeze(0).transpose(0, 1)
point_feats.append(point_feat)
fine_grained_feats.append(torch.cat(point_feats, dim=0))
return torch.cat(fine_grained_feats, dim=1)
def _mask_point_forward_test(self, x, rois, label_pred, mask_pred,
img_metas):
"""Mask refining process with point head in testing."""
refined_mask_pred = mask_pred.clone()
for subdivision_step in range(self.test_cfg.subdivision_steps):
refined_mask_pred = F.interpolate(
refined_mask_pred,
scale_factor=self.test_cfg.scale_factor,
mode='bilinear',
align_corners=False)
# If `subdivision_num_points` is larger or equal to the
# resolution of the next step, then we can skip this step
num_rois, channels, mask_height, mask_width = \
refined_mask_pred.shape
if (self.test_cfg.subdivision_num_points >=
self.test_cfg.scale_factor**2 * mask_height * mask_width
and
subdivision_step < self.test_cfg.subdivision_steps - 1):
continue
point_indices, rel_roi_points = \
self.point_head.get_roi_rel_points_test(
refined_mask_pred, label_pred, cfg=self.test_cfg)
fine_grained_point_feats = self._get_fine_grained_point_feats(
x, rois, rel_roi_points, img_metas)
coarse_point_feats = point_sample(mask_pred, rel_roi_points)
mask_point_pred = self.point_head(fine_grained_point_feats,
coarse_point_feats)
point_indices = point_indices.unsqueeze(1).expand(-1, channels, -1)
refined_mask_pred = refined_mask_pred.reshape(
num_rois, channels, mask_height * mask_width)
refined_mask_pred = refined_mask_pred.scatter_(
2, point_indices, mask_point_pred)
refined_mask_pred = refined_mask_pred.view(num_rois, channels,
mask_height, mask_width)
return refined_mask_pred
def simple_test_mask(self,
x,
img_metas,
det_bboxes,
det_labels,
rescale=False):
"""Obtain mask prediction without augmentation."""
ori_shapes = tuple(meta['ori_shape'] for meta in img_metas)
scale_factors = tuple(meta['scale_factor'] for meta in img_metas)
num_imgs = len(det_bboxes)
if all(det_bbox.shape[0] == 0 for det_bbox in det_bboxes):
segm_results = [[[] for _ in range(self.mask_head.num_classes)]
for _ in range(num_imgs)]
else:
# if det_bboxes is rescaled to the original image size, we need to
# rescale it back to the testing scale to obtain RoIs.
if rescale and not isinstance(scale_factors[0], float):
scale_factors = [
torch.from_numpy(scale_factor).to(det_bboxes[0].device)
for scale_factor in scale_factors
]
_bboxes = [
det_bboxes[i][:, :4] *
scale_factors[i] if rescale else det_bboxes[i][:, :4]
for i in range(len(det_bboxes))
]
mask_rois = bbox2roi(_bboxes)
mask_results = self._mask_forward(x, mask_rois)
# split batch mask prediction back to each image
mask_pred = mask_results['mask_pred']
num_mask_roi_per_img = [len(det_bbox) for det_bbox in det_bboxes]
mask_preds = mask_pred.split(num_mask_roi_per_img, 0)
mask_rois = mask_rois.split(num_mask_roi_per_img, 0)
# apply mask post-processing to each image individually
segm_results = []
for i in range(num_imgs):
if det_bboxes[i].shape[0] == 0:
segm_results.append(
[[] for _ in range(self.mask_head.num_classes)])
else:
x_i = [xx[[i]] for xx in x]
mask_rois_i = mask_rois[i]
mask_rois_i[:, 0] = 0 # TODO: remove this hack
mask_pred_i = self._mask_point_forward_test(
x_i, mask_rois_i, det_labels[i], mask_preds[i],
[img_metas])
segm_result = self.mask_head.get_seg_masks(
mask_pred_i, _bboxes[i], det_labels[i], self.test_cfg,
ori_shapes[i], scale_factors[i], rescale)
segm_results.append(segm_result)
return segm_results
def aug_test_mask(self, feats, img_metas, det_bboxes, det_labels):
"""Test for mask head with test time augmentation."""
if det_bboxes.shape[0] == 0:
segm_result = [[] for _ in range(self.mask_head.num_classes)]
else:
aug_masks = []
for x, img_meta in zip(feats, img_metas):
img_shape = img_meta[0]['img_shape']
scale_factor = img_meta[0]['scale_factor']
flip = img_meta[0]['flip']
_bboxes = bbox_mapping(det_bboxes[:, :4], img_shape,
scale_factor, flip)
mask_rois = bbox2roi([_bboxes])
mask_results = self._mask_forward(x, mask_rois)
mask_results['mask_pred'] = self._mask_point_forward_test(
x, mask_rois, det_labels, mask_results['mask_pred'],
img_metas)
# convert to numpy array to save memory
aug_masks.append(
mask_results['mask_pred'].sigmoid().cpu().numpy())
merged_masks = merge_aug_masks(aug_masks, img_metas, self.test_cfg)
ori_shape = img_metas[0][0]['ori_shape']
segm_result = self.mask_head.get_seg_masks(
merged_masks,
det_bboxes,
det_labels,
self.test_cfg,
ori_shape,
scale_factor=1.0,
rescale=False)
return segm_result
| [
"wangjiangben@huawei.com"
] | wangjiangben@huawei.com |
0efbe9bfb390808b69847c11b125982b045933b4 | d1ec629354ba7ee6f0187ce60b0cdab1cc680a7b | /retinanet/model.py | 61ecaa2ec3db78be8f29087eb7282437ee76d015 | [] | no_license | albatro-vm/apiepp | 48fc255e30e12d5617c204b69ca87f79c7bcb16d | 05a1b35aede8bac50cdbea40bc82e4a6890471e8 | refs/heads/main | 2023-08-12T19:12:30.675571 | 2021-10-15T00:44:55 | 2021-10-15T00:44:55 | 403,156,470 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 130 | py | version https://git-lfs.github.com/spec/v1
oid sha256:ab4175c56ab7ddbef2da78e9d2472af7685828fafb500fdd83bfb8717781a0a4
size 13050
| [
"liamoreno14@gmail.com"
] | liamoreno14@gmail.com |
8d62902da0b74f4b028f6b0033e8d4d333a9e97d | 97d1d43e232ece771ffcba6bd3f634df39d9417f | /multiagent/multiAgents.py | 7148717f20b970649b0795e616af4bbc5fc0af73 | [] | no_license | Ain2211/pacman-Multi-Agent-Search | d681ebe0b20fb46df2a2c9dd768575c40e420e74 | f69ebe4109bc93fb364505071ce0b33985d10ce2 | refs/heads/main | 2022-12-28T07:29:54.149047 | 2020-10-16T10:21:26 | 2020-10-16T10:21:26 | 304,528,285 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,431 | py | # multiAgents.py
# --------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
from util import manhattanDistance
from game import Directions
import random, util
from game import Agent
class ReflexAgent(Agent):
"""
A reflex agent chooses an action at each choice point by examining
its alternatives via a state evaluation function.
The code below is provided as a guide. You are welcome to change
it in any way you see fit, so long as you don't touch our method
headers.
"""
def getAction(self, gameState):
"""
You do not need to change this method, but you're welcome to.
getAction chooses among the best options according to the evaluation function.
Just like in the previous project, getAction takes a GameState and returns
some Directions.X for some X in the set {North, South, West, East, Stop}
"""
# Collect legal moves and successor states
legalMoves = gameState.getLegalActions()
# Choose one of the best actions
scores = [self.evaluationFunction(gameState, action) for action in legalMoves]
bestScore = max(scores)
bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]
chosenIndex = random.choice(bestIndices) # Pick randomly among the best
"Add more of your code here if you want to"
return legalMoves[chosenIndex]
def evaluationFunction(self, currentGameState, action):
"""
Design a better evaluation function here.
The evaluation function takes in the current and proposed successor
GameStates (pacman.py) and returns a number, where higher numbers are better.
The code below extracts some useful information from the state, like the
remaining food (newFood) and Pacman position after moving (newPos).
newScaredTimes holds the number of moves that each ghost will remain
scared because of Pacman having eaten a power pellet.
Print out these variables to see what you're getting, then combine them
to create a masterful evaluation function.
"""
# Useful information you can extract from a GameState (pacman.py)
successorGameState = currentGameState.generatePacmanSuccessor(action)
newPos = successorGameState.getPacmanPosition()
newFood = successorGameState.getFood()
newGhostStates = successorGameState.getGhostStates()
newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates]
"*** YOUR CODE HERE ***"
currentPos = list(successorGameState.getPacmanPosition())
min = 999999999
dist = 0
currentFood = currentGameState.getFood()
foodList = currentFood.asList()
for i in range(len(foodList)):
dist = (manhattanDistance(foodList[i], currentPos))
if dist < min:
min = dist
min = -min
for state in newGhostStates:
if state.scaredTimer == 0 and state.getPosition() == tuple(currentPos):
return -999999999
if action == 'Stop':
return -999999999
return min
def scoreEvaluationFunction(currentGameState):
"""
This default evaluation function just returns the score of the state.
The score is the same one displayed in the Pacman GUI.
This evaluation function is meant for use with adversarial search agents
(not reflex agents).
"""
return currentGameState.getScore()
class MultiAgentSearchAgent(Agent):
"""
This class provides some common elements to all of your
multi-agent searchers. Any methods defined here will be available
to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent.
You *do not* need to make any changes here, but you can if you want to
add functionality to all your adversarial search agents. Please do not
remove anything, however.
Note: this is an abstract class: one that should not be instantiated. It's
only partially specified, and designed to be extended. Agent (game.py)
is another abstract class.
"""
def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'):
self.index = 0 # Pacman is always agent index 0
self.evaluationFunction = util.lookup(evalFn, globals())
self.depth = int(depth)
class MinimaxAgent(MultiAgentSearchAgent):
"""
Your minimax agent (question 2)
"""
def getAction(self, gameState):
"""
Returns the minimax action from the current gameState using self.depth
and self.evaluationFunction.
Here are some method calls that might be useful when implementing minimax.
gameState.getLegalActions(agentIndex):
Returns a list of legal actions for an agent
agentIndex=0 means Pacman, ghosts are >= 1
gameState.generateSuccessor(agentIndex, action):
Returns the successor game state after an agent takes an action
gameState.getNumAgents():
Returns the total number of agents in the game
"""
cost, action = self.getMaxValue(gameState, 0)
return action
def getMaxValue(self, gameState, depth, agent = 0):
actions = gameState.getLegalActions(agent)
if not actions or gameState.isWin() or depth >= self.depth:
return self.evaluationFunction(gameState), Directions.STOP
bestCost = float('-inf')
bestAction = Directions.STOP
for action in actions:
successor = gameState.generateSuccessor(agent, action)
cost = self.getMinValue(successor, depth, agent + 1)[0]
if cost > bestCost:
bestCost = cost
bestAction = action
return bestCost, bestAction
def getMinValue(self, gameState, depth, agent):
actions = gameState.getLegalActions(agent)
if not actions or gameState.isLose() or depth >= self.depth:
return self.evaluationFunction(gameState), Directions.STOP
bestCost = float('inf')
bestAction = Directions.STOP
for action in actions:
successor = gameState.generateSuccessor(agent, action)
cost = 0
if agent == gameState.getNumAgents() - 1:
cost = self.getMaxValue(successor, depth + 1)[0]
else:
cost = self.getMinValue(successor, depth, agent + 1)[0]
if cost < bestCost:
bestCost = cost
bestAction = action
return bestCost, bestAction
class AlphaBetaAgent(MultiAgentSearchAgent):
"""
Your minimax agent with alpha-beta pruning (question 3)
"""
def getAction(self, gameState):
"""
Returns the minimax action using self.depth and self.evaluationFunction
"""
cost , action = self.getMaxValue(gameState, float('-inf'), float('inf'), 0)
return action
def getMaxValue(self, gameState, alpha, beta, depth, agent = 0):
actions = gameState.getLegalActions(agent)
if not actions or gameState.isWin() or depth >= self.depth:
return self.evaluationFunction(gameState), Directions.STOP
bestCost = float('-inf')
bestAction = Directions.STOP
for action in actions:
successor = gameState.generateSuccessor(agent, action)
cost = self.getMinValue(successor, alpha, beta, depth, agent + 1)[0]
if cost > bestCost:
bestCost = cost
bestAction = action
if bestCost > beta:
return bestCost, bestAction
alpha = max(alpha, bestCost)
return bestCost, bestAction
def getMinValue(self, gameState, alpha, beta, depth, agent):
actions = gameState.getLegalActions(agent)
if not actions or gameState.isLose() or depth >= self.depth:
return self.evaluationFunction(gameState), Directions.STOP
bestCost = float('inf')
bestAction = Directions.STOP
for action in actions:
successor = gameState.generateSuccessor(agent, action)
cost = 0
if agent == gameState.getNumAgents() - 1:
cost = self.getMaxValue(successor, alpha, beta, depth + 1)[0]
else:
cost = self.getMinValue(successor, alpha, beta, depth, agent + 1)[0]
if cost < bestCost:
bestCost = cost
bestAction = action
if bestCost < alpha:
return bestCost, bestAction
beta = min(beta, bestCost)
return bestCost, bestAction
class ExpectimaxAgent(MultiAgentSearchAgent):
"""
Your expectimax agent (question 4)
"""
def getAction(self, gameState):
"""
Returns the minimax action from the current gameState using self.depth
and self.evaluationFunction.
Here are some method calls that might be useful when implementing minimax.
gameState.getLegalActions(agentIndex):
Returns a list of legal actions for an agent
agentIndex=0 means Pacman, ghosts are >= 1
gameState.generateSuccessor(agentIndex, action):
Returns the successor game state after an agent takes an action
gameState.getNumAgents():
Returns the total number of agents in the game
"""
cost, action = self.getMaxValue(gameState, 0)
return action
def getMaxValue(self, gameState, depth, agent = 0):
actions = gameState.getLegalActions(agent)
if not actions or gameState.isWin() or depth >= self.depth:
return self.evaluationFunction(gameState), Directions.STOP
bestCost = float('-inf')
bestAction = Directions.STOP
for action in actions:
successor = gameState.generateSuccessor(agent, action)
cost = self.getMinValue(successor, depth, agent + 1)[0]
if cost > bestCost:
bestCost = cost
bestAction = action
return bestCost, bestAction
def getMinValue(self, gameState, depth, agent):
actions = gameState.getLegalActions(agent)
if not actions or gameState.isLose() or depth >= self.depth:
return self.evaluationFunction(gameState), Directions.STOP
bestCost = []
for action in actions:
successor = gameState.generateSuccessor(agent, action)
cost = 0
if agent == gameState.getNumAgents() - 1:
cost = self.getMaxValue(successor, depth + 1)[0]
else:
cost = self.getMinValue(successor, depth, agent + 1)[0]
bestCost.append(cost)
return sum(bestCost)/ float(len(bestCost)), None
def betterEvaluationFunction(currentGameState):
"""
Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable
evaluation function (question 5).
DESCRIPTION: <write something here so we know what you did>
"""
"*** YOUR CODE HERE ***"
newPos = currentGameState.getPacmanPosition()
newFood = currentGameState.getFood()
newGhostStates = currentGameState.getGhostStates()
foodList = newFood.asList()
score = currentGameState.getScore()
foodD = []
ghostD = []
for food in foodList:
foodD.append(manhattanDistance(newPos, food))
for ghost in newGhostStates:
ghostD.append(manhattanDistance(newPos, ghost.getPosition()))
if ghost.scaredTimer == 0:
if len(foodD) != 0:
score -= min(foodD)
if len(ghostD) != 0:
score += min(ghostD)
return score
# Abbreviation
better = betterEvaluationFunction
| [
"tuanh221120@gmail.com"
] | tuanh221120@gmail.com |
a8639e979db7d895673d5f6b9e4d845b351e3782 | dac57de9c28700ebacc25331d5ff04dec129b74b | /MxOnline/users/adminx.py | 59f3b2e3d6b9d7bc1ab58c529d848aaef9f1bd53 | [] | no_license | zmm064/Django- | 08144522ef9afcc3d85c11faa848554282fc6fcd | 1f8836ebb4902a738efc6c626ab10aa91fdde720 | refs/heads/master | 2021-08-09T03:00:01.049464 | 2017-11-12T01:52:34 | 2017-11-12T01:52:34 | 110,396,352 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 931 | py | import xadmin
from xadmin import views
from .models import EmailVerifyRecord, Banner
class BaseSetting:
enable_themes = True
use_bootswatch = True
class GlobalSettings:
site_title = "慕学后台管理系统"
site_footer = "慕学在线网"
menu_style = "accordion"
class EmailVerifyRecordAdmin:
list_display = ['code', 'email', 'send_type', 'send_time']
list_filter = ['code', 'email', 'send_type', 'send_time']
search_fields = ['code', 'email', 'send_type']
class BannerAdmin:
list_display = ['title', 'image', 'url', 'index', 'add_time']
list_filter = ['title', 'image', 'url', 'index', 'add_time']
search_fields = ['title', 'image', 'url', 'index']
xadmin.site.register(EmailVerifyRecord, EmailVerifyRecordAdmin)
xadmin.site.register(Banner, BannerAdmin)
xadmin.site.register(views.BaseAdminView, BaseSetting)
xadmin.site.register(views.CommAdminView, GlobalSettings)
| [
"zmm064@foxmail.com"
] | zmm064@foxmail.com |
0b9fdfc19478cd3711fb29d2dcfef928d5c522aa | f67dec556fe0dddc0be1cf28c44964425ee38019 | /venv/lib/python3.7/types.py | b685ab0b6897f18501ae1598f2ada4d95cbdb929 | [] | no_license | AdamC66/July-18--Avoiding-Bugs-with-Linters | 3b3a050227ee7865373adec6084a16fdc21334e7 | 1a5060efc23774941606b7c70a0ec56599f4ab39 | refs/heads/master | 2020-06-22T02:06:14.023492 | 2019-07-18T14:52:12 | 2019-07-18T14:52:12 | 197,469,940 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 54 | py | /home/oem/.pyenv/versions/3.7.3/lib/python3.7/types.py | [
"adam.cote66@gmail.com"
] | adam.cote66@gmail.com |
463d4a3035c7536df43458eb4be4d53450af98d3 | 5fee6afe91711fbb1ca87845f502776fbfab7851 | /examples/pymanopt_autograd_demo.py | 1761abe78a82061ff7149582fca5d90df8e0d786 | [
"MIT"
] | permissive | chenxofhit/pyprobml | f66ad4c1186f0ba22e520e14700ac0bd6fee400d | fe48d6111bd121e01cfbdefe3361a993fa14abe1 | refs/heads/master | 2021-01-24T09:39:29.828935 | 2016-09-17T03:34:59 | 2016-09-17T03:34:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 290 | py | #https://github.com/pymanopt/pymanopt/blob/master/pymanopt/core/problem.py
import autograd.numpy as np
from pymanopt import Problem
def cost(theta):
return np.square(theta)
problem = Problem(manifold=None, cost=cost, verbosity=1)
print problem.cost(5)
print problem.egrad(5.0) | [
"murphyk@gmail.com"
] | murphyk@gmail.com |
da15cd852366822a8d3987b0d3e6a408da6dceb7 | 61757ba1effd7b876a33db63aa5755d55753e2fe | /tool.py | 9890bd352f95e93a7ed0e0743fa49e00bbba9002 | [] | no_license | lotus0099/backup-blog | b06b3d8e6e4f36aae60370be3aa0821edcc0b5e7 | 05fe9dd57c20710b1a5073f88c67152ad8ef31ca | refs/heads/master | 2021-08-22T15:48:09.780591 | 2017-11-30T15:11:28 | 2017-11-30T15:11:28 | 112,496,086 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,020 | py | #coding: utf-8
from PIL import Image
import qiniu
import os
import sys
import json
from datetime import datetime
from ImageProcess import Graphics
# 定义压缩比,数值越大,压缩越小
SIZE_normal = 1.0
SIZE_small = 1.5
SIZE_more_small = 2.0
SIZE_more_small_small = 3.0
def make_directory(directory):
"""创建目录"""
os.makedirs(directory)
def directory_exists(directory):
"""判断目录是否存在"""
if os.path.exists(directory):
return True
else:
return False
def list_img_file(directory):
"""列出目录下所有文件,并筛选出图片文件列表返回"""
old_list = os.listdir(directory)
# print old_list
new_list = []
for filename in old_list:
name, fileformat = filename.split(".")
if fileformat.lower() == "jpg" or fileformat.lower() == "png" or fileformat.lower() == "gif":
new_list.append(filename)
# print new_list
return new_list
def print_help():
print("""
This program helps compress many image files
you can choose which scale you want to compress your img(jpg/png/etc)
1) normal compress(4M to 1M around)
2) small compress(4M to 500K around)
3) smaller compress(4M to 300K around)
""")
def compress(choose, des_dir, src_dir, file_list):
"""压缩算法,img.thumbnail对图片进行压缩,
参数
-----------
choose: str
选择压缩的比例,有4个选项,越大压缩后的图片越小
"""
if choose == '1':
scale = SIZE_normal
if choose == '2':
scale = SIZE_small
if choose == '3':
scale = SIZE_more_small
if choose == '4':
scale = SIZE_more_small_small
for infile in file_list:
img = Image.open(src_dir+infile)
# size_of_file = os.path.getsize(infile)
w, h = img.size
img.thumbnail((int(w/scale), int(h/scale)))
img.save(des_dir + infile)
def compress_photo():
'''调用压缩图片的函数
'''
src_dir, des_dir = "photos/", "min_photos/"
if directory_exists(src_dir):
if not directory_exists(src_dir):
make_directory(src_dir)
# business logic
file_list_src = list_img_file(src_dir)
if directory_exists(des_dir):
if not directory_exists(des_dir):
make_directory(des_dir)
file_list_des = list_img_file(des_dir)
# print file_list
'''如果已经压缩了,就不再压缩'''
for i in range(len(file_list_des)):
if file_list_des[i] in file_list_src:
file_list_src.remove(file_list_des[i])
compress('4', des_dir, src_dir, file_list_src)
def handle_photo():
'''根据图片的文件名处理成需要的json格式的数据
-----------
最后将data.json文件存到博客的source/photos文件夹下
'''
src_dir, des_dir = "photos/", "min_photos/"
file_list = list_img_file(src_dir)
list_info = []
for i in range(len(file_list)):
filename = file_list[i]
date_str, info = filename.split("_")
info, _ = info.split(".")
date = datetime.strptime(date_str, "%Y-%m-%d")
year_month = date_str[0:7]
if i == 0: # 处理第一个文件
new_dict = {"date": year_month, "arr":{'year': date.year,
'month': date.month,
'link': [filename],
'text': [info],
'type': ['image']
}
}
list_info.append(new_dict)
elif year_month != list_info[-1]['date']: # 不是最后的一个日期,就新建一个dict
new_dict = {"date": year_month, "arr":{'year': date.year,
'month': date.month,
'link': [filename],
'text': [info],
'type': ['image']
}
}
list_info.append(new_dict)
else: # 同一个日期
list_info[-1]['arr']['link'].append(filename)
list_info[-1]['arr']['text'].append(info)
list_info[-1]['arr']['type'].append('image')
list_info.reverse() # 翻转
final_dict = {"list": list_info}
with open("./source/photos/data.json","w") as fp:
json.dump(final_dict, fp)
def cut_photo():
"""裁剪算法
----------
调用Graphics类中的裁剪算法,将src_dir目录下的文件进行裁剪(裁剪成正方形)
"""
src_dir = "photos/"
if directory_exists(src_dir):
if not directory_exists(src_dir):
make_directory(src_dir)
# business logic
file_list = list_img_file(src_dir)
# print file_list
if file_list:
print_help()
for infile in file_list:
img = Image.open(src_dir+infile)
Graphics(infile=src_dir+infile, outfile=src_dir + infile).cut_by_ratio()
else:
pass
else:
print("source directory not exist!")
def git_operation():
'''
git 命令行函数,将仓库提交
----------
需要安装git命令行工具,并且添加到环境变量中
'''
os.system('git add --all')
os.system('git commit -m "add photos"')
os.system('git push origin master')
if __name__ == "__main__":
cut_photo() # 裁剪图片,裁剪成正方形,去中间部分
compress_photo() # 压缩图片,并保存到mini_photos文件夹下
git_operation() # 提交到github仓库
handle_photo() # 将文件处理成json格式,存到博客仓库中
| [
"lvdeshi2011@gmail.com"
] | lvdeshi2011@gmail.com |
c205d9ebfe6ca44bdca6e70d2161a94a246b4998 | be1fe5c3eeea0f83aa24d3e6c5fa1739fe3974e4 | /src/dtgui/tables.py | d0678c8524cecda9061387de039296e81ba9ae18 | [] | no_license | rofl0r/dro-trimmer | 03da573ae25c749ac8cba7668b72bbaddde5bbad | 6fcf6f960b17a4da84ae4a86a589a5c935bb4993 | refs/heads/master | 2023-02-21T07:57:54.323313 | 2017-11-04T00:52:03 | 2017-11-04T00:52:03 | 332,579,433 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,013 | py | #!/usr/bin/python
#
# Use, distribution, and modification of the DRO Trimmer binaries, source code,
# or documentation, is subject to the terms of the MIT license, as below.
#
# Copyright (c) 2008 - 2014 Laurence Dougal Myers
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import wx
class DTSongDataList(wx.ListCtrl):
def __init__(self, parent, drosong):
"""
@type drosong: DROSong
"""
wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER|wx.LC_VIRTUAL|wx.VSCROLL)
self.drosong = drosong
self.parent = parent
self.SetItemCount(self.GetItemCount()) # not as dumb as it looks. Because it's virtual, need to calculate the item count.
self.CreateColumns()
self.RegisterEvents()
def CreateColumns(self):
self.InsertColumn(0, "Pos.")
self.InsertColumn(1, "Bank")
self.InsertColumn(2, "Reg.")
self.InsertColumn(3, "Value")
self.InsertColumn(4, "Description")
self.InsertColumn(5, "Description (all register options)")
parent = self.GetParent()
self.SetColumnWidth(0, parent.GetCharWidth() * 10)
self.SetColumnWidth(1, parent.GetCharWidth() * 7)
self.SetColumnWidth(2, parent.GetCharWidth() * 8)
self.SetColumnWidth(3, parent.GetCharWidth() * 13)
self.SetColumnWidth(4, parent.GetCharWidth() * 70)
self.SetColumnWidth(5, parent.GetCharWidth() * 70)
def OnGetItemText(self, item, column):
# Possible TODO: split the description into sub-components
# eg for "Tremolo / Vibrato / Sustain / KSR / Frequency Multiplication Factor"
# (can't use bitmask because we may be disabling items - could possibly be solved by
# keeping track of register changes/state when loading the song)
if self.drosong is None:
return ""
if column == 0:
return str(item).zfill(4) + ">"
# Bank
elif column == 1:
return self.drosong.get_bank_description(item)
# Register
elif column == 2:
return self.drosong.get_register_display(item)
# Value
elif column == 3:
return self.drosong.get_value_display(item)
# Description
elif column == 4:
return self.drosong.get_detailed_register_description(item)
# Description (all register options)
elif column == 5:
return self.drosong.get_instruction_description(item)
def GetItemCount(self):
if self.drosong is None:
return 0
return self.drosong.getLengthData()
def GetLastSelected(self):
if not self.HasSelected():
return None
item = self.GetFirstSelected()
last_item = None
while item != -1:
last_item = item
item = self.GetNextSelected(item)
return last_item
def SelectItemManual(self, ind):
self.Select(ind, 1) # select
self.Focus(ind)
def SelectNextItem(self):
oldsel = self.GetLastSelected()
if oldsel is not None and oldsel < self.GetItemCount() - 1:
self.Deselect()
self.SelectItemManual(oldsel + 1)
# scroll if we're getting too near the bottom of the view
if oldsel + 1 >= (self.GetTopItem() + self.GetCountPerPage() - 2):
self.ScrollLines(1)
def CreateList(self, insong):
""" Regenerates the list based on data from a DROSong object. Takes a DROSong object.
@type insong: DROSong"""
self.DeleteAllItems()
if self.HasSelected():
self.Deselect()
self.drosong = insong
self.SetItemCount(self.GetItemCount())
self.RefreshViewableItems()
def Deselect(self):
item = self.GetFirstSelected()
while item != -1:
self.Select(item, 0)
item = self.GetNextSelected(item)
def RefreshViewableItems(self):
""" Updates items from the index of the topmost visible item to the index of the topmost visible item plus the number of items visible."""
first_index = self.GetTopItem()
last_index = min(self.GetTopItem() + self.GetCountPerPage(), self.GetItemCount() - 1)
self.RefreshItems(first_index, last_index) #redraw
def RefreshItemCount(self):
self.SetItemCount(self.GetItemCount())
def RegisterEvents(self):
#wx.EVT_LIST_ITEM_SELECTED(self, -1, self.SelectItem)
pass
def HasSelected(self):
return self.GetSelectedItemCount() > 0
def GetAllSelected(self):
sel_items = []
item = self.GetFirstSelected()
while item != -1:
sel_items.append(item)
item = self.GetNextSelected(item)
return sel_items
| [
"laurencedougalmyers@gmail.com"
] | laurencedougalmyers@gmail.com |
c89dd05b450410234b2a9964c70453cd420d4db4 | c6dd05439afbf7763bf6d01cd924d564ca0e5348 | /wrappers/python3/LongMult/AddTogether.py | ceb438595087cc6bf322fc880013742c8b50a086 | [] | no_license | jherrero/ensembl-hive | c232ee0236153ace61091da185c75a035c4eb034 | 31869d945230f89f1d7656041491662f157e99a5 | refs/heads/master | 2020-12-06T19:13:54.510300 | 2015-09-18T10:45:10 | 2015-09-18T10:45:10 | 15,343,860 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,436 | py |
import eHive
import time
class AddTogether(eHive.BaseRunnable):
"""Runnable that adds up all the partial-multiplications from PartMultiply"""
def param_defaults(self):
return {
'take_time' : 0,
'partial_product' : {}
}
def fetch_input(self):
a_multiplier = self.param_required('a_multiplier')
partial_product = self.param('partial_product')
print(partial_product)
partial_product['1'] = str(a_multiplier)
partial_product['0'] = '0'
def run(self):
b_multiplier = self.param_required('b_multiplier')
partial_product = self.param('partial_product')
self.param('result', add_together(b_multiplier, partial_product))
time.sleep( self.param('take_time') )
def write_output(self):
self.dataflow( { 'result': self.param('result') }, 1)
def add_together(b_multiplier, partial_product):
b_multiplier = str(b_multiplier)
accu = [0] * (1 + len(b_multiplier) + len(partial_product['1']))
for (i,b_digit) in enumerate(reversed(b_multiplier)):
product = str(partial_product[b_digit])
for (j,p_digit) in enumerate(reversed(product)):
accu[i+j] += int(p_digit)
carry = 0
for i in range(len(accu)):
val = carry + accu[i]
accu[i] = val % 10
carry = val // 10
return ''.join(str(_) for _ in reversed(accu)).lstrip('0')
1;
| [
"muffato@ebi.ac.uk"
] | muffato@ebi.ac.uk |
eaca63e5e424fa56715f10e05ddfbe09b2ff2f4c | 44064ed79f173ddca96174913910c1610992b7cb | /Second_Processing_app/temboo/Library/RunKeeper/Weight/UpdateEntry.py | e7d943997a26bf0fc309b517c6fea8f1ba7349e6 | [] | no_license | dattasaurabh82/Final_thesis | 440fb5e29ebc28dd64fe59ecd87f01494ed6d4e5 | 8edaea62f5987db026adfffb6b52b59b119f6375 | refs/heads/master | 2021-01-20T22:25:48.999100 | 2014-10-14T18:58:00 | 2014-10-14T18:58:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,005 | py | # -*- coding: utf-8 -*-
###############################################################################
#
# UpdateEntry
# Updates a weight entry in a user’s feed.
#
# Python version 2.6
#
###############################################################################
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class UpdateEntry(Choreography):
def __init__(self, temboo_session):
"""
Create a new instance of the UpdateEntry Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
"""
Choreography.__init__(self, temboo_session, '/Library/RunKeeper/Weight/UpdateEntry')
def new_input_set(self):
return UpdateEntryInputSet()
def _make_result_set(self, result, path):
return UpdateEntryResultSet(result, path)
def _make_execution(self, session, exec_id, path):
return UpdateEntryChoreographyExecution(session, exec_id, path)
class UpdateEntryInputSet(InputSet):
"""
An InputSet with methods appropriate for specifying the inputs to the UpdateEntry
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
"""
def set_Entry(self, value):
"""
Set the value of the Entry input for this Choreo. ((required, json) A JSON string containing the key/value pairs for the fields to be updated in the weight entry. See documentation for formatting examples.)
"""
InputSet._set_input(self, 'Entry', value)
def set_AccessToken(self, value):
"""
Set the value of the AccessToken input for this Choreo. ((required, string) The Access Token retrieved after the final step in the OAuth2 process.)
"""
InputSet._set_input(self, 'AccessToken', value)
def set_EntryID(self, value):
"""
Set the value of the EntryID input for this Choreo. ((required, string) This can be the individual id of the weight entry, or you can pass the full uri for the entry as returned from the RetrieveEntries Choreo (i.e. /weight/24085455).)
"""
InputSet._set_input(self, 'EntryID', value)
class UpdateEntryResultSet(ResultSet):
"""
A ResultSet with methods tailored to the values returned by the UpdateEntry Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
"""
def getJSONFromString(self, str):
return json.loads(str)
def get_Response(self):
"""
Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from RunKeeper.)
"""
return self._output.get('Response', None)
class UpdateEntryChoreographyExecution(ChoreographyExecution):
def _make_result_set(self, response, path):
return UpdateEntryResultSet(response, path)
| [
"dattasaurabh82@gmail.com"
] | dattasaurabh82@gmail.com |
504fbc42f87d185e7faba42c6ee71c860bcd255f | e5d3968f5cc89e4c66796f9a0ba0621397213a5b | /problem_set_1/exercise1_1.py | 36866a2a955c99241bdb89cf2a8c7b84b655cc7a | [] | no_license | thainv0212/spinningup-exercises | ad34dd1cab8c6ff13fa70f54a7ea1f3ec1d04f72 | b17d2af3131bc40b8edc9649df703fe636e31a81 | refs/heads/master | 2022-03-16T08:14:38.129181 | 2022-02-20T06:56:44 | 2022-02-20T06:56:44 | 209,860,564 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,927 | py | import tensorflow as tf
import numpy as np
"""
Exercise 1.1: Diagonal Gaussian Likelihood
Write a function which takes in Tensorflow symbols for the means and
log stds of a batch of diagonal Gaussian distributions, along with a
Tensorflow placeholder for (previously-generated) samples from those
distributions, and returns a Tensorflow symbol for computing the log
likelihoods of those samples.
"""
def gaussian_likelihood(x, mu, log_std):
"""
Args:
x: Tensor with shape [batch, dim]
mu: Tensor with shape [batch, dim]
log_std: Tensor with shape [batch, dim] or [dim]
Returns:
Tensor with shape [batch]
"""
#######################
# #
# YOUR CODE HERE #
# #
#######################
EPS=1e-8
pre_sum = -0.5 * (((x-mu)/(tf.exp(log_std)+EPS))**2 + 2*log_std + np.log(2*np.pi))
return tf.reduce_sum(pre_sum, axis=1)
if __name__ == '__main__':
"""
Run this file to verify your solution.
"""
from spinup.exercises.problem_set_1_solutions import exercise1_1_soln
from spinup.exercises.common import print_result
sess = tf.Session()
dim = 10
x = tf.placeholder(tf.float32, shape=(None, dim))
mu = tf.placeholder(tf.float32, shape=(None, dim))
log_std = tf.placeholder(tf.float32, shape=(dim,))
your_gaussian_likelihood = gaussian_likelihood(x, mu, log_std)
true_gaussian_likelihood = exercise1_1_soln.gaussian_likelihood(x, mu, log_std)
batch_size = 32
feed_dict = {x: np.random.rand(batch_size, dim),
mu: np.random.rand(batch_size, dim),
log_std: np.random.rand(dim)}
your_result, true_result = sess.run([your_gaussian_likelihood, true_gaussian_likelihood],
feed_dict=feed_dict)
correct = np.allclose(your_result, true_result)
print_result(correct) | [
"nguyenvanthai0212@gmail.com"
] | nguyenvanthai0212@gmail.com |
245e371f161140331b66bbcb3db32a5c16c35c99 | 252bf6d3b1a59e7842acd3bf3101fe03ba05752a | /dao.py | 54e7b8b0e14c5820337527bcb47673b2d8792c5b | [] | no_license | longsion/bigcwxspider | df596d078483508cb4810dc063f5f7562960e55d | 8621e99a9d98bdc8fff58812efa3b8c344daf065 | refs/heads/master | 2020-04-11T20:19:04.030363 | 2017-11-27T03:41:36 | 2017-11-27T03:41:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,572 | py | #! /usr/bin/env python
# coding:utf-8
# author:jzh
# 时间:2015-10-14 10:17
import utils, traceback
def get_schedule_pubnum_id(db):
return db.query("select pubnum_id from wechat_pubnum where last_article_time < %(article_time)s",
article_time=utils.get_middle_night())
def set_pubnum_status(db, pubnum_id, status=0):
return db.update("update wechat_pubnum set status=%(status)s where pubnum_id=%(pubnum_id)s",
pubnum_id=pubnum_id, status=status)
def push_pubnum_to_crawler(db, pubnum_id):
return set_pubnum_status(db, pubnum_id, status=0)
def set_pubnum_to_disable(db, pubnum_id):
return set_pubnum_status(db, pubnum_id, status=2)
def set_pubnum_to_crawlered(db, pubnum_id):
return set_pubnum_status(db, pubnum_id, status=1)
def get_pubnum_by_status(db, status):
return db.query("select pubnum_id, originid, biz from wechat_pubnum where status=%(status)s",
status=status)
def get_wechat_key(db):
return db.get("select * from wechat_key limit 1")
def insert_wechat_key(db, wechat_key):
return db.insert("insert into wechat_key(content) values(%(content)s)",
content=wechat_key)
def update_wechat_key(db, wechat_key):
return db.update("update wechat_key set content=%(content)s",
content=wechat_key)
def upsert_wechat_key(db, key_content):
record = get_wechat_key(db)
if not record:
return insert_wechat_key(db, key_content)
return update_wechat_key(db, key_content)
def get_wechat_article_by_url_md5(db, url_md5):
return db.get('select * from wechat_article where url_md5=%(url_md5)s',
url_md5=url_md5)
def update_pubnum_article_time(db, pubnum_id, article_time):
return db.update("update wechat_pubnum set last_article_time=%(art_time)s where pubnum_id=%(pubnum_id)s",
pubnum_id=pubnum_id, art_time=article_time)
def save_article(db, pubnum_id, art):
try:
return db.insert("insert into wechat_article(pubnum_id, url_md5, content_url, title, "
"author, cover_url, publish_time, create_time) values (%(pubnum_id)s, %(url_md5)s, "
"%(content_url)s, %(title)s, %(author)s, %(cover_url)s, %(publish_time)s, %(create_time)s)",
pubnum_id=pubnum_id, url_md5=art['url_md5'], content_url=art['content_url'],
title=art['title'], author=art['author'], cover_url=art['cover_url'],
publish_time=art['publish_time'], create_time=utils.get_curr_time())
except Exception as e:
print traceback.format_exc()
return False
def get_pubnum_by_originid(db, originid):
return db.get("select * from wechat_pubnum where originid=%(originid)s limit 1",
originid=originid)
def save_wecaht_pubnum(db, p):
try:
return db.insert('insert into wechat_pubnum(wechat_name, nick_name, pic_url,qr_code, originid, '
'biz, status, create_time) values(%(wechat_name)s, %(nick_name)s, %(pic_url)s, '
'%(qr_code)s, %(originid)s, %(biz)s, 0, %(curr_time)s);',
wechat_name=p.get('originid', ''), nick_name=p.get('nick_name',''),
pic_url=p.get('pic_url', ''), qr_code=p.get('qr_code', ''),
originid=p.get('originid', ''), biz=p.get('biz', ''), curr_time=utils.get_curr_time())
except Exception as e:
print traceback.format_exc()
return False | [
"chiwah.keen@gmail.com"
] | chiwah.keen@gmail.com |
6af51bf8cb1672b3a526dc92325dd61f00709985 | 63cbfedc2e6141ae12fc113a81e147e9b5769670 | /Chapt 13/sample2.py | 842aeb8880e4bceca85a07e275a5080323161ffd | [] | no_license | DamoM73/Learn-to-program-in-Python | 82d5fdfbb456186d63aa8ae244e87bf96955ff86 | 44b6b9ffa81735739180dc2055e2e803f4526c79 | refs/heads/master | 2020-04-23T06:51:58.591548 | 2019-04-27T09:16:14 | 2019-04-27T09:16:14 | 170,988,387 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,427 | py | # Program name: Ch 13 Sample app 2 validate password aaaaa.py
# Program askss use to login, then checks password
# in this program password is "aaaaaa"
from tkinter import *
from tkinter import messagebox
def submit():
password = entry_password.get()
username = entry_username.get()
messageAlert = Label(root, width = 30)
messageAlert.grid(row = 3, column = 0, columnspan = 2, padx = 5, pady = 5)
if password != "aaaaaa":
messageAlert.config(text = "Password incorrect")
entry_username.delete(0,"END")
entry_password.delete(0,"END")
entry_username.focus_set()
else:
messageAlert.config(text = "Password accepted")
print("password accepted")
print("Username: ", username)
print("Password: ", password)
messagebox.showinfo(title = "Password Ok", message = "Press OK to continue")
root.destroy()
# display a message box with a hint for password
def hint():
messagebox.showinfo(title = "Password hint", message = "Hint: Try password aaaaaa")
# create main window
root = Tk()
root.geometry("250x180")
root.title("Login Screen")
root.resizable(False,False)
root.configure(background = "Light blue")
# place a frame round labels and user entries
frame_entry = Frame(root, bg = 'Light blue')
frame_entry.grid(row = 0, column = 0, columnspan = 2, padx = 10, pady = 10)
# place a frame around the buttons
frame_buttons = Frame(root, bg = "Light blue")
frame_buttons.grid(row = 2, column = 0, columnspan = 3, padx = 10 , pady = 10)
# place the labels and text entry fields
Label(frame_entry, text = "Enter username: ")\
.grid(row = 0, column = 0, padx = 5, pady = 5)
entry_username = Entry(frame_entry, width = 15, bg = "white")
entry_username.grid(row = 0, column = 1, padx = 5, pady = 5)
Label(frame_entry, text = "Enter password: ")\
.grid(row = 1, column = 0, padx = 10, pady = 10)
entry_password = Entry(frame_entry, width = 15, bg = "white", show = "*")
entry_password.grid(row = 1, column = 1, padx = 5, pady = 5)
# place the submit button
submit_button = Button(frame_buttons, text = "Submit", width = 8, command = submit)
submit_button.grid(row = 0, column = 0, padx = 5, pady = 5)
# place the Hint button
hint_button = Button(frame_buttons, text = "Hint", width = 15, command = hint)
hint_button.grid(row = 0, column = 1, padx = 5, pady = 5)
# run mainloop
root.mainloop()
print("carry on now...") | [
"damomurtagh@gmail.com"
] | damomurtagh@gmail.com |
35547c7260ff7326d7ad645bdebb3212f6456a1c | 950785ac7c72a6ac634f355f2e3cb2559c581335 | /lesson1_list.py | 86becb1fa25c46ecc182ad09068c7e666908a4c3 | [] | no_license | olyapasy/classwork | af223995733675008edcbeb0c58c67e7e2eac19c | 56a2f76aba07d57fe9d62d7d35e7747cb12e26ce | refs/heads/master | 2021-05-06T20:42:51.696771 | 2017-12-20T17:01:16 | 2017-12-20T17:01:16 | 110,445,016 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,226 | py | import random
# lst = [10, 20, 30, 40, 50, 60, 70, 80, 90]
# for i in range(len(lst)):
# print(i, lst[i])
#
#
# for i, elem in enumerate(lst):
# print(i, elem)
# lst[i]*= 2
# print(i, elem)
#
#
# for elem in lst:
# elem *= 2
# print(elem)
#
#
# for i in range(len(lst)):
# lst[i] *= 2
# print(lst)
# cпособы подсчета списка
# print(lst)
# for i in range(len(lst)):
# lst[i] = lst[i]**2
# print(lst)
#
# print("//////////////////////////////////////////////////")
#
# lst = [10, 20, 30, 40, 50, 60,70,80,90]
#
# print(lst)
# for i, elem in enumerate(lst):
# lst[i] = lst[i] ** 2
# print(lst)
#
#
# print("//////////////////////////////////////////////////")
#
# lst = [0] * 20
# print(lst)
lst = [0] * 20
def fill_list(lst, lower_bound, upper_bound):
for i in range(len(lst)):
lst[i] = random.randint(lower_bound, upper_bound)
return lst
print(id(lst), fill_list(lst, 0, 100))
def multiple_list(lst,coeff):
for i in range(len(lst)):
lst[i] *= coeff
return lst
print(id(lst), multiple_list(lst,10))
def nullify_list(lst):
for i in range(len(lst)):
lst[i] = 0
return lst
print(id(lst), nullify_list(lst))
| [
"olgapasibayeva98@gmail.com"
] | olgapasibayeva98@gmail.com |
537bfc2830a5733b015fc4dc3a52b74404fa4c96 | 5206b472075924831f70e2b0674915eeda123ec4 | /forloop.py | 853443390c08228c9cd00716864fbffc3824a24f | [] | no_license | vrushabhd/GitLearningRepo | 15bfb889af54186a00b49f492d52b847d6497d2b | ce990cab5ed3ce92e8c12e560f8f97268d11ac4a | refs/heads/master | 2020-12-30T08:39:01.352507 | 2020-02-07T16:07:37 | 2020-02-07T16:07:37 | 238,933,286 | 0 | 0 | null | 2020-02-07T15:23:40 | 2020-02-07T13:43:52 | Python | UTF-8 | Python | false | false | 105 | py | for i in range(10):
print("Yahoo")
print("done with for loops")
print("wait what about while loops")
| [
"vrushabhdhond1907@gmail.com"
] | vrushabhdhond1907@gmail.com |
61809667b75b77ed0658b2764d8a6580eff27210 | ba3231b25c60b73ca504cd788efa40d92cf9c037 | /nitro-python-13.0.36/nssrc/com/citrix/netscaler/nitro/resource/config/lb/lbvserver_cachepolicy_binding.py | 69f8f99dd0ca1e599fbfdbfaa6887a306492e901 | [
"Apache-2.0",
"Python-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | zhuweigh/vpx13 | f6d559ae85341e56472e3592cbc67062dac34b93 | b36caa3729d3ca5515fa725f2d91aeaabdb2daa9 | refs/heads/master | 2020-07-04T22:15:16.595728 | 2019-09-20T00:19:56 | 2019-09-20T00:19:56 | 202,435,307 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,840 | py | #
# Copyright (c) 2008-2019 Citrix Systems, Inc.
#
# 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 nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception
from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util
class lbvserver_cachepolicy_binding(base_resource) :
""" Binding class showing the cachepolicy that can be bound to lbvserver.
"""
def __init__(self) :
self._policyname = None
self._priority = None
self._gotopriorityexpression = None
self._bindpoint = None
self._invoke = None
self._labeltype = None
self._labelname = None
self._name = None
self.___count = None
@property
def priority(self) :
r"""Priority.
"""
try :
return self._priority
except Exception as e:
raise e
@priority.setter
def priority(self, priority) :
r"""Priority.
"""
try :
self._priority = priority
except Exception as e:
raise e
@property
def bindpoint(self) :
r"""The bindpoint to which the policy is bound.<br/>Possible values = REQUEST, RESPONSE.
"""
try :
return self._bindpoint
except Exception as e:
raise e
@bindpoint.setter
def bindpoint(self, bindpoint) :
r"""The bindpoint to which the policy is bound.<br/>Possible values = REQUEST, RESPONSE
"""
try :
self._bindpoint = bindpoint
except Exception as e:
raise e
@property
def policyname(self) :
r"""Name of the policy bound to the LB vserver.
"""
try :
return self._policyname
except Exception as e:
raise e
@policyname.setter
def policyname(self, policyname) :
r"""Name of the policy bound to the LB vserver.
"""
try :
self._policyname = policyname
except Exception as e:
raise e
@property
def labelname(self) :
r"""Name of the label invoked.
"""
try :
return self._labelname
except Exception as e:
raise e
@labelname.setter
def labelname(self, labelname) :
r"""Name of the label invoked.
"""
try :
self._labelname = labelname
except Exception as e:
raise e
@property
def name(self) :
r"""Name for the virtual server. Must begin with an ASCII alphanumeric or underscore (_) character, and must contain only ASCII alphanumeric, underscore, hash (#), period (.), space, colon (:), at sign (@), equal sign (=), and hyphen (-) characters. Can be changed after the virtual server is created.
CLI Users: If the name includes one or more spaces, enclose the name in double or single quotation marks (for example, "my vserver" or 'my vserver'). .<br/>Minimum length = 1.
"""
try :
return self._name
except Exception as e:
raise e
@name.setter
def name(self, name) :
r"""Name for the virtual server. Must begin with an ASCII alphanumeric or underscore (_) character, and must contain only ASCII alphanumeric, underscore, hash (#), period (.), space, colon (:), at sign (@), equal sign (=), and hyphen (-) characters. Can be changed after the virtual server is created.
CLI Users: If the name includes one or more spaces, enclose the name in double or single quotation marks (for example, "my vserver" or 'my vserver'). .<br/>Minimum length = 1
"""
try :
self._name = name
except Exception as e:
raise e
@property
def gotopriorityexpression(self) :
r"""Expression specifying the priority of the next policy which will get evaluated if the current policy rule evaluates to TRUE.
"""
try :
return self._gotopriorityexpression
except Exception as e:
raise e
@gotopriorityexpression.setter
def gotopriorityexpression(self, gotopriorityexpression) :
r"""Expression specifying the priority of the next policy which will get evaluated if the current policy rule evaluates to TRUE.
"""
try :
self._gotopriorityexpression = gotopriorityexpression
except Exception as e:
raise e
@property
def invoke(self) :
r"""Invoke policies bound to a virtual server or policy label.
"""
try :
return self._invoke
except Exception as e:
raise e
@invoke.setter
def invoke(self, invoke) :
r"""Invoke policies bound to a virtual server or policy label.
"""
try :
self._invoke = invoke
except Exception as e:
raise e
@property
def labeltype(self) :
r"""The invocation type.<br/>Possible values = reqvserver, resvserver, policylabel.
"""
try :
return self._labeltype
except Exception as e:
raise e
@labeltype.setter
def labeltype(self, labeltype) :
r"""The invocation type.<br/>Possible values = reqvserver, resvserver, policylabel
"""
try :
self._labeltype = labeltype
except Exception as e:
raise e
def _get_nitro_response(self, service, response) :
r""" converts nitro response into object and returns the object array in case of get request.
"""
try :
result = service.payload_formatter.string_to_resource(lbvserver_cachepolicy_binding_response, response, self.__class__.__name__)
if(result.errorcode != 0) :
if (result.errorcode == 444) :
service.clear_session(self)
if result.severity :
if (result.severity == "ERROR") :
raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
else :
raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
return result.lbvserver_cachepolicy_binding
except Exception as e :
raise e
def _get_object_name(self) :
r""" Returns the value of object identifier argument
"""
try :
if self.name is not None :
return str(self.name)
return None
except Exception as e :
raise e
@classmethod
def add(cls, client, resource) :
try :
if resource and type(resource) is not list :
updateresource = lbvserver_cachepolicy_binding()
updateresource.name = resource.name
updateresource.policyname = resource.policyname
updateresource.priority = resource.priority
updateresource.gotopriorityexpression = resource.gotopriorityexpression
updateresource.bindpoint = resource.bindpoint
updateresource.invoke = resource.invoke
updateresource.labeltype = resource.labeltype
updateresource.labelname = resource.labelname
return updateresource.update_resource(client)
else :
if resource and len(resource) > 0 :
updateresources = [lbvserver_cachepolicy_binding() for _ in range(len(resource))]
for i in range(len(resource)) :
updateresources[i].name = resource[i].name
updateresources[i].policyname = resource[i].policyname
updateresources[i].priority = resource[i].priority
updateresources[i].gotopriorityexpression = resource[i].gotopriorityexpression
updateresources[i].bindpoint = resource[i].bindpoint
updateresources[i].invoke = resource[i].invoke
updateresources[i].labeltype = resource[i].labeltype
updateresources[i].labelname = resource[i].labelname
return cls.update_bulk_request(client, updateresources)
except Exception as e :
raise e
@classmethod
def delete(cls, client, resource) :
try :
if resource and type(resource) is not list :
deleteresource = lbvserver_cachepolicy_binding()
deleteresource.name = resource.name
deleteresource.policyname = resource.policyname
deleteresource.bindpoint = resource.bindpoint
deleteresource.priority = resource.priority
return deleteresource.delete_resource(client)
else :
if resource and len(resource) > 0 :
deleteresources = [lbvserver_cachepolicy_binding() for _ in range(len(resource))]
for i in range(len(resource)) :
deleteresources[i].name = resource[i].name
deleteresources[i].policyname = resource[i].policyname
deleteresources[i].bindpoint = resource[i].bindpoint
deleteresources[i].priority = resource[i].priority
return cls.delete_bulk_request(client, deleteresources)
except Exception as e :
raise e
@classmethod
def get(cls, service, name="", option_="") :
r""" Use this API to fetch lbvserver_cachepolicy_binding resources.
"""
try :
if not name :
obj = lbvserver_cachepolicy_binding()
response = obj.get_resources(service, option_)
else :
obj = lbvserver_cachepolicy_binding()
obj.name = name
response = obj.get_resources(service)
return response
except Exception as e:
raise e
@classmethod
def get_filtered(cls, service, name, filter_) :
r""" Use this API to fetch filtered set of lbvserver_cachepolicy_binding resources.
Filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
"""
try :
obj = lbvserver_cachepolicy_binding()
obj.name = name
option_ = options()
option_.filter = filter_
response = obj.getfiltered(service, option_)
return response
except Exception as e:
raise e
@classmethod
def count(cls, service, name) :
r""" Use this API to count lbvserver_cachepolicy_binding resources configued on NetScaler.
"""
try :
obj = lbvserver_cachepolicy_binding()
obj.name = name
option_ = options()
option_.count = True
response = obj.get_resources(service, option_)
if response :
return response[0].__dict__['___count']
return 0
except Exception as e:
raise e
@classmethod
def count_filtered(cls, service, name, filter_) :
r""" Use this API to count the filtered set of lbvserver_cachepolicy_binding resources.
Filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
"""
try :
obj = lbvserver_cachepolicy_binding()
obj.name = name
option_ = options()
option_.count = True
option_.filter = filter_
response = obj.getfiltered(service, option_)
if response :
return response[0].__dict__['___count']
return 0
except Exception as e:
raise e
class Bindpoint:
REQUEST = "REQUEST"
RESPONSE = "RESPONSE"
class Labeltype:
reqvserver = "reqvserver"
resvserver = "resvserver"
policylabel = "policylabel"
class lbvserver_cachepolicy_binding_response(base_response) :
def __init__(self, length=1) :
self.lbvserver_cachepolicy_binding = []
self.errorcode = 0
self.message = ""
self.severity = ""
self.sessionid = ""
self.lbvserver_cachepolicy_binding = [lbvserver_cachepolicy_binding() for _ in range(length)]
| [
"zhuwei@xsky.com"
] | zhuwei@xsky.com |
b74ebc898da76e03be426ceeac6797a359cd3fe7 | fb5148945d6211ceaa4e633b45c304793af3a893 | /content/urls.py | 02a01a10888cbce74bbeca5d52f6626e1bb53eea | [] | no_license | HanabiDev/ElDiario | 722546491839b155b988527d6b36e99387775036 | 4d2cfb6a6c52b6cda1a1a75d45febc55093dbba3 | refs/heads/master | 2021-01-22T07:03:08.202867 | 2015-05-07T21:14:23 | 2015-05-07T21:14:23 | 20,891,136 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,052 | py | from django.conf.urls import patterns, url, include
urlpatterns = patterns('',
url(r'^/$', 'content.views.home', name='home'),
url(r'^/categorias/$', 'content.views.list_categories', name='categories'),
url(r'^/categorias/nueva/', 'content.views.add_category', name='new_category'),
url(r'^/categorias/editar/(?P<id>\d+)/$', 'content.views.edit_category', name='edit_category'),
url(r'^/categorias/publicar/$', 'content.views.publish_group', name='publish_group'),
url(r'^/categorias/despublicar/$', 'content.views.unpublish_group', name='unpublish_group'),
url(r'^/categorias/publicar/(?P<id>\d+)/$', 'content.views.toggle_publish', name='toggle_publish'),
url(r'^/categorias/despublicar/(?P<id>\d+)/$', 'content.views.toggle_publish', name='toggle_publish'),
url(r'^/categorias/eliminar/$', 'content.views.delete_category', name='delete_category'),
url(r'^/articulos/$', 'content.views.list_articles', name='articles'),
url(r'^/articulos/nuevo/', 'content.views.add_article', name='new_article'),
url(r'^/articulos/editar/(?P<id>\d+)/$', 'content.views.edit_article', name='edit_article'),
url(r'^/articulos/publicar/$', 'content.views.publish_art_group', name='publish_art_group'),
url(r'^/articulos/despublicar/$', 'content.views.unpublish_art_group', name='unpublish_art_group'),
url(r'^/articulos/destacar/$', 'content.views.feature_art_group', name='publish_art_group'),
url(r'^/articulos/no_destacar/$', 'content.views.unfeature_art_group', name='unpublish_art_group'),
url(r'^/articulos/publicar/(?P<id>\d+)/$', 'content.views.toggle_art_publish', name='toggle_art_publish'),
url(r'^/articulos/despublicar/(?P<id>\d+)/$', 'content.views.toggle_art_publish', name='toggle_art_publish'),
url(r'^/articulos/destacar/(?P<id>\d+)/$', 'content.views.toggle_art_featured', name='toggle_art_publish'),
url(r'^/articulos/no_destacar/(?P<id>\d+)/$', 'content.views.toggle_art_featured', name='toggle_art_publish'),
url(r'^/articulos/eliminar/$', 'content.views.delete_article', name='delete_article'),
) | [
"dianariscanevo@MacBook-Pro-de-Diana-Riscanevo.local"
] | dianariscanevo@MacBook-Pro-de-Diana-Riscanevo.local |
cb9e95714806a3d517d16ea18f12a2ab5abd1bec | 2b4d9e395aa9d87ae5c67dc0cbb059e4661a8315 | /web_calculator/settings.py | c46bc585293a7fa45125c9edfa632e524b0cfafc | [] | no_license | ElenaVolchkova/web_calculator | c3d5d47b77ab433d46a516686230e85297077101 | cd4e6baeb85c82d4734adf66e67059661531803d | refs/heads/master | 2020-12-14T12:43:03.638130 | 2020-01-18T10:23:17 | 2020-01-18T10:23:17 | 234,748,391 | 0 | 0 | null | 2020-01-18T14:39:08 | 2020-01-18T14:39:07 | null | UTF-8 | Python | false | false | 3,179 | py | """
Django settings for web_calculator project.
Generated by 'django-admin startproject' using Django 3.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/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/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '_+b$29i=5v)0*on-rrf*5*87_ilg_x@$0c^f8$x4hd1vu^$3sl'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'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 = 'web_calculator.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'web_calculator/templates').replace('\\','/')],
'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 = 'web_calculator.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/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/3.0/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/3.0/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/3.0/howto/static-files/
STATIC_URL = '/static/'
| [
"vladislav-shepilov@digitalunicorn.com"
] | vladislav-shepilov@digitalunicorn.com |
0283af68947c62fb9881df0ba44b2a01e4807361 | 1f980a8693e87a0a64f1ba861e641ff48778baa3 | /utils.py | af1e60a177cbca7faa44632679edfc176d509559 | [] | no_license | ijt/swyzl | 3c0ee8a008a8c7b0665407dd5a6e1aa4e37ee320 | 0de408bebb0f1cb37ebbbb95da2b011abc623b98 | refs/heads/master | 2021-01-20T05:08:32.577935 | 2012-07-18T08:29:06 | 2012-07-18T08:29:06 | 73,775 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,120 | py | """Functions that do not depend on App Engine"""
import random
def MakeRandomLetterMap():
"""
Make a one-to-one map from every capital letter to every other.
@return: a mapping with a random permutation of letters
@rtype: dict
"""
alphabet = [chr(c) for c in range(ord('A'), ord('Z') + 1)]
shuffled = alphabet[:]
random.shuffle(shuffled)
return dict((alphabet[i], shuffled[i]) for i in xrange(len(alphabet)))
def GetLetters(string):
"""Get the set of letters in a given string."""
return set([x for x in string.upper() if x.isalpha()])
def MakeRandomLetterMapForLettersIn(message):
"""Make a map from letters in a message to other letters.
@param message: text to use as the domain for the map
@type message: str
@return: map from the message letters to randomly chosen other letters
"""
letters = GetLetters(message)
bigmap = MakeRandomLetterMap()
return dict((l, bigmap[l]) for l in letters)
def MakeEncryptionMap(solution_text, cipher_text):
"""Make an encryption map from a solution and cipher-text.
@param solution_text: the hidden message
@type solution_text: str
@param cipher_text: the encoded message that will be presented
@type cipher_text: str
@return: mapping from solution characters to cipher-text characters
@rtype: dict
"""
if len(solution_text) != len(cipher_text):
raise ValueError('Solution and cipher lengths do not match')
result = {}
for i in xrange(len(solution_text)):
s = solution_text[i]
c = cipher_text[i]
if s in result:
if result[s] != c:
raise ValueError('Character %s maps to both %s and %s.' %
(s, result[s], c))
else:
if s.isalpha():
result[s] = c
else:
if s != c:
msg = ("Non-letter %s mapped to %s. That's not allowed." %
(s, c))
raise ValueError(msg)
return result
def CheckPuzzle(solution_text, cipher_text):
"""
Check that the solution and cipher imply a 1-1 map.
@raise ValueError: if there is no 1-1 mapping between solution and
cipher-text
"""
MakeEncryptionMap(solution_text, cipher_text)
MakeEncryptionMap(cipher_text, solution_text)
def ConvertStringToEncodingMap(string):
"""
Convert strings like 'ABZX' to maps like {'A':'B', 'Z':'X'}.
@param string: a packed map
@type string: str
@return: mapping from even-indexed characters to the characters following
them
@rtype: dict
"""
n = len(string) / 2
evens = [string[2 * i] for i in xrange(n)]
odds = [string[2 * i + 1] for i in xrange(n)]
return dict((evens[i], odds[i]) for i in xrange(n))
def ListToTableRow(lst, klass=None):
"""
Generate an HTML-formatted table row from a list.
@param lst: cells for the table
@type lst: list
@param klass: class parameter fro the <td> tags
@type klass: str
@return: HTML
@rtype: str
"""
class_part = klass and (' class="%s"' % klass) or ''
td = '<td%s>' % class_part
inner_part = ('</td>%s' % td).join(lst)
return '<tr>' + td + inner_part + '</td></tr>'
def GenerateWordHtmls(cipher_words):
"""
Generate a list of HTML snippets to build a puzzle UI. The HTML allows the
puzzle UI to reflow when the browser is resized horizontally.
@param cipher_words: encrypted words in the puzzle
@type cipher_words: str
@return: HTML snippets
@rtype: list of str
"""
word_htmls = []
# Generate one table per word.
box_index = 0
for word in cipher_words:
top_row = []
bot_row = []
for char in word:
if char.isalpha():
# The code char is part of the input tag's class. That way we
# can easily find all the input boxes for a given code
# character.
input_tag = ('<input id="box%s" class="SwyzlTextBox %s" '
'maxlength="1" ' % (box_index, char))
# The size is set to 2 because setting it to 1 is supposed to
# not be well supported on all browsers.
callback = ("return onKeyDown('%s', event.keyCode || "
"event.which, %i)" % (char, box_index))
input_tag += 'size="2" onkeyDown="%s">' % callback
top_row.append(input_tag)
bot_row.append(char)
box_index += 1
else:
# Use the same CSS class as the text boxes to keep things lined
# up.
elt = '<span class="SwyzlTextBox noborder">%s</span>' % char
top_row.append(elt)
bot_row.append(elt)
word_html = '<table class="boxOnLetter">'
word_html += ListToTableRow(top_row)
word_html += ListToTableRow(bot_row, klass="letter")
word_html += '</table>'
word_htmls.append(word_html)
return word_htmls
| [
"issac.trotts@gmail.com"
] | issac.trotts@gmail.com |
a05c06d05e818c0aac7388e1a05bbfd442decc2c | 65581440417d9c3833f26c5cb673dd2e25e88c93 | /src/pasteFunBot/templates/buildbotLocal/funkload/credentialFL/test_Cmf.py | 5e3a31cf35ad3fe04ef2cbb200fcd02143289110 | [] | no_license | Piers73600/pasteFunBot | a2c80b36c31ef11d1149da4db7c6a814e97a5884 | 4a374b64bd7c4168dc8c8b0b8834530577c7bd7c | refs/heads/master | 2021-01-11T03:06:04.543633 | 2009-07-27T08:58:07 | 2009-07-27T08:58:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,221 | py | import unittest
from random import random
from funkload.FunkLoadTestCase import FunkLoadTestCase
from funkload.utils import xmlrpc_get_credential, xmlrpc_list_credentials
from funkload.Lipsum import Lipsum
class CmfTestCase(FunkLoadTestCase):
def cmfLogin(self, login, pwd):
params = [["login", login],
["password", pwd],
["submit", "Login"]]
self.post('%s/login_handler?_logins=0&came_from=/' % self.server_url, params, description="Login utilisateur %s" % login)
self.assert_('Welcome' in self.getBody(), "Credential invalide %s:%s" % (login, pwd))
self._cmf_login = login
class Cmf(CmfTestCase):
def setUp(self):
self.logd("setUp")
self.server_url = self.conf_get('main', 'url')
credential_host = self.conf_get('credential', 'host')
credential_port = self.conf_getInt('credential', 'port')
self.credential_host = credential_host
self.credential_port = credential_port
self.cred_manager = xmlrpc_get_credential(credential_host,
credential_port,
'managers')
def test_01_connect(self):
server_url = self.server_url
self.cmfLogin(*self.cred_manager)
def tearDown(self):
self.logd('tearDown.\n')
if __name__ in ('main', '__main__'):
unittest.main()
| [
"stpda@stpda-laptop.(none)"
] | stpda@stpda-laptop.(none) |
54a0286ff3e65c09df7ef4eff15345fef71120c9 | 2c4dbf80b7493beccdd6e8e3f3dbcfe05c235ae5 | /Lecture.8.Testing-CI-CD/airline/flights/migrations/0003_auto_20180329_1500.py | 188b3fb726b1df9d543d3ec08643890bda3fb938 | [] | no_license | mbegumgit/cs50 | 9cbe88dbc5d9d1751cb9c020ba1a6337dcfab8b5 | d7d641ef039794c18be3228596bbfbe6e58662d8 | refs/heads/master | 2021-07-12T11:12:14.864921 | 2021-02-26T05:02:12 | 2021-02-26T05:02:12 | 237,889,463 | 0 | 0 | null | 2020-02-03T05:08:26 | 2020-02-03T05:08:25 | null | UTF-8 | Python | false | false | 839 | py | # Generated by Django 2.0.3 on 2018-03-29 15:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('flights', '0002_auto_20180329_1219'),
]
operations = [
migrations.CreateModel(
name='Passanger',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('first', models.CharField(max_length=64)),
('last', models.CharField(max_length=64)),
('flights', models.ManyToManyField(blank=True, related_name='passanger', to='flights.Flight')),
],
),
migrations.AlterField(
model_name='airport',
name='code',
field=models.CharField(max_length=5),
),
]
| [
"taqi.official@gmail.com"
] | taqi.official@gmail.com |
861746feb7cdb398feda0237dcb2510589b3fa6d | c686e8f8fa580b03f37db9134ea6c1496efbe9d1 | /cmdb/models.py | 2f1a60b624da66d72d1fec4fcae8c001b04140a2 | [
"BSD-2-Clause"
] | permissive | reven-tang/ITMP | e5b8b696e13b20a5d569c3960e635dcebd1afbdd | 8d6686edb19fcc26c9cf1f7e14037f9d38a6e702 | refs/heads/master | 2022-12-13T10:31:38.032360 | 2018-12-29T07:40:32 | 2018-12-29T07:40:32 | 163,487,313 | 0 | 0 | BSD-2-Clause | 2022-12-08T03:00:35 | 2018-12-29T07:20:29 | JavaScript | UTF-8 | Python | false | false | 7,065 | py | from django.db import models
# Create your models here.
class DeviceInfo(models.Model):
dev_status = (
('Online', '在线'),
('Offline', '下线'),
('Unknown', '未知'),
('Fault', '故障'),
('Backup', '备用'),
)
dev_type = (
('VM', '虚拟机'),
('PM', '物理机'),
('Other', '其他'),
)
devid = models.AutoField('设备ID', primary_key=True)
devip = models.CharField('设备IP地址', max_length=16, unique=True)
devname = models.CharField('设备名称', max_length=32, blank=True, null=True)
devnamealias = models.CharField('设备别名', max_length=32, blank=True, null=True)
ostype = models.CharField('操作系统', max_length=64, blank=True, null=True)
devtype = models.CharField('设备类型', choices=dev_type, max_length=16, default='VM')
devstatus = models.CharField('设备状态', choices=dev_status, max_length=16, default='Online')
cpusize = models.FloatField('CPU大小(GHz)', default=0.0)
cpucorecount = models.PositiveSmallIntegerField('CPU核数', default=0)
memsize = models.IntegerField('内存大小(GB)', default=0)
disksize = models.FloatField('磁盘容量(GB)', default=0.0)
location = models.CharField('机房位置', max_length=64, blank=True, null=True)
devdesc = models.CharField('设备描述', max_length=256, blank=True, null=True)
pdappsystem = models.ManyToManyField('ProjectInfo', blank=True, verbose_name="应用系统")
customer1 = models.CharField('自定义字段1', max_length=256, blank=True, null=True)
customer2 = models.CharField('自定义字段2', max_length=256, blank=True, null=True)
customer3 = models.CharField('自定义字段3', max_length=256, blank=True, null=True)
customer4 = models.CharField('自定义字段4', max_length=256, blank=True, null=True)
customer5 = models.CharField('自定义字段5', max_length=256, blank=True, null=True)
customer6 = models.CharField('自定义字段6', max_length=256, blank=True, null=True)
customer7 = models.CharField('自定义字段7', max_length=256, blank=True, null=True)
customer8 = models.CharField('自定义字段8', max_length=256, blank=True, null=True)
def __str__(self):
return self.devip
class Meta:
verbose_name = '设备信息表'
verbose_name_plural = "设备信息表"
managed = True
db_table = 't_cmdb_device_info'
unique_together = (('devid', 'devip'),)
class ProjectInfo(models.Model):
pid = models.AutoField('项目ID', primary_key=True)
projname = models.CharField('项目名称', max_length=16)
appsystem = models.CharField('应用系统', max_length=64, unique=True)
# dpdevip = models.ManyToManyField('DeviceInfo', blank=True, verbose_name="设备IP地址")
projdesc = models.CharField('项目描述', max_length=256, blank=True, null=True)
projcontactname = models.CharField('项目联系人姓名', max_length=10, blank=True, null=True)
projcontactphone = models.CharField('项目联系人电话', max_length=16, blank=True, null=True)
projcontactemail = models.EmailField('项目联系人邮箱', max_length=256, blank=True, null=True)
appcontactname = models.CharField('应用联系人姓名', max_length=10, blank=True, null=True)
appcontactphone = models.CharField('应用联系人电话', max_length=16, blank=True, null=True)
appcontactemail = models.EmailField('应用联系人邮箱', max_length=256, blank=True, null=True)
groupname = models.CharField('小组名称', max_length=32, blank=True, null=True)
customer1 = models.CharField('自定义字段1', max_length=256, blank=True, null=True)
customer2 = models.CharField('自定义字段2', max_length=256, blank=True, null=True)
customer3 = models.CharField('自定义字段3', max_length=256, blank=True, null=True)
customer4 = models.CharField('自定义字段4', max_length=256, blank=True, null=True)
customer5 = models.CharField('自定义字段5', max_length=256, blank=True, null=True)
def __str__(self):
return self.appsystem
class Meta:
verbose_name = '项目信息表'
verbose_name_plural = "项目信息表"
managed = True
db_table = 't_cmdb_project_info'
unique_together = (('pid', 'appsystem'),)
class SoftwareInfo(models.Model):
sid = models.AutoField('软件ID', primary_key=True)
dsdevip = models.ForeignKey('DeviceInfo', on_delete=models.CASCADE, verbose_name='设备IP地址')
psappsystem = models.ForeignKey('ProjectInfo', on_delete=models.CASCADE, verbose_name='应用系统')
sname = models.CharField('软件名称', max_length=64)
stype = models.CharField('软件类型', max_length=16, blank=True, null=True)
sport = models.CharField('软件端口', max_length=6, blank=True, null=True)
sversion = models.CharField('版本', max_length=16, blank=True, null=True)
spath = models.CharField('路径', max_length=128, blank=True, null=True)
sdesc = models.CharField('软件描述', max_length=256, blank=True, null=True)
customer1 = models.CharField('自定义字段1', max_length=256, blank=True, null=True)
customer2 = models.CharField('自定义字段2', max_length=256, blank=True, null=True)
customer3 = models.CharField('自定义字段3', max_length=256, blank=True, null=True)
customer4 = models.CharField('自定义字段4', max_length=256, blank=True, null=True)
customer5 = models.CharField('自定义字段5', max_length=256, blank=True, null=True)
def __str__(self):
return self.sname
class Meta:
verbose_name = '软件信息表'
verbose_name_plural = "软件信息表"
managed = True
db_table = 't_cmdb_software_info'
class Relations(models.Model):
rid = models.AutoField('关系ID', primary_key=True)
drdevip = models.ForeignKey('DeviceInfo', on_delete=models.CASCADE, verbose_name='本端设备')
srsname = models.ForeignKey('SoftwareInfo', on_delete=models.CASCADE, verbose_name='软件名称')
upip = models.CharField('上联设备', max_length=16, blank=True, null=True)
updesc = models.CharField('上联描述', max_length=256, blank=True, null=True)
downip = models.CharField('下联设备', max_length=16, blank=True, null=True)
downdesc = models.CharField('下联描述', max_length=256, blank=True, null=True)
def __str__(self):
return str(self.drdevip)
class Meta:
verbose_name = '关系表'
verbose_name_plural = "关系表"
managed = True
db_table = 't_cmdb_relations'
class DpMap(models.Model):
id = models.AutoField('映射编号', primary_key=True)
deviceinfo_id = models.CharField('设备ID', max_length=16)
projectinfo_id = models.CharField('系统ID', max_length=16)
class Meta:
verbose_name = '设备系统映射表'
verbose_name_plural = "设备系统映射表"
managed = False
db_table = 't_cmdb_device_info_pdappsystem' | [
"wujh8701@163.com"
] | wujh8701@163.com |
d3f5cc473e7adb26e330593982da67161e41dc53 | ed5043e4fafb3655e26bc372e7f45fe1a55a1ad9 | /参数解析.py | 546c140d56b5be88e0bb7b3b6ae08a3d2dc45adb | [] | no_license | zhangyongming13/test | e4ecdbdef43303d064f6cad171853d0bf7599c0c | 2ffc8f0d7b05122282198405931c3108806504ce | refs/heads/master | 2021-03-06T11:32:44.433731 | 2020-04-01T13:02:38 | 2020-04-01T13:02:38 | 246,195,808 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 842 | py | # https://www.nowcoder.com/practice/668603dc307e4ef4bb07bcd0615ea677?tpId=37&tqId=21297&tPage=4&rp=&ru=/ta/huawei&qru=/ta/huawei/question-ranking
while True:
try:
input_string = str(input())
result = []
# flag用来记录遇到“和”
flag = 0
start = 0
for index, value in enumerate(input_string):
if value == '“':
flag += 1
if value == '”':
flag -= 1
if value == ' ' and flag == 0:
tmp = input_string[start:index]
result.append(tmp.strip('“”'))
tmp = []
start = index + 1
result.append(input_string[start:].strip('“”'))
print(len(result))
for i in result:
print(i)
except Exception as e:
break
| [
"790454963@qq.com"
] | 790454963@qq.com |
a37917ec2176aa13584edf7f2258ef73127c0c3b | a4e27d18c8a92a747c7350042190ff74117d61c3 | /router/osrm_router.py | 8f0ef0d134726cbbe402aa160cfd50055950aa98 | [] | no_license | zreactor/osrm | ebca63922f0101e786f62015ad8c7800f5119cff | 511e02cfa0d19313ecd4993bb5a0477bfa236dc7 | refs/heads/master | 2020-03-21T18:51:23.895171 | 2018-06-27T18:30:19 | 2018-06-27T18:30:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,707 | py | import urllib2
import json
from route import RouteObject
class RouteRequester(object):
'''Does stuff'''
def __init__(self, endpoints):
self.endpoints = endpoints
self.from_latlon = endpoints[0]
self.to_latlon = endpoints[1]
self.route = None
self._generateRoute()
def generateRequestURL_FE(self):
urlholder = """http://localhost:9966/?z=16¢er={lat0}%2C{lon0}&loc={lat0}%2C{lon0}&loc={lat1}%2C{lon1}&hl=en&alt=0""".format(
lat0=self.from_latlon[1],
lon0=self.from_latlon[0],
lat1=self.to_latlon[1],
lon1=self.to_latlon[0]
)
return urlholder
def generateRequestURL_BE(self):
urlholder = """http://localhost:5000/route/v1/driving/{lat0},{lon0};{lat1},{lon1}?steps=true""".format(
lat0=self.from_latlon[0],
lon0=self.from_latlon[1],
lat1=self.to_latlon[0],
lon1=self.to_latlon[1]
)
return urlholder
def getRoute(self):
return self.route
def _generateRoute(self):
# print "generating route"
holder = self.generateRequestURL_BE()
# self.route = self._getRouteFromURL(holder)
self.route = RouteObject(self.endpoints, self._getRouteFromURL(holder))
def generateRoute(self):
self._generateRoute()
return self.route.text
@classmethod
def _getRouteFromURL(self, urlholder):
response = urllib2.urlopen(urlholder)
routejson = json.loads(response.read())
return routejson["routes"]
@classmethod
def parseRoute(self, routejson):
'''Returns [length, traveltime, waypoints] attributes for arbitrary block of route json'''
length = routejson[0]["distance"]
traveltime = routejson[0]["duration"]
waypoints = [step["maneuver"]["location"] for step in routejson[0]["legs"][0]["steps"]]
return [length, traveltime, waypoints]
@classmethod
def generateAnyRouteFE(self, from_latlon, to_latlon):
urlholder = """http://localhost:9966/?z=16¢er={lat0}%2C{lon0}&loc={lat0}%2C{lon0}&loc={lat1}%2C{lon1}&hl=en&alt=0""".format(
lat0=from_latlon[1],
lon0=from_latlon[0],
lat1=to_latlon[1],
lon1=to_latlon[0]
)
return urlholder
@classmethod
def generateAnyRouteBE(self, from_latlon, to_latlon):
urlholder = """http://localhost:5000/route/v1/driving/{lat0},{lon0};{lat1},{lon1}?steps=true""".format(
lat0=from_latlon[0],
lon0=from_latlon[1],
lat1=to_latlon[0],
lon1=to_latlon[1]
)
return urlholder
| [
"tachibana.yki@gmail.com"
] | tachibana.yki@gmail.com |
79ab0431676802091010294afa5ac2e1dc2ed0bd | 06f544e970fe833c98929a15170a3a4b85750440 | /examples/python/6d_pose_annotation/coco_writer.py | 868c3b8a73bdf1354469d4d5e490424209201ab0 | [
"MIT"
] | permissive | mikkeljakobsen/Open3D | 330ffb81bac95b098cfdc750de87cb2b692d203e | 1b085653eaa3cc4145c911b8170d6d9f9f8a6d87 | refs/heads/master | 2023-05-23T08:59:36.961549 | 2021-06-03T11:19:16 | 2021-06-03T11:19:16 | 308,018,342 | 0 | 0 | NOASSERTION | 2021-01-07T14:44:47 | 2020-10-28T13:04:23 | C++ | UTF-8 | Python | false | false | 7,926 | py | # 6DoF pose annotator
# Shuichi Akizuki, Chukyo Univ.
# Email: s-akizuki@sist.chukyo-u.ac.jp
#
import open3d as o3
import json
import numpy as np
import os
from realsense import RealsenseDataset
from pathlib import Path
import pycocotools.mask as maskUtils
from PIL import Image
def project(xyz, K, RT):
# xyz: [N, 3], K: [3, 3], RT: [3, 4]
xyz = np.dot(xyz, RT[:, :3].T) + RT[:, 3:].T
xyz = np.dot(xyz, K.T)
z = xyz[:, 2:]
xy = xyz[:, :2] / z
return xy, z
class CocoWriter:
def __init__(self, _depth_factor=1000.0, first_image_id=0, first_scene_id=0, first_instance_id=0, categories=None,
info=None):
self.depth_factor = _depth_factor
self.annotations = []
if categories is not None:
self.categories = categories
else:
self.categories = [{'id': 0, 'name': 'EnabledBin_BitoMedium_C', 'supercategory': ''},
{'id': 1, 'name': 'EnabledBin_BitoLarge_C', 'supercategory': ''},
{'id': 2, 'name': 'EnabledBin_BitoSmall_C', 'supercategory': ''}]
self.images = []
if info is not None:
self.info = info
else:
self.info = {
'contributor': 'Enabled Robotics',
'description': "Enabled Robotic's validation data for bito_boxes",
'name': 'Bito Box Validation Dataset',
'year': '2021'}
self.image_id = first_image_id
self.scene_id = first_scene_id
self.instance_id = first_instance_id
def add_color_image(self, file_name, width, height, K):
self.images.append({
'file_name': str(file_name),
'width': width,
'height': height,
'K': K.tolist(),
'id': self.image_id,
'scene_id': self.scene_id,
'channel': 'rgb'
})
self.image_id += 1
def add_depth_image(self, file_name, width, height, K):
self.images.append({
'file_name': file_name,
'width': width,
'height': height,
'K': K.tolist(),
'id': self.image_id,
'scene_id': self.scene_id,
'channel': 'depth',
'depth_factor': self.depth_factor
})
self.image_id += 1
def add_annotation(self, RT, category_id, mask=None):
annotation = {
'RT': RT.tolist(),
'category_id': int(category_id),
'id': int(self.instance_id),
'image_id': int(self.image_id),
'iscrowd': 0
}
if mask is not None:
rle_mask = maskUtils.encode(np.asfortranarray(mask))
bbox = maskUtils.toBbox(rle_mask)
area = maskUtils.area(rle_mask)
rle_mask['counts'] = rle_mask['counts'].decode('ascii')
annotation['segmentation'] = rle_mask
annotation['bbox'] = bbox.tolist()
annotation['area'] = int(area)
self.annotations.append(annotation)
self.instance_id += 1
def get_keypoints(self, ann_id=0):
annot_data = self.annotations[ann_id]
# read in depth frame and scale to (m)
depth_factor = 1000.0 # self.scene_id_to_frames[scene_id]["depth"]["depth_factor"]
depth_path = Path(self.images[self.image_id]["file_name"])
raw_depth = Image.open(depth_path)
depth_frame = np.array(raw_depth) / depth_factor
width = self.images[self.image_id]["width"]
height = self.images[self.image_id]["height"]
K = np.array(self.images[self.image_id]['K'])
RT = np.array(annot_data['RT'])[:3, :4]
keypoints_3D = np.array(self.category_id_to_keypoints[annot_data['category_id']])
keypoints_xy, projected_depth = project(keypoints_3D, K, RT)
keypoints = []
for xy2, z in zip(keypoints_xy, projected_depth):
x = int(xy2[0])
keypoints.append(x)
y = int(xy2[1])
keypoints.append(y)
visible = 2 # keypoint labeled and visible
if not (0 < x < width):
visible = 0 # keypoint not labeled and not visible
elif not (0 < y < height):
visible = 0 # keypoint not labeled and not visible
elif depth_frame[y, x] + 0.01 < z:
visible = 1 # keypoint labeled but not visible
# print("keypoint not visible", depth_frame[y, x])
# else:
# print("keypoint is visible", depth_frame[y, x])
keypoints.append(visible)
return keypoints
def add_keypoints_to_annotations(self, keypoint_paths, category_ids):
self.category_id_to_keypoints = {}
self.keypoint_names = ["glass bottom right", "glass bottom left", "glass top left", "glass top right",
"box front bottom right", "box front bottom left", "#box front top left",
"box front top right", "box back bottom right", "box back bottom left",
"box back top left", "box back top right", "bossard label bottom right",
"bossard label bottom left", "bossard label top left", "bossard label top right",
"bossard sidepanel top", "bossard sidepanel bottom",
"bossard weight front bottom right",
"bossard weight front bottom left", "bossard weight back bottom left",
"bossard weight back bottom right"]
for keypoint_path, category_id in zip(keypoint_paths, category_ids):
keypoint_dict = json.load(open(keypoint_path))
keypoint_list = []
for keypoint_name in self.keypoint_names:
keypoint_list.append(np.array(keypoint_dict["keypoints"][keypoint_name]))
self.category_id_to_keypoints[int(category_id)] = keypoint_list
self.image_id_2_idx = {x["id"]: idx for idx, x in enumerate(self.images)}
self.scene_id_to_frames = {}
for im_data in self.images:
sid = im_data["scene_id"]
sid_frames = self.scene_id_to_frames.get(sid, {})
channel = im_data.get("channel", "rgb")
if channel == "depth":
sid_frames[channel] = im_data
else:
sid_frames["rgb"] = im_data
self.scene_id_to_frames[sid] = sid_frames
ann_count = len(self.annotations)
print("adding keypoints to " + str(ann_count) + " annotations")
for i in range(ann_count):
ann = self.annotations[i]
ann["keypoints"] = self.get_keypoints(i)
self.annotations[i] = ann
if i % 500 == 0:
print("progress " + str(i) + "/" + str(ann_count))
print("setting category keypoint-names to ", self.keypoint_names)
for i in range(len(self.categories)):
cat = self.categories[i]
cat["keypoints"] = self.keypoint_names
self.categories[i] = cat
def save_annotations(self, output_path="coco_annotations.json"):
output_dict = {
"info": self.info,
"categories": self.categories,
"annotations": self.annotations,
"images": self.images
}
f_out = open(output_path, 'w')
json.dump(output_dict, f_out)
print("annotations was saved to ", output_path)
def increase_scene_id(self):
self.scene_id += 1
if __name__ == "__main__":
from pycocotools import coco
coco_writer = CocoWriter()
data_root_path = Path("/home/mikkel/code/catkin_ws/bito_boxes_real_data")
scene_paths = sorted(data_root_path.glob('*'))
for scene_path in scene_paths:
scene_data = RealsenseDataset(scene_path)
ref_item = scene_data[0]
| [
"mikkeljakobsen@hotmail.com"
] | mikkeljakobsen@hotmail.com |
c1125a3c9282509b5516cdeb792bc198e9d43345 | 56907a3844ad8a237b4210f433ceda08f59d82ea | /Couprie_et_al_2013/szakdoga5_lookup.py | 46750913131a92bcff125dd43955f7165482bd9e | [] | no_license | ilitygergo/thesis | aee73e7b387148ea96d3462a3df2bd031ead662c | e72d337bbb37df2461e43143de7e4120b40b2a71 | refs/heads/master | 2023-07-09T03:45:36.931594 | 2020-12-13T12:26:57 | 2020-12-13T12:26:57 | 162,641,024 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,125 | py | import cv2
import time
import bcolors
from Common.functions import imreadgray
from Common.functions import flip
from Common.functions import equalmatrix
from Common.functions import makeequalmatrix
from Common.functions import borderpoint8
from Common.functions import binmatrix
from Common.functions import lowneighbour
from Common.functions import converttoarray
from Common.functions import arraytonum
start_time = time.time()
print(bcolors.OK, " _____ _ _ _ ")
print(" / ____| (_) | | | |")
print(" | | ___ _ _ _ __ _ __ _ ___ ___| |_ __ _| |")
print(" | | / _ \| | | | '_ \| '__| |/ _ \ / _ \ __| / _` | |")
print(" | |___| (_) | |_| | |_) | | | | __/ | __/ |_ | (_| | |")
print(" \_____\___/ \__,_| .__/|_| |_|\___| \___|\__| \__,_|_|")
print(" | | ")
print(" |_| ", bcolors.ENDC)
# Reading in the pictures as a gray picture
picture = 'dragon'
img = imreadgray('../Common/' + picture + '.png')
img2 = imreadgray('../Common/' + picture + '.png')
helper = imreadgray('../Common/' + picture + '.png')
lowest = imreadgray('../Common/' + picture + '.png')
# Converting values 0-255
img = flip(img)
img2 = flip(img2)
helper = flip(helper)
lowest = flip(lowest)
# Initialization
lepes = 0
size = img.shape
n = size[0]
m = size[1]
border = [0] * n
for x in range(n):
border[x] = ['O'] * m
binmatrixhelper = 0
table = []
with open("lookup", "rb") as f:
byte = f.read(1)
while byte:
table.append(int.from_bytes(byte, "little"))
byte = f.read(1)
print(img, '\n')
while True:
for row in range(0, size[0]):
for col in range(0, size[1]):
border[row][col] = 'O'
lowest[row][col] = 0
for row in range(2, size[0] - 2):
for col in range(2, size[1] - 2):
if img[row][col] == 0:
continue
if borderpoint8(img, row, col):
lowest[row][col] = lowneighbour(img, row, col)
border[row][col] = 'X'
for row in range(2, size[0] - 2):
for col in range(2, size[1] - 2):
binmatrixhelper = binmatrix(img, row, col, size)
if border[row][col] == 'O':
continue
binmatrixhelper = converttoarray(binmatrixhelper, 2, 2)
binmatrixhelper = arraytonum(binmatrixhelper)
helper[row][col] = table[binmatrixhelper]
for row in range(0, size[0]):
for col in range(0, size[1]):
if helper[row][col] == 1:
img[row][col] = lowest[row][col]
makeequalmatrix(helper, img, size)
lepes += 1
if equalmatrix(img, img2, size):
break
else:
makeequalmatrix(img2, img, size)
print(bcolors.BLUE, '\n', lepes, '. run:')
print(img, '\n', bcolors.ENDC)
# Converting the values back to normal
flip(img)
# Saving
cv2.imwrite('results_lookup/' + picture + '.png', img)
print("My program took", time.time() - start_time, "to run")
| [
"h659367@stud.u-szeged.hu"
] | h659367@stud.u-szeged.hu |
d02c4a0793ee279dabe9c0b95d2105dcd9706e63 | 7b3743f052da9a74808b7d2145418ce5c3e1a477 | /v2/api.thewatcher.io/api/models/saviors.py | 89626aa29873222a92953c0510d71808dfbb67f1 | [
"MIT"
] | permissive | quebecsti/kdm-manager | 5547cbf8928d485c6449650dc77805877a67ee37 | a5fcda27d04135429e43a21ac655e6f6acc7768e | refs/heads/master | 2020-11-26T19:22:53.197651 | 2019-10-22T20:53:40 | 2019-10-22T20:53:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,129 | py | #!/usr/bin/python2.7
from api.assets import saviors
from api import Models
import utils
class Assets(Models.AssetCollection):
def __init__(self, *args, **kwargs):
self.root_module = saviors
Models.AssetCollection.__init__(self, *args, **kwargs)
def get_asset_by_color(self, color=None):
""" This method will return an asset dictionary whose 'color' attrib
matches the value of the 'color' kwarg.
"""
if color is None:
msg = "get_asset_by_color() requires the 'color' kwarg!"
self.logger.exception(msg)
raise Exception(msg)
output = None
for d in self.get_dicts():
if d["color"] == color and output is None:
output = d
elif d["color"] == color and output is not None:
msg = "Multiple savior asset dicts have the color '%s'. Did you rememeber to filter?" % color
self.logger.exception(msg)
raise Exception(msg)
if output is None:
msg = "No asset dict found for color '%s'!" % color
return output
| [
"toconnell@tyrannybelle.com"
] | toconnell@tyrannybelle.com |
14940a0b39f1f7c4e8107e47cdc734cdf845df28 | 28bf7793cde66074ac6cbe2c76df92bd4803dab9 | /answers/MridulMohanta/Day29/question1.py | bd0a470a4989c366aa27de5d8ad3952e877f35eb | [
"MIT"
] | permissive | Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021 | 2dee33e057ba22092795a6ecc6686a9d31607c9d | 66c7d85025481074c93cfda7853b145c88a30da4 | refs/heads/main | 2023-05-29T10:33:31.795738 | 2021-06-10T14:57:30 | 2021-06-10T14:57:30 | 348,153,476 | 22 | 135 | MIT | 2021-06-10T14:57:31 | 2021-03-15T23:37:26 | Java | UTF-8 | Python | false | false | 534 | py | a=[]
b=[]
x=int(input("Enter length of the two variables"))
n=int(input("Enter test number"))
y=0
for i in range(0,x):
p=int(input("Enter element in a:"))
a.append(p)
q=int(input("Enter element in b:"))
b.append(q)
for i in range(x-1,-1,-1):
for j in range(i,-1,-1):
if ((a[i]+b[j])<=n):
print (a[i])
print (b[j])
temp=b[j]
b[j]=b[i]
b[i]=temp
y=y+1
break
print (b)
if ((x-1)<=y):
print ("YES")
else:
print("NO")
| [
"noreply@github.com"
] | Codechef-SRM-NCR-Chapter.noreply@github.com |
51b1e28cd322243c65d4e3e017c30b7b475c2a90 | 341bd4e4cf07f37e44fd8f2124d15c02b3f50884 | /visualization.py | 91ee7151c496fb065a83924228742fc1e3602587 | [] | no_license | Shikhar2205/Object-Recognition | 95afb21f9dcf94705a94db2180c8d4c18b453fac | 19060e8f972c7bd15d9626d38ae49f7500928f10 | refs/heads/main | 2023-05-01T14:38:14.041498 | 2021-05-17T20:15:29 | 2021-05-17T20:15:29 | 356,995,494 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,834 | py | # -*- coding: utf-8 -*-
"""
Created on Thu May 13 05:55:30 2021
@author: Shikhar Bajpai
"""
import cv2 as cv
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import glob
import torch
import os
from PIL import Image, ImageDraw
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
def visualization(image_path,label_path,output=False,resize_dim=1):
'''
Parameters
----------
image_path : STR
DESCRIPTION.
label_path : STR
DESCRIPTION.
output : BOOL, optional
DESCRIPTION. The default is False.
resize_dim : INT, optional
DESCRIPTION. The default is 1.
Returns
-------
None.
NOTE:
This function is used to visualize any input or output image. Format of input and output file
are different therefore there is a optional parameter as ouput which is set to False by default.
Resize_dim takes the value as how much the image was resized.
'''
image = cv.imread(image_path)
f1=open(label_path, 'r')
if (not output):
lines=f1.readlines()[2:]
else:
lines=f1.readlines()
for i in range(len(lines)):
split=lines[i].split(' ')
if( not output):
xmin=int(float(min(split[0],split[2],split[4],split[6])))
xmax=int(float(max(split[0],split[2],split[4],split[6])))
ymin=int(float(min(split[1],split[3],split[5],split[7])))
ymax=int(float(max(split[1],split[3],split[5],split[7])))
else:
if(resize_dim==1):
scale_y=1
scale_x=1
else:
y_,x_,c= image.shape
scale_y=resize_dim/y_
scale_x=resize_dim/x_
xmin=int(float(split[0])/scale_x)
xmax=int(float(split[2])/scale_x)
ymin=int(float(split[1])/scale_y)
ymax=int(float(split[3])/scale_y)
start_point = (xmin, ymin)
end_point = (xmax, ymax)
print (start_point,end_point)
# Blue color in BGR
color = (255, 0, 0)
# Line thickness of 2 px
thickness = 2
# Using cv2.rectangle() method
# Draw a rectangle with blue line borders of thickness of 2 px
print (i)
img_cov = cv.rectangle(image, start_point, end_point, color, thickness)
plt.imshow(img_cov)
plt.show()
#Visualizing input image
visualization('E:/DOTA DATASET/ships_val/P0887.png', 'E:\DOTA DATASET\labels_val\P0887.txt')
#Visualizing output image
visualization('E:/DOTA DATASET/ships_val/P0887.png', 'E:\DOTA DATASET\FastRCNN-split-labels\P0887.txt',output=True)
#Visualizing resized output image
visualization('E:/DOTA DATASET/ships_val/P0887.png', 'E:\DOTA DATASET\resized_labels_val\P0887.txt',ouput=True,resize_dim=2064)
| [
"shikharstruck@gmail.com"
] | shikharstruck@gmail.com |
57b74ea185e7550cf4cb4f8e83d488ac68fa2da2 | 0370bb3899e0f5ca5d151940f98a28c57945cac8 | /blueprints/user.py | 763c09a21ce1dcd337a256a366f748f6d47c0a48 | [] | no_license | mabattistini/beerfactory-api | 8ab302d1109aef6862df68232ca7690b46339920 | b3eeb2ebb183209405aa574070f4ea9a4656037a | refs/heads/master | 2020-12-02T06:36:20.231087 | 2017-07-11T07:12:01 | 2017-07-11T07:12:01 | 96,862,344 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,262 | py | # -*- coding: utf-8 -*-
from flask import Blueprint, jsonify, request, json
from flask_jwt import jwt_required
from app.models.user import User, getUserRecord
from lib.tools import sha224
usr_blueprint = Blueprint('user', __name__)
@usr_blueprint.route('/', methods=['GET'])
@jwt_required()
def index():
listaRecords = User.query.all()
lista = []
for reg in listaRecords:
lista.append(getUserRecord(reg))
return jsonify({'retorno':'sucesso', 'user': lista})
@usr_blueprint.route('/add', methods=['POST'])
@jwt_required()
def add():
if len(request.data) > 0:
data = json.loads(request.data)
userName = data['username']
nome = data['nome']
password = data['password']
else:
userName = request.form.get('username')
nome = request.form.get('nome')
password = request.form.get('password')
password = sha224(password)
newRecord = User(username=userName,nome=nome, password=password)
newRecord.add(newRecord)
return jsonify({'user':[{'retorno':'sucesso','id':newRecord.id}]})
@usr_blueprint.route('/login', methods=['POST'])
@jwt_required()
def login():
return jsonify({'user': [{'retorno': 'erro','mensagem': 'Falha na indentificação'}]}) | [
"mabattistini@gmail.com"
] | mabattistini@gmail.com |
1b5c39bc881e8cafd04e3f2cbd784c8cb2dbfcd0 | 43880d1273cb1104dec7ac982ff8e931a288cb8b | /decoder.py | 710751cb85a4c431f605bc3b7fc0d0d9e92c9185 | [] | no_license | moshen2888/AI-CW2 | 9870aa58bca3086694747f43f1f58b028222fbb2 | 4cf2268829c7ab8feb9cf293e6ff1c8eee795eb2 | refs/heads/main | 2023-04-24T19:33:20.980840 | 2021-05-21T11:39:16 | 2021-05-21T11:39:16 | 369,513,284 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,794 | py | """
COMP5623M Coursework on Image Caption Generation
python decoder.py
"""
import torch
import numpy as np
import torch.nn as nn
from torchvision import transforms
from torch.nn.utils.rnn import pack_padded_sequence
from PIL import Image
import matplotlib.pyplot as pyplot
import random
from datasets import Flickr8k_Images, Flickr8k_Features, Flickr8k_Images_comparison
from models import DecoderRNN, EncoderCNN
from utils import *
from config import *
# if false, train model; otherwise try loading model from checkpoint and evaluate
EVAL = True
# reconstruct the captions and vocab, just as in extract_features.py
lines = read_lines(TOKEN_FILE_TRAIN)
image_ids, cleaned_captions = parse_lines(lines)
vocab = build_vocab(cleaned_captions)
# device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# initialize the models and set the learning parameters
decoder = DecoderRNN(EMBED_SIZE, HIDDEN_SIZE, len(vocab), NUM_LAYERS).to(device)
if not EVAL:
# load the features saved from extract_features.py
print(len(lines))
features = torch.load('features.pt', map_location=device)
print("Loaded features", features.shape)
features = features.repeat_interleave(5, 0)
print("Duplicated features", features.shape)
dataset_train = Flickr8k_Features(
image_ids=image_ids,
captions=cleaned_captions,
vocab=vocab,
features=features,
)
train_loader = torch.utils.data.DataLoader(
dataset_train,
batch_size=64, # change as needed
shuffle=True,
num_workers=0, # may need to set to 0
collate_fn=caption_collate_fn, # explicitly overwrite the collate_fn
)
# loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(decoder.parameters(), lr=LR)
print(len(image_ids))
print(len(cleaned_captions))
print(features.shape)
#########################################################################
#
# QUESTION 1.3 Training DecoderRNN
#
#########################################################################
# TODO write training loop on decoder here
num_epochs = 5
for epoch in range(num_epochs):
epoch_loss = 0
n = 0
# for each batch, prepare the targets using this torch.nn.utils.rnn function
for data in train_loader:
features_batch, captions, lengths = data
features_batch = features_batch.cuda()
captions = captions.cuda()
optimizer.zero_grad()
outputs = decoder(features_batch, captions, lengths)
targets = pack_padded_sequence(captions, lengths, batch_first=True)[0]
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
epoch_loss += loss.item()
n += 1
total_loss = epoch_loss / n
print(total_loss)
# save model after training
decoder_ckpt = torch.save(decoder, "decoder.ckpt")
# if we already trained, and EVAL == True, reload saved model
else:
data_transform = transforms.Compose([
transforms.Resize(224),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize((0.485, 0.456, 0.406), # using ImageNet norms
(0.229, 0.224, 0.225))])
test_lines = read_lines(TOKEN_FILE_TEST)
test_image_ids, test_cleaned_captions = parse_lines(test_lines)
test_image_ids = test_image_ids[::5]
# load models
encoder = EncoderCNN().to(device)
decoder = torch.load("decoder.ckpt").to(device)
encoder.eval()
decoder.eval() # generate caption, eval mode to not influence batchnorm
#########################################################################
#
# QUESTION 2.1 Generating predictions on test data
#
#########################################################################
# TODO define decode_caption() function in utils.py
# predicted_caption = decode_caption(word_ids, vocab)
test_set = Flickr8k_Images_comparison(
image_ids = test_image_ids,
transform = data_transform,
)
# batch_size = 1
test_loader = torch.utils.data.DataLoader(
test_set,
batch_size=1,
shuffle=False,
num_workers=0,
)
sample_ids = []
for i, data in enumerate(test_loader):
image, image_id = data
image = image.cuda()
feature = encoder(image)
if test_loader.batch_size == 1:
feature = torch.squeeze(feature).unsqueeze(0)
else:
feature = torch.squeeze(feature)
sample_id = decoder.sample(feature)
sample_ids.append(sample_id)
# print(sample_ids)
predicted_caption_batch = decode_caption(sample_ids, vocab)
print(len(predicted_caption_batch))
# Store predicted_caption according to image_id
predicted_caption = dict(zip(test_image_ids, predicted_caption_batch))
# print(predicted_caption)
img_id = test_image_ids[108]
print(predicted_caption[img_id])
print(img_id)
#########################################################################
#
# QUESTION 2.2-3 Caption evaluation via text similarity
#
#########################################################################
# Feel free to add helper functions to utils.py as needed,
# documenting what they do in the code and in your report
total_score = []
for ids in test_image_ids:
predicted_captions = []
predicted_captions.append(predicted_caption[ids])
for sentence in predicted_captions:
predicted_words = [x for x in sentence.split(' ')]
reference_words = getreference(ids)
# weights = (1,0,0,0)
# weights = (0.5,0.5,0,0)
# weights = (0.33,0.33,0.33,0)
weights = (0.25,0.25,0.25,0.25)
bleuscore = BleuScore(reference_words, predicted_words, weights)
total_score.append(bleuscore)
# print(total_score)
print("BLEU Average: ", avg_score)
total_cosine_scores = []
for ids in test_image_ids:
cos_reference_words = getreference(ids)
cosine_score = Cosine_sim(predicted_caption, cos_reference_words, vocab, ids)
total_cosine_scores.append(cosine_score)
final_total_scores = []
for score in total_cosine_scores:
cosine_final_score = (score - min(total_cosine_scores)) / (max(total_cosine_scores) - min(total_cosine_scores))
final_total_scores.append(cosine_final_score)
avg_cosine_score = sum(final_total_scores)/len(final_total_scores)
print("Average Cosine Similarity Score: ", avg_cosine_score) | [
"noreply@github.com"
] | moshen2888.noreply@github.com |
f1ef048dff6b754ce5053155e42e2165854b2913 | 5d7a6113c19a6923039569f7cb07c8d525866188 | /lecture4/pages/login_page.py | 2d3381ffe8cd7031bed75329050a2aba3aeceb88 | [] | no_license | kashifch/selenium_training | 34a77fdf2ae16e5098d86d2882eb0b246ddaa7c8 | 3e8465a6be5b16953de2bd2bce4fe4ba60d4b69f | refs/heads/master | 2020-09-29T19:57:38.254442 | 2020-01-27T12:17:27 | 2020-01-27T12:17:27 | 227,110,086 | 1 | 1 | null | 2020-01-27T12:17:28 | 2019-12-10T12:02:08 | Python | UTF-8 | Python | false | false | 879 | py | from .base_page import BasePage
from .dashboard_page import DashboardPage
class LoginPage(BasePage):
def is_browser_on_page(self):
return self.find_elem('button[type="submit"]').is_displayed()
def fill_form(self, user_email, user_password):
email_elem = self.find_elem('#login-email')
email_elem.send_keys(user_email)
#Find and fill the password field
pwd_elem = self.find_elem('#login-password')
pwd_elem.send_keys(user_password)
def submit_form(self):
submit_elem = self.find_elem('button[type="submit"]')
# Wait for submit button to have blue color
self.wait_for_element_color('.login-button', 'rgba(18, 111, 154, 1)')
submit_elem.click()
# self.driver.execute_script("document.querySelector('.login-button').click()")
DashboardPage(self.driver).wait_for_page()
| [
"kashif.chaudhry@arbisoft.com"
] | kashif.chaudhry@arbisoft.com |
c72a6cfe94c62774e52e776dc27fd7cad37b4e39 | 76dde16457b3b41e12fef86e6c8a492ab7eeef7e | /03_pozoleria_map.py | f76261cb3fe9bfe8cc342f56accda0a1e8cf1758 | [] | no_license | Jmarquez30/bedu_data_03_281120 | 332200d554c51aed74ff5129ab16620e6c85c915 | 8f0b43ab5c2e7f75fb364782213824d7c8cee8a2 | refs/heads/main | 2023-01-24T17:07:42.718496 | 2020-11-28T20:14:33 | 2020-11-28T20:14:33 | 316,763,657 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 373 | py | #como usar la funcion map de python
IVA = 0.16
def aplicar_iva(precio):
resultado = precio * (1 * IVA)
return round(resulado, 2)
precios_sin_iva = [415, 90, 355, 385, 115, 100, 250, 600]
print(precios_sin_iva)
#usar map para palicar una funcion a cada elemento de mi lista
precios_con_iva = list(map(aplicar_iva, precios_sin_iva ))
print(precios_con_iva)
| [
"jmarquez.30@hotmail.com"
] | jmarquez.30@hotmail.com |
fad9116ad52a04d52f07e3dce17358804e1f7288 | 3da14b320b1b362bfe7b76244d2dc2e42a68e615 | /src/pyhf/optimize/opt_numpy.py | 3741e20ac670d7f1006e37b0cf2ca1f44ee5d59e | [
"Apache-2.0"
] | permissive | vladov3000/pyhf | d54232fd77b399bae8fb7a4537d94a515e5aacc0 | e55eea408d7c28e3109338de96252119ac63f87a | refs/heads/master | 2022-11-24T16:12:41.264392 | 2020-07-23T22:42:54 | 2020-07-23T22:42:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,019 | py | """Numpy Backend Function Shim."""
from .. import get_backend
from .. import exceptions
def wrap_objective(objective, data, pdf, stitch_pars, do_grad=False, jit_pieces=None):
"""
Wrap the objective function for the minimization.
Args:
objective (`func`): objective function
data (`list`): observed data
pdf (~pyhf.pdf.Model): The statistical model adhering to the schema model.json
stitch_pars (`func`): callable that stitches parameters, see :func:`pyhf.optimize.common.shim`.
do_grad (`bool`): enable autodifferentiation mode. Default is off.
Returns:
objective_and_grad (`func`): tensor backend wrapped objective,gradient pair
"""
tensorlib, _ = get_backend()
if do_grad:
raise exceptions.Unsupported("Numpy does not support autodifferentiation.")
def func(pars):
pars = tensorlib.astensor(pars)
constrained_pars = stitch_pars(pars)
return objective(constrained_pars, data, pdf)
return func
| [
"noreply@github.com"
] | vladov3000.noreply@github.com |
f46544f55783262cd511a1757d6230411238224d | d7f0369feac59997d465b3f55788ee04ad61d6b4 | /libs/flask_volcano/factory.py | 82808f5295150aa4013de479abb3fc1bcb433935 | [] | no_license | volcanicpixels/volcanicpixels | ba0c3e67b88d9485b31d5400acd9149a9e892fd5 | 2913baab89d2206f2c988f47b578403d0163c8e8 | refs/heads/master | 2021-01-22T02:28:34.383613 | 2015-04-27T10:47:11 | 2015-04-27T10:47:11 | 8,817,758 | 1 | 0 | null | 2014-02-27T22:21:55 | 2013-03-16T11:33:01 | Python | UTF-8 | Python | false | false | 1,305 | py | # -*- coding: utf-8 -*-
"""
flask_volcano.factory
~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2013 by Daniel Chatfield
"""
from flask import Flask, Blueprint
from flask.ext.modular_template_loader import register_loader
from .helpers import register_blueprints, url_build_handler, is_dev_server
def create_app(package_name, package_path, config=None, **kwargs):
"""Returns a :class:`Flask` application instance configured with common
extensions.
"""
default_kwargs = {
'instance_relative_config': True,
'template_folder': package_path[0]
}
# Merge the kwargs with the defaults
kwargs = dict(default_kwargs.items() + kwargs.items())
app = Flask(package_name, **kwargs)
app.config.from_object('volcanicpixels.settings')
if is_dev_server():
app.config.from_object('volcanicpixels.dev_keys')
else:
app.config.from_object('volcanicpixels.secret_keys')
app.config.from_pyfile('settings.cfg', silent=True)
app.config.from_object(config)
app.url_build_error_handlers.append(url_build_handler)
register_blueprints(app, package_name, package_path)
register_loader(app)
return app
def create_blueprint(name, import_name, *args, **kwargs):
return Blueprint(name, import_name, *args, **kwargs)
| [
"chatfielddaniel@gmail.com"
] | chatfielddaniel@gmail.com |
ef13df11512ea719086cfbfdf39a8b87e1caf542 | 9cd2a076f5044f29ba336d3a8c9721133f90b8d4 | /lingvodoc/views/v3/views.py | 140de8ccec5a14f09abf287c9a01a148b3430208 | [
"BSD-3-Clause",
"BSD-3-Clause-Modification",
"LGPL-3.0-or-later",
"LicenseRef-scancode-openssl-exception-lgpl3.0plus",
"Zlib",
"ZPL-2.1",
"LGPL-2.1-only",
"Apache-2.0",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-other-permissive",
... | permissive | ispras/lingvodoc | 19e889a92bfd5428fe8f2a409e21b44bd8a25d06 | 4e129f73e99a1dea93d900c4abf476409bc56957 | refs/heads/heavy_refactor | 2023-08-17T10:48:17.617483 | 2023-08-10T13:06:56 | 2023-08-10T13:06:56 | 22,783,020 | 7 | 22 | Apache-2.0 | 2023-09-06T14:13:29 | 2014-08-09T09:19:56 | JavaScript | UTF-8 | Python | false | false | 3,990 | py | # from lingvodoc.views.v2.utils import (
# get_user_by_client_id,
# view_field_from_object,
# check_client_id
# )
# from sqlalchemy.exc import IntegrityError
#
# from pyramid.response import Response
# from pyramid.view import view_config
# from lingvodoc.models import (
# DBSession,
# Locale,
# TranslationAtom,
# TranslationGist,
# BaseGroup,
# User,
# DictionaryPerspective,
# DictionaryPerspectiveToField,
# Field,
# Client,
# Group,
# UserBlobs,
# Language,
# ObjectTOC,
# LexicalEntry,
# Dictionary,
# Entity
# )
#
# from sqlalchemy import (
# func,
# or_,
# and_,
# tuple_
# )
# from pyramid.httpexceptions import (
# HTTPBadRequest,
# HTTPConflict,
# HTTPFound,
# HTTPInternalServerError,
# HTTPNotFound,
# HTTPOk
# )
# from pyramid.security import authenticated_userid
# # from pyramid.chameleon_zpt import render_template_to_response
# from pyramid.renderers import render_to_response
# from lingvodoc.exceptions import CommonException
#
# import sys
# import multiprocessing
#
# if sys.platform == 'darwin':
# multiprocessing.set_start_method('spawn')
#
# import logging
# log = logging.getLogger(__name__)
# import json
# import requests
# from pyramid.request import Request
# from time import time
# from lingvodoc.scheme import schema
#
# # def version_decorator(func):
# # def inner(**kwargs):
# # kwargs['route_name'] = 'v3/' + kwargs['route_name']
# # return func(**kwargs)
# # return inner
# #
# #
# # @version_decorator
# # def view_config(**kwargs):
# # return pyramid_view_config(**kwargs)
# #
# #
# # # @view_config(route_name='v2/testing_decorator', renderer='json')
# # @view_config(route_name='testing_decorator', renderer='json')
# # def testing_decorator(request):
# # return {'42': 'v3'}
# #
# #
# #
# # def testing_add_view(request):
# # return {'answer': 'v3'}
#
# #
# # @view_config(route_name='v3/testing_scan', renderer='json')
# # def testing_scan(request):
# # return {"version": 3}
#
#
#
#
# @view_config(route_name='v3/testing_graphene', renderer='json')
# def testing_graphene(request):
# published = request.params.get('published')
# if published is None:
# published = False
#
# # result = schema.execute('query dictionary{ client dictionaries(published: %s){translation status} dictionary(id: [70,4]){id translation}}' % str(published).lower(),
# # context_value={'client': get_user_by_client_id(authenticated_userid(request)).name,
# # 'locale_id': 1,
# # 'request': request})
#
# # result = schema.execute(
# # 'query perspective{ perspective(id: [630])'
# # '{id translation tree{id translation dataType}'
# # 'fields{id translation}'
# # 'lexicalEntries{id entities{id content fieldType}}'
# # '}}',
# # context_value={'client': get_user_by_client_id(authenticated_userid(request)).name,
# # 'locale_id': 2,
# # 'request': request})
#
#
# result = schema.execute(
# 'query entity{ entity(id: [70, 773])'
# '{ id content fieldType}}',
# context_value={'client': get_user_by_client_id(authenticated_userid(request)).name,
# 'locale_id': 2,
# 'request': request})
#
# # result = schema.execute(
# # 'query perspective{ perspective(id: [70,5])'
# # '{id translation '
# # 'lexicalEntries{id entities{id content fieldType}}'
# # '}}',
# # context_value={'client': get_user_by_client_id(authenticated_userid(request)).name,
# # 'locale_id': 2,
# # 'request': request})
#
# if result.invalid:
# return {'errors': [str(e) for e in result.errors]}
# return result.data
| [
"a.tapekhin@gmail.com"
] | a.tapekhin@gmail.com |
4b19ca2268f7d449f84c5f54f7f7e339e68f9e97 | cf1f1d3f7a4aaaaaee322b0101f7b294909c5a67 | /Code/Kevin/django/ShortenerProj/ShortenerApp/views.py | 169c98adf09a7d1dcc2612f010b37055d1f06769 | [] | no_license | PdxCodeGuild/class_emu | 0b52cc205d01af11860a975fc55e36c065d1cc68 | 9938f384d67a4f57e25f2714efa6b63e2e41b892 | refs/heads/master | 2020-05-31T01:16:52.911660 | 2019-12-09T05:22:06 | 2019-12-09T05:22:06 | 190,046,342 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,170 | py | from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from .models import ShortURL
import random
# Create your views here.
def index(request):
shorturls = ShortURL.objects.all()
context = {
'shorturls': shorturls
}
return render(request, 'shortenerapp/index.html', context)
def saveurl(request):
lurl = request.POST['long_url']
# generate code
password_Length = 6
int_Counter = 0
random_choice = 'abcdefhijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
password = ''
while int_Counter < password_Length:
password += random.choice(random_choice)
int_Counter += 1
print(password)
newshorturl = ShortURL(longurl = lurl, code = password)
newshorturl.save()
return HttpResponseRedirect(reverse('ShortenerApp:index'))
def code_redirect(request, code):
a_url = ShortURL.objects.get(code=code)
# find the record in the ShortURL table whose code matches the given code (.get)
# redirect to the url associated with that code (redirect)
return redirect(a_url.longurl) | [
"wrenJTD@gmail.com"
] | wrenJTD@gmail.com |
b1e5d11c3810f209a4d9efd41bfcd65fb38800dc | 8b20e8f36a1d9758aa927b1674f9877d8a21a6c9 | /hello.py | d534f1d0f2c3794f9d1d4a8953b5775ad17acf7a | [] | no_license | EmperorNiu/ChineseSpeechEvaluationBe | ec5028ada5152c81bc0a6270f6e5110aada4f5d7 | 7d9afd49550b57c9e7d57fe9ac8fc317dca4f248 | refs/heads/main | 2023-03-10T20:01:37.185220 | 2021-02-20T19:17:02 | 2021-02-20T19:17:02 | 337,700,705 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 68 | py | import sys
a = sys.argv[1]
b = sys.argv[2]
print("hello world",a,b) | [
"niuyuean99@sina.com"
] | niuyuean99@sina.com |
b2623d79325303f544e7d0d69417d268e841b738 | 0578fa0de4197184cc603099e44ec2574f2f2543 | /HackerrankBubbleSort.py | 1b529291dac3261f64dd0ab635c8ea739713b0db | [] | no_license | AlMamun-CSE/Python-Problem-Solving | 15c36dac7f55ce680b0f09512e1595802dbd037a | b71d4efe6b784a7f5a94994d9ba60f089f896d39 | refs/heads/master | 2023-01-24T08:30:44.846767 | 2020-12-07T14:28:47 | 2020-12-07T14:28:47 | 318,968,857 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 537 | py | #!/bin/python3
import sys
n = int(input().strip())
a = list(map(int, input().strip().split(' ')))
# Write Your Code Here
numSwaps = 0
for i in range(n):
numberOfSwaps = 0
for j in range(n-1):
if a[j] > a[j+1]:
temp = a[j]
a[j] = a[j+1]
a[j+1] = temp
numberOfSwaps += 1
if numberOfSwaps == 0:
break
else:
numSwaps += numberOfSwaps
print("Array is sorted in %d swaps."%(numSwaps))
print("First Element: %d"%a[0])
print("Last Element: %d"%(a[n-1]))
| [
"almamuncse2020@gmail.com"
] | almamuncse2020@gmail.com |
bd4aad249f16920134c68e9fbf78296000b44bc2 | c50eb81b57f3dac7c0273d1781e4ce5ba9c41584 | /petBookApi/petBookApi/models/pet_allergy_model.py | c67664989193caba336206fb16738bcd41a10203 | [] | no_license | rsbabcock/pet-book | 474b7c6ffb27a2765cbda359b796e089ccc78f45 | ccd548f119fcad93ee85415dddcd3b6c9f1d94d9 | refs/heads/master | 2020-03-27T08:57:34.884012 | 2018-10-13T19:06:47 | 2018-10-13T19:06:47 | 146,301,896 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 496 | py | from django.db import models
class PetAllergy(models.Model):
"""Pet Allergy
This class represents the Pet Allergies join table resource in the database.
Each Model in the join table needs to have a reference as a foreign key
This model is needed to have a join table, but you do not need to reference it anywhere else in this project
"""
pet = models.ForeignKey('Pet', on_delete=models.CASCADE)
allergy = models.ForeignKey('Allergy', on_delete=models.CASCADE)
| [
"rachael.s.babcock@gmail.com"
] | rachael.s.babcock@gmail.com |
97c0f32ede8294cdc6a2e47a1577f8df99873183 | e0219e252eee7e61dffe23584f70f8e8cb879a8f | /hsserver/sqlalchemy-workspace/bin/easy_install | ab91837fbde6e38e3e2806b9747dfc0a8493ff4e | [] | no_license | ColbySaxton/sizzle | 8bda4a4a7036522719603c4ecc041f61c4096300 | c3582698295a225386249bfc7a078ff89a46e511 | refs/heads/master | 2020-04-23T11:01:35.510303 | 2019-02-17T12:39:50 | 2019-02-17T12:39:50 | 171,121,993 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 292 | #!/Users/colbysaxton/Desktop/hotMaps/hsserver/sqlalchemy-workspace/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from setuptools.command.easy_install import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())
| [
"cas264@case.edu"
] | cas264@case.edu | |
fdfaf5133245d102f34dbb38f190dc97481a6095 | bdc0b8809d52933c10f8eb77442bd0b4453f28f9 | /build/std_msgs/rosidl_generator_py/std_msgs/msg/_header.py | 9b81821f0602af102a642cfc19c4bb22e9f5e525 | [] | no_license | ClaytonCalabrese/BuiltRos2Eloquent | 967f688bbca746097016dbd34563716bd98379e3 | 76bca564bfd73ef73485e5c7c48274889032e408 | refs/heads/master | 2021-03-27T22:42:12.976367 | 2020-03-17T14:24:07 | 2020-03-17T14:24:07 | 247,810,969 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,074 | py | # generated from rosidl_generator_py/resource/_idl.py.em
# with input from std_msgs:msg/Header.idl
# generated code does not contain a copyright notice
# Import statements for member types
import rosidl_parser.definition # noqa: E402, I100
class Metaclass_Header(type):
"""Metaclass of message 'Header'."""
_CREATE_ROS_MESSAGE = None
_CONVERT_FROM_PY = None
_CONVERT_TO_PY = None
_DESTROY_ROS_MESSAGE = None
_TYPE_SUPPORT = None
__constants = {
}
@classmethod
def __import_type_support__(cls):
try:
from rosidl_generator_py import import_type_support
module = import_type_support('std_msgs')
except ImportError:
import logging
import traceback
logger = logging.getLogger(
'std_msgs.msg.Header')
logger.debug(
'Failed to import needed modules for type support:\n' +
traceback.format_exc())
else:
cls._CREATE_ROS_MESSAGE = module.create_ros_message_msg__msg__header
cls._CONVERT_FROM_PY = module.convert_from_py_msg__msg__header
cls._CONVERT_TO_PY = module.convert_to_py_msg__msg__header
cls._TYPE_SUPPORT = module.type_support_msg__msg__header
cls._DESTROY_ROS_MESSAGE = module.destroy_ros_message_msg__msg__header
from builtin_interfaces.msg import Time
if Time.__class__._TYPE_SUPPORT is None:
Time.__class__.__import_type_support__()
@classmethod
def __prepare__(cls, name, bases, **kwargs):
# list constant names here so that they appear in the help text of
# the message class under "Data and other attributes defined here:"
# as well as populate each message instance
return {
}
class Header(metaclass=Metaclass_Header):
"""Message class 'Header'."""
__slots__ = [
'_stamp',
'_frame_id',
]
_fields_and_field_types = {
'stamp': 'builtin_interfaces/Time',
'frame_id': 'string',
}
SLOT_TYPES = (
rosidl_parser.definition.NamespacedType(['builtin_interfaces', 'msg'], 'Time'), # noqa: E501
rosidl_parser.definition.UnboundedString(), # noqa: E501
)
def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %s' % \
', '.join(sorted(k for k in kwargs.keys() if '_' + k not in self.__slots__))
from builtin_interfaces.msg import Time
self.stamp = kwargs.get('stamp', Time())
self.frame_id = kwargs.get('frame_id', str())
def __repr__(self):
typename = self.__class__.__module__.split('.')
typename.pop()
typename.append(self.__class__.__name__)
args = []
for s, t in zip(self.__slots__, self.SLOT_TYPES):
field = getattr(self, s)
fieldstr = repr(field)
# We use Python array type for fields that can be directly stored
# in them, and "normal" sequences for everything else. If it is
# a type that we store in an array, strip off the 'array' portion.
if (
isinstance(t, rosidl_parser.definition.AbstractSequence) and
isinstance(t.value_type, rosidl_parser.definition.BasicType) and
t.value_type.typename in ['float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64']
):
if len(field) == 0:
fieldstr = '[]'
else:
assert fieldstr.startswith('array(')
prefix = "array('X', "
suffix = ')'
fieldstr = fieldstr[len(prefix):-len(suffix)]
args.append(s[1:] + '=' + fieldstr)
return '%s(%s)' % ('.'.join(typename), ', '.join(args))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.stamp != other.stamp:
return False
if self.frame_id != other.frame_id:
return False
return True
@classmethod
def get_fields_and_field_types(cls):
from copy import copy
return copy(cls._fields_and_field_types)
@property
def stamp(self):
"""Message field 'stamp'."""
return self._stamp
@stamp.setter
def stamp(self, value):
if __debug__:
from builtin_interfaces.msg import Time
assert \
isinstance(value, Time), \
"The 'stamp' field must be a sub message of type 'Time'"
self._stamp = value
@property
def frame_id(self):
"""Message field 'frame_id'."""
return self._frame_id
@frame_id.setter
def frame_id(self, value):
if __debug__:
assert \
isinstance(value, str), \
"The 'frame_id' field must be of type 'str'"
self._frame_id = value
| [
"calabreseclayton@gmail.com"
] | calabreseclayton@gmail.com |
0efa85ab2f38d40aa8bc541800359c5db6ec6353 | f87d67c70cf13512320d50671e9bf31c5653f795 | /temple_project/use_app/admin.py | a7eb79d8f945c596322e8509e4e63bf1442b0b6f | [] | no_license | wtyhome/testing | bf6e5b45e8efc0696c0bf877868ee1adf54c8c79 | 663b7d4714aedff0d516bc5eb3d29c2f72a98c90 | refs/heads/master | 2020-12-22T18:34:36.328037 | 2020-01-29T02:53:11 | 2020-01-29T02:53:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,036 | py | from django.contrib import admin
from .models import Home, People_data, activity_data,history_data
# Register your models here.
admin.site.site_header = '後臺管理系統'
admin.site.site_title = '後臺管理'
admin.site.index_title = '鄉廟資料庫 管理'
class set_history(admin.ModelAdmin):
list_display = [field.name for field in history_data._meta.fields]
class Meat:
ordering = ['order_date']
admin.site.register(history_data,set_history)
class set_home(admin.ModelAdmin):
list_display = [field.name for field in Home._meta.fields]
class Meat:
ordering = ['order_date']
class set_people_data(admin.ModelAdmin):
list_display = [field.name for field in People_data._meta.fields]
class set_activity(admin.ModelAdmin):
list_display = [field.name for field in activity_data._meta.fields]
class Meat:
ordering = ['order_date']
admin.site.register(Home, set_home)
admin.site.register(activity_data, set_activity)
admin.site.register(People_data, set_people_data)
| [
"asd19199009@gmail.com"
] | asd19199009@gmail.com |
8baad6fdfbd6f0d94ef8ee0e79d18a18ebbde60c | 6230afce84d14ab22f52fcc3fe6879bb8ee6f324 | /0x0A-python-inheritance/100-my_int.py | 75c0c7f3f2837d5e7cc0de2832cbf5a57ef77dcd | [] | no_license | Rielch/holbertonschool-higher_level_programming | a7b4c893953f269fff6ebec0d858dab930c0b1f3 | cb7505dc860891ef33a2bd5408defcedf01d7bf3 | refs/heads/main | 2023-07-10T12:56:37.666165 | 2021-08-20T20:05:54 | 2021-08-20T20:05:54 | 319,380,808 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 578 | py | #!/usr/bin/python3
"""Creates a class MyInt that inherites from int that inverts == and !="""
class MyInt(int):
"""Class that inherites from int but inverts == and !="""
def __init__(self, value):
"""Initializates a MyInt class"""
self.value = value
def __new__(cls, value):
"""Creates a new int object"""
return int.__new__(cls, value)
def __eq__(self, other):
"""defines equality"""
return self.value != other
def __ne__(self, other):
"""defines inequality"""
return self.value == other
| [
"2288@holbertonschool.com"
] | 2288@holbertonschool.com |
5c4e8a88206eeec9f0f6a8c430c17346c8d7179c | 8366f74f63b5fabf6d9eb400dfebeac051d283e5 | /vir/lib/python2.7/site-packages/scss/tool.py | 205bb8170a167d92a4ffbbf669bc95f28cc417a2 | [] | no_license | matthewst/flask-skeleton | 6438d2fb4d57b7222d8b67b8bbee4eb9957b6db6 | 9aa62336ba21d464e854bf16f997cec034474d34 | refs/heads/master | 2020-05-29T18:40:15.896150 | 2015-03-04T12:45:04 | 2015-03-04T12:45:04 | 31,656,127 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 15,962 | py | #!/usr/bin/env python
from __future__ import absolute_import
from __future__ import print_function
from contextlib import contextmanager
import logging
import os
import re
import sys
from collections import deque
from scss import config
from scss.util import profiling
from scss import Scss, SourceFile, log
from scss import _prop_split_re
from scss.rule import SassRule
from scss.rule import UnparsedBlock
from scss.expression import Calculator
from scss.scss_meta import BUILD_INFO
from scss.errors import SassEvaluationError
try:
raw_input
except NameError:
raw_input = input
log.setLevel(logging.INFO)
def main():
logging.basicConfig(format="%(levelname)s: %(message)s")
from optparse import OptionGroup, OptionParser, SUPPRESS_HELP
parser = OptionParser(usage="Usage: %prog [options] [file]",
description="Converts Scss files to CSS.",
add_help_option=False)
parser.add_option("-i", "--interactive", action="store_true",
help="Run an interactive Scss shell")
parser.add_option("-w", "--watch", metavar="DIR",
help="Watch the files in DIR, and recompile when they change")
parser.add_option("-r", "--recursive", action="store_true", default=False,
help="Also watch directories inside of the watch directory")
parser.add_option("-o", "--output", metavar="PATH",
help="Write output to PATH (a directory if using watch, a file otherwise)")
parser.add_option("-s", "--suffix", metavar="STRING",
help="If using watch, a suffix added to the output filename (i.e. filename.STRING.css)")
parser.add_option("--time", action="store_true",
help="Display compliation times")
parser.add_option("--debug-info", action="store_true",
help="Turns on scss's debugging information")
parser.add_option("--no-debug-info", action="store_false",
dest="debug_info", default=False,
help="Turns off scss's debugging information")
parser.add_option("-T", "--test", action="store_true", help=SUPPRESS_HELP)
parser.add_option("-t", "--style", metavar="NAME",
dest="style", default='nested',
help="Output style. Can be nested (default), compact, compressed, or expanded.")
parser.add_option("-C", "--no-compress", action="store_false", dest="style", default=True,
help="Don't minify outputted CSS")
parser.add_option("-?", action="help", help=SUPPRESS_HELP)
parser.add_option("-h", "--help", action="help",
help="Show this message and exit")
parser.add_option("-v", "--version", action="store_true",
help="Print version and exit")
paths_group = OptionGroup(parser, "Resource Paths")
paths_group.add_option("-I", "--load-path", metavar="PATH",
action="append", dest="load_paths",
help="Add a scss import path, may be given multiple times")
paths_group.add_option("-S", "--static-root", metavar="PATH", dest="static_root",
help="Static root path (Where images and static resources are located)")
paths_group.add_option("-A", "--assets-root", metavar="PATH", dest="assets_root",
help="Assets root path (Sprite images will be created here)")
paths_group.add_option("-a", "--assets-url", metavar="URL", dest="assets_url",
help="URL to reach the files in your assets_root")
paths_group.add_option("-F", "--fonts-root", metavar="PATH", dest="fonts_root",
help="Fonts root path (Where fonts are located)")
paths_group.add_option("-f", "--fonts-url", metavar="PATH", dest="fonts_url",
help="URL to reach the fonts in your fonts_root")
paths_group.add_option("--images-root", metavar="PATH", dest="images_root",
help="Images root path (Where images are located)")
paths_group.add_option("--images-url", metavar="PATH", dest="images_url",
help="URL to reach the images in your images_root")
paths_group.add_option("--cache-root", metavar="PATH", dest="cache_root",
help="Cache root path (Cache files will be created here)")
parser.add_option_group(paths_group)
parser.add_option("--sass", action="store_true",
dest="is_sass", default=None,
help="Sass mode")
(options, args) = parser.parse_args()
# General runtime configuration
config.VERBOSITY = 0
if options.time:
config.VERBOSITY = 2
if options.static_root is not None:
config.STATIC_ROOT = options.static_root
if options.assets_root is not None:
config.ASSETS_ROOT = options.assets_root
if options.fonts_root is not None:
config.FONTS_ROOT = options.fonts_root
if options.fonts_url is not None:
config.FONTS_URL = options.fonts_url
if options.images_root is not None:
config.IMAGES_ROOT = options.images_root
if options.images_url is not None:
config.IMAGES_URL = options.images_url
if options.cache_root is not None:
config.CACHE_ROOT = options.cache_root
if options.load_paths is not None:
# TODO: Convert global LOAD_PATHS to a list. Use it directly.
# Doing the above will break backwards compatibility!
if hasattr(config.LOAD_PATHS, 'split'):
load_path_list = [p.strip() for p in config.LOAD_PATHS.split(',')]
else:
load_path_list = list(config.LOAD_PATHS)
for path_param in options.load_paths:
for p in path_param.replace(os.pathsep, ',').replace(';', ',').split(','):
p = p.strip()
if p and p not in load_path_list:
load_path_list.append(p)
# TODO: Remove this once global LOAD_PATHS is a list.
if hasattr(config.LOAD_PATHS, 'split'):
config.LOAD_PATHS = ','.join(load_path_list)
else:
config.LOAD_PATHS = load_path_list
if options.assets_url is not None:
config.ASSETS_URL = options.assets_url
# Execution modes
if options.test:
run_tests()
elif options.version:
print_version()
elif options.interactive:
run_repl(options)
elif options.watch:
watch_sources(options)
else:
do_build(options, args)
def print_version():
print(BUILD_INFO)
def run_tests():
try:
import pytest
except ImportError:
raise ImportError("You need py.test installed to run the test suite.")
pytest.main("") # don't let py.test re-consume our arguments
def do_build(options, args):
if options.output is not None:
output = open(options.output, 'wt')
else:
output = sys.stdout
css = Scss(scss_opts={
'style': options.style,
'debug_info': options.debug_info,
})
if args:
for path in args:
output.write(css.compile(scss_file=path, is_sass=options.is_sass))
else:
output.write(css.compile(sys.stdin.read(), is_sass=options.is_sass))
for f, t in profiling.items():
sys.stderr.write("%s took %03fs" % (f, t))
def watch_sources(options):
import time
try:
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
except ImportError:
sys.stderr.write("Using watch functionality requires the `watchdog` library: http://pypi.python.org/pypi/watchdog/")
sys.exit(1)
if options.output and not os.path.isdir(options.output):
sys.stderr.write("watch file output directory is invalid: '%s'" % (options.output))
sys.exit(2)
class ScssEventHandler(PatternMatchingEventHandler):
def __init__(self, *args, **kwargs):
super(ScssEventHandler, self).__init__(*args, **kwargs)
self.css = Scss(scss_opts={
'style': options.style,
'debug_info': options.debug_info,
})
self.output = options.output
self.suffix = options.suffix
def is_valid(self, path):
return os.path.isfile(path) and (path.endswith('.scss') or path.endswith('.sass')) and not os.path.basename(path).startswith('_')
def process(self, path):
if os.path.isdir(path):
for f in os.listdir(path):
full = os.path.join(path, f)
if self.is_valid(full):
self.compile(full)
elif self.is_valid(path):
self.compile(path)
def compile(self, src_path):
fname = os.path.basename(src_path)
if fname.endswith('.scss') or fname.endswith('.sass'):
fname = fname[:-5]
if self.suffix:
fname += '.' + self.suffix
fname += '.css'
else:
# you didn't give me a file of the correct type!
return False
if self.output:
dest_path = os.path.join(self.output, fname)
else:
dest_path = os.path.join(os.path.dirname(src_path), fname)
print("Compiling %s => %s" % (src_path, dest_path))
dest_file = open(dest_path, 'w')
dest_file.write(self.css.compile(scss_file=src_path))
def on_moved(self, event):
super(ScssEventHandler, self).on_moved(event)
self.process(event.dest_path)
def on_created(self, event):
super(ScssEventHandler, self).on_created(event)
self.process(event.src_path)
def on_modified(self, event):
super(ScssEventHandler, self).on_modified(event)
self.process(event.src_path)
event_handler = ScssEventHandler(patterns=['*.scss', '*.sass'])
observer = Observer()
observer.schedule(event_handler, path=options.watch, recursive=options.recursive)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
@contextmanager
def readline_history(fn):
try:
import readline
except ImportError:
yield
return
try:
readline.read_history_file(fn)
except IOError:
pass
try:
yield
finally:
try:
readline.write_history_file(fn)
except IOError:
pass
def run_repl(is_sass=False):
repl = SassRepl()
with readline_history(os.path.expanduser('~/.scss-history')):
print("Welcome to %s interactive shell" % (BUILD_INFO,))
while True:
try:
in_ = raw_input('>>> ').strip()
for output in repl(in_):
print(output)
except (EOFError, KeyboardInterrupt):
print("Bye!")
return
class SassRepl(object):
def __init__(self, is_sass=False):
self.css = Scss()
self.namespace = self.css.root_namespace
self.options = self.css.scss_opts
self.source_file = SourceFile.from_string('', '<shell>', line_numbers=False, is_sass=is_sass)
self.calculator = Calculator(self.namespace)
def __call__(self, s):
from pprint import pformat
if s in ('exit', 'quit'):
raise KeyboardInterrupt
for s in s.split(';'):
s = self.source_file.prepare_source(s.strip())
if not s:
continue
elif s.startswith('@'):
scope = None
properties = []
children = deque()
rule = SassRule(self.source_file, namespace=self.namespace, options=self.options, properties=properties)
block = UnparsedBlock(rule, 1, s, None)
code, name = (s.split(None, 1) + [''])[:2]
if code == '@option':
self.css._settle_options(rule, children, scope, block)
continue
elif code == '@import':
self.css._do_import(rule, children, scope, block)
continue
elif code == '@include':
final_cont = ''
self.css._do_include(rule, children, scope, block)
code = self.css._print_properties(properties).rstrip('\n')
if code:
final_cont += code
if children:
self.css.children.extendleft(children)
self.css.parse_children()
code = self.css._create_css(self.css.rules).rstrip('\n')
if code:
final_cont += code
yield final_cont
continue
elif s == 'ls' or s.startswith('show(') or s.startswith('show ') or s.startswith('ls(') or s.startswith('ls '):
m = re.match(r'(?:show|ls)(\()?\s*([^,/\\) ]*)(?:[,/\\ ]([^,/\\ )]+))*(?(1)\))', s, re.IGNORECASE)
if m:
name = m.group(2)
code = m.group(3)
name = name and name.strip().rstrip('s') # remove last 's' as in functions
code = code and code.strip()
ns = self.namespace
if not name:
yield pformat(sorted(['vars', 'options', 'mixins', 'functions']))
elif name in ('v', 'var', 'variable'):
variables = dict(ns._variables)
if code == '*':
pass
elif code:
variables = dict((k, v) for k, v in variables.items() if code in k)
else:
variables = dict((k, v) for k, v in variables.items() if not k.startswith('$--'))
yield pformat(variables)
elif name in ('o', 'opt', 'option'):
opts = self.options
if code == '*':
pass
elif code:
opts = dict((k, v) for k, v in opts.items() if code in k)
else:
opts = dict((k, v) for k, v in opts.items() if not k.startswith('@'))
yield pformat(opts)
elif name in ('m', 'mix', 'mixin', 'f', 'func', 'funct', 'function'):
if name.startswith('m'):
funcs = dict(ns._mixins)
elif name.startswith('f'):
funcs = dict(ns._functions)
if code == '*':
pass
elif code:
funcs = dict((k, v) for k, v in funcs.items() if code in k[0])
else:
pass
# TODO print source when possible
yield pformat(funcs)
continue
elif s.startswith('$') and (':' in s or '=' in s):
prop, value = [a.strip() for a in _prop_split_re.split(s, 1)]
prop = self.calculator.do_glob_math(prop)
value = self.calculator.calculate(value)
self.namespace.set_variable(prop, value)
continue
# TODO respect compress?
try:
yield(self.calculator.calculate(s).render())
except (SyntaxError, SassEvaluationError) as e:
print("%s" % e, file=sys.stderr)
if __name__ == "__main__":
main()
| [
"ykur@seznam.cz"
] | ykur@seznam.cz |
891b80fe0e964a07d5c4a98e20bab20b2fd165a9 | b2e306049892a510c4623f0f16653274c7bdd760 | /MinAvgTwoSlice.py | 5f34f76e66ee9343fe1acebec6cfa95e5aa6c014 | [] | no_license | letteropener/algo_exercises | 199fcf377538cbb1784aa4518caeacbc98b4f095 | b176fef271cb593d4e7fbed032a8b4b0f9d8ad53 | refs/heads/master | 2020-03-22T15:59:41.851136 | 2018-07-20T16:15:59 | 2018-07-20T16:15:59 | 140,294,719 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,429 | py | '''
A non-empty array A consisting of N integers is given. A pair of integers (P, Q), such that 0 ≤ P < Q < N, is called a slice of array A (notice that the slice contains at least two elements). The average of a slice (P, Q) is the sum of A[P] + A[P + 1] + ... + A[Q] divided by the length of the slice. To be precise, the average equals (A[P] + A[P + 1] + ... + A[Q]) / (Q − P + 1).
For example, array A such that:
A[0] = 4
A[1] = 2
A[2] = 2
A[3] = 5
A[4] = 1
A[5] = 5
A[6] = 8
contains the following example slices:
slice (1, 2), whose average is (2 + 2) / 2 = 2;
slice (3, 4), whose average is (5 + 1) / 2 = 3;
slice (1, 4), whose average is (2 + 2 + 5 + 1) / 4 = 2.5.
The goal is to find the starting position of a slice whose average is minimal.
Write a function:
class Solution { public int solution(int[] A); }
that, given a non-empty array A consisting of N integers, returns the starting position of the slice with the minimal average. If there is more than one slice with a minimal average, you should return the smallest starting position of such a slice.
For example, given array A such that:
A[0] = 4
A[1] = 2
A[2] = 2
A[3] = 5
A[4] = 1
A[5] = 5
A[6] = 8
the function should return 1, as explained above.
Assume that:
N is an integer within the range [2..100,000];
each element of array A is an integer within the range [−10,000..10,000].
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N) (not counting the storage required for input arguments).
'''
def solution(A):
min_avg_value = (A[0] + A[1]) / 2.0 # The mininal average
min_avg_pos = 0 # The begin position of the first
# slice with mininal average
for index in range(0, len(A) - 2):
# Try the next 2-element slice
if (A[index] + A[index + 1]) / 2.0 < min_avg_value:
min_avg_value = (A[index] + A[index + 1]) / 2.0
min_avg_pos = index
# Try the next 3-element slice
if (A[index] + A[index + 1] + A[index + 2]) / 3.0 < min_avg_value:
min_avg_value = (A[index] + A[index + 1] + A[index + 2]) / 3.0
min_avg_pos = index
# Try the last 2-element slice
if (A[-1] + A[-2]) / 2.0 < min_avg_value:
min_avg_value = (A[-1] + A[-2]) / 2.0
min_avg_pos = len(A) - 2
return min_avg_pos
print(solution([4,2,2,5,1,5,8])) | [
"letteropener2011@gmail.com"
] | letteropener2011@gmail.com |
76248405f1c00343fddef1efe2213d5897023cdc | 51086c09f2c920d057db12e373a01b08571c4cbf | /pebble-sdk/SDKs/4.3/sdk-core/pebble/common/tools/inject_metadata.py | 132a3d5457b902f386c30f11dc86721ecedec725 | [] | no_license | JohnHoder/pebble-dev | 66dc69258dfd009313c23ba5c2eb518aec257652 | e9d95bd564ba6f58b539a1a68f21fe82b6d0992b | refs/heads/master | 2022-11-23T17:32:26.573394 | 2018-12-26T03:17:37 | 2018-12-26T03:17:37 | 163,131,045 | 0 | 1 | null | 2022-10-31T10:03:38 | 2018-12-26T03:15:57 | Python | UTF-8 | Python | false | false | 11,374 | py | #!/usr/bin/env python
from __future__ import with_statement
from struct import pack, unpack
import os
import os.path
import sys
import time
from subprocess import Popen, PIPE
from shutil import copy2
from binascii import crc32
from struct import pack
from pbpack import ResourcePack
import stm32_crc
# Pebble App Metadata Struct
# These are offsets of the PebbleProcessInfo struct in src/fw/app_management/pebble_process_info.h
HEADER_ADDR = 0x0 # 8 bytes
STRUCT_VERSION_ADDR = 0x8 # 2 bytes
SDK_VERSION_ADDR = 0xa # 2 bytes
APP_VERSION_ADDR = 0xc # 2 bytes
LOAD_SIZE_ADDR = 0xe # 2 bytes
OFFSET_ADDR = 0x10 # 4 bytes
CRC_ADDR = 0x14 # 4 bytes
NAME_ADDR = 0x18 # 32 bytes
COMPANY_ADDR = 0x38 # 32 bytes
ICON_RES_ID_ADDR = 0x58 # 4 bytes
JUMP_TABLE_ADDR = 0x5c # 4 bytes
FLAGS_ADDR = 0x60 # 4 bytes
NUM_RELOC_ENTRIES_ADDR = 0x64 # 4 bytes
UUID_ADDR = 0x68 # 16 bytes
RESOURCE_CRC_ADDR = 0x78 # 4 bytes
RESOURCE_TIMESTAMP_ADDR = 0x7c # 4 bytes
VIRTUAL_SIZE_ADDR = 0x80 # 2 bytes
STRUCT_SIZE_BYTES = 0x82
# Pebble App Flags
# These are PebbleAppFlags from src/fw/app_management/pebble_process_info.h
PROCESS_INFO_STANDARD_APP = (0)
PROCESS_INFO_WATCH_FACE = (1 << 0)
PROCESS_INFO_VISIBILITY_HIDDEN = (1 << 1)
PROCESS_INFO_VISIBILITY_SHOWN_ON_COMMUNICATION = (1 << 2)
PROCESS_INFO_ALLOW_JS = (1 << 3)
PROCESS_INFO_HAS_WORKER = (1 << 4)
# Max app size, including the struct and reloc table
# Note that even if the app is smaller than this, it still may be too big, as it needs to share this
# space with applib/ which changes in size from release to release.
MAX_APP_BINARY_SIZE = 0x10000
# This number is a rough estimate, but should not be less than the available space.
# Currently, app_state uses up a small part of the app space.
# See also APP_RAM in stm32f2xx_flash_fw.ld and APP in pebble_app.ld.
MAX_APP_MEMORY_SIZE = 24 * 1024
# This number is a rough estimate, but should not be less than the available space.
# Currently, worker_state uses up a small part of the worker space.
# See also WORKER_RAM in stm32f2xx_flash_fw.ld
MAX_WORKER_MEMORY_SIZE = 10 * 1024
ENTRY_PT_SYMBOL = 'main'
JUMP_TABLE_ADDR_SYMBOL = 'pbl_table_addr'
DEBUG = False
class InvalidBinaryError(Exception):
pass
def inject_metadata(target_binary, target_elf, resources_file, timestamp, allow_js=False,
has_worker=False):
if target_binary[-4:] != '.bin':
raise Exception("Invalid filename <%s>! The filename should end in .bin" % target_binary)
def get_nm_output(elf_file):
nm_process = Popen(['arm-none-eabi-nm', elf_file], stdout=PIPE)
# Popen.communicate returns a tuple of (stdout, stderr)
nm_output = nm_process.communicate()[0]
if not nm_output:
raise InvalidBinaryError()
nm_output = [ line.split() for line in nm_output.splitlines() ]
return nm_output
def get_symbol_addr(nm_output, symbol):
# nm output looks like the following...
#
# U _ITM_registerTMCloneTable
# 00000084 t jump_to_pbl_function
# U _Jv_RegisterClasses
# 0000009c T main
# 00000130 T memset
#
# We don't care about the lines that only have two columns, they're not functions.
for sym in nm_output:
if symbol == sym[-1] and len(sym) == 3:
return int(sym[0], 16)
raise Exception("Could not locate symbol <%s> in binary! Failed to inject app metadata" %
(symbol))
def get_virtual_size(elf_file):
""" returns the virtual size (static memory usage, .text + .data + .bss) in bytes """
readelf_bss_process = Popen("arm-none-eabi-readelf -S '%s'" % elf_file,
shell=True, stdout=PIPE)
readelf_bss_output = readelf_bss_process.communicate()[0]
# readelf -S output looks like the following...
#
# [Nr] Name Type Addr Off Size ES Flg Lk Inf Al
# [ 0] NULL 00000000 000000 000000 00 0 0 0
# [ 1] .header PROGBITS 00000000 008000 000082 00 A 0 0 1
# [ 2] .text PROGBITS 00000084 008084 0006be 00 AX 0 0 4
# [ 3] .rel.text REL 00000000 00b66c 0004d0 08 23 2 4
# [ 4] .data PROGBITS 00000744 008744 000004 00 WA 0 0 4
# [ 5] .bss NOBITS 00000748 008748 000054 00 WA 0 0 4
last_section_end_addr = 0
# Find the .bss section and calculate the size based on the end of the .bss section
for line in readelf_bss_output.splitlines():
if len(line) < 10:
continue
# Carve off the first column, since it sometimes has a space in it which screws up the
# split. Two leading spaces, a square bracket, 2 digits (with space padding),
# a second square brack is 6
line = line[6:]
columns = line.split()
if len(columns) < 6:
continue
if columns[0] == '.bss':
addr = int(columns[2], 16)
size = int(columns[4], 16)
last_section_end_addr = addr + size
elif columns[0] == '.data' and last_section_end_addr == 0:
addr = int(columns[2], 16)
size = int(columns[4], 16)
last_section_end_addr = addr + size
if last_section_end_addr != 0:
return last_section_end_addr
sys.stderr.writeline("Failed to parse ELF sections while calculating the virtual size\n")
sys.stderr.write(readelf_bss_output)
raise Exception("Failed to parse ELF sections while calculating the virtual size")
def get_relocate_entries(elf_file):
""" returns a list of all the locations requiring an offset"""
# TODO: insert link to the wiki page I'm about to write about PIC and relocatable values
entries = []
# get the .data locations
readelf_relocs_process = Popen(['arm-none-eabi-readelf', '-r', elf_file], stdout=PIPE)
readelf_relocs_output = readelf_relocs_process.communicate()[0]
lines = readelf_relocs_output.splitlines()
i = 0
reading_section = False
while i < len(lines):
if not reading_section:
# look for the next section
if lines[i].startswith("Relocation section '.rel.data"):
reading_section = True
i += 1 # skip the column title section
else:
if len(lines[i]) == 0:
# end of the section
reading_section = False
else:
entries.append(int(lines[i].split(' ')[0], 16))
i += 1
# get any Global Offset Table (.got) entries
readelf_relocs_process = Popen(['arm-none-eabi-readelf', '--sections', elf_file],
stdout=PIPE)
readelf_relocs_output = readelf_relocs_process.communicate()[0]
lines = readelf_relocs_output.splitlines()
for line in lines:
# We shouldn't need to do anything with the Procedure Linkage Table since we don't
# actually export functions
if '.got' in line and '.got.plt' not in line:
words = line.split(' ')
while '' in words:
words.remove('')
section_label_idx = words.index('.got')
addr = int(words[section_label_idx + 2], 16)
length = int(words[section_label_idx + 4], 16)
for i in range(addr, addr + length, 4):
entries.append(i)
break
return entries
nm_output = get_nm_output(target_elf)
try:
app_entry_address = get_symbol_addr(nm_output, ENTRY_PT_SYMBOL)
except:
raise Exception("Missing app entry point! Must be `int main(void) { ... }` ")
jump_table_address = get_symbol_addr(nm_output, JUMP_TABLE_ADDR_SYMBOL)
reloc_entries = get_relocate_entries(target_elf)
statinfo = os.stat(target_binary)
app_load_size = statinfo.st_size
if resources_file is not None:
with open(resources_file, 'rb') as f:
pbpack = ResourcePack.deserialize(f, is_system=False)
resource_crc = pbpack.get_content_crc()
else:
resource_crc = 0
if DEBUG:
copy2(target_binary, target_binary + ".orig")
with open(target_binary, 'r+b') as f:
total_app_image_size = app_load_size + (len(reloc_entries) * 4)
if total_app_image_size > MAX_APP_BINARY_SIZE:
raise Exception("App image size is %u (app %u relocation table %u). Must be smaller "
"than %u bytes" % (total_app_image_size,
app_load_size,
len(reloc_entries) * 4,
MAX_APP_BINARY_SIZE))
def read_value_at_offset(offset, format_str, size):
f.seek(offset)
return unpack(format_str, f.read(size))
app_bin = f.read()
app_crc = stm32_crc.crc32(app_bin[STRUCT_SIZE_BYTES:])
[app_flags] = read_value_at_offset(FLAGS_ADDR, '<L', 4)
if allow_js:
app_flags = app_flags | PROCESS_INFO_ALLOW_JS
if has_worker:
app_flags = app_flags | PROCESS_INFO_HAS_WORKER
app_virtual_size = get_virtual_size(target_elf)
struct_changes = {
'load_size' : app_load_size,
'entry_point' : "0x%08x" % app_entry_address,
'symbol_table' : "0x%08x" % jump_table_address,
'flags' : app_flags,
'crc' : "0x%08x" % app_crc,
'num_reloc_entries': "0x%08x" % len(reloc_entries),
'resource_crc' : "0x%08x" % resource_crc,
'timestamp' : timestamp,
'virtual_size': app_virtual_size
}
def write_value_at_offset(offset, format_str, value):
f.seek(offset)
f.write(pack(format_str, value))
write_value_at_offset(LOAD_SIZE_ADDR, '<H', app_load_size)
write_value_at_offset(OFFSET_ADDR, '<L', app_entry_address)
write_value_at_offset(CRC_ADDR, '<L', app_crc)
write_value_at_offset(RESOURCE_CRC_ADDR, '<L', resource_crc)
write_value_at_offset(RESOURCE_TIMESTAMP_ADDR, '<L', timestamp)
write_value_at_offset(JUMP_TABLE_ADDR, '<L', jump_table_address)
write_value_at_offset(FLAGS_ADDR, '<L', app_flags)
write_value_at_offset(NUM_RELOC_ENTRIES_ADDR, '<L', len(reloc_entries))
write_value_at_offset(VIRTUAL_SIZE_ADDR, "<H", app_virtual_size)
# Write the reloc_entries past the end of the binary. This expands the size of the binary,
# but this new stuff won't actually be loaded into ram.
f.seek(app_load_size)
for entry in reloc_entries:
f.write(pack('<L', entry))
f.flush()
return struct_changes
| [
"hoder.john@gmail.com"
] | hoder.john@gmail.com |
02b18a3855a92224188e775e3c0f3759dfe9ae54 | d6abe9b5286efeaca03b08325690c4e32a00994f | /index/urls.py | 3707dd480c4030805d5ec0c77429b914ec913817 | [] | no_license | lookflying/pictrail | b5e8896ae53bdde9201d81e2689b7c75c2921630 | 1f00c173cdc88fc3b6746f8c86732e3d067559e4 | refs/heads/master | 2020-06-01T16:05:59.618272 | 2014-07-24T01:59:06 | 2014-07-24T01:59:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 139 | py | from django.conf.urls import patterns, url
from index import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
)
| [
"lookflying@gmail.com"
] | lookflying@gmail.com |
0edb15c99b81287d2f5f4c1a226de09d6b692c6c | ce0a34a4a1f44cda31042e4294e6cef334392a37 | /tests/test_gui_klgui.py | 9c28eb7d7c5c47e2c9694da7f660414fd1c1df94 | [
"GPL-3.0-only"
] | permissive | PhonologicalCorpusTools/CorpusTools | ba6644f90a9790d3f61d923b3b5622eaeaa24caa | 314bd30be24b1cb7ee0c252a6529bbfe964056ad | refs/heads/master | 2022-09-29T20:36:12.148289 | 2022-09-16T01:57:47 | 2022-09-16T01:57:47 | 18,848,568 | 108 | 24 | BSD-3-Clause | 2021-05-07T23:58:03 | 2014-04-16T17:14:55 | Python | UTF-8 | Python | false | false | 188 | py |
from corpustools.gui.klgui import *
def test_klgui(qtbot, specified_test_corpus, settings):
dialog = KLDialog(None, settings,specified_test_corpus, True)
qtbot.addWidget(dialog)
| [
"michael.e.mcauliffe@gmail.com"
] | michael.e.mcauliffe@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.