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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
65d209957ed0b1274f6084fdff6c816d0a95f31b | fe9f6bfbc08fffc6cb4e27f251b5768031dbbe5d | /mysite/settings.py | 53a46f8091047e5242a6a478591346fee48294d2 | [] | no_license | vicmgs/djangopractice2 | 8efaa5d0e6ec9fb8d86d79ebc100c1bd594d4717 | 60ecb7ed8ef4b5fbcb86479195ab4a3676eca2c2 | refs/heads/master | 2020-12-30T11:51:41.247942 | 2017-05-17T05:18:46 | 2017-05-17T05:18:46 | 91,532,456 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,203 | py | """
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.11.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/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/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '=y(+80!^*9)@mhw2jh_$do@vmmydwjm^d62$%%#r(%^-c#1fl='
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['127.0.0.1', '.pythonanywhere.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
]
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 = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/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/1.11/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/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Los_Angeles'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
| [
"vic.mgs@gmail.com"
] | vic.mgs@gmail.com |
3b9283807f9a633e9ca03ea36b3db90607bb9388 | 5063587053951fc1dc558c657d06e0b99187baf5 | /electrumx/server/controller.py | 6c449b6927f07497c4a7bd4b643a57b2177d5729 | [
"MIT"
] | permissive | Japangeek/electrumx | 04cbd7f793afe9fa2dff8adad8e7900f4a80b279 | a4ea34c6fb9bc887afb19779bde107d97006d8b7 | refs/heads/master | 2020-05-15T11:46:52.339001 | 2019-04-18T13:29:37 | 2019-04-18T13:29:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,092 | py | # Copyright (c) 2016-2018, Neil Booth
#
# All rights reserved.
#
# See the file "LICENCE" for information about the copyright
# and warranty status of this software.
from asyncio import Event
from aiorpcx import _version as aiorpcx_version, TaskGroup
import electrumx
from electrumx.lib.server_base import ServerBase
from electrumx.lib.util import version_string
from electrumx.server.db import DB
from electrumx.server.mempool import MemPool, MemPoolAPI
from electrumx.server.session import SessionManager
class Notifications(object):
# hashX notifications come from two sources: new blocks and
# mempool refreshes.
#
# A user with a pending transaction is notified after the block it
# gets in is processed. Block processing can take an extended
# time, and the prefetcher might poll the daemon after the mempool
# code in any case. In such cases the transaction will not be in
# the mempool after the mempool refresh. We want to avoid
# notifying clients twice - for the mempool refresh and when the
# block is done. This object handles that logic by deferring
# notifications appropriately.
def __init__(self):
self._touched_mp = {}
self._touched_bp = {}
self._highest_block = -1
async def _maybe_notify(self):
tmp, tbp = self._touched_mp, self._touched_bp
common = set(tmp).intersection(tbp)
if common:
height = max(common)
elif tmp and max(tmp) == self._highest_block:
height = self._highest_block
else:
# Either we are processing a block and waiting for it to
# come in, or we have not yet had a mempool update for the
# new block height
return
touched = tmp.pop(height)
for old in [h for h in tmp if h <= height]:
del tmp[old]
for old in [h for h in tbp if h <= height]:
touched.update(tbp.pop(old))
await self.notify(height, touched)
async def notify(self, height, touched):
pass
async def start(self, height, notify_func):
self._highest_block = height
self.notify = notify_func
await self.notify(height, set())
async def on_mempool(self, touched, height):
self._touched_mp[height] = touched
await self._maybe_notify()
async def on_block(self, touched, height):
self._touched_bp[height] = touched
self._highest_block = height
await self._maybe_notify()
class Controller(ServerBase):
'''Manages server initialisation and stutdown.
Servers are started once the mempool is synced after the block
processor first catches up with the daemon.
'''
async def serve(self, shutdown_event):
'''Start the RPC server and wait for the mempool to synchronize. Then
start serving external clients.
'''
if not (0, 15, 0) <= aiorpcx_version < (0, 16):
raise RuntimeError('aiorpcX version 0.15.x is required')
env = self.env
min_str, max_str = env.coin.SESSIONCLS.protocol_min_max_strings()
self.logger.info(f'software version: {electrumx.version}')
self.logger.info(f'aiorpcX version: {version_string(aiorpcx_version)}')
self.logger.info(f'supported protocol versions: {min_str}-{max_str}')
self.logger.info(f'event loop policy: {env.loop_policy}')
self.logger.info(f'reorg limit is {env.reorg_limit:,d} blocks')
notifications = Notifications()
Daemon = env.coin.DAEMON
BlockProcessor = env.coin.BLOCK_PROCESSOR
daemon = Daemon(env.coin, env.daemon_url)
db = DB(env)
bp = BlockProcessor(env, db, daemon, notifications)
# Set notifications up to implement the MemPoolAPI
def get_db_height():
return db.db_height
notifications.height = daemon.height
notifications.db_height = get_db_height
notifications.cached_height = daemon.cached_height
notifications.mempool_hashes = daemon.mempool_hashes
notifications.raw_transactions = daemon.getrawtransactions
notifications.lookup_utxos = db.lookup_utxos
MemPoolAPI.register(Notifications)
mempool = MemPool(env.coin, notifications)
session_mgr = SessionManager(env, db, bp, daemon, mempool,
shutdown_event)
# Test daemon authentication, and also ensure it has a cached
# height. Do this before entering the task group.
await daemon.height()
caught_up_event = Event()
mempool_event = Event()
async def wait_for_catchup():
await caught_up_event.wait()
await group.spawn(db.populate_header_merkle_cache())
await group.spawn(mempool.keep_synchronized(mempool_event))
async with TaskGroup() as group:
await group.spawn(session_mgr.serve(notifications, mempool_event))
await group.spawn(bp.fetch_and_process_blocks(caught_up_event))
await group.spawn(wait_for_catchup())
| [
"kyuupichan@gmail.com"
] | kyuupichan@gmail.com |
9ae1525c652f292ae18f38228bddd9d9cb30120c | 5588a2e55e5c0ad371db6402d4bccb910b8e94c6 | /summary_holdings/23$81$av.$b(yr.).py | 6a0e7d48165209e37341411a4adea8882830105e | [] | no_license | jdcar/holdingssummary | 84ba539b8444eb2113e5f4c8098bda9e821a6854 | 510a8f082cb192464491a62426f2f7c7522ed88e | refs/heads/master | 2020-03-11T04:58:18.345764 | 2018-04-16T19:21:36 | 2018-04-16T19:21:36 | 129,789,967 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,716 | py | import re
fhand = open("H:\\MFHD\\mfhds.txt")
for line in fhand:
if re.compile("23\$81\$av\.\$b\(yr\.\),"):
mfhd = line.split(", ")[0]
p = re.compile("23\$81\$av\.\$b\(yr\.\),")
matchResult = p.search(line)
if "23$81$av.$b(yr.)," in str(matchResult):
p2 = re.compile("4.\$8.*")
matchResult2 = p2.search(line)
m = str(matchResult2)
m2 = m.split("$a")[-1].split("$b")[0]
m3 = m.split("$b")[-1].split("'>")[0]
if re.search("18\\d\\d/\\d\\d-18\\d\\d/\\d\\d$", m3):
firstYear = m3.split("/")[0]
secondYear = m3.split("/")[1].split("-")[0]
thirdYear = m3.split("-")[-1].split("/")[0]
fourthYear = m3.split("/")[-1]
m3 = "".join(map(str,(firstYear, "/18" , secondYear, "-" , thirdYear, "/18" , fourthYear)))
elif re.search("18\\d\\d/\\d\\d-19\\d\\d/\\d\\d$", m3):
firstYear = m3.split("/")[0]
secondYear = m3.split("/")[1].split("-")[0]
thirdYear = m3.split("-")[-1].split("/")[0]
fourthYear = m3.split("/")[-1]
m3 = "".join(map(str,(firstYear, "/18" , secondYear, "-" , thirdYear, "/19" , fourthYear)))
elif re.search("19\\d\\d/\\d\\d-19\\d\\d/\\d\\d$", m3):
firstYear = m3.split("/")[0]
secondYear = m3.split("/")[1].split("-")[0]
thirdYear = m3.split("-")[-1].split("/")[0]
fourthYear = m3.split("/")[-1]
m3 = "".join(map(str,(firstYear, "/19" , secondYear, "-" , thirdYear, "/19" , fourthYear)))
elif re.search("20\\d\\d/\\d\\d-20\\d\\d/\\d\\d$", m3):
firstYear = m3.split("/")[0]
secondYear = m3.split("/")[1].split("-")[0]
thirdYear = m3.split("-")[-1].split("/")[0]
fourthYear = m3.split("/")[-1]
m3 = "".join(map(str,(firstYear, "/20" , secondYear, "-" , thirdYear, "/20" , fourthYear)))
elif re.search("19\\d\\d/\\d\\d-20\\d\\d/\\d\\d$", m3):
firstYear = m3.split("/")[0]
secondYear = m3.split("/")[1].split("-")[0]
thirdYear = m3.split("-")[-1].split("/")[0]
fourthYear = m3.split("/")[-1]
m3 = "".join(map(str,(firstYear, "/19" , secondYear, "-" , thirdYear, "/20" , fourthYear)))
elif re.search("18\\d\\d-18\\d\\d/\\d\\d$", m3):
firstYear = m3.split("-")[0]
secondYear = m3.split("-")[1].split("/")[0]
thirdYear = m3.split("/")[-1]
m3 = "".join(map(str,(firstYear, "-", secondYear, "/18" , thirdYear)))
elif re.search("18\\d\\d-19\\d\\d/\\d\\d$", m3):
firstYear = m3.split("-")[0]
secondYear = m3.split("-")[1].split("/")[0]
thirdYear = m3.split("/")[-1]
m3 = "".join(map(str,(firstYear, "-" , secondYear, "/19" , thirdYear)))
elif re.search("19\\d\\d-19\\d\\d/\\d\\d$", m2):
firstYear = m3.split("-")[0]
secondYear = m3.split("-")[1].split("/")[0]
thirdYear = m3.split("/")[-1]
m3 = "".join(map(str,(firstYear, "-" , secondYear, "/19" , thirdYear)))
elif re.search("20\\d\\d-20\\d\\d/\\d\\d$", m3):
firstYear = m3.split("-")[0]
secondYear = m3.split("-")[1].split("/")[0]
thirdYear = m3.split("/")[-1]
m3 = "".join(map(str,(firstYear, "-" , secondYear, "/20" , thirdYear)))
elif re.search("19\\d\\d-20\\d\\d/\\d\\d$", m3):
firstYear = m3.split("-")[0]
secondYear = m3.split("-")[1].split("/")[0]
thirdYear = m3.split("/")[-1]
m3 = "".join(map(str,(firstYear, "-" , secondYear, "/20" , thirdYear)))
elif re.search("18\\d\\d/\\d\\d$", m3):
firstYear = m3.split("/")[0]
secondYear = m3.split("/")[-1]
m3 = "".join(map(str,(firstYear, "/18" , secondYear)))
elif re.search("19\\d\\d/\\d\\d$", m3):
firstYear = m3.split("/")[0]
secondYear = m3.split("/")[-1]
m3 = "".join(map(str,(firstYear, "/19" ,secondYear)))
elif re.search("20\\d\\d/\\d\\d$", m3):
firstYear = m3.split("/")[0]
secondYear = m3.split("/")[-1]
m3 = "".join(map(str,(firstYear, "/20" , secondYear)))
elif re.search("18\\d\\d/18\\d\\d-\\d\\d$", m3):
firstYear = m3.split("/")[0]
secondYear = m3.split("/")[1].split("-")[0]
thirdYear = m3.split("-")[-1]
m3 = "".join(map(str,(firstYear, "/", secondYear, "-18" , thirdYear)))
elif re.search("18\\d\\d/19\\d\\d-\\d\\d$", m2):
firstYear = m3.split("-")[0]
secondYear = m3.split("-")[-1]
m3 = "".join(map(str,(firstYear, "-19" , secondYear)))
elif re.search("19\\d\\d/19\\d\\d-\\d\\d$", m3):
firstYear = m3.split("-")[0]
secondYear = m3.split("-")[-1]
m3 = "".join(map(str,(firstYear, "-19" , secondYear)))
elif re.search("19\\d\\d/20\\d\\d-\\d\\d$", m3):
firstYear = m3.split("-")[0]
secondYear = m3.split("-")[-1]
m3 = "".join(map(str,(firstYear, "-20" , secondYear)))
elif re.search("20\\d\\d-20\\d\\d/\\d\\d$", m3):
firstYear = m3.split("-")[0]
secondYear = m3.split("-")[-1]
m3 = "".join(map(str,(firstYear, "-20" , secondYear)))
elif re.search("18\\d\\d/\\d\\d-\\d\\d$", m3):
firstYear = m3.split("/")[0]
secondYear = m3.split("/")[1].split("-")[0]
thirdYear = m3.split("-")[-1]
m3 = "".join(map(str,(firstYear, "/18", secondYear, "-18" , thirdYear)))
elif re.search("19\\d\\d/\\d\\d-\\d\\d$", m3):
firstYear = m3.split("/")[0]
secondYear = m3.split("/")[1].split("-")[0]
thirdYear = m3.split("-")[-1]
m3 = "".join(map(str,(firstYear, "/19" , secondYear, "-19" , thirdYear)))
elif re.search("20\\d\\d/\\d\\d-\\d\\d$", m3):
firstYear = m3.split("/")[0]
secondYear = m3.split("/")[1].split("-")[0]
thirdYear = m3.split("-")[-1]
m3 = "".join(map(str,(firstYear, "/20" , secondYear, "-20" , thirdYear)))
elif re.search("18\\d\\d-\\d\\d$", m3):
firstYear = m3.split("-")[0]
secondYear = m3.split("-")[-1]
m3 = "".join(map(str,(firstYear, "-18" , secondYear)))
elif re.search("19\\d\\d-\\d\\d$", m3):
firstYear = m3.split("-")[0]
secondYear = m3.split("-")[-1]
m3 = "".join(map(str,(firstYear, "-19" ,secondYear)))
elif re.search("20\\d\\d-\\d\\d$", m3):
firstYear = m3.split("-")[0]
secondYear = m3.split("-")[-1]
m3 = "".join(map(str,(firstYear, "-20" , secondYear)))
elif re.search("18\\d\\d/\\d\\d-18\\d\\d$", m3):
firstYear = m3.split("/")[0]
secondYear = m3.split("/")[1].split("-")[0]
thirdYear = m3.split("-")[-1]
m3 = "".join(map(str,(firstYear, "/18" , secondYear, "-" , thirdYear)))
elif re.search("18\\d\\d/\\d\\d-19\\d\\d$", m3):
firstYear = m3.split("/")[0]
secondYear = m3.split("/")[1].split("-")[0]
thirdYear = m3.split("-")[-1]
m3 = "".join(map(str,(firstYear, "/18" , secondYear, "-" , thirdYear)))
elif re.search("19\\d\\d/\\d\\d-19\\d\\d$", m3):
firstYear = m3.split("/")[0]
secondYear = m3.split("/")[1].split("-")[0]
thirdYear = m3.split("-")[-1]
m3 = "".join(map(str,(firstYear, "/19" , secondYear, "-" , thirdYear)))
elif re.search("19\\d\\d/\\d\\d-20\\d\\d$", m3):
firstYear = m3.split("/")[0]
secondYear = m3.split("/")[1].split("-")[0]
thirdYear = m3.split("-")[-1]
m3 = "".join(map(str,(firstYear, "/19" , secondYear, "-" , thirdYear)))
elif re.search("20\\d\\d/\\d\\d-20\\d\\d$", m3):
firstYear = m3.split("/")[0]
secondYear = m3.split("/")[1].split("-")[0]
thirdYear = m3.split("-")[-1]
m3 = "".join(map(str,(firstYear, "/20" , secondYear, "-" , thirdYear)))
else:
m3 = m3
holdings1 = m2, m3
holdings = str(holdings1)
hyphenCount = holdings.count("-")
if matchResult:
if re.search('[a-zA-Z>]+', holdings):
print ("Nope|" , mfhd, "|v.", m2, "(" , m3, ")", sep='')
elif ("-" not in holdings):
print ("Done|", mfhd, "|v.", m2, "(" , m3, ")", sep='')
elif hyphenCount == 1:
print ("Done|", mfhd, "|v.", m2, "(" , m3, ")", sep='')
elif hyphenCount == 2:
hyphens = mfhd, "|v.", m2, "(" , m3, ")"
firstIssue = m2.split("-")[0]
firstDate = m3.split("-")[0]
secondIssue = m2.split("-")[1]
secondDate = m3.split("-")[-1]
print ("Done|" , mfhd, "|v.", firstIssue, "(", firstDate, ")", "-", "v.", secondIssue, "(", secondDate, ")", sep="")
else:
print ("Done|", mfhd, "|v.", m2, "(", m3, ")", sep="")
| [
"34754596+jdcar@users.noreply.github.com"
] | 34754596+jdcar@users.noreply.github.com |
5b30bc46c43b516ec3776f3c87294dd9014c077b | 4cd537e6d3b65a1d6d54fa4fa7596b98c20abe40 | /script_auxiliares.py | fdc22ee783d92c0ae2a7b973022e755f569e2525 | [] | no_license | gsiriani/proyGrado | 3386c6be80b5ea399e6a6bce7b298305aae3f0a3 | ba1e83c7b9b225d3ba236e1dcf6d92629eb7c989 | refs/heads/master | 2020-12-22T03:32:58.673947 | 2018-02-28T23:17:37 | 2018-02-28T23:17:37 | 58,835,734 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,021 | py | # -*- coding: utf-8 -*-
import sys
# Print iterations progress
def print_progress(iteration, total, prefix='', suffix='', decimals=1, bar_length=100):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : positive number of decimals in percent complete (Int)
bar_length - Optional : character length of bar (Int)
"""
str_format = "{0:." + str(decimals) + "f}"
percents = str_format.format(100 * (iteration / float(total)))
filled_length = int(round(bar_length * iteration / float(total)))
bar = '█' * filled_length + '-' * (bar_length - filled_length)
sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percents, '%', suffix)),
if iteration == total:
sys.stdout.write('\n')
sys.stdout.flush()
| [
"guillebogus@gmail.com"
] | guillebogus@gmail.com |
a43712de411dba85507f8ceaa78155c931e6bbb4 | 5cff645ec85414dee7dc5c074579eb8477a2f996 | /venv/bin/chardetect | 629c2a58340c80a46b589b4d09d5e31130710c57 | [] | no_license | SNvortex/ExchangeTelegramBot | dba6cbe8b2a697d5b0a20b23a4232133d267eab0 | 2e0344be8a18303046764ccaf6a80a9999d8a7b0 | refs/heads/master | 2020-07-23T06:55:45.945557 | 2019-09-11T09:49:38 | 2019-09-11T09:49:38 | 207,478,480 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 255 | #!/home/nick/projects/TelegramBot/venv/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from chardet.cli.chardetect import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())
| [
"niksvortex@gmail.com"
] | niksvortex@gmail.com | |
6c201191527104f2d328b58b2ba84caec9c846d3 | a5ea93395d8d762caefd129648b2e954754afb00 | /examples/6_p_scale_test_Yokoo_Pt.py | fc618a74a4e14089082439c5476fe6df9f86e0e2 | [
"Apache-2.0"
] | permissive | SHDShim/pytheos | 4295e233dd089d0c9c66218a127d3f099f1d36df | bb86e0ff345efcffb04f08182c09b06b3c54930e | refs/heads/master | 2023-03-16T23:23:56.840071 | 2023-03-11T03:13:23 | 2023-03-11T03:13:23 | 93,273,486 | 7 | 6 | Apache-2.0 | 2019-11-18T13:11:46 | 2017-06-03T20:54:46 | Python | UTF-8 | Python | false | false | 1,369 | py |
# coding: utf-8
# In[1]:
get_ipython().run_line_magic('cat', '0Source_Citation.txt')
# In[2]:
get_ipython().run_line_magic('matplotlib', 'inline')
# %matplotlib notebook # for interactive
# For high dpi displays.
# In[3]:
get_ipython().run_line_magic('config', "InlineBackend.figure_format = 'retina'")
# # 0. General note
# This example compares pressure calculated from `pytheos` and original publication for the platinum scale by Yokoo 2009.
# # 1. Global setup
# In[4]:
import matplotlib.pyplot as plt
import numpy as np
from uncertainties import unumpy as unp
import pytheos as eos
# # 3. Compare
# In[5]:
eta = np.linspace(1., 0.60, 21)
print(eta)
# In[6]:
yokoo_pt = eos.platinum.Yokoo2009()
# In[7]:
yokoo_pt.print_equations()
# In[8]:
yokoo_pt.print_equations()
# In[9]:
yokoo_pt.print_parameters()
# In[10]:
v0 = 60.37930856339099
# In[11]:
yokoo_pt.three_r
# In[12]:
v = v0 * (eta)
temp = 3000.
# In[13]:
p = yokoo_pt.cal_p(v, temp * np.ones_like(v))
# <img src='./tables/Yokoo_Pt.png'>
# In[14]:
print('for T = ', temp)
for eta_i, p_i in zip(eta, p):
print("{0: .3f} {1: .2f}".format(eta_i, p_i))
# It is alarming that even 300 K isotherm does not match with table value. The difference is 1%.
# In[15]:
v = yokoo_pt.cal_v(p, temp * np.ones_like(p), min_strain=0.6)
print(1.-(v/v0))
| [
"SHDShim@gmail.com"
] | SHDShim@gmail.com |
8aad654f743a97284e6607a741abc184b41bf200 | 25ebc03b92df764ff0a6c70c14c2848a49fe1b0b | /daily/20181014/example_pycomment/pycomment.py | 4604d5e1df1248b710f77c3ea0471b933a54d818 | [] | no_license | podhmo/individual-sandbox | 18db414fafd061568d0d5e993b8f8069867dfcfb | cafee43b4cf51a321f4e2c3f9949ac53eece4b15 | refs/heads/master | 2023-07-23T07:06:57.944539 | 2023-07-09T11:45:53 | 2023-07-09T11:45:53 | 61,940,197 | 6 | 0 | null | 2022-10-19T05:01:17 | 2016-06-25T11:27:04 | Python | UTF-8 | Python | false | false | 6,165 | py | import sys
import contextlib
from io import StringIO
from lib2to3 import pytree
from lib2to3 import pygram
from lib2to3.pgen2 import driver
from lib2to3.pgen2 import token
from lib2to3.pgen2.parse import ParseError
from lib2to3.fixer_util import Assign, Name, Newline
# utf8 's PUA(https://en.wikipedia.org/wiki/Private_Use_Areas)
SEP = "\U000F0000"
SEP_MARKER = "ZZ{}ZZ".format(SEP)
COMMENT_MARKER = "# =>"
STDOUT_HEADER_MARKER = "# -- stdout --------------------"
default_driver = driver.Driver(pygram.python_grammar_no_print_statement, convert=pytree.convert)
def parse_string(code, parser_driver=default_driver, *, debug=True):
return parser_driver.parse_string(code, debug=debug)
def parse_file(filename, parser_driver=default_driver, *, debug=True):
try:
return parser_driver.parse_file(filename, debug=debug)
except ParseError as e:
if "bad input:" not in repr(e): # work around
raise
with open(filename) as rf:
body = rf.read()
return parse_string(body + "\n", parser_driver=parser_driver, debug=debug)
def node_name(node):
# Nodes with values < 256 are tokens. Values >= 256 are grammar symbols.
if node.type < 256:
return token.tok_name[node.type]
else:
return pygram.python_grammar.number2symbol[node.type]
type_repr = pytree.type_repr
class PyTreeVisitor:
def visit(self, node):
method = 'visit_{0}'.format(node_name(node))
if hasattr(self, method):
# Found a specific visitor for this node
if getattr(self, method)(node):
return
elif hasattr(node, "value"): # Leaf
self.default_leaf_visit(node)
else:
self.default_node_visit(node)
def default_node_visit(self, node):
for child in node.children:
self.visit(child)
def default_leaf_visit(self, leaf):
pass
def transform_string(source: str):
t = parse_string(source)
return transform(t)
def transform_file(fname: str):
with open(fname) as rf:
return transform_string(rf.read())
def transform(node):
t = Transformer()
t.transform(node)
return node
class Transformer(PyTreeVisitor):
marker = COMMENT_MARKER
def visit_NEWLINE(self, node):
if node.prefix.lstrip().startswith(self.marker):
# MEMO: <expr> -> _ = <expr>
target = node
while True:
parent = target.parent
if parent is None:
return
if type_repr(target.parent.type) == "simple_stmt":
break
target = parent
eol = target # target is Leaf("\n]")
target = eol.prev_sibling
cloned = target.clone()
cloned.parent = None
assigned = Assign(Name("_"), cloned)
assigned.prefix = target.prefix
target.replace(assigned)
# MEMO: adding print(SEP_MARKER, _, SEP_MARKER, sep="\n")
this_stmt = eol.parent
print_stmt = this_stmt.clone()
print_stmt.children = []
print_stmt.append_child(
Name(
"print({ms!r}, repr(_), {me!r}, sep='')".format(
ms="{}{}:".format(SEP_MARKER, node.get_lineno()), me=SEP_MARKER
)
)
)
print_stmt.prefix = assigned.prefix
# xxx: for first line
if not print_stmt.prefix:
prev_line = assigned.parent.prev_sibling
if prev_line.type == token.INDENT:
print_stmt.prefix = prev_line.value
print_stmt.append_child(Newline())
for i, stmt in enumerate(this_stmt.parent.children):
if stmt == this_stmt:
this_stmt.parent.insert_child(i + 1, print_stmt)
break
transform = PyTreeVisitor.visit
def run(sourcefile, out=sys.stdout):
o = StringIO()
with contextlib.redirect_stdout(o):
exec(str(transform_file(sourcefile)))
result_map = {}
stdout_outputs = []
for line in o.getvalue().splitlines():
if line.startswith(SEP_MARKER) and line.endswith(SEP_MARKER):
line = line.strip(SEP_MARKER)
lineno, line = line.split(":", 2)
result_map[lineno] = line
else:
stdout_outputs.append(line)
i = 0
with open(sourcefile) as rf:
import re
rx = re.compile(COMMENT_MARKER + ".*$")
for lineno, line in enumerate(rf, 1):
if line.rstrip() == STDOUT_HEADER_MARKER:
break
m = rx.search(line)
k = str(lineno)
if m is None or k not in result_map:
print(line, end="", file=out)
else:
print(line[:m.start()] + COMMENT_MARKER, result_map[k], file=out)
i += 1
if stdout_outputs:
print(STDOUT_HEADER_MARKER, file=out)
for line in stdout_outputs:
print("# >>", line, file=out)
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("sourcefile")
parser.add_argument("--inplace", action="store_true")
parser.add_argument("--show-only", action="store_true")
args = parser.parse_args()
if args.show_only:
print(str(transform_file(args.sourcefile)))
from prestring.python.parse import dump_tree
dump_tree(transform_file(args.sourcefile))
elif not args.inplace:
run(args.sourcefile)
else:
import tempfile
import os
import shutil
name = None
try:
with tempfile.NamedTemporaryFile("w", delete=False) as wf:
name = wf.name
run(args.sourcefile, out=wf)
print("replace: {} -> {}".format(name, args.sourcefile), file=sys.stderr)
shutil.move(name, args.sourcefile)
except Exception:
if os.path.exists(name):
os.unlink(name)
raise
if __name__ == "__main__":
main()
| [
"ababjam61+github@gmail.com"
] | ababjam61+github@gmail.com |
90262d4823d787cd5efb6813861d9604cea464cb | 096f1d7cf38929d1dad3a9c4526c8fb6f16a9f8c | /order/migrations/0009_auto_20190718_1515.py | fb35b4dcdfcd090a930ea7ab1df16c88e5bfb07a | [] | no_license | zkrami/masaood-api | e9dbb90054ff4c789797ad53f6e999faea203c6d | d3f5ee70c5c8dff77f7f73e0af3ef0bd09f6a149 | refs/heads/master | 2022-12-09T13:59:22.366518 | 2019-09-04T08:47:35 | 2019-09-04T08:47:35 | 196,029,774 | 1 | 0 | null | 2022-12-08T05:57:20 | 2019-07-09T14:54:16 | Python | UTF-8 | Python | false | false | 690 | py | # Generated by Django 2.2.3 on 2019-07-18 15:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('order', '0008_auto_20190718_1437'),
]
operations = [
migrations.AddField(
model_name='order',
name='assignedAt',
field=models.DateField(null=True),
),
migrations.AddField(
model_name='order',
name='canceledAt',
field=models.DateTimeField(null=True),
),
migrations.AddField(
model_name='order',
name='deliveredAt',
field=models.DateTimeField(null=True),
),
]
| [
"17zrami@gmail.com"
] | 17zrami@gmail.com |
0a0861fdcb160f3d564364edafa8e9f89d421950 | ff2ed99fcae710657580b16649bf119a76c2b14d | /src/20200318_new/event_b/mag_spec/const_lims/moving_mag_spec_const_lims.py | 6e87fe8fe9bc32e7ab2b871f22bc2624c278d2df | [] | no_license | jmsplank/PhD-Starter-Project | dd43b2fda00862b9d430e3506d5564d8daf6d7d6 | 70f1c647362def4b47602ac40535113379bcc80f | refs/heads/master | 2023-06-09T14:29:37.985566 | 2021-07-07T08:34:26 | 2021-07-07T08:34:26 | 299,309,204 | 1 | 0 | null | 2021-02-02T14:37:07 | 2020-09-28T12:56:52 | Jupyter Notebook | UTF-8 | Python | false | false | 5,165 | py | """
Last modified: 19/04/21
Moving windows of magnetic spectrum, with fixed (const) ion & electron limits.
"""
import os
import numpy as np
import matplotlib.pyplot as plt
import logging as log
import time as timetime
import json
from scipy.optimize import curve_fit
from tqdm import tqdm
path = os.path.dirname(os.path.realpath(__file__))
dirpath = "/".join(path.split("/")[:-1])
print(dirpath)
log.basicConfig(
filename=f"{path}/mag_spec.log",
level=log.INFO,
format="%(asctime)s | %(name)s | %(levelname)s | %(message)s",
)
def extract_grads(k, y, ion, elec, instr):
def split(X, Y, low, high):
mask_x = X[(X >= low) & (X <= high)]
mask_y = Y[(X >= low) & (X <= high)]
return (np.log10(mask_x), np.log10(mask_y))
def fit(X, Y):
grad, pcov = curve_fit(lambda x, m, c: c + m * x, X, Y)
return grad[0]
# Iner
a, b = split(k, y, k[0], ion)
iner = fit(a, b)
# Ion
a, b = split(k, y, ion, elec)
ion = fit(a, b)
# Elec
a, b = split(k, y, elec, instr)
elec = fit(a, b)
return np.array([iner, ion, elec])
def lengths(s, number_density, temp_perp, B):
if s == "i":
log.info("---->----IONS----<----")
else:
log.info("---->----ELEC----<----")
n = number_density.mean()
const = 1.32e3 if s == "i" else 5.64e4
# https://en.wikipedia.org/wiki/Plasma_parameters#Fundamental_plasma_parameters
omega_p = const * np.sqrt(n)
p = 2.99792458e8 / omega_p
p /= 1e3
log.info(f"Inertial length: {p:.3f}km")
T = temp_perp
v = (
np.sqrt(
np.mean(T)
* 2
* 1.60217662e-19
/ (1.6726219e-27 if s == "i" else 9.10938356e-31)
)
/ 1e3
)
B *= 1e-9
BT = np.linalg.norm(B, axis=1).mean()
log.info(f"V: {v:.3f}kms⁻¹")
omega_c = 1.60217662e-19 * BT / (1.6726219e-27 if s == "i" else 9.10938356e-31)
rho = v / omega_c
log.info(f"Gyroradius: {rho:.3f}km")
limit = p if p > rho else rho
log.info("---->----<<>>----<----")
log.info("")
# return limit
if s == "i":
return rho
else:
return p
log.info("Loading data")
big_data = np.load(f"{dirpath}/data/fsm/data.npy")
log.info("Loading time")
big_time = np.load(f"{dirpath}/data/fsm/time.npy")
td = big_time[1] - big_time[0]
log.info("Loading temp_perp")
big_temp_perp_e = np.load(f"{dirpath}/data/fpi/data_tempperp_e.npy")
big_temp_perp_i = np.load(f"{dirpath}/data/fpi/data_tempperp_i.npy")
log.info("Loading number_density")
big_number_density_e = np.load(f"{dirpath}/data/fpi/data_numberdensity_e.npy")
big_number_density_i = np.load(f"{dirpath}/data/fpi/data_numberdensity_i.npy")
log.info("Loading electron time")
time_e = np.load(f"{dirpath}/data/fpi/time_e.npy")
log.info("Loading ion time")
time_i = np.load(f"{dirpath}/data/fpi/time_i.npy")
log.info("Loading stats")
with open(f"{dirpath}/data/fpi/stats.json") as f:
stats = json.load(f)
meanv = stats["mean_v"]["value"]
N = 100 # Number of windows
ion_lim = 1.0 / lengths("i", big_number_density_i, big_temp_perp_i, big_data)
electron_lim = 1.0 / lengths("e", big_number_density_e, big_temp_perp_e, big_data)
min_freq = ion_lim * 5
bin_size = int(1 / (min_freq * td))
print(bin_size)
max_index = len(big_data) - bin_size
log.info(f"max index: {max_index}")
bin_starts = np.linspace(0, max_index, N, dtype=int)
log.info(f"Ion lim: {ion_lim}\nelectron lim: {electron_lim}")
grads = []
times = []
for bin in tqdm(bin_starts):
Y = {}
data = big_data[bin : bin + bin_size, :]
time = big_time[bin : bin + bin_size]
# log.info("Comutping FFT over each coord")
for i in range(3):
# log.info(f"index {i}")
B = data[:, i] * 1e-9
# log.info("Scaling mean")
B -= B.mean()
# log.info("Applying Hanning window")
Hann = np.hanning(len(B)) * B
# log.info("Calculating FFT")
Yi = np.fft.fft(Hann)
# log.info("Calculating Frequencies")
freq = np.fft.fftfreq(len(B), td)
# log.info("Obtaining power spectrum")
Y[["x", "y", "z"][i]] = (np.power(np.abs(Yi), 2) * 1e9 * td)[freq > 0]
# log.info("Summing components")
y = np.sum([Y[i] for i in ["x", "y", "z"]], axis=0)
k = freq[freq > 0] * 2 * np.pi / meanv
grads.append(extract_grads(k, y, ion_lim, electron_lim, 10))
times.append(big_time[bin + bin_size // 2])
plt.loglog(k, y)
plt.vlines(
[ion_lim, electron_lim, 10],
np.min(1e-51),
np.max(1e-36),
("red", "green", "blue"),
)
plt.ylim((1e-51, 1e-36))
plt.savefig(f"{path}/anim/{bin}.png")
plt.clf()
del y
del Y
del freq
del B
del Hann
del Yi
del data
del time
grads = np.array(grads)
np.save(f"{path}/grads.npy", grads)
np.save(f"{path}/times.npy", times)
fig, ax = plt.subplots(2, 1, sharex=True)
ax[0].plot(big_time, np.linalg.norm(big_data, axis=1))
for i in range(3):
ax[1].plot(
times,
grads[:, i],
color=["r", "g", "b"][i],
label=["inertial", "ion", "electron"][i],
)
ax[1].legend()
plt.show()
| [
"plankjames@gmail.com"
] | plankjames@gmail.com |
221ab1ad77324845627959d14968b0eed0e8e187 | f66016b962e105898ea14982e229bd44f66f32a2 | /settings.py | c142f11377dc1d70c39b3451e46f9a4f2ab30a36 | [
"MIT"
] | permissive | DerThorsten/pc | d3ceace388dd3460c0133e97b7fba0fde8d1e811 | 41d7474ceff8de7b95be5d4fbc42a40e89799e34 | refs/heads/master | 2021-01-12T10:41:47.797694 | 2016-11-10T21:59:35 | 2016-11-10T21:59:35 | 72,621,794 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,216 | py | from collections import OrderedDict
import h5py
from features import registerdFeatureOperators
class Settings(object):
def __init__(self, settingsDict, predictionSettingsDict=None):
self.settingsDict = settingsDict
self.featureBlockShape = tuple(self.settingsDict["setup"]["blockShape"])
if predictionSettingsDict is not None:
self.featureBlockShape = tuple(predictionSettingsDict['setup']["blockShape"])
self.numberOfClasses = self.settingsDict["setup"]["nClasses"]
self.predictionSettingsDict = predictionSettingsDict
print(self.settingsDict['setup'])
self.useBlockF = self.settingsDict['setup'].get("useBlock", None)
#self.useBlockF = self.settingsDict['setup']['useBlock']
assert self.useBlockF is not None
def useTrainingBlock(self, blockIndex, blockBegin, blockEnd):
if self.useBlockF is not None:
return self.useBlockF(blockIndex=blockIndex, blockBegin=blockBegin, blockEnd=blockBegin)
else:
return True
def trainingInstancesNames(self):
setup = self.settingsDict["setup"]
return setup['trainingDataNames']
def predictionInstancesNames(self):
return self.predictionSettingsDict['predictionInput'].keys()
def trainignInstancesDataDicts(self):
setup = self.settingsDict["setup"]
trainingDataNames = setup['trainingDataNames']
trainingInstancesSettings = [ ]
for trainingDataName in trainingDataNames:
s = self.settingsDict["trainingData"][trainingDataName]
s['name'] = trainingDataName
trainingInstancesSettings.append(s)
return trainingInstancesSettings
def predictionInstancesDataDicts(self):
assert self.predictionSettingsDict is not None
d = self.predictionSettingsDict['predictionInput']
dicts = []
for key in d.keys():
ddict = d[key]
ddict['name'] = key
dicts.append(ddict)
return dicts
def featureSetttingsList(self):
return self.settingsDict["setup"]["featureSettings"]
def getLabelsH5Path(self, instanceName):
trainingInstanceDataDict = self.settingsDict["trainingData"][instanceName]
f,d = trainingInstanceDataDict['labels']
return f,d
def getDataH5Dsets(self, instanceDataDict, openH5Files):
dataH5Dsets = OrderedDict()
for featureSettings in self.featureSetttingsList():
inputFileName = featureSettings['name']
print(" ","inputFile:",inputFileName)
# get the h5filename
dataDict = instanceDataDict['data']
f,d = dataDict[inputFileName]['file']
h5File = h5py.File(f,'r')
dset = h5File[d]
# dsets
dataH5Dsets[inputFileName] = dset
# remeber all files opend
openH5Files.append(h5File)
return dataH5Dsets, openH5Files
def getFeatureOperators(self):
dataH5Dsets = OrderedDict()
outerList = []
maxHaloList = []
#print("fs0",self.featureSetttingsList()[0])
#print("fs1",self.featureSetttingsList()[0])
for featureSettings in self.featureSetttingsList():
inputFileName = featureSettings['name']
#print("features for",inputFileName)
featureOperatorsSettingsList = featureSettings["features"]
innerList = []
maxHalo = (0,0,0)
for featureOperatorSettings in featureOperatorsSettingsList:
#print(featureOperatorSettings)
fOpName = featureOperatorSettings['type']
fOpKwargs = featureOperatorSettings['kwargs']
fOpCls = registerdFeatureOperators[fOpName]
fOp = fOpCls(**fOpKwargs)
halo = fOp.halo()
maxHalo = map(lambda aa,bb: max(aa,bb), halo, maxHalo)
innerList.append(fOp)
outerList.append(innerList)
maxHaloList.append(maxHalo)
return outerList,maxHaloList
| [
"thorsten.beier@iwr.uni-heidelberg.de"
] | thorsten.beier@iwr.uni-heidelberg.de |
c31a0e73d6e975d7fadf3b697bac94aa6dd6b066 | 3c06dc187183b5f78dbe24d38f7a3556b7cc9975 | /Python/LC51_NQueens.py | 24f5ce90b79b47c78b3abc2259af3dc85e7f029c | [] | no_license | wondershow/CodingTraining | 071812ffd34850ce0417b95a91ac39a983fca92d | 0250c3764b6e68dfe339afe8ee047e16c45db4e0 | refs/heads/master | 2021-07-02T22:18:46.774286 | 2021-06-30T14:08:54 | 2021-06-30T14:08:54 | 77,458,117 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,110 | py | class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
def generate_board(pos, n):
res = []
for i in range(n):
line = ["."] * n
line[pos[i]] = "Q"
res.append("".join(line))
return res
cols, diagnoal, anti_diagnoal = set(), set(), set()
def dfs(res, row, n, cur):
nonlocal cols, diagnoal, anti_diagnoal
if row == n:
res.append(generate_board(cur, n))
return
for col in range(n):
if col in cols or (row + col) in anti_diagnoal or (row - col) in diagnoal:
continue
cols.add(col)
anti_diagnoal.add(row + col)
diagnoal.add(row - col)
cur.append(col)
dfs(res, row + 1, n, cur)
cur.pop()
cols.remove(col)
anti_diagnoal.remove(row + col)
diagnoal.remove(row - col)
res = []
dfs(res, 0, n, [])
return res
| [
"noreply@github.com"
] | wondershow.noreply@github.com |
5b66b460d0bf7820cedfd1669fafa8b4498c8529 | 8780d1623128e1ef707c0d4d38a97686bce18958 | /__init__.py | 5a2231bd5b31f80c55ca490c3437976e065c4b70 | [
"MIT"
] | permissive | yingyulou/pathtools | c1b267ead00b1e27ffdfb4d81fb1278cda400f93 | 7f559f8b72aec1fd925606fb2aefac88ad92f162 | refs/heads/master | 2021-07-06T06:05:42.620366 | 2020-10-15T08:12:55 | 2020-10-15T08:12:55 | 174,488,557 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 90 | py | #!/bin/env python
# coding=UTF-8
# Import Self
from .pathtools import enter, walk, iwalk
| [
"yingyulou@vip.qq.com"
] | yingyulou@vip.qq.com |
a2151107c06eefd9c29d3273142f5de1db083c3d | b8e38484583efcc697e7cb9f2a035e5c36d13b5f | /models/ResNet152.py | a34f85dc6cf75c5d2aaf0423cccc44f69c4b94fe | [] | no_license | shunzhang876/Person_ReID_Library | 5d7134cfc362fe3e2609448ccb7e4ceefc01129a | c7cd7a56cd845df97a7b7c0ff966c18e17eead71 | refs/heads/master | 2020-06-10T03:20:37.338525 | 2019-06-18T06:52:05 | 2019-06-18T06:52:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,198 | py | import torch
from torch import nn
from torchvision import models
from .BasicModule import BasicModule
from .backbones.resnet import resnet152
def weights_init_kaiming(m):
classname = m.__class__.__name__
if classname.find('Linear') != -1:
nn.init.kaiming_normal_(m.weight, a=0, mode='fan_out')
nn.init.constant_(m.bias, 0.0)
elif classname.find('Conv') != -1:
nn.init.kaiming_normal_(m.weight, a=0, mode='fan_in')
if m.bias is not None:
nn.init.constant_(m.bias, 0.0)
elif classname.find('BatchNorm') != -1:
if m.affine:
nn.init.constant_(m.weight, 1.0)
nn.init.constant_(m.bias, 0.0)
def weights_init_classifier(m):
classname = m.__class__.__name__
if classname.find('Linear') != -1:
nn.init.normal_(m.weight, std=0.001)
if m.bias:
nn.init.constant_(m.bias, 0.0)
class ResNet152(BasicModule):
in_planes = 2048
def __init__(self, num_classes, last_stride, pool):
super(ResNet152, self).__init__()
self.model_name = 'ResNet152'
self.base = resnet152(pretrained=True, last_stride=last_stride)
if pooling == 'AVG':
self.gap = nn.AdaptiveAvgPool2d(1)
elif pooling == 'MAX':
self.gap = nn.AdaptiveMaxPool2d(1)
else:
raise Exception('The POOL value should be AVG or MAX')
self.num_classes = num_classes
self.bottleneck = nn.BatchNorm1d(self.in_planes)
self.bottleneck.bias.requires_grad_(False) # no shift
self.classifier = nn.Linear(self.in_planes, self.num_classes, bias=False)
self.bottleneck.apply(weights_init_kaiming)
self.classifier.apply(weights_init_classifier)
def forward(self, x):
global_feat = self.gap(self.base(x)) # (b, 2048, 1, 1)
global_feat = global_feat.view(global_feat.shape[0], -1) # flatten to (bs, 2048)
feat = self.bottleneck(global_feat) # normalize for angular softmax
if self.training:
cls_score = self.classifier(feat)
return (cls_score,), (global_feat,) # global feature for triplet loss
else:
return feat | [
"LinShanify@gmail.com"
] | LinShanify@gmail.com |
b41587ccf99106d53073e598c9a4f1609f495cc1 | 441ee65564e7135c8136d382dacd6e548cd9fcb8 | /sahara/service/api/v2/node_group_templates.py | 1262879beb2af2329799ae8a6ac6877b18d42446 | [
"Apache-2.0"
] | permissive | stackhpc/sahara | bccae95d0b8963dab1d6c1add2f6fe31fa80e8c1 | 83c7506076ee6913a381d1fda26361d9eb466e68 | refs/heads/master | 2021-01-25T09:32:55.555734 | 2017-06-08T22:21:46 | 2017-06-08T22:21:46 | 93,850,995 | 0 | 0 | Apache-2.0 | 2022-01-20T19:09:48 | 2017-06-09T11:09:22 | Python | UTF-8 | Python | false | false | 1,315 | py | # Copyright (c) 2016 Red Hat, 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 sahara import conductor as c
from sahara import context
conductor = c.API
# NodeGroupTemplate ops
def get_node_group_templates(**kwargs):
return conductor.node_group_template_get_all(context.ctx(),
regex_search=True, **kwargs)
def get_node_group_template(id):
return conductor.node_group_template_get(context.ctx(), id)
def create_node_group_template(values):
return conductor.node_group_template_create(context.ctx(), values)
def terminate_node_group_template(id):
return conductor.node_group_template_destroy(context.ctx(), id)
def update_node_group_template(id, values):
return conductor.node_group_template_update(context.ctx(), id, values)
| [
"msm@redhat.com"
] | msm@redhat.com |
00fff9c3f6a791cff57ca4256663eb0f39e4a2c9 | 2809be199ebbf3ed6df64f34963d638cfa123e0b | /= Fishc bbs/44 魔法方法 简答的定制:计时器.py | 1ede94f166a63ed2aa89fa00b341accd5952e288 | [] | no_license | wanggao1990/PythonProjects | 7e05859f100ccce5ce215726e601f11629f017d6 | c4c499daded55ea72de5c3d968d2d452e544bbf9 | refs/heads/master | 2020-03-21T17:45:13.920240 | 2019-10-21T05:21:52 | 2019-10-21T05:21:52 | 138,842,477 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,485 | py | ## 要求
# - 定制一个定时器的类
# - start和stop方法代表启动和停止计时器
# - 计时器对象t1, 调用print(t1),t1均显示结果
# - 未启动或者已经停止计时,调用stop提示
# - 计时器对象可以相加,如t1 + t2
# - 有限的资源完成:
# time模块的localtime方法获取当前时间
# 纤细介绍见http://bbs.fishc.com/thread-51326-1-2.html
# time.localtime返回struct_time元组的时间格式
#
# 输入类名,给出信息,需要重写 __str__ 和 __repr__
#
# 其他类似模块 datetime 、timeit
import time as tm
class Timer:
"这里也可以说明"
def __init__(self):
self.tickLable = False
print('提示:还没有开始计时')
def __add__(self,other):
total = tm.strftime("%H:%M:%S", tm.gmtime(self.elapsed + other.elapsed))
return '共耗时 %f , %s' % (self.elapsed + other.elapsed,total)
def start(self):
self.startTime = tm.perf_counter() # 返回1970开始的浮点秒数 ,系统运行时间(包括睡眠),进程运行时间
# time.time , time.perf_counter, time.process_time
self.tickLable = True;
print('开始计时')
def stop(self):
if False == self.tickLable:
print('提示:还没开始计时')
return
self.endTime = tm.perf_counter() # time.time , time.perf_count, time.process_time
self.elapsed =self.endTime - self.startTime;
self.tickLable = False;
print('结束计时')
def __str__(self): ## 调用print(instanse)时,打印该方法获取字符串
## 需要用 print(t1)
return 'str: 总共运行了 {0} 秒'.format(self.elapsed)
# __repr__ = __str__ ## 在shell中,直接输入类名,打印__repr__函数返回的字符串
## 这里复制后,实际是指向str方法返回的字符串
def __repr__(self):
return 'repr: 当前时间 %s, 总共运行了 %s' %( tm.asctime(), tm.strftime("%H:%M:%S", tm.gmtime(self.elapsed)))
t1 = Timer()
t1.start()
tm.sleep(2.5413212132)
t1.stop()
t2 = Timer()
t2.start()
tm.sleep(1.62513212132)
t2.stop()
print(t1 + t2)
print(t1, t2)
| [
"80475837@qq.com"
] | 80475837@qq.com |
23fcb8e9eb391486d00cf9583a372a4b34723870 | ad2c9f6037d7897ed3656ee50e7abd32dacc1960 | /dough/db/sqlalchemy/models.py | 49813e85d82276e33080dfa95be7c82062339db0 | [] | no_license | pperezrubio/dough | 81d63d92c5dd537445e9fb4f454d1de8f316f627 | 3ec2f0a65282c56446f600cb987efb34ec52df30 | refs/heads/master | 2021-01-24T03:36:56.227833 | 2012-04-28T09:09:36 | 2012-04-28T09:09:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,812 | py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Sina Corporation
# All Rights Reserved.
# Author: Zhongyue Luo <lzyeval@gmail.com>
#
# 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.
"""
SQLAlchemy models for dough data.
"""
from sqlalchemy.orm import relationship, backref
from sqlalchemy import Column, Integer, String
from sqlalchemy import ForeignKey, DateTime, Boolean, Float
from nova.db.sqlalchemy import models
class Region(models.BASE, models.NovaBase):
"""Represents regions."""
__tablename__ = 'regions'
id = Column(Integer, primary_key=True, nullable=False, autoincrement=True)
name = Column(String(255), nullable=False)
class Item(models.BASE, models.NovaBase):
"""Represents items."""
__tablename__ = 'items'
id = Column(Integer, primary_key=True, nullable=False, autoincrement=True)
name = Column(String(255), nullable=False)
class ItemType(models.BASE, models.NovaBase):
"""Represents item types."""
__tablename__ = 'item_types'
id = Column(Integer, primary_key=True, nullable=False, autoincrement=True)
name = Column(String(255), nullable=False)
class PaymentType(models.BASE, models.NovaBase):
"""Represents payment types."""
__tablename__ = 'payment_types'
id = Column(Integer, primary_key=True, nullable=False, autoincrement=True)
name = Column(String(255), nullable=False)
interval_unit = Column(String(255), nullable=False)
interval_size = Column(Integer, nullable=False)
is_prepaid = Column(Boolean, nullable=False, default=False)
class Product(models.BASE, models.NovaBase):
"""Represents products."""
__tablename__ = 'products'
id = Column(Integer, primary_key=True, nullable=False, autoincrement=True)
region_id = Column(Integer,
ForeignKey(Region.id),
nullable=False)
region = relationship(Region,
backref=backref('products'),
foreign_keys=region_id,
primaryjoin='and_('
'Product.region_id == Region.id,'
'Product.deleted == False)')
item_id = Column(Integer,
ForeignKey(Item.id),
nullable=False)
item = relationship(Item,
backref=backref('products'),
foreign_keys=item_id,
primaryjoin='and_('
'Product.item_id == Item.id,'
'Product.deleted == False)')
item_type_id = Column(Integer,
ForeignKey(ItemType.id),
nullable=False)
item_type = relationship(ItemType,
backref=backref('products'),
foreign_keys=item_type_id,
primaryjoin='and_('
'Product.item_type_id == ItemType.id,'
'Product.deleted == False)')
payment_type_id = Column(Integer,
ForeignKey(PaymentType.id),
nullable=False)
payment_type = relationship(PaymentType,
backref=backref('products'),
foreign_keys=payment_type_id,
primaryjoin='and_('
'Product.payment_type_id == '
'PaymentType.id,'
'Product.deleted == False)')
order_unit = Column(String(255), nullable=False)
order_size = Column(Integer, nullable=False)
price = Column(Float(asdecimal=True), nullable=False)
currency = Column(String(255), nullable=False)
class Subscription(models.BASE, models.NovaBase):
"""Represents subscriptions."""
__tablename__ = 'subscriptions'
id = Column(Integer, primary_key=True, nullable=False, autoincrement=True)
project_id = Column(Integer, nullable=False, index=True)
product_id = Column(Integer,
ForeignKey(Product.id),
nullable=False)
product = relationship(Product,
backref=backref('subscriptions'),
foreign_keys=product_id,
primaryjoin='and_('
'Subscription.product_id == Product.id,'
'Subscription.deleted == False)')
resource_uuid = Column(String(255), nullable=False, index=True)
resource_name = Column(String(255), nullable=False)
expires_at = Column(DateTime, nullable=False, index=True)
status = Column(String(255), nullable=False)
class Purchase(models.BASE, models.NovaBase):
"""Represents purchases."""
__tablename__ = 'purchases'
id = Column(Integer, primary_key=True, nullable=False, autoincrement=True)
subscription_id = Column(Integer,
ForeignKey(Subscription.id),
nullable=False)
quantity = Column(Float(asdecimal=True), nullable=False)
line_total = Column(Float(asdecimal=True), nullable=False)
| [
"lzyeval@gmail.com"
] | lzyeval@gmail.com |
7945d014e0c4f6e43010dcb95d1b20fa7116a909 | 62fb142ed5d138bf00ab50c35b43d70ba3d1d356 | /cssfmt.py | 5ddb4daf8924475f94b5790cbcbf3c832f0aff9e | [
"MIT"
] | permissive | Redknife/sublime-cssfmt | 16f0b1188a5e840079cb43ff56a80c5699723fb9 | 04d0302ad77cfe1149e72df5986acdeb988a3303 | refs/heads/master | 2016-09-11T02:25:59.223803 | 2015-08-12T07:36:46 | 2015-08-12T07:36:46 | 40,576,973 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,701 | py | # coding: utf-8
import os
import platform
import sublime
import sublime_plugin
from subprocess import Popen, PIPE
# monkeypatch `Region` to be iterable
sublime.Region.totuple = lambda self: (self.a, self.b)
sublime.Region.__iter__ = lambda self: self.totuple().__iter__()
CSSFMT_PATH = os.path.join(sublime.packages_path(), os.path.dirname(os.path.realpath(__file__)), 'cssfmt.js')
class CssfmtCommand(sublime_plugin.TextCommand):
def run(self, edit):
syntax = self.get_syntax()
if not syntax:
return
if not self.has_selection():
region = sublime.Region(0, self.view.size())
originalBuffer = self.view.substr(region)
formated = self.fmt(originalBuffer)
if formated:
self.view.replace(edit, region, formated)
return
for region in self.view.sel():
if region.empty():
continue
originalBuffer = self.view.substr(region)
formated = self.fmt(originalBuffer)
if formated:
self.view.replace(edit, region, formated)
def fmt(self, css):
folder = os.path.dirname(self.view.file_name())
try:
p = Popen(['node', CSSFMT_PATH] + [folder],
stdout=PIPE, stdin=PIPE, stderr=PIPE,
env=self.get_env(), shell=self.is_windows())
except OSError:
raise Exception("Couldn't find Node.js. Make sure it's in your " +
'$PATH by running `node -v` in your command-line.')
stdout, stderr = p.communicate(input=css.encode('utf-8'))
if stdout:
sublime.status_message('CSSfmt done!')
return stdout.decode('utf-8')
else:
sublime.status_message('CSSfmt error:\n%s' % stderr.decode('utf-8'))
sublime.error_message('CSSfmt error:\n%s' % stderr.decode('utf-8'))
print(stderr.decode('utf-8'))
def get_env(self):
env = None
if self.is_osx():
env = os.environ.copy()
env['PATH'] += self.get_node_path()
return env
def get_node_path(self):
return self.get_settings().get('node-path')
def get_settings(self):
settings = self.view.settings().get('cssfmt')
if settings is None:
settings = sublime.load_settings('cssfmt.sublime-settings')
return settings
def get_syntax(self):
if self.is_css():
return 'css'
if self.is_scss():
return 'scss'
if self.is_sass():
return 'sass'
if self.is_less():
return 'less'
if self.is_unsaved_buffer_without_syntax():
return 'css'
return False
def has_selection(self):
for sel in self.view.sel():
start, end = sel
if start != end:
return True
return False
def is_osx(self):
return platform.system() == 'Darwin'
def is_windows(self):
return platform.system() == 'Windows'
def is_unsaved_buffer_without_syntax(self):
return self.view.file_name() == None and self.is_plaintext() == True
def is_plaintext(self):
return self.view.scope_name(0).startswith('text.plain')
def is_css(self):
return self.view.scope_name(0).startswith('source.css')
def is_scss(self):
return self.view.scope_name(0).startswith('source.scss') or self.view.file_name().endswith('.scss')
def is_sass(self):
return self.view.scope_name(0).startswith('source.sass')
def is_less(self):
return self.view.scope_name(0).startswith('source.less')
| [
"realredknife@gmail.com"
] | realredknife@gmail.com |
c2dd906e1d6aa116a2534100466aaf82e8a28222 | bd604fbf7d2c474f7f19d05be86d89e46307ab68 | /pytopenface/align_dlib.py | 07862ce38c51aa767f052856c0d0903dc0d75777 | [
"Apache-2.0"
] | permissive | idiap/pytopenface | 2d1ab6c85eb47045000840b6aba69a4b701df157 | c56e6b8365b6f7542e2bdb5712236e770375993e | refs/heads/main | 2023-01-05T06:54:38.869304 | 2020-10-12T10:08:09 | 2020-10-12T10:08:09 | 303,352,465 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,877 | py | # Copyright 2015-2016 Carnegie Mellon University
#
# 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.
"""Module for dlib-based alignment."""
import cv2
import dlib
import numpy as np
TEMPLATE = np.float32([
(0.0792396913815, 0.339223741112), (0.0829219487236, 0.456955367943),
(0.0967927109165, 0.575648016728), (0.122141515615, 0.691921601066),
(0.168687863544, 0.800341263616), (0.239789390707, 0.895732504778),
(0.325662452515, 0.977068762493), (0.422318282013, 1.04329000149),
(0.531777802068, 1.06080371126), (0.641296298053, 1.03981924107),
(0.738105872266, 0.972268833998), (0.824444363295, 0.889624082279),
(0.894792677532, 0.792494155836), (0.939395486253, 0.681546643421),
(0.96111933829, 0.562238253072), (0.970579841181, 0.441758925744),
(0.971193274221, 0.322118743967), (0.163846223133, 0.249151738053),
(0.21780354657, 0.204255863861), (0.291299351124, 0.192367318323),
(0.367460241458, 0.203582210627), (0.4392945113, 0.233135599851),
(0.586445962425, 0.228141644834), (0.660152671635, 0.195923841854),
(0.737466449096, 0.182360984545), (0.813236546239, 0.192828009114),
(0.8707571886, 0.235293377042), (0.51534533827, 0.31863546193),
(0.516221448289, 0.396200446263), (0.517118861835, 0.473797687758),
(0.51816430343, 0.553157797772), (0.433701156035, 0.604054457668),
(0.475501237769, 0.62076344024), (0.520712933176, 0.634268222208),
(0.565874114041, 0.618796581487), (0.607054002672, 0.60157671656),
(0.252418718401, 0.331052263829), (0.298663015648, 0.302646354002),
(0.355749724218, 0.303020650651), (0.403718978315, 0.33867711083),
(0.352507175597, 0.349987615384), (0.296791759886, 0.350478978225),
(0.631326076346, 0.334136672344), (0.679073381078, 0.29645404267),
(0.73597236153, 0.294721285802), (0.782865376271, 0.321305281656),
(0.740312274764, 0.341849376713), (0.68499850091, 0.343734332172),
(0.353167761422, 0.746189164237), (0.414587777921, 0.719053835073),
(0.477677654595, 0.706835892494), (0.522732900812, 0.717092275768),
(0.569832064287, 0.705414478982), (0.635195811927, 0.71565572516),
(0.69951672331, 0.739419187253), (0.639447159575, 0.805236879972),
(0.576410514055, 0.835436670169), (0.525398405766, 0.841706377792),
(0.47641545769, 0.837505914975), (0.41379548902, 0.810045601727),
(0.380084785646, 0.749979603086), (0.477955996282, 0.74513234612),
(0.523389793327, 0.748924302636), (0.571057789237, 0.74332894691),
(0.672409137852, 0.744177032192), (0.572539621444, 0.776609286626),
(0.5240106503, 0.783370783245), (0.477561227414, 0.778476346951)])
TPL_MIN, TPL_MAX = np.min(TEMPLATE, axis=0), np.max(TEMPLATE, axis=0)
MINMAX_TEMPLATE = (TEMPLATE - TPL_MIN) / (TPL_MAX - TPL_MIN)
class AlignDlib:
"""
Use `dlib's landmark estimation <http://blog.dlib.net/2014/08/real-time-face-pose-estimation.html>`_ to align faces.
The alignment preprocess faces for input into a neural network.
Faces are resized to the same size (such as 96x96) and transformed
to make landmarks (such as the eyes and nose) appear at the same
location on every image.
Normalized landmarks:
.. image:: ../images/dlib-landmark-mean.png
"""
#: Landmark indices.
INNER_EYES_AND_BOTTOM_LIP = [39, 42, 57]
OUTER_EYES_AND_NOSE = [36, 45, 33]
def __init__(self, facePredictor):
"""
Instantiate an 'AlignDlib' object.
:param facePredictor: The path to dlib's
:type facePredictor: str
"""
assert facePredictor is not None
self.detector = dlib.get_frontal_face_detector()
self.predictor = dlib.shape_predictor(facePredictor)
def getAllFaceBoundingBoxes(self, rgbImg):
"""
Find all face bounding boxes in an image.
:param rgbImg: RGB image to process. Shape: (height, width, 3)
:type rgbImg: numpy.ndarray
:return: All face bounding boxes in an image.
:rtype: dlib.rectangles
"""
assert rgbImg is not None
try:
return self.detector(rgbImg, 0)
except Exception as e:
print("Warning: {}".format(e))
# In rare cases, exceptions are thrown.
return []
def getLargestFaceBoundingBox(self, rgbImg, skipMulti=False):
"""
Find the largest face bounding box in an image.
:param rgbImg: RGB image to process. Shape: (height, width, 3)
:type rgbImg: numpy.ndarray
:param skipMulti: Skip image if more than one face detected.
:type skipMulti: bool
:return: The largest face bounding box in an image, or None.
:rtype: dlib.rectangle
"""
assert rgbImg is not None
faces = self.getAllFaceBoundingBoxes(rgbImg)
if (not skipMulti and len(faces) > 0) or len(faces) == 1:
return max(faces, key=lambda rect: rect.width() * rect.height())
else:
return None
def findLandmarks(self, rgbImg, bb):
"""
Find the landmarks of a face.
:param rgbImg: RGB image to process. Shape: (height, width, 3)
:type rgbImg: numpy.ndarray
:param bb: Bounding box around the face to find landmarks for.
:type bb: dlib.rectangle
:return: Detected landmark locations.
:rtype: list of (x,y) tuples
"""
assert rgbImg is not None
assert bb is not None
points = self.predictor(rgbImg, bb)
return list(map(lambda p: (p.x, p.y), points.parts()))
def align(self, imgDim, rgbImg, bb=None,
landmarks=None, landmarkIndices=INNER_EYES_AND_BOTTOM_LIP,
skipMulti=False):
r"""align(imgDim, rgbImg, bb=None, landmarks=None, landmarkIndices=INNER_EYES_AND_BOTTOM_LIP)
Transform and align a face in an image.
:param imgDim: The edge length in pixels of the square the image is resized to.
:type imgDim: int
:param rgbImg: RGB image to process. Shape: (height, width, 3)
:type rgbImg: numpy.ndarray
:param bb: Bounding box around the face to align. \
Defaults to the largest face.
:type bb: dlib.rectangle
:param landmarks: Detected landmark locations. \
Landmarks found on `bb` if not provided.
:type landmarks: list of (x,y) tuples
:param landmarkIndices: The indices to transform to.
:type landmarkIndices: list of ints
:param skipMulti: Skip image if more than one face detected.
:type skipMulti: bool
:return: The aligned RGB image. Shape: (imgDim, imgDim, 3)
:rtype: numpy.ndarray
"""
assert imgDim is not None
assert rgbImg is not None
assert landmarkIndices is not None
if bb is None:
bb = self.getLargestFaceBoundingBox(rgbImg, skipMulti)
if bb is None:
return
if landmarks is None:
landmarks = self.findLandmarks(rgbImg, bb)
npLandmarks = np.float32(landmarks)
npLandmarkIndices = np.array(landmarkIndices)
H = cv2.getAffineTransform(npLandmarks[npLandmarkIndices],
imgDim * MINMAX_TEMPLATE[npLandmarkIndices])
thumbnail = cv2.warpAffine(rgbImg, H, (imgDim, imgDim))
return thumbnail, landmarks
| [
"philip.abbet@idiap.ch"
] | philip.abbet@idiap.ch |
a726fded486bd2431700f554247ec143c4470120 | 947fa6a4a6155ffce0038b11f4d743603418ad68 | /.c9/metadata/environment/fb_post_learning/fb_post_v2/tests/storages/test_is_reply.py | 6f54509d512ad6b525aa649971f404875a96935a | [] | no_license | bharathi151/bharathi_diyyala | bd75e10639d7d22b332d5ce677e7799402dc4984 | 99f8657d010c790a0e4e4c9d6b57f81814784eb0 | refs/heads/master | 2022-11-21T12:43:48.401239 | 2020-07-23T09:05:52 | 2020-07-23T09:05:52 | 281,903,260 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 27,064 | py | {"changed":true,"filter":false,"title":"test_is_reply.py","tooltip":"/fb_post_learning/fb_post_v2/tests/storages/test_is_reply.py","value":"import pytest\nfrom fb_post_v2.storages.comment_storage_implementation import StorageImplementation\n\n\n@pytest.mark.django_db\ndef test_is_reply_given_invalid_details_returns_flase(\n create_users,\n create_post,\n create_comments\n):\n comment_id = 1\n invalid = False\n sql_storage = StorageImplementation()\n\n result = sql_storage.is_reply(comment_id=comment_id)\n\n assert result == invalid\n\n\n@pytest.mark.django_db\ndef test_is_reply_given_valid_details_returns_true(create_comments,\n create_users,\n create_replies,\n create_post):\n comment_id = 3\n valid = True\n sql_storage = StorageImplementation()\n\n result = sql_storage.is_reply(comment_id=comment_id)\n\n assert result == valid","undoManager":{"mark":88,"position":92,"stack":[[{"start":{"row":1,"column":33},"end":{"row":1,"column":34},"action":"remove","lines":["t"],"id":2},{"start":{"row":1,"column":32},"end":{"row":1,"column":33},"action":"remove","lines":["s"]},{"start":{"row":1,"column":31},"end":{"row":1,"column":32},"action":"remove","lines":["o"]},{"start":{"row":1,"column":30},"end":{"row":1,"column":31},"action":"remove","lines":["P"]},{"start":{"row":1,"column":29},"end":{"row":1,"column":30},"action":"remove","lines":[" "]},{"start":{"row":1,"column":28},"end":{"row":1,"column":29},"action":"remove","lines":["t"]},{"start":{"row":1,"column":27},"end":{"row":1,"column":28},"action":"remove","lines":["r"]},{"start":{"row":1,"column":26},"end":{"row":1,"column":27},"action":"remove","lines":["o"]},{"start":{"row":1,"column":25},"end":{"row":1,"column":26},"action":"remove","lines":["p"]},{"start":{"row":1,"column":24},"end":{"row":1,"column":25},"action":"remove","lines":["m"]},{"start":{"row":1,"column":23},"end":{"row":1,"column":24},"action":"remove","lines":["i"]},{"start":{"row":1,"column":22},"end":{"row":1,"column":23},"action":"remove","lines":[" "]},{"start":{"row":1,"column":21},"end":{"row":1,"column":22},"action":"remove","lines":["s"]},{"start":{"row":1,"column":20},"end":{"row":1,"column":21},"action":"remove","lines":["l"]},{"start":{"row":1,"column":19},"end":{"row":1,"column":20},"action":"remove","lines":["e"]},{"start":{"row":1,"column":18},"end":{"row":1,"column":19},"action":"remove","lines":["d"]},{"start":{"row":1,"column":17},"end":{"row":1,"column":18},"action":"remove","lines":["o"]}],[{"start":{"row":1,"column":16},"end":{"row":1,"column":17},"action":"remove","lines":["m"],"id":5},{"start":{"row":1,"column":15},"end":{"row":1,"column":16},"action":"remove","lines":["."]},{"start":{"row":1,"column":14},"end":{"row":1,"column":15},"action":"remove","lines":["2"]},{"start":{"row":1,"column":13},"end":{"row":1,"column":14},"action":"remove","lines":["v"]},{"start":{"row":1,"column":12},"end":{"row":1,"column":13},"action":"remove","lines":["_"]},{"start":{"row":1,"column":11},"end":{"row":1,"column":12},"action":"remove","lines":["t"]},{"start":{"row":1,"column":10},"end":{"row":1,"column":11},"action":"remove","lines":["s"]},{"start":{"row":1,"column":9},"end":{"row":1,"column":10},"action":"remove","lines":["o"]},{"start":{"row":1,"column":8},"end":{"row":1,"column":9},"action":"remove","lines":["p"]},{"start":{"row":1,"column":7},"end":{"row":1,"column":8},"action":"remove","lines":["_"]},{"start":{"row":1,"column":6},"end":{"row":1,"column":7},"action":"remove","lines":["b"]},{"start":{"row":1,"column":5},"end":{"row":1,"column":6},"action":"remove","lines":["f"]},{"start":{"row":1,"column":4},"end":{"row":1,"column":5},"action":"remove","lines":[" "]},{"start":{"row":1,"column":3},"end":{"row":1,"column":4},"action":"remove","lines":["m"]},{"start":{"row":1,"column":2},"end":{"row":1,"column":3},"action":"remove","lines":["o"]},{"start":{"row":1,"column":1},"end":{"row":1,"column":2},"action":"remove","lines":["r"]}],[{"start":{"row":1,"column":0},"end":{"row":1,"column":1},"action":"remove","lines":["f"],"id":6},{"start":{"row":0,"column":13},"end":{"row":1,"column":0},"action":"remove","lines":["",""]}],[{"start":{"row":5,"column":24},"end":{"row":5,"column":25},"action":"remove","lines":["d"],"id":7},{"start":{"row":5,"column":23},"end":{"row":5,"column":24},"action":"remove","lines":["i"]},{"start":{"row":5,"column":22},"end":{"row":5,"column":23},"action":"remove","lines":["_"]},{"start":{"row":5,"column":21},"end":{"row":5,"column":22},"action":"remove","lines":["t"]},{"start":{"row":5,"column":20},"end":{"row":5,"column":21},"action":"remove","lines":["s"]},{"start":{"row":5,"column":19},"end":{"row":5,"column":20},"action":"remove","lines":["o"]},{"start":{"row":5,"column":18},"end":{"row":5,"column":19},"action":"remove","lines":["p"]},{"start":{"row":5,"column":17},"end":{"row":5,"column":18},"action":"remove","lines":["_"]},{"start":{"row":5,"column":16},"end":{"row":5,"column":17},"action":"remove","lines":["d"]},{"start":{"row":5,"column":15},"end":{"row":5,"column":16},"action":"remove","lines":["i"]},{"start":{"row":5,"column":14},"end":{"row":5,"column":15},"action":"remove","lines":["l"]},{"start":{"row":5,"column":13},"end":{"row":5,"column":14},"action":"remove","lines":["a"]}],[{"start":{"row":5,"column":12},"end":{"row":5,"column":13},"action":"remove","lines":["v"],"id":8}],[{"start":{"row":5,"column":12},"end":{"row":5,"column":13},"action":"insert","lines":["r"],"id":9},{"start":{"row":5,"column":13},"end":{"row":5,"column":14},"action":"insert","lines":["e"]},{"start":{"row":5,"column":14},"end":{"row":5,"column":15},"action":"insert","lines":["p"]},{"start":{"row":5,"column":15},"end":{"row":5,"column":16},"action":"insert","lines":["l"]},{"start":{"row":5,"column":16},"end":{"row":5,"column":17},"action":"insert","lines":["y"]}],[{"start":{"row":16,"column":24},"end":{"row":16,"column":25},"action":"remove","lines":["d"],"id":10},{"start":{"row":16,"column":23},"end":{"row":16,"column":24},"action":"remove","lines":["i"]},{"start":{"row":16,"column":22},"end":{"row":16,"column":23},"action":"remove","lines":["_"]},{"start":{"row":16,"column":21},"end":{"row":16,"column":22},"action":"remove","lines":["t"]},{"start":{"row":16,"column":20},"end":{"row":16,"column":21},"action":"remove","lines":["s"]},{"start":{"row":16,"column":19},"end":{"row":16,"column":20},"action":"remove","lines":["o"]},{"start":{"row":16,"column":18},"end":{"row":16,"column":19},"action":"remove","lines":["p"]},{"start":{"row":16,"column":17},"end":{"row":16,"column":18},"action":"remove","lines":["_"]},{"start":{"row":16,"column":16},"end":{"row":16,"column":17},"action":"remove","lines":["d"]},{"start":{"row":16,"column":15},"end":{"row":16,"column":16},"action":"remove","lines":["i"]},{"start":{"row":16,"column":14},"end":{"row":16,"column":15},"action":"remove","lines":["l"]},{"start":{"row":16,"column":13},"end":{"row":16,"column":14},"action":"remove","lines":["a"]},{"start":{"row":16,"column":12},"end":{"row":16,"column":13},"action":"remove","lines":["v"]}],[{"start":{"row":16,"column":12},"end":{"row":16,"column":13},"action":"insert","lines":["r"],"id":11},{"start":{"row":16,"column":13},"end":{"row":16,"column":14},"action":"insert","lines":["e"]},{"start":{"row":16,"column":14},"end":{"row":16,"column":15},"action":"insert","lines":["p"]},{"start":{"row":16,"column":15},"end":{"row":16,"column":16},"action":"insert","lines":["l"]},{"start":{"row":16,"column":16},"end":{"row":16,"column":17},"action":"insert","lines":["l"]},{"start":{"row":16,"column":17},"end":{"row":16,"column":18},"action":"insert","lines":["y"]}],[{"start":{"row":16,"column":67},"end":{"row":16,"column":68},"action":"insert","lines":[","],"id":12}],[{"start":{"row":5,"column":54},"end":{"row":5,"column":55},"action":"insert","lines":["r"],"id":13}],[{"start":{"row":5,"column":54},"end":{"row":5,"column":55},"action":"remove","lines":["r"],"id":14}],[{"start":{"row":5,"column":54},"end":{"row":5,"column":55},"action":"insert","lines":["c"],"id":15},{"start":{"row":5,"column":55},"end":{"row":5,"column":56},"action":"insert","lines":["o"]},{"start":{"row":5,"column":56},"end":{"row":5,"column":57},"action":"insert","lines":["m"]},{"start":{"row":5,"column":57},"end":{"row":5,"column":58},"action":"insert","lines":["m"]}],[{"start":{"row":5,"column":57},"end":{"row":5,"column":58},"action":"remove","lines":["m"],"id":16},{"start":{"row":5,"column":56},"end":{"row":5,"column":57},"action":"remove","lines":["m"]},{"start":{"row":5,"column":55},"end":{"row":5,"column":56},"action":"remove","lines":["o"]}],[{"start":{"row":5,"column":55},"end":{"row":5,"column":56},"action":"insert","lines":["r"],"id":17},{"start":{"row":5,"column":56},"end":{"row":5,"column":57},"action":"insert","lines":["e"]},{"start":{"row":5,"column":57},"end":{"row":5,"column":58},"action":"insert","lines":["a"]},{"start":{"row":5,"column":58},"end":{"row":5,"column":59},"action":"insert","lines":["t"]},{"start":{"row":5,"column":59},"end":{"row":5,"column":60},"action":"insert","lines":["e"]}],[{"start":{"row":5,"column":60},"end":{"row":5,"column":61},"action":"insert","lines":["_"],"id":18}],[{"start":{"row":5,"column":54},"end":{"row":5,"column":61},"action":"remove","lines":["create_"],"id":19},{"start":{"row":5,"column":54},"end":{"row":5,"column":71},"action":"insert","lines":["create_comments()"]}],[{"start":{"row":5,"column":69},"end":{"row":5,"column":71},"action":"remove","lines":["()"],"id":20}],[{"start":{"row":16,"column":68},"end":{"row":16,"column":69},"action":"insert","lines":["c"],"id":21},{"start":{"row":16,"column":69},"end":{"row":16,"column":70},"action":"insert","lines":["r"]}],[{"start":{"row":16,"column":69},"end":{"row":16,"column":70},"action":"remove","lines":["r"],"id":22},{"start":{"row":16,"column":68},"end":{"row":16,"column":69},"action":"remove","lines":["c"]}],[{"start":{"row":16,"column":68},"end":{"row":16,"column":69},"action":"insert","lines":[" "],"id":23},{"start":{"row":16,"column":69},"end":{"row":16,"column":70},"action":"insert","lines":["c"]},{"start":{"row":16,"column":70},"end":{"row":16,"column":71},"action":"insert","lines":["r"]},{"start":{"row":16,"column":71},"end":{"row":16,"column":72},"action":"insert","lines":["e"]},{"start":{"row":16,"column":72},"end":{"row":16,"column":73},"action":"insert","lines":["a"]}],[{"start":{"row":16,"column":73},"end":{"row":16,"column":74},"action":"insert","lines":["t"],"id":24},{"start":{"row":16,"column":74},"end":{"row":16,"column":75},"action":"insert","lines":["e"]},{"start":{"row":16,"column":75},"end":{"row":16,"column":76},"action":"insert","lines":["_"]}],[{"start":{"row":16,"column":76},"end":{"row":16,"column":77},"action":"insert","lines":["r"],"id":25},{"start":{"row":16,"column":77},"end":{"row":16,"column":78},"action":"insert","lines":["e"]}],[{"start":{"row":16,"column":69},"end":{"row":16,"column":78},"action":"remove","lines":["create_re"],"id":26},{"start":{"row":16,"column":69},"end":{"row":16,"column":85},"action":"insert","lines":["create_replies()"]}],[{"start":{"row":16,"column":83},"end":{"row":16,"column":85},"action":"remove","lines":["()"],"id":27}],[{"start":{"row":16,"column":68},"end":{"row":16,"column":69},"action":"remove","lines":[" "],"id":28}],[{"start":{"row":16,"column":68},"end":{"row":17,"column":0},"action":"insert","lines":["",""],"id":29}],[{"start":{"row":17,"column":0},"end":{"row":17,"column":4},"action":"insert","lines":[" "],"id":30}],[{"start":{"row":17,"column":4},"end":{"row":17,"column":8},"action":"insert","lines":[" "],"id":31}],[{"start":{"row":17,"column":8},"end":{"row":17,"column":12},"action":"insert","lines":[" "],"id":32}],[{"start":{"row":17,"column":12},"end":{"row":17,"column":16},"action":"insert","lines":[" "],"id":33}],[{"start":{"row":17,"column":16},"end":{"row":17,"column":20},"action":"insert","lines":[" "],"id":34}],[{"start":{"row":17,"column":20},"end":{"row":17,"column":24},"action":"insert","lines":[" "],"id":35}],[{"start":{"row":17,"column":24},"end":{"row":17,"column":28},"action":"insert","lines":[" "],"id":36}],[{"start":{"row":17,"column":28},"end":{"row":17,"column":32},"action":"insert","lines":[" "],"id":37}],[{"start":{"row":17,"column":32},"end":{"row":17,"column":36},"action":"insert","lines":[" "],"id":38}],[{"start":{"row":17,"column":36},"end":{"row":17,"column":40},"action":"insert","lines":[" "],"id":39}],[{"start":{"row":17,"column":40},"end":{"row":17,"column":44},"action":"insert","lines":[" "],"id":40}],[{"start":{"row":17,"column":44},"end":{"row":17,"column":48},"action":"insert","lines":[" "],"id":41}],[{"start":{"row":17,"column":48},"end":{"row":17,"column":52},"action":"insert","lines":[" "],"id":42}],[{"start":{"row":22,"column":25},"end":{"row":22,"column":44},"action":"remove","lines":["is_valid_comment_id"],"id":43}],[{"start":{"row":22,"column":25},"end":{"row":22,"column":26},"action":"insert","lines":["i"],"id":44},{"start":{"row":22,"column":26},"end":{"row":22,"column":27},"action":"insert","lines":["s"]},{"start":{"row":22,"column":27},"end":{"row":22,"column":28},"action":"insert","lines":["_"]},{"start":{"row":22,"column":28},"end":{"row":22,"column":29},"action":"insert","lines":["r"]},{"start":{"row":22,"column":29},"end":{"row":22,"column":30},"action":"insert","lines":["e"]}],[{"start":{"row":22,"column":30},"end":{"row":22,"column":31},"action":"insert","lines":["p"],"id":45},{"start":{"row":22,"column":31},"end":{"row":22,"column":32},"action":"insert","lines":["l"]},{"start":{"row":22,"column":32},"end":{"row":22,"column":33},"action":"insert","lines":["y"]}],[{"start":{"row":10,"column":25},"end":{"row":10,"column":44},"action":"remove","lines":["is_valid_comment_id"],"id":46}],[{"start":{"row":10,"column":25},"end":{"row":10,"column":26},"action":"insert","lines":["i"],"id":47},{"start":{"row":10,"column":26},"end":{"row":10,"column":27},"action":"insert","lines":["s"]}],[{"start":{"row":10,"column":25},"end":{"row":10,"column":27},"action":"remove","lines":["is"],"id":48},{"start":{"row":10,"column":25},"end":{"row":10,"column":33},"action":"insert","lines":["is_reply"]}],[{"start":{"row":16,"column":16},"end":{"row":16,"column":17},"action":"remove","lines":["l"],"id":49}],[{"start":{"row":17,"column":48},"end":{"row":17,"column":52},"action":"remove","lines":[" "],"id":50}],[{"start":{"row":17,"column":48},"end":{"row":17,"column":49},"action":"insert","lines":[" "],"id":51},{"start":{"row":17,"column":49},"end":{"row":17,"column":50},"action":"insert","lines":[" "]},{"start":{"row":17,"column":50},"end":{"row":17,"column":51},"action":"insert","lines":[" "]}],[{"start":{"row":17,"column":65},"end":{"row":17,"column":66},"action":"insert","lines":[","],"id":52}],[{"start":{"row":17,"column":66},"end":{"row":18,"column":0},"action":"insert","lines":["",""],"id":53},{"start":{"row":18,"column":0},"end":{"row":18,"column":51},"action":"insert","lines":[" "]},{"start":{"row":18,"column":51},"end":{"row":18,"column":52},"action":"insert","lines":["c"]},{"start":{"row":18,"column":52},"end":{"row":18,"column":53},"action":"insert","lines":["r"]},{"start":{"row":18,"column":53},"end":{"row":18,"column":54},"action":"insert","lines":["e"]}],[{"start":{"row":18,"column":51},"end":{"row":18,"column":54},"action":"remove","lines":["cre"],"id":54},{"start":{"row":18,"column":51},"end":{"row":18,"column":67},"action":"insert","lines":["create_comment()"]}],[{"start":{"row":18,"column":65},"end":{"row":18,"column":67},"action":"remove","lines":["()"],"id":55},{"start":{"row":18,"column":64},"end":{"row":18,"column":65},"action":"remove","lines":["t"]},{"start":{"row":18,"column":63},"end":{"row":18,"column":64},"action":"remove","lines":["n"]},{"start":{"row":18,"column":62},"end":{"row":18,"column":63},"action":"remove","lines":["e"]},{"start":{"row":18,"column":61},"end":{"row":18,"column":62},"action":"remove","lines":["m"]},{"start":{"row":18,"column":60},"end":{"row":18,"column":61},"action":"remove","lines":["m"]},{"start":{"row":18,"column":59},"end":{"row":18,"column":60},"action":"remove","lines":["o"]},{"start":{"row":18,"column":58},"end":{"row":18,"column":59},"action":"remove","lines":["c"]}],[{"start":{"row":18,"column":58},"end":{"row":18,"column":59},"action":"insert","lines":["p"],"id":56},{"start":{"row":18,"column":59},"end":{"row":18,"column":60},"action":"insert","lines":["o"]},{"start":{"row":18,"column":60},"end":{"row":18,"column":61},"action":"insert","lines":["s"]},{"start":{"row":18,"column":61},"end":{"row":18,"column":62},"action":"insert","lines":["t"]}],[{"start":{"row":19,"column":17},"end":{"row":19,"column":18},"action":"remove","lines":["1"],"id":57}],[{"start":{"row":19,"column":17},"end":{"row":19,"column":18},"action":"insert","lines":["3"],"id":58}],[{"start":{"row":5,"column":54},"end":{"row":6,"column":0},"action":"insert","lines":["",""],"id":59},{"start":{"row":6,"column":0},"end":{"row":6,"column":4},"action":"insert","lines":[" "]}],[{"start":{"row":6,"column":19},"end":{"row":7,"column":0},"action":"insert","lines":["",""],"id":60},{"start":{"row":7,"column":0},"end":{"row":7,"column":4},"action":"insert","lines":[" "]},{"start":{"row":7,"column":4},"end":{"row":8,"column":0},"action":"insert","lines":["",""]},{"start":{"row":8,"column":0},"end":{"row":8,"column":4},"action":"insert","lines":[" "]}],[{"start":{"row":8,"column":0},"end":{"row":8,"column":4},"action":"remove","lines":[" "],"id":61},{"start":{"row":7,"column":4},"end":{"row":8,"column":0},"action":"remove","lines":["",""]},{"start":{"row":7,"column":0},"end":{"row":7,"column":4},"action":"remove","lines":[" "]}],[{"start":{"row":5,"column":54},"end":{"row":6,"column":0},"action":"insert","lines":["",""],"id":62},{"start":{"row":6,"column":0},"end":{"row":6,"column":4},"action":"insert","lines":[" "]},{"start":{"row":6,"column":4},"end":{"row":6,"column":5},"action":"insert","lines":["c"]},{"start":{"row":6,"column":5},"end":{"row":6,"column":6},"action":"insert","lines":["r"]},{"start":{"row":6,"column":6},"end":{"row":6,"column":7},"action":"insert","lines":["e"]}],[{"start":{"row":6,"column":7},"end":{"row":6,"column":8},"action":"insert","lines":["a"],"id":63}],[{"start":{"row":6,"column":4},"end":{"row":6,"column":8},"action":"remove","lines":["crea"],"id":64},{"start":{"row":6,"column":4},"end":{"row":6,"column":19},"action":"insert","lines":["create_comments"]}],[{"start":{"row":6,"column":18},"end":{"row":6,"column":19},"action":"remove","lines":["s"],"id":65},{"start":{"row":6,"column":17},"end":{"row":6,"column":18},"action":"remove","lines":["t"]},{"start":{"row":6,"column":16},"end":{"row":6,"column":17},"action":"remove","lines":["n"]},{"start":{"row":6,"column":15},"end":{"row":6,"column":16},"action":"remove","lines":["e"]},{"start":{"row":6,"column":14},"end":{"row":6,"column":15},"action":"remove","lines":["m"]},{"start":{"row":6,"column":13},"end":{"row":6,"column":14},"action":"remove","lines":["m"]},{"start":{"row":6,"column":12},"end":{"row":6,"column":13},"action":"remove","lines":["o"]},{"start":{"row":6,"column":11},"end":{"row":6,"column":12},"action":"remove","lines":["c"]}],[{"start":{"row":6,"column":11},"end":{"row":6,"column":12},"action":"insert","lines":["u"],"id":66},{"start":{"row":6,"column":12},"end":{"row":6,"column":13},"action":"insert","lines":["s"]},{"start":{"row":6,"column":13},"end":{"row":6,"column":14},"action":"insert","lines":["e"]},{"start":{"row":6,"column":14},"end":{"row":6,"column":15},"action":"insert","lines":["r"]},{"start":{"row":6,"column":15},"end":{"row":6,"column":16},"action":"insert","lines":["s"]},{"start":{"row":6,"column":16},"end":{"row":6,"column":17},"action":"insert","lines":[","]}],[{"start":{"row":6,"column":17},"end":{"row":7,"column":0},"action":"insert","lines":["",""],"id":67},{"start":{"row":7,"column":0},"end":{"row":7,"column":4},"action":"insert","lines":[" "]},{"start":{"row":7,"column":4},"end":{"row":7,"column":5},"action":"insert","lines":["c"]},{"start":{"row":7,"column":5},"end":{"row":7,"column":6},"action":"insert","lines":["r"]},{"start":{"row":7,"column":6},"end":{"row":7,"column":7},"action":"insert","lines":["e"]}],[{"start":{"row":7,"column":7},"end":{"row":7,"column":8},"action":"insert","lines":["a"],"id":68}],[{"start":{"row":7,"column":4},"end":{"row":7,"column":8},"action":"remove","lines":["crea"],"id":69},{"start":{"row":7,"column":4},"end":{"row":7,"column":16},"action":"insert","lines":["create_users"]}],[{"start":{"row":7,"column":15},"end":{"row":7,"column":16},"action":"remove","lines":["s"],"id":70},{"start":{"row":7,"column":14},"end":{"row":7,"column":15},"action":"remove","lines":["r"]},{"start":{"row":7,"column":13},"end":{"row":7,"column":14},"action":"remove","lines":["e"]},{"start":{"row":7,"column":12},"end":{"row":7,"column":13},"action":"remove","lines":["s"]},{"start":{"row":7,"column":11},"end":{"row":7,"column":12},"action":"remove","lines":["u"]}],[{"start":{"row":7,"column":11},"end":{"row":7,"column":12},"action":"insert","lines":["p"],"id":71},{"start":{"row":7,"column":12},"end":{"row":7,"column":13},"action":"insert","lines":["o"]},{"start":{"row":7,"column":13},"end":{"row":7,"column":14},"action":"insert","lines":["s"]},{"start":{"row":7,"column":14},"end":{"row":7,"column":15},"action":"insert","lines":["t"]},{"start":{"row":7,"column":15},"end":{"row":7,"column":16},"action":"insert","lines":[","]}],[{"start":{"row":20,"column":67},"end":{"row":21,"column":0},"action":"insert","lines":["",""],"id":72}],[{"start":{"row":21,"column":0},"end":{"row":21,"column":4},"action":"insert","lines":[" "],"id":73}],[{"start":{"row":21,"column":4},"end":{"row":21,"column":8},"action":"insert","lines":[" "],"id":74}],[{"start":{"row":21,"column":8},"end":{"row":21,"column":12},"action":"insert","lines":[" "],"id":75}],[{"start":{"row":21,"column":12},"end":{"row":21,"column":16},"action":"insert","lines":[" "],"id":76}],[{"start":{"row":21,"column":16},"end":{"row":21,"column":20},"action":"insert","lines":[" "],"id":77}],[{"start":{"row":21,"column":20},"end":{"row":21,"column":24},"action":"insert","lines":[" "],"id":78}],[{"start":{"row":21,"column":24},"end":{"row":21,"column":28},"action":"insert","lines":[" "],"id":79}],[{"start":{"row":21,"column":28},"end":{"row":21,"column":32},"action":"insert","lines":[" "],"id":80}],[{"start":{"row":21,"column":32},"end":{"row":21,"column":36},"action":"insert","lines":[" "],"id":81}],[{"start":{"row":21,"column":36},"end":{"row":21,"column":40},"action":"insert","lines":[" "],"id":82}],[{"start":{"row":21,"column":40},"end":{"row":21,"column":44},"action":"insert","lines":[" "],"id":83}],[{"start":{"row":21,"column":44},"end":{"row":21,"column":48},"action":"insert","lines":[" "],"id":84}],[{"start":{"row":21,"column":48},"end":{"row":21,"column":52},"action":"insert","lines":[" "],"id":85}],[{"start":{"row":21,"column":48},"end":{"row":21,"column":52},"action":"remove","lines":[" "],"id":86}],[{"start":{"row":21,"column":48},"end":{"row":21,"column":49},"action":"insert","lines":[" "],"id":87},{"start":{"row":21,"column":49},"end":{"row":21,"column":50},"action":"insert","lines":[" "]},{"start":{"row":21,"column":50},"end":{"row":21,"column":51},"action":"insert","lines":[" "]},{"start":{"row":21,"column":51},"end":{"row":21,"column":52},"action":"insert","lines":["c"]},{"start":{"row":21,"column":52},"end":{"row":21,"column":53},"action":"insert","lines":["r"]}],[{"start":{"row":21,"column":53},"end":{"row":21,"column":54},"action":"insert","lines":["e"],"id":88},{"start":{"row":21,"column":54},"end":{"row":21,"column":55},"action":"insert","lines":["a"]}],[{"start":{"row":21,"column":51},"end":{"row":21,"column":55},"action":"remove","lines":["crea"],"id":89},{"start":{"row":21,"column":51},"end":{"row":21,"column":66},"action":"insert","lines":["create_comments"]}],[{"start":{"row":21,"column":65},"end":{"row":21,"column":66},"action":"remove","lines":["s"],"id":90},{"start":{"row":21,"column":64},"end":{"row":21,"column":65},"action":"remove","lines":["t"]},{"start":{"row":21,"column":63},"end":{"row":21,"column":64},"action":"remove","lines":["n"]},{"start":{"row":21,"column":62},"end":{"row":21,"column":63},"action":"remove","lines":["e"]},{"start":{"row":21,"column":61},"end":{"row":21,"column":62},"action":"remove","lines":["m"]},{"start":{"row":21,"column":60},"end":{"row":21,"column":61},"action":"remove","lines":["m"]},{"start":{"row":21,"column":59},"end":{"row":21,"column":60},"action":"remove","lines":["o"]},{"start":{"row":21,"column":58},"end":{"row":21,"column":59},"action":"remove","lines":["c"]}],[{"start":{"row":21,"column":58},"end":{"row":21,"column":59},"action":"insert","lines":["u"],"id":91},{"start":{"row":21,"column":59},"end":{"row":21,"column":60},"action":"insert","lines":["s"]},{"start":{"row":21,"column":60},"end":{"row":21,"column":61},"action":"insert","lines":["e"]},{"start":{"row":21,"column":61},"end":{"row":21,"column":62},"action":"insert","lines":["r"]},{"start":{"row":21,"column":62},"end":{"row":21,"column":63},"action":"insert","lines":["s"]}],[{"start":{"row":21,"column":63},"end":{"row":21,"column":64},"action":"insert","lines":[","],"id":92}],[{"start":{"row":1,"column":28},"end":{"row":1,"column":29},"action":"remove","lines":["t"],"id":93},{"start":{"row":1,"column":27},"end":{"row":1,"column":28},"action":"remove","lines":["s"]},{"start":{"row":1,"column":26},"end":{"row":1,"column":27},"action":"remove","lines":["o"]},{"start":{"row":1,"column":25},"end":{"row":1,"column":26},"action":"remove","lines":["p"]}],[{"start":{"row":1,"column":25},"end":{"row":1,"column":26},"action":"insert","lines":["c"],"id":94},{"start":{"row":1,"column":26},"end":{"row":1,"column":27},"action":"insert","lines":["o"]},{"start":{"row":1,"column":27},"end":{"row":1,"column":28},"action":"insert","lines":["m"]},{"start":{"row":1,"column":28},"end":{"row":1,"column":29},"action":"insert","lines":["e"]}],[{"start":{"row":1,"column":28},"end":{"row":1,"column":29},"action":"remove","lines":["e"],"id":95}],[{"start":{"row":1,"column":28},"end":{"row":1,"column":29},"action":"insert","lines":["m"],"id":96},{"start":{"row":1,"column":29},"end":{"row":1,"column":30},"action":"insert","lines":["e"]},{"start":{"row":1,"column":30},"end":{"row":1,"column":31},"action":"insert","lines":["n"]},{"start":{"row":1,"column":31},"end":{"row":1,"column":32},"action":"insert","lines":["t"]}]]},"ace":{"folds":[],"scrolltop":0,"scrollleft":0,"selection":{"start":{"row":6,"column":17},"end":{"row":6,"column":17},"isBackwards":false},"options":{"guessTabSize":true,"useWrapMode":false,"wrapToView":true},"firstLineState":0},"timestamp":1590061738237} | [
"bharathi151273@gmail.com"
] | bharathi151273@gmail.com |
87f86ee5f18ff897da50586e96692fc1a9d89d64 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03371/s901597766.py | 123ae25fb816ba52b35bc7528454231feb8593bf | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 532 | py | A, B, C, X, Y = map(int, input().split())
cntA = 0
cntB = 0
cntC = 0
value = 0
if 2*C<=A+B:
#Cで買いそろえた方が安いので
#(max(X, Y)-abs(X-Y))*2枚は買うことになる
Cmaisu = (max(X, Y)-abs(X-Y))*2
value += C * Cmaisu
if (2*C<=A and X>Y) or (2*C<=B and X<Y):
#abs(X-Y)枚についても2Cが安けりゃCで買う
value += C * abs(X-Y) * 2
else:
if X>Y:
value += A*(X-Y)
else:
value += B*(Y-X)
else:
value += A*X+B*Y
print(value) | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
f8838e64f8cf5ee928874555734d1900e11c1487 | 44d71cfdf4ed035f64e34a8a8ae960566104730f | /Reverse elements in Stack.py | fdeb199b2f9d9081bd68174d4870fd13c2298cd4 | [] | no_license | indrajitrdas/Simple-Programs | 82a2ec2c8580792b6a7279bb5a74038d49019c15 | 2214b1d365eec38ee0019a9baa3873341fc0dbc6 | refs/heads/master | 2020-04-30T09:29:33.766059 | 2019-03-20T14:24:56 | 2019-03-20T14:24:56 | 176,748,769 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 687 | py | # Reverse Stack using Recursion
def createStack():
stack = []
return stack
def push(stack, item):
stack.append(item)
def pop(stack):
if len(stack) == 0:
return False
else:
return stack.pop()
def reverseStack(stack):
if len(stack) >= 1:
temp = pop(stack)
reverseStack(stack)
pushlast(stack, temp)
def pushlast(stack, item):
if len(stack) == 0:
push(stack, item)
else:
temp = pop(stack)
pushlast(stack, item)
push(stack, temp)
stack = createStack()
push(stack, 1)
push(stack, 2)
push(stack, 3)
push(stack, 4)
| [
"noreply@github.com"
] | indrajitrdas.noreply@github.com |
bb4f8983351dfbbb503bd0739eeec0facac8ff2e | 2605cf6e355b8be8cd019c26ae81af7980405d3f | /BBB/stm/ninja.py | b0093be03753ab2a7117d7bb3ffa5ddaa17aa825 | [] | no_license | pablovaldes/intelligent_camera_trap | 29a905130d955214d98277a13acab49fcbc3a54d | 7cffcc15230e94f39635cb77b66d5951c0b8fa38 | refs/heads/master | 2020-07-25T23:25:12.361686 | 2014-06-08T04:37:20 | 2014-06-08T04:37:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,058 | py | import serial
import time
packetNum = 11
commandCharNum = 1
commandHeader = "STC"
dataHeader = "STD"
#commandPan = ["R0120", "R0100", "R0060", "R0040", "R0020", "R0010", "R0005", "R0000", "L0005", "L0010", "L0020", "L0040", "L0060", "L0100", "L0120"]
commandPan = ["R0320", "R0100", "R0060", "R0040", "R0020", "R0010", "R0005", "R0000", "L0005", "L0010", "L0020", "L0040", "L0060", "L0100", "L020"]
commandXStep = ["X0000","X0100", "X0200", "X0300","X0400","X0500", "X0600","X0700","X0800","X0900", "X1000"]
commandTilt = ["U0020", "Z0000", "D0020"]
commandCenter= "X0500Y0200"
ser = None
def init (port):
global ser
ser = serial.Serial(port, 19200, timeout=1)
def pan(number):
ser.write(dataHeader + b'\x0B' + commandPan[number] + commandTilt [1] + "AA")
#def panX_Set(number):
# ser.write(dataHeader + b'\x05' + commandXStep[number] + "AA")
def center():
ser.write(dataHeader + b'\x0B' + commandCenter + "AA")
def panX(num):
number = str(num).zfill(4)
ser.write(dataHeader + b'\x05' + "X" + number + "AA")
| [
"ubuntu@ubuntu-armhf.(none)"
] | ubuntu@ubuntu-armhf.(none) |
d5fdd53f33605608b0d099989fc0d533fc14221a | 8c5902881416b6f77e9ed350197f8d0463913cf4 | /portrait.py | 95d1ff4bbc09439a6ffa5646876c5b2a0ecd8240 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | RyoheiTomiyama/e-calendar | 93574dda07e55854287f4e612a7df5bd59497cb2 | 50ff8d2ee1b3b04d3935462fa3f55071f17294c4 | refs/heads/master | 2023-03-23T05:05:03.834172 | 2021-03-20T10:32:39 | 2021-03-20T10:32:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,553 | py | # -*- coding: utf-8 -*-
import calendar
from datetime import date, datetime
import itertools
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from connect_calendar import Calendar
def get_font(font_symbol: str, font_size: int):
return ImageFont.truetype(font_files[font_symbol], font_size)
def get_width(text: str, font_symbol: str, font_size: int):
bbox = draw.multiline_textbbox(
(0, 0), text,
font=get_font(font_symbol, font_size)
)
return bbox[2] - bbox[0]
def padding_width(width: int, text: str, font_symbol: str, font_size: int):
return (width - get_width(text, font_symbol, font_size)) // 2
# for mac only
font_files = dict(
en='/System/Library/Fonts/Optima.ttc',
ja='/System/Library/Fonts/ヒラギノ角ゴシック W3.ttc',
title='/System/Library/Fonts/Supplemental/Zapfino.ttf'
)
# grey scale
grey = np.arange(0, 255, 256 // 16).tolist()
# image size
SIZE = (600, 800)
# create a new image
img = Image.new('L', SIZE, '#FFF')
today = date.today()
year = today.year
month = today.month
# get my schedule and holidays
events, event_days, holidays = Calendar.get_events(today)
draw = ImageDraw.Draw(img)
# show year
draw.multiline_text(
(10, 10),
str(year),
fill=grey[2],
font=get_font('en', 24)
)
# show month
draw.multiline_text(
(padding_width(SIZE[0], today.strftime("%B"), 'title', 30), 18),
today.strftime("%B"),
fill=grey[1],
font=get_font('title', 30)
)
draw.line(((10, 110), (SIZE[0] - 10, 110)), fill=grey[0], width=2)
# labels of weekday
days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
# get the date of this month
calendar_eu = calendar.monthcalendar(year, month)
formatted = [0]+list(itertools.chain.from_iterable(calendar_eu))[:-1]
calendar = np.array(formatted).reshape(-1, 7).tolist()
w_day = 600 // 7
x_start = np.arange(7) * w_day
# calendar
# show the label of weekday
for i, text in enumerate(days):
w_pad = padding_width(w_day, text, 'en', 20)
color = grey[8] if i % 6 == 0 else grey[2]
draw.multiline_text((x_start[i] + w_pad, 120),
text, font=get_font('en', 20), fill=color)
draw.line(((10, 150), (SIZE[0] - 10, 150)), fill=grey[10], width=1)
# show the dates
for h, row in enumerate(calendar):
for i, text in enumerate(row):
if text == 0:
continue
w_pad = padding_width(w_day, str(text), 'en', 30)
color = grey[8] if i % 6 == 0 or text in holidays else grey[0]
draw.multiline_text((x_start[i] + w_pad, 170 + 60 * h),
str(text), font=get_font('en', 30), fill=color)
if text in event_days:
draw.line(((x_start[i] + (w_day - 10) // 2, 204 + 60 * h),
(x_start[i] + (w_day - 10) // 2 + 10, 204 + 60 * h)), fill=grey[4])
draw.line(((10, 470), (SIZE[0] - 10, 470)), fill=grey[1], width=2)
# show the schedule
for h, event in enumerate(events[:8]):
text = f'{"/".join(event[1][0].split("-")[1:])}' \
+ f'{f" {event[1][1][:5]}" if len(event[1]) != 1 else ""} {event[0]}'
draw.multiline_text((30, 480 + 30 * h),
text, font=get_font('ja', 20), fill=grey[2])
draw.line(
((16, 500 + 30 * h), (SIZE[0] - 16, 500 + 30 * h)), fill=grey[10], width=1)
dt = datetime.now().isoformat(sep=' ')[:16].replace('-', '.')
draw.multiline_text((10, SIZE[1] - 30), f'Updated at {dt}',
font=get_font('en', 16), fill=grey[8])
# to bmp
file_name = './image_600x800.bmp'
img.save(file_name, 'bmp')
| [
"19624453+mktia@users.noreply.github.com"
] | 19624453+mktia@users.noreply.github.com |
23ff063edd1eed8fcca419c2c1dd4e257ee702ef | e955a750f5a75a38440be389e6a1825d26f1e42b | /scrapy_policy_zhejiang2.py | 4d34a5919f760ca024d42dbace42a16f5769b528 | [] | no_license | jarekbiu/policy_spider | 1c59ea582377823bcefd5bb8a8af3d677bd3459a | 81ba4248903c63a448d9743bb5158061d7e52159 | refs/heads/master | 2020-04-06T15:08:29.718177 | 2018-11-14T15:15:30 | 2018-11-14T15:15:30 | 157,567,101 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,792 | py | # -*- coding: UTF-8 -*-
import requests
import re
import xlwt
import time
import random
import json
from bs4 import BeautifulSoup
import hashlib
#浙江省政府公报
file_db = open(r'/Users/jarek-mac/THU/ipolicy/data_policy_public.txt','a',encoding='utf-8')
file_fail = open(r'/Users/jarek-mac/THU/ipolicy/data_policy_publicfail.txt','a',encoding='utf-8')
get_person="zhaorui"
check_person=''
province='浙江省'
source_name='浙江省政府'
get_one_page():
policy_num=0
policy_success_num=0
policy_fail_num=0
row=['null','null','null','null','null'
,'null','null','null','null','null'
,'null','null','null','null','null'
,'null','null','null','null','null'
,'null','null','null','null','null'
,'null','null','null','null','null'
,'null','null','null','null','null'
,'null','null']
row[6]=get_person
row[7]=check_person
row[2]=source_name
header = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36'
}
url='http://www.zj.gov.cn/col/col41314/index.html'
try:
response=requests.get(url,header,timeout=20)
response.encoding = 'utf-8'
response=response.text
soup = BeautifulSoup(response)
options=soup.find_all('option')
option1=options[1:11]#第一部分 以年份为单位
option2=options[11:]#第二部分 以期刊为单位
#print(option1)
m = hashlib.md5()
for option in option1:
info=[]
info.append(province)
info.append(source_name)
gongbaoUrl='http://www.zj.gov.cn'+option['value']
#m.update(gongbaoUrl.encode("utf8"))
# md5 for url
#md5 = m.hexdigest()
row[1] = md5
row[0] = gongbaoUrl
#print(gongbaoUrl)
try:
datas=requests.get(gongbaoUrl,header,timeout=5)
datas.encoding='utf-8'
datas=datas.text
soup1=BeautifulSoup(datas)
gongbao_as=soup1.find_all(class_='bt_link')
gongbao_as=gongbao_as[4:]
gongbao_source = soup1.find('title')
row[12] = gongbao_source.string
#info.append(gongbao_source.string)#title
print(row[12])
for gongbao_a in gongbao_as:
policy_num+=1
print('正在抓取第'+str(policy_num)+'条数据...')
gongbao_content_url=gongbao_a['href']
#print(gongbao_content_url)
if gongbao_content_url[0:4]!='http':
gongbao_content_url='http://www.zj.gov.cn'+gongbao_content_url
row[10]=gongbao_content_url
gongbao_title=gongbao_a['title']
row[9]=gongbao_title
info.append(gongbao_content_url)
m.update(gongbao_content_url.encode("utf8"))
# md5 for url
md5 = m.hexdigest()
info.append(md5)
info.append(gongbao_source.string)#title
info.append(gongbao_content_url)#公报内容是一个链接
info.append(get_person)
info.append('1')
policy_success_num+=1
except Exception as err:
print('scrapy fail in option1')
policy_fail_num+=1
for option in option2:
info=[]
gongbaoUrl='http://www.zj.gov.cn'+option['value']#每一期
info.append(province)
info.append(source_name)
#m.update(gongbaoUrl.encode("utf8"))
try:
datas=requests.get(gongbaoUrl,header,timeout=5)
datas.encoding='utf-8'
datas=datas.text
soup3=BeautifulSoup(datas)
gongbao_as=soup3.select('a')
gongbao_source=soup3.find('title')
row[12]=gongbao_source.string#title
#print(row[12])
gongbao_as=gongbao_as[4:-1]#公告每一条
content = ''
for gongbao_a in gongbao_as:
policy_num+=1
print('正在抓取第'+str(policy_num)+'条数据...')
gongbao_content_url=gongbao_a['href']
if gongbao_content_url[0:4] != 'http':
gongbao_content_url='http://www.zj.gov.cn'+gongbao_content_url
row[10] = gongbao_content_url#每条具体内容
#print(row[10])
m.update(gongbao_content_url.encode("utf8"))
# md5 for url
md5 = m.hexdigest()
info.append(gongbao_content_url)
info.append(md5)
contents=requests.get(gongbao_content_url,header,timeout=5)
contents.encoding = 'utf-8'
contents = contents.text
soup2 = BeautifulSoup(contents)
div_contents=soup2.find_all(id='zoom')
#for div_content in div_contents:
# p_contents=div_content.findAll('p')
# for p_content in p_contents:
# for s in p_content.stripped_strings:
# content+=s
policy_success_num+=1
gongbao_title = gongbao_a['title']
info.append(gongbao_title)
info.append(str(div_contents))
info.append(get_person)
info.append('1')
#print(gongbao_a['title'])
#print(content)
#print(gongbao_as)
except Exception as err:
print('scrapy fail in option2')
policy_fail_num+=1
except Exception as err:
print('scrapy fail in first level')
def main(i):
get_one_page(i)
def post_info(url, info):
data = {"province":'',"sitename":'',"url":'',"url_md5":'',"title":'',"content":'',"get_person":'',"status":''}
header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36'
}
for one_info ,one_key in zip(info,data.keys()):
data[one_key] = one_info
print(data)
push_data = {
'table': 'ipolicy',
'data': str(data),
'override':0
}
result = requests.post(url, headers=header, data=push_data)
print(result.text)
if __name__ == '__main__':
get_one_page()
| [
"570098093@qq.com"
] | 570098093@qq.com |
b8db97db94cf914740b91f7d63f34a7c5b80a4d4 | 4c387669f624ae01342c1b69c0184e3ef336d102 | /club/club/Apps/Eventos/urls.py | 49476536ff3a35e87ddfcd9d9958cc1e4898b6cb | [
"Unlicense"
] | permissive | yorlysoro/club2 | 3e55fc4d1f856ed79b59969aa6594eec45ef8989 | 6a34009760406947a3640e30b023e17b3301e2b9 | refs/heads/master | 2022-11-17T20:05:24.888489 | 2020-07-23T19:50:57 | 2020-07-23T19:50:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 363 | py | from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from .views import EventosLista, EventoDetalle
app_name = 'Eventos'
urlpatterns = [
url(r'^$', login_required(EventosLista.as_view()), name='Eventos_Lista'),
url(r'^detalle_evento/(?P<pk>[0-9]+)/$', login_required(EventoDetalle.as_view()), name='Evento_Detalle'),
] | [
"yorlysoro@gmail.com"
] | yorlysoro@gmail.com |
8c5c6c4c35f991c7bdd97c028e797a6754d1aa10 | 01c3bd4773651211b83413ca61f11316ade3c346 | /Mission_files/mission_train_easy.py | 2eeade5a6b4ec451739323e06889c75527f68813 | [] | no_license | hiroto-udagawa/malmo-cs229 | b5f14e78bb15a378bfb8e32c90807c437cdb3b47 | 5fe517929a16704b63974dd09ad8bd3974a770a9 | refs/heads/master | 2021-01-13T07:19:25.636487 | 2016-12-25T07:43:51 | 2016-12-25T07:43:51 | 71,596,685 | 2 | 4 | null | 2016-12-17T03:17:22 | 2016-10-21T21:05:25 | TeX | UTF-8 | Python | false | false | 5,794 | py | # ------------------------------------------------------------------------------------------------
# Copyright (c) 2016 Microsoft Corporation
#
# 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.
# ------------------------------------------------------------------------------------------------
# Tutorial sample #2: Run simple mission using raw XML
import MalmoPython
import os
import sys
import time
import json
import random
sys.path.append("functions/.")
from DeepAgent import DeepAgent
from deep_q import DeepLearner
import tensorflow as tf
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # flush print output immediately
# Create default Malmo objects:
agent_host = MalmoPython.AgentHost()
try:
agent_host.parse( sys.argv )
except RuntimeError as e:
print 'ERROR:',e
print agent_host.getUsage()
exit(1)
if agent_host.receivedArgument("help"):
print agent_host.getUsage()
exit(0)
agent_host.setObservationsPolicy(MalmoPython.ObservationsPolicy.LATEST_OBSERVATION_ONLY)
agent_host.setVideoPolicy(MalmoPython.VideoPolicy.LATEST_FRAME_ONLY)
# -- set up the mission -- #
mission_file = './mission_setup.xml'
with open(mission_file, 'r') as f:
print "Loading mission from %s" % mission_file
mission_xml = f.read()
my_mission = MalmoPython.MissionSpec(mission_xml, True)
my_mission_record = MalmoPython.MissionRecordSpec()
deep_learner = DeepLearner()
num_repeats = 5000
kills = 0
t = 0
for i in xrange(num_repeats):
prev_kills = kills
t = deep_learner.t
first = True
deep_learner.agent = DeepAgent()
deep_learner.agent.kills = kills
print
print 'Repeat %d of %d' % ( i+1, num_repeats )
# Attempt to start a mission:
max_retries = 3
for retry in range(max_retries):
try:
agent_host.startMission( my_mission, my_mission_record )
break
except RuntimeError as e:
if retry == max_retries - 1:
print "Error starting mission:",e
exit(1)
else:
time.sleep(2)
# Loop until mission starts:
print "Waiting for the mission to start ",
world_state = agent_host.getWorldState()
while not world_state.has_mission_begun:
sys.stdout.write(".")
time.sleep(0.1)
world_state = agent_host.getWorldState()
for error in world_state.errors:
print "Error:",error.text
print "Mission running ",
#Loop until mission ends:
for i in xrange(-3, -1):
for j in xrange(-3,-1):
agent_host.sendCommand("chat /summon Zombie " + str(i) + " 207 " + str(j) + ' {Equipment:[{},{},{},{},{id:minecraft:stone_button}], HealF:10.0f}')
agent_host.sendCommand("chat /summon Zombie -3 207 -1 {Equipment:[{},{},{},{},{id:minecraft:stone_button}], HealF:10.0f}")
agent_host.sendCommand("chat /gamerule naturalRegeneration false")
agent_host.sendCommand("chat /difficulty 1")
while world_state.is_mission_running:
agent_host.sendCommand("attack 1")
time.sleep(0.02)
if len(world_state.observations) > 0 and len(world_state.video_frames) > 0:
if first == True:
ob = json.loads(world_state.observations[-1].text)
frame = world_state.video_frames[0]
action = deep_learner.initNetwork(frame, ob, False)
agent_host.sendCommand(deep_learner.agent.actions[action])
first = False
else:
ob = json.loads(world_state.observations[-1].text)
frame = world_state.video_frames[0]
prev_action = action
action = deep_learner.trainNetwork(frame, ob, False)
#print action
agent_host.sendCommand(deep_learner.agent.antiActions[prev_action])
agent_host.sendCommand(deep_learner.agent.actions[action])
if "MobsKilled" in ob and ob[u'MobsKilled'] > kills:
agent_host.sendCommand("chat /summon Zombie -1 207 -3 {Equipment:[{},{},{},{},{id:minecraft:stone_button}], HealF:10.0f}")
kills = ob[u'MobsKilled']
world_state = agent_host.getWorldState()
for error in world_state.errors:
print "Error:",error.text
deep_learner.trainNetwork(frame, ob, True)
print "We scored " + str(deep_learner.agent.cum_reward)
print "We Killed " + str(kills - prev_kills)
print "We survived for " + str(deep_learner.t - t)
file = open("rewards.txt", "a")
file.write(str(deep_learner.agent.cum_reward) + " " + str(kills-prev_kills) + " " + str(deep_learner.t - t) + "\n")
file.close()
print
print "Mission ended"
# Mission has ended. | [
"noreply@github.com"
] | hiroto-udagawa.noreply@github.com |
0872144ecf9de9b6bc08e7ffb6507c542d48d6bd | 6e866a8b473d5c920804e6bc4a00e6f61aeb3188 | /Database/flask-sqlalchemy/app.py | 22c2e04041f959f5f1f4dcbe121da9dc3eacf5cb | [
"MIT"
] | permissive | amamov/cs001 | f2f7f81f0aa63e74a41de525bec88b063a7c03d2 | 5753f28e74e2330837d22142cff4713801c77a2d | refs/heads/main | 2023-06-10T22:14:41.716927 | 2021-07-08T14:43:28 | 2021-07-08T14:43:28 | 318,575,774 | 5 | 3 | null | null | null | null | UTF-8 | Python | false | false | 615 | py | from flask import Flask, render_template
from pathlib import Path
from models import db
from models.users import User
app = Flask(__name__)
BASE_DIR = Path(__file__).resolve().parent
DB_PATH = str(BASE_DIR / "db.sqlite")
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + DB_PATH
app.config["SQLALCHEMY_COMMIT_ON_SUBMIT"] = True
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(app)
db.app = app
db.create_all()
@app.route("/")
def hello():
return render_template("index.html")
if __name__ == "__main__":
# print(app.config)
app.run(host="localhost", port=5000, debug=True)
| [
"ysangsuk78@gmail.com"
] | ysangsuk78@gmail.com |
f6b658b1ddac70cd71d916a2ed089c862e530a4e | f8666599b83d34c861651861cc7db5b3c434fc87 | /plotly/validators/scatterpolargl/marker/colorbar/tickformatstop/_templateitemname.py | 3aca0890a4cb67b0ff4f477575d146dfbe41dbf8 | [
"MIT"
] | permissive | mode/plotly.py | 8b66806e88c9f1820d478bab726f0bea81884432 | c5a9ac386a40df2816e6c13264dadf14299401e4 | refs/heads/master | 2022-08-26T00:07:35.376636 | 2018-09-26T19:08:54 | 2018-09-26T19:19:31 | 60,372,968 | 1 | 1 | MIT | 2019-11-13T23:03:22 | 2016-06-03T19:34:55 | Python | UTF-8 | Python | false | false | 545 | py | import _plotly_utils.basevalidators
class TemplateitemnameValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name='templateitemname',
parent_name='scatterpolargl.marker.colorbar.tickformatstop',
**kwargs
):
super(TemplateitemnameValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop('edit_type', 'calc'),
role=kwargs.pop('role', 'info'),
**kwargs
)
| [
"noreply@github.com"
] | mode.noreply@github.com |
488668fe58accdbc9aef13f9ef35a62a25fa4e58 | 20181547b293925b94c1a9f3f592a9c046b9cb80 | /898751/eboek/config.py | d76ff6a3c31dd0f286f0bc215deba623fccfdcc5 | [] | no_license | dbsr/assortmentofsorts | 3e695ae2746ed8c5b4b79a4d2cf7bc16a4a6cf51 | 2d4c51447095fcf15cac103e80cd5c812a6f345d | refs/heads/master | 2016-09-06T13:17:25.895990 | 2013-12-25T23:11:24 | 2013-12-25T23:11:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 392 | py | # -*- coding: utf-8 -*-
# dydrmntion@gmail.com ~ 2013
import os
_here = os.path.join(os.path.dirname(os.path.abspath(__file__)))
# app settings
DB_HOST = '192.168.1.147'
BOOKS_PER_PAGE = 36
# uwsgi/production
AUTH_LOG = os.path.join(_here, '../log/auth.log')
APP_LOG = os.path.join(_here, '../log/app.log')
SECRET_KEY = '#\xffj\xb9\x80\xb5\x92$~\x84Z\xe4\xfb[\xba\xb4\xc1\rp~S\x83t\xe6l'
| [
"dydrmntion@gmail.com"
] | dydrmntion@gmail.com |
97ff7ded305f72dfea3d7387879a7953029a4be9 | ac8f88e24fe765cfe55da4cb6e083200877c3663 | /src/TwitchVideoDownloader/TwitchTools/__init__.py | 5da4e85a804d1b735209bc1f60308b13572e486e | [] | no_license | EraYaN/TwitchToxicity | bca2b3e51c9e94c5d38c0b0199918c8aefcccd6c | 24d0921995d3a92301c650944451de7fc074b114 | refs/heads/master | 2021-03-19T13:27:52.364266 | 2017-07-09T15:59:45 | 2017-07-09T15:59:45 | 91,580,806 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 47 | py | __all__ = ['YouTubeDLWrapper', 'RechatScraper'] | [
"EraYaN@users.noreply.github.com"
] | EraYaN@users.noreply.github.com |
c68a5fe39e9667aa594ea738a5dd976e42cdd58c | 8e4a7a4a0a7bb0a8fae8c77195386ce949075712 | /Professor_Dados/Core/migrations/0001_initial.py | 94636be3c88cdc1a59fe201a251964cd5f5776d1 | [
"MIT"
] | permissive | Francisco-Carlos/Site-Professor | 9ea33802354d732e82a84323a7494b6ce37f30ac | 07f7308f85f5a1dc5b18ed16ec2817052dd67786 | refs/heads/main | 2023-06-27T09:57:40.763636 | 2021-08-03T14:58:31 | 2021-08-03T14:58:31 | 391,096,948 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 887 | py | # Generated by Django 3.2.4 on 2021-06-27 14:01
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='Conteudos',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Nome', models.CharField(max_length=200)),
('Conteudo', models.TextField()),
('Arquivo', models.FileField(blank=True, upload_to='arquivos/%d/%m/%Y')),
('Criador', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| [
"franciscocx124@gmail.com"
] | franciscocx124@gmail.com |
bf825d15878d7b99d77904e32eb9daf305bfa790 | 4eaa1b9b08914e0a2cc9276363e489ccef19d3a2 | /ch3/guest_list.py | 3a09e97b39d325d4f92b191d3cabd2777d74e4f8 | [] | no_license | melihcanyardi/Python-Crash-Course-2e-Part-I | 69b3b5b3f63cdbd7be6fabd6d4f2ddfd9a3434a3 | 0c9b250f512985c04b2c0397f3afaa8bf3a57f17 | refs/heads/main | 2023-03-12T21:43:14.012537 | 2021-03-03T19:23:41 | 2021-03-03T19:23:41 | 344,236,741 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 416 | py | guest_list = ['Ali', 'Ayşe', 'Mehmet', 'Ahmet']
message = f"Hey {guest_list[0]}, would you like to join me for the dinner?"
print(message)
message = f"Hey {guest_list[1]}, would you like to join me for the dinner?"
print(message)
message = f"Hey {guest_list[2]}, would you like to join me for the dinner?"
print(message)
message = f"Hey {guest_list[3]}, would you like to join me for the dinner?"
print(message)
| [
"melihcanyardi@hotmail.com"
] | melihcanyardi@hotmail.com |
6ba7192f09c12fcc1baeb18b4963231d1eca2d1a | 8f6a550153bf5e37a658421d9aba7bb422139fde | /mainapp/backend/src/models/SDM220Model.py | 55a7ee8e63796b8e233534f9c00d2c5cb413d75f | [] | no_license | nguyendinhviet260396/apptruyen | 82df4daee13c4f78163c69d8753384614bb2f9ce | 008aa23406f8fd5fbd412e636069db42e2fb9040 | refs/heads/main | 2023-06-25T21:41:29.159340 | 2021-07-22T16:49:41 | 2021-07-22T16:49:41 | 377,896,690 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,774 | py | # src/models/SPM91Model.py
from datetime import datetime, timedelta
from . import db, bcrypt
from src.db import run, connection
import pandas as pd
class SDM220Model(db.Model):
"""
SPM91 Model
"""
# table name
__tablename__ = 'sdm220table'
id = db.Column(db.Integer, primary_key=True)
device_id = db.Column(db.String(128))
frequency = db.Column(db.Float)
powerfactor = db.Column(db.Float)
voltage = db.Column(db.Float)
current = db.Column(db.Float)
power = db.Column(db.Float)
enegry = db.Column(db.Float)
timestamp = db.Column(db.DateTime)
# class constructor
def __init__(self):
"""
Class constructor
"""
self.device_id = ''
self.frequency = ''
self.powerfactor = ''
self.voltage = ''
self.current = ''
self.power = ''
self.enegry = ''
self.timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def insert(self):
query = """
INSERT INTO sdm220table (device_id, frequency,powerfactor, voltage, current, power, enegry,timestamp)
VALUES (%s, %s, %s, %s, %s, %s, %s,%s)
"""
params = (self.device_id, self.frequency, self.powerfactor, self.voltage,
self.current, self.power, self.enegry, self.timestamp)
return run(query, params)
def delete(self):
query = """
DELETE FROM sdm220table
WHERE id = %s;
"""
params = (self.id)
return run(query, params)
@staticmethod
def getall():
query = """
SELECT enegry,timestamp
FROM sdm220table
"""
return pd.read_sql(query, con=connection)
@staticmethod
def getlast(value):
query = """
SELECT *
FROM sdm220table
WHERE device_id = '%s'
ORDER BY id DESC LIMIT 1
""" % (value)
return pd.read_sql(query, con=connection)
@staticmethod
def getlast5min(from_date, to_date, value):
df_new = pd.DataFrame([])
query = """
SELECT timestamp,power,enegry
FROM sdm220table
WHERE timestamp BETWEEN '%s' AND '%s' AND device_id = '%s'
""" % (from_date, to_date, value)
df = pd.read_sql(query, con=connection)
if len(df) > 0:
df['power'] = (df['power']/1000).round(2)
df['enegry'] = (df['enegry']).round(2)
df = df.groupby(pd.Grouper(key='timestamp',
freq='15min')).first().reset_index()
df['enegry'] = df.enegry - df.enegry.shift()
df = df.fillna(0)
df['timestamp'] = df['timestamp'].astype(str)
df_new = pd.concat([df_new, df])
return df_new
@staticmethod
def getenegrylasthours(from_date, to_date, value):
df_new = pd.DataFrame([])
query = """
SELECT timestamp,enegry
FROM sdm220table
WHERE timestamp BETWEEN '%s' AND '%s' AND device_id = '%s'
""" % (from_date, to_date, value)
df = pd.read_sql(query, con=connection)
if len(df) > 0:
df = df.loc[[0, len(df)-1]]
df['enegry'] = df.enegry - df.enegry.shift()
df['enegry'] = (df['enegry']).round(3)
df = df.fillna(0)
df['timestamp'] = df['timestamp'].astype(str)
df = df.iloc[[1]]
df_new = pd.concat([df_new, df])
df_new = df_new[['timestamp', 'enegry']]
return df_new
@staticmethod
def getenegrybytoday(from_date, to_date, value):
df_new = pd.DataFrame([])
query = """
SELECT timestamp,enegry
FROM sdm220table
WHERE timestamp BETWEEN '%s' AND '%s' AND device_id = '%s'
""" % (from_date, to_date, value)
df = pd.read_sql(query, con=connection)
if len(df) > 0:
df = df.loc[[0, len(df)-1]]
df['enegry'] = df.enegry - df.enegry.shift()
df['enegry'] = (df['enegry']).round(3)
df = df.fillna(0)
df['timestamp'] = df['timestamp'].astype(str)
df = df.iloc[[1]]
df_new = pd.concat([df_new, df])
df_new = df_new[['timestamp', 'enegry']]
return df_new
@staticmethod
def getenegrybyyesterday(from_date, to_date, value):
df_new = pd.DataFrame([])
query = """
SELECT timestamp,enegry
FROM sdm220table
WHERE timestamp BETWEEN '%s' AND '%s' AND device_id = '%s'
""" % (from_date, to_date, value)
df = pd.read_sql(query, con=connection)
if len(df) > 0:
df = df.loc[[0, len(df)-1]]
df['enegry'] = df.enegry - df.enegry.shift()
df['enegry'] = (df['enegry']).round(3)
df = df.fillna(0)
df['timestamp'] = df['timestamp'].astype(str)
df = df.iloc[[1]]
df_new = pd.concat([df_new, df])
df_new = df_new[['timestamp', 'enegry']]
return df_new
@staticmethod
def getenegrybyweek(from_date, to_date, value):
df_new = pd.DataFrame([])
query = """
SELECT timestamp,enegry
FROM sdm220table
WHERE timestamp BETWEEN '%s' AND '%s' AND device_id = '%s'
""" % (from_date, to_date, value)
df = pd.read_sql(query, con=connection)
if len(df) > 0:
df = df.loc[[0, len(df)-1]]
df['enegry'] = df.enegry - df.enegry.shift()
df['enegry'] = (df['enegry']).round(3)
df = df.fillna(0)
df['timestamp'] = df['timestamp'].astype(str)
df = df.iloc[[1]]
df_new = pd.concat([df_new, df])
df_new = df_new[['timestamp', 'enegry']]
return df_new
@staticmethod
def getenegrybymothly(from_date, to_date, value):
df_new = pd.DataFrame([])
query = """
SELECT timestamp,enegry
FROM sdm220table
WHERE timestamp BETWEEN '%s' AND '%s' AND device_id = '%s'
""" % (from_date, to_date, value)
df = pd.read_sql(query, con=connection)
if len(df) > 0:
df = df.loc[[0, len(df)-1]]
df['enegry'] = df.enegry - df.enegry.shift()
df['enegry'] = (df['enegry']).round(3)
df = df.fillna(0)
df['timestamp'] = df['timestamp'].astype(str)
df = df.iloc[[1]]
df_new = pd.concat([df_new, df])
df_new = df_new[['timestamp', 'enegry']]
return df_new
@staticmethod
def getenegrybyyearly(from_date, to_date, value):
df_new = pd.DataFrame([])
query = """
SELECT timestamp,enegry
FROM sdm220table
WHERE timestamp BETWEEN '%s' AND '%s' AND device_id = '%s'
""" % (from_date, to_date, value)
df = pd.read_sql(query, con=connection)
if len(df) > 0:
df = df.loc[[0, len(df)-1]]
df['enegry'] = df.enegry - df.enegry.shift()
df['enegry'] = (df['enegry']).round(3)
df = df.fillna(0)
df['timestamp'] = df['timestamp'].astype(str)
df = df.iloc[[1]]
df_new = pd.concat([df_new, df])
df_new = df_new[['timestamp', 'enegry']]
return df_new
@staticmethod
def getanalytics(from_date, to_date, _type):
df_new = pd.DataFrame([])
query = """
SELECT %s,timestamp
FROM sdm220table
WHERE timestamp BETWEEN '%s' AND '%s'
""" % (_type, from_date, to_date)
df = pd.read_sql(query, con=connection)
if len(df) > 0:
df = df.groupby(pd.Grouper(key='timestamp',
freq='15min')).first().reset_index()
if _type == "enegry":
df['enegry'] = df.enegry - df.enegry.shift()
df = df.fillna(0)
df['timestamp'] = df['timestamp'].astype(str)
df_new = pd.concat([df_new, df])
return df_new
@staticmethod
def history(from_date, to_date):
df_new = pd.DataFrame([])
query = """
SELECT *
FROM sdm220table
WHERE timestamp BETWEEN '%s' AND '%s'
""" % (from_date, to_date)
df = pd.read_sql(query, con=connection)
if len(df) > 0:
df = df.groupby(pd.Grouper(key='timestamp',
freq='15min')).first().reset_index()
df = df.fillna(0)
df['timestamp'] = df['timestamp'].astype(str)
df_new = pd.concat([df_new, df])
return df_new
def __repr(self):
return '<id {}>'.format(self.id)
| [
"vietnguyen940@gmail.com"
] | vietnguyen940@gmail.com |
f2b97e88ccd663d59bcb34028d9bfb9aa2c19a7a | 172187ed5c1c7c779d948e6db522e874700e4b80 | /cmMacList.py | 23fb4e5302f6b72781664b0a196acf811891f3eb | [] | no_license | bigcraig/cmMacList.py | 2f5562dba9cbdc55d3de4115d93b551aea803d5f | c5b15f7e11454576b94bfa9171686c944188f6f8 | refs/heads/master | 2020-12-18T16:33:44.296922 | 2020-03-04T04:51:47 | 2020-03-04T04:51:47 | 235,456,822 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,255 | py | #!/usr/bin/env python
# 2nd Version that takes into account stale mac addresses
# 3rd version , will remmber if dead mac detected on previous poll of cmts
# 4th Version , can handle connection loss without crashing
import pika
import sys
import base64
import zlib
import gzip
import signal
import StringIO
import json
import os.path
import time
import signal
def extract_element_from_json(obj, path):
'''
Extracts an element from a nested dictionary or
a list of nested dictionaries along a specified path.
If the input is a dictionary, a list is returned.
If the input is a list of dictionary, a list of lists is returned.
obj - list or dict - input dictionary or list of dictionaries
path - list - list of strings that form the path to the desired element
'''
def extract(obj, path, ind, arr):
'''
Extracts an element from a nested dictionary
along a specified path and returns a list.
obj - dict - input dictionary
path - list - list of strings that form the JSON path
ind - int - starting index
arr - list - output list
'''
key = path[ind]
if ind + 1 < len(path):
if isinstance(obj, dict):
if key in obj.keys():
extract(obj.get(key), path, ind + 1, arr)
else:
arr.append(None)
elif isinstance(obj, list):
if not obj:
arr.append(None)
else:
for item in obj:
extract(item, path, ind, arr)
else:
arr.append(None)
if ind + 1 == len(path):
if isinstance(obj, list):
if not obj:
arr.append(None)
else:
for item in obj:
arr.append(item.get(key, None))
elif isinstance(obj, dict):
arr.append(obj.get(key, None))
else:
arr.append(None)
return arr
if isinstance(obj, dict):
return extract(obj, path, 0, [])
elif isinstance(obj, list):
outer_arr = []
for item in obj:
outer_arr.append(extract(item, path, 0, []))
return outer_arr
def cmMacDiff(cmts, macArray):
# once a dead mac is detected this method will compare the new mac list
# with the old to determine who died
newBrick = False
newBrickList = []
filename = cmts + '.current'
if os.path.isfile(filename):
previousMacList = [line.rstrip('\n') for line in open(filename)]
set_previousMacList = set(previousMacList)
set_macArray = set(macArray)
diffset = set_previousMacList - set_macArray
listDiffset = list(diffset)
filename = cmts + '.detected'
f = open(filename, 'w')
for item in listDiffset:
f.write("%s\n" % item)
f.close
f = open('detected.bricks', 'a+')
currentMacList = [line.rstrip('\n') for line in f]
f.close()
for item in listDiffset:
if not item in currentMacList:
# new brick has been detectedcat lat
newBrick = True
newBrickList.append(item)
if newBrick:
f = open('detected.bricks', 'a+')
g = open('latestDeadModem.txt', 'w')
for item in newBrickList:
f.write("%s\n" % item)
g.write(" the following address is a candidate for dead modem: %s\n" % item)
f.close()
g.close()
print('send email')
# t3.filesender --to 'rakeshashok;travismohr;vince@gmail.com' --cc brettnewman --attach latestDeadModem.txt --subject 'Notification DEAD modem'
return
# write the file if dead modem detect but no current list exists
with open(filename, 'w') as f:
for item in macArray:
f.write("%s\n" % item)
f.close
return
print(' [*] Waiting for NXT messages. To exit press CTRL+C')
def callback(ch, method, properties, body):
decoded_data=gzip.GzipFile(fileobj=StringIO.StringIO(body)).read()
# print(" Routing Key %r" % (method.routing_key))
routerKeyList = str.split(method.routing_key,'.')
cmtsName = routerKeyList[1]
filename = cmtsName +'.current'
parsed = json.loads(decoded_data)
for key, value in dict.items(parsed):
# print key, value
if key == "data":
macData = {"data":value}
# print extract_element_from_json(macData,["data","macAddr"])
macArray = extract_element_from_json(macData,["data","macAddr"])
statusArray = extract_element_from_json(macData,["data","status"])
# Mark offline modems
for i in range(0,len(macArray)):
if statusArray[i] == 1:
macArray[i] = 'OFFLINE'
if deadMac in macArray:
#check if cmts already in badcmts list
if cmtsName in deadCmtsList:
print ("dead mac already detected in cmts")
return
print("DEAD mac found in cmts : ",cmtsName)
deadCmtsList.append(cmtsName)
cmMacDiff(cmtsName,macArray)
return
if cmtsName in deadCmtsList:
deadCmtsList.remove(cmtsName)
print("dead mac in cmts reset detected")
with open(filename,'w') as f:
for item in macArray:
if item != 'OFFLINE':
f.write("%s\n" % item)
f.close
def signal_handler(signal, frame):
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
credentials = pika.PlainCredentials('craig', 'craig')
parameters=pika.ConnectionParameters('10.238.131.199',
5672,
'arrisSales',
credentials)
deadMac ='002040DEAD01'
#deadMac ='7823AEA32D29'
deadCmtsList = []
while True:
try:
connection = pika.BlockingConnection(parameters)
channel = connection.channel()
channel.exchange_declare(exchange='tenant-out',
exchange_type='topic',
durable=True )
result = channel.queue_declare('DEAD_DETECT',auto_delete=True)
queue_name = result.method.queue
binding_keys = sys.argv[1:]
if not binding_keys:
sys.stderr.write("Usage: %s [binding_key]\n" % sys.argv[0])
sys.exit(1)
for binding_key in binding_keys:
channel.queue_bind(exchange='tenant-out',
queue=queue_name,
routing_key=binding_key)
# print json.dumps(parsed, indent=4, sort_keys=True)
# print (" " )
channel.basic_consume(callback,
queue=queue_name,
no_ack=True)
channel.start_consuming()
except pika.exceptions.ConnectionClosed:
print ('lost rabbit connection, attempting reconnect')
time.sleep(1)
| [
"craigwoollett@outlook.com"
] | craigwoollett@outlook.com |
9fa19c1c612185b344cf0f7e8ea8b4e7e753e7ee | 96b35ca4930ea56b931bddcb4038722bcb8ca9b9 | /misc/fly/oracle.py | 143e1b2bdd17404d52770dd548d2284e6682e237 | [] | no_license | gpapadop79/gsakkis-utils | 6267b67394f82341e0f5bcfe42253cf9baf108ab | 7e597d06de055a634b4674d546334230c825db92 | refs/heads/master | 2021-01-10T10:52:27.314501 | 2006-11-26T19:36:55 | 2006-11-26T19:36:55 | 49,063,671 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 691 | py | """Use to verify the results generated by your solution.
My solution is safely hidden on a server so you can't peek :-)
The bad part is that you need internet access to use it.
"""
if 0:
from fly_oracle import fly
else:
import xmlrpclib
s = xmlrpclib.Server('http://www.sweetapp.com/cgi-bin/pycontest/fly_oracle.py')
def fly(from_, to, schedule):
# Only strings can be XML-RPC dictionary keys, so flatten
# dictionary into a list of key, value tuples
s2 = [day.items() for day in schedule]
try:
return s.fly(from_, to, s2)
except xmlrpclib.Fault, f:
raise ValueError(f.faultString)
| [
"george.sakkis@9e0c86ed-a01c-0410-97cc-1de4ee9595b8"
] | george.sakkis@9e0c86ed-a01c-0410-97cc-1de4ee9595b8 |
627cbd538ee44cf1cc2e0462f49f4d218374670a | 33d566cb4e0b4890eac2d5f30075f34d7319071c | /lab1python/2photos1.py | 739cffdb2824125073b9e091c6594a62fd8236a6 | [] | no_license | Nikita-Osipov/computational-geometry | fa69993722a82972862e6de9f2cb344856577b13 | 695679776cf0ebacf9078486be62802d8cbca8e9 | refs/heads/master | 2021-04-01T14:34:01.016297 | 2020-04-21T17:47:43 | 2020-04-21T17:47:43 | 248,193,773 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,510 | py | import random, math
from PIL import Image, ImageDraw #Подключим необходимые библиотеки
image = Image.open("park.jpg") #Открываем изображение
draw = ImageDraw.Draw(image) #Создаем инструмент для рисования
width = image.size[0] #Определяем ширину
height = image.size[1] #Определяем высоту
pix = image.load() #Выгружаем значения пикселей
image2 = Image.open("winter.jpg") #Открываем изображение
draw2 = ImageDraw.Draw(image2) #Создаем инструмент для рисования
width2 = image2.size[0] #Определяем ширину
height2 = image2.size[1] #Определяем высоту
pix2 = image2.load() #Выгружаем значения пикселей
w = width // 3
for x in range(width):
for y in range(height):
if x <= w:
a = pix[x, y][0]
b = pix[x, y][1]
c = pix[x, y][2]
draw.point((x, y), (a,b,c))
elif x <= 2*w:
q = (x - w) / w
a = round(pix[x, y][0]*(1-q) + pix2[x,y][0]*q)
b = round(pix[x, y][1]*(1-q) + pix2[x,y][1]*q)
c = round(pix[x, y][2]*(1-q) + pix2[x,y][2]*q)
draw.point((x, y), (a,b,c))
else:
a = pix2[x, y][0]
b = pix2[x, y][1]
c = pix2[x, y][2]
draw.point((x, y), (a,b,c))
image.show()
del draw
| [
"nikitaovspb@gmail.com"
] | nikitaovspb@gmail.com |
66ffc4421381f5d47cefa6e5c70f766c7dc2c0d7 | cd3415d18220103e9ac952f9d587011f3de42966 | /registrationmod/forms.py | 1c20cd8d6b29595b714a190d4b891e495c18ff6c | [] | no_license | AshwathyVijayan/hospital_app | 7509894352138315bc29c80a2af6fa0eb6befe8b | 81ba70b8ec1d4cf69eb435cf195afae910d8369e | refs/heads/master | 2021-08-14T18:58:42.704423 | 2017-11-16T13:57:59 | 2017-11-16T13:57:59 | 110,628,564 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 248 | py |
from django.contrib.auth.models import User
from django import forms
class UserForms(forms.ModelForm):
password=forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields= ['username','email','password']
| [
"aswathyvijayan1994@gmail.com"
] | aswathyvijayan1994@gmail.com |
f93d84eef993d1eb17829fdaba48d09c0e06ff04 | d6793dc4d493c137922c68e8b68cb9f714675eff | /w6_01.py | abadf503604b18780e826f8c90bc952b78813b61 | [] | no_license | tibetsam/learning | 16d95ee76131600afcd1abcb0fc1b786269502b8 | d4728c85a5eb133cb53144f28e7593673a8bcd3f | refs/heads/master | 2022-05-03T14:00:43.571054 | 2022-04-04T06:40:26 | 2022-04-04T06:40:26 | 73,468,663 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 359 | py | import json
import urllib
url=raw_input('Enter location:')
html=urllib.urlopen(url)
print 'Retrieving',url
jcontent=html.read()
datas=json.loads(jcontent)
chars=len(jcontent)
counts=len(datas['comments'])
total=0
for data in datas['comments']:
total=data['count']+total
print 'Retrived %s characters' % chars
print 'Count:',counts
print 'Sum',total
| [
"tibetsam@gmail.com"
] | tibetsam@gmail.com |
50cfad0de6624ac6ec7de8cebe2f29fd33c6f865 | e16c4a24c3bf0ea0db23935c645381c59670b029 | /experiments/python/vibrationdata_gui_python_4_6_15/vb_Doppler_shift_gui.py | 20d16aad1869cdac3201b0894d9db51356dd5069 | [] | no_license | ceramicspeed/vibrationanalysis | 6b00efa39eb4430e596235b4302f2803606c8d8d | 248500f40e4aed886eb2732f86654c0f138c8e93 | refs/heads/master | 2021-01-25T05:56:10.450358 | 2017-04-05T15:44:32 | 2017-04-05T15:44:32 | 80,701,922 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 14,019 | py | ###########################################################################
# program: vb_Doppler_shift_gui.py
# author: Tom Irvine
# version: 1.0
# date: May 23, 2014
#
###############################################################################
from __future__ import print_function
import sys
if sys.version_info[0] == 2:
print ("Python 2.x")
import Tkinter as tk
from tkFileDialog import asksaveasfilename
import tkMessageBox
if sys.version_info[0] == 3:
print ("Python 3.x")
import tkinter as tk
from tkinter.filedialog import asksaveasfilename
import tkinter.messagebox as tkMessageBox
###############################################################################
class vb_Doppler_shift:
def __init__(self,parent):
self.master=parent # store the parent
top = tk.Frame(parent) # frame for all class widgets
top.pack(side='top') # pack frame in parent's window
self.master.minsize(550,550)
self.master.geometry("650x550")
self.master.title("vb_Doppler_shift_gui.py ver 1.0 by Tom Irvine")
crow=0
self.hwtext1=tk.Label(top,text='Select Velocity Unit')
self.hwtext1.grid(row=crow, column=0, padx=4,pady=7)
self.speed_sound_text=tk.StringVar()
self.speed_sound_text.set('Speed of Sound (ft/sec)')
self.hwtext2=tk.Label(top,textvariable=self.speed_sound_text)
self.hwtext2.grid(row=crow, column=1, columnspan=1, padx=4, pady=7,sticky=tk.S)
crow=crow+1
self.Lb1 = tk.Listbox(top,height=4,width=28,exportselection=0)
self.Lb1.insert(1, "ft/sec")
self.Lb1.insert(2, "mph")
self.Lb1.insert(3, "m/sec")
self.Lb1.insert(4, "km/hr")
self.Lb1.grid(row=crow, column=0, columnspan=1, padx=10, pady=4,sticky=tk.N)
self.Lb1.select_set(0)
self.Lb1.bind('<<ListboxSelect>>',self.velocity_unit_option)
self.speed_soundr=tk.StringVar()
self.speed_soundr.set('1120')
self.speed_sound_entry=tk.Entry(top, width = 8,textvariable=self.speed_soundr)
self.speed_sound_entry.grid(row=crow, column=1,padx=5, pady=4,sticky=tk.N)
crow=crow+1
self.hwtext3=tk.Label(top,text='Calculate')
self.hwtext3.grid(row=crow, column=0, padx=4,pady=7)
self.results_text=tk.StringVar()
self.results_text.set(' ')
self.hwtext5=tk.Label(top,textvariable=self.results_text)
self.hwtext5.grid(row=crow, column=2, columnspan=2, padx=4, pady=7,sticky=tk.S)
crow=crow+1
self.Lb2 = tk.Listbox(top,height=4,width=28,exportselection=0)
self.Lb2.insert(1, "Apparent Frequency")
self.Lb2.insert(2, "Source Frequency")
self.Lb2.insert(3, "Source Velocity")
self.Lb2.insert(4, "Receiver Velocity")
self.Lb2.grid(row=crow, column=0, columnspan=1, padx=10, pady=2,sticky=tk.N)
self.Lb2.select_set(0)
self.Lb2.bind('<<ListboxSelect>>',self.calculate_option)
self.resultr=tk.StringVar()
self.resultr.set('')
self.result_entry=tk.Entry(top, width = 14,textvariable=self.resultr)
self.result_entry.grid(row=crow, column=2,padx=5, pady=2,sticky=tk.N)
self.result_entry.configure(state='readonly')
crow=crow+1
self.source_frequency_text=tk.StringVar()
self.source_frequency_text.set(' ')
self.hwtext11=tk.Label(top,textvariable=self.source_frequency_text)
self.hwtext11.grid(row=crow, column=0, columnspan=1, padx=4, pady=7,sticky=tk.S)
self.apparent_frequency_text=tk.StringVar()
self.apparent_frequency_text.set(' ')
self.hwtext10=tk.Label(top,textvariable=self.apparent_frequency_text)
self.hwtext10.grid(row=crow, column=1, columnspan=1, padx=4, pady=7,sticky=tk.S)
self.button_go = tk.Button(top, text="Calculate",command=self.analysis_go)
self.button_go.config( height = 2, width = 15 )
self.button_go.grid(row=crow, column=2,columnspan=1,padx=12,pady=10)
crow=crow+1
self.source_frequencyr=tk.StringVar()
self.source_frequency=tk.Entry(top, width = 8,textvariable=self.source_frequencyr)
self.source_frequency.grid(row=crow, column=0,padx=5, pady=4,sticky=tk.N)
self.apparent_frequencyr=tk.StringVar()
self.apparent_frequency=tk.Entry(top, width = 8,textvariable=self.apparent_frequencyr)
self.apparent_frequency.grid(row=crow, column=1,padx=5, pady=4,sticky=tk.N)
root=self.master
self.button_quit=tk.Button(top, text="Quit", command=lambda root=root:quit(root))
self.button_quit.config( height = 2, width = 15 )
self.button_quit.grid(row=crow, column=2, padx=12,pady=10)
crow=crow+1
self.source_velocity_text=tk.StringVar()
self.source_velocity_text.set(' ')
self.hwtext14=tk.Label(top,textvariable=self.source_velocity_text)
self.hwtext14.grid(row=crow, column=0, columnspan=1, padx=4, pady=7,sticky=tk.S)
self.receiver_velocity_text=tk.StringVar()
self.receiver_velocity_text.set(' ')
self.hwtext15=tk.Label(top,textvariable=self.receiver_velocity_text)
self.hwtext15.grid(row=crow, column=1, columnspan=1, padx=4, pady=7,sticky=tk.S)
crow=crow+1
self.source_velocityr=tk.StringVar()
self.source_velocity=tk.Entry(top, width = 8,textvariable=self.source_velocityr)
self.source_velocity.grid(row=crow, column=0,padx=5, pady=4,sticky=tk.N)
self.receiver_velocityr=tk.StringVar()
self.receiver_velocity=tk.Entry(top, width = 8,textvariable=self.receiver_velocityr)
self.receiver_velocity.grid(row=crow, column=1,padx=5, pady=4,sticky=tk.N)
self.source_frequency.bind("<Key>", self.callback_clear)
self.apparent_frequency.bind("<Key>", self.callback_clear)
self.source_velocity.bind("<Key>", self.callback_clear)
self.receiver_velocity.bind("<Key>", self.callback_clear)
self.change_entry(self)
###############################################################################
def callback_clear(self,event):
self.results_text.set(' ')
self.resultr.set(' ')
def calculate_option(self,val):
# sender=val.widget
self.change_entry(self)
@classmethod
def change_entry(cls,self):
n1=int(self.Lb1.curselection()[0])
n2=int(self.Lb2.curselection()[0])
self.source_frequency_text.set('Source Frequency (Hz)')
self.apparent_frequency_text.set('Apparent Frequency (Hz)')
self.source_frequency.configure(state='normal')
self.apparent_frequency.configure(state='normal')
self.source_velocity.configure(state='normal')
self.receiver_velocity.configure(state='normal')
if(n1==0):
self.source_velocity_text.set('Source Velocity (ft/sec)')
self.receiver_velocity_text.set('Receiver Velocity (ft/sec)')
if(n1==1):
self.source_velocity_text.set('Source Velocity (mph)')
self.receiver_velocity_text.set('Receiver Velocity (mph)')
if(n1==2):
self.source_velocity_text.set('Source Velocity (m/sec)')
self.receiver_velocity_text.set('Receiver Velocity (m/sec)')
if(n1==3):
self.source_velocity_text.set('Source Velocity (km/hr)')
self.receiver_velocity_text.set('Receiver Velocity (km/hr)')
if(n2==0): # apparent frequency
self.apparent_frequency_text.set(' ')
self.apparent_frequency.configure(state='disabled')
if(n2==1): # source frequency
self.source_frequency_text.set(' ')
self.source_frequency.configure(state='disabled')
if(n2==2): # source velocity
self.source_velocity_text.set(' ')
self.source_velocity.configure(state='disabled')
if(n2==3): # receiver velocity
self.receiver_velocity_text.set(' ')
self.receiver_velocity.configure(state='disabled')
self.results_text.set(' ')
self.resultr.set(' ')
###############################################################################
def velocity_unit_option(self,val):
sender=val.widget
n= int(sender.curselection()[0])
if(n==0):
self.speed_sound_text.set('Speed of Sound (ft/sec)')
self.speed_soundr.set('1120')
if(n==1):
self.speed_sound_text.set('Speed of Sound (mph)')
self.speed_soundr.set('767')
if(n==2):
self.speed_sound_text.set('Speed of Sound (m/sec)')
self.speed_soundr.set('343')
if(n==3):
self.speed_sound_text.set('Speed of Sound (km/hr)')
self.speed_soundr.set('1234')
self.change_entry(self)
def analysis_go(self):
c=float(self.speed_soundr.get())
n1=int(self.Lb1.curselection()[0])
n2=int(self.Lb2.curselection()[0])
if(n2==0): # apparent frequency
self.results_text.set('Results: Apparent Frequency (Hz)')
fs=float(self.source_frequencyr.get())
u=float(self.source_velocityr.get())
v=float(self.receiver_velocityr.get())
if(abs(u)>=c):
tkMessageBox.showwarning("warning", "Source velocity must be less than speed of sound.",parent=self.button_go)
if(abs(v)>=c):
tkMessageBox.showwarning("warning", "Receiver velocity must be less than speed of sound.",parent=self.button_go)
if(abs(u)<c and abs(v)<c):
fa=fs*((c-v)/(c-u))
buf1 = "%8.4g" %fa
self.resultr.set(buf1)
if(n2==1): # source frequency
self.results_text.set('Results: Source Frequency (Hz)')
fa=float(self.apparent_frequencyr.get())
u=float(self.source_velocityr.get())
v=float(self.receiver_velocityr.get())
if(abs(u)>=c):
tkMessageBox.showwarning("warning", "Source velocity must be less than speed of sound.",parent=self.button_go)
if(abs(v)>=c):
tkMessageBox.showwarning("warning", "Receiver velocity must be less than speed of sound.",parent=self.button_go)
if(abs(u)<c and abs(v)<c):
fs=fa/((c-v)/(c-u))
buf1 = "%8.4g" %fs
self.resultr.set(buf1)
if(n2==2): # source velocity
if(n1==0):
self.results_text.set('Results: Source Velocity (ft/sec)')
if(n1==1):
self.results_text.set('Results: Source Velocity (mph)')
if(n1==2):
self.results_text.set('Results: Source Velocity (m/sec)')
if(n1==3):
self.results_text.set('Results: Source Velocity (km/sec)')
fs=float(self.source_frequencyr.get())
fa=float(self.apparent_frequencyr.get())
v=float(self.receiver_velocityr.get())
if(abs(v)>=c):
tkMessageBox.showwarning("warning", "Receiver velocity must be less than speed of sound.")
else:
u=-((fs/fa)*(c-v))+c
buf1 = "%8.4g" %u
self.resultr.set(buf1)
if(n2==3): # receiver velocity
if(n1==0):
self.results_text.set('Results: Receiver Velocity (ft/sec)')
if(n1==1):
self.results_text.set('Results: Receiver Velocity (mph)')
if(n1==2):
self.results_text.set('Results: Receiver Velocity (m/sec)')
if(n1==3):
self.results_text.set('Results: Receiver Velocity (km/sec)')
fs=float(self.source_frequencyr.get())
fa=float(self.apparent_frequencyr.get())
u=float(self.source_velocityr.get())
if(abs(u)>=c):
tkMessageBox.showwarning("warning", "Source velocity must be less than speed of sound.")
else:
v=-((fa/fs)*(c-u))+c
buf1 = "%8.4g" %v
self.resultr.set(buf1)
def quit(root):
root.destroy() | [
"mortenopprudjakobsen@mortens-MacBook-Pro.local"
] | mortenopprudjakobsen@mortens-MacBook-Pro.local |
4554481aaf3bd232811054dab11bafb6d6f874df | eea0cf1a38e6b03ac460bee2e96597f3eb3cd3ce | /test.py | 44443596bdbeec89936eb21d49bc2e6b18251299 | [] | no_license | Preran08/Synesketc-emotions-from-text | a3825c251c0ec0299d67fd81e743df4ec0600c21 | 198e72e313e0fa3a71364acb57f6e4a98ca481fd | refs/heads/main | 2023-03-20T02:02:08.070299 | 2021-03-22T19:45:59 | 2021-03-22T19:45:59 | 350,460,254 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,236 | py | import nltk
#from xml.dom import minidom
#from xmlfile import checknegation
text = nltk.word_tokenize(input())
x = nltk.pos_tag(text)
print(x)
#negationflag = checknegation(text)
nf = 0
z =["no","not","don't","haven't","weren't","wasn't","didn't","hadn't","shouldn't","wouldn't","won't","dont","havent","werent","wasnt","didnt", "hadnt","shouldnt","wouldnt","wont"]
for i in text:
if i in z:
nf = 1
count = 0
words = []
for i in x:
if i[1] == "JJ" or i[1] == "VBG" or i[1] == "VBN" or i[1] == "VBP" or i[1] == "NN":
count = count + 1
words.append(i[0])
print(words)
f_ptr = open("/home/preran/Documents/Synesketch/bin/data/lex/synesketch_lexicon.txt", "r")
details = f_ptr.readlines()
scorelist = []
wordlist = []
for i in details:
v = i.split()
wordlist.append(v[0])
list1 = []
list1.append(v[2])
list1.append(v[3])
list1.append(v[4])
list1.append(v[5])
list1.append(v[6])
list1.append(v[7])
scorelist.append(list1)
hcount = 0
scount = 0
acount = 0
fcount = 0
dcount = 0
sucount = 0
list2 = [0]*6
list4 = [0]*6
for i in words:
if i in wordlist:
y = wordlist.index(i)
val = max(scorelist[y])
#w = scorelist[y].index(val)
q = scorelist[y].index(val)
if q == 0:
hcount = hcount + 1
list2[0] = hcount
list4[0] = float(val)
elif q == 1:
scount = scount + 1
list2[1] = scount
list4[1] = float(val)
elif q == 2:
acount = acount + 1
list2[2] = acount
list4[2] = float(val)
elif q == 3:
fcount = fcount + 1
list2[3] = fcount
list4[3] = float(val)
elif q == 4:
dcount = dcount + 1
list2[4] = dcount
list4[4] = float(val)
else:
sucount = sucount + 1
list2[6] = sucount
list4[6] = float(val)
#list2 = [hcount, scount, acount, fcount, dcount, sucount]
list3 = ['happy', 'sad', 'angry', 'fear', 'disgust', 'surprise']
a = max(list2)
c = max(list4)
b = list2.index(a)
if(list4.index(max(list4))==(b)):
if nf == 1:
if list3[b] == 'happy':
print("sad")
elif list3[b] == 'sad':
print("happy")
elif list3[b] == 'fear':
print("confident")
elif list3[b] == 'angry':
print("surprise")
elif list3[b] == 'surprise':
print("happy")
else:
print(list3[b])
#print(list3[b])
#print(scorelist)
#print(count)
#print(x)
| [
"noreply@github.com"
] | Preran08.noreply@github.com |
4696d4803fcbd9b7f1fa002caeed6d15ed478d7e | 4d0f3e2d7455f80caea978e4e70621d50c6c7561 | /Threading/Lock.py | efce0601f22fa1de07581c3637eba0dc6384a431 | [] | no_license | mhdr/PythonSamples | 66940ee2353872d2947c459e3865be42140329c6 | 1a9dccc05962033ea02b081a39cd67c1e7b29d0c | refs/heads/master | 2020-04-14T01:10:13.033940 | 2016-05-28T15:33:52 | 2016-05-28T15:33:52 | 30,691,539 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 164 | py | import threading
from threading import Lock
def print_multi():
lock=Lock()
lock.acquire()
print("Hello World")
lock.release()
print_multi() | [
"ramzani.mahmood@gmail.com"
] | ramzani.mahmood@gmail.com |
41145f929c555d6dbce800f1fcee289dcffe886c | 59a0e503a34e7dae00e49ed52810a5e34263f813 | /Q1.py | 10c8521402b3fbf571d40e9339688da95edbbd76 | [] | no_license | Jackson-coder/MCM-fungi | 97c3309983ad25feaf95e2a45f4b1219e1343b06 | e2a766e968d40335c0fb687a63b59e1b70399bc8 | refs/heads/master | 2023-02-27T18:00:07.196919 | 2021-02-08T09:37:52 | 2021-02-08T09:37:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,087 | py | import numpy as np
import matplotlib.pyplot as plt
import math
class fungis:
def __init__(self, extension_max_g, Tmax, Tmin, T_real, Wmax, Wmin, W_real, weight_b, weight_c, number, Neq, moisture_tolerance, decomposition_rate, competition, symbiosis_b, symbiosis_index,parasitic_c,parasitic_index,be_parasitic_index):
self.extension_max_g = extension_max_g
self.Tmax = Tmax
self.Tmin = Tmin
self.T_real = T_real
self.Wmax = Wmax
self.Wmin = Wmin
self.W_real = W_real
self.weight_b = weight_b
self.weight_c = weight_c
self.number = number
self.Neq = Neq
self.moisture_tolerance = moisture_tolerance
self.decomposition_rate = decomposition_rate
self.t = 0
self.a = 0
self.number_log = []
self.dnumber_log = []
self.competition = competition
self.symbiosis_b = symbiosis_b
self.symbiosis_index = symbiosis_index
self.parasitic_c=parasitic_c
self.parasitic_index=parasitic_index
self.be_parasitic_index=be_parasitic_index
def extension_real(self):
Tmid = (self.Tmin+self.Tmax)/2
Wmid = (self.Wmin+self.Wmax)/2
delta_T = 2*abs(self.T_real-Tmid)/(self.Tmax-self.Tmin)
delta_W = 2*abs(self.W_real-Wmid)/(self.Wmax-self.Wmin)
# if delta_T > 1:
# delta_T = 1-1e-03
if delta_W > 1.5:
# delta_W = 1-1e-03
delta_W = 1.5
extension_gi = self.extension_max_g * \
(self.weight_b*(1-delta_T) +
self.weight_c*(np.log10(1+(1-delta_W))))
# print(self.Neq,self.extension_max_g,delta_T,self.Tmax-self.Tmin,(1-delta_T), (1-delta_W), extension_gi)
return extension_gi
def update_real_number(fungis, m2, threshold):
N = 0
Q = 0
d_num = 0
extension_gi = []
total_gi = 0
total_number = 0
for fungi in fungis:
gi = fungi.extension_real()
extension_gi.append(gi)
total_gi += gi
total_number += fungi.number
for i in range(len(fungis)):
# print(fungis[i].number / total_number)
if fungis[i].Neq == 800000:
if fungis[i].number-1 <= 0:
fungis[i].number = 2
fungis[i].Neq = m2 # * extension_gi[i] / total_gi # + 1000
# print(m2, fungis[i].Neq, delta, extension_gi[i] -
# delta, total_gi - delta * len(fungis))
fungis[i].a = math.log(fungis[i].Neq/fungis[i].number-1)
else:
fungis[i].Neq = m2 # * extension_gi[i] / total_gi
sigma = 0
for z in range(len(fungis)):
if z != i:
sigma += fungis[z].competition / \
fungis[i].competition*fungis[z].number
# 普通模式
# fungis[i].number = fungis[i].Neq / \
# (1 + math.exp(fungis[i].a - extension_gi[i] * fungis[i].t))
# if fungis[i].number < 0:
# fungis[i].number = 0
# d_number = fungis[i].Neq*extension_gi[i] * \
# math.exp(fungis[i].a-extension_gi[i] * fungis[i].t) / \
# (1+math.exp(fungis[i].a-extension_gi[i] * fungis[i].t))**2
# 竞争模式
fungis[i].number = (fungis[i].Neq-sigma) / \
(1 + math.exp(fungis[i].a - (1-sigma/fungis[i].Neq)*extension_gi[i] * fungis[i].t)) #竞争模式
if fungis[i].number < 0:
fungis[i].number = 0
d_number = fungis[i].Neq * extension_gi[i] * (1-sigma/fungis[i].Neq)*fungis[i].number
#竞争模式 + 共生模式
# gamma = 0
# if fungis[i].symbiosis_index != 0:
# gamma = fungis[i].symbiosis_b*fungis[int(fungis[i].symbiosis_index)].number
# # print('gamma',sigma,gamma)
# fungis[i].number = (fungis[i].Neq-sigma+gamma) / \
# (1 + math.exp(fungis[i].a - (1-sigma /
# fungis[i].Neq+gamma/fungis[i].Neq)*extension_gi[i] * fungis[i].t))
# if fungis[i].number < 0:
# fungis[i].number = 0
# d_number = extension_gi[i] * (1-sigma/fungis[i].Neq+gamma/fungis[i].Neq)*fungis[i].number
#竞争模式 + 共生模式 + 寄生模式
# gamma = 0
# belta = 0
# alpha = 0
# d_number = 0
# if fungis[i].symbiosis_index != 0:
# gamma = fungis[i].symbiosis_b*fungis[int(fungis[i].symbiosis_index)].number
# if fungis[i].parasitic_index != 0:
# belta = 1
# if fungis[i].be_parasitic_index != 0:
# alpha = 1
# if fungis[i].number < 0:
# fungis[i].number = 0
# if alpha == 1:
# d_number = extension_gi[i] * (1-sigma/fungis[i].Neq-gamma/fungis[i].Neq)*fungis[i].number
# fungis[i].number = (fungis[i].Neq-sigma-gamma) / (1 + math.exp(fungis[i].a - (1-sigma /fungis[i].Neq-gamma/fungis[i].Neq)*extension_gi[i] * fungis[i].t))
# if belta == 1:
# fungis[i].number = fungis[i].Neq*(-fungis[i].parasitic_c/extension_gi[i]+gamma-sigma) / \
# (1 + math.exp(fungis[i].a - (-fungis[i].parasitic_c+extension_gi[i]*(gamma-sigma))))
# d_number = (-fungis[i].parasitic_c+extension_gi[i]*(gamma-sigma))*fungis[i].number
fungis[i].t = fungis[i].t + 1
# print(fungis[i].Neq, extension_gi[i],m2,
# fungis[i].a, d_number, fungis[i].number)
N += fungis[i].number
Q += fungis[i].moisture_tolerance * \
fungis[i].decomposition_rate*fungis[i].number
d_num += d_number
fungis[i].number_log.append(fungis[i].number)
fungis[i].dnumber_log.append(d_number)
# d_num /= len(fungis)
Q = Q/1000000
# print('m2, Q',m2, Q)
m2 = m2 * (1 - Q)
if m2 < 0:
print(m2, Q)
plt.plot()
plt.show()
flag = 0
if m2 < threshold and threshold > 50000:
flag = 1
threshold /= 2
return N, Q, m2, d_num, flag, threshold
# 总菌数
| [
"jlxxlyh@163.com"
] | jlxxlyh@163.com |
a7fd9cf7d553612b3ea39de24be44a85105c8729 | 49f4392282a55743b092a6d349b064539f2b41f5 | /NumberGame.py | 50ef1c80d250600180970f5decd7d0f305f428b8 | [] | no_license | nergizozgeerdagi/PythonForBasicLevel | c394791a00bfbd09c58b284358abeb03ec49b76b | ddb1dd9b886a2f7621640bb3e2f3838d9980a0be | refs/heads/main | 2023-06-21T09:56:11.677606 | 2021-08-02T11:55:52 | 2021-08-02T11:55:52 | 384,756,997 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 498 | py | import random
bilgisayarinTuttuguSayi=random.randint(1,100)
#print(bilgisayarinTuttuguSayi)
denemeSayisi=0
while True:
benimTahminEttigimSayi=int(input("Tuttuğum sayıyı tahmin et:"))
denemeSayisi=denemeSayisi+1
if bilgisayarinTuttuguSayi==benimTahminEttigimSayi:
print("Tebrik ederim, {} denemede bildin.".format(denemeSayisi))
break # döngüden çıkar
elif bilgisayarinTuttuguSayi>benimTahminEttigimSayi:
print("Daha büyük dene")
else:
print("Daha küçük dene") | [
"noreply@github.com"
] | nergizozgeerdagi.noreply@github.com |
1fa1aa1716ebc77f09f3e1a49c19263fd617b179 | 4af9dffafe0c112f4ae3c9aebbdea02ffec4ebb6 | /Ejercicios/_8_Clases_objetos/Ejercicio 1.py | 9a268c8c27e5e1ce862fb671c5d22d2966f83308 | [] | no_license | aitorlopez98/iw-ejercicios-python | 4ac8148cbe873af2721f27d24bc46b9bff7c9edf | 0825b45afd6953eecc4ac6f2d76389fb8f4f479f | refs/heads/master | 2021-03-13T06:32:33.743588 | 2020-03-20T20:21:57 | 2020-03-20T20:21:57 | 246,649,060 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,030 | py | class clsCoche:
def __init__(self, matricula, marca):
self.matricula = matricula
self.marca = marca
self.kilometros_recorridos = 0
self.gasolina = 0
def suficiente(self, gasolina, kilometros):
max_km = gasolina / 0.1
if kilometros <= max_km:
return True
return False
def avanzar(self, kilometros):
if self.suficiente(self.gasolina, kilometros):
self.gasolina -= (kilometros*0.1)
self.kilometros_recorridos += kilometros
else:
print("Hace falta gasolina")
def repostar(self, gasolina):
self.gasolina += gasolina
c1 = clsCoche("0908IKJ", "Tesla")
c1.repostar(100)
print(f"KM: {c1.kilometros_recorridos} -- Gasolina: {c1.gasolina}")
c1.avanzar(150)
print(f"KM: {c1.kilometros_recorridos} -- Gasolina: {c1.gasolina}")
c1.avanzar(600)
print(f"KM: {c1.kilometros_recorridos} -- Gasolina: {c1.gasolina}")
c1.avanzar(200)
print(f"KM: {c1.kilometros_recorridos} -- Gasolina: {c1.gasolina}")
| [
"aitorlopez98@opendeusto.es"
] | aitorlopez98@opendeusto.es |
457315c3a43dfe622c2fc59ba1fb549efb6dcbd1 | 227725944927b2311be5243dbc92d770c7061007 | /empresas/migrations/0001_initial.py | 81230f902adc60a47a91a6d41c8d712b984b1b01 | [] | no_license | labcodes/dados_brasil_io | 8286946577248b65d7e1ddb375c4dd8fc208f0d1 | 4f1cc3daa3465b03e927edbc4e845d71281b26a0 | refs/heads/master | 2022-12-10T06:20:51.003603 | 2019-10-29T13:42:51 | 2019-10-29T13:42:51 | 132,934,926 | 7 | 0 | null | 2022-01-21T19:10:46 | 2018-05-10T17:44:50 | Python | UTF-8 | Python | false | false | 3,831 | py | # Generated by Django 2.0.4 on 2018-05-04 17:34
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Empresa',
fields=[
('cnpj', models.CharField(max_length=14, primary_key=True, serialize=False)),
('nome', models.CharField(db_index=True, max_length=255, null=True)),
('unidade_federativa', models.CharField(choices=[('Acre', 'AC'), ('Alagoas', 'AL'), ('Amapá', 'AP'), ('Amazonas', 'AM'), ('Bahia', 'BA'), ('Ceará', 'CE'), ('Distrito Federal', 'DF'), ('Espírito Santo', 'ES'), ('Goiás', 'GO'), ('Maranhão', 'MA'), ('Mato Grosso', 'MT'), ('Mato Grosso do Sul', 'MS'), ('Minas Gerais', 'MG'), ('Paraná', 'PR'), ('Paraíba', 'PB'), ('Pará', 'PA'), ('Pernambuco', 'PE'), ('Piauí', 'PI'), ('Rio Grande do Norte', 'RN'), ('Rio Grande do Sul', 'RS'), ('Rio de Janeiro', 'RJ'), ('Rondônia', 'RO'), ('Roraima', 'RR'), ('Santa Catarina', 'SC'), ('Sergipe', 'SE'), ('São Paulo', 'SP'), ('Tocantins', 'TO')], db_index=True, max_length=2, null=True)),
],
),
migrations.CreateModel(
name='Socio',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nome', models.CharField(db_index=True, max_length=255, null=True)),
('tipo_socio', models.PositiveSmallIntegerField(choices=[(1, 'Pessoa Jurídica'), (2, 'Pessoa Física'), (3, 'Nome Exterior')], db_index=True, null=True)),
('qualificacao_socio', models.PositiveSmallIntegerField(choices=[(5, 'Administrador'), (8, 'Conselheiro de Administração'), (10, 'Diretor'), (16, 'Presidente'), (17, 'Procurador'), (20, 'Sociedade Consorciada'), (21, 'Sociedade Filiada'), (22, 'Sócio'), (23, 'Sócio Capitalista'), (24, 'Sócio Comanditado'), (25, 'Sócio Comanditário'), (26, 'Sócio de Indústria'), (28, 'Sócio-Gerente'), (29, 'Sócio Incapaz ou Relat.Incapaz (exceto menor)'), (30, 'Sócio Menor (Assistido/Representado)'), (31, 'Sócio Ostensivo'), (37, 'Sócio Pessoa Jurídica Domiciliado no Exterior'), (38, 'Sócio Pessoa Física Residente no Exterior'), (47, 'Sócio Pessoa Física Residente no Brasil'), (48, 'Sócio Pessoa Jurídica Domiciliado no Brasil'), (49, 'Sócio-Administrador'), (52, 'Sócio com Capital'), (53, 'Sócio sem Capital'), (54, 'Fundador'), (55, 'Sócio Comanditado Residente no Exterior'), (56, 'Sócio Comanditário Pessoa Física Residente no Exterior'), (57, 'Sócio Comanditário Pessoa Jurídica Domiciliado no Exterior'), (58, 'Sócio Comanditário Incapaz'), (59, 'Produtor Rural'), (63, 'Cotas em Tesouraria'), (65, 'Titular Pessoa Física Residente ou Domiciliado no Brasil'), (66, 'Titular Pessoa Física Residente ou Domiciliado no Exterior'), (67, 'Titular Pessoa Física Incapaz ou Relativamente Incapaz (exceto menor)'), (68, 'Titular Pessoa Física Menor (Assistido/Representado)'), (70, 'Administrador Residente ou Domiciliado no Exterior'), (71, 'Conselheiro de Administração Residente ou Domiciliado no Exterior'), (72, 'Diretor Residente ou Domiciliado no Exterior'), (73, 'Presidente Residente ou Domiciliado no Exterior'), (74, 'Sócio-Administrador Residente ou Domiciliado no Exterior'), (75, 'Fundador Residente ou Domiciliado no Exterior')], null=True)),
('empresa', models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, related_name='socios', to='empresas.Empresa')),
('empresa_origem', models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, related_name='participacao_em_sociedades', to='empresas.Empresa')),
],
),
]
| [
"maribedran@gmail.com"
] | maribedran@gmail.com |
56fe51b6f02f6824930e2f3683d7915a6df1646f | 3d994e469dc7c9dd5aa82fffe3a332691713d5e6 | /build/catkin_tools_prebuild/catkin_generated/pkg.develspace.context.pc.py | 7619f9f8745a64973a1f4a2220a4336ce8ea31c7 | [] | no_license | marikamurphy/pointcloud | d30393e3e0ae5e40760f4711d32e0704f1343a1e | 6e1ee3ca845e3857631872d5c7a6317bce76e944 | refs/heads/master | 2020-08-05T04:39:59.381150 | 2019-12-17T07:35:04 | 2019-12-17T07:35:04 | 212,398,268 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 426 | py | # generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else []
PROJECT_CATKIN_DEPENDS = "".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else []
PROJECT_NAME = "catkin_tools_prebuild"
PROJECT_SPACE_DIR = "/home/bwilab/pointcloud/pointcloud/devel/.private/catkin_tools_prebuild"
PROJECT_VERSION = "0.0.0"
| [
"jsuriadinata@utexas.edu"
] | jsuriadinata@utexas.edu |
33a4677eb54946c298e043f9605e66f5799c718f | dc52ed6d3d4742d46ed9f7d210f341b78968debb | /stringtranslate/admin.py | 154b204d12f42dea1a8e8bc64a3483eea57acf7f | [] | no_license | james-git/stringtranslate | a8b2af00a232f9c9ea57086a2bd2129a9d4588f5 | 6856072dde496430bbc4ef641770ded8ca0710cb | refs/heads/master | 2020-12-24T12:01:01.412537 | 2016-08-11T06:38:53 | 2016-08-11T06:38:53 | 64,995,690 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 305 | py | from django.contrib import admin
from .models import AppSet
from .models import LangCode
from .models import StringKey
from .models import StringTable
# Register your models here.
admin.site.register(AppSet)
admin.site.register(LangCode)
admin.site.register(StringKey)
admin.site.register(StringTable)
| [
"jamesc@ms5.url.com.tw"
] | jamesc@ms5.url.com.tw |
ee7f7beb8cf8be75b2510285ce28ed063262a72b | 4099874b184134618724eb99a1a907dfd86d4ea8 | /nova/tests/compute/no_arie_resource_tracker.py | da7e3d1ffb4726f43772fb2efc8f435bdf117190 | [
"Apache-2.0"
] | permissive | shahar-stratoscale/nova | 809e710e2744ec31ffd351ada692356089ddb4c1 | 5a4581a2e219669c7841a59acf2f42686e319840 | refs/heads/master | 2021-01-16T21:26:37.503025 | 2014-09-18T00:58:59 | 2015-04-14T08:27:08 | 33,251,708 | 0 | 1 | Apache-2.0 | 2023-08-15T09:20:06 | 2015-04-01T14:19:07 | Python | UTF-8 | Python | false | false | 932 | py | # Copyright (c) 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nova.compute import resource_tracker
class NoArieResourceTracker(resource_tracker.ResourceTracker):
"""Version without a DB requirement."""
def __init__(self, *args, **kawrgs):
super(NoArieResourceTracker, self).__init__(*args, **kawrgs)
self.arieMode = False
| [
"shahar@stratoscale.com"
] | shahar@stratoscale.com |
327d4f1ffe0c7df8a02478ed0253666c47150d9b | c860d184fedd0f1c91888b865e60630b017c9d9d | /accounts/models.py | f0c821426f5e040ae90a66bf8554ca84992cf1b8 | [] | no_license | catherinashby/webBase | b5bcd2d3db2474301c52141d575f3a3bcf15eb79 | 6ecead419030e93df771ce4ee398dc971e7a2d37 | refs/heads/master | 2023-02-19T06:33:30.403345 | 2021-07-19T00:30:11 | 2021-07-19T00:30:11 | 144,876,124 | 0 | 1 | null | 2023-02-15T17:56:23 | 2018-08-15T16:18:51 | Python | UTF-8 | Python | false | false | 1,256 | py | from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
email = models.EmailField(
'email address',
unique=True,
blank=True
)
is_active = models.BooleanField(
'active',
default=False,
help_text=(
'Designates whether this user should be treated as active. '
'Unselect this instead of deleting accounts.'
),
)
class UserProfile(models.Model):
class Gender(models.IntegerChoices):
FEMALE = 1, 'Female'
MALE = 2, 'Male'
NONB = 3, 'Non-binary'
DECLINE = 4, 'Decline to state'
user = models.OneToOneField(User, on_delete=models.CASCADE,
primary_key=True)
gender = models.IntegerField(choices=Gender.choices,
default=Gender.DECLINE, blank=True)
location = models.CharField(max_length=100, null=True, blank=True)
website = models.CharField(max_length=100, null=True, blank=True)
company = models.CharField(max_length=100, null=True, blank=True)
about_me = models.TextField(null=True, blank=True)
def __str__(self):
return 'Profile for {}'.format(self.user.get_username())
| [
"catherinashby@gmail.com"
] | catherinashby@gmail.com |
4733bae1eb944dc330c20c4483dd7b1171de45b2 | 99833651e4a6a0bc1221d577d9fc43b8568abedd | /nltk_contrib/hadoop/tf_idf/tf_map.py | 25f49052f7b5472b8a00478c177aac8e3dd514cd | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | nltk/nltk_contrib | 689e2683aa01b120c7473b9a4fc50bc49f014390 | 95d1806e2f4e89e960b76a685b1fba2eaa7d5142 | refs/heads/master | 2023-07-31T13:32:47.358897 | 2022-11-21T18:49:33 | 2022-11-21T18:49:33 | 2,530,774 | 145 | 127 | NOASSERTION | 2022-11-21T18:49:34 | 2011-10-07T05:59:13 | Python | UTF-8 | Python | false | false | 692 | py | from hadooplib.mapper import MapperBase
class TFMapper(MapperBase):
"""
get the filename (one filename per line),
open the file and count the term frequency.
"""
def map(self, key, value):
"""
output (word filename, 1) for every word in files
@param key: None
@param value: filename
"""
filename = value.strip()
if len(filename) == 0:
return
file = open(filename, 'r')
for line in file:
words = line.strip().split()
for word in words:
self.outputcollector.collect(word + " " + filename, 1)
if __name__ == "__main__":
TFMapper().call_map()
| [
"stevenbird1@gmail.com"
] | stevenbird1@gmail.com |
f6880c6ca55d12f0273c401e72eff066908b33da | 10db5d0c11f429a947a58e4563e21e5fc0cd7dde | /consumers/ksql.py | ba553efbc1d29e286e8d2c23bb29d75a0f3e9fdb | [] | no_license | salomondavila84/Optimizing_Public_Transportation | 3e7456887e04bd5f5ebd2467dcff3382b04b4661 | fff2c637d2e8ddcd040b21df265799b7bc46f8c5 | refs/heads/master | 2023-03-22T03:13:28.330386 | 2021-03-08T21:27:50 | 2021-03-08T21:27:50 | 345,368,771 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,679 | py | """Configures KSQL to combine station and turnstile data
Confirmation:
[{"@type":"currentStatus","statementText":"CREATE TABLE turnstile (\n station_id INTEGER,\n station_name VARCHAR,\n line VARCHAR\n) WITH (\n KAFKA_TOPIC='cta.turnstile',\n VALUE_FORMAT='avro',\n KEY='station_id'\n);","commandId":"table/TURNSTILE/create","commandStatus":{"status":"SUCCESS","message":"Table created"},"commandSequenceNumber":0},{"@type":"currentStatus","statementText":"CREATE TABLE turnstile_summary\nWITH (KAFKA_TOPIC = 'TURNSTILE_SUMMARY', VALUE_FORMAT= 'json') AS\n SELECT station_id, COUNT(station_id) AS count\n FROM turnstile\n GROUP BY station_id;","commandId":"table/TURNSTILE_SUMMARY/create","commandStatus":{"status":"SUCCESS","message":"Table created and running"},"commandSequenceNumber":1}]
Manual Construction:
% docker exec -it kafka_project_ksql_1 bash
# ksql
ksql> server; http://localhost:8088
ksql> show topics;
ksql> CREATE TABLE turnstile (station_id INTEGER, station_name VARCHAR, line VARCHAR) WITH (KAFKA_TOPIC='cta-turnstile', VALUE_FORMAT='AVRO', KEY='station_id');
ksql> set 'auto.offset.reset'='earliest';
ksql> select * from TURNSTILE limit 10;
1612264738857 | �����] | 40900 | Howard | red
1612264739016 | �¼��] | 41400 | Roosevelt | red
1612264739029 | �ü��] | 40240 | 79th | red
1612264739272 | �Ƽ��] | 40610 | Ridgeland | green
1612264738504 | ں���] | 40570 | California | blue
1612264738549 | »���] | 40490 | Grand | blue
1612264738563 | 컼��] | 40380 | Clark/Lake | blue
1612264739328 | �Ǽ��] | 41360 | California | green
1612264738608 | ��] | 40430 | Clinton | blue
1612264738631 | 似��] | 40350 | UIC-Halsted | blue
Limit Reached
Query terminated
ksql> CREATE TABLE turnstile_summary with (KAFKA_TOPIC='TURNSTILE_SUMMARY', VALUE_FORMAT= 'JSON') AS SELECT station_id, COUNT(station_id) AS count FROM turnstile GROUP BY station_id;
Message
---------------------------
Table created and running
---------------------------
ksql> SELECT * FROM TURNSTILE_SUMMARY LIMIT 10;
1612264776424 | 40590 | 40590 | 1
1612264852645 | 40430 | 40430 | 3
1612264862883 | 40130 | 40130 | 3
1612264867940 | 41000 | 41000 | 5
1612264878057 | 40230 | 40230 | 2
1612264878061 | 41240 | 41240 | 3
1612264893293 | 40750 | 40750 | 3
1612264893354 | 40380 | 40380 | 5
1612264893356 | 40260 | 40260 | 1
1612264933987 | 40100 | 40100 | 5
Limit Reached
Query terminated
ksql> terminate CTAS_TURNSTILE_SUMMARY_1;
Message
-------------------
Query terminated.
-------------------
ksql> drop table turnstile;
Message
--------------------------------
Source TURNSTILE was dropped.
--------------------------------
ksql> drop table turnstile_summary;
Message
----------------------------------------
Source TURNSTILE_SUMMARY was dropped.
----------------------------------------
% kafka-topics --zookeeper 127.0.0.1:2181 --topic TURNSTILE_SUMMARY --delete
"""
import json
import logging
import requests
import topic_check
logger = logging.getLogger(__name__)
KSQL_URL = "http://localhost:8088"
#
# TODO: Complete the following KSQL statements.
# TODO: For the first statement, create a `turnstile` table from your turnstile topic.
# Make sure to use 'avro' datatype!
# TODO: For the second statement, create a `turnstile_summary` table by selecting from the
# `turnstile` table and grouping on station_id.
# Make sure to cast the COUNT of station id to `count`
# Make sure to set the value format to JSON
KSQL_STATEMENT = """
CREATE TABLE turnstile (
station_id INTEGER,
station_name VARCHAR,
line VARCHAR
) WITH (
KAFKA_TOPIC='cta.turnstile',
VALUE_FORMAT='avro',
KEY='station_id'
);
CREATE TABLE turnstile_summary
WITH (KAFKA_TOPIC = 'TURNSTILE_SUMMARY', VALUE_FORMAT= 'json') AS
SELECT station_id, COUNT(station_id) AS count
FROM turnstile
GROUP BY station_id;
"""
def execute_statement():
"""Executes the KSQL statement against the KSQL API"""
if topic_check.topic_exists("TURNSTILE_SUMMARY") is True:
return
logging.debug("executing ksql statement...")
resp = requests.post(
f"{KSQL_URL}/ksql",
headers={"Content-Type": "application/vnd.ksql.v1+json"},
data=json.dumps(
{
"ksql": KSQL_STATEMENT,
"streamsProperties": {"ksql.streams.auto.offset.reset": "earliest"},
}
),
)
# Ensure that a 2XX status code was returned
resp.raise_for_status()
print(resp.text)
if __name__ == "__main__":
execute_statement()
| [
"salomon@scopewave.com"
] | salomon@scopewave.com |
d68dd9aee38f272a57637402ae90918c73bc1986 | 641df38bb75077cd8da28b69e38b84af293b5db7 | /docassemble_base/setup.py | 73a6d2bf9b44a96183a19d6f23282978224b061d | [
"MIT"
] | permissive | bgordo3/docassemble | f19e01f2daf41eb05e2c19b5d4278bdc0d6d3ea5 | 3ce22e22e818598badc2242038f4e4abc4ee9fde | refs/heads/master | 2020-12-26T01:03:14.840009 | 2016-05-15T13:50:35 | 2016-05-15T13:50:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,809 | py | #!/usr/bin/env python
import os
import sys
from setuptools import setup, find_packages
from fnmatch import fnmatchcase
from distutils.util import convert_path
standard_exclude = ('*.py', '*.pyc', '*~', '.*', '*.bak', '*.swp*')
standard_exclude_directories = ('.*', 'CVS', '_darcs', './build', './dist', 'EGG-INFO', '*.egg-info')
def find_package_data(where='.', package='', exclude=standard_exclude, exclude_directories=standard_exclude_directories):
out = {}
stack = [(convert_path(where), '', package)]
while stack:
where, prefix, package = stack.pop(0)
for name in os.listdir(where):
fn = os.path.join(where, name)
if os.path.isdir(fn):
bad_name = False
for pattern in exclude_directories:
if (fnmatchcase(name, pattern)
or fn.lower() == pattern.lower()):
bad_name = True
break
if bad_name:
continue
if os.path.isfile(os.path.join(fn, '__init__.py')):
if not package:
new_package = name
else:
new_package = package + '.' + name
stack.append((fn, '', new_package))
else:
stack.append((fn, prefix + name + '/', package))
else:
bad_name = False
for pattern in exclude:
if (fnmatchcase(name, pattern)
or fn.lower() == pattern.lower()):
bad_name = True
break
if bad_name:
continue
out.setdefault(package, []).append(prefix+name)
return out
setup(name='docassemble.base',
version='0.1',
description=('A python module for assembling documents from templates while automatically querying a user for necessary information.'),
author='Jonathan Pyle',
author_email='jhpyle@gmail.com',
license='MIT',
url='http://docassemble.org',
namespace_packages = ['docassemble'],
install_requires = ['docassemble', '3to2', 'babel', 'bcrypt', 'blinker', 'cffi', 'fdfgen', 'guess-language-spirit', 'html2text', 'httplib2', 'itsdangerous', 'jellyfish', 'jinja2', 'lxml', 'mako', 'markdown', 'markupsafe', 'mdx-smartypants', 'namedentities==1.5.2', 'passlib', 'pdfminer', 'pillow', 'pip', 'pycparser', 'pycrypto', 'geopy', 'pygments', 'pyjwt', 'pypdf', 'PyPDF2', 'pyrtf-ng', 'python-dateutil', 'pytz', 'pyyaml', 'qrcode', 'six', 'titlecase', 'us', 'wheel'],
packages=find_packages(),
zip_safe = False,
package_data=find_package_data(where='docassemble/base/', package='docassemble.base'),
)
| [
"jpyle@philalegal.org"
] | jpyle@philalegal.org |
7bd85f927bc9fbd4e55fb4f877f126a500ab6dc3 | fbdf0b289caad852e6492c9039d126c5c1b0b1d0 | /function/function/wsgi.py | 70fcf9c3bba0fc90f875c22a3032e931b1bc07ac | [
"MIT"
] | permissive | choohyojung/DB_is_Free-Hotel_DB_System | 13484ef71227cfa7de285af4c5b439cb35725354 | d0790a49fe383b68350d6320ea60d59611ba689f | refs/heads/main | 2023-07-23T11:55:54.363661 | 2020-12-07T17:04:48 | 2020-12-07T17:04:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 393 | py | """
WSGI config for function project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'function.settings')
application = get_wsgi_application()
| [
"jaehoonkim.dev@gmail.com"
] | jaehoonkim.dev@gmail.com |
dc5f7b8e61b15898fda5a2bd6759d4f8c4ab4680 | 2dd5c248f58b456b876c779cddfa0976c9555a60 | /remcmd.py | 2988c22b2d6fad3da8a8d9218296c5abedc9599b | [] | no_license | natbett/remcmd | 0a728336bd2ce23c7aa6ef92cd5227a7541e56b5 | 2938e699d0207d84a123412ec567deb5027e06d4 | refs/heads/master | 2021-01-10T19:59:35.941875 | 2014-06-20T17:45:47 | 2014-06-20T17:45:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,369 | py | #!/usr/bin/python
import pexpect
import getpass
from sys import argv
import sys
script, hostlist, remcmd = argv
user = "set_username"
password = '[Pp]assword'
prompt = '[#$]'
yn = 'yes/no'
sshagent = 'id_rsa'
listing = open(hostlist, "r")
num = 0
psswd = getpass.getpass("Pass: ")
for host in listing:
host = host.strip()
num += 1
cmd1 = "ssh %s@%s" % (user, host)
print str(num) + ". " + host
child = pexpect.spawn(cmd1, timeout=600)
i = child.expect([password, prompt, yn, sshagent,
'Connection timed out',
'Could not resolve hostname'])
if i == 0:
child.sendline(psswd)
child.expect(prompt)
if i == 1:
pass
if i == 2:
child.sendline('yes')
child.expect(password)
child.sendline(psswd)
child.expect(prompt)
if i == 3:
print 'please do a ssh-add'
break
if i == 4:
print host + " down."
continue
if i == 5:
print host + " hostname not found."
continue
child.sendline('sudo su -')
t = child.expect([password, prompt])
if t == 0:
child.sendline(psswd)
child.expect(prompt)
if t == 1:
pass
child.sendline(remcmd)
child.expect(']#')
print child.before
child.sendline('~.')
child.expect(pexpect.EOF)
listing.close()
| [
"natbett@users.noreply.github.com"
] | natbett@users.noreply.github.com |
8b7f0478528201b5204abccdd64d32ab2477615b | 46327d9f913bd6798d56d08630649158b7744577 | /ECNU online judge/Last exams/1013.py | c64c614fccf9abf962781ff3a2f6977d4b003f41 | [] | no_license | Weaverzhu/acm | b79ce23d21752cb16791565f53689794b263b276 | 8ee154d4b586ee77d206c27d6b91ec2cc6d07547 | refs/heads/master | 2021-05-05T23:04:22.551334 | 2018-01-06T12:44:26 | 2018-01-06T12:44:26 | 116,482,436 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 333 | py | c = [[0 for i in range(31)] for i in range(31)]
c[0][0] = 1
for i in range(1, 31):
c[i][0] = 1
c[i][i] = 1
for j in range(1, i):
c[i][j] = c[i-1][j-1] + c[i-1][j]
while True:
n = int(input())
if n == 0:
break
for i in range(0, n):
for j in range(0, i):
print("{} ".format(c[i][j]), end="")
print(c[i][i])
print("")
| [
"1739635118@qq.com"
] | 1739635118@qq.com |
4228ce5872ac7e93c7c1127f84d6492f3243f49e | 008c69a66f8d6ee0b758de48bc1098cd176afa57 | /QService/quantitative/bean/record.py | bae7f7643225fa6e54c712f4bd4ddf343d366320 | [] | no_license | OriginPrince/quantitative | 127ab181369f9a3b20f7a0fa36164754c00eb6bc | 92b05d146a2db26a37281f61f5faca6ea93de2f5 | refs/heads/master | 2021-01-20T05:56:55.747737 | 2017-06-04T01:03:45 | 2017-06-04T01:03:45 | 89,826,418 | 12 | 6 | null | null | null | null | UTF-8 | Python | false | false | 567 | py | #coding=utf-8
class record(object):
def __init__(self,date,term,invest,stock):
self.date=date
self.term=term
self.invest=invest
if stock=='sh_hist_data':
self.stock=0
elif stock=='sz_hist_data':
self.stock=1
elif stock=='sz50_hist_data':
self.stock=2
elif stock=='hs300_hist_data':
self.stock=3
elif stock=='cyb_hist_data':
self.stock=4
elif stock=='zxb_hist_data':
self.stock=5
else:
self.stock=-1 | [
"1492854075@qq.com"
] | 1492854075@qq.com |
08ec156b0866331b3e9fe051ae1791df970000ba | f362cf4ba4a25a3278ed05781a21733a8fefddd7 | /user/models.py | 2e39e5a6220a18a58b08e889979b5b64d353e101 | [] | no_license | yurisjbc23/Backend_Laboratorio | 740020564c8ac745d259f1aab8d13bb96c06c993 | 50e39e25ffd06277f346913035bcc1049e80660a | refs/heads/main | 2023-08-14T17:44:17.883876 | 2021-09-28T17:53:10 | 2021-09-28T17:53:10 | 411,376,380 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,994 | py | from django.db import models
# Create your models here.
from proyecto.models import *
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class Employee(models.Model):
"""Modelo Employee"""
code = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
program_code = models.ForeignKey(Program, on_delete=models.CASCADE, default=0)
address = models.CharField(max_length=255)
phone = models.CharField(max_length=20)
Photo = models.ImageField(
upload_to='pictures',
default='pictures/default.jpg',
max_length=255
)
status = models.BooleanField(default=True)
def __str__(self):
return self.first_name
class Meta: # pylint: disable=too-few-public-methods
"""Propiedades adicionales del modelo Employee"""
db_table = 'Employee'
class Role(models.Model):
"""Modelo Role de Usuario"""
code = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
status = models.BooleanField(default=True)
def __str__(self):
return self.name
class Meta: # pylint: disable=too-few-public-methods
"""Propiedades adicionales del modelo Role"""
db_table = 'Role'
class Usuario(models.Model):
""" Modelo Usuario """
code = models.AutoField(primary_key=True)
username = models.EmailField(('Correo electronico'), unique=True)
password=models.CharField(max_length= 20, blank= False, null= False)
#first_name = None
#last_name = None
#is_staff = None
#is_superuser = None
Employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
Role = models.ForeignKey(Role, on_delete=models.CASCADE)
def __str__(self):
return self.username
class Meta: # pylint: disable=too-few-public-methods
"""Propiedades adicioneles del modelo User"""
db_table = 'Usuario'
| [
"yurisbellys23@gmail.com"
] | yurisbellys23@gmail.com |
311aacc98d2391a3939e775304b33711c96bf075 | ee4ff0fc4404b832071a71f3d447a4a5a805218e | /tests/fixtures.py | 9d41c10acfc20dce9c4bd73e23735c3fc858652e | [] | no_license | bronfo/ng-sanic | 2cc9aef0cd56b8c2475a8ab705ff76b5d32d6de2 | e3be42baec3c2f9581bf030cb106c2655444855e | refs/heads/master | 2020-04-01T13:28:19.003899 | 2018-10-16T08:59:57 | 2018-10-16T08:59:57 | 153,253,703 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 186 | py | import pytest
from vibora import Vibora
pytestmark = pytest.mark.asyncio
@pytest.fixture(name="app")
async def create_app():
_app = Vibora()
yield _app
_app.clean_up()
| [
"test1@test1.com"
] | test1@test1.com |
47821cfbba0dbe4c3efe3982af6bf0e12bc36614 | 8e7a2b9efbc0d25111f01f4cddb781961032685a | /python-1025/python/a_socket/3_ssh/cli.py | a8eb9d81fb94a0cd363d5f6691ffd91955caf960 | [] | no_license | Dituohgasirre/python | e044aa2e1fb2233b6ccd59701b834ab01e4e24c2 | 05f036d2723f75cd89e4412aaed7ee0ba5d3a502 | refs/heads/master | 2023-06-03T13:50:18.641433 | 2021-06-17T10:23:40 | 2021-06-17T10:23:40 | 366,942,423 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 834 | py | #!/usr/bin/env python3
import socket
from pargs import parse
from net import Packet
if __name__ == "__main__":
def main():
args, opt = parse(['s|srv|1', 'p|port|1'])
srvIp = opt['srv'] if 'srv' in opt else "3.3.3.3"
port = int(opt['port']) if 'port' in opt else 9000
sd = socket.socket(type=socket.SOCK_DGRAM)
addr = (srvIp, port)
packet = Packet(sd)
while True:
cmd = input("<自己的网络SHELL>: ")
packet.send(cmd, addr, Packet.DATA)
if cmd == "exit":
break
out = ""
while True:
data, addr = packet.recv()
if data['type'] == Packet.QUIT:
break
out += data['data']
print(out)
sd.close()
main()
| [
"linfeiji4729289@126.com"
] | linfeiji4729289@126.com |
4eb66817c6874423ce5198503c3e2958e963eaa2 | 1d74c2cb99f6ed34bc8e47dbade639b7c1ffa9eb | /数据爬取/爬虫代码/tcSpider/tcCity.py | e744e8ea3adc7e1bb9a77450d7b330ba6d5163d6 | [] | no_license | CarinaChen96/Data-analysis | ae3e1f5d3cd51a454953f4fe4434fe7d9ac86156 | c5236245299d35dc44566049264c308e7d19a951 | refs/heads/master | 2020-06-01T10:35:58.419470 | 2019-06-07T14:05:36 | 2019-06-07T14:05:36 | 190,750,883 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,517 | py | # -*- coding: utf-8 -*
import urllib.request as ur
#import urllib.parse as up
import json
import re
import os
import time
from bs4 import BeautifulSoup
from tcSpider import tcAllDuty
#####################获得起始的地点地址,与真实爬虫项目无关,仅为获得地址的方法
def getSpace():
# str='http://beijing.ganji.com/zpjisuanjiwangluo/'
space_start = 'http://' #beijing'.ganji.com/zpjisuanjiwangluo/'
space_end = '.58.com/tech/'
# url = ur.Request(str)
# url.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36')
# rep = ur.urlopen(url)
# html = rep.read().decode('utf-8')
# soup = BeautifulSoup(html,'lxml')
# # print(soup.prettify())
s='北京、上海、广州、深圳、天津、杭州、南京、济南、重庆、青岛、大连、宁波、厦门、成都、武汉、哈尔滨、沈阳、西安、长春、长沙、福州、郑州、石家庄、苏州、佛山、东莞、无锡、烟台、太原、合肥'
s1 = s.replace('、',',')
# print(s1)
space_name_dict={'北京':'beijing','上海':'shanghai','广州':'guangzhou','深圳':'shenzhen','天津':'tianjin',
'杭州':'hangzhou','南京':'nanjing','济南':'jinan','重庆':'chongiqng','青岛':'qingdao',
'大连':'dalian','宁波':'ningbo','厦门':'xiamen','成都':'chengdu','武汉':'wuhan','哈尔滨':'haerbin',
'沈阳':'shenyang','西安':'xian','长春':'changchun','长沙':'changsha','福州':'fuzhou','郑州':'zhengzhou',
'石家庄':'shijiazhuang','苏州':'suzhou','佛山':'foshan','东莞':'donguan','无锡':'wuxi','烟台':'yantai',
'太原':'taiyuan','合肥':'hefei','淄博':'zibo'}
space_url={}
for key in space_name_dict:
space_str_url = space_start + space_name_dict[key] + space_end
space_url[key]=space_str_url
print(space_url)
# getSpace()
######################爬虫的起始方法,将地点链接存入列表中,读取链接传入第二个方法中
def mySpaceUrl():
enterWord = input('请输入开始指令\n\n')
while enterWord != '开始':
print('对不起,指令错误')
enterWord = input('请重新输入开始指令\n\n')
else:
print('项目开始')
# num = 0
# space_address = input('请输入文件储存地址(例如:I:\\space1\\)\n\n')
space_address = 'I:\\tcresult\\'
print('爬虫进行中......')
#'北京': 'http://beijing.58.com/tech', '上海': 'http://shanghai.58.com/tech', '广州': 'http://guangzhou.58.com/tech', '深圳': 'http://shenzhen.58.com/tech', '天津': 'http://tianjin.58.com/tech', '杭州': 'http://hangzhou.58.com/tech', '南京': 'http://nanjing.58.com/tech', '济南': 'http://jinan.58.com/tech', '重庆': 'http://chongiqng.58.com/tech',
spaceUrl={'青岛': 'http://qingdao.58.com/tech', '东莞': 'http://dg.58.com/tech', '无锡': 'http://wx.58.com/tech','太原': 'http://ty.58.com/tech', '合肥': 'http://hf.58.com/tech'}
# {'北京': 'http://beijing.58.com/tech/', '上海': 'http://shanghai.58.com/tech/',
# '广州': 'http://guangzhou.58.com/tech/', '深圳': 'http://shenzhen.58.com/tech/',
# '天津': 'http://tianjin.58.com/tech/', '杭州': 'http://hangzhou.58.com/tech/', '南京': 'http://nanjing.58.com/tech/',
# '济南': 'http://jinan.58.com/tech/', '重庆': 'http://chongiqng.58.com/tech/', '青岛': 'http://qingdao.58.com/tech/',
# '大连': 'http://dalian.58.com/tech/', '宁波': 'http://ningbo.58.com/tech/', '厦门': 'http://xiamen.58.com/tech/',
# '成都': 'http://chengdu.58.com/tech/', '武汉': 'http://wuhan.58.com/tech/', '哈尔滨': 'http://haerbin.58.com/tech/',
# '沈阳': 'http://shenyang.58.com/tech/', '西安': 'http://xian.58.com/tech/', '长春': 'http://changchun.58.com/tech/',
# '长沙': 'http://changsha.58.com/tech/', '福州': 'http://fuzhou.58.com/tech/',
# '郑州': 'http://zhengzhou.58.com/tech/', '石家庄': 'http://shijiazhuang.58.com/tech/',
# '苏州': 'http://suzhou.58.com/tech/', '佛山': 'http://foshan.58.com/tech/', '东莞': 'http://donguan.58.com/tech/',
# '无锡': 'http://wuxi.58.com/tech/', '烟台': 'http://yantai.58.com/tech/', '太原': 'http://taiyuan.58.com/tech/',
# '合肥': 'http://hefei.58.com/tech/', '淄博': 'http://zibo.58.com/tech/'}
for space in spaceUrl:
#try:
# os.mkdir('I:\\space\\'+space)
if space !='青岛':
time.sleep(60)
space_file = space_address+space
os.mkdir(space_file)
filename = space_file + '\\' + space + '.txt'
print('\n\n*********************************************************************')
print('恭喜你,*{}*文件创建成功'.format(space))
space_url=spaceUrl[space]
tcAllDuty.getduty(space_url, filename)
print('''*********************************************************************
*********************************************************************\n\n''')
# except OSError:
# print('对不起,*{}*此文件已存在'.format(space))
# print(mySpaceUrl())
# mySpaceUrl()
if __name__ == '__main__':
getSpace()
| [
"noreply@github.com"
] | CarinaChen96.noreply@github.com |
e326495aad641222002bd2cf626bf6085a57213a | b9a7775c116fe233fea282d8568febb7694ae0d6 | /TH.py | ea57c41999cc36921b6535e21ccbd037ff0bcbcf | [] | no_license | jh6226/Texas_Holdem | 41c2b64c3cb4824dfa4f699de111dda693c34a8c | 1f7eeb1c83a8849cea63ac9136fc66e8038faeba | refs/heads/master | 2023-03-31T11:52:48.586586 | 2020-06-18T16:16:58 | 2020-06-18T16:16:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 15,511 | py | #import dependencies
import random
import copy
from timeit import default_timer as timer
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
class Hand:
'''
This class creates a Texas Holdem
'''
def __init__(self):
cards = [2,3,4,5,6,7,8,9,10,11,12,13,14]
suits = ['H','D','S','C']
self.deck = [(card,suit) for card in cards for suit in suits]
random.shuffle(self.deck)
self.selected_hand = []
def player_1(self):
'''
selects two random cards for the player
'''
return self.deck[:2]
def table(self,cards_on_table = 3):
'''
places cards_on_table number of random cards on the table
key word arguments:
cards_on_table -- Number of cards on the table (0 3 or 4) defualt = 3
'''
return self.deck[2:2+cards_on_table], self.deck[2+cards_on_table:]
def hand_selection(self):
'''
input allowing for two specific cards to be selected
'''
card_1_value = input('Card 1 value:')
card_1_suit = input('Card 1 suit:')
card1 = (int(card_1_value), card_1_suit)
card_2_value = input('Card 2 value:')
card_2_suit = input('Card 2 suit:')
card2 = (int(card_2_value), card_2_suit)
self.selected_hand.append(card1)
self.selected_hand.append(card2)
return self.selected_hand
def table_selection(self, cards_on_table = 3):
'''
input allowing for cards_on_table number of cards to be selected to be placed on the table
key word arguments:
cards_on_table -- Number of cards on the table (0 3 or 4) defualt = 3
'''
on_table = []
if cards_on_table >= 3:
table1_value = input('table 1 value:')
table1_suit = input('table 1 suit:')
on_table.append((int(table1_value),table1_suit))
table2_value = input('table 2 value:')
table2_suit = input('table 2 suit:')
on_table.append((int(table2_value),table2_suit))
table3_value = input('table 3 value:')
table3_suit = input('table 3 suit:')
on_table.append((int(table3_value),table3_suit))
if cards_on_table == 4:
table1_value = input('table 4 value:')
table1_suit = input('table 4 suit:')
on_table.append((int(table4_value),table4_suit))
deck_return = [i for i in self.deck if i != self.selected_hand[0] and i != self.selected_hand[1]]
deck_return_minus_table = [i for i in deck_return if i not in on_table]
return [on_table, deck_return_minus_table]
def hand_selection_list(self,cards_in_hand):
'''
input allowing for two specific cards to be selected
key word arguments:
cards_in_hand -- a list of the cards you want in your hand
'''
card1 = cards_in_hand[0]
card2 = cards_in_hand[1]
self.selected_hand.append(card1)
self.selected_hand.append(card2)
return self.selected_hand
def table_selection_list(self,cards_on_table):
'''
input allowing for cards_on_table number of cards to be selected to be placed on the table
key word arguments:
cards_on_table -- a list of cards to appear on the table
'''
deck_return = [i for i in self.deck if i not in self.selected_hand]
deck_return_minus_table = [i for i in deck_return if i not in cards_on_table]
return [cards_on_table, deck_return_minus_table]
#this probably shouldnt be a class
class Table:
'''
This class takes a selected hand and deals two random cards to every player and finishes dealing the remaining deck
'''
def __init__(self, player_1, table, player_count = 5):
self.player_1 = player_1
self.table = table[0]
self.player_count = player_count
self.hands = player_1[0]
self.remaining_deck = table[1]
random.shuffle(self.remaining_deck)
def deal(self):
'''
This function deals cards to player_count-1 number of remaining players and deals the remaining cards on the table
key word arguments:
player_1 -- Two cards from Hand class that stay constant
table -- Cards from Hand class that stay constant
player_count -- the total number of players in this game
returns a [hands, table_dealt] where hands are the other players two
card hands and table_dealt is the 5 cards on the table at the end of the hand
'''
remaining_deck_copy = copy.copy(self.remaining_deck)
hands = [[] for _ in range(self.player_count-1)]
for _ in range(2): #hands everyone one card and then a second
for i in range(self.player_count-1):
hands[i].append(remaining_deck_copy.pop())
table_dealt = [*self.table, *remaining_deck_copy[-(5-len(self.table)):]]
return hands, table_dealt
class Hit_Hand:
'''
This class returns a boolean value for weather or not the 7 card hand hit each possibity
key word arguments:
player_1 -- The two cards the player one is given
deal -- the 5 cards on the table as well as the other players hands (not used here)
print_hand -- will print the hand if True (defualt False)
'''
def __init__(self, player_1, deal, print_hand = False):
self.player_1 = player_1
self.other_players = deal[0]
self.table = deal[1]
self.total_hand = [*player_1,*self.table]
self.suits = [x[1] for x in self.total_hand]
self.value = [x[0] for x in self.total_hand] #list of cards
if print_hand == True:
print('Your Cards:')
print(self.player_1)
print('Table:')
print(self.table)
#this needs to be tested
def straight_flush(self):
hand = []
if (self.suits.count('H') >= 5):
for card in self.total_hand:
if card[1] == 'H':
hand.append(card[0])
elif (self.suits.count('S') >= 5):
for card in self.total_hand:
if card[1] == 'S':
hand.append(card[0])
elif (self.suits.count('D') >= 5):
for card in self.total_hand:
if card[1] == 'D':
hand.append(card[0])
elif (self.suits.count('C') >= 5):
for card in self.total_hand:
if card[1] == 'C':
hand.append(card[0])
if len(hand) >= 5:
#if their is a 14 add a 1 to the begining because Ace is high or low for straight
cards = list(set(hand))
if cards.count(14) == 1:
cards.append(1)
cards.sort()
c = 1
for i in range(len(cards)-1):
if cards[i] + 1 == cards[i + 1]:
c += 1
elif c >= 5:
return True
else:
c = 1
return (c >= 5)
return False
def four_of_kind(self):
c = 0
for i in set(self.value):
if self.value.count(i) == 4:
c += 1
return (c == 1)
def full_house(self):
pair = 0
three = 0
for i in set(self.value):
if self.value.count(i) == 2:
pair += 1
elif self.value.count(i) >= 3:
three += 1
return ((pair >= 1) and (three == 1)) or (three >= 2)
def flush(self):
return (self.suits.count('H') >= 5) or (self.suits.count('D') >= 5) or \
(self.suits.count('S') >= 5) or (self.suits.count('C') >= 5)
def straight(self):
#if their is a 14 add a 1 to the begining because Ace is high or low for straight
cards = list(set(self.value))
if cards.count(14) == 1:
cards.append(1)
cards.sort()
c = 1
for i in range(len(cards)-1):
if cards[i] + 1 == cards[i + 1]:
c += 1
elif c >= 5:
return True
else:
c = 1
return (c >= 5)
def three_of_kind(self):
c = 0
for i in set(self.value):
if self.value.count(i) >= 3:
c += 1
return (c >= 1)
def two_pair(self):
c = 0
for i in set(self.value):
if self.value.count(i) >= 2:
c += 1
return (c >= 2)
def pair(self):
for i in set(self.value):
if self.value.count(i) >= 2:
return True
return False
#identifying the best hand
class Best_Hand:
'''
This class returns the best five card hand
key word arguments:
player_1 -- The two cards the player one is given
deal -- the 5 cards on the table as well as the other players hands (not used here)
print_hand -- will print the hand if True (default False)
***
Note: this was designed to be run in order and does not immidiatly identify the best hand but works in conjuction with the top_hand function
***
'''
def __init__(self, player_1, deal, print_hand = False):
self.player_1 = player_1
self.other_players = deal[0]
self.table = deal[1]
self.total_hand = [*player_1,*self.table]
self.suits = [x[1] for x in self.total_hand]
self.value = [x[0] for x in self.total_hand] #list of cards
if print_hand == True:
print('Your Cards:')
print(self.player_1)
print('Table:')
print(self.table)
#done
def straight_flush(self):
hand = []
if (self.suits.count('H') >= 5):
for card in self.total_hand:
if card[1] == 'H':
hand.append(card[0])
elif (self.suits.count('S') >= 5):
for card in self.total_hand:
if card[1] == 'S':
hand.append(card[0])
elif (self.suits.count('D') >= 5):
for card in self.total_hand:
if card[1] == 'D':
hand.append(card[0])
elif (self.suits.count('C') >= 5):
for card in self.total_hand:
if card[1] == 'C':
hand.append(card[0])
if len(hand) >= 5:
#if their is a 14 add a 1 to the begining because Ace is high or low for straight
cards = list(set(hand))
if cards.count(14) == 1:
cards.append(1)
cards.sort()
c = 1
hand_suited = []
for i in range(len(cards)-1):
if (cards[i] + 1) == cards[i + 1]:
c += 1
if len(hand_suited) == 0:
hand_suited.append(cards[i])
hand_suited.append(cards[i+1])
else:
hand_suited.append(cards[i+1])
elif c >= 5:
return hand_suited[-5:]
else:
c = 1
hand_suited = []
def four_of_kind(self):
hand = []
for card in self.value:
if self.value.count(card) == 4:
hand.append(card)
if len(hand) == 4:
high_cards = sorted(self.value)
if high_cards[-1] != hand[0]:
hand.append(high_cards[-1])
else:
hand.append(high_cards[-5])
return hand[::-1]
def full_house(self):
pair_hand = list()
three_hand = list()
for card in set(self.value):
if self.value.count(card) == 2:
pair_hand.append(card)
elif self.value.count(card) == 3:
three_hand.append(card)
if len(three_hand) == 2:
return [min(three_hand), min(three_hand), max(three_hand), max(three_hand), max(three_hand)]
elif len(three_hand) == 1 and len(pair_hand) >= 1:
return [max(pair_hand),max(pair_hand),max(three_hand),max(three_hand), max(three_hand)]
def flush(self):
hand = []
if (self.suits.count('H') >= 5):
for card in self.total_hand:
if card[1] == 'H':
hand.append(card)
elif (self.suits.count('S') >= 5):
for card in self.total_hand:
if card[1] == 'S':
hand.append(card)
elif (self.suits.count('D') >= 5):
for card in self.total_hand:
if card[1] == 'D':
hand.append(card)
elif (self.suits.count('C') >= 5):
for card in self.total_hand:
if card[1] == 'C':
hand.append(card)
if len(hand) > 1:
hand_value = [x[0] for x in hand]
return sorted(hand_value)[-5:]
def straight(self):
#if their is a 14 add a 1 to the begining because Ace is high or low for straight
cards = list(set(self.value))
if cards.count(14) == 1:
cards.append(1)
cards.sort()
hand = []
for i in range(len(cards)-1):
if (cards[i] + 1) == cards[i + 1]:
if len(hand) == 0:
hand.append(cards[i])
hand.append(cards[i+1])
else:
hand.append(cards[i+1])
if len(hand) >= 5:
return hand[-5:]
elif (cards[i] + 1) != cards[i + 1]:
hand = []
def three_of_kind(self):
hand = []
for card in self.value:
if self.value.count(card) == 3:
hand.append(card)
if len(hand) == 3:
high_cards = []
for num in sorted(self.value):
if num != hand[0]:
high_cards.append(num)
hand.append(high_cards[-1])
hand.append(high_cards[-2])
return hand[::-1]
def two_pair(self):
c = 0
hand = []
for card in self.value:
if self.value.count(card) == 2:
c += 1
hand.append(card)
if (c >= 4):
top_pairs = sorted(hand)[-4:][::-1]
high_card = []
for num in sorted(self.value):
if num != top_pairs[-3] and num != top_pairs[-1]:
high_card.append(num)
top_pairs.append(high_card[-1])
return top_pairs[::-1]
def pair(self):
hand = []
for card in self.value:
if self.value.count(card) == 2:
hand.append(card)
if len(hand) == 2:
high_cards = []
for num in sorted(self.value):
if num != hand[0]:
high_cards.append(num)
hand.append(high_cards[-1])
hand.append(high_cards[-2])
hand.append(high_cards[-3])
return hand[::-1]
def high_card(self):
return sorted(self.value)[-5:]
| [
"MicahelEmmert1234@gmail.com"
] | MicahelEmmert1234@gmail.com |
142b653304c76390760894385d5afff488314564 | 110bbe2362d9852ff5e41f6a3c31fb592298f453 | /Tratamiento de datos/Ejemplos/reemplazardatos.py | a30bf7fd2ebea5fe7c5b102cf68339b1dbf90207 | [] | no_license | marcosperezper/cursoPython | a08650b1c646d707b9a17d8bc5888c61baca4e73 | 40cf13d3e59cc382be93bcf622b5db60dda93b11 | refs/heads/master | 2023-03-09T23:10:01.471000 | 2021-02-24T10:09:26 | 2021-02-24T10:09:26 | 279,596,773 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 202 | py | #Reemplazar datos en series
import numpy as np
import pandas as pd
serie1 =pd.Series([1,2,3,4,5], index=list('abcde'))
serie2 = serie1.replace(1,6)
serie3 = serie1.replace({2:8,3:9})
print(serie3) | [
"marcosperez@Marcos-Perez.local"
] | marcosperez@Marcos-Perez.local |
44a9a15bccfd2eaf0f5fdda0303ffd954d09fe74 | 6a378987bf7fbd437d64d01d454c22ea09039e48 | /skstack/settings.py | 2ad9a17fc9784a8d3f531ec396126ff341a21edb | [
"Apache-2.0"
] | permissive | qsvic/skstack | 4242ee773c1b5dafa6da9ef31470d1f42916ef46 | fe874f540a56297919533a955bc822071b234f5e | refs/heads/master | 2022-11-11T16:37:52.579089 | 2020-07-09T06:33:15 | 2020-07-09T06:33:15 | 278,256,729 | 0 | 0 | Apache-2.0 | 2020-07-09T03:48:27 | 2020-07-09T03:48:26 | null | UTF-8 | Python | false | false | 10,809 | py | # coding:utf8
"""
Django settings for skstack project.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
import configparser as ConfigParser
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if os.path.exists(BASE_DIR+'/skstack_dev.conf'):
CONFIGFILE = os.path.join(BASE_DIR, 'skstack_dev.conf')
else:
CONFIGFILE = os.path.join(BASE_DIR, 'skstack_prod.conf')
config = ConfigParser.ConfigParser()
config.read(CONFIGFILE)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'n@s)3&f$tu#-^^%k-dj__th2)7m!m*(ag!fs=6ezyzb7l%@i@9'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config.get('setup', 'debug')
# DEBUG = True if config.get('setup', 'debug') == 'True' else False
ALLOWED_HOSTS = config.get('setup', 'allowed_hosts').split(',')
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
# Application definition
INSTALLED_APPS = [
'skrpt',
# 'sktask',
# 'skcmdb',
# 'skrecord',
# 'skyw',
'skconfig',
'skaccounts',
'skworkorders',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_celery_results',
# 'channels',
]
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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.common.BrokenLinkEmailsMiddleware',
]
ROOT_URLCONF = 'skstack.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'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',
'skstack.context_processor.url_permission',
],
},
},
]
WSGI_APPLICATION = 'skstack.wsgi.application'
DATABASES = {}
if config.get('db', 'engine') == 'mysql':
DB_HOST = config.get('db', 'host')
DB_PORT = config.getint('db', 'port')
DB_USER = config.get('db', 'user')
DB_PASSWORD = config.get('db', 'password')
DB_DATABASE = config.get('db', 'database')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': DB_DATABASE,
'USER': DB_USER,
'PASSWORD': DB_PASSWORD,
'HOST': DB_HOST,
'PORT': DB_PORT,
'OPTIONS': {
"init_command": "SET sql_mode='STRICT_TRANS_TABLES'",
}
}
}
elif config.get('db', 'engine') == 'sqlite':
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': config.get('db', 'database'),
}
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
DATABASE_ROUTERS = ['skstack.utils.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = {
'skjumpserver': 'jumpserver_db',
}
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',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = False
STATIC_URL = '/static/'
# STATIC_ROOT = BASE_DIR + '\\static\\'
#for windows py37
STATIC_ROOT = ''
STATICFILES_DIRS = ( os.path.join('static'), )
#for windows py37_64 debug mode
# STATIC_ROOT = os.path.join(BASE_DIR, '/static/')
# STATICFILES_DIRS = [
# os.path.join(BASE_DIR, 'static')
# ]
#print("STATIC_ROOT: %s" % STATIC_ROOT)
# STATICFILES_DIRS = (
# os.path.join(BASE_DIR, './static/').replace('\\', '/'),
# # os.path.join(BASE_DIR, '/static/'),
#
# )
# print("this STATICFILES_DIRS: %s" % STATICFILES_DIRS)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
CKEDITOR_UPLOAD_PATH = "uploads/"
CKEDITOR_IMAGE_BACKEND = "pillow"
CKEDITOR_RESTRICT_BY_USER = False
CKEDITOR_CONFIGS = {
# 配置名是default时,django-ckeditor默认使用这个配置
'default': {
# 使用简体中文
'language':'zh-cn',
# 编辑器的宽高请根据你的页面自行设置
'width':'530px',
'height':'150px',
'image_previewText':' ',
'tabSpaces': 4,
'toolbar': 'Custom',
# 添加按钮在这里
'toolbar_Custom': [
['Bold', 'Italic', 'Underline', 'Format', 'RemoveFormat'],
['NumberedList', 'BulletedList'],
['Blockquote', 'CodeSnippet'],
['Image', 'Link', 'Unlink'],
['Maximize']
],
# 插件
'extraPlugins': ','.join(['codesnippet','uploadimage','widget','lineutils',]),
}
}
'''
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
'''
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
)
}
AUTH_USER_MODEL = 'skaccounts.UserInfo'
LOGIN_URL = '/skaccounts/login/'
#celery config
# CELERY_BROKER_URL = config.get('celery', 'celery_broker_url')
CELERY_BROKER_URL = 'redis://:redispskstack@localhost:6379/5'
CELERY_RESULT_BACKEND = 'django-db'
CELERY_TIMEZONE = 'Asia/Shanghai'
CELERY_RESULT_EXPIRES = 99999
CELERY_ACCEPT_CONTENT = ['json','yaml']
log_path = config.get('log', 'log_path')
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'filters': {
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
},
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse',
},
},
'formatters': {
'standard': {
'format': '%(asctime)s|%(levelname)s|%(process)d|%(funcName)s|%(lineno)d|msg:%(message)s'
},
'verbose': {
'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
'style': '{',
},
'simple': {
'format': '{levelname} {message}',
'style': '{',
},
},
'handlers': {
'null': {
'level':'DEBUG',
'class':'logging.NullHandler',
},
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'filters': ['require_debug_false'], # DEBUG = False sendemail
'include_html':True,
'formatter': 'standard',
},
'default': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(log_path,'skstack.log'),
'maxBytes': 1024 * 1024 * 5,
'backupCount': 5,
'formatter': 'standard',
},
'console': {
'level': 'DEBUG',
'filters': ['require_debug_true'],
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
'skworkorders_log': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(log_path,'skworkorders.log'),
'formatter': 'standard'
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': 'INFO',
'propagate': True,
},
'django.request': {
'handlers': ['console', 'default'],
'level': 'INFO',
'propagate': False,
},
'skstack': {
'handlers': ['console', 'default'],
'level': 'INFO',
'propagate': False,
},
'skworkorders': {
'handlers': ['skworkorders_log','console'],
'level': 'INFO',
'propagate': False,
},
}
}
# EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# EMAIL_HOST = config.get('email', 'email_host')
# EMAIL_PORT = config.get('email', 'email_port')
# EMAIL_HOST_USER = config.get('email', 'email_user')
# EMAIL_HOST_PASSWORD = config.get('email', 'email_password')
# EMAIL_SUBJECT_PREFIX = 'skstack' #为邮件标题的前缀,默认是'[django]'
# DEFAULT_FROM_EMAIL = SERVER_EMAIL = EMAIL_HOST_USER #设置发件人
#
# ADMINS = (
#
# ('encodingl','encodingl@sina.com'),
#
# )
# MANAGERS = ADMINS
# SEND_BROKEN_LINK_EMAILS = True
# CRONJOBS = [
# ('*/10 * * * *', 'skrecord.cron','>>/var/log/skrecord_cron.log')
# ]
#for channels websockets
# ASGI_APPLICATION = 'skstack.routing.application'
# RedisHost = config.get('redis', 'host')
# RedisPort = config.get('redis', 'port')
# CHANNEL_LAYERS = {
# "default": {
# "BACKEND": "channels_redis.core.RedisChannelLayer",
# "CONFIG": {
# "hosts": [(RedisHost, RedisPort)],
# },
#
# },
# }
| [
"encodingl@sina.com"
] | encodingl@sina.com |
e2c55a5f3b68d50bc41e994cf2066a0d40e76506 | 6db5c91bf444ebbe2fc0b9a64cb6360636cdefd7 | /JVApp/management/urls.py | 91b2ad48fac59f6ee41e5934a9909fe2cf10e081 | [] | no_license | bgilbarreto/JVAPP | 3cd3b7937b46744c259ef0fd09084c82027f29cb | 7cac1450b68af0b7bae13efa819183649dc91125 | refs/heads/master | 2022-09-19T16:48:45.514641 | 2020-05-30T05:20:29 | 2020-05-30T05:20:29 | 256,841,197 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,201 | py | from django.contrib import admin
from django.urls import include, path
from management.views import Home, listarProductos, insertarCliente, borrarCliente, editarCliente, insertarProducto, insertarCategoria
from management.views import editarProducto, eliminarProducto, insertarTiendas, seacrhByProduct
from management.views import listaEnvios, seacrhByName, verDetalle, verProductosDetalle, listProdAPI, listEnvioAPI, listClientAPI
from django.contrib.auth import views as auth_views
urlpatterns = [
# path's de clientes
path('',Home.as_view(), name= 'home'),
path('insertar_cliente/', insertarCliente.as_view(), name ='insertar_cliente'),
path('editar/cliente<int:pk>',editarCliente.as_view(), name='editar_cliente'),
path('delete/client/<int:pk>', borrarCliente.as_view(), name= 'delete_client'),
path('searchClient/', seacrhByName.as_view(), name='buscarNombre'),
path('clientesJson/',listClientAPI.as_view(), name='lst_client_json'),
#path's de login/logout
path('login/',auth_views.LoginView.as_view(template_name='login.html'),name='login'),
path('logout/',auth_views.LogoutView.as_view(template_name='login.html'),name='logout'),
#path's de Productos
path('insertar_producto/',insertarProducto.as_view(), name= 'insertar_producto'),
path('listar_productos/',listarProductos.as_view(), name= 'listarProducto'),
path('editar/producto<int:pk>', editarProducto.as_view(), name='editar_producto'),
path('delete/product<int:pk>', eliminarProducto.as_view(), name= 'delete_product'),
path('searchProduct/', seacrhByProduct.as_view(), name='search_product'),
path('productosJson/',listProdAPI.as_view(), name='lst_prod_json'),
#path's de Categorias, Tiendas y Envios
path('lst_package/', listaEnvios.as_view(), name='lst_pckg'),
path('detail_package/<int:pk>',verDetalle.as_view(), name='detail_package'),
path('products_in_sell/', verProductosDetalle.as_view(), name = 'detail_sell'),
path('add_store/', insertarTiendas.as_view(), name= 'insert_store'),
path('add_cathegory/', insertarCategoria.as_view(), name= 'insert_cathegory'),
path('tiendasJson/',listEnvioAPI.as_view(), name='lst_sended_json'),
]
| [
"bgilbarreto@gmail.com"
] | bgilbarreto@gmail.com |
97f85c7798c664387dad86df61551fbabd7383ae | 9bb1325693c93bb9ba1e6deef79b4f89dd4a89da | /celeryapp.py | 65ebd7a0cdf5f7b377944e71436a30ca1fdd5a8a | [] | no_license | delving/hub3_demo | d5e51251e1323577665f91819f0ba3a3300c19b4 | 0aea7268c6dcdbdb83f51207b44d35de5553e69d | refs/heads/master | 2021-06-07T02:10:25.093114 | 2017-11-29T16:12:49 | 2017-11-29T16:12:49 | 112,497,191 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 551 | py |
import os
from celery import Celery
from django.conf import settings
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nave.projects.demo.settings')
app = Celery('nave.projects.demo')
# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
@app.task(bind=True)
def debug_task(self):
print(('Request: {0!r}'.format(self.request))) | [
"sjoerd.siebinga@gmail.com"
] | sjoerd.siebinga@gmail.com |
885f52ae3ed5f9c54b198180fc65d4f85267b7c0 | dd1ae5a84940ed800ff9a064cb4f4cdfc16ecaab | /ticketapi/tickets/migrations/0002_auto_20180430_0951.py | bbcd86756af26c95997127fbb598ccd96daa4f32 | [] | no_license | nnamdei/supportticketapi | 361054cef1a06a3cdadefa0c310cda2d668cb962 | c22ffee54befd2b8727f305c35304d03c3da1650 | refs/heads/master | 2020-03-14T10:47:24.913363 | 2018-04-30T10:11:50 | 2018-04-30T10:11:50 | 131,575,861 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 427 | py | # Generated by Django 2.0.4 on 2018-04-30 09:51
from django.conf import settings
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('tickets', '0001_initial'),
]
operations = [
migrations.RenameModel(
old_name='Support_ticket',
new_name='Ticket',
),
]
| [
"nnamsok@gmail.com"
] | nnamsok@gmail.com |
506db17bc8e187a4e4492669c1e1714682c2e99d | 588fc7a74ec467f708a6e0684870929cf4c99234 | /34.py | cf0b2f5edebdc6762699d5f4396d418c96737cbc | [] | no_license | petitviolet/project_euler | 87710cd1b5138d6fea15a563c5a23b23c2b3c870 | 03f62a400708bd5cd4370456178c2ee63fb717db | refs/heads/master | 2020-05-27T10:56:32.187374 | 2013-05-16T00:16:38 | 2013-05-16T00:16:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 599 | py | # -*- encoding:utf-8 -*-
def analysis(n):
if n <= 2:
return False
ch = str(n)
result = 0
for c in ch:
result += fact(int(c))
if result == n:
return result
else:
return False
def fact(n):
if n <= 1:
return 1
elif n <= 2:
return 2
else:
return n * fact(n - 1)
def main():
max_num = fact(9) * 4
print 'max_num =', max_num
ans = 0
for i in xrange(3, max_num):
a = analysis(i)
if a:
print a
ans += a
print ans
if __name__ == '__main__':
main()
| [
"violethero0820@gmail.com"
] | violethero0820@gmail.com |
9513a704745937eb0d0d0f25d0b26abfbdb37fca | 2a95c64fc0c944fb21ad941b92d36273480e63a3 | /scripts/abdulrafik.py | da3dcdf6f7a27b249f9548a6da8d10c5e43d3fd4 | [] | no_license | developerjamiu/HNG-Script | 24cee0dd4e79e6a890d0df67cb1cd55c2570b151 | 5b2dd32173858fe7214a2f7a0cfb77930f50c886 | refs/heads/master | 2022-09-06T02:25:26.614043 | 2020-06-04T14:34:30 | 2020-06-04T14:34:30 | 269,370,302 | 2 | 0 | null | 2020-06-04T13:42:04 | 2020-06-04T13:42:04 | null | UTF-8 | Python | false | false | 196 | py | def hng_stage2_task(name, id, lang):
print(f" Hello World, this is {name} with HNGi7 ID: {id} using {lang} for stage 2 task")
hng_stage2_task("Abdul Rafik Al-hassan", "HNG-05318", "Python") | [
"aral-hassan001@st.ug.edu.gh"
] | aral-hassan001@st.ug.edu.gh |
2073c2fc128cdbf6ac4b4f843d76d09105bb1cbc | 7af8f71ac0fc95e751d72d332903c4ad558445f5 | /2015/11a.py | 030aaa3e25395830d2948897989aadaf084bc0e7 | [] | no_license | ChesleyTan/Advent-of-Code | b89479eb59b5dab1ced810a9d3f18c4a79eba83e | 45e5cc4f9b0a4e098ac36f2728b7a81af54611bf | refs/heads/master | 2021-10-12T04:21:48.048182 | 2019-02-01T20:39:43 | 2019-02-01T20:39:43 | 115,364,521 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 963 | py | #!/usr/bin/python
ctoi = lambda c: ord(c) - ord('a')
passwd = "vzbxkghb"
pairs = [2*chr(i+ord('a')) for i in xrange(26)]
print pairs
def rule1(s):
two_prev = -1
prev = -1
s = map(ctoi, s)
for c in s:
if two_prev == prev - 1 and prev == c - 1:
return True
else:
two_prev = prev
prev = c
return False
def rule2(s):
for c in s:
if c in "iol":
return False
return True
def rule3(s):
count = 0
for pair in pairs:
if pair in s:
count += 1
if count > 1:
return True
return False
def inc(passwd):
passwd = map(ctoi, passwd)
i = len(passwd) - 1
passwd[i] += 1
while passwd[i] > 25:
passwd[i] = 0
i -= 1
passwd[i] += 1
return ''.join([chr(i + ord('a')) for i in passwd])
while not (rule1(passwd) and rule2(passwd) and rule3(passwd)):
passwd = inc(passwd)
print passwd
| [
"chesleytan97@gmail.com"
] | chesleytan97@gmail.com |
c11a910543ff20788908eca4c0574fe43d26b4a4 | c25a97c88ca5714a23f9e99361ae4aa6849b546a | /robot.py | a01fdec40e06ba7ae607fed454773a2145cc0349 | [] | no_license | AustinMay1/Robo-v-Dino | 4053ea291f3ea3af5cab8703393043f304bc0f70 | 760fd4c024821ee13717771a5ae45347fa9282a6 | refs/heads/main | 2023-07-17T06:22:12.441442 | 2021-09-10T01:35:19 | 2021-09-10T01:35:19 | 404,523,631 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 530 | py | from weapon import Weapon
class Robot:
def __init__ (self, name, health, weapon):
self.name = name
self.health = health
self.weapon = weapon
def robot_info (self):
print('Robots Name: ', self.name)
print('Robots Health: ', self.health)
print('Robots Weapon: ', self.weapon.wep_type)
print('Attack Power: ', self.weapon.attack_power)
def robo_attack (self, dinosaur):
dinosaur.health -= self.wep_power
| [
"austin.may@protonmail.com"
] | austin.may@protonmail.com |
51e0e2a1659f95d3b8414243848b7426d1ff7812 | 09e57dd1374713f06b70d7b37a580130d9bbab0d | /data/p3BR/R1/benchmark/startCirq58.py | a2b36467a64bf7e0413c3647fae2acfbe412bd39 | [
"BSD-3-Clause"
] | permissive | UCLA-SEAL/QDiff | ad53650034897abb5941e74539e3aee8edb600ab | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | refs/heads/main | 2023-08-05T04:52:24.961998 | 2021-09-19T02:56:16 | 2021-09-19T02:56:16 | 405,159,939 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,870 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=3
# total number=12
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
#thatsNoCode
from cirq.contrib.svg import SVGCircuit
# Symbols for the rotation angles in the QAOA circuit.
def make_circuit(n: int, input_qubit):
c = cirq.Circuit() # circuit begin
c.append(cirq.H.on(input_qubit[0])) # number=1
c.append(cirq.rx(-0.09738937226128368).on(input_qubit[2])) # number=2
c.append(cirq.H.on(input_qubit[1])) # number=3
c.append(cirq.H.on(input_qubit[0])) # number=9
c.append(cirq.CZ.on(input_qubit[1],input_qubit[0])) # number=10
c.append(cirq.H.on(input_qubit[0])) # number=11
c.append(cirq.CNOT.on(input_qubit[1],input_qubit[0])) # number=5
c.append(cirq.X.on(input_qubit[1])) # number=6
c.append(cirq.Z.on(input_qubit[1])) # number=8
c.append(cirq.X.on(input_qubit[1])) # number=7
# circuit end
c.append(cirq.measure(*input_qubit, key='result'))
return c
def bitstring(bits):
return ''.join(str(int(b)) for b in bits)
if __name__ == '__main__':
qubit_count = 4
input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]
circuit = make_circuit(qubit_count,input_qubits)
circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')
circuit_sample_count =2000
simulator = cirq.Simulator()
result = simulator.run(circuit, repetitions=circuit_sample_count)
frequencies = result.histogram(key='result', fold_func=bitstring)
writefile = open("../data/startCirq58.csv","w+")
print(format(frequencies),file=writefile)
print("results end", file=writefile)
print(circuit.__len__(), file=writefile)
print(circuit,file=writefile)
writefile.close() | [
"wangjiyuan123@yeah.net"
] | wangjiyuan123@yeah.net |
43c44c76892f9eaaf27193ca1ea271b4b2c3452f | 2671665b2b03f627bf9027b65359eafb84e78263 | /test.py | d49190d41de135817429ad2f3c7d0f7361107760 | [] | no_license | pawelsz99/QuidditchAssessment | db1ece57f70f053953e37ff6b42f80bcb2e276f1 | 99a52542b2f27670bf98e00864ec2bc23d475c7e | refs/heads/main | 2023-02-02T11:55:41.459212 | 2020-12-17T21:34:02 | 2020-12-17T21:34:02 | 318,354,836 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 87 | py | table = [[1,2,3,4],
[5,6,7,8],
[9,10,11,12]]
print(str(table[1][2])) | [
"52848605+pawelsz99@users.noreply.github.com"
] | 52848605+pawelsz99@users.noreply.github.com |
7edafadac071aafea52ebcfe79f924215a9c522e | dd7740c0ce248fdafbfd009c31e258a7e891797c | /migrations/versions/cccf1c4ea739_.py | b80a4e7c7c8ae0605a44834670a21a89c6cef260 | [] | no_license | Vidal23/info3180-project2 | a547f832a306339968e37dd0f02d046525b7a9fd | e5ece20d2cc6687b5694c7e8028e02bbda7f37a4 | refs/heads/master | 2020-03-13T18:36:42.447833 | 2018-04-30T03:41:17 | 2018-04-30T03:41:17 | 131,238,341 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,509 | py | """empty message
Revision ID: cccf1c4ea739
Revises:
Create Date: 2018-04-27 04:01:59.732518
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'cccf1c4ea739'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('users',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(length=80), nullable=True),
sa.Column('password', sa.String(length=255), nullable=True),
sa.Column('firstname', sa.String(length=80), nullable=True),
sa.Column('lastname', sa.String(length=80), nullable=True),
sa.Column('gender', sa.String(length=10), nullable=True),
sa.Column('email', sa.String(length=255), nullable=True),
sa.Column('location', sa.String(length=100), nullable=True),
sa.Column('biography', sa.String(length=255), nullable=True),
sa.Column('profile_photo', sa.String(length=80), nullable=True),
sa.Column('joined_on', sa.String(length=20), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('follows',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('follower_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['follower_id'], ['users.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('posts',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('photo', sa.String(length=80), nullable=True),
sa.Column('caption', sa.String(length=255), nullable=True),
sa.Column('created_on', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('likes',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('post_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['post_id'], ['posts.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('likes')
op.drop_table('posts')
op.drop_table('follows')
op.drop_table('users')
# ### end Alembic commands ###
| [
"vidalrm94@gmail.com"
] | vidalrm94@gmail.com |
aa886a213c5f135a412aba43490ad62764c40613 | 33836016ea99776d31f7ad8f2140c39f7b43b5fe | /fip_collab/2017_02_24_HCF_pearson/get_linkage_alt.py | 81760c80d5b2307eb97b7f5b1d063001511737ce | [] | no_license | earthexploration/MKS-Experimentation | 92a2aea83e041bfe741048d662d28ff593077551 | 9b9ff3b468767b235e7c4884b0ed56c127328a5f | refs/heads/master | 2023-03-17T23:11:11.313693 | 2017-04-24T19:24:35 | 2017-04-24T19:24:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,035 | py | import numpy as np
import functions as rr
import reg_functions as rf
from constants import const
from scipy.stats import pearsonr
import h5py
import time
from sklearn.preprocessing import PolynomialFeatures
def analysis(X, response_tot, groups, iscal):
RpredCV = rf.cv(X[iscal, :], response_tot[iscal], groups[iscal])
coef = rf.regression(X[iscal, :], response_tot[iscal])
Rpred = rf.prediction(X, coef)
return coef, RpredCV, Rpred
def pearson_eval(X, y):
Nfeat = X.shape[1]
pvec = np.zeros((Nfeat,))
# pvec[0] = 1 # for the constant term
for ii in xrange(Nfeat):
""" pearsonr returns tuples with the pearson correlation
and the P-value (chance of observing the data
if the null hypothesis is true). I'm going to throw away
the p-value"""
if np.all(X[:, ii] == 1):
pvec[ii] = 1
else:
pvec[ii] = pearsonr(X[:, ii], y)[0]
return pvec
def optimal_set(X, y, names):
C = const()
Nfeat = X.shape[1]
"""obtain pearson correlation scores against the response variable"""
pvec = pearson_eval(X, y)
indxv_ = np.argsort(np.abs(pvec))[::-1]
pvec_f = np.zeros((C['fmax'],))
names_f = np.zeros((C['fmax'],), dtype="S20")
support = np.zeros((Nfeat,), dtype='bool')
indxv = np.zeros((C['fmax']), dtype='int32')
"""start by adding zero vector"""
pvec_f[0] = pvec[indxv_[0]]
names_f[0] = names[indxv_[0]]
indxv[0] = indxv_[0]
"""add vector with highest pearson correlation besides the zero vector"""
pvec_f[1] = pvec[indxv_[1]]
names_f[1] = str(names[indxv_[1]])
support[indxv_[1]] = True
indxv[1] = indxv_[1]
c = 1
for ii in xrange(2, C['fmax']):
pvecA = np.ones((ii,))
while True:
c += 1
pvecT = pearson_eval(X[:, support], X[:, indxv_[c]])
pvecA = np.abs(pvecT)
# if pvecA.max() < 0.6:
if pvecA.max() < 1.6:
break
# print str(c) + ', ' + str(np.argmax(pvecA)) + ', ' + str(pvecA.max())
pvec_f[ii] = pvec[indxv_[c]]
names_f[ii] = names[indxv_[c]]
support[indxv_[c]] = True
indxv[ii] = indxv_[c]
"""we add support for the vector of ones at the end to not screw up the
calculation"""
support[indxv_[0]] = True
return pvec_f, names_f, support, indxv
def preanalysis(loc_tot, cov_tot):
npc = loc_tot.shape[1]
ns = loc_tot.shape[0]
"""extract names from mean loc info"""
mean_only_names = []
for ii in xrange(npc):
mean_only_names += ['m%s' % str(ii+1)]
"""extract variance info from covariance matrix"""
var_only = np.zeros((ns, npc))
var_only_names = []
for ii in xrange(npc):
var_only[:, ii] = cov_tot[:, ii, ii]
var_only_names += ['c%s_%s' % (str(ii+1), str(ii+1))]
"""extract unique, off-diagonal co-variance info from
covariance matrix"""
nc = (npc**2-npc)/2
cov_only = np.zeros((ns, nc))
cov_only_names = []
c = 0
for ii in xrange(npc):
for jj in xrange(ii+1, npc):
cov_only[:, c] = cov_tot[:, ii, jj]
cov_only_names += ['c%s_%s' % (str(ii+1), str(jj+1))]
c += 1
return loc_tot, var_only, cov_only, \
mean_only_names, var_only_names, cov_only_names
def get_poly(X_pre, names_pre):
C = const()
"""get the polynomial features"""
poly = PolynomialFeatures(C['deg_max'])
poly.fit(X_pre)
X = poly.transform(X_pre)
"""get the names of the polynomial features"""
names = poly.get_feature_names(names_pre)
return X, names
def prepare(par):
np.random.seed(0)
C = const()
p = C['n_sc']
f_link = h5py.File("sample_L%s.hdf5" % C['H'], 'r')
"""gather the calibration data"""
n_tot = len(C['sid'])
ns_tot = n_tot*p
groups = np.zeros(ns_tot, dtype='int16')
response_tot = np.zeros(ns_tot, dtype='float64')
loc_tot = np.zeros((ns_tot, C['n_pc_max']), dtype='float64')
cov_tot = np.zeros((ns_tot, C['n_pc_max'], C['n_pc_max']), dtype='float64')
iscal = np.zeros((ns_tot,), dtype='bool')
c = 0
for ii in xrange(n_tot):
c_ = c + p
sid = C['sid'][ii]
"""flag elements of the calibration set"""
if sid in C['sid_cal']:
iscal[c:c_] = True
groups[c:c_] = 2*ii+np.round(np.random.random((p,)))
dset_name = "%s_%s" % (par, sid)
response_tot[c:c_] = f_link.get(dset_name)[...]
tmp = f_link.get('samp_%s' % sid)[:, :, :C['n_pc_max']]
loc_tot[c:c_, :] = np.mean(tmp, 1)
for jj in xrange(p):
cov_tot[c+jj, ...] = np.cov(tmp[jj, ...], rowvar=False)
c = c_
f_link.close()
return groups, response_tot, loc_tot, cov_tot, iscal
def linkage(par):
st = time.time()
C = const()
p = C['n_sc']
n_tot = len(C['sid'])
ns_tot = n_tot*p
"""create arrays required for linkage creation"""
precursors = prepare(par)
groups = precursors[0]
response_tot = precursors[1]
loc_tot = precursors[2]
cov_tot = precursors[3]
iscal = precursors[4]
f_reg = h5py.File("regression_results_L%s.hdf5" % C['H'], 'a')
f_reg.create_dataset('Rsim_%s' % par, data=response_tot)
f_reg.create_dataset('iscal_%s' % par, data=iscal)
coef_set = f_reg.create_dataset('coef_%s' % par,
(C['fmax'], C['fmax']),
dtype='float64')
Rpred_set = f_reg.create_dataset('Rpred_%s' % par,
(C['fmax'], ns_tot),
dtype='float64')
RpredCV_set = f_reg.create_dataset('RpredCV_%s' % par,
(C['fmax'],
p*len(C['sid_cal'])),
dtype='float64')
"""get the polynomial features"""
tmp = preanalysis(loc_tot, cov_tot)
var_only = tmp[1]
cov_only = tmp[2]
mean_only_names = tmp[3]
var_only_names = tmp[4]
cov_only_names = tmp[5]
# X_pre = np.concatenate((loc_tot, var_only, cov_only), axis=1)
# names_pre = mean_only_names + var_only_names + cov_only_names
# X_pre = np.concatenate((loc_tot, var_only), axis=1)
# names_pre = mean_only_names + var_only_names
X_pre = loc_tot
names_pre = mean_only_names
f_reg.create_dataset('featurenames_%s' % par, data=names_pre)
X, names = get_poly(X_pre, names_pre)
print "# deg1 features: " + str(len(names_pre))
print "# higher deg features: " + str(len(names))
"""perform the pearson correlation"""
pvec, names_f, support, indxv = optimal_set(X[iscal, :], response_tot[iscal], names)
f_reg.create_dataset('scores_%s' % par, data=pvec)
f_reg.create_dataset('indxsel_%s' % par, data=indxv)
"""select the most highly correlated features"""
Xp = X[:, indxv]
# import matplotlib.pyplot as plt
# plt.plot(np.arange(pvec.size), np.abs(pvec))
# plt.show()
msg = "\ntop 20 scoring features"
rr.WP(msg, C['wrt_file'])
for ii in xrange(20):
msg = "%s: %s" % (names_f[ii], pvec[ii])
rr.WP(msg, C['wrt_file'])
"""create and evaluate the final linkages"""
meanc = np.abs(response_tot[iscal]).mean()
for ii in xrange(C['fmax']):
coef, RpredCV, Rpred = analysis(Xp[:, :(ii+1)], response_tot,
groups, iscal)
coef_set[ii, :] = 0
coef_set[ii, :(ii+1)] = coef
RpredCV_set[ii, :] = RpredCV
Rpred_set[ii, :] = Rpred
err = np.mean(np.abs(RpredCV - response_tot[iscal]))/meanc
msg = "%s features: cv.mean(): %s" % (str(ii+1), str(err))
rr.WP(msg, C['wrt_file'])
f_reg.close()
timeE = np.round(time.time()-st, 1)
msg = "regressions and cross-validations completed: %s s" % timeE
rr.WP(msg, C['wrt_file'])
if __name__ == '__main__':
par = 'mu'
linkage(par)
| [
"noahhpaulson@gmail.com"
] | noahhpaulson@gmail.com |
cfcf4c4c948d02a6254d41f9f56773077bb97583 | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/59/usersdata/201/47100/submittedfiles/testes.py | ffc9bae8827fb40a5106a1cf09f62f630d98ad23 | [] | no_license | rafaelperazzo/programacao-web | 95643423a35c44613b0f64bed05bd34780fe2436 | 170dd5440afb9ee68a973f3de13a99aa4c735d79 | refs/heads/master | 2021-01-12T14:06:25.773146 | 2017-12-22T16:05:45 | 2017-12-22T16:05:45 | 69,566,344 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 288 | py | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
r=float(input('Quanto ganha por hora:'))
h=float(input('Horas trabalhadas no mês:'))
t=r*t
print('%.2f' %t)
inss=0.08:
i=inss*t
print('Desconto do INSS:' '%.2f' %i)
sind=0.05:
j=sind*t
print('Desconto do sindicato:' '%.2f' %j)
| [
"rafael.mota@ufca.edu.br"
] | rafael.mota@ufca.edu.br |
eefa5d64c63fa80ea4cdb7c8006e5524cd516256 | 0e59ea03cf8c0914c4a4dcb39f0ff2d2c9bb1b6f | /userRecommendation/models.py | 68aa3ed97156e0cd549e577c7fc84305dfddfa92 | [] | no_license | mohamadgamalali/E-Learning-wep-app-Recommendations | 7f22697fdf8022b82a544817f5168d36027553e5 | 0ffc4fa25f457ccdc5acc1897c111a55425aa668 | refs/heads/master | 2020-04-29T13:14:08.596215 | 2019-04-29T20:14:27 | 2019-04-29T20:14:27 | 176,164,423 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 601 | py | from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
class Users (models.Model):
userId = models.CharField(max_length=250)
userName = models.CharField(max_length=250)
userInterest = models.CharField(max_length=250)
userSkillScore = models.IntegerField(
default=0,
validators=[
MaxValueValidator(10),
MinValueValidator(0)
]
)
def __str__(self):
return self.userId + ' - ' + self.userName + ' - ' + self.userInterest + ' - ' + str(self.userSkillScore)
| [
"noreply@github.com"
] | mohamadgamalali.noreply@github.com |
97a91cebc68f16b3735bd9455e75512bcbc5e513 | 03dff6bd4aca74983640cc1edb059c3d5c9aac2e | /tushare/Report/MC-T.py | 3f7510a63db77b2f3d7f13f258388eb633304dc8 | [] | no_license | aboluo67/Stock | 365c69404d45973a34e8cd4c5c399db002c27928 | 4b7a92e4c948451d8fe73b63f558d9992ba37ad1 | refs/heads/master | 2021-01-17T18:51:55.449691 | 2016-08-18T09:06:35 | 2016-08-18T09:06:35 | 65,879,983 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,744 | py | # -*- coding:utf-8 -*-
# 回测 早晨十字星
# 再加一个第三根K线的 收盘价超第一次的开盘价
#时间问题 停牌问题 停牌因素是否引起计数图形的无效性
import sys
import tick
import schedule
from pymongo import MongoClient
conn = MongoClient('localhost',27017)
data = []
datalist = []
#十字星有红绿 最好第一天跌幅能在input时手动输入%之多少 提示一般为X
#十字星上下影线长度灵活设定 是否上影线越长越好
#----------------------------------------------------------
#---------------------此处修改参数---------------------------
db = conn.db.data2016
start = '2016-08-08'
span = 6
#----------------------------------------------------------
#---------------------此处修改参数---------------------------
print('——*——*——*————*——*——*————*——*——*————*——*——*———*——*——*——')
print('当 K 线 下 行 至 MA15 以 下 时,切 勿 冲 动 买 入 !!!')
print('——*——*——*————*——*——*————*——*——*————*——*——*———*——*——*——')
datalistindex = schedule.schedule.index(start)
for i in range(datalistindex,datalistindex+span):
datalist.append(schedule.schedule[i])
print(datalist)
count = 0
ticklen = len(tick.tick)
for ticki in tick.tick:
for i in range(0,span):
for item in db.find({'dt':datalist[i],'tick':ticki}):
data.append(item)
if data != []:
# 跌幅大于4% 0.04
try:
if (1-round(data[i]['open']/data[i]['close'],2)) < -0.04 :
if data[i+1]['open']>data[i+1]['close']:
# if ((data[i+1]['open']/data[i+1]['close'] - 1) * 100) < 0.5:
count += 1
print('')
print ('No.'),count
# 十字星系数好像有点不对 问题不严重
print ('十字星系数'),round(((data[i+1]['open']/data[i+1]['close'] - 1) * 100),2)
# print ('十字星系数'),round(((data[i]['open']/data[i]['close'] - 1) * 100),2)
print ('%17s' % 'open '),('%7s' % 'close'),('%9s' % '| close')
print data[i]['dt'],\
'%8.2f' % data[i]['open'],\
'%8.2f' % data[i]['close']
print data[i+1]['dt'],\
'%8.2f' % data[i+1]['open'],\
'%8.2f' % data[i+1]['close']
print data[i+2]['dt'],'%8.2f' % data[i+2]['close']
print data[i+3]['dt'],'%8.2f' % data[i+3]['close']
print data[i+4]['dt'],'%8.2f' % data[i+4]['close']
# print data[i+5]['dt'],'%8.2f' % data[i+5]['close']
# print data[i+6]['dt'],'%8.2f' % data[i+6]['close']
# print data[i+7]['dt'],'%8.2f' % data[i+7]['close']
# print data[i+8]['dt'],'%8.2f' % data[i+8]['close']
# print data[i+9]['dt'],'%8.2f' % data[i+9]['close']
print(data[i]['tick']),(' 前一日跌幅为4%以上 今日为早晨十字星 绿')
for i in range(0,len(data)):
print(data[i]['dt']),('%8.2f' % data[i]['close']),('%6d' % (data[i]['vol']/1000))\
,('%6d' % (data[i]['amount']/1000000)),('%27s' % data[i]['macd'])
print ('----------------')
except:pass
del data[:]
print '\r','进度 :',tick.tick.index(ticki),'/',ticklen,
sys.stdout.flush() | [
"zt@feheadline.com"
] | zt@feheadline.com |
e772e008905fd203826a8d141783c1b9e39c1fbf | 7575a0624bd9776adc98228a30fd33d037ec7706 | /scripts/justified_text.py | ad52acc96044bdcf9ac50b79090b2ce78170156f | [] | no_license | leemich/python-practice | 6cf216367c0c94d1aa2a0efad3561abeae361011 | 3895348fa7f4e0cea8f423e28646ad5c58cb3d2a | refs/heads/master | 2021-01-10T08:37:03.100265 | 2015-12-02T20:58:46 | 2015-12-02T20:58:46 | 47,045,999 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,437 | py | # Examples of justified and centered text
print('''
LEFT AND RIGHT JUSTIFIED TEXT
------------------------------
The 1st argument passed to the ljust() or rjust() methods
is the total length of the string to be printed.
A string 5 chars long with .rjust(10) called on it
will move the string to the right with 5 whitespace chars
to the left of it in a string with a total of 10 chars.
For example, the following code:
spam = 'Hello'
print(spam.rjust(10))
print(spam.rjust(20))
print(spam.ljust(15))
will print:
''')
spam = 'Hello'
print(spam.rjust(10))
print(spam.rjust(20))
print(spam.ljust(15))
print()
print('----------------------------------')
print()
print('''A second argument can be passed to fill the space with a
char other than white space. Examples:
print(spam.rjust(10, '.'))
print(spam.rjust(20, '*'))
print(spam.ljust(15, '~'))
This prints:
''')
print(spam.rjust(10, '.'))
print(spam.rjust(20, '*'))
print(spam.ljust(15, '~'))
print()
print()
print('''
CENTERING TEXT
---------------
The center() method works just like the ljust() and rjust()
methods, except it (surprise!) centers the text.
For example, the following code:
print(spam.center(20))
print()
print(spam.center(20, '.'))
returns the following:
''')
print(spam.center(20))
print()
print(spam.center(20, '.'))
print()
print('''As you can see, the center() method can also take a
second argument which designates the character to be used to
fill the space.
--------------------------------------------
USING JUSTIFY TO PRINT TABULAR DATA
You can use justified text to neatly print data in a table.
For example:
def printPicnic(itemsDict, leftWidth, rightWidth):
print('PICNIC ITEMS'.center(leftWidth + rightWidth, '-'))
for k, v in itemsDict.items():
print(k.ljust(leftWidth, '.') + str(v).rjust(rightWidth, '.'))
picnicItems = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000}
printPicnic(picnicItems, 12, 5)
print()
printPicnic(picnicItems, 20, 6)
This is what the code looks like when it's executed:
''')
def printPicnic(itemsDict, leftWidth, rightWidth):
print('PICNIC ITEMS'.center(leftWidth + rightWidth, '-'))
for k, v in itemsDict.items():
print(k.ljust(leftWidth, '.') + str(v).rjust(rightWidth, '.'))
picnicItems = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000}
printPicnic(picnicItems, 12, 5)
print()
printPicnic(picnicItems, 20, 6)
| [
"inthedeep75@gmail.com"
] | inthedeep75@gmail.com |
51f36d5eee2c943cd5c30badff1530044ab2b26f | 4891d71a1c0c3ec23f7c0f5d2bd686107373fe6c | /ninjafruits/__init__.py | bd8fcde5e58f9c36534fef71c0185743368220fb | [] | no_license | labesoft/top-projects | 23bf2b0ebf79589af09112233656585ec630272c | 7806b2121dc918f9877c597854b94d0a1273a284 | refs/heads/main | 2023-05-12T08:59:18.051754 | 2021-05-19T02:22:34 | 2021-05-19T02:23:45 | 312,672,482 | 2 | 1 | null | 2021-03-11T23:16:43 | 2020-11-13T20:05:18 | Python | UTF-8 | Python | false | false | 353 | py | """The Ninja Fruits Game
-----------------------------
Package structure
-----------------
*ninjafruits/*
**__init__.py**:
The Ninja Fruits Game
**__main__.py**:
The Ninja Fruits Game Application
"""
__author__ = "Benoit Lapointe"
__date__ = "2021-03-09"
__copyright__ = "Copyright 2021, Benoit Lapointe"
__version__ = "1.0.0"
| [
"Benoit Lapointe"
] | Benoit Lapointe |
f6f9a3484b589376dce50dd0c6ecf4f88ad23df6 | ac761dc843b7c5f33c310b935d0094160a1cae33 | /Aman/Homework/homework6.py | 7a29540c77b9652d94bf086202b25973bcb49417 | [] | no_license | amanverma15/programing | 147ea7e751d99d0147925d4fc6bae31240e96fbd | fb1a1be2de5394bcd3784b350e271f7898eef729 | refs/heads/master | 2020-09-11T18:07:16.286924 | 2019-11-21T03:01:35 | 2019-11-21T03:01:35 | 222,147,577 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 132 | py | #666666666666666666
a = "fl"
m = len(a)
if m <3:
n = a
elif a[-3:] == "ing":
n = a + "ly"
else:
n = a + "ing"
print(n)
| [
"amanverma15@gmail.com"
] | amanverma15@gmail.com |
3441a0dc6aaf84df0e2f823ddfcc8b0521ddf056 | 2ddd6906e3cd0eeec0f434cfef051976ee808037 | /server/src/gameserver/Log.py | 04a3bc869123096cef373a711b03d93221ae5ea8 | [] | no_license | kongyt/open_world | 905051b8e64bfbfee029a7480933f6d5052e569c | 6db78ed97307fcde38eff38483e9da540ef5a254 | refs/heads/master | 2021-01-22T19:09:18.292956 | 2017-03-16T11:49:19 | 2017-03-16T11:49:19 | 85,172,886 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,344 | py | #coding: utf-8
import logging
import logging.handlers
from Singleton import *
class LogMgr:
# 日志等级
CRITICAL = logging.CRITICAL
ERROR = logging.ERROR
WARNING = logging.WARNING
INFO = logging.INFO
DEBUG = logging.DEBUG
NOTSET = logging.NOTSET
def __init__(self, logfile, level):
self.logfile = logfile
# 实例化handler
self.handler = logging.handlers.RotatingFileHandler('../log/' + self.logfile + '.log', maxBytes = 1014 * 1024, backupCount = 5)
self.fmt = "%(asctime)s - %(levelname)s - %(message)s"
# 实例化formatter
self.formatter = logging.Formatter(self.fmt)
# 为logger添加formatter
self.handler.setFormatter(self.formatter)
# 获取名字为filename的logger
self.logger = logging.getLogger(self.logfile)
# 为logger添加handler
self.logger.addHandler(self.handler)
# 设置日志等级
self.setLevel(level)
def setLevel(self, level):
self.logger.setLevel(level)
def logC(self, msg):
self.logger.critical(msg)
def logE(self, msg):
self.logger.error(msg)
def logW(self, msg):
self.logger.warning(msg)
def logI(self, msg):
self.logger.info(msg)
def logD(self, msg):
self.logger.debug(msg)
| [
"839339849.qq.com"
] | 839339849.qq.com |
5949e5b7b341be84c032621320c353d443f0392e | 555bc4ef39ebdf5d1f62c95f7aa921d6e8ecfa00 | /venv/Scripts/pip-script.py | cf283a460e29d98e6141155d3337aa69c4087b90 | [] | no_license | gitcoder27/DataMining | a482ec46995cec2a85197e47aaf14f865e69264a | 0721683370df17c4050baf940c46044cf40c470d | refs/heads/master | 2020-05-16T19:34:36.089460 | 2019-04-24T16:42:39 | 2019-04-24T16:42:39 | 183,264,371 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 404 | py | #!G:\PycharmProjects\FlaskWebApp2\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==10.0.1','console_scripts','pip'
__requires__ = 'pip==10.0.1'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('pip==10.0.1', 'console_scripts', 'pip')()
)
| [
"ayanmails.saha@gmail.com"
] | ayanmails.saha@gmail.com |
39c206d9346b81a7b5575b98b7e67f9d69263997 | 6d387640952972d7c94904d430f296202ba9ff33 | /Prove/use_fun.py | a21208383823809bd68e9f436d080051cc83d604 | [] | no_license | MrSpadala/Epic_VANET | 25e36593667ab60bed79e2d0eaf2c58606ec2781 | cbd07efc00efa35b48b01ab9548d79bc805af81b | refs/heads/master | 2020-04-05T20:20:44.993142 | 2020-02-23T19:44:01 | 2020-02-23T19:44:01 | 157,175,833 | 1 | 2 | null | null | null | null | UTF-8 | Python | false | false | 1,344 | py | def get_adj(balls, raggio):
adj=[]
for b in balls:
if abs(b.pos - loc) < raggio:
adj.append(b)
def dist(c1, c2):
distx = abs(c1.pos[0] - c2.pos[0])
disty = abs(c1.pos[1] - c2.pos[1])
return sqrt(distx*distx + disty*disty)
def evaluate_positions(messages, my_pos): # 1 messaggio solo ## valuta se mandare in broadcast o no
quads = [0,0,0,0] # flags dei quadranti: 0 quadrante inesplorato, 1 quadrante esplorato
# abbiamo scelto quadranti divisi da una X dalla nostra posizione
for m in messages:
if quads[0]!=1:
if m.emit[0]>my_pos[0] and my_pos[1]-(abs((my_pos[0]-m.emit[0])/2)) <= m.emit[1] <= my_pos[1]-(abs((my_pos[0]-m.emit[0])/2)): # X > myX dx
quads[0]=1
if quads[1]!=1:
if m.emit[1]>my_pos[1] and (my_pos[0]-(abs((my_pos[1]-m.emit[1])/2)) <= m.emit[0] <= my_pos[0]-(abs((my_pos[1]-m.emit[1])/2))): # Y > myY su
quads[1]=1
if quads[2]!=1:
if m.emit[0]<my_pos[0] and (my_pos[1]-(abs((my_pos[0]-m.emit[0])/2)) <= m.emit[1] <= my_pos[1]-(abs((my_pos[0]-m.emit[0])/2))): # X < myX sx
quads[2]=1
if quads[3]!=1:
if m.emit[1]<my_pos[1] and (my_pos[0]-(abs((my_pos[1]-m.emit[1])/2)) <= m.emit[0] <= my_pos[0]-(abs((my_pos[1]-m.emit[1])/2))): # Y < myY giu
quads[3]=1
print("Decidendo...")
if quads==[1,1,1,1]:
return False
else:
return True
| [
"pconti97@libero.it"
] | pconti97@libero.it |
c1a2840663bccc8c210735f777cffa3f4fbd0c8b | f4ae1e15068cf5e9952a16ff49a33a868fc4dbee | /lol.py | d97556f9b83bac6495927a77e68566869930bab4 | [] | no_license | jmurrayufo/Scripting-Fun | 1bd415d9378a5727e5190eca9ddc1bf85661ca78 | 29eb6e53b34e48bdad8a6cc65315cf86ca92b956 | refs/heads/master | 2019-01-19T11:23:52.721303 | 2013-07-26T22:10:57 | 2013-07-26T22:10:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,846 | py | import random
import json
items = [
["an Abyssal Scepter", 2650],
["an Aegis of the Legion", 2150],
["an Atma's Impaler", 2300],
["a Banner of Command", 2400],
["a Banshee's veil", 2500],
["a Bilgewater Cultlass", 1925],
["an Executioner's calling", 1900],
["a Guardian Angel", 2600],
["a Guinsoo's Rageblade", 2600],
["a Hextech Sweeper(dominion/TT)", 1920],
["a Kitae's Bloodrazor(dominion/tt)", 2525],
["a Last Whisper", 2135],
["a Locket of the Iron Solari", 2000],
["a Malady", 2035],
["a Manamune", 2100],
["a Mikael's Crucible", 2200],
["a Morellonomicon", 2200],
["a Nashor's tooth", 2500],
["an Odyn's veil(Dominion/TT)", 2610],
["an Overlord's bloodmail", 2455],
["a Rod of Ages", 2800],
["a Shard of True Ice", 1700],
["a Shurelya's Reverie", 2100],
["a Spirit Visage", 2200],
["a Spirit of the Ancient Golem", 2400],
["a Spirit of the Elder Lizard", 2400],
["a Spirit of the Spectral Wraith", 2400],
["a Statikk Shiv", 2500],
["a Sunfire Cape", 2500],
["a Sword of the Divine", 2200],
["a Brutalizer", 1337],
["a Thornmail", 2200],
["a Tiamat", 2300],
["a Twin Shadows", 1900],
["a Void Staff", 2295],
["a Warmog's Armor", 2650],
["a Wicked Hatchet", 2840],
["a Will of the Ancients", 2500],
["a Wit's end", 2200],
["a Zeke's Herald", 2450]
]
choices = [ "All Yordle",
"All AD Carry",
"All Mid",
"All AP Carry",
"Jungle Fever",
"All Human",
"No Humans",
"No Mana",
"Alphabet",
"All Support",
"Fill Dorians",
"No Boots",
"No Consumables",
"Pick Item",
"SwapAKill",
"Keep It Full!",
"Max Lead",
"Deadly Aces",
"Unique Shoes",
"Follow the Leader",
"Opposite Day",
"Low Mobility"]
def LoadChampList():
champions = json.load(open("lolChamps.json",'r'))
return champions
while(1):
result = random.choice(choices)
print "Rules:",result
if(result=="Alphabet"):
print "You must spell something out!"
elif(result=="Fill Dorians"):
print "Only boots/dorians items until inventory is full, then may proceed with normal build"
elif(result=="Pick Item"):
Item = random.choice(items)
print "Everyone MUST build %s by %d minutes."%(Item[0], Item[1]/96+1+1.5+3)
elif(result=="SwapAKill"):
print "Every time you get a kill, you you must swap to a new lane (your choice)"
elif(result=="Keep It Full!"):
print "Never leave the summoners platform will more empty inventory spaces then when you got there."
elif(result=="Max Lead"):
print "You may not push towers while your team is 5 or more kills ahead"
elif(result=="Deadly Aces"):
print "If you score an ace, all alive players MUST rush the enemy summoners platform and die there if they reach it."
elif(result=="Unique Shoes"):
print "Everyone must have a unique level 2+ set of boots, no duplicates!"
elif(result=="Follow the Leader"):
player = [1,2,3,4,5]
minmark = [10,11,12,13,14,15,16,17,18,19,20]
print "After the %d minute mark, everyone must follow player number %d" %(random.choice(minmark),random.choice(player))
elif(result=="Opposite Day"):
print "Randomly select a champion and build them for the opposite role they usually take"
elif(result=="Low Mobility"):
print "No flash, No ghost, No champions with gap closers/escapes"
elif(result=="Jungle Fever"):
junglelist = [1,2,3,4,5,6,7,8,9,10]
jungle = random.choice(junglelist)
if jungle >=8:
print "Champions can only leave the jungle while everything in it is dead... in both jungles"
else:
print "Champions can only leave your jungle while everything in it is dead"
raw_input("Press enter to reroll, or CTRL+C to exit\n")
| [
"jmurrayufo@gmail.com"
] | jmurrayufo@gmail.com |
b43f0cb071ff13433819472540aee03848bcc18f | c6b0bd512380cfd7c22bbec13d35fff01bcba8c7 | /BuildingDepot-v3.2.8/buildingdepot/DataService/app/service/forms.py | 62434e90dd0e3c2b415ec29de0b368d5c538a5d4 | [
"MIT"
] | permissive | Entromorgan/GIoTTo | 515f83b5ef8ffaf4d5dbb0d495bc3d9afe324478 | 53ba7519c56d46af1e32a77aab5cf1c5cd8143fc | refs/heads/master | 2020-04-24T14:17:19.334845 | 2019-05-09T08:56:18 | 2019-05-09T08:56:18 | 172,015,746 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 852 | py | """
DataService.form
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Contains the definitions for all the forms that will be shown to the user
in the frontend of the DataService.
@copyright: (c) 2016 SynergyLabs
@license: UCSD License. See License file for details.
"""
from flask_wtf import Form
from wtforms import StringField, SelectMultipleField, SubmitField, SelectField, BooleanField
from wtforms.validators import DataRequired
class SensorForm(Form):
source_name = StringField('Source Name')
source_identifier = StringField('Source Identifier')
building = SelectField('Building', validators=[DataRequired()])
submit = SubmitField('Submit')
class PermissionQueryForm(Form):
user = StringField('User Email', validators=[DataRequired()])
sensor = StringField('Sensor ID', validators=[DataRequired()])
submit = SubmitField('Submit')
| [
"entro_morgan@foxmail.com"
] | entro_morgan@foxmail.com |
a673ae74e63f1b12a6b009519c144970596c84e9 | 34d376b512e03142d5592ab69da374090822a30d | /run.py | d9a97cbcbe63f61aac6db873866f39815683a1f1 | [] | no_license | Arthur-ext/googlemaps-flask | 6c11fc61f4f7e1c92280f3ade42ae0ce247a3935 | 5e00c54421290d5e8e0531de9198402cf455de8a | refs/heads/master | 2023-05-26T05:18:14.688275 | 2020-02-11T07:21:01 | 2020-02-11T07:21:01 | 239,700,309 | 0 | 0 | null | 2023-05-22T22:40:39 | 2020-02-11T07:18:36 | Python | UTF-8 | Python | false | false | 308 | py | from flask import Flask
def create_app(config_filename):
app = Flask(__name__)
app.config.from_object(config_filename)
from app import api_bp
app.register_blueprint(api_bp, url_prefix="/api")
return app
if __name__ == "__main__":
app = create_app('config')
app.run(debug=True) | [
"arthur.ext@gmail.com"
] | arthur.ext@gmail.com |
d712a1e82bfad9c49a7b16248e8cae4e4a6aafa2 | a4c710fd7d4ea02d90fe8ad1c8dc7b9038cb0e8f | /DATABASES AND PYTHON CHALLENGE.py | b4225a85feb92c8b24372877bdc7cb19ef333b33 | [] | no_license | JacobDrawhorn/Python_Projects | 35d6ef89a3d0e2141c4152a523897319847a36d1 | b6f09b4140e847d0f1305d6010a9186da588fc22 | refs/heads/main | 2023-08-18T16:25:12.954481 | 2021-10-11T15:50:08 | 2021-10-11T15:50:08 | 400,966,017 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 739 | py | import sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.executescript("""
CREATE TABLE Roster(
Name,
Species,
IQ
);
insert into Roster(Name, Species, IQ)
values (
'Jean-Baptiste Zorg',
'Human',
122
);
insert into Roster(Name, Species, IQ)
values (
'Korben Dallas',
'Meat Popsicle',
100
);
insert into Roster(Name, Species, IQ)
values (
'Aknot',
'Mangalore',
-5
);
UPDATE Roster SET Species = 'Human' WHERE Name = 'Korben Dallas';
""")
cur.execute("SELECT Name, IQ FROM Roster WHERE Species = 'Human'")
for row in cur.fetchall():
print(row)
con.close()
| [
"jake.drawhorn@gmail.com"
] | jake.drawhorn@gmail.com |
c8e5d4e8bd9bc5c8d7eead694c4cb58c94bb18f9 | f9cc00ae34c87191f1e16d567742b55878a151cc | /src/kafka_producer/kafka_producer.py | 6ab3365f89e37feb85c3b11612b4eff5febfb61e | [] | no_license | IABcb/DataVisualization | f81ebd5834f596928d9fe15f0d96ebccf8b6d129 | e033c1784502ac948ac9c842add577420a1cd7b4 | refs/heads/master | 2021-01-22T22:34:20.048198 | 2017-06-28T15:27:03 | 2017-06-28T15:27:03 | 92,777,633 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,907 | py | from kafka import KafkaProducer
from pykafka import KafkaClient
import random
from time import sleep
import sys, os
if __name__=="__main__":
try:
print("Initialization...")
# producer = KafkaProducer(bootstrap_servers='172.20.1.21:9092')
producer = KafkaProducer(bootstrap_servers='127.0.0.1:9092')
print("Sending messages to kafka 'test' topic...")
sleep_time = 0.5
topic = "visualization"
filename = "/home/raul/GIT/DataVisualization/data/final_data/final_data.csv"
# client = KafkaClient(hosts="127.0.0.1:9092")
# topic = client.topics[b'visualization']
# producer = topic.get_sync_producer()
f = open(filename, 'rt')
try:
for line in f:
dic_data = {}
line_list = line.split(",")
dic_data["Date"] = line_list[0]
dic_data["EEUU_DJI"] = line_list[1]
dic_data["UK_LSE"] = line_list[2]
dic_data["Spain_IBEX35"] = line_list[3]
dic_data["Japan_N225"] = line_list[4]
dic_data["EEUU_Unem"] = line_list[5]
dic_data["UK_Unem"] = line_list[6]
dic_data["Spain_Unem"] = line_list[7]
dic_data["Japan_Unem"] = line_list[8][:-1]
print(dic_data)
producer.send(topic, bytes(str(dic_data), 'utf8'))
# producer.produce(str(dic_data).encode(encoding='UTF-8'))
sleep(sleep_time)
# sleep(random.uniform(float(low), float(high)))
finally:
f.close()
# print("Waiting to complete delivery...")
# producer.flush()
# print("End")
except KeyboardInterrupt:
print('Interrupted from keyboard, shutdown')
try:
sys.exit(0)
except SystemExit:
os._exit(0)
| [
"raul.sanchez.martin@bbva.com"
] | raul.sanchez.martin@bbva.com |
0b0c8c6dce2928daeb4bcff7cea36904a6afd59e | de7fac293d510e9dd5ace543a1cd6c66f49037de | /FUNDAMENTOS-PROGRAMACION/03 Entrada_Teclado/Entrada_Teclado.py | 99c51bbfe2dad1d9b6358e348df7ff934446793a | [] | no_license | Champiiy/CURSO-PYTON | 4dcf4747868371cec7fc9e82ab320cea6eb9702d | 36d5f002251ff8f196efa0a343bbff2f918386f6 | refs/heads/master | 2020-06-15T12:54:54.357902 | 2019-07-04T22:14:02 | 2019-07-04T22:14:02 | 195,305,274 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 81 | py | print("INGRESE SU NOMBRE")
nombre = input()
print("Hola", nombre, "como estas")A | [
"ballina.santiago@gmail.com"
] | ballina.santiago@gmail.com |
59fb1b9942445e327401295b33931bbb8d4aa432 | 9dd2bc9409bcdd7749cf0bad79092cd204200eb5 | /examples/rest/crypto-last_trade_for_a_crypto_pair.py | 850bd98aee0db35f396796a62e34ab79f525f5f3 | [
"MIT"
] | permissive | polygon-io/client-python | b36ccdd380fdf4b9ec344c3e9d43eaab0ce313cc | 195d3a2894b979c4ad86c6bd170b674e09c30d9d | refs/heads/master | 2023-08-29T12:04:36.823546 | 2023-08-28T16:19:25 | 2023-08-28T16:19:25 | 216,660,192 | 574 | 189 | MIT | 2023-09-11T19:50:33 | 2019-10-21T20:33:17 | Python | UTF-8 | Python | false | false | 387 | py | from polygon import RESTClient
# docs
# https://polygon.io/docs/crypto/get_v1_last_crypto__from___to
# https://polygon-api-client.readthedocs.io/en/latest/Trades.html#get-last-crypto-trade
# client = RESTClient("XXXXXX") # hardcoded api_key is used
client = RESTClient() # POLYGON_API_KEY environment variable is used
trade = client.get_last_crypto_trade("BTC", "USD")
print(trade)
| [
"noreply@github.com"
] | polygon-io.noreply@github.com |
34b4e482e8a9d31e87aea08955734b27f5530ad1 | ec792d6a49fe56e714a9051a5fce18de23a9d78c | /dupidup/tests/testview.py | 12d4e70ad23090c3dc8fbcd1fb3b5602d87c8ea2 | [] | no_license | mlinhard/dupidup | 7d5d0fb80a8755ed3b6411c5678b4fa9e5b5e31d | 278c57c49a6958e74f417cefde3dbc5c95cc4487 | refs/heads/master | 2020-07-28T18:26:42.258423 | 2019-09-19T08:01:26 | 2019-09-19T08:01:26 | 209,493,072 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,491 | py | '''
Created on 18 Sep 2019
@author: mlinhard
'''
from magicur.screen import MagicWindow
class TestMagicWindow(MagicWindow):
def __init__(self, width, height, x, y):
self._x, self._y = x, y
self._width, self._height = width, height
self.line = None
self.reset_to(" ", None)
self.children = []
def put_text(self, x, y, text):
if x >= self._width:
raise Exception(f"Can't put text at x={x}, width={self._width}")
if y >= self._height:
raise Exception(f"Can't put text at y={y}, height={self._height}")
old = self.line[y]
new = old[:x] + text[:self._width - x] + old[x + len(text):self._width]
self.line[y] = new
if len(text) + x > self._width and y + 1 < self._height:
self.put_text(0, y + 1, text[self._width - x:])
def set_paint(self, x, y, length, color_pair_key):
pass
def reset_to(self, char, color_pair_key):
self.line = [char * self._width for _ in range(self._height)]
def sub_window(self, width, height, x, y):
child = TestMagicWindow(width, height, x, y)
self.children.append(child)
return child
def refresh(self):
pass
def size(self):
return self._width, self._height
@property
def width(self):
return self._width
@property
def height(self):
return self._height
def contents(self):
return "\n".join(self.line) + "\n"
| [
"michal.linhard@gmail.com"
] | michal.linhard@gmail.com |
e116473f7e025c8ca3ef0ab00ab01b268e68821d | 7874e27637a5956c841fa6a2f6f60494daf97437 | /ch03/pandas_Ch03_log.py.py | 92716aeaf0f92a12189c3d86c4bc8d20d128490a | [] | no_license | mithegooie/pydata-book | 00cb1848de74ec7a3d2ee48a7948be9752470530 | 39d127a4f662283cafd01b49118035da90973746 | refs/heads/master | 2021-01-21T02:41:45.267096 | 2014-07-11T05:17:12 | 2014-07-11T05:17:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,474 | py | # IPython log file
import datetime
get_ipython().magic(u'who ')
get_ipython().magic(u'who int')
get_ipython().magic(u'logstart ')
get_ipython().magic(u'logon ')
a = 5
a
b = [1,2,3]
get_ipython().magic(u'pinfo b')
def add_numbers(a,b):
"""
Add two numbers together
Returns
-------
the_sum : type of arguments
"""
return a + b
get_ipython().magic(u'pinfo add_numbers')
get_ipython().magic(u'pinfo2 add_numbers')
import numpy as np
get_ipython().magic(u'psearch np.*load*')
import pandas as pd
get_ipython().magic(u'psearch pd.*')
pd.__version__
get_ipython().magic(u'pinfo pd.__repr__')
get_ipython().magic(u'pinfo2 pd.__repr__')
get_ipython().magic(u'pinfo2 pd.value_counts')
get_ipython().magic(u'pinfo2 pd.Series')
x = 5
x = 5
x = 5
get_ipython().magic(u'paste')
if x > 5:
x += 1
y = 8
get_ipython().magic(u'paste')
x = 5
y = 7
if x > 5:
x += 1
y = 8
get_ipython().magic(u'cpaste')
x = 5
x = 5
x = 5
get_ipython().magic(u'pinfo %logstart')
get_ipython().magic(u'logstart -o -r -t append')
get_ipython().magic(u'logstop')
import datetime
who
who int
logstart
logon
a = 5
a
#[Out]# 5
b = [1,2,3]
b?
def add_numbers(a,b):
"""
Add two numbers together
Returns
-------
the_sum : type of arguments
"""
return a + b
add_numbers?
add_numbers??
import numpy as np
np.*load*?
import pandas as pd
pd.*?
pd.__version__
#[Out]# '0.13.1'
pd.__repr__?
pd.__repr__??
pd.value_counts??
pd.Series??
x = 5
x = 5
x = 5
%paste
%paste
%cpaste
%logstart?
%logstart -o -r -t append
%logstop
%logstart -o -r -t append
a = 1
a
#[Out]# 1
%logstop
# Wed, 21 May 2014 09:08:55
ts = pd.Series(['2012-01-01', '2012-02-01'])
# Wed, 21 May 2014 09:08:56
ts
#[Out]# 0 2012-01-01
#[Out]# 1 2012-02-01
#[Out]# dtype: object
# Thu, 22 May 2014 22:42:54
%pwd
#[Out]# u'C:\\Users\\millerdr\\Documents\\Python Scripts'
# Thu, 22 May 2014 23:01:15
import numpy as np
# Thu, 22 May 2014 23:01:26
from numpy.linalg import eigvals
# Thu, 22 May 2014 23:03:02
def run_experiment(niter=100):
K = 100
results = []
for _ in xrange(niter):
mat = np.random.randn(K, K)
max_eigenvalue = np.abs(eigvals(mat)).max()
results.append(max_eigenvalue)
return results
# Thu, 22 May 2014 23:03:20
some_results = run_experiment()
# Thu, 22 May 2014 23:04:03
print 'Largest one we saw: %s' % np.max(some_results)
# Thu, 22 May 2014 23:06:41
%prun -l 7 -s cumulative run_experiment()
# Thu, 22 May 2014 23:40:41
%logoff
| [
"mithegooie@gmail.com"
] | mithegooie@gmail.com |
8be30f112bcec9339105493e2972fcfac46308e9 | 83d0dada5e6df8ff2205e781a710298eff49f14c | /covidhelp/food/migrations/0001_initial.py | e9baeac3611dea315c0257e41f5c83657f74c098 | [] | no_license | covidhelpin/covidhelp | 9d230be916cf4f589a74487414a1f69157d270bf | e56e304074cd6208d8ce635964fc4c1d77ae776e | refs/heads/main | 2023-04-30T02:58:46.384056 | 2021-05-22T13:39:53 | 2021-05-22T13:39:53 | 360,040,879 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,081 | py | # Generated by Django 3.2 on 2021-05-18 06:09
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='Volunteer',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('phone', models.CharField(max_length=15)),
('pin_code', models.CharField(max_length=10)),
('approved', models.BooleanField(default=False)),
('name', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Donor',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('phone', models.CharField(max_length=15)),
('approved', models.BooleanField(default=False)),
('name', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Customer',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('adhaar', models.CharField(max_length=20)),
('phone', models.CharField(max_length=15)),
('pin_code', models.CharField(max_length=10)),
('tiffin_nos', models.CharField(choices=[('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5')], default='1', max_length=1)),
('approved', models.BooleanField(default=False)),
('name', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| [
"covidhelp.in.website@gmail.com"
] | covidhelp.in.website@gmail.com |
667aa020eb99ac78780a0649c585cfdb3e7113f3 | 2c4ee3cff11310b38fdcc34a58dbc4649f49c5b2 | /01_Basic/25_rotate_img.py | d77d85db415f0d938fecb8ec17af471559f287cf | [] | no_license | HeinHtetOo9/Computer-Vision-and-Machine_Learning | 85dc0e3d899c118e10e1aabbe018b89620cc6724 | 50581d6b23b4521b711edb846d3758eb3edb6763 | refs/heads/main | 2023-08-23T12:09:16.373876 | 2021-10-14T14:59:47 | 2021-10-14T14:59:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 499 | py | #python program to rotate image
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
def main():
img = cv.imread('images/4.2.01.tiff')
img = cv.cvtColor(img,cv.COLOR_BGR2RGB)
rows,cols,channels = img.shape
R = cv.getRotationMatrix2D( (cols/2,rows/2), 90,1) # 1 is for scaling
print(R)
output = cv.warpAffine( img, R, (cols,rows) )
plt.imshow(output)
plt.title('rotating')
plt.show()
if __name__ == "__main__":
main() | [
"heinhtetoo@localhost.localdomain"
] | heinhtetoo@localhost.localdomain |
24e12208404260962acd4db161af5cc91f0d8e2b | e1e0224d12dc82a219230c640c67f649077b0cba | /fta | 03c8873f326a018fa7f1be423e948618f859afad | [] | no_license | vikasjain1402/Find-Text-in-Folder | eaebd921fbd6f26e5c1293019da53cf1919b85e1 | 362f672299910c96d266f8c886c9e9c892befbe4 | refs/heads/master | 2022-06-16T01:50:46.921310 | 2020-05-08T12:15:55 | 2020-05-08T12:15:55 | 262,313,660 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,148 | #!/usr/bin/python3
import os
import sys
def find_text_in_file_in_path(path,text):
os.chdir(path)
for i,j,k in os.walk(path):
for l in k:
filepath=os.path.join(i,l)
try:
f=open(filepath,"r",)
r=f.readlines()
except:
pass
else:
for m in r:
if text in m:
print(i," $$ ",l)
inp=input("need more search Y/N ")
if inp=='N' or inp=='n' :
print ("Thanks!!")
return None
else:
break
if __name__=="__main__":
text=input("Enter file text or phrase you want to Search : ")
while True:
#path=input('Enter Path e.g /Search/this/folder : ')
path=sys.argv[1]
if os.path.exists(path)==True:
find_text_in_file_in_path(path,text)
print("bye")
break
| [
"noreply@github.com"
] | vikasjain1402.noreply@github.com | |
f61c8fb97e99e9fad5eee469844097e78f971738 | 560c22b02c8f759d05c2bf36cf48e94a5fcfa8c3 | /hrk_phd_scrape.py | d06198900eaa9534052408a22c9aff9bff405a28 | [] | no_license | kmvinoth/project_scrape | 1678424616994b3901d30c8d56058316146f8790 | 74f416a25b2b072f44b9e9f8aeb785b93c24418b | refs/heads/master | 2022-12-19T23:25:02.175115 | 2019-01-03T11:26:40 | 2019-01-03T11:26:40 | 160,195,382 | 0 | 0 | null | 2022-12-08T01:19:45 | 2018-12-03T13:29:51 | Python | UTF-8 | Python | false | false | 4,065 | py | import requests
import time
import json
from bs4 import BeautifulSoup
import pandas as pd
# First 100 results
# https://www.hochschulkompass.de/en/degree-programmes/study-in-germany-search/advanced-degree-programme-search/search/1/studtyp/3.html?tx_szhrksearch_pi1%5Bresults_at_a_time%5D=100
# Deatiled information about each course (Learn More button)
# https://www.hochschulkompass.de/en/degree-programmes/study-in-germany-search/advanced-degree-programme-search/detail/all/search/1/studtyp/3.html?tx_szhrksearch_pi1%5Bresults_at_a_time%5D=100
# first_page_url = "https://www.hochschulkompass.de/en/degree-programmes/study-in-germany-search/advanced-degree-programme-search/search/1/studtyp/3.html?tx_szhrksearch_pi1%5Bresults_at_a_time%5D=100"
# remaining_pages_url = "https://www.hochschulkompass.de/en/degree-programmes/study-in-germany-search/advanced-degree-programme-search/search/1/studtyp/3/pn/1.html?tx_szhrksearch_pi1%5Bresults_at_a_time%5D=100"
page_num_list = list(range(1, 9))
url_list_second_page_to_last_page = []
url_list_first_page = ["https://www.hochschulkompass.de/en/doctoral-studies/doctorate-search/search/1.html?tx_szhrksearch_pi1%5Bresults_at_a_time%5D=100"]
""" Construct a list of urls for all the 9 pages """
for num in page_num_list:
url = "https://www.hochschulkompass.de/en/doctoral-studies/doctorate-search/search/1/pn/"+str(num)+".html?tx_szhrksearch_pi1%5Bresults_at_a_time%5D=100"
url_list_second_page_to_last_page.append(url)
url_list = url_list_first_page + url_list_second_page_to_last_page
only_learn_more_links = []
main_dict = {}
counter = 0
# small_url = [url_list[0], url_list[1], url_list[8]]
for url in url_list:
print("Entering page %s" % counter)
page_data = requests.get(url)
page_soup = BeautifulSoup(page_data.text, 'html.parser')
# find all the Learn More links in the page
links = page_soup.find_all('a', {'class': 'btn-info btn'})
for link in links:
if 'Learn More' in link.text:
# print(link['href'])
only_learn_more_links.append(link['href']) # Save href only
for ul_tag in page_soup.find_all('section', {'class': 'result-box'}):
counter = counter + 1
results = {}
# print("Course name = ", ul_tag.h2.text)
results["Id"] = counter
results["Course_Name"] = ul_tag.h2.text
# counter -1, because list index starts from 0
# print("COUNTER = ", counter)
dum_var = counter-1
# print("DUM_VAR = ", dum_var)
results["Learn_more_url"] = "https://www.hochschulkompass.de" + only_learn_more_links[dum_var]
for li_tag in ul_tag.find_all('ul', {'class': 'info list-inline'}):
for span_tag in li_tag.find_all('li'):
field = span_tag.find('span', {'class': 'title'}).text
value = span_tag.find('span', {'class': 'status'}).text
# print("field = ", field)
# print("value = ", value)
field = field.replace(" ", "_")
results[field] = value
# data = pd.DataFrame.from_dict(results)
# df.append(data)
main_dict[counter] = results
cols = list(main_dict.keys())
with open("phd_res_all.json", "w") as f:
json.dump(main_dict, f, ensure_ascii=False, indent=4)
#
# **************************
# Doctoral Studies links
# ***************************
# first page_100)results = https://www.hochschulkompass.de/en/doctoral-studies/doctorate-search/search/1.html?tx_szhrksearch_pi1%5Bresults_at_a_time%5D=100
# second_page_100 results = https://www.hochschulkompass.de/en/doctoral-studies/doctorate-search/search/1/pn/1.html?tx_szhrksearch_pi1%5Bresults_at_a_time%5D=100
# third_page_100_results = https://www.hochschulkompass.de/en/doctoral-studies/doctorate-search/search/1/pn/2.html?tx_szhrksearch_pi1%5Bresults_at_a_time%5D=100
# last_page_100_results = https://www.hochschulkompass.de/en/doctoral-studies/doctorate-search/search/1/pn/8.html?tx_szhrksearch_pi1%5Bresults_at_a_time%5D=100 | [
"kmvinoth@gmail.com"
] | kmvinoth@gmail.com |
9056c7250bee2fddfcf73335b28f3dc21f4c304f | 89f88f397145d09264adf0992d9821cd5d81c1f0 | /app/database/models/common.py | d7fb1a32aa3fecc00b382379f66e124bcdde0fe0 | [
"MIT"
] | permissive | RobertWarrenGilmore/InsidiousCucumber | 5b5a1f0b46e11ee249afc70fc727151101019a48 | e43e10d180db712f40e1b70e6d057a84c9d353c5 | refs/heads/master | 2021-05-01T09:37:46.917296 | 2015-05-12T12:40:29 | 2015-05-12T12:40:29 | 30,265,931 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 378 | py | """ Created on Apr 12, 2015
@author: chris
"""
class CommonEqualityMixin(object):
""" Provide Functionality for comparing two objects """
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
else:
return False
def __ne__(self, other):
return not self.__eq__(other) | [
"majorpayne327@gmail.com"
] | majorpayne327@gmail.com |
c2db9fed8d3d7953430514b58aa47a57e52a59f2 | 6acea1c5206052393beb5cba132f40e55b637c11 | /doc_curation/scraping/misc_sites/iitk.py | 6df37d4e6779f4afcd0c5073d46022a249314662 | [
"MIT"
] | permissive | sanskrit-coders/doc_curation | a44afacf68d1711bcebd02c97b30a42b6d82bccc | db330393d3df052c008811f4b442421900e5fa84 | refs/heads/master | 2023-08-27T09:41:22.784001 | 2023-08-11T05:40:46 | 2023-08-11T05:40:46 | 157,027,340 | 8 | 4 | MIT | 2022-12-08T08:26:49 | 2018-11-10T22:32:26 | Python | UTF-8 | Python | false | false | 880 | py | import logging
import regex
from doc_curation.scraping.html_scraper import souper
from indic_transliteration import sanscript
def dump_item(item_url, outfile_path, title_maker):
logging.info(item_url)
def html_fixer(soup):
souper.tag_replacer(soup=soup, css_selector="table", tag_name="div")
souper.element_remover(soup=soup, css_selector="div.view-filters")
def md_fixer(md):
md = md.replace("।।", " ॥ ")
# md = md.replace(".", " - ")
md = md.replace(":", "ः")
md = md.replace("\n \n", "\n\n")
md = regex.sub("\n{3, 13}", "\n\n", md)
md = sanscript.transliterate(md, sanscript.IAST, sanscript.DEVANAGARI)
return md
souper.dump_text_from_element(url=item_url, outfile_path=outfile_path, text_css_selector="div.content", title_maker=title_maker, title_prefix="", html_fixer=html_fixer, md_fixer=md_fixer, dry_run=False)
| [
"vishvas.vasuki@gmail.com"
] | vishvas.vasuki@gmail.com |
53277e15694b78d490c3d600935b966cae84dfbf | b5adfa6892620125cbce330e88e3578ae1f7e492 | /main_idk.py | da1e6a42c5f2b104e3f610000460ab040f17377f | [] | no_license | sebastianvz/TKinter_ACS122 | 738b16c9a6a7daa7b53138f6d4d1b95c0363132e | 258624617efa89a78b64ae89be4cf771a64ab283 | refs/heads/master | 2020-09-08T05:17:15.288050 | 2019-09-17T03:48:23 | 2019-09-17T03:48:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,634 | py | from guizero import App, Text,Picture,TextBox
#from gpiozero import Buzzer
import time
#import RPi.GPIO as GPIO
import urllib
import json
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
PIN_1=23
PIN_2=24
PIN_3=12
#GPIO.setmode(GPIO.BCM)
#GPIO.setup(PIN_1, GPIO.OUT)
#GPIO.setup(PIN_2, GPIO.OUT)
#GPIO.setup(PIN_3, GPIO.OUT)
#buzzer = Buzzer(PIN_3)
#import os
#base_folder = os.path.dirname(__file__)
#image_path = os.path.join(base_folder, 'MotoCroos_love')
image_path="Logo.jpg"
#Para modificar los tiempos de espera
TimepoBienvenida=1000
TimepoError=2000
TimepoVuelvaPronto=1000
def OPEN():
print("OPEN")
GPIO.output(PIN_1,1)
app.after(1000,CLOSE)
def CLOSE():
print("CLOSE")
GPIO.output(PIN_1,0)
def OPEN2():
print("OPEN2")
GPIO.output(PIN_2,1)
app.after(1000,CLOSE2)
def CLOSE2():
print("CLOSE2")
GPIO.output(PIN_2,0)
def bg_green():
app.bg="#8BC900"
space1.bg="#8BC900"
space1.text_color="#8BC900"
Text_Response.value="Bienvenido"
app.after(TimepoBienvenida,bg_grey)
def bg_blue():
app.bg="#1128D0"
space1.bg="#1128D0"
space1.text_color="#1128D0"
Text_Response.value="Regresa pronto"
app.after(TimepoVuelvaPronto,bg_grey)
def bg_grey():
app.bg="gray"
space1.bg="gray"
space1.text_color="gray"
buzzer.off()
BARCODE.enable()
Text_Response.value=""
def ScanBarcode(event):
BARCODE.disable()
scan=BARCODE.get()
print("BarCode "+scan)
valido=URL(scan)
if(valido == 1):
OPEN()
#Text_Response.value=""
elif(valido == 2):
print("OPEN 2 !")
OPEN2()
BARCODE.clear()
def URL(Barcode):
url= ("http://sebastianvzapivalidar.appsource.com.co/api/Entradas_V_0_1/?token=3&codigo="+Barcode)
req = Request(url)
try:
response = urlopen(req)
#print(response)
data = json.loads(response.read().decode('utf-8'))
print(data)
if (data['value']==1):
Text_Response.value="Bienvenido"
bg_green()
return 1
elif(data['value']==2):
Text_Response.value="Regesa Pronto"
bg_blue()
return 2
elif(data['value']==3):
Text_Response.value="No valida"
app.bg="#DF541e"
space1.bg="#DF541e"
space1.text_color="#DF541e"
buzzer.on()
app.after(TimepoError,bg_grey)
return 3
else:
Text_Response.value="No Existe"
app.bg="#DF541e"
space1.bg="#DF541e"
space1.text_color="#DF541e"
buzzer.on()
app.after(TimepoVuelvaPronto,bg_grey)
return 3
except URLError as e:
print(e.reason)
#print(str(e.reason))
if(str(e.reason)=='[Errno -3] Temporary failure in name resolution'):
Text_Response.value="Sin Conexion a Internet"
app.bg="#FFFF00"
app.after(TimepoError,bg_grey)
return False
elif(e.reason=='Not Found'):
Text_Response.value="Error 404"
app.bg="#FFFF00"
space1.bg="#FFFF00"
space1.text_color="#FFFF00"
app.after(TimepoError,bg_grey)
return False
else:
Text_Response.value=e.reason
app.bg="#FFFF00"
space1.bg="#FFFF00"
space1.text_color="#FFFF00"
app.after(TimepoError,bg_grey)
return False
app = App(title="Sebas",height=420,width=480,layout="grid",bg="gray")
#app = App(title="Sebas",height=420,width=480)
space1 = Text(app, text="aaaaaaa", size=20, grid=[0,0],color="gray",bg="gray")
logo = Picture(app, image=image_path, grid=[1,0])
logo.height=250
logo.width=250
space2 = Text(app, text="", size=10, grid=[1,1])
Text_Response = Text(app, text="", size=28, grid=[1,2], font="Times New Roman", color="black")
space3 = Text(app, text="", size=10, grid=[1,3])
BARCODE = TextBox(app, height=64, width=36, grid=[1,4])
BARCODE.focus()
BARCODE.tk.bind('<Key-Return>', ScanBarcode)
app.display()
| [
"noreply@github.com"
] | sebastianvz.noreply@github.com |
d40819eaa32850e593b7164b506c76330a4367cb | cd71bdd7b70951da7f699578e4051e5fefdf7d94 | /build_bed.py | 6c0110d284d6140ccd2adced60e1095d16a40eab | [] | no_license | Kontakter/cancer_project | d52bcc73ddd7ccf45de598e8a7e76f9ded7423c1 | 82439f1edcc66901637aac18b194635c6ac2653a | refs/heads/master | 2021-07-07T01:48:45.669612 | 2017-09-28T11:12:47 | 2017-09-28T11:12:47 | 103,363,662 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,145 | py | #!/usr/bin/env python
import argparse
from collections import defaultdict
def parse(multivalue_field):
return map(int, multivalue_field.strip(",").split(","))
def join_segments(segments):
ends = []
for start, end in segments:
ends.append((start, 0))
ends.append((end, 1))
result = []
start = None
open_count = 0
for end in ends:
coord, type = end
if type == 0:
if open_count == 0:
start = coord
open_count += 1
else:
open_count -= 1
if open_count == 0:
result.append((start, coord))
start = None
assert start is None
return result
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--genes-file", required=True, help="Path to file with genes")
parser.add_argument("--ref-genes-file", required=True, help="Path to file with genes coordinates")
parser.add_argument("--margin", type=int, help="Margin for regions near exomes", default=20)
parser.add_argument("--bed-output-file", required=True)
args = parser.parse_args()
genes = open(args.genes_file).read().split()
chrom_to_segments = defaultdict(list)
for line in open(args.ref_genes_file):
# 585!NR_046018! chr1! +! 11873! 14409! 14409! 14409! 3! 11873,12612,13220,! 12227,12721,14409,! 0! DDX11L1!unk!unk!-1,-1,-1,$
bin, name, chrom, strand, txStart, txEnd, cdsStart, cdsEnd, exonCount, exonStarts, exonEnds, score, name2, cdsStartStat, cdsEndStat, exonFrames = line.strip().split("\t")
if name2 in genes:
for start, end, frame in zip(*map(parse, [exonStarts, exonEnds, exonFrames])):
if frame == -1:
continue
chrom_to_segments[chrom].append((start - args.margin, end + args.margin))
with open(args.bed_output_file, "w") as fout:
for key in chrom_to_segments:
segments = join_segments(chrom_to_segments[key])
for start, end in segments:
print >>fout, key ,start, end
if __name__ == "__main__":
main()
| [
"ignat@yandex-team.ru"
] | ignat@yandex-team.ru |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.