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 213 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 246 values | content stringlengths 2 10.3M | authors listlengths 1 1 | author_id stringlengths 0 212 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2ea87234d59de6ae4fb9b29d3183eae4614596ec | 8b565f036a531ebd071df3bd33b48ef13ecf5dfd | /aste_core/urls.py | 20ec459389bd51d959c0ed9bc2a32bf7f40d1a7f | [] | no_license | Picchi/aste | 85c1638f08166a1043f415c0d1274e7501b84703 | 27212ba3178a543af03059e5281c23d7ec753d4e | refs/heads/master | 2020-03-30T01:02:20.933636 | 2014-06-11T11:19:05 | 2014-06-11T11:19:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 303 | py | from django.conf.urls import patterns, include, url
from aste_core import views
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'aste.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$',views.page),
)
| [
"picchinetor@hotmail.it"
] | picchinetor@hotmail.it |
ec5e2eb2e3df598ee10c64f7ca153096fd615a99 | 47e0754497b733dcce1f4a9a191c7b6b214cbdb7 | /load_numpy_dataforold.py | 3e9746d2dfe3f0f5b882898a0ff0f4a953e34998 | [] | no_license | soans1994/hand-pose | 47643e2bfc64570d227ee47f7c3d0fff772eab88 | 0be9db3e658fa8efdf6a835ea259043c8fb64aa6 | refs/heads/main | 2023-08-19T09:35:21.581000 | 2021-09-29T07:11:56 | 2021-09-29T07:11:56 | 401,683,335 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,488 | py | """
Process CMU Hand dataset to get cropped hand datasets.
"""
import keras
import json
from tqdm import tqdm
import glob
import cv2
import numpy as np
from matplotlib import pyplot as plt
import os
from imgaug.augmentables.kps import KeypointsOnImage
from imgaug.augmentables.kps import Keypoint
import imgaug.augmenters as iaa
IMG_SIZE = 256
NUM_KEYPOINTS = 42
class generator(keras.utils.Sequence):
def __init__(self, image_keys, aug, batch_size, train=True):
self.image_keys = image_keys
self.aug = aug
self.batch_size = batch_size
self.train = train
self.on_epoch_end()
def __len__(self):
return len(self.image_keys) // self.batch_size
def on_epoch_end(self):
self.indexes = np.arange(len(self.image_keys))
if self.train:
np.random.shuffle(self.indexes)
def __getitem__(self, index):
indexes = self.indexes[index * self.batch_size : (index + 1) * self.batch_size]
image_keys_temp = [self.image_keys[k] for k in indexes]
images = self.__data_generation(image_keys_temp)
return images
def __data_generation(self, image_keys_temp):
batch_images = np.empty((self.batch_size, IMG_SIZE, IMG_SIZE, 3), dtype="int")
batch_keypoints = np.empty((self.batch_size, NUM_KEYPOINTS), dtype="float32")
for i, key in enumerate(image_keys_temp):
data = cv2.imread(key)
split = os.path.split(key)
#print(split)
#print(split[1])
extension = os.path.splitext(split[1])[0]
#print(extension)
if self.image_keys == samples2:
key2 = "hand_labels/test/label/" + extension + ".json"
else:
key2 = "hand_labels/train/label/" + extension + ".json"
#print(key2)
#data = cv2.resize(data, (256, 256))
# We then project the original image and its keypoint coordinates.
#current_image = data
# Apply the augmentation pipeline.
#new_image = self.aug(image=current_image)
#new_image = current_image
#batch_images[i,] = new_image
batch_images[i,] = data
dat = json.load(open(key2))
pts = np.array(dat['hand_pts'])
xmin = min(pts[:, 0])
xmax = max(pts[:, 0])
ymin = min(pts[:, 1])
ymax = max(pts[:, 1])
B = max(xmax - xmin, ymax - ymin)
# B is the maximum dimension of the tightest bounding box
width = 2.2 * B # This is based on the paper
# the center of hand box can be
center = dat["hand_box_center"]
hand_box = [[center[0] - width / 2., center[1] - width / 2.],
[center[0] + width / 2., center[1] + width / 2.]]
hand_box = np.array(hand_box)
pts = pts[:, :2] - hand_box[0, :]
# current_keypoint = np.array(data["joints"])[:, :2]
# kps = []
pts = pts * 256 / width
# More on why this reshaping later.
# batch_keypoints[i,] = np.array(kp_temp).reshape(1, 1, 42)#same as below
batch_keypoints[i,] = np.array(pts).reshape(-1, 42) # same as above
# Scale the coordinates to [0, 1] range.
return batch_images, batch_keypoints
def plot_keypoints(img, points):
# display image
plt.imshow(img, cmap='gray')
#plt.imshow(np.float32(img), cmap='gray')
# plot the keypoints
for i in range(0, 42, 2):
#plt.scatter((points[i] + 0.5)*256, (points[i+1]+0.5)*256, color='red')
plt.scatter(points[i], points[i + 1], color='red')
#plt.scatter(points[:, 0], points[:, 1])
#cv2.circle(img, (int(points[i]), int(points[i + 1])), 3, (0, 255, 0), thickness=-1) # , lineType=-1)#, shift=0)
plt.show()
samples = sorted(glob.glob("hand_labels/train/crop/*.jpg"))
samples2 = sorted(glob.glob("hand_labels/test/crop/*.jpg"))
x = generator(samples, batch_size=32, aug=None)#, aug=train_aug)
y = generator(samples2, batch_size=32, aug=None)#, aug=train_aug)
#train_images, train_labels = generator(samples, batch_size=32, aug=None)#, aug=train_aug)
#print(len(x), len(y))
for i,j in x:
print(i.shape, j.shape)
print(i[0].shape, j[0].shape)
break
plot_keypoints(i[0], j[0])
for i,j in y:
print(i.shape, j.shape)
print(i[0].shape, j[0].shape)
break
plot_keypoints(i[0], j[0])
plt.show() | [
"noreply@github.com"
] | soans1994.noreply@github.com |
7859c9931f01fef268f1900cbd09c1bd67c026c1 | de318630ae27136eda81943b4be388704b3e79f9 | /facebook/promo_post_winner.py | b16a3df8330343fc75eedc3cbc546c0e242d90e4 | [] | no_license | Shirhussain/Selenium-Automation | 8ceed35defbdaaacbcd07b7b332ec3abcc2b8b57 | 2091754197b0d60d85885fa6bc1481172d8f04d3 | refs/heads/main | 2023-02-06T05:14:57.562841 | 2020-12-29T12:15:59 | 2020-12-29T12:15:59 | 324,145,121 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,422 | py | import requests
import random
from time import sleep
from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from secrit import username, password
class FaceBookBot():
def __init__(self):
options = webdriver.ChromeOptions()
# to disable the pub up notifications
options.add_argument('--disable-notifications')
self.driver = webdriver.Chrome(options=options)
def login(self,username, password):
self.driver.get("https://www.facebook.com/login")
sleep(2)
email_in = self.driver.find_element_by_xpath('//*[@id="email"]')
email_in.send_keys(username)
password_in = self.driver.find_element_by_xpath('//*[@id="pass"]')
password_in.send_keys(password)
login_btn = self.driver.find_element_by_xpath('//*[@id="loginbutton"]')
login_btn.click()
sleep(2)
def log_in_basic(self):
POST_LOGIN_URL = 'https://mbasic.facebook.com/login'
payload = {
'email': username,
'pass': password
}
with requests.Session() as session:
post = session.post(POST_LOGIN_URL, data=payload)
def post_likes(self):
#This URL will be the URL that your login form points to with the "action" tag.
POST_LOGIN_URL = 'https://mbasic.facebook.com/login'
#This URL is the page you actually want to pull down with requests.
post_ID = 'the-post-ID'
limit = 200
REQUEST_URL = f'https://mbasic.facebook.com/ufi/reaction/profile/browser/fetch/?limit={limit}&total_count=17&ft_ent_identifier={post_ID}'
payload = {
'email': username,
'pass': password
}
with requests.Session() as session:
post = session.post(POST_LOGIN_URL, data=payload)
r = session.get(REQUEST_URL)
soup = BeautifulSoup(r.content, "html.parser")
names = soup.find_all('h3', class_='be')
people_who_liked = []
for name in names:
people_who_liked.append(name.text)
return people_who_liked
def post_shares(self):
#This URL will be the URL that your login form points to with the "action" tag.
POST_LOGIN_URL = 'https://mbasic.facebook.com/login'
post_ID = 'the-post-ID'
#This URL is the page you actually want to pull down with requests.
REQUEST_URL = f'https://m.facebook.com/browse/shares?id={post_ID}'
payload = {
'email': username,
'pass': password
}
with requests.Session() as session:
post = session.post(POST_LOGIN_URL, data=payload)
r = session.get(REQUEST_URL)
soup = BeautifulSoup(r.content, "html.parser")
names = soup.find_all('span')
people_who_shared = []
for name in names:
people_who_shared.append(name.text)
return people_who_shared
def page_likes(self):
self.login(username, password)
page_name = "your-page-name"
# This URL is the page you actually want to pull down with requests.
REQUEST_URL = f'https://www.facebook.com/{page_name}/settings/?tab=people_and_other_pages&ref=page_edit'
self.driver.get(REQUEST_URL)
sleep(2)
for i in range(1,15):
self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
sleep(3)
page = self.driver.page_source
soup = BeautifulSoup(page, "html.parser")
names = soup.find_all('a', class_='_3cb8')
people_who_liked_page = []
for name in names:
people_who_liked_page.append(name.text)
return people_who_liked_page
def select_winner(self,list_A,list_B,list_C):
eligible_to_win = []
for name in list_A:
if name in list_B and name in list_C:
eligible_to_win.append(name)
return eligible_to_win
bot = FaceBookBot()
people_who_follow = bot.page_likes()
people_who_liked = bot.post_likes()
people_who_shared = bot.post_shares()
eligible = bot.select_winner(people_who_liked,people_who_follow,people_who_shared)
winner = random.choice(eligible)
print(winner)
# src: https://www.youtube.com/watch?v=tY13OlAFBxg
# https://youtu.be/ZImNusQ0I6g
# https://youtu.be/lvFAuUcowT4 | [
"sh.danishyar@gmail.com"
] | sh.danishyar@gmail.com |
9861e06cc5da5930b82807d36b6f08c2caa6bd47 | 599a14d5702a35e3e51fd4a832952899df89e764 | /src/sender/stack.py | ab18fc743fa3e9f49362af43a62b3990a45974b0 | [] | no_license | gpedro/whatsappcli | fc189d19e599348e7f79fee3bce105143646712c | 2d37204eeb9ed6f8af8986d817e22a907adf358d | refs/heads/master | 2020-12-26T04:04:25.569505 | 2015-10-22T13:37:41 | 2015-10-22T13:37:41 | 44,747,115 | 1 | 0 | null | 2015-10-22T13:32:16 | 2015-10-22T13:32:15 | null | UTF-8 | Python | false | false | 2,177 | py | from yowsup.stacks import YowStack
from .layer import SendLayer
from yowsup.layers import YowLayerEvent
from yowsup.layers.auth import YowCryptLayer, YowAuthenticationProtocolLayer, AuthError
from yowsup.layers.coder import YowCoderLayer
from yowsup.layers.network import YowNetworkLayer
from yowsup.layers.protocol_messages import YowMessagesProtocolLayer
from yowsup.layers.stanzaregulator import YowStanzaRegulator
from yowsup.layers.protocol_receipts import YowReceiptProtocolLayer
from yowsup.layers.protocol_acks import YowAckProtocolLayer
class YowsupSendStack(object):
def __init__(self, credentials, messages, encryptionEnabled = False):
"""
:param credentials:
:param messages: list of (jid, message) tuples
:param encryptionEnabled:
:return:
"""
if encryptionEnabled:
from yowsup.layers.axolotl import YowAxolotlLayer
layers = (
SendLayer,
(YowAuthenticationProtocolLayer, YowMessagesProtocolLayer, YowReceiptProtocolLayer, YowAckProtocolLayer),
YowAxolotlLayer,
YowCoderLayer,
YowCryptLayer,
YowStanzaRegulator,
YowNetworkLayer
)
else:
layers = (
SendLayer,
(YowAuthenticationProtocolLayer, YowMessagesProtocolLayer, YowReceiptProtocolLayer, YowAckProtocolLayer),
YowCoderLayer,
YowCryptLayer,
YowStanzaRegulator,
YowNetworkLayer
)
self.stack = YowStack(layers)
self.stack.setProp(SendLayer.PROP_MESSAGES, messages)
self.stack.setProp(YowAuthenticationProtocolLayer.PROP_PASSIVE, True)
self.stack.setCredentials(credentials)
def start(self):
self.stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
try:
self.stack.loop()
except AuthError as e:
print("Authentication Error: %s" % e.message) | [
"karim.jedda@gmail.com"
] | karim.jedda@gmail.com |
7e81c02be21821bb2fdc59acf36e972ae88034aa | f889e5aae4e223d10d7f64e6ebc4a8508a42c556 | /bento/core/parser/visitor.py | fb5f9b16909211072c96faf9ddf098c9154ea025 | [
"BSD-3-Clause"
] | permissive | pberkes/Bento | f7735b34f185945395ca2fc237ef36f35fffedcf | 332f525495d32d1329826186860dd7a39ab949b6 | refs/heads/master | 2021-01-16T17:40:44.924595 | 2011-11-16T15:28:45 | 2011-11-16T15:28:45 | 2,788,379 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 16,280 | py | import sys
import copy
from bento.core.parser.nodes \
import \
Node
def split_newline(s):
try:
ind = [i.type for i in s].index("newline")
return [s[:ind+1], s[ind+1:]]
except ValueError:
return [s]
def split_newlines(s):
t = []
def _split_newlines(s):
sp = split_newline(s)
t.append(sp[0])
if len(sp) > 1 and sp[1]:
_split_newlines(sp[1])
_split_newlines(s)
return t
# XXX: fix the str vs bool issue with flag variables
_LIT_BOOL = {"true": True, "false": False, True: True, False: False}
class Dispatcher(object):
def __init__(self, user_values=None):
self._d = {}
self.action_dict = {
"empty": self.empty,
"stmt_list": self.stmt_list,
"description": self.description,
"description_from_file": self.description_from_file,
"summary": self.summary,
"author": self.author,
"maintainer": self.author,
"hook_files": self.hook_files,
"config_py": self.config_py,
"meta_template_file": self.meta_template_file,
"subento": self.subento,
# Library
"library": self.library,
"library_name": self.library_name,
"library_stmts": self.library_stmts,
# Path
"path": self.path,
"path_default": self.path_default,
"path_stmts": self.path_stmts,
"path_description": self.path_description,
# Flag
"flag": self.flag,
"flag_default": self.flag_default,
"flag_stmts": self.flag_stmts,
"flag_description": self.flag_description,
# Extension
"extension": self.extension,
"extension_declaration": self.extension_declaration,
"extension_field_stmts": self.extension_field_stmts,
# Pure C library
"compiled_library": self.compiled_library,
"compiled_library_declaration": self.compiled_library_declaration,
"compiled_library_field_stmts": self.compiled_library_field_stmts,
# Conditional
"conditional": self.conditional,
"osvar": self.osvar,
"flagvar": self.flagvar,
"not_flagvar": self.not_flagvar,
"bool": self.bool_var,
# Extra source files
"extra_source_files": self.extra_source_files,
# Data files handling
"data_files": self.data_files,
"data_files_stmts": self.data_files_stmts,
# Executable
"executable": self.executable,
"exec_stmts": self.exec_stmts,
"exec_name": self.exec_name,
"function": self.function,
"module": self.module,
}
if user_values is not None:
self._vars = copy.deepcopy(user_values)
else:
self._vars = {}
def empty(self, node):
return {}
def stmt_list(self, node):
for c in node.children:
if c.type in ["name", "description", "version", "summary", "url",
"download_url", "author", "author_email",
"maintainer", "maintainer_email", "license",
"platforms", "classifiers", "hook_files",
"config_py", "description_from_file",
"meta_template_file", "keywords"]:
self._d[c.type] = c.value
elif c.type == "path":
if "path_options" in self._d:
self._d["path_options"].update({c.value["name"]: c.value})
else:
self._d["path_options"] = {c.value["name"]: c.value}
elif c.type == "flag":
if "flag_options" in self._d:
self._d["flag_options"].update({c.value["name"]: c.value})
else:
self._d["flag_options"] = {c.value["name"]: c.value}
elif c.type == "library":
if "libraries" in self._d:
self._d["libraries"].update({c.value["name"]: c.value})
else:
self._d["libraries"] = {c.value["name"]: c.value}
elif c.type == "executable":
if "executables" in self._d:
self._d["executables"].update({c.value["name"]: c.value})
else:
self._d["executables"] = {c.value["name"]: c.value}
elif c.type == "data_files":
if "data_files" in self._d:
self._d["data_files"].update({c.value["name"]: c.value})
else:
self._d["data_files"] = {c.value["name"]: c.value}
else:
raise ValueError("Unhandled top statement (%s)" % c)
return self._d
def summary(self, node):
ret = Node(node.type)
ret.value = "".join([i.value for i in node.value])
return ret
def author(self, node):
node.value = "".join([i.value for i in node.value])
return node
def maintainer(self, node):
node.value = "".join([i.value for i in node.value])
return node
def hook_files(self, node):
if "hook_files" in self._d:
self._d["hook_files"].extend(node.value)
else:
self._d["hook_files"] = node.value
def config_py(self, node):
return node
def meta_template_file(self, node):
return node
def description_from_file(self, node):
return node
def description(self, node):
tokens = []
for i in node.value:
if i.type in ["literal", "multi_literal", "newline",
"indent", "dedent", "single_line"]:
tokens.append(i)
# FIXME: fix grammar to get ind_shift
ind_shift = 4
inds = [0]
line_str = []
for line in split_newlines(tokens):
if line[0].type == "dedent":
while line[0].type == "dedent":
inds.pop(0)
line = line[1:]
remain = line
elif line[0].type == "indent":
inds.insert(0, line[0].value - ind_shift)
remain = line[1:]
else:
remain = line
if remain[-1].type == "dedent":
remain = remain[:-1]
cur_line = [" " * inds[0]]
cur_line.extend([t.value for t in remain])
line_str.append("".join(cur_line))
return Node("description", value="".join(line_str))
#--------------------------
# Library section handlers
#--------------------------
def library(self, node):
library = {}
def update(library_dict, c):
if type(c) == list:
for i in c:
update(library_dict, i)
elif c.type == "name":
library_dict["name"] = c.value
elif c.type == "modules":
if "modules" in library_dict:
library_dict["py_modules"].extend(c.value)
else:
library_dict["py_modules"] = c.value
elif c.type == "packages":
if "packages" in library_dict:
library_dict["packages"].extend(c.value)
else:
library_dict["packages"] = c.value
elif c.type in ("build_requires", "install_requires"):
if c.type in library_dict:
library_dict[c.type].extend(c.value)
else:
library_dict[c.type] = c.value
elif c.type == "extension":
name = c.value["name"]
if "extensions" in library_dict:
library_dict["extensions"][name] = c.value
else:
library_dict["extensions"] = {name: c.value}
elif c.type == "compiled_library":
name = c.value["name"]
if "compiled_libraries" in library_dict:
library_dict["compiled_libraries"][name] = c.value
else:
library_dict["compiled_libraries"] = {name: c.value}
else:
raise ValueError("Unhandled node type: %s" % c)
if len(node.children) > 1:
nodes = [node.children[0]] + node.children[1]
else:
nodes = [node.children[0]]
for c in nodes:
update(library, c)
return Node("library", value=library)
def library_name(self, node):
return Node("name", value=node.value)
def library_stmts(self, node):
return node.children
def extension(self, node):
ret = {}
def update(extension_dict, c):
if type(c) == list:
for i in c:
update(extension_dict, i)
elif c.type == "name":
ret["name"] = c.value
elif c.type == "sources":
if "sources" in ret:
ret["sources"].extend(c.value)
else:
ret["sources"] = c.value
elif c.type == "include_dirs":
if "include_dirs" in ret:
ret["include_dirs"].extend(c.value)
else:
ret["include_dirs"] = c.value
else:
raise ValueError("Gne ?")
for c in [node.children[0]] + node.children[1]:
update(ret, c)
return Node("extension", value=ret)
def extension_field_stmts(self, node):
return node.children
def extension_declaration(self, node):
return Node("name", value=node.value)
def compiled_library(self, node):
ret = {"sources": [], "include_dirs": []}
def update(compiled_library_dict, c):
if type(c) == list:
for i in c:
update(compiled_library_dict, i)
elif c.type == "name":
ret["name"] = c.value
elif c.type == "sources":
ret["sources"].extend(c.value)
elif c.type == "include_dirs":
ret["include_dirs"].extend(c.value)
else:
raise ValueError("Unknown node %s" % c)
for c in [node.children[0]] + node.children[1]:
update(ret, c)
return Node("compiled_library", value=ret)
def compiled_library_field_stmts(self, node):
return node.children
def compiled_library_declaration(self, node):
return Node("name", value=node.value)
#-----------------
# Path option
#-----------------
def path_stmts(self, node):
return node.children
def path(self, node):
path = {}
def update(c):
if type(c) == list:
for i in c:
update(i)
elif c.type == "path_declaration":
path["name"] = c.value
elif c.type == "path_description":
path["description"] = c.value
elif c.type == "default":
path["default"] = c.value
elif c.type == "conditional_stmt":
path["default"] = c.value
else:
raise SyntaxError("GNe ?")
if len(node.children) > 1:
nodes = [node.children[0]] + node.children[1]
else:
nodes = [node.children[0]]
for node in nodes:
update(node)
if not "description" in path or not "default" in path:
raise ValueError("Missing description in path section %r" %
(path["name"],))
return Node("path", value=path)
def path_default(self, node):
return Node("default", value=node.value)
def path_stmts(self, node):
return node.children
def path_description(self, node):
node.value = "".join([i.value for i in node.value])
return node
#-----------------
# Flag option
#-----------------
# XXX: refactor path/flag handling, as they are almost identical
def flag(self, node):
flag = {}
for i in [node.children[0]] + node.children[1]:
if i.type == "flag_declaration":
flag["name"] = i.value
elif i.type == "flag_description":
flag["description"] = i.value
elif i.type == "default":
flag["default"] = i.value
else:
raise SyntaxError("GNe ?")
if not flag["default"] in ["true", "false"]:
raise SyntaxError("invalid default value %s for flag %s" \
% (flag["default"], flag["name"]))
if not flag["name"] in self._vars:
self._vars[flag["name"]] = flag["default"]
return Node("flag", value=flag)
def flag_default(self, node):
return Node("default", value=node.value)
def flag_stmts(self, node):
return node.children
def flag_description(self, node):
node.value = "".join([i.value for i in node.value])
return node
#-------------------
# Conditionals
#-------------------
def conditional(self, node):
test = node.value
if self.action_dict[test.type](test):
return node.children[:1]
else:
return node.children[1:]
def osvar(self, node):
os_name = node.value.value
return os_name == sys.platform
def bool_var(self, node):
return node.value
def not_flagvar(self, node):
name = node.value.value
try:
value = self._vars[name]
except KeyError:
raise ValueError("Unknown flag variable %s" % name)
else:
return not _LIT_BOOL[value]
def flagvar(self, node):
name = node.value.value
try:
value = self._vars[name]
except KeyError:
raise ValueError("Unknown flag variable %s" % name)
else:
return _LIT_BOOL[value]
def extra_source_files(self, node):
if "extra_source_files" in self._d:
self._d["extra_source_files"].extend(node.value)
else:
self._d["extra_source_files"] = node.value
def subento(self, node):
if "subento" in self._d:
self._d["subento"].extend(node.value)
else:
self._d["subento"] = node.value
# Data handling
def data_files(self, node):
d = {}
def update(data_d, c):
if type(c) == list:
for i in c:
update(data_d, i)
elif c.type == "data_files_declaration":
d["name"] = c.value
elif c.type == "source_dir":
d["source_dir"] = c.value
elif c.type == "target_dir":
d["target_dir"] = c.value
elif c.type == "files":
d["files"] = c.value
else:
raise ValueError("Unhandled node type: %s" % c)
for c in node.children:
update(d, c)
return Node("data_files", value=d)
def data_files_stmts(self, node):
return node.children
# Executable handling
def executable(self, node):
d = {}
def update(exec_d, c):
if type(c) == list:
for i in c:
update(exec_d, i)
elif c.type == "name":
exec_d["name"] = c.value
elif c.type == "module":
exec_d["module"] = c.value
elif c.type == "function":
exec_d["function"] = c.value
else:
raise ValueError("Unhandled node type: %s" % c)
for c in node.children:
update(d, c)
return Node("executable", value=d)
def exec_stmts(self, node):
return node.children
def exec_name(self, node):
return Node("name", value=node.value)
def function(self, node):
return Node("function", value=node.value)
def module(self, node):
return Node("module", value=node.value)
| [
"cournape@gmail.com"
] | cournape@gmail.com |
0a9437b2d8efdebd1845ea6e37ade80d8fad61e1 | 750510a2a79e811b86099baa7634b2f3bb9a9dee | /participations/migrations/0001_initial.py | aa636912db4f793cd5f85cf2d27e8273ddb37a4f | [] | no_license | kawamorikaito/tournament | b388a4d6d4c0987b69afddb86051571b58cd8089 | 0ff24415697ec581036231383578ac56e024d18a | refs/heads/master | 2020-12-01T20:29:55.267482 | 2020-03-17T14:46:28 | 2020-03-17T14:46:28 | 230,760,493 | 0 | 0 | null | 2020-03-17T14:46:30 | 2019-12-29T14:21:21 | Python | UTF-8 | Python | false | false | 947 | py | # Generated by Django 2.2.5 on 2020-03-07 01:50
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('games', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Participations',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('redist_time', models.DateTimeField(default=django.utils.timezone.now)),
('Game', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='games.Game')),
('User', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),
],
),
]
| [
"noreply@github.com"
] | kawamorikaito.noreply@github.com |
1b4089136acb1bd10f24f01c1da1e29b65096fd3 | 10b873d984c9e4cffe12c51907fd9dd102043664 | /src/remove_the_exclamation_marks.py | 48211e0a86e61cc9b2ac744c282c0defa29c0c02 | [] | no_license | alvinalmodal/codewars | 7db1c53f616d80b0fa021851b0b99cb04a2ce7c3 | 0e190ea984fe67188cbaf4cf6c4ddab1963a4f66 | refs/heads/main | 2023-07-29T02:40:21.182654 | 2021-09-06T11:19:48 | 2021-09-06T11:19:48 | 398,095,583 | 0 | 0 | null | 2021-09-06T11:19:49 | 2021-08-19T23:03:44 | Python | UTF-8 | Python | false | false | 151 | py | def remove(words):
if type(words) != str or len(words) == 0:
raise ValueError('Please provide a valid string')
return words.rstrip('!') | [
"almodalalvin@gmail.com"
] | almodalalvin@gmail.com |
fb53e404b307772f0beaa3622f4611eed825f154 | 375c05dc48eacb4bdaabe8930bd39c133ff8c159 | /web/flaskr/main/views/models.py | 0488e56a3229758acbff9c5a9fa7477a49c3dd52 | [] | no_license | wangshoujunnew/ai_qi | e68e719b772c9762b64c68bd4537793df8be089a | a6dc1cd326410f522af59b657f99b675c54b4880 | refs/heads/master | 2021-07-17T00:36:28.977847 | 2021-07-15T23:41:48 | 2021-07-15T23:41:48 | 132,225,071 | 0 | 0 | null | 2018-05-05T07:27:20 | 2018-05-05T07:27:20 | null | UTF-8 | Python | false | false | 198 | py | from flask import render_template, make_response
from .. import main
@main.route('/models', methods=['GET'])
def models():
resp = make_response(render_template('models.html'))
return resp
| [
"lijianan@hujiang.com"
] | lijianan@hujiang.com |
0a544fbd4b5602eb6f2a149438adfa695cf1ca01 | cb1d59b57510d222efcfcd37e7e4e919b6746d6e | /python/word_break_II.py | 42c0963ca7b0687f03fe375c71efbea118f441c8 | [] | no_license | pzmrzy/LeetCode | 416adb7c1066bc7b6870c6616de02bca161ef532 | ef8c9422c481aa3c482933318c785ad28dd7703e | refs/heads/master | 2021-06-05T14:32:33.178558 | 2021-05-17T03:35:49 | 2021-05-17T03:35:49 | 49,551,365 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 767 | py | class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: List[str]
"""
self.dic = {}
if len(wordDict) == 0:
return []
return self.dfs(s, wordDict)
def dfs(self, s, wordDict):
if s in self.dic:
return self.dic[s]
res = []
if len(s) == 0:
res.append("")
return res
for word in wordDict:
l = len(word)
if (s[:l] == word):
sublist = self.wordBreak(s[l:], wordDict)
for sub in sublist:
res.append(word + ("" if len(sub) == 0 else " ") + sub)
self.dic[s] = res
return res
| [
"pzmrzy@gmail.com"
] | pzmrzy@gmail.com |
1d1abb0bb49bcf0af5053cfd16816cecc85a9aac | 68ea05d0d276441cb2d1e39c620d5991e0211b94 | /2157.py | ca9f59c6c84073c2a27cbe12d854b32f9a3bf69d | [] | no_license | mcavalca/uri-python | 286bc43aa157d3a6880dc222e0136c80cf079565 | e22875d2609fe7e215f9f3ed3ca73a1bc2cf67be | refs/heads/master | 2021-11-23T08:35:17.614443 | 2021-10-05T13:26:03 | 2021-10-05T13:26:03 | 131,339,175 | 50 | 27 | null | 2021-11-22T12:21:59 | 2018-04-27T19:54:09 | Python | UTF-8 | Python | false | false | 167 | py | n = int(input())
while(n > 0):
n -= 1
b, e = input().split()
s = ''
for i in range(int(b), int(e)+1):
s += str(i)
s += s[::-1]
print(s) | [
"marcelo.cavalca@cptec.inpe.br"
] | marcelo.cavalca@cptec.inpe.br |
09b8d18c5f6f09d2d73e0262c5d0145d5ce16c23 | ce6fc44470dcb5fca78cdd3349a7be70d75f2e3a | /ICPC/2015 Divisionals/front/submissions/front_andrew.py | 8639d9314af6f4157380a992e284ddf7c92e1f75 | [] | no_license | cormackikkert/competitive-programming | f3fa287fcb74248ba218ecd763f8f6df31d57424 | 3a1200b8ff9b6941c422371961a127d7be8f2e00 | refs/heads/master | 2022-12-17T02:02:40.892608 | 2020-09-20T11:47:15 | 2020-09-20T11:47:15 | 266,775,265 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,083 | py | import sys
def solve(n, h, a, P):
if h == 0:
return 0.0
P = {k: v/100.0 for k, v in P.items()}
dp = [None for x in range(0,n+1)]
A = [None for x in range(0,n+1)]
Y = range(0,h+1)
trans = [ [(-1,P[-1]), (0,P[-1]+P[0])] if y == 0 else (
[(-1,P[-1]), (0,P[0]), (1,P[1])] if y < h else
[(0,P[0]+P[1]), (1,P[1])] )
for y in Y]
dp[0] = [(1.0 if y == a else 0.0) for y in Y]
A[0] = [0 for y in Y]
for i in range(1, n+1):
dp[i] = [sum(dp[i-1][y-k]*p for k,p in trans[y]) for y in Y]
A[i] = [sum((dp[i-1][y-k]*A[i-1][y-k] + dp[i-1][y-k]*(y-k + y)/2.0)*p
for k,p in trans[y])/dp[i][y] if dp[i][y] > 1e-9 else 0.0 for y in Y]
assert abs(sum(dp[n]) - 1.0) < 1e-9
return sum(dp[n][y]*A[n][y] for y in Y)
def main():
P = {}
n, h, a, P[-1], P[0], P[1] = [int(x) for x in str(sys.stdin.readline()).split()]
print ("{0:.10f}".format(solve(n, h, a, P)))
if __name__ == "__main__":
main()
| [
"u6427001@anu.edu.au"
] | u6427001@anu.edu.au |
335e9dcfd2af0c9fa511ec361fb6123cbfbaf489 | 411818b9198fab4f12592da82f007f3de314f088 | /hebin.py | 61b29eab6f25226267788fe38f0e3f768b3a07d4 | [] | no_license | WatsonJay/torrenthunter | f6caccea5e33e48089d7ddf3fa39c9319e5a3079 | 15a6d1387ed421eb3801ace571926055b9f801da | refs/heads/master | 2020-03-21T18:13:00.952728 | 2019-03-23T03:01:45 | 2019-03-23T03:01:45 | 138,878,736 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,390 | py | import xlrd
import xlwt
class hebinxls():
def hebin(self,timerun):
myfile = xlwt.Workbook()
wtable = myfile.add_sheet(u"信息", cell_overwrite_ok=True)
wtable.write(0, 0, u"名字")
wtable.write(0, 1, u"番号")
wtable.write(0, 2, u"文件名")
wtable.write(0, 3, u"文件大小")
wtable.write(0, 4, u"文件更新日期")
wtable.write(0, 5, u"链接")
wtable.write(0, 6, u"磁力链接")
p=0
for i in range(1,6):
data = xlrd.open_workbook(timerun + "link"+str(i)+".xls")
table = data.sheets()[0]
nrows = table.nrows
for j in range(nrows):
if j == 0 :
continue
else:
wtable.write(p + j, 0, table.cell(j, 0).value)
wtable.write(p + j, 1, table.cell(j, 1).value)
wtable.write(p + j, 2, table.cell(j, 2).value)
wtable.write(p + j, 3, table.cell(j, 3).value)
wtable.write(p + j, 4, table.cell(j, 4).value)
wtable.write(p + j, 5, table.cell(j, 5).value)
wtable.write(p + j, 6, table.cell(j, 6).value)
p += nrows-1
filename = timerun + "link.xls"
myfile.save(filename)
print(u"自动合并%s的磁力链接备份" % timerun) | [
"446725026@qq.com"
] | 446725026@qq.com |
f5ca91190656e9619fa62f7a39c8901570d93006 | 4c098b625c07ccad676140e6bab98d1893cbed75 | /backend/post/migrations/0001_initial.py | 6abcbd420a9d26cf4e139ed71e285d8cbb0f0021 | [] | no_license | PrasannaIITM/Excalidraw_Save_Image | e18680b9f76074d6d6518ecc86aa4fea39626ade | 89bdc0cf8a62160b67e0d62d8a68d0d16cec254c | refs/heads/main | 2023-06-22T01:16:01.175325 | 2021-07-18T06:03:09 | 2021-07-18T06:03:09 | 387,100,523 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 608 | py | # Generated by Django 3.2.3 on 2021-07-17 12:42
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100)),
('content', models.TextField()),
('image', models.ImageField(upload_to='post_images')),
],
),
]
| [
"prasanna.bartakke@gmail.com"
] | prasanna.bartakke@gmail.com |
aa3a115ac79408f54b1de80a728f9a33126ecea7 | cf88b214e7dffc0c8b6a7a2ad4b5ecc8f946c567 | /Branch.py | 66887853fc825ff60c460f83b00ec445fcdb5ca7 | [] | no_license | BlenderCN/grove2.8 | a1dadd211b148f5b8196e5ee652c104c8f1fddbe | fb8a561a5e107feab5535f39de13f8706248febe | refs/heads/master | 2020-04-29T22:29:56.783710 | 2019-03-19T11:04:41 | 2019-03-19T11:04:41 | 176,449,551 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 63,818 | py | # coding=utf-8
""" This is where the magic happens. A collection of recursive functions that treats every
branch generation equal. Each branch does its thing and then calls its child branches
to do the same.
Copyright 2014 - 2018, Wybren van Keulen, The Grove """
import bpy
from mathutils import Matrix, Vector, bvhtree, Euler, Quaternion
from math import pi
from random import random
from copy import copy, deepcopy
from .Node import Node
from .TwigInstance import TwigInstance
from .Utils import *
class Branch:
def __init__(self, direction):
self.nodes = []
self.nodes.append(Node(direction))
self.is_trunk = False
self.marked_to_drop = False
self.skip = False
self.juice = 0.0
self.power = 1.0
self.shade = 0.0
self.phototropism_direction = Vector((0.0, 0.0, 0.0))
self.dead = False
self.offset = 0.0
self.initial_phyllotaxic_angle = 0.0
self.is_regenerative = False
self.tip_thickness = 0.001
self.uv_offset_x = random()
self.uv_offset_y = random()
def count_branches(self):
if len(self.nodes) > 1:
number = 1
else:
number = 0
for node in self.nodes:
if node.sub_branches:
for sub_branch in node.sub_branches:
number += sub_branch.count_branches()
return number
def count_power(self):
total_power = self.power
for node in self.nodes:
if node.sub_branches:
for sub_branch in node.sub_branches:
total_power += sub_branch.count_power()
return total_power
def add_regenerative(self, shade_samples, regenerative_branch_chance, regenerative_branch_chance_light_required,
internode_length, branch_angle, branching, twist, plagiotropism_buds, bvh, samples):
if self.skip or self.dead:
return 0
cast = bvh.ray_cast
number_of_regenerative_branches = 0
for i, node in enumerate(self.nodes):
if i == 0:
continue
if node.sub_branches:
for sub_branch in node.sub_branches:
number_of_regenerative_branches += sub_branch.add_regenerative(
shade_samples,
regenerative_branch_chance,
regenerative_branch_chance_light_required,
internode_length,
branch_angle, branching, twist,
plagiotropism_buds, bvh, samples)
else:
if self.skip:
continue
if random() < regenerative_branch_chance:
shade = 0.0
pos = node.pos
for ray in samples:
if cast(pos, ray)[0]:
shade += 1
shade /= shade_samples
light = 1.0 - shade
if light > regenerative_branch_chance_light_required:
node.dead = False
branch_dir = deviate(branch_angle, branching, twist, self.initial_phyllotaxic_angle,
plagiotropism_buds, 0.0, node.direction, i, 0)
branch_dir.normalize()
branch_dir *= internode_length
sub_branch = Branch(branch_dir)
sub_branch.power = 1.0
sub_branch.shade = self.shade
sub_branch.initial_phyllotaxic_angle = random() * 6.2832
sub_branch.nodes[0].pos = node.pos
sub_branch.is_regenerative = True
sub_branch.skip = self.skip
node.sub_branches.append(sub_branch)
number_of_regenerative_branches += 1
return number_of_regenerative_branches
def calculate_shade(self, shade_samples, shade_sensitivity, bvh, samples):
for node in self.nodes:
if node.sub_branches:
for sub_branch in node.sub_branches:
if not sub_branch.dead:
sub_branch.calculate_shade(shade_samples, shade_sensitivity, bvh, samples)
else:
sub_branch.shade = 1.0
pos = self.nodes[-1].pos.copy()
pos.z += 0.01
shade = shade_samples
light_direction = Vector((0.0, 0.0, 0.0))
cast = bvh.ray_cast
for ray in samples:
if not cast(pos, ray)[0]:
shade -= 1
light_direction += ray
number_of_bright_spots = shade_samples - shade
shade /= shade_samples
self.shade = pow(shade, shade_sensitivity)
self.phototropism_direction = light_direction
if number_of_bright_spots > 0:
self.phototropism_direction /= number_of_bright_spots
def die(self, start_node=0):
if start_node > 0:
self.nodes[-1].dead = True
for node in self.nodes[start_node:]:
for sub_branch in node.sub_branches:
sub_branch.die()
else:
self.dead = True
for node in self.nodes:
if node.sub_branches:
for sub_branch in node.sub_branches:
sub_branch.die()
def drop(self, drop_relatively_weak, drop_dead_exponent, apical_bud_fatality, flower_power, drop_shaded_threshold):
count_dropped = 0
count_dead_ends = 0
has_sub_branch = False
for i, node in enumerate(self.nodes):
if node.sub_branches:
has_sub_branch = True
for sub_branch in node.sub_branches:
if sub_branch.dead:
length = len(sub_branch.nodes)
rand = random()**drop_dead_exponent * (length - 1)
rand = int(rand) + 1
if rand < 2:
sub_branch.marked_to_drop = True
elif rand < length - 1:
sub_branch.nodes[rand-1].dead_thickness = sub_branch.nodes[rand-1].radius * 2.0
sub_branch.nodes = sub_branch.nodes[0:rand]
else:
if sub_branch.nodes[0].radius == 0.0:
sub_branch.die()
else:
sub_health = sub_branch.nodes[0].photosynthesis / (3.1415 * pow(sub_branch.nodes[0].radius, 2))
total_health = node.photosynthesis / (3.1415 * pow(node.radius, 2))
sub_health = (3.1415 * pow(sub_branch.nodes[0].radius, 2))
total_health = (3.1415 * pow(node.radius, 2))
sub_health = sub_branch.nodes[0].photosynthesis + 0.0000001
total_health = node.photosynthesis + 0.0000001
if sub_health / total_health < drop_relatively_weak:
sub_branch.die()
else:
if i != len(self.nodes) - 1:
ongoing_health = self.nodes[i + 1].photosynthesis / (3.1415 * pow(self.nodes[i + 1].radius, 2))
ongoing_health = (3.1415 * pow(self.nodes[i + 1].radius, 2))
ongoing_health = self.nodes[i + 1].photosynthesis + 0.0000001
if ongoing_health / total_health < drop_relatively_weak:
self.die(start_node=i + 1)
counts = sub_branch.drop(drop_relatively_weak, drop_dead_exponent, apical_bud_fatality,
flower_power, drop_shaded_threshold)
count_dropped += counts[0]
count_dead_ends += counts[1]
for sub_branch in node.sub_branches:
if sub_branch.skip:
continue
if sub_branch.marked_to_drop:
if len(node.sub_branches) == 1:
node.dead_thickness += sub_branch.nodes[0].radius * 2.0
node.sub_branches.remove(sub_branch)
node.dead = True
count_dropped += 1
if self.power < flower_power:
count_dead_ends += 1
self.nodes[-1].dead = True
if self.shade > drop_shaded_threshold:
if random() < apical_bud_fatality:
self.nodes[-1].dead = True
if not has_sub_branch:
self.die()
return count_dropped, count_dead_ends
def drop_low(self, trim_height, keep_thick):
last_node = len(self.nodes)-1
for i, node in enumerate(self.nodes):
if node.sub_branches:
if not self.nodes[-1].dead:
node.sub_branches = [branch for branch in node.sub_branches
if branch.nodes[0].pos.z > trim_height
or ((branch.nodes[0].radius * 2.0) > keep_thick)]
for sub_branch in node.sub_branches:
sub_branch.drop_low(trim_height, keep_thick)
if i != last_node:
if self.nodes[i + 1].pos.z < trim_height and self.nodes[i].pos.z >= trim_height:
if not self.is_trunk:
del self.nodes[i + 1:]
self.nodes[i].dead = True
return
if self.nodes[0].pos.z < trim_height and ((self.nodes[0].radius * 2.0) > keep_thick):
if self.nodes[i + 1].pos.z < self.nodes[i].pos.z:
if not self.is_trunk:
del self.nodes[i + 1:]
self.nodes[i].dead = True
return
def prune(self, bvh, shape):
slice_index = -1
for i, node in enumerate(self.nodes):
if node.sub_branches:
for sub_branch in node.sub_branches:
sub_branch.prune(bvh, shape)
node.sub_branches = [branch for branch in node.sub_branches if len(branch.nodes) > 1]
if i == len(self.nodes)-1:
break
if self.is_trunk and i < 3:
continue
ray = self.nodes[i + 1].pos - node.pos
if bvh.ray_cast(node.pos, ray, ray.length)[0]:
slice_index = i + 1
self.nodes[i].dead = False
if not shape:
self.nodes[i].dead_thickness = self.nodes[i].radius * 2.0
self.nodes[i].dead = True
break
if slice_index != -1:
del self.nodes[slice_index:]
def lateral_takeover(self):
if self.nodes[-1].dead:
do = False
skip_thicker = False
i = 0
thickest_sub_branch = 0
for j in reversed(range(len(self.nodes))):
node = self.nodes[j]
if node.sub_branches:
thickest_sub_branch = node.sub_branches[0]
if len(node.sub_branches) > 1:
for sub_branch in node.sub_branches[1:]:
if thickest_sub_branch.dead:
thickest_sub_branch = sub_branch
continue
if sub_branch.nodes[0].thickness > thickest_sub_branch.nodes[0].thickness:
if len(sub_branch.nodes) > 1:
thickest_sub_branch = sub_branch
if len(thickest_sub_branch.nodes) < 2:
continue
if thickest_sub_branch.dead:
continue
if node.radius < 0.01 or thickest_sub_branch.nodes[0].thickness > 0.5 * node.thickness:
do = True
i = j
else:
skip_thicker = True
break
if do:
self.nodes[i].sub_branches.remove(thickest_sub_branch)
new_lead_branch_nodes = self.nodes[:i] + [deepcopy(self.nodes[i])] + thickest_sub_branch.nodes[1:]
new_lead_branch_nodes[i].direction = thickest_sub_branch.nodes[0].direction
old_branch_end = Branch(Vector((0.0, 0.0, 0.0)))
old_branch_end.nodes = self.nodes[i:]
old_branch_end.nodes[0].sub_branches = []
old_branch_end.die()
old_branch_end_tip_thickness = copy(self.tip_thickness)
self.tip_thickness = thickest_sub_branch.tip_thickness
old_branch_end.tip_thickness = old_branch_end_tip_thickness
self.nodes = new_lead_branch_nodes
self.nodes[i].sub_branches.append(old_branch_end)
else:
if not skip_thicker:
if not self.is_trunk:
self.die()
do = False
i = 0
thickest_sub_branch = 0
last_node = len(self.nodes) - 1
for j in range(len(self.nodes)):
node = self.nodes[j]
if node.sub_branches:
thickest_sub_branch = node.sub_branches[0]
if len(node.sub_branches) > 1:
for sub_branch in node.sub_branches[1:]:
if sub_branch.nodes[0].thickness > thickest_sub_branch.nodes[0].thickness:
thickest_sub_branch = sub_branch
if j != last_node:
if (thickest_sub_branch.nodes[0].radius * 2.0) > (self.nodes[j + 1].radius * 2.0 + 0.002):
if not thickest_sub_branch.dead:
do = True
i = j
break
if do:
old_branch_end = deepcopy(thickest_sub_branch)
self.nodes[i].sub_branches.remove(thickest_sub_branch)
new_lead_branch_nodes = self.nodes[:i] + [deepcopy(self.nodes[i])] + thickest_sub_branch.nodes[1:]
new_lead_branch_nodes[i].direction = thickest_sub_branch.nodes[0].direction
old_branch_end.nodes = self.nodes[i:]
old_branch_end.nodes[0].sub_branches = []
old_branch_end.nodes[-1].dead_thickness = self.nodes[-1].radius * 2.0
old_branch_end_tip_thickness = copy(self.tip_thickness)
self.tip_thickness = thickest_sub_branch.tip_thickness
old_branch_end.tip_thickness = old_branch_end_tip_thickness
self.nodes = new_lead_branch_nodes
self.nodes[i].sub_branches.append(old_branch_end)
for node in self.nodes:
if node.sub_branches:
for sub_branch in node.sub_branches:
if not sub_branch.dead:
sub_branch.lateral_takeover()
def flow_bright(self, favor_current, shade_avoidance, favor_healthy, internode_length,
favor_current_reach, peak_height, juice, equal_power, generation,
branching_inefficiency):
self.juice = juice * 1.0
for i, node in enumerate(self.nodes):
if node.sub_branches:
for j, sub_branch in enumerate(node.sub_branches):
if sub_branch.dead:
sub_branch.power = 0.0
continue
sub_juice = 1.0 - sub_branch.shade
self.juice -= sub_juice
sub_branch.flow_bright(favor_current, shade_avoidance, favor_healthy, internode_length,
favor_current_reach, peak_height, sub_juice, equal_power,
generation + 1, branching_inefficiency)
self.power = self.juice
self.power = 1.0 - self.shade
light = 1.0 - self.shade
self.power = (favor_healthy * light + (1.0 - favor_healthy) * equal_power)
squeeze = pow((1.0 - branching_inefficiency), generation)
self.power *= squeeze
def flow_exaggerate(self, favor_current, shade_avoidance, favor_healthy, internode_length,
favor_current_reach, peak_height, juice):
self.juice = juice * 1.0
last_node_index = len(self.nodes) - 1
for i, node in enumerate(self.nodes):
if node.sub_branches:
Qt = 0.0
if i == last_node_index:
Qm = self.nodes[i].photosynthesis * 1.0
for sub_branch in node.sub_branches:
Qm -= sub_branch.nodes[0].photosynthesis
else:
Qm = self.nodes[i + 1].photosynthesis * 1.0
Qt += Qm
Qls = []
for sub_branch in node.sub_branches:
Qls.append(sub_branch.nodes[0].photosynthesis)
Qt += sub_branch.nodes[0].photosynthesis
Qtnew = 0.0
if Qm < 0.0:
print('Qm lower than 0.0, why does this happen?! For now, set to 0.0 to prevent complex numbers!')
Qm = 0.0
Qm = pow(Qm, favor_healthy)
Qtnew += Qm
for k in range(len(Qls)):
Qls[k] = pow(Qls[k], favor_healthy)
Qtnew += Qls[k]
if Qtnew != 0.0:
Qm *= (Qt / Qtnew)
for k in range(len(Qls)):
Qls[k] *= (Qt / Qtnew)
for j, sub_branch in enumerate(node.sub_branches):
if sub_branch.dead:
sub_branch.power = 0.0
continue
if Qt == 0.0:
sub_juice = 0.0
else:
sub_juice = (Qls[j] / Qt) * self.juice
distance = (len(self.nodes) - i) * internode_length
if distance > favor_current_reach:
current_favor_current = 0.0
else:
current_favor_current = favor_current
sub_juice *= (1.0 - current_favor_current)
sub_branch.juice = sub_juice
sub_branch.flow_exaggerate(favor_current, shade_avoidance, favor_healthy, internode_length,
favor_current_reach, peak_height, sub_juice)
if Qt == 0.0:
self.juice = 0.0
else:
self.juice = (Qm / Qt) * self.juice
self.power = self.juice * 1.0
def add_side_branches(self, grow_nodes, bud_life, branch_chance, branch_chance_only_terminal, internode_length,
favor_current_reach, favor_current, shade_avoidance, branch_angle, branching, twist,
plagiotropism_buds, do_environment_block, environment,
branch_chance_light_required, tip_thickness, gravitropism_buds, gravitropism_buds_randomness):
for node in self.nodes:
if node.sub_branches:
for sub_branch in node.sub_branches:
if not sub_branch.dead:
sub_branch.add_side_branches(grow_nodes, bud_life, branch_chance, branch_chance_only_terminal,
internode_length, favor_current_reach, favor_current,
shade_avoidance, branch_angle, branching, twist,
plagiotropism_buds, do_environment_block,
environment, branch_chance_light_required, tip_thickness,
gravitropism_buds, gravitropism_buds_randomness)
if self.skip:
return
random_num = random
number_of_nodes = len(self.nodes)
young_wood = number_of_nodes - 1 - (grow_nodes * bud_life)
if young_wood < 1:
young_wood = 1
branch_chance = branch_chance
for i, node in enumerate(self.nodes):
if i != number_of_nodes - 1 and random_num() < branch_chance_only_terminal:
continue
if i < young_wood:
continue
if random_num() > branch_chance or node.sub_branches:
continue
if node.dead:
continue
distance = (number_of_nodes - 1 - i) * internode_length
if distance > favor_current_reach:
power = self.power * 1.0
else:
power = self.power * (1.0 - favor_current)
if (1.0 - self.shade) < branch_chance_light_required:
continue
if i != number_of_nodes - 1:
direction = self.nodes[i + 1].pos - self.nodes[i].pos
else:
direction = self.nodes[i].pos - self.nodes[i - 1].pos
diff = node.direction.rotation_difference(direction)
current_branching = branching
current_branching = int(branching * min(1.0, self.power))
if branching > 1 and current_branching < 2:
current_branching = 2
elif branching == 1 and current_branching == 0:
current_branching = 1
for j in range(current_branching):
sub_branch_dir = deviate(branch_angle, current_branching, twist, self.initial_phyllotaxic_angle,
plagiotropism_buds, gravitropism_buds + gravitropism_buds_randomness * (0.5 - random()), direction, i, j)
sub_branch_dir.normalize()
sub_branch_dir *= internode_length
if do_environment_block:
ray = (node.pos + sub_branch_dir * 4.0) - node.pos
if environment.ray_cast(node.pos, ray, ray.length)[0]:
if current_branching == 1:
node.dead = True
continue
sub_branch_dir = diff.conjugated() @ sub_branch_dir
sub_branch = Branch(sub_branch_dir)
sub_branch.power = power
sub_branch.shade = self.shade
sub_branch.initial_phyllotaxic_angle = random() * 6.2832
sub_branch.nodes[0].pos = node.pos
sub_branch.tip_thickness = tip_thickness
node.sub_branches.append(sub_branch)
node.sub_branches[-1].skip = self.skip
def mark(self, bvh, parent_skip):
if not parent_skip:
self.skip = False
for node in self.nodes:
if node.sub_branches:
for sub_branch in node.sub_branches:
sub_branch.mark(bvh, self.skip)
else:
self.skip = True
for i, node in enumerate(self.nodes[:-1]):
ray = self.nodes[i + 1].pos - node.pos
if bvh.ray_cast(node.pos, ray, ray.length)[0]:
self.skip = False
if node.sub_branches:
for sub_branch in node.sub_branches:
sub_branch.mark(bvh, self.skip)
def unmark(self):
self.skip = False
for node in self.nodes:
for sub_branch in node.sub_branches:
sub_branch.unmark()
def grow(self, grow_nodes, internode_length, shade_elongation, random_heading, random_pitch,
gravitropism, gravitropism_shade, plagiotropism, phototropism, do_environment, do_environment_block,
force, force_radius, force_power, environment, tip_thickness, tip_decrease,
grow_exponent, favor_rising,
vector_up=Vector((0.0, 0.0, 1.0)), half_pi=0.5 * pi):
start_number_of_nodes = len(self.nodes)
for node in self.nodes:
if node.sub_branches:
for sub_branch in node.sub_branches:
if not sub_branch.dead:
sub_branch.grow(grow_nodes, internode_length, shade_elongation,
random_heading, random_pitch, gravitropism, gravitropism_shade,
plagiotropism, phototropism, do_environment, do_environment_block,
force, force_radius, force_power, environment,
tip_thickness, tip_decrease, grow_exponent, favor_rising)
if self.nodes[-1].dead:
return
if self.skip:
return
current_gravitropism = (1.0 - self.shade) * gravitropism + self.shade * gravitropism_shade
current_gravitropism /= 10.0
if self.is_regenerative:
current_gravitropism = gravitropism / 5.0
phototropism_strength = phototropism * self.phototropism_direction.length * self.shade / grow_nodes
power = self.power * 1.0
if power > 1.0:
power = 1.0
direction = self.nodes[-1].direction.copy()
if len(self.nodes) > 1:
direction = self.nodes[-1].pos - self.nodes[-2].pos
vector_up = Vector((0.0, 0.0, 1.0))
squeeze = vector_up.angle(direction, 0.0) / 3.1415
squeeze *= favor_rising
power *= (1.0 - squeeze)
max_power = 1.0
if power > max_power:
power = max_power
new_nodes = int(power * grow_nodes)
if (power * grow_nodes) % 1 > 0.3:
new_nodes += 1
new_internode_length = 0.0
if new_nodes != 0:
grow_length = internode_length * grow_nodes
new_internode_length = (power * grow_length) / new_nodes
for i in range(new_nodes):
direction = self.nodes[-1].direction.copy()
if len(self.nodes) > 1:
direction = self.nodes[-1].pos - self.nodes[-2].pos
diff = self.nodes[-1].direction.rotation_difference(direction)
flat_dir = direction.copy()
flat_dir.z = 0.0
horizontal = 1.0 - (abs(direction.angle(flat_dir, 0.0)) / half_pi)
horizontal = pow(abs(horizontal), 2.0 * 0.8)
random_heading_angle = horizontal * (1.0 - random() * 2) * random_heading
multiplier = (1.0 - power)
if multiplier < 0.0:
multiplier = 0.0
multiplier = pow(multiplier, 0.1)
direction = Quaternion(vector_up, random_heading_angle) @ direction
axis_pitch = Quaternion(vector_up, half_pi) @ flat_dir
if flat_dir.x < 0.01 and flat_dir.y < 0.01:
axis_pitch = Quaternion(vector_up, 6.28 * random()) @ axis_pitch
random_pitch_angle = (1.0 - random() * 2) * random_pitch
random_pitch_angle /= (power + 0.00001)
direction = Quaternion(axis_pitch, random_pitch_angle) @ direction
if current_gravitropism < 0.0:
if Vector((0.0, 0.0, -1.0)).angle(direction, 0.0) > 0.01:
direction = direction.slerp(vector_up, -current_gravitropism)
else:
direction = direction.lerp(vector_up, -current_gravitropism)
else:
if vector_up.angle(direction, 0.0) > 0.01:
direction = direction.slerp(Vector((0.0, 0.0, -1.0)), current_gravitropism)
else:
direction = direction.lerp(Vector((0.0, 0.0, -1.0)), current_gravitropism)
if plagiotropism > 0.0 and (abs(direction.x) + abs(direction.y)) > 0.0001:
current_plagiotropism = plagiotropism * pow(self.shade, 0.5)
plagio_dir = direction.copy()
plagio_dir.z = 0.0
direction = direction.slerp(plagio_dir, current_plagiotropism)
direction.normalize()
direction *= new_internode_length
if phototropism_strength != 0.0:
direction = direction.lerp(self.phototropism_direction.normalized() * new_internode_length, phototropism_strength)
direction.normalize()
direction *= new_internode_length
if self.is_regenerative:
direction *= 1.5
direction *= 1.0 + shade_elongation * self.shade
if do_environment:
if force in ["2", "3", "4", "5"]:
point = environment.find_nearest(self.nodes[-1].pos)[0]
if point:
force_vec = point - self.nodes[-1].pos
force_strength = 1.0 - (force_vec.length / force_radius)
if force in ["2", "3"]:
force_vec = -force_vec
if force_strength > 0.0 and len(self.nodes) > 2 and force_vec.length > 0.1:
force_vec = force_vec.normalized() * new_internode_length
direction = direction.lerp(force_vec, force_strength * force_power)
do_environment_cling = False
if do_environment_block:
last_pos = self.nodes[-1].pos
ray = (last_pos + direction) - last_pos
ray = direction
if environment.ray_cast(last_pos, ray, ray.length)[0]:
if do_environment_cling:
nearest = environment.find_nearest(last_pos + direction)[0]
direction = (nearest - last_pos) * 0.95
else:
continue
direction = diff.conjugated() @ direction
self.nodes.append(Node(direction))
self.nodes[-1].pos = self.nodes[-2].pos + direction
self.tip_thickness = tip_thickness * 1.0
if power < 1.0:
max_decrease = (1.0 - power) * tip_thickness
self.tip_thickness -= tip_decrease * max_decrease
if self.is_regenerative:
self.is_regenerative = False
def photosynthesize(self, favor_current, leaf_area, photo_range):
number_of_nodes = len(self.nodes)
for i in reversed(range(number_of_nodes)):
node = self.nodes[i]
if i == number_of_nodes - 1:
node.node_weight = 0
node.photosynthesis = (1.0 - self.shade)
if self.dead:
node.photosynthesis = 0.0
node.phloem = 0.000001
node.xylem = 0.0
node.auxin = 1.0 - self.shade
if node.dead:
node.auxin = 0.0
else:
next_node = self.nodes[i + 1]
node.node_weight = 1 + next_node.node_weight
node.photosynthesis = next_node.photosynthesis
node.phloem = next_node.phloem + 2 * pi * node.radius * node.direction.length
node.xylem = next_node.xylem + pi * pow(node.radius, 2) * node.direction.length
node.auxin = next_node.auxin * favor_current
if node.sub_branches:
for sub_branch in node.sub_branches:
if not sub_branch.dead:
l, w, p, x, a = sub_branch.photosynthesize(favor_current, leaf_area, photo_range)
node.photosynthesis += l
node.node_weight += w
node.phloem += p
node.xylem += x
node.auxin += a
return self.nodes[0].photosynthesis, self.nodes[0].node_weight, self.nodes[0].phloem, self.nodes[0].xylem, self.nodes[0].auxin
def weigh(self, leaf_weight, lateral_twig_chance, lateral_twig_limit, branch_weight, rand=0.0, wind_vector=Vector((1.0, 0.0, 0.0))):
number_of_nodes = len(self.nodes)
for i in reversed(range(number_of_nodes)):
node = self.nodes[i]
if i == number_of_nodes - 1:
node.real_weight = leaf_weight / 500000
node.leaf_weight = leaf_weight / 500000
if rand > 0.0:
node.real_weight += (1.0 - (random() * 2)) * rand / 200000
self.wind_area = 0.0
else:
node.real_weight = node.direction.length * pi * pow(node.radius, 2)
node.real_weight *= branch_weight / 100
if rand > 0.0:
node.real_weight += (1.0-(random() * 2)) * rand / 200000
node.real_weight += self.nodes[i + 1].real_weight
node.leaf_weight = self.nodes[i + 1].leaf_weight
angle = wind_vector.angle(Vector((0.0, 1.0, 0.0)))
dir_to_wind = Quaternion(Vector((0.0, 0.0, 1.0)), -angle) @ node.direction
dir_to_wind.x = 0.0
length = dir_to_wind.length
self.wind_area = self.nodes[i + 1].wind_area + (2.0 * node.radius * length)
if node.sub_branches:
for sub_branch in node.sub_branches:
if not sub_branch.dead:
rw, lw, wa = sub_branch.weigh(leaf_weight, lateral_twig_chance, lateral_twig_limit, branch_weight, rand)
node.real_weight += rw
node.leaf_weight += lw
node.wind_area += wa
return self.nodes[0].real_weight, self.nodes[0].leaf_weight, self.wind_area
def bend(self, pos, parent_diff_quaternion, fatigue, quarter_pi=0.7854, vec_back=Vector((0.0, 1.0, 0.0)),
wind_force=0.0, wind_vector=Vector((1.0, 0.0, 0.0))):
current_pos = pos * 1.0
parent_node_dif_quaternion = parent_diff_quaternion.copy()
gravity_vector = Vector((0.0, 0.0, -1.0))
for i, node in enumerate(self.nodes):
node.pos = current_pos * 1.0
bent_direction = parent_node_dif_quaternion @ node.direction
I = quarter_pi * node.radius ** 4
if I == 0.0:
I = 0.001
E = 10.0
axis = bent_direction.copy().cross(gravity_vector)
flat_bent_direction = bent_direction.copy()
flat_bent_direction.z = 0.0
arm = flat_bent_direction.length
weight = node.real_weight - (node.baked_weight * (1.0 - fatigue))
if weight < 0.0:
weight = 0.0
deflection = weight * arm ** 3 / (3 * E * I)
v = Quaternion(axis, deflection) @ bent_direction
v = v.normalized() * node.direction.length
if wind_force != 0.0:
for iteration in range(1):
fluctuation = (1.0 - 2.0 * random()) * 0.3 * pi
randomized_wind_vector = Quaternion(Vector((0.0, 0.0, 1.0)), fluctuation) @ wind_vector
axis = v.copy().cross(randomized_wind_vector)
flat_bent_direction1 = v.copy()
flat_bent_direction1.x = 0.0
arm = flat_bent_direction1.length
angle = wind_vector.angle(Vector((0.0, 1.0, 0.0)))
dir_to_wind = Quaternion(Vector((0.0, 0.0, 1.0)), -angle) @ v
dir_to_wind.x = 0.0
arm = dir_to_wind.length
weight = node.real_weight - (node.baked_weight * (1.0 - fatigue))
weight += wind_force * (1/50000)
weight *= wind_force
area = 2 * node.radius * arm
weight = area * wind_force / 200.0
weight += node.leaf_weight * wind_force
I = quarter_pi * node.radius ** 3
if I == 0.0:
I = 0.000001
print('Encounter!')
print(node.radius)
weight *= 50.0
deflection = weight * arm ** 3 / (3 * E * I)
v = Quaternion(axis, deflection) @ v
v = v.normalized() * node.direction.length
parent_node_dif_quaternion = -node.direction.rotation_difference(v)
if len(node.sub_branches):
for sub_branch in node.sub_branches:
bla = wind_force * 1.0
if wind_force > 0.0:
sub_branch.bend(current_pos, parent_node_dif_quaternion, fatigue,
wind_force=bla, wind_vector=wind_vector)
else:
sub_branch.bend(current_pos, parent_node_dif_quaternion, fatigue)
current_pos += v
def bake_bend(self, bake_bend):
for i, node in enumerate(self.nodes):
if i < len(self.nodes) - 1:
node.direction = bake_bend * (self.nodes[i + 1].pos - node.pos) + (1.0 - bake_bend) * node.direction
added_baked_weight = (node.real_weight - node.baked_weight) * bake_bend
if added_baked_weight > 0.0:
node.baked_weight += added_baked_weight
else:
if len(self.nodes) != 1:
node.direction = bake_bend * (node.pos - self.nodes[i - 1].pos) + (1.0 - bake_bend) * node.direction
if node.sub_branches:
for sub_branch in node.sub_branches:
sub_branch.bake_bend(bake_bend)
def thicken(self, e, internode_gain, tip_decrease):
last_node_index = len(self.nodes) - 1
for i, node in reversed(list(enumerate(self.nodes))):
if i == last_node_index:
node.thickness = self.tip_thickness
else:
node.thickness = self.nodes[i + 1].thickness + internode_gain
sub_thickness = 0.0
thickest_sub_thickness = 0.0
if node.sub_branches:
for sub_branch in node.sub_branches:
if len(sub_branch.nodes) < 2:
continue
sub_branch.thicken(e, internode_gain, tip_decrease)
sub_thickness = sub_branch.nodes[0].thickness
if sub_thickness > 0.0:
a = pow(node.thickness, e)
b = pow(sub_thickness, e)
node.thickness = pow(a + b, 1 / e)
if sub_thickness > thickest_sub_thickness:
thickest_sub_thickness = sub_thickness
if node.dead_thickness > thickest_sub_thickness:
sub_thickness = node.dead_thickness
a = pow(node.thickness, e)
b = pow(sub_thickness, e)
node.thickness = pow(a + b, 1 / e)
node.radius = node.thickness / 2
def make_data_relative_to_root(self, root_thickness, root_photosynthesis):
for node in self.nodes:
node.thickness /= root_thickness
node.photosynthesis /= (root_photosynthesis + 0.0000001)
if node.sub_branches:
for sub_branch in node.sub_branches:
sub_branch.make_data_relative_to_root(root_thickness, root_photosynthesis)
def smooth_kinks(self, threshold_angle):
for i, node in enumerate(self.nodes):
if i == 0:
continue
if node.sub_branches:
for sub_branch in node.sub_branches:
sub_branch.smooth_kinks(threshold_angle)
else:
previous_dir = self.nodes[i - 1].direction * 1.0
node_direction = node.direction
ang = previous_dir.angle(node_direction, 0.0)
if ang > threshold_angle:
endpoint = previous_dir + node_direction
straight_midpoint = endpoint / 2.0
new_midpoint = (previous_dir + straight_midpoint) / 2.0
self.nodes[i - 1].direction = new_midpoint
node.direction = endpoint - new_midpoint
def build_branches_mesh(self, build_type,
profile_resolution, profile_resolution_reduction, twist, u_repeat, texture_aspect_ratio,
root_distribution, root_shape, root_scale, root_bump, base_weight,
parent_previous_node, parent_node, parent_next_node, v, verts, faces, uvs, shape,
layers, origin, circles, shape_key_pass,
threshold, branch_angle, branching, plagiotropism_buds, wind_force,
vector_zero=Vector((0.0, 0.0, 0.0)),
vector_z=Vector((0.0, 0.0, 1.0)),
vector_y=Vector((0.0, 1.0, 0.0)),
twopi=6.2832):
prevaxis = None
res = profile_resolution * self.nodes[0].thickness
res = profile_resolution_reduction * res + (1.0 - profile_resolution_reduction) * profile_resolution
res = max(3, int(res))
prev_res = res
uv_offset_x = self.uv_offset_x
uv_offset_y = self.uv_offset_y
nodes = []
if parent_previous_node:
node = Node(parent_previous_node.direction)
node.pos = (parent_previous_node.pos + self.nodes[0].pos) / 2.0
node.node_weight = parent_previous_node.node_weight
node.real_weight = parent_previous_node.real_weight
node.radius = parent_node.radius * 0.95
node.thickness = node.radius * 2.0
node.thickness = parent_previous_node.thickness
node.photosynthesis = parent_previous_node.photosynthesis
nodes.append(node)
if parent_node.radius * 2.0 < (self.nodes[1].pos-self.nodes[0].pos).length:
node2 = Node(vector_zero)
posa = node.pos + (self.nodes[1].pos - node.pos) / 2
posb = posa + (self.nodes[0].pos - posa) / 2
node2.pos = posb
node2.thickness = parent_previous_node.thickness * 0.87
node2.thickness = parent_previous_node.thickness
node2.radius = parent_previous_node.radius * 2.87
node2.radius = (parent_previous_node.radius + self.nodes[0].radius) / 2.0
node2.thickness = node2.radius * 2.0
node2.thickness = parent_previous_node.thickness
if self.nodes[1].radius / parent_node.radius < 0.5:
node2.radius = self.nodes[1].radius
node2.thickness = node2.radius * 2.0
node2.thickness = parent_previous_node.thickness
node2.photosynthesis = parent_previous_node.photosynthesis
node2.node_weight = parent_previous_node.node_weight
node2.real_weight = parent_previous_node.real_weight
nodes.append(node2)
if len(self.nodes) > 1:
node3 = Node(vector_zero)
node3.pos = self.nodes[0].pos + (self.nodes[1].pos - self.nodes[0].pos) / 2
node3.node_weight = self.nodes[1].node_weight
node3.real_weight = self.nodes[1].real_weight
node3.thickness = self.nodes[0].thickness
node3.radius = self.nodes[0].radius
node3.photosynthesis = self.nodes[0].photosynthesis
node3.thickness = parent_node.thickness
nodes.append(node3)
nodes.extend(self.nodes[1:])
else:
nodes.extend(self.nodes[1:])
ratio = nodes[1].radius / parent_node.radius
nodes[0].pos = parent_previous_node.pos * ratio + (1.0 - ratio) * parent_node.pos
ratio = pow(ratio, 0.5)
nodes[0].radius = parent_node.radius * ratio + (1.0 - ratio) * nodes[1].radius
else:
first_node = self.nodes[0]
if first_node.direction.x != 0.0 or first_node.direction.y != 0.0:
root_node = Node(Vector((0.0, 0.0, 0.1)))
root_node.pos = first_node.pos - Vector((0.0, 0.0, first_node.radius))
root_node.thickness = first_node.thickness
root_node.radius = first_node.radius
nodes = [root_node] + self.nodes
else:
nodes = self.nodes
number_of_nodes = len(nodes)
circle = []
previous_y = uv_offset_y
current_y = uv_offset_y
verts_append = verts.append
verts_extend = verts.extend
faces_append = faces.append
uvs_extend = uvs.extend
shape_extend = shape.extend
do_layers = False
if not shape_key_pass:
do_layers = True
layers_shade_extend = layers['layer_shade'].extend
layers_thickness_extend = layers['layer_thickness'].extend
layers_weight_extend = layers['layer_weight'].extend
layers_power_extend = layers['layer_power'].extend
layers_health_extend = layers['layer_health'].extend
layers_dead_extend = layers['layer_dead'].extend
layers_pitch_extend = layers['layer_pitch'].extend
layers_apical_extend = layers['layer_apical'].extend
layers_lateral_extend = layers['layer_lateral'].extend
if base_weight == 0.0:
base_weight = 0.0001
last_node_index = len(nodes) - 1
cur_twist = 0.0
repeat = int(u_repeat * self.nodes[0].thickness)
if repeat < 1:
repeat = 1
for j, n in enumerate(nodes):
aspect = texture_aspect_ratio * repeat
circumference = 2 * pi * n.radius
pos_offset = n.pos - origin
previous_y = current_y
if j != 0:
current_y += aspect / circumference * abs((n.pos - nodes[j - 1].pos).length)
radius = n.radius
if self.is_trunk:
root_scale_reach = root_distribution * number_of_nodes
if j < root_scale_reach:
x = 1.0 - (j / root_scale_reach)
y = pow(x, root_shape * 75.0)
multiplier = y * (root_scale - 1.0)
radius += radius * multiplier
amount = multiplier * 0.2 * root_bump * radius
if j != last_node_index:
direction = nodes[j + 1].pos - n.pos
axis = direction.to_track_quat('X', 'Z') @ vector_y
angle = vector_z.angle(direction, 0.0)
if j != 0:
previous_direction = n.pos - nodes[j - 1].pos
previous_axis = previous_direction.to_track_quat('X', 'Z') @ vector_y
previous_angle = vector_z.angle(previous_direction, 3.14)
angle = (angle + previous_angle) / 2.0
axis = axis.lerp(previous_axis, 0.5)
axis.normalize()
else:
axis = (n.pos - nodes[j - 1].pos).to_track_quat('X', 'Z') @ Vector((1.0, twopi, 0.0))
angle = vector_z.angle(n.pos - nodes[j - 1].pos, 0.0)
if j != 0:
if direction.z < 0.0:
down = cos(Vector((0.0, 0.0, -1.0)).angle(direction))
flip_angle = Vector((prevaxis.x, prevaxis.y)).angle_signed(Vector((axis.x, axis.y)), 0.0)
cur_twist -= down * flip_angle
if j > 0:
cur_twist += twist
do_twist = cur_twist != 0.0
cur_res = profile_resolution * n.thickness
cur_res = profile_resolution_reduction * cur_res + (1.0 - profile_resolution_reduction) * profile_resolution
cur_res = int(cur_res)
if cur_res < 3:
cur_res = 3
if cur_res < prev_res - 1:
cur_res = prev_res - 1
if j < 3:
cur_res = prev_res
circle = circles[cur_res]
for i in range(cur_res):
a = (i - 1) / cur_res * repeat + uv_offset_x
b = i / cur_res * repeat + uv_offset_x
c = (1 / prev_res) * repeat
if self.is_trunk:
curradius = radius + amount * (1.0 + 0.5 * sin(i * 6 / cur_res * twopi))
curradius += amount * (1.0 + 0.5 * cos(i * 9 / cur_res * twopi)) * 0.5
else:
curradius = radius
co = circle[i] * curradius
if do_twist:
co = Quaternion(Vector((0.0, 0.0, 1.0)), cur_twist) @ co
co = Quaternion(axis, angle) @ co
co += pos_offset
if shape_key_pass:
shape_extend(co)
else:
verts_append(co)
v += 1
if j > 0 and i > 0:
offset = v - 1
faces_append((offset - 1 - cur_res,
offset - cur_res,
offset,
offset - 1))
if prev_res == cur_res:
uvs_extend([(a, previous_y),
(b, previous_y),
(b, current_y),
(a, current_y)])
elif prev_res == cur_res + 1:
uvs_extend([((i - 1) / prev_res * repeat + uv_offset_x + ((1 / prev_res) * repeat), previous_y),
(i / prev_res * repeat + uv_offset_x + ((1 / prev_res) * repeat), previous_y),
(i / cur_res * repeat + uv_offset_x, current_y),
((i - 1) / cur_res * repeat + uv_offset_x, current_y)])
if j > 0 and not shape_key_pass:
offset = v - 1 - i
a = i / cur_res * repeat + uv_offset_x
b = repeat + uv_offset_x
c = (1 / prev_res) * repeat
if prev_res == cur_res:
faces_append((offset - 1,
offset - cur_res,
offset,
offset + cur_res - 1))
uvs_extend([(a, previous_y),
(b, previous_y),
(b, current_y),
(a, current_y)])
elif prev_res == cur_res + 1:
faces_append((offset - cur_res - 1,
offset - cur_res,
offset,
offset + cur_res - 1))
uvs_extend([(a + c, previous_y),
(b + c, previous_y),
(b, current_y),
(a, current_y)])
faces_append((offset - 1,
offset - cur_res - 1,
offset + cur_res - 1))
uvs_extend([(a, previous_y),
(b, previous_y),
(a, current_y)])
if j == last_node_index:
if shape_key_pass:
shape_extend(co)
else:
verts_append(self.nodes[-1].pos - origin)
v += 1
for i in range(cur_res):
if i == cur_res - 1:
faces_append((v - 2,
v - 2 - i,
v - 1))
uvs_extend([(0.5 * circle[0].x + 0.5, 0.5 * circle[0].y + 0.5),
(0.5 * circle[i].x + 0.5, 0.5 * circle[i].y + 0.5),
(0.5, 0.5)])
else:
faces_append((v - 3 - i,
v - 2 - i,
v - 1))
uvs_extend([(0.5 * circle[i + 1].x + 0.5, 0.5 * circle[i + 1].y + 0.5),
(0.5 * circle[i].x + 0.5, 0.5 * circle[i].y + 0.5),
(0.5, 0.5)])
if do_layers:
if j == last_node_index:
number = cur_res + 1
else:
number = cur_res
layers_shade_extend([self.shade] * number)
layers_thickness_extend([n.thickness] * number)
layers_weight_extend([n.real_weight / base_weight] * number)
layers_power_extend([self.power] * number)
layers_health_extend([pow(n.photosynthesis, 0.2)] * number)
if self.dead:
layers_dead_extend([1.0] * number)
else:
layers_dead_extend([0.0] * number)
layers_pitch_extend([1.0 - (angle / pi)] * number)
layers_apical_extend([0.0] * number)
layers_lateral_extend([0.0] * number)
prev_res = cur_res
prevaxis = axis.copy()
if not self.dead:
lateral_twig_chance = 1.0
duplicator = [Vector((0.0, -0.001, -0.001)),
Vector((0.0, 0.001, -0.001)),
Vector((0.0, 0.000, 0.001))]
last_node = self.nodes[-1]
if not last_node.dead:
direc = last_node.pos - self.nodes[-2].pos
branch_mat = two_point_transform(vector_zero, direc)
twig_matrix = Matrix.Translation(last_node.pos) @ branch_mat
if shape_key_pass:
shape_extend(twig_matrix @ duplicator[0] - origin)
shape_extend(twig_matrix @ duplicator[1] - origin)
shape_extend(twig_matrix @ duplicator[2] - origin)
else:
verts_extend(twig_matrix @ vert - origin for vert in duplicator)
v += 3
faces_append((v - 3, v - 2, v - 1))
uvs_extend([(0.5, 0.5),
(0.5, 0.5),
(0.5, 0.5)])
if do_layers:
number = 3
layers_shade_extend([self.shade] * number)
layers_thickness_extend([last_node.thickness] * number)
layers_weight_extend([last_node.real_weight / base_weight] * number)
layers_power_extend([self.power] * number)
layers_health_extend([pow(last_node.photosynthesis, 0.2)] * number)
if self.dead:
layers_dead_extend([1.0] * number)
else:
layers_dead_extend([0.0] * number)
angle = vector_z.angle(direc, 0.0)
layers_pitch_extend([1.0 - (angle / pi)] * number)
layers_apical_extend([1.0] * number)
layers_lateral_extend([0.0] * number)
last_node_index = len(self.nodes) - 1
for i, n in enumerate(self.nodes):
if i == 0 or i == last_node_index or n.radius * 2.0 > threshold:
continue
if len(n.sub_branches):
if len(n.sub_branches[0].nodes) > 2:
continue
direction = self.nodes[i + 1].pos - n.pos
current_branching = int(branching * min(1.0, self.power))
if branching > 1 and current_branching < 2:
current_branching = 2
elif branching == 1 and current_branching == 0:
current_branching = 1
for b in range(current_branching):
if random() > lateral_twig_chance:
continue
sub_branch_dir = deviate(branch_angle, current_branching, twist, self.initial_phyllotaxic_angle,
plagiotropism_buds, 0.0, direction, i, b)
branch_mat = two_point_transform(vector_zero, sub_branch_dir)
twig_matrix = Matrix.Translation(n.pos) @ branch_mat
if shape_key_pass:
shape_extend(twig_matrix @ duplicator[0] - origin)
shape_extend(twig_matrix @ duplicator[1] - origin)
shape_extend(twig_matrix @ duplicator[2] - origin)
else:
verts_extend(twig_matrix @ vert - origin for vert in duplicator)
v += 3
faces_append((v - 3, v - 2, v - 1))
uvs_extend([(0.5, 0.5),
(0.5, 0.5),
(0.5, 0.5)])
if do_layers:
number = 3
layers_shade_extend([self.shade] * number)
layers_thickness_extend([n.thickness] * number)
layers_weight_extend([n.real_weight / base_weight] * number)
layers_power_extend([self.power] * number)
layers_health_extend([pow(n.photosynthesis, 0.2)] * number)
if self.dead:
layers_dead_extend([1.0] * number)
else:
layers_dead_extend([0.0] * number)
angle = vector_z.angle(sub_branch_dir, 0.0)
layers_pitch_extend([1.0 - (angle / pi)] * number)
layers_apical_extend([0.0] * number)
layers_lateral_extend([1.0] * number)
for i, node in enumerate(self.nodes):
if node.sub_branches:
for sub_branch in node.sub_branches:
if len(sub_branch.nodes) < 2:
continue
if i == 1 and i != len(self.nodes) - 1:
if len(self.nodes) == len(nodes):
previous_node, current_node, next_node = self.nodes[0], self.nodes[1], self.nodes[2]
else:
previous_node, current_node, next_node = nodes[2], nodes[3], nodes[4]
elif i < len(self.nodes) - 1:
previous_node, current_node, next_node = self.nodes[i - 1], self.nodes[i], self.nodes[i + 1]
else:
previous_node, current_node, next_node = self.nodes[i - 1], self.nodes[i], None
v = sub_branch.build_branches_mesh(build_type,
profile_resolution, profile_resolution_reduction,
twist, u_repeat, texture_aspect_ratio,
root_distribution, root_shape, root_scale, root_bump,
base_weight,
previous_node, current_node, next_node, v,
verts, faces, uvs, shape, layers,
origin, circles, shape_key_pass,
threshold, branch_angle, branching, plagiotropism_buds,
wind_force)
return v
def distribute_twigs(self, lateral_twig_limit, branch_angle, branching, twist, plagiotropism_buds,
lateral_twig_chance, apical_twigs, lateral_twigs, shade, skip_lateral_twigs,
random_heading, random_pitch,
vec_zero=Vector((0.0, 0.0, 0.0))):
if self.dead:
return
number_of_nodes = len(self.nodes)
if number_of_nodes > 1:
apical_pos = self.nodes[-1].pos
mat = two_point_transform(apical_pos, apical_pos + (apical_pos - self.nodes[-2].pos))
apical_twigs.append(TwigInstance(mat, 1, apical_pos, (apical_pos - self.nodes[-2].pos)))
for i, node in reversed(list(enumerate(self.nodes))):
if node.sub_branches:
for sub_branch in node.sub_branches:
sub_branch.distribute_twigs(lateral_twig_limit, branch_angle, branching, twist,
plagiotropism_buds, lateral_twig_chance, apical_twigs,
lateral_twigs, shade, skip_lateral_twigs, random_heading, random_pitch)
continue
if skip_lateral_twigs:
continue
if i == 0 or i == number_of_nodes - 1:
continue
if node.radius * 2.0 > lateral_twig_limit:
continue
direction = self.nodes[i + 1].pos - node.pos
branch_dir = deviate(branch_angle, branching, twist, self.initial_phyllotaxic_angle,
plagiotropism_buds, 0.0, direction, i, 0)
for j in range(branching):
if random() > lateral_twig_chance:
continue
sub_branch_dir = deviate(branch_angle, branching, twist, self.initial_phyllotaxic_angle,
plagiotropism_buds, 0.0, direction, i, j)
if j == 1 and branching == 2:
normal = direction.normalized()
sub_branch_dir = -branch_dir - 2.0 * -branch_dir.dot(normal) * normal
branch_mat = two_point_transform(vec_zero, sub_branch_dir)
lateral_twigs.append(TwigInstance(Matrix.Translation(node.pos) @ branch_mat,
0, node.pos, sub_branch_dir))
def find_highest_point(self, highest):
for node in self.nodes:
if node.pos.z > highest:
highest = node.pos.z
if node.sub_branches:
for sub_branch in node.sub_branches:
sub_high = sub_branch.find_highest_point(highest)
if sub_high > highest:
highest = sub_high
return highest
| [
"noreply@github.com"
] | BlenderCN.noreply@github.com |
7072836f481a2276f536fedf7f5a30f7ab27162f | 7089e5df484d94974f38417b130c90d35ab30296 | /tests/settings.py | e171f06a222251ea9ab8e1f807125c0badca3c2e | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | rpkilby/django-template-forms | 5dc3cc863adc7ea8a521234b4616346636af220e | 5099d87d661a6a313df49fa484afd94f145e65bc | refs/heads/master | 2021-09-06T11:17:01.575926 | 2018-02-05T23:37:24 | 2018-02-05T23:37:24 | 111,064,077 | 1 | 0 | BSD-3-Clause | 2018-02-05T23:35:09 | 2017-11-17T05:56:39 | Python | UTF-8 | Python | false | false | 1,109 | py | import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'not-a-secret'
DEBUG = True
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.staticfiles',
'template_forms',
'testapp',
]
MIDDLEWARE = []
ROOT_URLCONF = 'testapp.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'debug': True,
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
],
},
},
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'TEST': {
'NAME': ':memory:',
},
},
}
# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
| [
"rpkilby@ncsu.edu"
] | rpkilby@ncsu.edu |
b3a577c38880b998afeb78cac5e8124560a81987 | 27af33176030aaa0f166fc7e95315ea13b8b40cf | /sitemapgenerator.py | 811a32cf09866f4ace89fae1dab7b9cf3a40a38d | [] | no_license | megapro3/sitemapgenerator-public | 9cf5ded1950134537d6720926b658df32d413d82 | cf4e23f3c109cc6c0d6837796b681c335cb9b59c | refs/heads/master | 2021-01-04T03:51:12.391034 | 2020-02-13T21:42:53 | 2020-02-13T21:42:53 | 240,369,118 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,669 | py | #!/usr/bin/env python
# coding: utf-8
# In[1]:
from urllib.request import urlopen, Request, HTTPError
# In[2]:
import urllib.parse as parse
# In[3]:
from datetime import datetime as dt
# In[4]:
import hashlib
# In[5]:
import re
# In[6]:
import csv
# In[37]:
class Robotstxt():
def __init__(self,ssl=False):
self.rules = {}
self.sitemaps = []
self.agents = []
self.ssl = ssl
def set_url(self,url):
ad = 'https://' if self.ssl else 'http://'
text = urlopen(ad+url).read().decode('utf-8')
cur = []
self.rules['*'] = []
agent = ''
for line in text.split('\n'):
if line.strip().lower().startswith('user-agent:'):#new agent
#prev work
if agent!='':
self.rules[agent] = self.rules.get(agent,[])+cur
agent = line.strip().split(':')[1].strip()
elif line.strip().lower().startswith('disallow:'):#new rule
if len(line.strip().split(':')[1])!=0:
cur.append([False,line.strip().split(':')[1]])
else:
cur.append([True,'/'])
elif line.strip().lower().startswith('allow:'):
if len(line.strip().split(':')[1])!=0:
cur.append([True,line.strip().split(':')[1]])
elif line.strip().lower().startswith('Sitemap:'):
if len(line.strip().split(':')[1])!=0:
self.sitemaps.append(line.strip().split(':')[1])
else:#doesnt matter
pass
if agent!='':
self.rules[agent] = self.rules.get(agent,[])+cur
self.agents = [*self.rules]
def can_fetch(self,agent,url):
if agent!='*' and agent in self.agents:
realrules = self.rules.get(agent,[])+self.rules.get('*',[])
elif agent=='*':
realrules = self.rules.get('*',[])
elif agent not in self.agents:
realrules = self.rules.get('*',[])
else:
realrules = self.rules.get('*',[])
userules = sorted(realrules,key=lambda x:len(x[1].strip()),reverse=True)
for rule in userules:
crule = rule[1].strip()
crule = crule.replace('*','.*')
res = re.findall(crule,url)
if len(res)>0:
return rule[0]
return True
# In[7]:
def getD(url):
r= urlopen(Request(url, headers={'User-Agent': 'Mozilla'})).read()
res = hashlib.md5(r)
return r,res.hexdigest()
# In[26]:
def artd(ar):
di = {}
for i in ar:
di[i[0]] = i[1]
return di
# In[55]:
class Crawler():
def __init__(self,host='http://example.com', debug=False):
self.sitemap_lc = 1000 # link amount in one file
self.sitemap_il = 'sitemap.xml' # sitemap index main file name
self.sitemap_fl = 'sitemap_{}.xml'# sitemap file pattern
self.sitemap_hashkeep = 'hash{}.csv'.format('1') #name url hash keep
## local variables
self.linksOnLook = [host]
self.linksAlreadySaw = []
self.linksAndHash = []
self.debug = debug
self.ssl = host.startswith('https')
self.host = parse.urlparse(host).netloc
self.td_str = dt.now().strftime('%d.%m.%Y')
def linkLook(self,url):
if self.debug:
print('Parsing: {}'.format(url))
try:
res,hvalue = getD(url)
page = str(res)
except BaseException:
if self.debug:
print('some problems with link {}'.format(url))
raise
return None
pattern = r'<a [^>]*href=[\'|"](.*?)[\'"].*?>'
foundLinks = re.findall(pattern,page)
links = []
for link in foundLinks:
if self.isUrl(link):
if self.isInternal(link):
links.append(self.normalize(link))
for link in links:
curl = parse.urljoin(url,link)
curl = self.normalize(curl)
if curl not in self.linksAlreadySaw:
self.linksAlreadySaw.append(curl)
self.linksOnLook.append(curl)
self.linksAndHash.append([url,hvalue])
def normalize(self, url):
scheme, netloc, path, qs, anchor = parse.urlsplit(url)
return parse.urlunsplit((scheme, netloc, path, qs, anchor))
def isUrl(self,url):
scheme, netloc, path, qs, anchor = parse.urlsplit(url)
if url != '' and scheme in ['http', 'https', '']:
return True
else:
return False
def isInternal(self,url):
host = parse.urlparse(url).netloc
return host == self.host or host == ''
def start(self):
fl = len(self.linksOnLook)>0
while fl:# we have some links on look
url = self.linksOnLook.pop(0)
self.linksAlreadySaw.append(url)
self.linkLook(url)
fl = len(self.linksOnLook)>0
print(len(self.linksOnLook))
#already saw all links
newd = self.checkUpdate()
if len(newd)>0:
self.save(newd)
def saveHash(self,newst):
d =artd(self.linksAndHash)
with open(self.sitemap_hashkeep,'w') as f:
for i in newst:
try:
f.write('{};{};{}\n'.format(i[0],i[1],d.get(i[0],'None')))
except BaseException:
print(i)
#not finished
def save(self,newst):
self.saveHash(newst)
self.linksForSitemap = self.leftOnlyGood()
self.createSitemap()
def createSitemap(self):
lpatt = '<url><loc>{url}</loc>\n<lastmod>{lastmod}</lastmod>\n<priority>1.0</priority>\n</url>'
ress = """<?xml version="1.0" encoding="UTF-8"?>
<!-- created with seo-plus.ru/asdream --><urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
{document_list}
</urlset>
"""
ps = ''
for item in self.linksForSitemap:
n = lpatt.format(url=item[0],lastmod=dt.strptime(item[1],'%d.%m.%Y').strftime('%Y-%m-%d'))
ps+=n+'\n'
ans = ress.format(document_list=ps)
with open(self.sitemap_il,'w') as file:
file.write(ans)
return True
def leftOnlyGood(self):
rb = Robotstxt(ssl=self.ssl)
rb.set_url(self.host+'/robots.txt')
l = []
goodlink = []
with open(self.sitemap_hashkeep,'r') as file:
rr = csv.reader(file,delimiter=';')
for i in rr:
l.append([i[0],i[1],i[2]])
for link,dat,ha in l:
y = rb.can_fetch('Yandex',link)
g = rb.can_fetch('Googlebot',link)
if y and g:#link left
goodlink.append([link,dat])
return goodlink
def checkUpdate(self):
with open(self.sitemap_hashkeep,'r') as f:
csvr = csv.reader(f,delimiter=';')
dr = {}
for line in csvr:
dr[line[0]] = [line[1],line[2]]
ans = []
for link in self.linksAndHash:
info = dr.get(link[0],-1)
if (info !=-1) and (info[0] == link[1]):
ans.append(info)
else:
ans.append(link[:1]+[self.td_str])
return ans
# In[56]:
crw = Crawler(host='https://a.ru/',debug=False)
crw.start()
| [
"48083717+megapro3@users.noreply.github.com"
] | 48083717+megapro3@users.noreply.github.com |
e41ed64fbfd9778e7c3098540793498a01d8d5bc | a86a13b19aac58905b08fc516085aa2ad0a392ad | /getTweets.py | c7c426342da7ec19d64e37a2454ecf7acc6c1a85 | [] | no_license | eligoodwin/magabot | c87edf5367c5dd8cd3494d28fc9bc5947f2a698e | 5452e5ba8e835f4a35f1ebca5bc6cb5f35b0e754 | refs/heads/master | 2021-08-23T01:25:22.425965 | 2017-12-02T04:32:02 | 2017-12-02T04:32:02 | 111,015,762 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,820 | py | import tweepy
import json
import io
import twittercreds
#get the tweets of the
class Tweets():
newTweetData = [] #an array holding the
def __init__(self, userName, lastTweetId):
self.userName = userName
self.lastTweetId = lastTweetId
def __init__(self, userName):
self.screenName = userName
def getLotsOfTweets(self):
#authorize twitter
auth = tweepy.OAuthHandler(twittercreds.consumerKey, twittercreds.consumerSecret)
auth.set_access_token(twittercreds.accessToken, twittercreds.accessTokenSecret)
api = tweepy.API(auth)
#this is howe the tweeting bullshit works. It gets the--it comes in as a josn formatted str
#the problem is that we can deal with it yet
self.newTweetData = self.makeToList(api.user_timeline(screen_name=self.screenName, count=200))
#get length of newTweets
#if lenght == 200, get more tweets until length is no longer 200 or total length is 3000
length = len(self.newTweetData)
newTweets = []
if length == 200:
#make request for last tweet
while length == 200 and len(self.newTweetData) < 3600:
lastTweetId = self.newTweetData[-1]['id_str']
tempTweets = api.user_timeline(screen_name=self.screenName, count=200, max_id=lastTweetId)
#convert to json then to dict
newTweets = self.makeToList(tempTweets)
self.newTweetData += newTweets
length = len(newTweets)
# jsonTweets = json.dumps([status._json for status in newTweets])
# #now we can load it up and treat as json
# self.newTweetData = json.loads(jsonTweets)
print len(self.newTweetData)
def getRecentTweets(self):
auth = tweepy.OAuthHandler(twittercreds.consumerKey, twittercreds.consumerSecret)
auth.set_access_token(twittercreds.accessToken, twittercreds.accessTokenSecret)
api = tweepy.API(auth)
newTweets = api.user_timeline(screen_name=self.screenName, since_id=self.lastTweetId)
jsonTweets = json.dumps([status._json for status in newTweets])
self.newTweetData = json.loads(jsonTweets)
self.lastTweetId = self.newTweetData[0]['id_str']
def writeTweets(self, outfileName):
with io.open(outfileName, 'w', encoding='utf-8') as file:
file.write(json.dumps(self.newTweetData, ensure_ascii=False))
def makeToList(self, inputResult):
"""takes the resulting tweet data coverts it to json, then to a list of dicts"""
tweetJson = json.dumps([status._json for status in inputResult])
return json.loads(tweetJson)
def printTWeets(self):
for i in range(len(self.newTweetData)):
print self.newTweetData[i]['text'] | [
"goodwiel@oregonstate.edu"
] | goodwiel@oregonstate.edu |
e18dfe8d2505818d2aba17214fe34e4aadbeaf67 | 40472cdbd913cbef183ea002514a57710ac51373 | /src/scripts/calc_density.py | 59f893830730967e856d4ba3c87ca48d22077e2a | [] | no_license | NatasjaWezel/project_handbag | fa52485c459c26318e8d44900d9d7cc92f0f5a93 | 838f13ed610e4352199fd08fb53870d7b816de31 | refs/heads/master | 2023-06-22T10:58:04.689179 | 2021-07-20T12:44:38 | 2021-07-20T12:44:38 | 292,266,199 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,078 | py | # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# This script is part of the quantification pipeline of 3D experimental data of crystal structures that I wrote for my
# thesis in the Master Computational Science, University of Amsterdam, 2021.
#
# `calc_density` loads the coordinates of the aligned fragments. It then divides the surrounding space into a number of
# bins, depending on which resolution is set. It counts how many of the contact atoms/ centers of contact groups are
# are in each bin and normalizes that by the total amount of contact atoms or groups.
#
# Author: Natasja Wezel
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
import sys
import time
import numpy as np
import pandas as pd
from classes.Settings import Settings
from classes.Radii import Radii
from helpers.density_helpers import make_density_df, find_available_volume, calc_distances
from helpers.geometry_helpers import make_coordinate_df
from constants.constants import STANDARD_THRESHOLD, STANDARD_RES, STANDARD_EXTRA_VDW
from constants.paths import WORKDIR
def main():
if len(sys.argv) != 3:
print("Usage: python plot_density.py <path/to/inputfile> <contact group reference point>")
sys.exit(1)
t0 = time.time()
settings = Settings(WORKDIR, sys.argv[1])
settings.set_contact_reference_point(sys.argv[2])
# resolution of the bins, in Angstrom
settings.set_resolution(STANDARD_RES)
settings.set_threshold(STANDARD_THRESHOLD)
try:
df = pd.read_csv(settings.get_aligned_csv_filename(), header=0)
avg_frag = pd.read_csv(settings.outputfile_prefix + "_avg_fragment.csv", header=0)
except FileNotFoundError:
print('First align and calculate average fragment.')
sys.exit(2)
radii = Radii(settings.get_radii_csv_name())
# grab only the atoms that are in the contact groups
coordinate_df = make_coordinate_df(df, settings, avg_frag, radii)
density_df = make_density_df(settings, coordinate_df, again=True)
t1 = time.time() - t0
print("Duration: %.2f s." % t1)
# find the volume of the central group
tolerance = STANDARD_EXTRA_VDW
contact_group_radius = radii.get_vdw_distance_contact(settings.contact_rp)
Vavailable = find_available_volume(avg_fragment=avg_frag, extra=(tolerance + contact_group_radius))
print('Available volume:', Vavailable)
threshold_calc = density_df.datafrac_normalized.max() * settings.threshold
in_cluster = density_df[density_df.datafrac_normalized >= threshold_calc]
datafrac = in_cluster.datafrac_normalized.sum()
Vcluster = len(in_cluster) * settings.resolution**3
directionality = datafrac / Vcluster * (Vavailable/2)
print(f"Directionality: {directionality}")
vdw_overlap = calc_vdw_overlap(in_cluster.copy(), settings, avg_frag, contact_group_radius)
print(f"Vdw overlap datapoints in cluster: {vdw_overlap :.2f}%")
def calc_vdw_overlap(in_cluster, settings, avg_fragment, contact_group_radius):
# center of bin is at xstart + a half times the resolution
in_cluster['x_center'] = in_cluster.xstart + 0.5 * settings.resolution
in_cluster['y_center'] = in_cluster.ystart + 0.5 * settings.resolution
in_cluster['z_center'] = in_cluster.zstart + 0.5 * settings.resolution
bin_coordinates = np.transpose(np.array([in_cluster.x_center, in_cluster.y_center, in_cluster.z_center]))
in_vdw_vol = np.zeros(len(in_cluster))
for i, atom in avg_fragment.iterrows():
indices = np.transpose(np.where(in_vdw_vol == 0))
fragment_point = np.array([atom.x, atom.y, atom.z, atom.vdw_radius])
in_vdw_vol = calc_distances(in_vdw_vol, bin_coordinates, fragment_point, indices,
extra=(contact_group_radius))
in_cluster['in_vdw_vol'] = in_vdw_vol
return in_cluster[in_cluster.in_vdw_vol != 0].datafrac_normalized.sum() * 100
if __name__ == "__main__":
main()
| [
"natasjawezel@hotmail.com"
] | natasjawezel@hotmail.com |
d2471ea9af31f6ee908d57c4a5d7f01b86db2fc1 | 85afcf96da3d1068496d807fb3d6e5122d41cd8e | /moives/spiders/zhuixinfandownloadlink.py | df258e9881bb07c2dd77d3566f062f28ed3b372e | [] | no_license | robbinhan/movies | f3d87f3122507f975bad73102180427690ce7865 | a48577af2e5f2d00e3ab0b79f672f0c1fea3ee67 | refs/heads/master | 2022-12-10T23:45:19.949896 | 2021-04-01T01:37:55 | 2021-04-01T01:37:55 | 97,911,141 | 3 | 0 | null | 2022-11-04T19:36:22 | 2017-07-21T05:55:50 | HTML | UTF-8 | Python | false | false | 762 | py | import scrapy
import subprocess
class ZhuixinfanDownloadLinkSpider(scrapy.Spider):
name = "zhuixinfan_downloadlink"
def __init__(self, url):
super(ZhuixinfanDownloadLinkSpider, self).__init__()
self.url = url
def start_requests(self):
print(self.url)
yield scrapy.Request(url=self.url, callback=self.parse_movie_home)
def parse_movie_home(self, response):
downloadLink = response.xpath('//dd[@id="torrent_url"]/text()').extract()[0]
print(downloadLink)
if "magnet:?" in downloadLink:
command = 'npm run webtorrent-cli -- download "' + downloadLink + '" --mpv'
(status) = subprocess.call(command, shell=True)
print(status)
| [
"hanb@kingnet.com"
] | hanb@kingnet.com |
06dd063ed44cdcd528e2beed2254da0550654d75 | f803a1470c29d71fb192dcd4345b0678bb3a44aa | /datasets/DentalDataset.py | ce96ca44e052fbd0b9ae104aee01651e6a65bbaf | [] | no_license | zendi014/DLCariesScreen | 62dd23cd20922d244474153521ecfbc48f2da87c | 1b27cb6dff07c2b98bf739f6f108c6cdc31a183b | refs/heads/master | 2023-02-05T09:55:06.717176 | 2020-12-29T23:24:03 | 2020-12-29T23:24:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,808 | py | import os.path as osp
import numpy as np
import mmcv
from torch.utils.data import Dataset
from mmcv.parallel.data_container import DataContainer
from cores.pre_processing.image_transform import ImageTransform, BboxTransform
from cores.pre_processing.augmentations import Augmentation, random_scale
from utils.image_utils import to_tensor
class DentalDataset(Dataset):
"""dental dataset for detection.
Annotation format:
[
{
'filename': 'a.jpg',
'width': 1280,
'height': 720,
"pigment": int,
"soft_deposit": int,
'ann': {
'bboxes': <np.ndarray> (n, 4),
'labels': <np.ndarray> (n, ),
}
},
...
]
The `ann` field is optional for testing.
detection labels in pickle file:
0: negative
1: periodontal_disease (includes periodontitis and gingivitis)
2:calculus
3: caries
"""
def __init__(
self,
num_class,
ann_file,
img_prefix,
img_scale,
img_norm_cfg,
multiscale_mode='value',
flip_ratio=0,
with_label=True,
extra_aug=None,
test_mode=False
):
"""Dataset class.
Args:
ann_file (List(Dir)): format as above.
img_prefix (str): dir path.
img_scale (tuple or List(Tuple)): (h, w)
img_norm_cfg (mean, std, to_rgb, size_divisor, resize_keep_ratio):
multiscale_mode (str):
None for not multi-scale.
'value' for random take one scale from img_scale.
'range' for taking as a range.
flip_ratio (float): flip_ratio = 0 means no flip. should be within [0, 1].
with_label (bool): with bbox label or not.
extra_aug (None or dict): augmentation except scaling and flipping.
Including PhotoMetricDistortion, Expand, and RandomCrop.
Input list is for their parameters.
test_mode (bool): test mode.
Returns:
"""
self.num_class = num_class
# prefix for images path
self.img_prefix = img_prefix
# load annotations at once during init
self.img_infos = self.load_annotations(ann_file)
# in test mode or not
self.test_mode = test_mode
# filter images that are too small
if not self.test_mode:
valid_inds = self._filter_imgs()
self.img_infos = [self.img_infos[i] for i in valid_inds]
# (long_edge, short_edge) or [(long1, short1), (long2, short2), ...]
self.img_scales = img_scale if isinstance(img_scale, list) else [img_scale]
assert mmcv.is_list_of(self.img_scales, tuple)
# normalization configs
self.img_norm_cfg = img_norm_cfg
# multi-scale mode (only applicable for multi-scale training)
self.multiscale_mode = multiscale_mode
assert multiscale_mode in ['value', 'range']
# flip ratio
self.flip_ratio = flip_ratio
assert 0 <= flip_ratio <= 1
# with label is False for RPN
self.with_label = with_label
# transforms
self.img_transform = ImageTransform(
mean=img_norm_cfg['mean'],
std=img_norm_cfg['std'],
to_rgb=img_norm_cfg['to_rgb'],
)
self.bbox_transform = BboxTransform(max_num_gts=None)
# if use extra augmentation
if extra_aug is not None:
self.extra_aug = Augmentation(**extra_aug)
else:
self.extra_aug = None
# image padding color values
self.pad_values = img_norm_cfg['pad_values']
# image rescale if keep ratio
self.resize_keep_ratio = img_norm_cfg['resize_keep_ratio']
def __len__(self):
return len(self.img_infos)
def _rand_another(self):
return np.random.choice(list(range(0, len(self))))
def __getitem__(self, idx):
if self.test_mode:
return self.prepare_test_img(idx)
while True:
data = self.prepare_train_img(idx)
if data is None:
idx = self._rand_another()
continue
return data
def prepare_test_img(self, idx):
"""Prepare an image for testing"""
img_info = self.img_infos[idx]
# load image
img = mmcv.imread(osp.join(self.img_prefix, img_info['filename']))
img, img_shape, pad_shape, scale_factor = \
self.img_transform(
img=img, scale=self.img_scales[0], flip=False, pad_val=self.pad_values, keep_ratio=self.resize_keep_ratio
)
img_meta = dict(
ori_shape=(img_info['height'], img_info['width'], 3),
img_shape=img_shape,
pad_shape=pad_shape,
scale_factor=scale_factor,
flip=False
)
data = dict(
img=DataContainer(to_tensor(img), stack=True),
img_meta=DataContainer(img_meta, cpu_only=True)
)
return data
def prepare_train_img(self, idx):
img_info = self.img_infos[idx]
# load image
img = mmcv.imread(osp.join(self.img_prefix, img_info['filename']))
ann = self.get_ann_info(idx)
gt_bboxes = ann['bboxes']
gt_labels = ann['labels']
# skip the image if there is no valid gt bbox
if len(gt_bboxes) == 0:
return None
# aug 1: apply extra augmentation
if self.extra_aug is not None:
img, gt_bboxes, gt_labels = \
self.extra_aug(img, gt_bboxes, gt_labels)
# visualize augmented data
# import string
# import random
# import os
# temp_data = np.copy(img)
# letters = string.ascii_lowercase
# name = ''.join(random.choice(letters) for i in range(10))
# dir_path = os.path.dirname(os.getcwd()) + '/MobileDentist'
# work_dir = dir_path + '/work_dirs/dental_1009_w_pretrained_wt_fix_w_phonaugment/'
# mmcv.imwrite(temp_data, work_dir + '{}.jpg'.format(name))
# aug 2: apply ordinary augmentations: flipping
flip = True if np.random.rand() < self.flip_ratio else False
# aug 3: apply ordinary augmentations: scaling
img_scale = random_scale(self.img_scales, self.multiscale_mode)
img, img_shape, pad_shape, scale_factor = \
self.img_transform(
img=img, scale=img_scale, flip=flip, pad_val=self.pad_values, keep_ratio=self.resize_keep_ratio
)
img = img.copy()
gt_bboxes = self.bbox_transform(
bboxes=gt_bboxes, img_shape=img_shape, scale_factor=scale_factor, flip=flip
)
img_meta = dict(
ori_shape=(img_info['height'], img_info['width'], 3),
img_shape=img_shape,
pad_shape=pad_shape,
scale_factor=scale_factor,
flip=flip
)
data = dict(
img=DataContainer(to_tensor(img), stack=True),
img_meta=DataContainer(data=img_meta, cpu_only=True),
gt_bboxes=DataContainer(data=to_tensor(gt_bboxes)),
gt_labels = DataContainer(to_tensor(gt_labels.astype(np.long)))
)
return data
def load_annotations(self, ann_file):
annotations = mmcv.load(ann_file)
return annotations
def _filter_imgs(self, min_size=32):
"""Filter images too small."""
valid_inds = []
for i, img_info in enumerate(self.img_infos):
if min(img_info['width'], img_info['height']) >= min_size:
valid_inds.append(i)
return valid_inds
def get_ann_info(self, idx):
ann_info = self.img_infos[idx]['ann']
gt_bboxes = []
gt_labels = []
# filter out useless labels. fix the labels for the training case.
for bbox, label in zip(ann_info['bboxes'], ann_info['labels']):
if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:
print('wrong box size happens: {}'.format(bbox))
continue
if label+1 >= self.num_class or label+1 <= 0:
print('wrong label number happens {}'.format(label))
continue
gt_bboxes.append(bbox)
gt_labels.append(label+1)
if gt_bboxes:
gt_bboxes = np.array(gt_bboxes, dtype=np.float32)
gt_labels = np.array(gt_labels, dtype=np.int64)
else:
gt_bboxes = np.zeros((0, 4), dtype=np.float32)
gt_labels = np.array([], dtype=np.int64)
ann = dict(
bboxes=gt_bboxes, labels=gt_labels)
return ann
| [
"liangyuandg@g.ucla.edu"
] | liangyuandg@g.ucla.edu |
8ebbf36d3c88ee93f19d20db7545d8c5baaf247d | e539e77ccf29457e9b3beed88381be440071d0d6 | /bin/pasteurize | c19f18dcab407054416dcc88b0b5eb91f90f4d95 | [] | no_license | wenjiehe/crawlerDemo | a518781c78bf5e19a62878f786b9c94f67df3b6f | 7949d9f85a9ac5eaf59c56e68eb550c8c17176f5 | refs/heads/master | 2023-03-01T07:01:10.292814 | 2021-02-02T14:52:09 | 2021-02-02T14:52:09 | 334,104,880 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,004 | #!/Users/hewenjie/Documents/gitDemo/crawlerDemo/bin/python
# EASY-INSTALL-ENTRY-SCRIPT: 'future==0.18.2','console_scripts','pasteurize'
import re
import sys
# for compatibility with easy_install; see #2198
__requires__ = 'future==0.18.2'
try:
from importlib.metadata import distribution
except ImportError:
try:
from importlib_metadata import distribution
except ImportError:
from pkg_resources import load_entry_point
def importlib_load_entry_point(spec, group, name):
dist_name, _, _ = spec.partition('==')
matches = (
entry_point
for entry_point in distribution(dist_name).entry_points
if entry_point.group == group and entry_point.name == name
)
return next(matches).load()
globals().setdefault('load_entry_point', importlib_load_entry_point)
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(load_entry_point('future==0.18.2', 'console_scripts', 'pasteurize')())
| [
"wx2018543@dev.bcs"
] | wx2018543@dev.bcs | |
3cc6123073a2ea6001ba79af240f79bf16f3fc1b | cdb8189ca1dcd35251420aa6571e734735348c34 | /covid-twitter-bert/run.py | f9b85d271310cc4ce75a4331a3e12c4ff977d768 | [] | no_license | SumonKantiDey/Constraint-AAAI2021-COVID19-Fake-News-Detection-in-English | 4a329878f4d4df99cdab5ecf426c8faf59288640 | 5e08942befeae14e3a69b56b7f9d316f0f6e38f7 | refs/heads/main | 2023-04-19T11:16:24.673904 | 2021-05-11T06:20:32 | 2021-05-11T06:20:32 | 366,106,129 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,833 | py | ############################ Last Two Layer ###########################
## Covid twitter Bert
python train.py --bert_hidden 1024 \
--pretrained_model_name "digitalepidemiologylab/covid-twitter-bert-v2" \
--learning_rate 2e-5 \
--epochs 4 \
--max_len 128 \
--train_batch_size 16 \
--valid_batch_size 32 \
--do_lower_case \
--model_layer "last_two" \
--model_specification "covid_bert_two_train_16_2e5" \
--output "covid_bert_two_train_16_2e5.csv"
python train.py --bert_hidden 1024 \
--pretrained_model_name "digitalepidemiologylab/covid-twitter-bert-v2" \
--learning_rate 3e-5 \
--epochs 4 \
--max_len 128 \
--train_batch_size 16 \
--valid_batch_size 32 \
--do_lower_case \
--model_layer "last_two" \
--model_specification "covid_bert_two_train_16_3e5" \
--output "covid_bert_two_train_16_3e5.csv"
## Bio Bert
python train.py --bert_hidden 768 \
--pretrained_model_name "seiya/oubiobert-base-uncased" \
--learning_rate 2e-5 \
--epochs 8 \
--max_len 128 \
--train_batch_size 16 \
--valid_batch_size 32 \
--do_lower_case \
--model_layer "last_two" \
--model_specification "bio_bert_two_train_16_2e5" \
--output "bio_bert_two_train_16_2e5.csv"
python train.py --bert_hidden 768 \
--pretrained_model_name "seiya/oubiobert-base-uncased" \
--learning_rate 3e-5 \
--epochs 8 \
--max_len 128 \
--train_batch_size 16 \
--valid_batch_size 32 \
--do_lower_case \
--model_layer "last_two" \
--model_specification "bio_bert_two_train_16_3e5" \
--output "bio_bert_two_train_16_3e5.csv"
## Sci Bert
python train.py --bert_hidden 768 \
--pretrained_model_name "allenai/scibert_scivocab_uncased" \
--learning_rate 2e-5 \
--epochs 4 \
--max_len 128 \
--train_batch_size 16 \
--valid_batch_size 32 \
--do_lower_case \
--model_layer "last_two" \
--model_specification "sci_bert_two_train_16_2e5" \
--output "sci_bert_two_train_16_2e5.csv"
python train.py --bert_hidden 768 \
--pretrained_model_name "allenai/scibert_scivocab_uncased" \
--learning_rate 3e-5 \
--epochs 4 \
--max_len 128 \
--train_batch_size 32 \
--valid_batch_size 32 \
--do_lower_case \
--model_layer "last_two" \
--model_specification "sci_bert_two_train_32_3e5" \
--output "sci_bert_two_train_32_3e5.csv"
################################# Last Four Layer ###########################
## Covid twitter Bert
python train.py --bert_hidden 1024 \
--pretrained_model_name "digitalepidemiologylab/covid-twitter-bert-v2" \
--learning_rate 2e-5 \
--epochs 4 \
--max_len 128 \
--train_batch_size 16 \
--valid_batch_size 32 \
--do_lower_case \
--model_layer "last_four" \
--model_specification "covid_bert_four_train_16_2e5" \
--output "covid_bert_four_train_16_2e5.csv"
python train.py --bert_hidden 1024 \
--pretrained_model_name "digitalepidemiologylab/covid-twitter-bert-v2" \
--learning_rate 3e-5 \
--epochs 4 \
--max_len 128 \
--train_batch_size 16 \
--valid_batch_size 32 \
--do_lower_case \
--model_layer "last_four" \
--model_specification "covid_bert_four_train_16_3e5" \
--output "covid_bert_four_train_16_3e5.csv"
## Bio Bert
python train.py --bert_hidden 768 \
--pretrained_model_name "seiya/oubiobert-base-uncased" \
--learning_rate 2e-5 \
--epochs 8 \
--max_len 128 \
--train_batch_size 16 \
--valid_batch_size 32 \
--do_lower_case \
--model_layer "last_four" \
--model_specification "bio_bert_four_train_16_2e5" \
--output "bio_bert_four_train_16_2e5.csv"
python train.py --bert_hidden 768 \
--pretrained_model_name "seiya/oubiobert-base-uncased" \
--learning_rate 3e-5 \
--epochs 8 \
--max_len 128 \
--train_batch_size 16 \
--valid_batch_size 32 \
--do_lower_case \
--model_layer "last_four" \
--model_specification "bio_bert_four_train_16_3e5" \
--output "bio_bert_four_train_16_3e5.csv"
## Sci Bert
python train.py --bert_hidden 768 \
--pretrained_model_name "allenai/scibert_scivocab_uncased" \
--learning_rate 2e-5 \
--epochs 4 \
--max_len 128 \
--train_batch_size 16 \
--valid_batch_size 32 \
--do_lower_case \
--model_layer "last_four" \
--model_specification "sci_bert_four_train_16_2e5" \
--output "sci_bert_four_train_16_2e5.csv"
python train.py --bert_hidden 768 \
--pretrained_model_name "allenai/scibert_scivocab_uncased" \
--learning_rate 3e-5 \
--epochs 4 \
--max_len 128 \
--train_batch_size 32 \
--valid_batch_size 32 \
--do_lower_case \
--model_layer "last_four" \
--model_specification "sci_bert_four_train_32_3e5" \
--output "sci_bert_four_train_32_3e5.csv" | [
"sumonkantidey23@gmail.com"
] | sumonkantidey23@gmail.com |
31791fefda554f78f6883a22f704dfdf79e47740 | f58d7f1dc962f81b58c04849a82cfe8ee19f1a0b | /gauss_env.py | 46cab40d522b54114ec3e9646dcbf8ca2f74f9f4 | [] | no_license | FranziskaGoerler/Bachelorarbeit | 9a382b8fa53d0f5566304d765dcabc9c7905ca7b | 506ec2e65bb83ac90ee74ac5554d8d16fc87f723 | refs/heads/master | 2023-03-04T04:51:08.091239 | 2021-02-04T20:02:39 | 2021-02-04T20:02:39 | 310,677,211 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 38,953 | py | import arcade
import gym
# import random
import timeit
# import math
import numpy as np
import time
import bisect
from matplotlib import pyplot as plt
from multiple_formatter import multiple_formatter
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 800
N_BINS = 4
N_BOTS = 6
BOT_RADIUS = 17.5
COLLISION_DISTANCE = BOT_RADIUS + 17.5
PLAN_STEPS = 20 # default 45
CHECK_MAX_STEPS = 5 # default 15
RADIUS = 100
MIN_DIST = 20
SCREEN_TITLE = "pycking environment"
ROBOT_MAX_SPEED = 0 # if exactly 0, step function of robot is never called, which speeds up environment
AGENT_MAX_SPEED = 8
PUNISH_WRONG_DIRECTION = True
WRONG_DIRECTION_CONSTANT = - 0.5 # additional constant punishment. Wrong direction punishment is a linear function, this is added.
REWARD_TARGET_FOUND = 50 # reward for reaching target
REWARD_COLLISION = -100
REWARD_BOUNDARY = -100
TARGET_GAUSS_STD = np.pi/4
ROBOT_GAUSS_STD = np.pi/12
ROBOT_DISTANCE_SCALING_CONSTANT = 60 # distance scaling is -(2 / np.exp(800/C)) * np.exp((800-x)/C)
ROBOT_REWARD_MAX = -4
N_SENSORS = 36
DONE_AT_COLLISION = True
IGNORE_ROBOTS = False
AGENT_MAX_STEPS = 350 # max length of an episode
TARGET_INDEX = None # Index of target for agent. None for random target each episode.
CENTER_START = False # Whether to always put agent in the screen center (True) or initialize randomly (False)
# DESCRIPTION = ''
DESCRIPTION = 'observation: agent pos, target vector, 36 gauss sensors. Learnrate decreased by 10.' \
'Sensors are exactly the part of the reward function that is caused by robots.'
param_names = ['SCREEN_WIDTH', 'SCREEN_HEIGHT', 'N_BINS', 'N_BOTS', 'BOT_RADIUS', 'COLLISION_DISTANCE',
'PLAN_STEPS', 'CHECK_MAX_STEPS', 'RADIUS', 'MIN_DIST', 'SCREEN_TITLE', 'ROBOT_MAX_SPEED',
'AGENT_MAX_SPEED', 'PUNISH_WRONG_DIRECTION', 'WRONG_DIRECTION_CONSTANT', 'REWARD_TARGET_FOUND',
'REWARD_COLLISION', 'REWARD_BOUNDARY', 'TARGET_GAUSS_STD', 'ROBOT_GAUSS_STD', 'ROBOT_DISTANCE_SCALING_CONSTANT', 'ROBOT_REWARD_MAX',
'N_SENSORS', 'DONE_AT_COLLISION', 'IGNORE_ROBOTS', 'AGENT_MAX_STEPS', 'TARGET_INDEX', 'CENTER_START', 'DESCRIPTION']
env_params = {p: eval(p) for p in param_names}
class Shape:
""" Generic base shape class """
def __init__(self, x, y, width, height, angle, color):
self.x = x
self.y = y
self.width = width
self.height = height
self.angle = angle
self.color = color
self.shape_list = None
def draw(self):
pass
class BufferedShape(Shape):
def __init__(self, x, y, width, height, angle, color):
super().__init__(x, y, width, height, angle, color)
def draw(self):
self.shape_list.center_x = self.x
self.shape_list.center_y = self.y
self.shape_list.angle = self.angle
self.shape_list.draw()
class Line(Shape):
def __init__(self, point_list=()):
self._line_width = 2
super().__init__(point_list, list(range(len(point_list))), self._line_width, 0, 0, arcade.color.BLACK)
def draw(self):
# drawing the lines is unbuffered because each line segment may change between frames
# it might make sense to have an option to disable line drawing completely for performance boost
arcade.draw_line_strip(self.x, self.color, self.width)
class RobotShape(BufferedShape):
def __init__(self, xpos, ypos):
self._radius = BOT_RADIUS
super().__init__(xpos, ypos, self._radius, self._radius, 0, arcade.color.GREEN)
shape = arcade.create_ellipse_filled(0, 0,
self.width, self.height,
self.color, self.angle)
self.shape_list = arcade.ShapeElementList()
self.shape_list.append(shape)
point_list = ((self.x, self.y), (self.x + 10, self.y + 10), (self.x + 14, self.y + 18))
self.planned_path = Line(point_list)
def draw(self):
super().draw()
self.planned_path.draw()
def points_on_circumference(center=(0, 0), r=50, n=100):
return [
(
center[0] + (np.cos(2 * np.pi / n * x) * r), # x
center[1] + (np.sin(2 * np.pi / n * x) * r) # y
) for x in range(n)]
def gauss_func(x, mean=0, std=1):
return np.exp(-((x-mean)/std)**2 / 2) / (std * np.sqrt(2*np.pi))
def x_wrap_around(x):
x[x > np.pi] -= 2 * np.pi
x[x < -np.pi] += 2 * np.pi
return x
class Robot:
def __init__(self, xpos, ypos, start_target, end_target):
self.x = xpos
self.y = ypos
self.time = 0
self.delta_average = 0
self.wait = 0
self.has_package = False
self.pick_target = start_target
self.drop_target = end_target
# self.trajectory = points_on_circumference((400,400), 100, 100)
# self.traj_index = 0
point_list = ((self.x, self.y), (self.x + 10, self.y + 10), (self.x + 14, self.y + 18))
# point_list = points_on_circumference((self.x, self.y), UNSAFE_DISTANCE, 100)
# point_list = self.trajectory
self.planned_path = Line(point_list)
def step(self, dt, robots):
# new_pos = self.trajectory[self.traj_index]
# self.traj_index = (self.traj_index + 1) % len(self.trajectory)
# self.x, self.y = new_pos[0], new_pos[1]
# return
if self.delta_average == 0:
self.delta_average = dt
else:
self.delta_average = self.delta_average * 0.8 + dt * 0.2
self.time += dt
if self.wait > 0.0:
self.wait -= dt
if self.wait <= 0.0:
if self.has_package:
# drop package and release target
self.drop_target.blocked = False
self.has_package = False
self.drop_target = None
else:
# pick up package and release target
self.pick_target.blocked = False
self.has_package = True
self.pick_target = None
self.wait = 0.0
else:
return
self.plan(robots)
if len(self.planned_path.x) > 1:
self.x = self.planned_path.x[1][0]
self.y = self.planned_path.x[1][1]
target = self.drop_target if self.has_package else self.pick_target
diffx, diffy = target.x - self.x, target.y - self.y
if abs(diffx) <= MIN_DIST and abs(diffy) <= MIN_DIST:
self.planned_path.x = [(self.x, self.y)]
self.planned_path.y = [self.time]
self.wait = 1.0
def plan(self, robots):
posx = self.x
posy = self.y
target = self.drop_target if self.has_package else self.pick_target
t = self.time
mv_plan = [(posx, posy)]
mv_times = [t]
for s in range(PLAN_STEPS):
left_steps = PLAN_STEPS - s
flag = False
diffx, diffy = target.x - posx, target.y - posy
angle = np.arctan2(diffy, diffx)
d = 0
max = np.pi * 2.0 / (s * 0.2 + 1)
while d < max:
sp = ROBOT_MAX_SPEED
if np.sqrt(diffx**2+diffy**2) < RADIUS:
sp = ROBOT_MAX_SPEED / 2
if not target.blocked:
target.blocked = True
target.blocked_by = self
elif target.blocked_by != self:
sp = 0.0
time = t + (s + 1) * self.delta_average
vx = np.cos(angle + d) * sp
vy = np.sin(angle + d) * sp
if self.check_plan(robots, left_steps, posx, posy, vx, vy, time):
mv_plan.append((posx+vx, posy+vy))
mv_times.append(time)
posx += vx
posy += vy
dx, dy = target.x - posx, target.y - posy
if abs(dx) <= MIN_DIST and abs(dy) <= MIN_DIST:
self.planned_path.x = mv_plan
self.planned_path.y = mv_times
return
flag = True
break
vx = np.cos(angle - d) * sp
vy = np.sin(angle - d) * sp
if self.check_plan(robots, left_steps, posx, posy, vx, vy, time):
mv_plan.append((posx + vx, posy + vy))
mv_times.append(time)
posx += vx
posy += vy
dx, dy = target.x - posx, target.y - posy
if abs(dx) <= MIN_DIST and abs(dy) <= MIN_DIST:
self.planned_path.x = mv_plan
self.planned_path.y = mv_times
return
flag = True
break
d += 0.3
if not flag:
self.planned_path.x = mv_plan
self.planned_path.y = mv_times
return
self.planned_path.x = mv_plan
self.planned_path.y = mv_times
def check_plan(self, robots, left_steps, posx, posy, vx, vy, time):
steps = min(left_steps, CHECK_MAX_STEPS)
for s in range(steps):
pt = time + (s + 1) * self.delta_average
px = posx + (s + 1) * vx
py = posy + (s + 1) * vy
if not self.validate(robots, px, py, pt):
return False
return True
def validate(self, robots, posx, posy, time):
for rob in robots:
if rob != self:
traj = rob.planned_path.x
times = rob.planned_path.y
for j in range(len(traj)):
if abs(times[j] - time) <= 1.5 * self.delta_average:
d = np.sqrt((traj[j][0] - posx)**2 + (traj[j][1] - posy)**2)
if d < COLLISION_DISTANCE:
return False
last_index = len(traj) - 1
if times[last_index] <= time:
d = np.sqrt((traj[last_index][0] - posx)**2 + (traj[last_index][1] - posy)**2)
if d < COLLISION_DISTANCE:
return False
return True
class AgentShape(BufferedShape):
def __init__(self, xpos, ypos):
self._radius = 17.5
super().__init__(xpos, ypos, self._radius, self._radius, 0, arcade.color.BLUE)
shape = arcade.create_ellipse_filled(0, 0,
self.width, self.height,
self.color, self.angle)
lin = arcade.create_line(0, 0, 0+self._radius, 0, arcade.color.WHITE, 5)
self.shape_list = arcade.ShapeElementList()
self.shape_list.append(shape)
self.shape_list.append(lin)
class Agent:
OK = 0
TARGET_FOUND = 1
BOUNDARY_COLLISION = 2
ROBOT_COLLISION = 3
def __init__(self, xpos, ypos, first_target, robots):
self.x = xpos
self.y = ypos
# self.angle_pi6 = 0 # angle in multiples of pi/6, to avoid accumulating round-off error
self.angle = 0
self.angle_error = 0
self.has_package = False
self.target = first_target
diffy, diffx = self.target.y - self.y, self.target.x - self.x
self.angle_to_destination = np.arctan2(diffy, diffx)
self.angle_error = self.angle_to_destination - self.angle
self.dist_to_target = np.sqrt(diffy**2 + diffx**2)
self._radius = 17.5
# pi6 = np.pi/6
# self.sensor_boundaries = [-2*pi6, -pi6, 0, pi6, 2*pi6, 3*pi6]
# self.sensor_boundaries_all = [-5*pi6, -4*pi6, -3*pi6, -2*pi6, -pi6, 0, pi6, 2*pi6, 3*pi6, 4*pi6, 5*pi6, np.pi]
self.gauss_sensor_x = np.arange(1, N_SENSORS+1) * (2*np.pi / N_SENSORS) - np.pi
self.sensor_values = [0]*N_SENSORS
# self.dist_to_rob = SCREEN_WIDTH+SCREEN_HEIGHT
# self.dist_to_wall = min((self.x, SCREEN_WIDTH-self.x, self.y, SCREEN_HEIGHT-self.y))
# self.update_sensors(robots)
self.target_gauss_scaling = 1 / gauss_func(self.angle_to_destination, mean=self.angle_to_destination, std=TARGET_GAUSS_STD)
self.robot_angles = []
self.robot_distances = []
self.robot_gauss = []
self.robot_gauss_scaling = []
for r in robots:
C = ROBOT_DISTANCE_SCALING_CONSTANT
diffx, diffy = r.x-self.x, r.y-self.y
rob_angle = np.arctan2(diffy, diffx)
rob_distance = np.sqrt(np.sum(diffx**2 + diffy**2))
self.robot_angles.append(rob_angle)
self.robot_distances.append(rob_distance)
distance_to_collision = COLLISION_DISTANCE - rob_distance
distance_scaling = -(2 / np.exp(800 / C)) * np.exp((800 - distance_to_collision) / C) # heuristic
rob_gauss_scaling = distance_scaling / gauss_func(rob_angle, mean=rob_angle, std=ROBOT_GAUSS_STD)
self.robot_gauss_scaling.append(rob_gauss_scaling)
self.update_gauss_sensors()
def step(self, action, robots):
# def distance_to_closest_robot(x, y, robots):
# d = SCREEN_HEIGHT+SCREEN_WIDTH
# d_min = SCREEN_HEIGHT+SCREEN_WIDTH
# for rob in robots:
# dx = rob.x - x
# dy = rob.y - y
# d = np.sqrt(dx**2 + dy**2)
#
# if d <= COLLISION_DISTANCE:
# return 0
#
# if d < d_min:
# d_min = d
#
# return d_min
action_length = np.sqrt(np.sum(action ** 2))
if action_length > AGENT_MAX_SPEED:
action = (action / action_length) * AGENT_MAX_SPEED
action_length = AGENT_MAX_SPEED
nx = self.x + action[0]
ny = self.y + action[1]
pre_diffx, pre_diffy = self.target.x - self.x, self.target.y - self.y
if not IGNORE_ROBOTS:
for ri, r in enumerate(robots):
rob_diffx, rob_diffy = r.x - self.x, r.y - self.y
self.robot_angles[ri] = np.arctan2(rob_diffy, rob_diffx)
self.robot_distances[ri] = np.sqrt(np.sum(rob_diffx ** 2 + rob_diffy ** 2))
min_dist_to_rob = min(self.robot_distances)
if min_dist_to_rob <= COLLISION_DISTANCE:
return Agent.ROBOT_COLLISION, REWARD_COLLISION
min_dist_to_wall = min((nx, SCREEN_WIDTH-nx, ny, SCREEN_HEIGHT-ny))
if min_dist_to_wall < 0:
return Agent.BOUNDARY_COLLISION, REWARD_BOUNDARY
self.x = nx
self.y = ny
diffx, diffy = self.target.x - self.x, self.target.y - self.y
self.dist_to_target = np.sqrt(diffy**2 + diffx**2)
if abs(diffx) <= MIN_DIST and abs(diffy) <= MIN_DIST:
# target reached
self.has_package = not self.has_package
self.target.active = False
self.target = None
return Agent.TARGET_FOUND, REWARD_TARGET_FOUND
# self.update_sensors(robots)
self.angle_to_destination = np.arctan2(pre_diffy, pre_diffx) # Winkel zum Ziel (von Ausgangsposition)
action_angle = np.arctan2(action[1], action[0])
self.angle_error = self.angle_to_destination - action_angle
self.target_gauss_scaling = 1 / gauss_func(self.angle_to_destination, mean=self.angle_to_destination, std=TARGET_GAUSS_STD)
reward = self.target_gauss_scaling * \
gauss_func(action_angle, mean=self.angle_to_destination, std=TARGET_GAUSS_STD)
if not IGNORE_ROBOTS:
C = ROBOT_DISTANCE_SCALING_CONSTANT
for ri, r in enumerate(robots):
rob_angle = self.robot_angles[ri]
distance_to_collision = self.robot_distances[ri] - COLLISION_DISTANCE
distance_scaling = (ROBOT_REWARD_MAX / np.exp(800/C)) * np.exp((800 - distance_to_collision)/C) # heuristic
rob_gauss_scaling = distance_scaling/gauss_func(rob_angle, mean=rob_angle, std=ROBOT_GAUSS_STD)
robot_reward = rob_gauss_scaling*gauss_func(action_angle, mean=rob_angle, std=ROBOT_GAUSS_STD)
reward += robot_reward
self.robot_gauss_scaling[ri] = rob_gauss_scaling
if not IGNORE_ROBOTS:
self.update_gauss_sensors()
reward *= action_length
if abs(self.angle_error) > np.pi/2 and PUNISH_WRONG_DIRECTION:
reward = - action_length * ((2 / np.pi) * abs(self.angle_error) - (1 + WRONG_DIRECTION_CONSTANT))
return Agent.OK, reward
def update_gauss_sensors(self):
robots_y = np.zeros(N_SENSORS)
for ri in range(len(self.robot_angles)):
rob_gauss_scaling = self.robot_gauss_scaling[ri]
rob_angle = self.robot_angles[ri]
rob_y = rob_gauss_scaling * gauss_func(self.gauss_sensor_x + rob_angle, mean=rob_angle, std=ROBOT_GAUSS_STD)
rob_x = x_wrap_around(self.gauss_sensor_x + self.robot_angles[ri])
rob_sortind = np.argsort(rob_x)
rob_y = rob_y[rob_sortind]
robots_y += rob_y
self.sensor_values = robots_y
# def update_sensors(self, robots):
# agent_angle = self.angle
# # if agent_angle > np.pi:
# # agent_angle -= 2*np.pi # angle should be in {-pi/2, pi/2}
# pi6 = np.pi/6
# angle_by_pi6 = agent_angle / pi6
# rotation_steps = int(np.ceil(angle_by_pi6)) # by how many steps entries in sensor list need to be shifted
# angle_delta = (angle_by_pi6 - rotation_steps) * pi6 # to subtract from sensor boundaries for calculation
# boundary_values = [0] * 12
# for ai, ang in enumerate(self.sensor_boundaries):
# sensor_angle = angle_delta + ang
# sin = np.sin(sensor_angle)
# cos = np.cos(sensor_angle)
# if abs(cos) > 1e-5:
# m = sin / cos # y = mx + b <-> b = y - mx
# b = self.y - m * self.x # <-> x = (y-b)/m
# x1 = SCREEN_WIDTH
# y1 = m * x1 + b
# if y1 > SCREEN_HEIGHT:
# y1 = SCREEN_HEIGHT
# x1 = (y1 - b) / m
# value_right = np.sqrt((x1 - self.x) ** 2 + (y1 - self.y) ** 2)
# x0 = 0
# y0 = m * x0 + b
# if y0 < 0:
# y0 = 0
# x0 = (y0 - b) / m
# value_left = np.sqrt((x0 - self.x) ** 2 + (y0 - self.y) ** 2)
# else:
# # denominator almost 0 (vertical line) -> do sth else
# # x constant at self.x
# # y every value, including 0 and SCREEN_HEIGHT
# if ai > 0:
# value_right = SCREEN_HEIGHT - self.y
# value_left = self.y
# else:
# value_left = SCREEN_HEIGHT - self.y
# value_right = self.y
# boundary_values[(ai-rotation_steps) % 12] = value_right
# boundary_values[(ai+6-rotation_steps) % 12] = value_left
# boundary_values.append(boundary_values[0]) # tiny wrap-around
# for si in range(len(self.sensor_values)):
# self.sensor_values[si] = np.min(boundary_values[si:si + 2]) - 17.5
#
# for r in robots:
# diffx, diffy = r.x - self.x, r.y - self.y
# angle_to_robot = np.arctan2(diffy, diffx)
# angle_r = angle_to_robot - angle_delta
# if angle_r > np.pi:
# angle_r -= 2*np.pi
# # distance is from center to center, but sensor would measure from edge to edge, so radii are subtracted
# distance_to_robot = np.sqrt(diffx**2 + diffy**2) - BOT_RADIUS - 17.5
# # sensor boundaries begin with -5*pi6. If bisect returns 0 that means angle < -5*pi6,
# # which is sensor number 8. So we add 8 to the index, and take modulo 12 to wrap indices around.
# sensor_index = (bisect.bisect(self.sensor_boundaries_all, angle_r) + 8) % 12
# self.sensor_values[sensor_index] = distance_to_robot
class TargetShape(BufferedShape):
def __init__(self, xpos, ypos):
self._width = 35
super().__init__(xpos, ypos, self._width, self._width, 0, arcade.color.MAGENTA)
shape = arcade.create_rectangle_filled(0, 0,
self.width, self.height,
self.color, self.angle)
self.shape_list = arcade.ShapeElementList()
self.shape_list.append(shape)
def change_color(self, new_color):
self.color = new_color
shape = arcade.create_rectangle_filled(0, 0,
self.width, self.height,
self.color, self.angle)
self.shape_list = arcade.ShapeElementList()
self.shape_list.append(shape)
class Target:
def __init__(self, xpos, ypos):
self.x = xpos
self.y = ypos
self.blocked = False
self.blocked_by = None
self.active = False
class Wind(arcade.Window):
def __init__(self, master, render=False, plot_reward=False):
super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
self.background_color = arcade.color.WHITE
self.master = master
self.draw_time = 0
self.frame_count = 0
self.fps_start_timer = None
self.fps = None
self.step_time = timeit.default_timer()
self.robots = []
self.start_targets = []
self.end_targets = []
self.agent = AgentShape(self.master.agent.x, self.master.agent.y)
for r in self.master.robots:
self.robots.append(RobotShape(r.x, r.y))
self.robots[-1].planned_path = r.planned_path
for t in self.master.start_targets:
self.start_targets.append(TargetShape(t.x, t.y))
if t.active:
self.start_targets[-1].change_color(arcade.color.RED_ORANGE)
for t in self.master.end_targets:
self.end_targets.append(TargetShape(t.x, t.y))
if t.active:
self.end_targets[-1].change_color(arcade.color.RED_ORANGE)
if plot_reward:
pi = np.pi
self.gauss_x = np.arange(1, 101) * (pi/50) - pi
self.draw_x = np.array(self.gauss_x)
# self.gauss_x_inner = self.gauss_x[24:75]
# self.gauss_x_left = self.gauss_x[:24]
# self.gauss_x_right = self.gauss_x[75:]
self.target_y = np.zeros(100)
self.robots_y = np.zeros(100)
self.overall_y = np.zeros(100)
plt.axis([-pi, pi, -2, 1])
self.ax = plt.gca()
self.ax.axhline(0, color='black', lw=1)
self.ax.axvline(0, color='black', lw=1)
self.ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 2))
self.ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 12))
self.ax.xaxis.set_major_formatter(plt.FuncFormatter(multiple_formatter()))
plt.ion()
plt.show()
self.line_target, = self.ax.plot(self.draw_x, self.target_y, color='green')
self.line_robot, = self.ax.plot(self.draw_x, self.robots_y, color='red')
self.line_overall, = self.ax.plot(self.draw_x, self.overall_y, color='black')
self.rendering = render
self.plot_reward = plot_reward
self.closed = False
@self.event
def on_close():
# print("I'm closing now")
self.closed = True
self.close()
def update_diagram_data(self):
self.target_y = self.master.agent.target_gauss_scaling * gauss_func(
self.gauss_x + self.master.agent.angle_to_destination,
mean=self.master.agent.angle_to_destination, std=TARGET_GAUSS_STD)
if PUNISH_WRONG_DIRECTION:
self.target_y[:25] = - ((2 / np.pi) * abs(self.gauss_x[:25]) - (1 + WRONG_DIRECTION_CONSTANT))
self.target_y[75:] = - ((2 / np.pi) * abs(self.gauss_x[75:]) - (1 + WRONG_DIRECTION_CONSTANT))
self.robots_y = np.zeros(100)
if not IGNORE_ROBOTS:
for ri in range(len(self.master.robots)):
# rob_gauss = self.master.agent.robot_gauss[ri]
rob_gauss_scaling = self.master.agent.robot_gauss_scaling[ri]
rob_angle = self.master.agent.robot_angles[ri]
rob_y = rob_gauss_scaling * gauss_func(self.gauss_x + rob_angle, mean=rob_angle, std=ROBOT_GAUSS_STD)
rob_x = x_wrap_around(self.gauss_x + self.master.agent.robot_angles[ri])
rob_sortind = np.argsort(rob_x)
rob_y = rob_y[rob_sortind]
self.robots_y += rob_y
self.draw_x = x_wrap_around(self.gauss_x + self.master.agent.angle_to_destination)
sortind = np.argsort(self.draw_x)
self.draw_x = self.draw_x[sortind]
self.target_y = self.target_y[sortind]
self.overall_y = self.target_y + self.robots_y
def on_update(self, dt):
def color_check(t, tS):
if t.active and tS.color == arcade.color.MAGENTA:
tS.change_color(arcade.color.RED_ORANGE)
elif not t.active and tS.color == arcade.color.RED_ORANGE:
tS.change_color(arcade.color.MAGENTA)
self.agent.x = self.master.agent.x
self.agent.y = self.master.agent.y
# angle is in rad, but arcade used deg angle. This has to be converted here
self.agent.angle = self.master.agent.angle*(180 / np.pi)
for r, rS in zip(self.master.robots, self.robots):
rS.x = r.x
rS.y = r.y
rS.planned_path = r.planned_path
for t, tS in zip(self.master.start_targets, self.start_targets):
tS.x = t.x
tS.y = t.y
color_check(t, tS)
for t, tS in zip(self.master.end_targets, self.end_targets):
tS.x = t.x
tS.y = t.y
color_check(t, tS)
if self.plot_reward:
self.update_diagram_data()
def on_draw(self):
"""
Render the screen.
"""
# Start timing how long this takes
draw_start_time = timeit.default_timer()
if self.frame_count % 60 == 0:
if self.fps_start_timer is not None:
total_time = timeit.default_timer() - self.fps_start_timer
self.fps = 60 / total_time
self.fps_start_timer = timeit.default_timer()
self.frame_count += 1
arcade.start_render()
for shape in self.robots:
shape.draw()
self.agent.draw()
for shape in self.start_targets:
shape.draw()
for shape in self.end_targets:
shape.draw()
# Display timings
output = f"Processing time: {self.master.processing_time:.3f}"
arcade.draw_text(output, 20, SCREEN_HEIGHT - 20, arcade.color.BLACK, 16)
output = f"Drawing time: {self.draw_time:.3f}"
arcade.draw_text(output, 20, SCREEN_HEIGHT - 40, arcade.color.BLACK, 16)
if self.fps is not None:
output = f"FPS: {self.fps:.0f}"
arcade.draw_text(output, 20, SCREEN_HEIGHT - 60, arcade.color.BLACK, 16)
if self.plot_reward:
self.line_target.set_xdata(self.draw_x)
self.line_target.set_ydata(self.target_y)
self.line_robot.set_xdata(self.draw_x)
self.line_robot.set_ydata(self.robots_y)
self.line_overall.set_xdata(self.draw_x)
self.line_overall.set_ydata(self.overall_y)
plt.draw()
plt.pause(0.001)
self.draw_time = timeit.default_timer() - draw_start_time
def step(self):
arcade.pyglet.clock.tick()
# making sure framerate is not well above 60 fps
start_time = timeit.default_timer()
dt = start_time - self.step_time
self.step_time = start_time
dt_difference = 0.0155 - dt
if dt_difference > 0:
time.sleep(dt_difference)
self.switch_to()
self.dispatch_events()
if self.closed:
return
self.dispatch_event('on_draw')
self.flip()
class App(gym.Env):
""" Main application class. """
def __init__(self, always_render=False, plot_reward=False, verbose=False):
self.print = True
self.robots = []
self.agent = None
self.step_return = 0
self.agent_angle = 0
self.agent_dx = 0
self.agent_dy = 0
self.agent_speed = 0
self.start_targets = []
self.end_targets = []
self.cum_reward = 0
self.always_render = always_render
self.plot_reward = plot_reward
self.verbose = verbose
self.processing_time = 0
self.step_time = timeit.default_timer()
self.done = False
self.step_count = 0
self.max_steps = AGENT_MAX_STEPS
self.rng = np.random.default_rng()
# maxdist = np.sqrt(SCREEN_WIDTH**2 + SCREEN_HEIGHT**2)
# space_len = (2 + N_BOTS)
# self.observation_space = gym.spaces.box.Box(np.array([0, 0] + [-800, -800] * (space_len-1)), np.array([800, 800] * space_len), (2 * space_len,))
# space_len = 2
self.observation_space = gym.spaces.box.Box( # x-y-agent, x-y-vector-to-target, 12-distance-sensor-values
np.array([0, 0] + [-SCREEN_WIDTH, -SCREEN_HEIGHT] + [0]*N_SENSORS),
np.array([SCREEN_WIDTH, SCREEN_HEIGHT]*2 + [np.sqrt(SCREEN_WIDTH**2 + SCREEN_HEIGHT**2)]*N_SENSORS),
(4 + N_SENSORS,))
# self.observation_space = gym.spaces.box.Box( # x-y-agent, x-y-vector-to-target, 12-distance-sensor-values
# np.array([0, 0] + [-SCREEN_WIDTH, -SCREEN_HEIGHT] + [0]*12),
# np.array([SCREEN_WIDTH, SCREEN_HEIGHT]*2 + [np.sqrt(SCREEN_WIDTH**2 + SCREEN_HEIGHT**2)]*12),
# (16,))
# self.observation_space = gym.spaces.box.Box( # x-y-vector-to-target, 12-distance-sensor-values
# np.array([-SCREEN_WIDTH, -SCREEN_HEIGHT] + [0]*12),
# np.array([SCREEN_WIDTH, SCREEN_HEIGHT] + [np.sqrt(SCREEN_WIDTH**2 + SCREEN_HEIGHT**2)]*12),
# (14,))
# self.observation_space = gym.spaces.box.Box( # dist-to-target, angle error, 12-distance-sensor-values
# np.array([0, -np.pi/2] + [0]*12),
# np.array([maxdist, np.pi/2] + [maxdist]*12),
# (14,))
self.action_space = gym.spaces.box.Box(np.array([-AGENT_MAX_SPEED, -AGENT_MAX_SPEED]), np.array([AGENT_MAX_SPEED, AGENT_MAX_SPEED]), (2,))
# self.action_space = gym.spaces.Discrete(3) # 0: forward, 1: turn right pi/6, 2: turn left pi/6
self.wind = None
def setup(self):
""" Set up the game and initialize the variables. """
self.print = True
self.robots = []
self.agent = None
self.start_targets = []
self.end_targets = []
self.step_count = 0
self.done = False
robot_rng = np.random.default_rng()
def near_robot(x, y, robots):
d = SCREEN_HEIGHT
for rob in robots:
dx = rob.x - x
dy = rob.y - y
d = np.sqrt(dx**2 + dy**2)
if d <= COLLISION_DISTANCE:
return True
return False
space = (SCREEN_HEIGHT - 100) / (N_BINS - 1)
for i in range(N_BINS):
self.start_targets.append(Target(50, 50 + i * space))
self.end_targets.append(Target(SCREEN_WIDTH - 50, 50 + i * space))
# self.start_targets.append(Target(50 + i * space, 50))
# self.end_targets.append(Target(50 + i * space, SCREEN_HEIGHT - 50))
for i in range(N_BOTS):
# rx = self.rng.random()
# ry = self.rng.random()
rx = robot_rng.random()
ry = robot_rng.random()
nx = rx * (SCREEN_WIDTH - 150) + 75
ny = ry * (SCREEN_HEIGHT - 150) + 75
while near_robot(nx, ny, self.robots):
# rx = self.rng.random()
# ry = self.rng.random()
rx = robot_rng.random()
ry = robot_rng.random()
nx = rx * (SCREEN_WIDTH - 150) + 75
ny = ry * (SCREEN_HEIGHT - 150) + 75
# nx, ny = SCREEN_WIDTH/2, SCREEN_HEIGHT/2
# ti_start = self.rng.integers(0, N_BINS-1)
# ti_end = self.rng.integers(0, N_BINS - 1)
ti_start = robot_rng.integers(0, N_BINS)
ti_end = robot_rng.integers(0, N_BINS)
self.robots.append(Robot(nx, ny, self.start_targets[ti_start], self.end_targets[ti_end]))
# self.robots[-1].has_package = self.rng.random() < 0.5
self.robots[-1].has_package = robot_rng.random() < 0.5
if CENTER_START:
nx = SCREEN_WIDTH / 2
ny = SCREEN_HEIGHT / 2
else:
rx = self.rng.random()
ry = self.rng.random()
nx = rx * (SCREEN_WIDTH - 150) + 75
ny = ry * (SCREEN_HEIGHT - 150) + 75
while near_robot(nx, ny, self.robots):
rx = self.rng.random()
ry = self.rng.random()
nx = rx * (SCREEN_WIDTH - 150) + 75
ny = ry * (SCREEN_HEIGHT - 150) + 75
if TARGET_INDEX is None:
ti_start = self.rng.integers(0, N_BINS )
package = self.rng.random() < 0.5
else:
ti_start = TARGET_INDEX % N_BINS
package = TARGET_INDEX // N_BINS
if package:
targets = self.end_targets
else:
targets = self.start_targets
self.agent = Agent(nx, ny, targets[ti_start], self.robots)
self.agent.target.active = True
self.agent.has_package = package
if self.wind is None and self.always_render:
self.wind = Wind(self, self.always_render, self.plot_reward)
def step(self, action):
self.step_count += 1
# Ehemals update()
""" Move everything """
start_time = timeit.default_timer()
dt = start_time - self.step_time
if not IGNORE_ROBOTS and ROBOT_MAX_SPEED > 0:
for r in self.robots:
r.step(dt, self.robots)
if r.drop_target is None:
r.drop_target = self.end_targets[self.rng.integers(0, N_BINS )]
if r.pick_target is None:
r.pick_target = self.start_targets[self.rng.integers(0, N_BINS)]
self.step_time = timeit.default_timer()
signal, reward = self.agent.step(action, self.robots)
# print('distance = {:.2f}, reward = {:.2f} * 8'.format(self.agent.robot_distances[0], reward/8))
if signal == Agent.TARGET_FOUND:
if self.verbose:
print("Target Found! Reward: {}".format(REWARD_TARGET_FOUND))
self.done = True
if signal == Agent.ROBOT_COLLISION and DONE_AT_COLLISION:
self.done = True
if signal == Agent.BOUNDARY_COLLISION:
self.done = True
if self.agent.target is None:
if TARGET_INDEX is None:
ti = self.rng.integers(0, N_BINS)
else:
ti = TARGET_INDEX % N_BINS
self.agent.target = self.end_targets[ti] if self.agent.has_package else self.start_targets[ti]
self.agent.target.active = True
self.processing_time = timeit.default_timer() - start_time
if self.wind is not None:
if self.wind.rendering:
self.wind.step()
else:
arcade.pyglet.clock.tick()
if self.step_count >= self.max_steps:
if self.verbose:
print("time's up!")
self.done = True
self.cum_reward += reward
if self.done:
if self.verbose:
print("Cumulative Reward for this episode: {}".format(self.cum_reward))
self.cum_reward = 0
# return observation, reward, done, info
rob_pos = [[r.x - self.agent.x, r.y - self.agent.y] for r in self.robots]
# return np.array([self.agent.x, self.agent.y] +
# [self.agent.target.x - self.agent.x, self.agent.target.y - self.agent.y] +
# [coord for coord_list in rob_pos for coord in coord_list]), reward, self.done, dict()
return np.concatenate(([self.agent.x, self.agent.y],
[self.agent.target.x - self.agent.x, self.agent.target.y - self.agent.y],
self.agent.sensor_values)), reward, self.done, dict()
# return np.array([self.agent.dist_to_target, self.agent.angle_error] +
# self.agent.sensor_values), reward, self.done, dict()
def reset(self):
if self.wind is not None and not self.always_render:
self.wind.rendering = False
self.setup()
rob_pos = [[r.x - self.agent.x, r.y - self.agent.y] for r in self.robots]
# return np.array([self.agent.x, self.agent.y] +
# [self.agent.target.x - self.agent.x, self.agent.target.y - self.agent.y] +
# [coord for coord_list in rob_pos for coord in coord_list])
return np.concatenate(([self.agent.x, self.agent.y],
[self.agent.target.x - self.agent.x, self.agent.target.y - self.agent.y],
self.agent.sensor_values))
# return np.array([self.agent.dist_to_target, self.agent.angle_error] +
# self.agent.sensor_values)
def render(self, mode='human'):
if self.wind is None:
self.wind = Wind(self, render=True, plot_reward=self.plot_reward)
if not self.wind.rendering:
self.wind.rendering = True
# if self.print:
# self.print = False
# print("Rendering is always on")
def main():
app = App(always_render=True, plot_reward=True)
app.setup()
app.render()
app.agent.x, app.agent.y = 600, 600
app.robots[0].x, app.robots[0].y = 450, 450
# while app.wind is None or not app.wind.closed:
for i in range(100):
print(i)
app.step(np.array([-AGENT_MAX_SPEED, -AGENT_MAX_SPEED]))
app.wind.on_update(1)
app.wind.on_draw()
time.sleep(2)
# arcade.run()
if __name__ == '__main__':
main()
| [
"64753087+FranziskaGoerler@users.noreply.github.com"
] | 64753087+FranziskaGoerler@users.noreply.github.com |
f27c14584dc3cf409eafba3d068e89802cc3b6b8 | d5d0ea5615fc5156837d22efafc83f3e78d79cf6 | /WebApp.py | 21f321d0a03b021dedfe46d517d2d40850924471 | [] | no_license | RodrigoAntoniaci/WYSP | b68617b469b531c484d37331eb37c4abe5aaa733 | d0ad84d06866b3a7201c9483fa2ecca8e7887e20 | refs/heads/master | 2023-01-20T15:39:14.290310 | 2020-12-03T12:01:45 | 2020-12-03T12:01:45 | 283,348,417 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,282 | py | #Libraries
import streamlit as st
import pandas as pd
import base64
#Importing code to calculate distance
from Calc_Dist import PlayIt
#Loading Dataframe to calculate distance
@st.cache
def load_dataset():
dataframe = pd.read_csv('dummy_ign.csv',sep='|')
return dataframe
dataset = load_dataset()
@st.cache
def get_table_download_link(df):
"""Generates a link allowing the data in a given panda dataframe to be downloaded
in: dataframe
out: href string
"""
csv = df.to_csv(index=False)
b64 = base64.b64encode(csv.encode()).decode() # some strings <-> bytes conversions necessary here
href = f'<a href="data:file/csv;base64,{b64}">Download: Right click here and save as CSV</a>'
return href
#Creating Dict structure of user's choice
def Calc_result(dataframe,platform,theme1,theme2,old,critic,metric,n_results):
user_dict = {'title':["User's choice"], 'release_date':[None],'score':[None], 'score_phrase':[None],'editors_choice':[None],
'genre':[None],'url':[None],'old_game':[0], 'critic_high_score':[0],'Sony':[0],'Microsoft':[0],'Nintendo':[0],
'Portable':[0],'Old_Consoles':[0],'Mobile':[0],'PC':[0],'Others_Plat':[0],'Playstation_4':[0],'Xbox_One':[0],
'Wii_U':[0],'Action':[0],'Adult':[0],'Adventure':[0],'Baseball':[0],'Battle':[0],'Board':[0],'Card':[0],
'Casino':[0],'Compilation':[0],'Editor':[0],'Educational':[0],'Episodic':[0],'Fighting':[0],'First-Person':[0],
'Flight':[0],'Golf':[0],'Hardware':[0],'Hunting':[0],'Music':[0],'Other':[0],'Party':[0],'Pet':[0],'Pinball':[0],
'Platformer':[0],'Productivity':[0],'Puzzle':[0],'RPG':[0],'Racing':[0],'Shooter':[0],'Simulation':[0],'Sports':[0],
'Strategy':[0],'Trivia':[0],'Virtual':[0],'Word':[0],'Wrestling':[0]}
if old == 'Hell Yeah':
user_dict['old_game'] = [1]
else:
pass
if critic == 'Yes, milord':
user_dict['critic_high_score'] = [1]
else:
pass
for key,value in user_dict.items():
if key == theme1 or key == theme2 or key == platform:
user_dict[key] = [1]
else:
pass
calc = PlayIt(dataframe,user_dict,metric=metric, n_results=n_results)
return calc.play_it()
st.sidebar.markdown('# IronHack - Final Project')
st.sidebar.markdown('# What You Should Play')
st.sidebar.markdown('## Description: \n\n Content-based game recommender system, calculates multi-dimensional distance between **User Input** VS **[Kaggle IGN Database](https://github.com/john7obed/ign_games_of_20_years/blob/master/ign.csv)**.')
st.sidebar.markdown('## Created by: \n\n **Rodrigo Sampaio Antoniaci**')
st.title('Choose Your Weapons')
#Initilizing Class to load Select Fields
play = PlayIt()
#Select Box of Platform
st.markdown('### **Choose a Console or Fabricant**')
platform = st.selectbox('',(play.platforms))
#Select Box of Theme 1
st.markdown('### **And what about the genres, which do you like the most?**')
themes1 = st.selectbox('',(play.themes))
#Select Box of Theme 2
st.markdown('### **Choose another on the house, if you want of course**')
themes2 = st.selectbox("",(play.themes),index=2)
#Select Box of Old
st.markdown('### **Would you like this game be an old one?** \n\n **We consider everything before 2k old... Milennials**')
old = st.selectbox("¯\__(ツ)__/¯",('Hell Yeah', 'Nops' ))
#Select Box of Critic Score
st.markdown('### **Would you like this game have high score by critics?**')
critic = st.selectbox("",('Yes, milord', 'Hate this guys' ))
#Select Box of Metric
st.markdown('### **What kind of metric do you want to use?**')
metric = st.selectbox("",('cityblock', 'cosine', 'euclidean'),index=2)
#Input of the number of results the user
st.markdown('### **How many results do you want to see?**')
n_results = st.number_input('',min_value=10,max_value=100,value=20)
#Button to run the distance calculation
apply_button = st.button("Lets play a game")
if apply_button:
result = Calc_result(dataset,platform,themes1,themes2,old,critic,metric,n_results)
st.markdown('# **Have a nice play time ;D**')
st.markdown(f'## {get_table_download_link(result)}', unsafe_allow_html=True)
st.dataframe(result)
else:
pass
| [
"rodrigo.antoniaci@gmail.com"
] | rodrigo.antoniaci@gmail.com |
b7bfc9d90761700d6f7d5eeb648630549208a4e7 | 0524c932fbe5ac9d9e7a28831249bc30f14185a8 | /Task 4/problem2.py | dc8178f5532d71d963e7d204627ad062b2b3ab25 | [] | no_license | devmeraj/python_practice | 5050487587c125fab5b7d1853a13128813ce0124 | d7ae22e10b7fe37f94e3a68790dda031e4c891ad | refs/heads/master | 2020-06-19T21:24:27.547675 | 2019-07-14T20:09:21 | 2019-07-14T20:09:21 | 196,879,288 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 241 | py | # Write a Python program to read first n lines of a file
def readLine(fileName, nLine):
with open(fileName, 'r') as myFile:
for i in range(1, nLine + 1):
print(myFile.readlines(i)[0], '\n')
readLine('test.txt', 4) | [
"merajulnu@gmail.com"
] | merajulnu@gmail.com |
79807061dd68c41f7f3c0ffcb032d69f63ae5ad5 | f0cce1eb9d88fd3696822f1a1e021b4d0ae64ef5 | /system_model/Behavior Models/initialize_agent.py | 0d21c4430e032d74443cc6b93c2a59923631fc44 | [
"BSD-3-Clause"
] | permissive | arpa-e-transnet/incenTrip_systemmodel_sharing | dda872dc7e9edafc3acf81871519953b65742687 | 8dc0618704faaded9c63dbec5e793a5a10fa7110 | refs/heads/master | 2020-03-30T18:09:46.509404 | 2018-09-12T22:12:22 | 2018-09-12T22:12:22 | 151,486,574 | 0 | 1 | BSD-3-Clause | 2018-10-03T22:06:50 | 2018-10-03T22:06:49 | null | UTF-8 | Python | false | false | 2,789 | py | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 26 22:39:48 2017
@author: cxiong
"""
import pandas as pd
import pickle
import time
import random
start_time = time.time()
agent=pd.read_csv('output_agent_day0.csv')
with open('taz_dic.pickle') as f: # Python 3: open(..., 'rb')
taz_dic = pickle.load(f)
del taz_dic[98]
del taz_dic[934]
agent.assign(emp=0, inc=0, sex=0, rac=0)
start_time = time.time()
for index, row in agent.iterrows():
if int(index)%1000 == 0:
print str(int(index/1000))+'000 records completed'
rd_num1 = random.random()
rd_num2 = random.random()
rd_num3 = random.random()
rd_num4 = random.random()
taz = int(row['from_zone_id'])
try: dem_data = taz_dic[taz]
except:
taz = random.choice(taz_dic.keys())
dem_data = taz_dic[taz]
if rd_num1 > dem_data['sex'][0]:
agent.set_value(index, 'sex', 1)
if rd_num2 > dem_data['esr'][0]:
agent.set_value(index, 'emp', 1)
if rd_num3 > dem_data['rac'][0]:
agent.set_value(index, 'rac', 1)
tmp = len(dem_data['inc'])
if tmp == 2:
if rd_num4 > dem_data['inc'][0]:
agent.set_value(index, 'inc', 1)
elif tmp == 3:
if rd_num4 > dem_data['inc'][0] and rd_num3 <= dem_data['inc'][0]+dem_data['inc'][1]:
agent.set_value(index, 'inc', 1)
elif rd_num4 > dem_data['inc'][0]+dem_data['inc'][1] and rd_num3 <= dem_data['inc'][0]+dem_data['inc'][1]+dem_data['inc'][2]:
agent.set_value(index, 'inc', 2)
elif tmp == 4:
if rd_num4 > dem_data['inc'][0] and rd_num3 <= dem_data['inc'][0]+dem_data['inc'][1]:
agent.set_value(index, 'inc', 1)
elif rd_num4 > dem_data['inc'][0]+dem_data['inc'][1] and rd_num3 <= dem_data['inc'][0]+dem_data['inc'][1]+dem_data['inc'][2]:
agent.set_value(index, 'inc', 2)
elif rd_num4 > 1- dem_data['inc'][3]:
agent.set_value(index, 'inc', 3)
elif tmp == 5:
if rd_num4 > dem_data['inc'][0] and rd_num3 <= dem_data['inc'][0]+dem_data['inc'][1]:
agent.set_value(index, 'inc', 1)
elif rd_num4 > dem_data['inc'][0]+dem_data['inc'][1] and rd_num3 <= dem_data['inc'][0]+dem_data['inc'][1]+dem_data['inc'][2]:
agent.set_value(index, 'inc', 2)
elif rd_num4 <= 1- dem_data['inc'][4] and rd_num3 > 1- dem_data['inc'][4]- dem_data['inc'][3]:
agent.set_value(index, 'inc', 3)
elif rd_num4 > 1- dem_data['inc'][4]:
agent.set_value(index, 'inc', 4)
print("--- %s seconds ---" % (time.time() - start_time))
with open('synthetic_pop.pickle', 'wb') as handle:
pickle.dump(agent, handle)
#check if the dictionary keys are empty
#for item in taz_dic:
# if len(taz_dic[item]['sex'])==0:
# del taz_dic[item] | [
"cxiong@umd.edu"
] | cxiong@umd.edu |
72f5b3b1beeb6ae2469e57609e9fa66f74c5566c | 80cfb5f42bc93433249bb2789be33208bb037679 | /platin/httpservices/scheduler.py | b16c257c1b936671383999f9cd92f8d4d535bdf5 | [] | no_license | legibe/platin | b3960975c214b99d699fc3c8d5e94d473d173a8c | 430c4421ac2056c3041c1ac4b7f950c202334fb4 | refs/heads/master | 2020-12-24T21:28:15.740529 | 2016-05-13T00:29:53 | 2016-05-13T00:29:53 | 55,983,322 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,204 | py | #--------------------------------------------------------------------------------
# Author: Claude Gibert
#
#--------------------------------------------------------------------------------
from twisted.internet import reactor
from ..core.date import utcNow
"""
A convenience class to use some of the features of the twisted reactor.
Here it is about scheduling jobs, in the different methods, any extra
arguments, either named or not are sent to the action when it is called.
- repeatAction: periodic action every "repeat" seconds.
- delayAction: excutes a task once only after the given delay in seconds.
- repeatRoundTimeAction: same as repeat action but calls the action on round
values of time, e.g. every n minutes. The argument 'delay' is added to the
round time. For example:
repeatRoundTimeAction(action,3600,300) will call action every hour,
5 minutes after the hour.
- run: to call to start the twisted reactor loop. If you are using
an http server as well, class HTTPServer, just call server.run(...)
"""
class Scheduler(object):
def repeatAction(self, action, repeat, *args, **kwargs):
def wrapper(*args, **kwargs):
reactor.callLater(repeat, wrapper, *args, **kwargs)
action(*args, **kwargs)
reactor.callLater(repeat, wrapper, *args, **kwargs)
def delayAction(self, action, delay, *args, **kwargs):
reactor.callLater(delay, action, *args, **kwargs)
def repeatRoundTimeAction(self, action, increment, delay=0, *args, **kwargs):
def wrapper(currentcall, *args, **kwargs):
action(increment, delay, *args, **kwargs)
nextcall = currentcall + increment
now = utcNow()
incr = max(nextcall - now + 1, 0)
reactor.callLater(incr, wrapper, nextcall, *args, **kwargs)
nextcall, incr = self.nextCall(increment, delay)
reactor.callLater(incr, wrapper, nextcall, *args, **kwargs)
def run(self):
reactor.run()
def nextCall(self, increment, delay):
now = utcNow()
then = now.nextRoundMultiple(increment) + delay
incr = then - now + 1
if incr < 0:
incr = 0
return then, incr
| [
"claudegibert@Bearwood.local"
] | claudegibert@Bearwood.local |
6afbca4d67690a130eca57de406b845c679b4272 | a05f5638c145964fdb203883ee415f4a021b8086 | /code/stock/tables/__init__.py | 0d53e9091b0ab3720c7217655b184739ae8fc800 | [] | no_license | jackstine/stockAnalysis | a209a5b126a04370b22e485400975c88be53a998 | 83f74c5fc1c5216baa28fccf6e5a6511dfd6c11b | refs/heads/master | 2021-01-18T23:57:20.143074 | 2016-08-09T02:10:22 | 2016-08-09T02:10:22 | 53,628,447 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 214 | py | from DataPool import DataPool
from Collection import Collection
from TableDescription import TableDescription
from Description import Description
from Table import Table
from Field import Field
from Row import Row
| [
"ecstaticjack@gmail.com"
] | ecstaticjack@gmail.com |
3da95b9dd547f1e4f76a1f56d2a7ba805110539f | c0156da1c81a3a76e397974399c7345d082eca9b | /venv/lib/python3.7/site-packages/AccessControl/User.py | ce243e3ea746dde5d02b4caecec5843200d5094c | [
"Apache-2.0"
] | permissive | leanhvu86/matrix-server | 1823c60fc6ba5ed489bb5720474c6b56a9aec688 | 6e16fc53dfebaeaf222ff5a371ccffcc65de3818 | refs/heads/master | 2023-05-09T01:21:37.774510 | 2021-05-21T15:10:48 | 2021-05-21T15:10:48 | 369,569,370 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,931 | py | ##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Access control package.
"""
from zope.deferredimport import deprecated
# BBB
from AccessControl.users import BasicUser
from AccessControl.users import NullUnrestrictedUser
from AccessControl.users import SimpleUser
from AccessControl.users import SpecialUser
from AccessControl.users import UnrestrictedUser as Super
from AccessControl.users import User
from AccessControl.users import _remote_user_mode
from AccessControl.users import absattr
from AccessControl.users import addr_match
from AccessControl.users import domainSpecMatch
from AccessControl.users import emergency_user
from AccessControl.users import host_match
from AccessControl.users import nobody
from AccessControl.users import readUserAccessFile
from AccessControl.users import reqattr
from AccessControl.users import rolejoin
from AccessControl.users import system
from AccessControl.users import UnrestrictedUser # noqa isort:skip
deprecated(
"The standard Zope user folder implementation has moved to "
"OFS.userfolder. Please depend on Zope2 and import from "
"OFS.userfolder or use the new minimal "
"user folder classes from AccessControl.userfolder.",
BasicUserFolder='OFS.userfolder:BasicUserFolder',
manage_addUserFolder='OFS.userfolder:manage_addUserFolder',
UserFolder='OFS.userfolder:UserFolder',
)
| [
"leanhvu86@gmail.com"
] | leanhvu86@gmail.com |
3b55dee9a74bedd0c8fbb0830eefd44422dcf8dc | a5f482640695b5d46ae68e6661efaa40ae948636 | /orttraining/orttraining/test/python/orttraining_test_debuggability.py | 4353174c386c3e37f723899f0f57893fd9c47e48 | [
"MIT"
] | permissive | jupvfranco/onnxruntime | 1a94c0072ed23150226bc1d99b66bc0d85eb9309 | 57c92066c2cbd384deecbe74e0950ab3e726718a | refs/heads/master | 2023-08-07T20:38:19.624633 | 2020-11-23T07:19:27 | 2020-11-23T07:19:27 | 290,848,080 | 1 | 0 | MIT | 2020-11-24T17:24:37 | 2020-08-27T18:09:04 | C++ | UTF-8 | Python | false | false | 1,853 | py | import inspect
import onnx
import os
import pytest
import torch
import torchvision
from numpy.testing import assert_allclose
from onnxruntime import set_seed
from onnxruntime.capi.ort_trainer import IODescription as Legacy_IODescription,\
ModelDescription as Legacy_ModelDescription,\
LossScaler as Legacy_LossScaler,\
ORTTrainer as Legacy_ORTTrainer
from onnxruntime.training import _utils, amp, optim, orttrainer, TrainStepInfo,\
model_desc_validation as md_val,\
orttrainer_options as orttrainer_options
from orttraining_test_orttrainer_frontend import _load_pytorch_transformer_model
import _test_helpers
###############################################################################
# Testing starts here #########################################################
###############################################################################
@pytest.mark.parametrize("seed, device", [
(24, 'cuda'),
])
def testORTTransformerModelExport(seed, device):
# Common setup
optim_config = optim.LambConfig()
opts = orttrainer.ORTTrainerOptions({
'debug' : {
'check_model_export': True,
},
'device' : {
'id' : device,
}
})
# Setup for the first ORTTRainer run
torch.manual_seed(seed)
set_seed(seed)
model, model_desc, my_loss, batcher_fn, train_data, val_data, _ = _load_pytorch_transformer_model(device)
first_trainer = orttrainer.ORTTrainer(model, model_desc, optim_config, loss_fn=my_loss, options=opts)
data, targets = batcher_fn(train_data, 0)
_ = first_trainer.train_step(data, targets)
assert first_trainer._onnx_model is not None
| [
"noreply@github.com"
] | jupvfranco.noreply@github.com |
a5d51b267590375dc7684a31d5cc2d46d226d447 | 42b2c7f740ec13c5a70b84886599f77a50972245 | /signup/account/views.py | 5e306800197719599e0ffdfe1c0434e5ffbd100d | [] | no_license | yeching/Django | c7419204423dbcdbb204ffe619e737c9485cc0b4 | 85ee235dfcf702978c0a9f6630e44e74022b4381 | refs/heads/master | 2021-01-11T16:49:56.873273 | 2017-01-22T00:38:14 | 2017-01-22T00:38:14 | 79,680,781 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,233 | py | #coding=utf-8
from django.shortcuts import render
from django import forms
from django.shortcuts import render_to_response
from django.http import HttpResponse,HttpResponseRedirect
from django.template import RequestContext
from account.models import User
#定义表单模型
class UserForm(forms.Form):
username = forms.CharField(label='用户名:',max_length=100)
passworld = forms.CharField(label='密码:',widget=forms.PasswordInput())
email = forms.EmailField(label='电子邮件:')
# Create your views here.
def register(request):
if request.method == "POST":
uf = UserForm(request.POST)
if uf.is_valid():
#获取表单信息
username = uf.cleaned_data['username']
passworld = uf.cleaned_data['passworld']
email = uf.cleaned_data['email']
#将表单写入数据库
user = User()
user.username = username
user.passworld = passworld
user.email = email
user.save()
#返回注册成功页面
return render_to_response('success.html',{'username':username})
else:
uf = UserForm()
return render_to_response('register.html',{'uf':uf})
| [
"yq08051035@163.com"
] | yq08051035@163.com |
8fb95bcd56b00c429fc56afddec6f5b3a1b9d960 | 90afc972b2259054e7cc9b63ec19bf11c3153e48 | /problems/A/RemoveSmallest.py | ee87546f8b201d89ed96f2446ef91d24fa5d2852 | [
"MIT"
] | permissive | Ahsanhabib1080/CodeForces | 88ca768ceefa409b0c10cac500148bfaf19e3c7e | 707b374f03012ec68054841f791d48b33ae4ef1b | refs/heads/master | 2023-05-26T20:58:23.180369 | 2021-06-19T02:40:15 | 2021-06-19T02:40:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 683 | py | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/1399/A
Solution: Pretty straightforward question. Sort the array and check if any pair of adjacent elements differ
by more than 1. If so return NO. If all the elements check out, return YES.
'''
def solve(n, arr):
arr.sort()
for i in xrange(1, n):
if arr[i] - arr[i-1] > 1:
return "NO"
return "YES"
if __name__ == "__main__":
t = int(raw_input())
results = list()
for _ in xrange(0, t):
n = int(raw_input())
arr = map(int, raw_input().split(" "))
results.append(solve(n, arr))
for result in results:
print result
| [
"devesh.bajpai19@gmail.com"
] | devesh.bajpai19@gmail.com |
bf4bd154ed77855a57a4908d693902b0a9bff8f1 | 5c2a66d59adff9c06a870a548a6c3af23a79be77 | /schrodinger/ex1/github/display_nnout.py | 282b931976e7c2f5a8b356cb8e9d8286bc40a183 | [] | no_license | OscarGB/TFGMat | f63690f456f1a107101248278430ff71ee882b98 | cc95948cd8d371c5adcb19f8540965b299d3591c | refs/heads/master | 2022-07-26T15:17:25.439335 | 2020-05-16T18:01:19 | 2020-05-16T18:01:19 | 214,371,579 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 455 | py | display_nnout.py
# Makes plots of an individual potential (scaled to unit max), the gradient descent (“correct”) ground state,
# and the neural network predicted ground state
# should be added to notebook containing schroedinger_nn.py
import matplotlib.pyplot as mp
potenid = 5397
mp.plot(sess.run(L3,feed_dict={X: [trainx[potenid]]})[0])
mp.plot([trainx[potenid][i]/max(trainx[potenid]) for i in range(bins - 1)])
mp.plot(trainy[potenid])
mp.show()
| [
"oscar.gomez.borz@gmail.com"
] | oscar.gomez.borz@gmail.com |
8a90400c1676da47db9e358fba77580deaaa1f06 | a59cd0e6e9e75543cd24630e37a0f4a006c91093 | /trackit/issues/migrations/0005_auto_20150318_0922.py | ab1fe191e45ba69b5d608c618562f099dca58df2 | [
"MIT"
] | permissive | noracami/track-it | 974acf8863004525911bf3193f2b8a8ee3a1485c | 7b787575573f3e807d1d7b863c3961474464c6d6 | refs/heads/master | 2016-09-06T21:33:15.813177 | 2015-04-04T15:43:21 | 2015-04-04T15:43:21 | 32,306,127 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 755 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('issues', '0004_comment_ticket'),
]
operations = [
migrations.AddField(
model_name='ticket',
name='opened_user',
field=models.ForeignKey(related_name='OpenedUser', default=1, to='issues.User'),
preserve_default=False,
),
migrations.AddField(
model_name='user',
name='password',
field=models.CharField(max_length=56, verbose_name='密碼', default='71454996db126e238e278a202a7dbc49dda187ec4f8c9dfc95584900'),
preserve_default=True,
),
]
| [
"im771216@gmail.com"
] | im771216@gmail.com |
e08e22402a1801b44e630f11eb7904ed750e58bb | d45b7f297523152753808e464972bff02b5725be | /myPets.py | fad37cbff27d1ec3ad27cea82d93a31027406f64 | [] | no_license | arjunlol/AutoBoringPython | a65c246f6777d48e2b00df48c4008266d01b53f8 | e38753a00d33a049080cfeededafc6d840f6c0af | refs/heads/master | 2021-01-24T08:17:38.303289 | 2016-10-04T01:13:01 | 2016-10-04T01:13:01 | 69,140,224 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 189 | py | myPets = ['Zophie','Pooka','Fat-tail']
print('enter a pet name:')
name = input()
if name not in myPets:
print('I do not have a pet named ' + name)
else:
print(name + ' is my pet.')
| [
"lallarjun@gmail.com"
] | lallarjun@gmail.com |
cf0ee5f068b5dc3a25ff1a72eda3a87564871b12 | c59654aa7bbb49743db247afb227f73e6b9f4548 | /normalize1.py | cc654492370c6c27e7ecef11b0a3b4a27754c3fc | [] | no_license | Gorg0n/Agenda | 39edbb063e1cea60b1faae4c5e4754ec0a7c2d06 | 79b98934996e7eadb7ac540d0c0fb82bbd7b1911 | refs/heads/master | 2023-03-02T19:22:24.914155 | 2021-02-09T20:33:26 | 2021-02-09T20:33:26 | 278,675,676 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,119 | py | import pandas as pd
import numpy as np
from copy import deepcopy
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
inFolder = 'outputFiles/'
outFolder = 'outputFiles/'
fileRANS = 'RANScylLeak1'
fin = inFolder+fileRANS
df = pd.read_hdf(fin)
dfxyz = deepcopy(df[['x','y','z']])
df.drop(columns=['x','y','z','CH4MF','dCH4MF'],inplace=True)
dfNorm = pd.DataFrame()
dontNorm = ['BC', 'CLOUD', 'IC']
for dn in dontNorm:
dfNorm[dn]=deepcopy(df[dn])
min_max_scaler = MinMaxScaler()
minMaxS = ['T', 'velocity']
for dn in minMaxS:
dfNorm[dn] = min_max_scaler.fit_transform(df[[dn]])
print(dfNorm['velocity'].max())
print(dfNorm['velocity'].min())
print(dfNorm['T'].max())
print(dfNorm['T'].min())
#df['LRANS']=4*df['velocity']/(df['S']+1e30)
df['LRANS']=(df['k'] **1.5)/df['epsilon']
scaleLocal = ['nut', 'dnut', 'p', 'dp', 'epsilon', 'depsilon', 'k', 'dk', 'S', 'W', 'axis', 'radius']
scales = ('velocity','LRANS')
scale = [(-1,-1),(-1,0),(-2,0),(-2,1),(-3,1),(-3,2),(-2,0),(-2,1),(-1,1),(-1,1),(0,-1),(0,-1)]
print(dfNorm.shape)
print(df.shape)
for i,dn in enumerate(scaleLocal):
dfNorm[dn]=deepcopy(df[dn])
print(dn,dfNorm[dn].min(),dfNorm[dn].max())
for j,s in enumerate(scales):
print(scales[j],scale[i][j],df[s].min(),df[s].max())
dfNorm[dn] *= df[s] * (df[scales[j]]**scale[i][j])
print('\n')
print(df.columns)
import seaborn as sns
for col in dfNorm.columns:
ax = sns.boxplot(x=dfNorm[col])
fn = outFolder + str(col) + '.png'
plt.savefig(fn)
plt.close()
'''
print(dfNorm['axis'].max())
print(dfNorm['axis'].min())
print(dfNorm['radius'].max())
print(dfNorm['radius'].min())
'''
plt.figure(figsize=(7,7))
corrMatrix = dfNorm.corr()
sns.heatmap(corrMatrix,vmin=-1,vmax=1,cmap='bwr')
fn = outFolder + 'cmatrix.png'
plt.tight_layout()
plt.savefig(fn)
plt.close()
print(dfxyz.columns)
print(dfNorm.columns)
dfToT = pd.concat([dfxyz,dfNorm],axis=1)
print(dfToT.columns)
print(dfxyz.shape,dfNorm.shape,dfToT.shape)
fn = outFolder + 'Norm' + fileRANS + '.h5'
print('writing file',fn)
dfNorm.to_hdf(fin, key='dfToT', mode='w')
| [
"49187086+Gorg0n@users.noreply.github.com"
] | 49187086+Gorg0n@users.noreply.github.com |
89198bf16a76e7c2866ad363143f04bbac4f0283 | c20cc3797472c2a0ec4d39a7aae73e25fab9b214 | /GERDA_SIS/init.py | c585dcb9f872d6b48c97fed857425b50ee2f0af2 | [] | no_license | yannmu/SIS | 655cb153aabb01c249a39edcb15e7fa1157f977d | e443781c99e2bf1a62dca90f57fd877b87e9965b | refs/heads/master | 2021-05-24T07:03:56.282566 | 2020-07-31T09:03:43 | 2020-07-31T09:03:43 | 253,446,277 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 14,578 | py | #initialise command
#only works if units are in remote control mode
#initialise all, or only specific units
#initialisation of all units as default (init.py)
#initialisation of only a certain unit (1, 2, 3) if and only if the corresponding single unit number is specified (e.g. init.py 1)
#the expected time to finish is printed in the beginning
#an overview of the current positions is printed every 5 sec
#the speed of the movement is approx. 10 mm/s
#the setup of the units needs to be as follows: 1, 2, 3 at control box ports 1, 2, 3; usb-to-serial converter port 2)
#in case of errors the script exits on 1
import platform
import serial
import time
import sys
import os
from datetime import datetime
port = 1
baudrate = 9600
#time step for position update during movement 5 sec
delta_t = 5
#average speed 10 mm / sec
v = 10
#bandlength
length = [9500, 8690, 9500]
#precision
prec = 10
#read in unit specification
try:
unit = int(sys.argv[1])
units = [unit]
except(IndexError):
units = [1, 2, 3]
unit = "(1, 2, 3)"
for unit_num in units:
if not (1 <= unit_num <= 3):
print("Valid unit numbers are 1, 2, or 3. ")
time.sleep(5)
sys.exit(1)
#prepare log-file
time_start = datetime.now().strftime("%H-%M-%S")
date = datetime.now().strftime("%Y-%m-%d")
file_name = datetime.now().strftime("%H-%M-%S")
#global port specification
if platform.system() == "Windows":
global_port_spec = 'COM'
plat_sys = 1
dir_name = 'C:/Users/ym-st/OneDrive/Desktop/GERDA_SIS/log/' + str(date)
if platform.system() == "Linux":
global_port_spec = '/dev/ttyMXUSB'
plat_sys = 0
dir_name = 'log/' + str(date)
port_spec = global_port_spec
port += plat_sys
port_spec += str(port)
if not os.path.exists(dir_name):
os.mkdir(dir_name)
file = open(dir_name +'/log-init_' + file_name + '.txt', 'w')
file.write('Initialisation started at: ' + time_start + '\n')
file.write('Script called with external unit specification ' + str(units) + '\n\n')
#checksum used to ensure correct communication
def check_sum (array):
csum = (sum(array) & 255) ^ 255
return csum
#transmitting and receiving byte array
def tx_rx(tx_array, rx_length):
communication_time = time.time() + 2 #maximal time span until communication is considered nonreliable 2 sec
while True:
if time.time() > communication_time:
return 0
#send tx_array
ser = serial.Serial(port_spec, baudrate, timeout = 0.1)
ser.write(bytearray(tx_array))
#read in rx_array
try:
rx_array = ser.read(rx_length)
rx_array = list(rx_array)
acknow_byte = rx_array[2]
ser.close()
except (IndexError):
ser.close()
continue
#check rx_array
current_time = datetime.now().strftime("%H-%M-%S")
bits=['{0:08b}'.format(rx_array[n]) for n in range(len(rx_array))]
if (rx_length == len(rx_array) and rx_array[0] == tx_array[0]):
if (rx_length == 4 and acknow_byte != 0):
print("Make sure that remote control mode is turned on!")
file.write(current_time + ': Make sure that remote control mode is turned on!\n')
file.write('Received bytes: ' + str(rx_array) + '\n')
file.write('Received bits: ' + str(bits) + '\n')
file.close()
time.sleep(5)
sys.exit(1)
elif (rx_length == 6 and acknow_byte != 0):
if acknow_byte == 1:
print("Make sure that remote control mode is turned on!")
file.write(current_time + ': Make sure that remote control mode is turned on!\n')
if acknow_byte == 4:
print("Position specifications invalid!")
file.write(current_time + ': Position specifications invalid!\n')
if acknow_byte == 8:
print("A unit needs to be initialised before it can be moved!")
file.write(current_time + ': A unit needs to be initialised before it can be moved!\n')
file.write('Received bytes: ' + str(rx_array) + '\n')
file.write('Received bits: ' + str(bits) + '\n')
file.close()
time.sleep(5)
sys.exit(1)
else:
return rx_array
time.sleep(0.1)
#internal commands needed for initialisation:
#stop(): stop command is sent to specified units; script is terminated, and exits on 1
#get_status(): get current status of specified units, save status of all units to file
#get_position(): get current positions (in mm) of specified units, save and print positions of all units to file/to terminal
#init(): initialise specified units
def stop():
err = 0
cmd_byte = 195
rx_length = 4
for unit_num in units:
unit_num = unit_num - 1
#prepare tx_array
tx_array = [cmd_byte,
unit_num,
cmd_byte ^ 255,
unit_num ^ 255,
cmd_byte ^ 255,
unit_num ^ 255]
tx_array.append(check_sum(tx_array))
#send and receive
rx_array = tx_rx(tx_array, rx_length)
if rx_array == 0:
err += 1
#error handling
current_time = datetime.now().strftime("%H-%M-%S")
if err > 0:
print("Communication error occured when sending stop command as backstop!")
file.write(current_time + ': Communication error occured when sending stop command as backstop!\n')
else:
print("Stop command sent to specified units!")
file.write(current_time + ': Stop command sent to specified units!\n')
file.close()
time.sleep(5)
sys.exit(1)
def get_status():
err = 0
cmd_byte = 51
rx_length = 15
rx_init = []
rx_motor = []
rx_bits = []
rx_bytes = []
rx_status = []
rx_error = []
#prepare tx_array
tx_array = [cmd_byte,
0,
0,
0,
0,
0]
tx_array.append(check_sum(tx_array))
#send and receive
rx_array = tx_rx(tx_array, rx_length)
if rx_array == 0:
err += 1
rx_init.extend((-1111, -1111, -1111))
rx_motor.extend((-1111, -1111, -1111))
rx_bits.extend((-1111, -1111, -1111))
rx_bytes.extend((-1111, -1111, -1111))
rx_status.extend((-1111, -1111, -1111))
rx_error.extend((-1111, -1111, -1111))
#data processing
else:
rx_bits.append(['{0:08b}'.format(rx_array[n]) for n in range(len(rx_array))])
rx_bytes.append(rx_array)
for unit_num in range(3):
#initialisation status
rx_init.append(rx_array[8 + unit_num] >> 2 & 1)
#state of motor movement
rx_motor.append(rx_array[8 + unit_num] & 3)
#status flags
rx_status.append(rx_array[8 + unit_num])
#error flags
rx_error.append(rx_array[11 + unit_num])
print("----------Movement (0: idle/break, 1: down, 2: up):",str(rx_motor))
print("----------Initialisitaion status (0: not init., 1: init.):",str(rx_init))
print("----------Status flags:",str(rx_status))
print("----------Error flags:",str(rx_error))
current_time = datetime.now().strftime("%H-%M-%S")
file.write(current_time + ': Status check:\n')
file.write('Received bytes: ' + str(rx_bytes) + '\n')
file.write('Received bits: ' + str(rx_bits) + '\n')
file.write('Movement (0: idle/break, 1: down, 2: up): ' + str(rx_motor) + '\n')
file.write('Initialisitaion status (0: not init., 1: init.): ' + str(rx_init) + '\n')
file.write('Status flags: ' + str(rx_status) + '\n')
file.write('Error flags: ' + str(rx_error) + '\n')
#status to be returned
if len(units) == 1:
status = [[rx_init[units[0] - 1]], [rx_motor[units[0] - 1]]]
if len(units) == 2:
status = [[rx_init[units[0] - 1], rx_init[units[1] - 1]], [rx_motor[units[0] - 1], rx_motor[units[1] - 1]]]
if len(units) == 3:
status = [rx_init, rx_motor]
#error handling
if err > 0:
print("Communication error occured during status check!")
file.write(current_time + ': Communication error occured during status check!\n')
stop()
return status
def get_position():
err = 0
cmd_byte = 85
rx_length = 20
inc_pos = []
abs_pos = []
discr = []
pos = []
#prepare tx_array
tx_array = [cmd_byte,
0,
0,
0,
0,
0]
tx_array.append(check_sum(tx_array))
#send and receive
rx_array = tx_rx(tx_array, rx_length)
if rx_array == 0:
err += 1
inc_pos.extend((-1111, -1111, -1111))
abs_pos.extend((-1111, -1111, -1111))
discr.extend((-1111, -1111, -1111))
pos.extend((-1111, -1111, -1111))
#data processing
else:
for unit_num in range(3):
inc_pos.append(256 * rx_array[4 + 4 * unit_num] + rx_array[3 + 4 * unit_num])
abs_pos.append(256 * rx_array[2 + 4 * unit_num] + rx_array[1 + 4 * unit_num])
discr.append(inc_pos[unit_num] - abs_pos[unit_num])
for unit_num in range(3):
if not -20 <= inc_pos[unit_num] <= length[unit_num] + 100:
inc_pos[unit_num] = -9999
if not -20 <= abs_pos[unit_num] <= length[unit_num] + 100:
abs_pos[unit_num] = -9999
if (not -999 < discr[unit_num] < 999) or inc_pos[unit_num] == -9999 or abs_pos[unit_num] == -9999:
discr[unit_num] = -9999
#positions to be saved
if inc_pos[unit_num] != -9999:
pos.append(inc_pos[unit_num])
else:
pos.append(abs_pos[unit_num])
print("----------Incremental encoder:",str(inc_pos))
print("----------Absolute encoder:",str(abs_pos))
print("----------Discrepancies (incremental - absolute):",str(discr))
print("\nCURRENT POSITIONS:",str(pos),"\n")
pos_file = open('current_positions.txt', 'w')
pos_file.write('Positions:\n' + str(pos) + '\nIncremental encoder:\n' + str(inc_pos) + '\nAbsolute encoder:\n' + str(abs_pos) + '\nDiscrepancies (incremental - absolute):\n' + str(discr))
pos_file.close()
current_time = datetime.now().strftime("%H-%M-%S")
file.write(current_time + ': Current positions: \n')
file.write('Incremental encoder: ' + str(inc_pos) + '\n')
file.write('Absolute encoder: ' + str(abs_pos) + '\n')
file.write('Discrepancies (incremental - absolute): ' + str(discr) + '\n')
#positions to be returned (all units or individual units)
if len(units) == 1:
pos = [pos[units[0] - 1]]
if len(units) == 2:
pos = [pos[units[0] - 1], pos[units[1] - 1]]
#error handling
current_time = datetime.now().strftime("%H-%M-%S")
if err > 0:
print("Communication error occured during position check!")
file.write(current_time + ': Communication error occured during position check!\n')
stop()
return pos
def init():
err = 0
cmd_byte = 170
rx_length = 4
for unit_num in units:
unit_num = unit_num - 1
#prepare tx_array
tx_array = [cmd_byte,
unit_num,
cmd_byte ^ 255,
unit_num ^ 255,
cmd_byte ^ 255,
unit_num ^ 255]
tx_array.append(check_sum(tx_array))
#send and receive
rx_array = tx_rx(tx_array, rx_length)
if rx_array == 0:
err += 1
current_time = datetime.now().strftime("%H-%M-%S")
#error handling
if err > 0:
print("Communication error occured when sending initialisation command!")
file.write(current_time + ': Communication error occured when sending initialisation command!\n')
stop()
return 0
#main program
#check current position, send init command, print expected time needed to finish
status = get_status()
pos = get_position()
init()
t = int(max(pos) / v + 1)
#2 seconds to hit end-switch and move back to parking position
t += 2
current_time = datetime.now().strftime("%H-%M-%S")
if t > 0:
print("Expected time needed to initialise (in sec):",str(t),"\n")
file.write(current_time + ': Expected time needed to initialise (in sec): ' + str(t) + '\n')
else:
print("Expected time needed to initialise unknown (approx. 3 sec from parking position).\n")
file.write(current_time + ': Expected time needed to initialise unknown (approx. 3 sec from parking position).\n')
#check positions and motor status during movement
max_time = time.time() + 60*20 #maximal waiting time 20 mins
while True:
current_time = datetime.now().strftime("%H-%M-%S")
if time.time() > max_time:
print("Maximum waiting time has expired. Make sure that communication works properly.")
file.write(current_time + ': Maximum waiting time has expired. Make sure that communication works properly.\n')
stop()
if 0 <= t <= delta_t:
time.sleep(t)
else:
time.sleep(delta_t)
status = get_status()
pos = get_position()
init = status[0]
motor = status[1]
#exit loop when motor(s) has/have stopped
if all(elem == 0 for elem in motor):
time.sleep(1)
break
#check initialisation status, ensure that parking position has been approached, and finish log-file
time_end = datetime.now().strftime("%H-%M-%S")
if (all(elem == 1 for elem in init) and all(abs(elem) <= prec for elem in pos)):
file.write('\nInitialisation finished at: ' + time_end + '\n')
file.close()
print("Initialisation finished.")
else:
file.write(current_time + ': Initialisation could not be finished successfully!\n')
file.close()
print("Initialisation could not be finished successfully!")
sys.exit(1)
#exit(0)
| [
"noreply@github.com"
] | yannmu.noreply@github.com |
a352923e8a24cde56d18fc07e4c6ba6e4b87ae56 | f9d564f1aa83eca45872dab7fbaa26dd48210d08 | /huaweicloud-sdk-ocr/huaweicloudsdkocr/v1/model/general_table_request_body.py | cbb5370a0a0a803403eabeae578ba76fe2bdf447 | [
"Apache-2.0"
] | permissive | huaweicloud/huaweicloud-sdk-python-v3 | cde6d849ce5b1de05ac5ebfd6153f27803837d84 | f69344c1dadb79067746ddf9bfde4bddc18d5ecf | refs/heads/master | 2023-09-01T19:29:43.013318 | 2023-08-31T08:28:59 | 2023-08-31T08:28:59 | 262,207,814 | 103 | 44 | NOASSERTION | 2023-06-22T14:50:48 | 2020-05-08T02:28:43 | Python | UTF-8 | Python | false | false | 14,275 | py | # coding: utf-8
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class GeneralTableRequestBody:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'image': 'str',
'url': 'str',
'return_text_location': 'bool',
'return_char_location': 'bool',
'return_confidence': 'bool',
'return_excel': 'bool',
'return_rectification_matrix': 'bool'
}
attribute_map = {
'image': 'image',
'url': 'url',
'return_text_location': 'return_text_location',
'return_char_location': 'return_char_location',
'return_confidence': 'return_confidence',
'return_excel': 'return_excel',
'return_rectification_matrix': 'return_rectification_matrix'
}
def __init__(self, image=None, url=None, return_text_location=None, return_char_location=None, return_confidence=None, return_excel=None, return_rectification_matrix=None):
"""GeneralTableRequestBody
The model defined in huaweicloud sdk
:param image: 与url二选一 图片最小边不小于15px,最长边不超过8192px,支持JPEG、JPG、PNG、BMP、TIFF格式。 图片文件Base64编码字符串,点击[这里](https://support.huaweicloud.com/ocr_faq/ocr_01_0032.html)查看详细获取方式。
:type image: str
:param url: 与image二选一 图片的URL路径,目前支持: - 公网http/https url - OBS提供的url,使用OBS数据需要进行授权。包括对服务授权、临时授权、匿名公开授权,详情参见[配置OBS访问权限](https://support.huaweicloud.com/api-ocr/ocr_03_0132.html)。 > 说明: - 接口响应时间依赖于图片的下载时间,如果图片下载时间过长,会返回接口调用失败。 - 请保证被检测图片所在的存储服务稳定可靠,推荐使用OBS服务存储图片数据。
:type url: str
:param return_text_location: 返回文本块坐标及单元格坐标信息,可选值如下所示: - true:返回文本块和单元格坐标 - false:不返回 > 说明: - 如果未传入该参数时默认为false,即不返回。
:type return_text_location: bool
:param return_char_location: 返回单字符的坐标信息,可选值包括: - true:返回单字符的坐标 - false:不返回 未传入该参数时默认为false,即不返回。如果此参数为true时,return_text_loaction必须为true
:type return_char_location: bool
:param return_confidence: 是否返回置信度的开关,可选值包括: - true:返回置信度 - false:不返回置信度 > 说明: - 如果未传入该参数,系统默认为“false”,即不返回置信度。
:type return_confidence: bool
:param return_excel: 是否返回表格转换Microsoft Excel的base64编码字段。可选值包括: - true:返回'excel'字段,表示xlsx格式的表格识别结果的base64编码 - false:不返回。默认为false > 说明: - 对返回的Excel编码,可用Python函数 base64.b64decode解码后保存为.xlsx文件。
:type return_excel: bool
:param return_rectification_matrix: 可选值包括: - true:返回透视变换矩阵 - false:不返回 未传入该参数时默认为false,即不返回透视变换矩阵。
:type return_rectification_matrix: bool
"""
self._image = None
self._url = None
self._return_text_location = None
self._return_char_location = None
self._return_confidence = None
self._return_excel = None
self._return_rectification_matrix = None
self.discriminator = None
if image is not None:
self.image = image
if url is not None:
self.url = url
if return_text_location is not None:
self.return_text_location = return_text_location
if return_char_location is not None:
self.return_char_location = return_char_location
if return_confidence is not None:
self.return_confidence = return_confidence
if return_excel is not None:
self.return_excel = return_excel
if return_rectification_matrix is not None:
self.return_rectification_matrix = return_rectification_matrix
@property
def image(self):
"""Gets the image of this GeneralTableRequestBody.
与url二选一 图片最小边不小于15px,最长边不超过8192px,支持JPEG、JPG、PNG、BMP、TIFF格式。 图片文件Base64编码字符串,点击[这里](https://support.huaweicloud.com/ocr_faq/ocr_01_0032.html)查看详细获取方式。
:return: The image of this GeneralTableRequestBody.
:rtype: str
"""
return self._image
@image.setter
def image(self, image):
"""Sets the image of this GeneralTableRequestBody.
与url二选一 图片最小边不小于15px,最长边不超过8192px,支持JPEG、JPG、PNG、BMP、TIFF格式。 图片文件Base64编码字符串,点击[这里](https://support.huaweicloud.com/ocr_faq/ocr_01_0032.html)查看详细获取方式。
:param image: The image of this GeneralTableRequestBody.
:type image: str
"""
self._image = image
@property
def url(self):
"""Gets the url of this GeneralTableRequestBody.
与image二选一 图片的URL路径,目前支持: - 公网http/https url - OBS提供的url,使用OBS数据需要进行授权。包括对服务授权、临时授权、匿名公开授权,详情参见[配置OBS访问权限](https://support.huaweicloud.com/api-ocr/ocr_03_0132.html)。 > 说明: - 接口响应时间依赖于图片的下载时间,如果图片下载时间过长,会返回接口调用失败。 - 请保证被检测图片所在的存储服务稳定可靠,推荐使用OBS服务存储图片数据。
:return: The url of this GeneralTableRequestBody.
:rtype: str
"""
return self._url
@url.setter
def url(self, url):
"""Sets the url of this GeneralTableRequestBody.
与image二选一 图片的URL路径,目前支持: - 公网http/https url - OBS提供的url,使用OBS数据需要进行授权。包括对服务授权、临时授权、匿名公开授权,详情参见[配置OBS访问权限](https://support.huaweicloud.com/api-ocr/ocr_03_0132.html)。 > 说明: - 接口响应时间依赖于图片的下载时间,如果图片下载时间过长,会返回接口调用失败。 - 请保证被检测图片所在的存储服务稳定可靠,推荐使用OBS服务存储图片数据。
:param url: The url of this GeneralTableRequestBody.
:type url: str
"""
self._url = url
@property
def return_text_location(self):
"""Gets the return_text_location of this GeneralTableRequestBody.
返回文本块坐标及单元格坐标信息,可选值如下所示: - true:返回文本块和单元格坐标 - false:不返回 > 说明: - 如果未传入该参数时默认为false,即不返回。
:return: The return_text_location of this GeneralTableRequestBody.
:rtype: bool
"""
return self._return_text_location
@return_text_location.setter
def return_text_location(self, return_text_location):
"""Sets the return_text_location of this GeneralTableRequestBody.
返回文本块坐标及单元格坐标信息,可选值如下所示: - true:返回文本块和单元格坐标 - false:不返回 > 说明: - 如果未传入该参数时默认为false,即不返回。
:param return_text_location: The return_text_location of this GeneralTableRequestBody.
:type return_text_location: bool
"""
self._return_text_location = return_text_location
@property
def return_char_location(self):
"""Gets the return_char_location of this GeneralTableRequestBody.
返回单字符的坐标信息,可选值包括: - true:返回单字符的坐标 - false:不返回 未传入该参数时默认为false,即不返回。如果此参数为true时,return_text_loaction必须为true
:return: The return_char_location of this GeneralTableRequestBody.
:rtype: bool
"""
return self._return_char_location
@return_char_location.setter
def return_char_location(self, return_char_location):
"""Sets the return_char_location of this GeneralTableRequestBody.
返回单字符的坐标信息,可选值包括: - true:返回单字符的坐标 - false:不返回 未传入该参数时默认为false,即不返回。如果此参数为true时,return_text_loaction必须为true
:param return_char_location: The return_char_location of this GeneralTableRequestBody.
:type return_char_location: bool
"""
self._return_char_location = return_char_location
@property
def return_confidence(self):
"""Gets the return_confidence of this GeneralTableRequestBody.
是否返回置信度的开关,可选值包括: - true:返回置信度 - false:不返回置信度 > 说明: - 如果未传入该参数,系统默认为“false”,即不返回置信度。
:return: The return_confidence of this GeneralTableRequestBody.
:rtype: bool
"""
return self._return_confidence
@return_confidence.setter
def return_confidence(self, return_confidence):
"""Sets the return_confidence of this GeneralTableRequestBody.
是否返回置信度的开关,可选值包括: - true:返回置信度 - false:不返回置信度 > 说明: - 如果未传入该参数,系统默认为“false”,即不返回置信度。
:param return_confidence: The return_confidence of this GeneralTableRequestBody.
:type return_confidence: bool
"""
self._return_confidence = return_confidence
@property
def return_excel(self):
"""Gets the return_excel of this GeneralTableRequestBody.
是否返回表格转换Microsoft Excel的base64编码字段。可选值包括: - true:返回'excel'字段,表示xlsx格式的表格识别结果的base64编码 - false:不返回。默认为false > 说明: - 对返回的Excel编码,可用Python函数 base64.b64decode解码后保存为.xlsx文件。
:return: The return_excel of this GeneralTableRequestBody.
:rtype: bool
"""
return self._return_excel
@return_excel.setter
def return_excel(self, return_excel):
"""Sets the return_excel of this GeneralTableRequestBody.
是否返回表格转换Microsoft Excel的base64编码字段。可选值包括: - true:返回'excel'字段,表示xlsx格式的表格识别结果的base64编码 - false:不返回。默认为false > 说明: - 对返回的Excel编码,可用Python函数 base64.b64decode解码后保存为.xlsx文件。
:param return_excel: The return_excel of this GeneralTableRequestBody.
:type return_excel: bool
"""
self._return_excel = return_excel
@property
def return_rectification_matrix(self):
"""Gets the return_rectification_matrix of this GeneralTableRequestBody.
可选值包括: - true:返回透视变换矩阵 - false:不返回 未传入该参数时默认为false,即不返回透视变换矩阵。
:return: The return_rectification_matrix of this GeneralTableRequestBody.
:rtype: bool
"""
return self._return_rectification_matrix
@return_rectification_matrix.setter
def return_rectification_matrix(self, return_rectification_matrix):
"""Sets the return_rectification_matrix of this GeneralTableRequestBody.
可选值包括: - true:返回透视变换矩阵 - false:不返回 未传入该参数时默认为false,即不返回透视变换矩阵。
:param return_rectification_matrix: The return_rectification_matrix of this GeneralTableRequestBody.
:type return_rectification_matrix: bool
"""
self._return_rectification_matrix = return_rectification_matrix
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
import simplejson as json
if six.PY2:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)
def __repr__(self):
"""For `print`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, GeneralTableRequestBody):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"hwcloudsdk@huawei.com"
] | hwcloudsdk@huawei.com |
87bfe478a4fb5e2d94899f72a0ba2acfdf930ee3 | 30abd041112e172cff60cc72905166870c5a1833 | /migrations/versions/89a7d21b8cca_.py | d4b393e8861c7abb156fc8af8a5b168b3ce1a322 | [] | no_license | rkdansrn2005/flask | c35123a57c75a954a5c97fab94cb3451e1f387a4 | c7e919a11b0d6395808b95b9681ac5efdc090350 | refs/heads/master | 2023-01-24T13:10:21.536393 | 2020-12-04T05:33:07 | 2020-12-04T05:33:07 | 285,784,883 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,006 | py | """empty message
Revision ID: 89a7d21b8cca
Revises: 1a786038ba41
Create Date: 2020-08-08 15:24:51.046673
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '89a7d21b8cca'
down_revision = '1a786038ba41'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('question', schema=None) as batch_op:
batch_op.alter_column('look',
existing_type=sa.INTEGER(),
nullable=False,
existing_server_default=sa.text("'1'"))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('question', schema=None) as batch_op:
batch_op.alter_column('look',
existing_type=sa.INTEGER(),
nullable=True,
existing_server_default=sa.text("'1'"))
# ### end Alembic commands ###
| [
"rkdansrn@gmaail.com"
] | rkdansrn@gmaail.com |
b4e3965049f4801fdec2a6b0307ef443d8c31f07 | 9c151eb7a6ca613f886ff2f631d4d3fb69635cc9 | /crispy/gui/items.py | 8c23700df8d4d12fb37b65b707048e6c6f2cd207 | [
"MIT"
] | permissive | hf6391964/crispy | 24d8067653f537d1e913bc2acccaea66c185b8cf | db49f91a5da77a5e02e91d2ae0cf96fb9b0ef3e4 | refs/heads/master | 2022-12-27T08:43:45.282407 | 2020-10-15T08:55:43 | 2020-10-15T08:55:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,818 | py | # coding: utf-8
###################################################################
# Copyright (c) 2016-2020 European Synchrotron Radiation Facility #
# #
# Author: Marius Retegan #
# #
# This work is licensed under the terms of the MIT license. #
# For further information, see https://github.com/mretegan/crispy #
###################################################################
# pylint: disable=unused-argument, no-self-use
"""Items for custom models."""
import copy
import logging
import weakref
import numpy as np
from PyQt5.QtCore import (
QAbstractItemModel,
QLocale,
QModelIndex,
QObject,
Qt,
pyqtSignal,
)
logger = logging.getLogger(__name__)
class BaseItem(QObject):
"""Base class for the items of the tree model."""
dataChanged = pyqtSignal(int)
def __init__(self, parent=None, name=None, value=None):
super().__init__(parent=parent)
self._name = name
self._value = value
self._model = None
self._parent = None
self._children = list()
self._visible = False
if isinstance(parent, (QAbstractItemModel, RootItem)):
self._ancestor = None
else:
if parent is not None and parent._ancestor is not None:
self._ancestor = parent._ancestor
else:
self._ancestor = None
self.setParent(parent)
# This might be overkill, but it is better to be on the safe side.
try:
self.dataChanged.disconnect()
except TypeError:
pass
self.dataChanged.connect(self._modelDataChanged)
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
self.dataChanged.emit(0)
@property
def value(self):
return self._value
@value.setter
def value(self, value):
self._value = value
self.dataChanged.emit(1)
@property
def ancestor(self):
return self._ancestor
def _modelDataChanged(self, column):
index = self.model().createIndex(self.childPosition(), column, self)
# logger.info(
# "Item = %s, Data = %s, Model = %s", *(self, self.data(column), self.model())
# )
self.model().dataChanged.emit(index, index)
def parent(self):
return self._parent() if self._parent is not None else None
def setParent(self, parent):
# If the parent is the same, return.
if self.parent() is parent:
# logger.debug("No need to set the parent again.")
return
# If the parent is None, remove the item from the current parent.
if parent is None:
if self.parent() is None:
return
# Remove it from the parent's children.
self.parent().removeRow(self)
self._parent = None
else:
# Remove the item from the current parent.
if self.parent() is not None:
self.parent().removeRow(self)
# Assign the new parent to the item.
self._parent = weakref.ref(parent)
parent = self.parent()
model = None
if isinstance(parent, QAbstractItemModel):
model = parent
elif isinstance(parent, BaseItem):
model = parent.model()
# logger.debug("Item = %s, Parent = %s, Model = %s", *(self, parent, model))
self._updateModel(model)
# Insert to the parent's children.
if isinstance(parent, BaseItem):
parent.appendRow(self)
super().setParent(parent)
def insertRow(self, index, row):
"""Insert a row to the children list at the position specified by the index."""
model = self.model()
if model is not None:
model.beginInsertRows(self.index(), index, index)
self.children().insert(index, row)
if model is not None:
model.endInsertRows()
def appendRow(self, item):
self.insertRow(self.rowCount(), item)
def removeRow(self, row):
"""Remove a row from the children list."""
model = self.model()
index = self.children().index(row)
if model is not None:
# The parent index corresponds to the parent from which the new
# rows are removed. Because the rows are removed from the current
# item, the parent index is self.index().
model.beginRemoveRows(self.index(), index, index)
self.children().pop(index)
if model is not None:
model.endRemoveRows()
def model(self):
model = self._model() if self._model is not None else None
return model
def _updateModel(self, model):
if model != self.model():
# logger.debug(
# "Updating the model for %s from %s to %s.", self, self.model(), model
# )
self._model = None if model is None else weakref.ref(model)
for child in self.children():
# pylint: disable=protected-access
child._updateModel(model)
def index(self, column=0):
"""Return corresponding index in the model or None if not in a model."""
parent = self.parent()
model = self.model()
if model is None: # Not in a model
return None
if parent is model: # Root node
return QModelIndex()
index = parent.index()
row = parent.children().index(self)
return model.index(row, column, index)
def child(self, index):
"""Return the child at the specified index.
FIXME: In some cases, when the method was called from the index()
method of the TreeModel class it raises an IndexError. This is
happening without apparent reason and it was not easily reproducible.
So instead of crashing the application we catch the error and log it.
"""
try:
return self.children()[index]
except IndexError as e:
logger.debug((str(e), self, self.children(), index))
def children(self):
return self._children
def siblings(self):
"""Return the siblings of the item or None if the item has no parent."""
return self.parent().children() if self.parent() else None
def childPosition(self):
"""Return the position of a child."""
parent = self.parent()
if not isinstance(parent, QAbstractItemModel):
return parent.children().index(self)
return 0
def lastChild(self):
try:
return self.children()[-1]
except IndexError:
return None
def columnCount(self):
return 2
def rowCount(self):
return len(self.children())
def data(self, column, role=Qt.DisplayRole):
if role in (Qt.EditRole, Qt.DisplayRole, Qt.UserRole):
if column == 0:
return self.name
if column == 1:
return self.value
return None
def setData(self, column, value, role=Qt.EditRole):
if role in (Qt.EditRole, Qt.UserRole):
if column == 0:
self.name = value
if column == 1:
self.value = value
return True
return False
def flags(self, column):
flags = Qt.ItemIsEnabled | Qt.ItemIsSelectable
if column > 0:
return flags | Qt.ItemIsEditable
return flags
def copyFrom(self, item):
# TODO: If the values are assigned using the setter, the time it takes
# to call the function doubles approximately at each call. The is
# related to the _modelDataChanged() function.
self._name = copy.deepcopy(item.name)
self._value = copy.deepcopy(item.value)
class SelectableItem(BaseItem):
def __init__(self, parent=None, name=None, value=None):
super().__init__(parent=parent, name=name, value=value)
self._checkState = Qt.Unchecked
def data(self, column, role=Qt.DisplayRole):
if role == Qt.CheckStateRole:
return self.checkState
return super().data(column, role)
def setData(self, column, value, role=Qt.EditRole):
if role == Qt.CheckStateRole:
self.checkState = value
return True
return super().setData(column, value, role=role)
@property
def checkState(self):
return self._checkState
@checkState.setter
def checkState(self, value):
self._checkState = value
self.dataChanged.emit(0)
def flags(self, column):
flags = super().flags(column)
if column == 0:
return flags | Qt.ItemIsUserCheckable
return flags
def copyFrom(self, item):
super().copyFrom(item)
self._checkState = copy.deepcopy(item.checkState)
class RootItem(BaseItem):
def __init__(self, parent=None):
super().__init__(parent=parent, name="Root")
class IntItem(BaseItem):
def data(self, column, role=Qt.DisplayRole):
if role in (Qt.EditRole, Qt.DisplayRole):
if column == 1:
try:
return QLocale().toString(self.value)
except TypeError:
return self.value
elif role in (Qt.UserRole,):
if column == 1:
return self.value
return super().data(column, role)
def setData(self, column, value, role=Qt.EditRole):
if role == Qt.EditRole:
if column == 1:
value, ok = QLocale().toInt(value)
if ok:
self.value = value
return True
return super().setData(column, value, role)
class DoubleItem(BaseItem):
def data(self, column, role=Qt.DisplayRole):
if role in (Qt.EditRole, Qt.DisplayRole):
if column == 1:
try:
return QLocale().toString(self._value)
except TypeError:
return self._value
return super().data(column, role)
def setData(self, column, value, role=Qt.EditRole):
if column == 1:
if role == Qt.EditRole:
value, ok = QLocale().toDouble(value)
if ok:
self.value = value
return True
return super().setData(column, value, role)
class Vector3DItem(BaseItem):
def data(self, column, role=Qt.DisplayRole):
# Qt.EditRole is needed to properly show the Numpy array in the
# VectorLineEdit. Because of this the delegates must rely on the Qt.UserRole
# to identify the type editor needed for the data.
if role in (Qt.DisplayRole, Qt.EditRole):
# Qt doesn't know how to represent a Numpy array, so we create a digestible
# representation for it.
if column == 1:
return repr(tuple(self.value))
return super().data(column, role)
def setData(self, column, value, role=Qt.EditRole):
if role == Qt.EditRole:
if column == 1:
# Convert the value to a Numpy array.
self.value = np.fromstring(value[1:-1], dtype=np.int32, sep=",")
return True
return super().setData(column, value, role)
class BoolItem(BaseItem):
@property
def value(self):
return self._value
@value.setter
def value(self, value):
self._value = value
def data(self, column, role=Qt.DisplayRole):
# Disable editing for this type of item.
if role in (Qt.EditRole,):
if column == 1:
return None
elif role in (Qt.DisplayRole, Qt.UserRole,):
if column == 1:
return self.value
return super().data(column, role)
def setData(self, column, value, role=Qt.EditRole):
if role == Qt.EditRole:
if column == 1:
self.value = value
return True
return super().setData(column, value, role)
class ComboItem(BaseItem):
def __init__(self, parent=None, name=None, value=None):
super().__init__(parent=parent, name=name, value=value)
self._items = None
@property
def items(self):
return self._items
@items.setter
def items(self, values):
self._items = values
@property
def currentItem(self):
return self.value
def copyFrom(self, item):
super().copyFrom(item)
self._items = copy.deepcopy(item.items)
| [
"marius.s.retegan@gmail.com"
] | marius.s.retegan@gmail.com |
478c1cd433d69ed09b153816ad9f01d3bdc01166 | 84e0f422b38d0ee9bb3923fb8f6159d6f2438528 | /backend/scrapers/snohomish.py | e808417749855f5735fb2be82c80217616ad492a | [
"MIT"
] | permissive | mazore/wa-covid-vaccines | ae0a3795dc291f9e7866f4609a882551de077c02 | 4d24110562be600bd60339a7789b6a27c790e334 | refs/heads/master | 2023-03-06T03:54:45.346252 | 2021-02-20T06:17:45 | 2021-02-20T06:17:45 | 337,855,615 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 966 | py | from .helpers import try_every_second
from .sign_up_genius import sign_up_genius
from scrape_result import ScrapeResult
def snohomish(driver):
url = 'https://snohomish-county-coronavirus-response-snoco-gis.hub.arcgis.com/pages/covid-19-vaccine'
driver.get(url)
def get_urls():
url1 = driver.find_element_by_xpath('//*[@id="ember87"]/h6[2]/ul[2]/li/a').get_attribute('innerHTML')
url2 = driver.find_element_by_xpath('//*[@id="ember87"]/h6[2]/ul[3]/li/a').get_attribute('innerHTML')
return url1, url2
url1, url2 = try_every_second(get_urls)
if not url1.startswith('https://'):
url1 = 'https://' + url1
if not url2.startswith('https://'):
url2 = 'https://' + url2
return [ScrapeResult("Monroe", url1, not sign_up_genius(driver, url1), '13850 179th Ave SE Monroe WA', 98272),
ScrapeResult("Arlington", url2, not sign_up_genius(driver, url2), '4226 188th St NE Arlington WA', 98223)]
| [
"evanmazor@gmail.com"
] | evanmazor@gmail.com |
d4834f24e9c939cecfa24dc783c3e06733678aeb | 2ce1642bcfafb2349b0a04062ed3ce86d5285566 | /monai/networks/blocks/fcn.py | 4e485f54732b371ad909b34334c2c0383f485edd | [
"Apache-2.0"
] | permissive | KungWanyi/MONAI | 89aa620d32fb6105f5afcaf869dfe25cf442a33d | 52e254ff3a87ccdd4c5d14c3a01b9d9fe5f9c855 | refs/heads/master | 2022-12-06T14:36:12.540456 | 2020-08-23T21:19:42 | 2020-08-23T21:19:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,124 | py | # Copyright 2020 MONAI Consortium
# 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 typing import Type
import torch
import torch.nn as nn
import torch.nn.functional as F
from monai.networks.blocks.convolutions import Convolution
from monai.networks.blocks.upsample import UpSample
from monai.networks.layers.factories import Act, Conv, Norm
from monai.utils import optional_import
models, _ = optional_import("torchvision", "0.5.0", name="models")
class GCN(nn.Module):
"""
The Global Convolutional Network module using large 1D
Kx1 and 1xK kernels to represent 2D kernels.
The code is adapted from lsqshr's original version:
https://github.com/lsqshr/AH-Net/blob/master/net2d.py
"""
def __init__(self, inplanes: int, planes: int, ks: int = 7):
"""
Args:
inplanes: number of input channels.
planes: number of output channels.
ks: kernel size for one dimension. Defaults to 7.
"""
super(GCN, self).__init__()
conv2d_type: Type[nn.Conv2d] = Conv[Conv.CONV, 2]
self.conv_l1 = conv2d_type(in_channels=inplanes, out_channels=planes, kernel_size=(ks, 1), padding=(ks // 2, 0))
self.conv_l2 = conv2d_type(in_channels=planes, out_channels=planes, kernel_size=(1, ks), padding=(0, ks // 2))
self.conv_r1 = conv2d_type(in_channels=inplanes, out_channels=planes, kernel_size=(1, ks), padding=(0, ks // 2))
self.conv_r2 = conv2d_type(in_channels=planes, out_channels=planes, kernel_size=(ks, 1), padding=(ks // 2, 0))
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Args:
x: in shape (batch, inplanes, spatial_1, spatial_2).
"""
x_l = self.conv_l1(x)
x_l = self.conv_l2(x_l)
x_r = self.conv_r1(x)
x_r = self.conv_r2(x_r)
x = x_l + x_r
return x
class Refine(nn.Module):
"""
Simple residual block to refine the details of the activation maps.
The code is adapted from lsqshr's original version:
https://github.com/lsqshr/AH-Net/blob/master/net2d.py
"""
def __init__(self, planes: int):
"""
Args:
planes: number of input channels.
"""
super(Refine, self).__init__()
relu_type: Type[nn.ReLU] = Act[Act.RELU]
conv2d_type: Type[nn.Conv2d] = Conv[Conv.CONV, 2]
norm2d_type: Type[nn.BatchNorm2d] = Norm[Norm.BATCH, 2]
self.bn = norm2d_type(num_features=planes)
self.relu = relu_type(inplace=True)
self.conv1 = conv2d_type(in_channels=planes, out_channels=planes, kernel_size=3, padding=1)
self.conv2 = conv2d_type(in_channels=planes, out_channels=planes, kernel_size=3, padding=1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Args:
x: in shape (batch, planes, spatial_1, spatial_2).
"""
residual = x
x = self.bn(x)
x = self.relu(x)
x = self.conv1(x)
x = self.bn(x)
x = self.relu(x)
x = self.conv2(x)
out = residual + x
return out
class FCN(nn.Module):
"""
2D FCN network with 3 input channels. The small decoder is built
with the GCN and Refine modules.
The code is adapted from lsqshr's original version:
https://github.com/lsqshr/AH-Net/blob/master/net2d.py
Args:
out_channels: number of output channels. Defaults to 1.
upsample_mode: The mode of upsampling manipulations, there are two choices:
1) ``transpose``, uses transposed convolution layers.
2) ``bilinear``, uses bilinear interpolate.
Using the second mode cannot guarantee the model's reproducibility. Defaults to ``bilinear``.
"""
def __init__(self, out_channels: int = 1, upsample_mode: str = "bilinear"):
super(FCN, self).__init__()
conv2d_type: Type[nn.Conv2d] = Conv[Conv.CONV, 2]
self.upsample_mode = upsample_mode
self.conv2d_type = conv2d_type
self.out_channels = out_channels
resnet = models.resnet50(pretrained=True)
self.conv1 = resnet.conv1
self.bn0 = resnet.bn1
self.relu = resnet.relu
self.maxpool = resnet.maxpool
self.layer1 = resnet.layer1
self.layer2 = resnet.layer2
self.layer3 = resnet.layer3
self.layer4 = resnet.layer4
self.gcn1 = GCN(2048, self.out_channels)
self.gcn2 = GCN(1024, self.out_channels)
self.gcn3 = GCN(512, self.out_channels)
self.gcn4 = GCN(64, self.out_channels)
self.gcn5 = GCN(64, self.out_channels)
self.refine1 = Refine(self.out_channels)
self.refine2 = Refine(self.out_channels)
self.refine3 = Refine(self.out_channels)
self.refine4 = Refine(self.out_channels)
self.refine5 = Refine(self.out_channels)
self.refine6 = Refine(self.out_channels)
self.refine7 = Refine(self.out_channels)
self.refine8 = Refine(self.out_channels)
self.refine9 = Refine(self.out_channels)
self.refine10 = Refine(self.out_channels)
self.transformer = self.conv2d_type(in_channels=256, out_channels=64, kernel_size=1)
if self.upsample_mode == "transpose":
self.up_conv = UpSample(
spatial_dims=2,
in_channels=self.out_channels,
out_channels=self.out_channels,
scale_factor=2,
with_conv=True,
)
def forward(self, x: torch.Tensor):
"""
Args:
x: in shape (batch, 3, spatial_1, spatial_2).
"""
org_input = x
x = self.conv1(x)
x = self.bn0(x)
x = self.relu(x)
conv_x = x
x = self.maxpool(x)
pool_x = x
fm1 = self.layer1(x)
fm2 = self.layer2(fm1)
fm3 = self.layer3(fm2)
fm4 = self.layer4(fm3)
gcfm1 = self.refine1(self.gcn1(fm4))
gcfm2 = self.refine2(self.gcn2(fm3))
gcfm3 = self.refine3(self.gcn3(fm2))
gcfm4 = self.refine4(self.gcn4(pool_x))
gcfm5 = self.refine5(self.gcn5(conv_x))
if self.upsample_mode == "transpose":
fs1 = self.refine6(self.up_conv(gcfm1) + gcfm2)
fs2 = self.refine7(self.up_conv(fs1) + gcfm3)
fs3 = self.refine8(self.up_conv(fs2) + gcfm4)
fs4 = self.refine9(self.up_conv(fs3) + gcfm5)
out = self.refine10(self.up_conv(fs4))
else:
fs1 = self.refine6(
F.interpolate(gcfm1, fm3.size()[2:], mode=self.upsample_mode, align_corners=True) + gcfm2
)
fs2 = self.refine7(F.interpolate(fs1, fm2.size()[2:], mode=self.upsample_mode, align_corners=True) + gcfm3)
fs3 = self.refine8(
F.interpolate(fs2, pool_x.size()[2:], mode=self.upsample_mode, align_corners=True) + gcfm4
)
fs4 = self.refine9(
F.interpolate(fs3, conv_x.size()[2:], mode=self.upsample_mode, align_corners=True) + gcfm5
)
out = self.refine10(F.interpolate(fs4, org_input.size()[2:], mode=self.upsample_mode, align_corners=True))
return out
class MCFCN(FCN):
"""
The multi-channel version of the 2D FCN module.
Adds a projection layer to take arbitrary number of inputs.
The code is adapted from lsqshr's original version:
https://github.com/lsqshr/AH-Net/blob/master/net2d.py
Args:
in_channels: number of input channels. Defaults to 3.
out_channels: number of output channels. Defaults to 1.
upsample_mode: The mode of upsampling manipulations, there are two choices:
1) ``transpose``, uses transposed convolution layers.
2) ``bilinear``, uses bilinear interpolate.
Using the second mode cannot guarantee the model's reproducibility. Defaults to ``bilinear``.
"""
def __init__(self, in_channels: int = 3, out_channels: int = 1, upsample_mode: str = "bilinear"):
super(MCFCN, self).__init__(out_channels=out_channels, upsample_mode=upsample_mode)
self.init_proj = Convolution(
dimensions=2,
in_channels=in_channels,
out_channels=3,
kernel_size=1,
act=("relu", {"inplace": True}),
norm=Norm.BATCH,
bias=False,
)
def forward(self, x: torch.Tensor):
"""
Args:
x: in shape (batch, in_channels, spatial_1, spatial_2).
"""
x = self.init_proj(x)
out = super(MCFCN, self).forward(x)
return out
| [
"noreply@github.com"
] | KungWanyi.noreply@github.com |
0cc769848860a855bec5c2ca9964aa47989c498d | f428f7c901ea7cd256b2900579ff6e91272a7021 | /config.py | 9ee4a26b9ba6f0bd8e4d927ff7f4325a86ea3e97 | [] | no_license | wvanbreukelen/nfc-pn532 | a5d0bf2c6101e681453080c80c28de909b7ea50a | 7386950d3f46491fd24addd88f4f9cbe99cfa2f3 | refs/heads/master | 2021-03-27T13:00:47.981450 | 2017-02-03T11:20:30 | 2017-02-03T11:20:30 | 77,852,228 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 79 | py |
# PN532 GPIO aansluitconfiguratie
CS = 18
MOSI = 23
MISO = 24
SCLK = 25
| [
"wiebe@vanbreukelen.me"
] | wiebe@vanbreukelen.me |
196e76eb7e399789a7471bed8b621a5195ec9bc2 | 16243d6f64201848d204fd3a767cbe805d88bdca | /win_notification.py | 9a730940c5d8cb684773da3ea6ebc017f6a64965 | [] | no_license | vinayakz/python_ex | b4d990c8d2d6bef3189989b8cda2e8efd3e347a5 | 2ced10a76afc9adcc9770fa0ae3373984a03a8aa | refs/heads/master | 2022-10-07T14:31:05.293078 | 2020-06-08T07:10:41 | 2020-06-08T07:10:41 | 267,270,750 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 272 | py | from win10toast import ToastNotifier
toaster = ToastNotifier()
toaster.show_toast("Notification!", "Alert! Hi VinayakZ Your System is Hacked...", threaded=True, icon_path=None, duration=10)#3seconds
import time
while toaster.notification_active():
time.sleep(1) | [
"noreply@github.com"
] | vinayakz.noreply@github.com |
898ab7721ccb11274093b021fc5b68ce7830ff15 | f18e38804d0dbd3e31366cad49f3b1f091cc78b8 | /mail/migrations/0001_initial.py | c9d3b908669dfa8add87aaa81ddeceaac14b625a | [] | no_license | waffledood/project3-mail | 9d4f1822acb8c343760b34fd7cbf57a39faafb5f | 41c44262a23ef702ac84b8d62a947070c9539225 | refs/heads/main | 2023-02-01T22:04:55.528590 | 2020-12-12T01:09:31 | 2020-12-12T01:09:31 | 308,658,831 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,881 | py | # Generated by Django 3.1 on 2020-12-09 01:57
from django.conf import settings
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
'abstract': False,
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
migrations.CreateModel(
name='Email',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('subject', models.CharField(max_length=255)),
('body', models.TextField(blank=True)),
('timestamp', models.DateTimeField(auto_now_add=True)),
('read', models.BooleanField(default=False)),
('archived', models.BooleanField(default=False)),
('recipients', models.ManyToManyField(related_name='emails_received', to=settings.AUTH_USER_MODEL)),
('sender', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='emails_sent', to=settings.AUTH_USER_MODEL)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='emails', to=settings.AUTH_USER_MODEL)),
],
),
]
| [
"itshaikalhere@hotmail.sg"
] | itshaikalhere@hotmail.sg |
a3efc2a6f910380e434f3cf1b9d41fbf65912c7b | 8f60757e6f9cd9259d7105abbf68c7bb499d3938 | /forms.py | 7a53fecfbb98814bb0e9a5d30bb7bd076d8911b1 | [] | no_license | jamesconfy/Login-Authentication | e9dc110c39597eb8165ae0ff56c7e6dc64de6161 | f248b99911521df4ef2d146daf8297dd04ee93a9 | refs/heads/main | 2023-02-04T21:27:47.123197 | 2020-12-27T08:47:00 | 2020-12-27T08:47:00 | 314,788,570 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,816 | py | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError
from db import *
class RegistratrionForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)])
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired(), Length(min=5, max=20)])
confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password', message='Password Must Match')])
first_name = StringField('First Name', validators=[DataRequired()])
last_name = StringField('Last Name', validators=[DataRequired()])
dob = StringField('Date of Birth')
address = StringField('Address')
city = StringField('City')
state = StringField('State')
phone_no = StringField('Phone Number')
submit = SubmitField('Sign Up')
def validate_username(self, username):
db = DB()
user = db.GetByUsername(username.data)
if user:
raise ValidationError('This username already exists')
def validate_email(self, email):
db = DB()
user = db.GetByEmail(email.data)
if user:
raise ValidationError('This email already exists')
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
remember = BooleanField('Remember Me')
submit = SubmitField('Login')
class UpdateAccountForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)])
email = StringField('Email', validators=[DataRequired(), Email()])
first_name = StringField('First Name', validators=[DataRequired()])
last_name = StringField('Last Name', validators=[DataRequired()])
dob = StringField('Date of Birth')
address = StringField('Address')
city = StringField('City')
state = StringField('State')
phone_no = StringField('Phone Number')
submit = SubmitField('Update')
def validate_username(self, username):
db = DB()
if db.GetByUsername(username.data) != None:
if username.data != db.GetByUsername(username.data)[1]:
user = db.GetByUsername(username.data)
if user:
raise ValidationError('This username already exists')
def validate_email(self, email):
db = DB()
if db.GetByEmail(email.data) != None:
if email.data != db.GetByEmail(email.data)[3]:
user = db.GetByEmail(email.data)
if user:
raise ValidationError('This email already exists') | [
"bobdence@gmail.com"
] | bobdence@gmail.com |
c7bba5bd5bb3cbb88643a359cb34af2a11d68f79 | 10411291b02bff6c6deece1849bb3377d8a33145 | /TinyImageNet/Transfer/network/wresnet.py | 13e800129a22a3e3a6a2e436fd6e8d6222ab4a52 | [] | no_license | PoE-code/Pool-of-Experts-code | cd28749b75445b9f23dbc9a85e4a416278120b22 | c979ff4c336a8593a31d63f3b856558c331657f0 | refs/heads/master | 2023-04-23T06:21:54.754888 | 2021-04-28T04:30:37 | 2021-04-28T04:30:37 | 339,690,464 | 4 | 3 | null | null | null | null | UTF-8 | Python | false | false | 7,616 | py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
def __init__(self, i, in_planes, out_planes, stride, dropRate=0.0):
super(BasicBlock, self).__init__()
self.bn1 = nn.BatchNorm2d(in_planes)
self.relu1 = nn.ReLU(inplace=True)
self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(out_planes)
self.relu2 = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(out_planes, out_planes, kernel_size=3, stride=1,
padding=1, bias=False)
self.droprate = dropRate
self.equalInOut = (in_planes == out_planes)
if (i == 0):
self.equalInOut = False
if (in_planes == 16) and (out_planes == 16):
self.equalInOut = True
self.convShortcut = (not self.equalInOut) and nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride,
padding=0, bias=False) or None
def forward(self, x):
if not self.equalInOut:
x = self.relu1(self.bn1(x))
else:
out = self.relu1(self.bn1(x))
out = self.relu2(self.bn2(self.conv1(out if self.equalInOut else x)))
if self.droprate > 0:
out = F.dropout(out, p=self.droprate, training=self.training)
out = self.conv2(out)
return torch.add(x if self.equalInOut else self.convShortcut(x), out)
class NetworkBlock(nn.Module):
def __init__(self, nb_layers, in_planes, out_planes, block, stride, dropRate=0.0):
super(NetworkBlock, self).__init__()
self.layer = self._make_layer(block, in_planes, out_planes, nb_layers, stride, dropRate)
def _make_layer(self, block, in_planes, out_planes, nb_layers, stride, dropRate):
layers = []
for i in range(int(nb_layers)):
layers.append(block(i, i == 0 and in_planes or out_planes, out_planes, i == 0 and stride or 1, dropRate))
return nn.Sequential(*layers)
def forward(self, x):
return self.layer(x)
class WideResNet_EX(nn.Module):
def __init__(self, depth, num_classes, widen_factor=1, dropRate=0.0):
super(WideResNet_EX, self).__init__()
nChannels = [16, 16*widen_factor, 32*widen_factor, 64*widen_factor]
assert((depth - 4) % 6 == 0)
n = (depth - 4) / 6
block = BasicBlock
# 1st conv before any network block
self.conv1 = nn.Conv2d(3, nChannels[0], kernel_size=3, stride=2, padding=1, bias=False)
# 1st block
self.block1 = NetworkBlock(n, nChannels[0], nChannels[1], block, 1, dropRate)
# 2nd block
self.block2 = NetworkBlock(n, nChannels[1], nChannels[2], block, 2, dropRate)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
elif isinstance(m, nn.Linear):
m.bias.data.zero_()
def forward(self, x):
out = self.conv1(x)
out = self.block1(out)
out = self.block2(out)
return out
class WideResNet_CL(nn.Module):
def __init__(self, depth, num_classes, EX_widen_factor=1, widen_factor=1, dropRate=0.0):
super(WideResNet_CL, self).__init__()
nChannels = [16, 16*EX_widen_factor, 32*EX_widen_factor, int(64*widen_factor)]
assert((depth - 4) % 6 == 0)
n = (depth - 4) / 6
block = BasicBlock
# 3rd block
self.block3 = NetworkBlock(n, nChannels[2], nChannels[3], block, 2, dropRate)
# global average pooling and classifier
self.bn1 = nn.BatchNorm2d(nChannels[3])
self.relu = nn.ReLU(inplace=True)
self.fc = nn.Linear(nChannels[3], num_classes)
self.nChannels = nChannels[3]
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
elif isinstance(m, nn.Linear):
m.bias.data.zero_()
def forward(self, x):
out = self.block3(x)
out = self.relu(self.bn1(out))
out = F.avg_pool2d(out, 8)
out = out.view(-1, self.nChannels)
out = self.fc(out)
return out
class WideResNet(nn.Module):
def __init__(self, depth, num_classes, widen_factor=1, dropRate=0.0):
super(WideResNet, self).__init__()
nChannels = [16, 16*widen_factor, 32*widen_factor, 64*widen_factor]
assert((depth - 4) % 6 == 0)
n = (depth - 4) / 6
block = BasicBlock
# 1st conv before any network block
self.conv1 = nn.Conv2d(3, nChannels[0], kernel_size=3, stride=2, padding=1, bias=False)
# 1st block
self.block1 = NetworkBlock(n, nChannels[0], nChannels[1], block, 1, dropRate)
# 2nd block
self.block2 = NetworkBlock(n, nChannels[1], nChannels[2], block, 2, dropRate)
# 3rd block
self.block3 = NetworkBlock(n, nChannels[2], nChannels[3], block, 2, dropRate)
# global average pooling and classifier
self.bn1 = nn.BatchNorm2d(nChannels[3])
self.relu = nn.ReLU(inplace=True)
self.fc = nn.Linear(nChannels[3], num_classes)
self.nChannels = nChannels[3]
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
elif isinstance(m, nn.Linear):
m.bias.data.zero_()
def forward(self, x):
out = self.conv1(x)
out = self.block1(out)
out = self.block2(out)
out = self.block3(out)
out = self.relu(self.bn1(out))
out = F.avg_pool2d(out, 8)
out = out.view(-1, self.nChannels)
out = self.fc(out)
return out
class WideResNet_MQ(nn.Module):
def __init__(self, library, experts):
super(WideResNet_MQ, self).__init__()
self.library = library
self.experts = experts
def forward(self, x, logits=False):
out = self.library(x)
logit_list = []
for expert in self.experts:
logit_list.append(expert(out))
out = torch.cat(logit_list, dim=1)
if logits is True:
return out, logit_list
return out
def wideresnet(depth=40, num_classes=100, widen_factor=2, dropRate=0.0):
return WideResNet(depth=depth, num_classes=num_classes, widen_factor=widen_factor, dropRate=dropRate)
def wideresnet_MQ(library, experts):
return WideResNet_MQ(library=library, experts=experts)
def wideresnet_ex(depth=40, num_classes=100, widen_factor=2, dropRate=0.0):
return WideResNet_EX(depth=depth, num_classes=num_classes, widen_factor=widen_factor, dropRate=dropRate)
def wideresnet_cl(depth=40, num_classes=100, EX_widen_factor=2, widen_factor=2, dropRate=0.0):
return WideResNet_CL(depth=depth, num_classes=num_classes, EX_widen_factor=EX_widen_factor, widen_factor=widen_factor, dropRate=dropRate)
| [
"qlsgkrrla@naver.com"
] | qlsgkrrla@naver.com |
ba6057b904c4d35f944213ce88ba21d69078d0e0 | ff8f622ada10cf1faa9d574323ca622c3cf60eed | /setup.py | 5e6cd041208f8f03e31b73e4f4ae347b9edd5527 | [] | no_license | openknot/broker | a43c7348601d67cea644732c7741464bbc1f84b8 | 6c981f1e054b573cabe31be50b3bf48b8747b407 | refs/heads/master | 2021-03-12T20:14:22.264746 | 2015-07-29T13:39:10 | 2015-07-29T13:39:10 | 39,689,953 | 0 | 0 | null | 2015-07-28T21:30:55 | 2015-07-25T14:53:30 | Python | UTF-8 | Python | false | false | 1,056 | py | #!/usr/bin/env python
from setuptools import setup, find_packages
from broker.version import version
def parse_requirements(filename):
with open(filename, "r") as f:
for line in f:
if line and line[:2] not in ("#", "-e"):
yield line.strip()
setup(
name="broker",
version=version,
description="OpenKnot Broker",
long_description=open("README.rst", "r").read(),
author="James Mills",
author_email="James Mills, prologic at shortcircuit dot net dot au",
url="https://github.com/openknot/broker",
download_url="https://github.com/openknot/broker/archive/master.zip",
classifiers=[
"Development Status :: 3 - Alpha",
"Programming Language :: Python :: 2.7",
],
license="TBA",
keywords="openknot broker",
platforms="POSIX",
packages=find_packages("."),
install_requires=list(parse_requirements("requirements.txt")),
entry_points={
"console_scripts": [
"broker=broker.main:main"
]
},
zip_safe=True
)
| [
"prologic@shortcircuit.net.au"
] | prologic@shortcircuit.net.au |
30560aefac3f85239aafbf3d358b0eec9b29a619 | 05bb0a05861a0800a7a34ff139eb4e31f6605ed9 | /weather/weatherapp/forms.py | 40ec175b6fe0112a4429bc83e1d6f94a5d7a765d | [] | no_license | KonstantinShr/WeatherWidget | 910223124b7f0a60d61031e8ff13ec2c0fdb61dc | db28cfcee4e47baa16839e3c296dc67312732cfe | refs/heads/master | 2022-12-30T12:16:42.188637 | 2020-10-13T17:59:45 | 2020-10-13T17:59:45 | 303,837,955 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 353 | py | from .models import City
from django.forms import ModelForm, TextInput
class CityForm(ModelForm):
class Meta:
model = City
fields = ['name']
widgets = {'name' : TextInput(attrs = {
'class': "form-control",
'name' : 'city',
'id': 'city',
'placeholder': 'Введите город'
})}
| [
"sharlaev2000@yandex.ru"
] | sharlaev2000@yandex.ru |
da09cbabc5dc2d36e79d5762510eba3f735394e0 | 78f78d2af464ec695746d9ae4b0f516ee261f8e0 | /castero/subscriptions.py | 34a4fe9811f1323c5c0671ba2e8b499e6dfe155e | [
"MIT"
] | permissive | hebecked/castero | 842e9b5c34086ca39523335d9cacf0547d9dbb3f | fc700a7bfc986205fc19d208d613beed9baf2fa6 | refs/heads/master | 2020-12-09T09:37:42.187025 | 2020-01-11T16:54:06 | 2020-01-11T16:54:06 | 233,264,238 | 0 | 0 | MIT | 2020-01-11T16:47:58 | 2020-01-11T16:47:57 | null | UTF-8 | Python | false | false | 5,173 | py | import xml.etree.ElementTree as ElementTree
from typing import List
from castero.feed import Feed
class SubscriptionsError(Exception):
"""An ambiguous error while handling the document.
"""
class SubscriptionsLoadError(SubscriptionsError):
"""A document could not be found at the provided file, or an IO exception
occurred when loading the file.
"""
class SubscriptionsParseError(SubscriptionsError):
"""The document could not be parsed as an XML document.
"""
class SubscriptionsStructureError(SubscriptionsError):
"""The file data is not a properly structured OPML document.
"""
class Subscriptions():
"""The user's podcast subscriptions.
Instances of this class represent a list of podcast subscriptions, which
the user can import from (and export to) OPML-formatted documents.
"""
def __init__(self) -> None:
self._tree = None
self._feeds = []
def load(self, path: str) -> None:
"""Load an OPML file of subscriptions.
Args:
path: the location of the OPML file to load
Raises:
SubscriptionsParseError: unable to parse text as an XML document
SubscriptionsLoadError: an exception occurred when attempting to
load the file
SubscriptionsStructureError: the file data is not a properly
structured OPML document
"""
self._tree = None
try:
self._tree = ElementTree.parse(path)
self._parse_feeds()
except IOError:
raise SubscriptionsLoadError(
"An I/O exception occurred when attempting to load the file")
except ElementTree.ParseError:
raise SubscriptionsParseError(
"Unable to parse text as an XML document")
def save(self, path: str) -> None:
"""Save an OPML file of subscriptions.
A subscriptions document must have been loaded (with .load) or created
(with .generate) before running this method.
Args:
path: the location of the OPML file to create
Raises:
SubscriptionsError: attempted to save before creating document
SubscriptionsLoadError: an exception occurred when attempting to
write the file
"""
if self._tree is not None:
try:
self._tree.write(path, xml_declaration=True)
except IOError:
raise SubscriptionsLoadError(
"An I/O exception occurred when attempting to save the"
" file")
else:
raise SubscriptionsError(
"Attempted to save an XML document that has not been loaded or"
" created")
def generate(self, feeds: List[Feed]) -> None:
"""Create subscriptions document from list of feeds.
Args:
feeds: the list of feeds to include in the document
"""
builder = ElementTree.TreeBuilder()
builder.start("opml", {'version': '2.0'})
builder.start("head", {})
builder.start("title", {})
builder.data("castero feeds")
builder.end("title")
builder.end("head")
builder.start("body", {})
for feed in feeds:
builder.start("outline", {
'type': 'rss',
'text': str(feed),
'xmlUrl': feed.key
})
builder.end("outline")
builder.end("body")
builder.end("opml")
# .close returns an Element, so we need to cast to an ElementTree
self._tree = ElementTree.ElementTree(builder.close())
def _parse_feeds(self) -> None:
"""Parse the XML tree into a list of feeds.
Raises:
SubscriptionsStructureError: the file data is not a properly
structured OPML document
"""
error_msg = "The file data is not a properly structured OPML document"
if self._tree is None:
raise SubscriptionsStructureError(error_msg)
body = self._tree.find('body')
if body is None:
raise SubscriptionsStructureError(error_msg)
feeds_container = self._find_rss_container(body)
if feeds_container is not None:
self._feeds = []
for entry in feeds_container.findall('outline'):
feed = Feed(url=entry.attrib['xmlUrl'])
self._feeds.append(feed)
def _find_rss_container(self, container):
"""Find potentially-nested container for RSS feeds.
Args:
container: the Element to search
Return:
Element: the first 'outline' Element containing an RSS feed
"""
outline = container.find('outline')
if outline is None:
return None
if 'type' in outline.attrib and \
outline.attrib['type'].lower() == 'rss':
return container
else:
return self._find_rss_container(outline)
@property
def feeds(self) -> List[Feed]:
"""List[Feed]: the loaded feeds"""
return self._feeds
| [
"jake@faltro.com"
] | jake@faltro.com |
0a0c6a5ea3bb0a65af3e4d4fe8168c525aa0fd1e | 4be544f5cd3ac39f60cc3ce3c0a4fa4a5c1fba19 | /47_movingwithbreaking.py | 4a847fba0973046cfb2d5fc1949585386f6e286e | [] | no_license | cjdool/pswtest | 3ee8f16b4497447ff00784dbefc6ac3d22fc5bb0 | 00b5c28842c7cb1057ee78781718c13744f4d52f | refs/heads/master | 2023-07-26T08:43:13.686836 | 2021-09-08T16:35:54 | 2021-09-08T16:35:54 | 338,948,284 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,165 | py | #추가 정보를 다른 데이터로 둘지 array에 축을 1개 더 추가할지 잘 판단할 것
import sys
from collections import deque
N, M = map(int, sys.stdin.readline().split())
maze = []
visited = []
dx = [0, 0, 1, -1]
dy = [1, -1, 0 ,0]
for _ in range(N):
maze.append(list(map(int, list(sys.stdin.readline().strip()))))
visited.append([[0]*2 for _ in range(M)])
queue = deque([(0, 0, 1)])
visited[0][0][1] = 1
pos = False
while queue:
x, y, flag = queue.popleft()
if x == N-1 and y == M-1:
pos = True
print(visited[x][y][flag])
break
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < N and 0 <= ny < M:
if maze[nx][ny] == 1 and flag == 1:
visited[nx][ny][0] = visited[x][y][1] + 1
queue.append((nx, ny, 0))
elif maze[nx][ny] == 0 and visited[nx][ny][flag] == 0:
visited[nx][ny][flag] = visited[x][y][flag] + 1
queue.append((nx, ny, flag))
if not pos:
print(-1)
'''
6 4
0000
1110
1111
0000
1111
0000
4 4
0111
0000
1111
1110
5 7
0110001
0110101
0110101
0100101
1111100
''' | [
"cjdool@naver.com"
] | cjdool@naver.com |
21ecb82e580061791ed6e92086b6ba506a3d85d1 | feac152816f4c9d2ae2a9f61645de35c6ea35300 | /oc_lettings_site/tests.py | 037486d1f7b6dcefe974bea3e2223d55c613c6b2 | [] | no_license | LevequeBenjamin/LevequeBenjamin_P13_09-09-2021 | 6f2afed2ee8d9895571021f5cb4d2d0bf6981b4b | b09ec3d656fb65f51a7c250e1f623e30313357fc | refs/heads/master | 2023-07-30T11:27:52.323891 | 2021-09-17T11:02:08 | 2021-09-17T11:02:08 | 404,604,021 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 208 | py | from django.urls import reverse
def test_index_view(client):
url = reverse('index')
response = client.get(url)
assert b'Holiday Homes' in response.content
assert response.status_code == 200
| [
"bosso27@live.fr"
] | bosso27@live.fr |
d814534fbaf444785b02cc43eea18d5d1b77d09d | 81f6f2ced384b98d6ab9acbfab377769a3f8d3d5 | /MaxValue.py | 3a11c460b48ff261afa7b784dfb3a872b02fccd1 | [] | no_license | lukejuusola/AoCMM2016-Traffic | d6ac286598d697cffcc13fbf74d551588e0fc681 | ed69aa93af9459f7152257e5b9dea1b16555ceaa | refs/heads/master | 2021-03-27T15:54:45.682915 | 2016-10-18T22:45:07 | 2016-10-18T22:45:07 | 70,879,866 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 406 | py | import numpy as np
import math
def MaxValue(f, X, Y):
Xl, Yl = np.meshgrid(X, Y)
vf = np.vectorize(f)
Z = vf(Xl, Yl)
index = np.argmax(Z)
x_in = math.floor(index/50)
y_in = index%50
return (X[x_in], Y[y_in], Z[x_in][y_in])
if __name__ == '__main__':
x_mean = .84
y_mean = .12
f = lambda x,y: 1 - math.sqrt((x-x_mean)**2 + (y-y_mean)**2)
print(MaxValue(f, np.linspace(0,1), np.linspace(0,1)))
| [
"luke.juusola@gmail.com"
] | luke.juusola@gmail.com |
61dc070e5a86e2b73d04f40ebd6bed134ea96081 | 3aa32c3dde014f7233ce8153b270ad2d1de105bd | /networking/asyncore/server.py | 1603062d78bf0299aad22559cf2fff292ec5646c | [] | no_license | mwhooker/a-posteriori | adc9ac1c187a5dad78652fa316fc635ac071befc | daf0a252babb20f3999ba0a8054dfe671bf7c37b | refs/heads/master | 2021-01-01T20:10:34.022064 | 2019-05-21T08:00:07 | 2019-05-21T08:00:07 | 2,758,393 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,261 | py | import asyncore
import asynchat
import json
import socket
class Clients(object):
def __init__(self):
self.clients = {}
def add_client(self, username, client):
self.clients[username] = client
class ChatHandler(asynchat.async_chat):
def __init__(self, socket, server):
asynchat.async_chat.__init__(self, socket)
self.server = server
self.ibuffer = []
self.set_terminator("\r\n\r\n")
def collect_incoming_data(self, data):
"""Buffer the data"""
self.ibuffer.append(data)
def found_terminator(self):
if self.ibuffer:
msg = ''.join(self.ibuffer)
msg = json.loads(msg)
print "got ", self.ibuffer
if msg["type"] == "connect":
self.username = msg["username"]
self.server.register(self)
elif msg["type"] == "msg":
self.server.message(self, msg["body"])
else:
print "unknown type: ", msg
self.ibuffer = []
def send_message(self, from_, message):
msg = json.dumps({
"from": from_,
"body": message
})
msg += self.get_terminator()
self.push(msg)
class ChatServer(asyncore.dispatcher):
def __init__(self, host, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind((host, port))
self.listen(5)
self.clients = {}
self.connections = set([])
def handle_accept(self):
pair = self.accept()
if pair is None:
pass
else:
sock, addr = pair
print 'Incoming connection from %s' % repr(addr)
self.connections.add(ChatHandler(sock, self))
def handle_write(self):
print "server ready to write"
def register(self, client):
self.clients[client.username] = client
def message(self, from_, message):
for username in self.clients:
if username != from_.username:
self.clients[username].send_message(from_.username, message)
server = ChatServer('localhost', 51234)
asyncore.loop(use_poll=True)
| [
"mwhooker@gmail.com"
] | mwhooker@gmail.com |
c04c1019206d17b9657ec39ea62fd188a10d5db3 | 3bb5b47919a0ed0b5fd03da930ec386e8d267f7a | /app/core/migrations/0001_initial.py | 3749106b063df94107c77f3d6fd31150e5aa846e | [
"MIT"
] | permissive | eliezerben/recipe-app-api | 83ff8eca5ead127d9bf87663e9efd0737613a4bb | 6d842dd66d861917d95181bbbf5a3a5b9827ce24 | refs/heads/master | 2020-07-02T07:16:20.241424 | 2019-09-14T08:04:42 | 2019-09-14T08:04:42 | 201,454,023 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,701 | py | # Generated by Django 2.2.4 on 2019-08-27 17:01
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('email', models.EmailField(max_length=255, unique=True)),
('name', models.CharField(max_length=255)),
('is_active', models.BooleanField(default=True)),
('is_staff', models.BooleanField(default=False)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'abstract': False,
},
),
]
| [
"eliezerben96@gmail.com"
] | eliezerben96@gmail.com |
4bfbae8cb1a8068c105251064ab6600c5fdb9928 | 84fa8eed5002ed65d2fcc6c1e10777bca4cc8d7f | /NetBeansPython/NetCrunch/src/FE_ConstantlyConnected.py | a048493c94f11bfd986e535e63be455129f8071b | [] | no_license | epasseto/pyprog | f76fe6e2484bd1aef0cc35c817e552098b50b875 | d570737b34d7d4502535798795a994a665855b6e | refs/heads/master | 2020-04-23T03:59:05.187402 | 2019-02-15T16:22:24 | 2019-02-15T16:22:24 | 170,894,252 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,175 | py | #! /usr/bin/python
# To change this template, choose Tools | Templates
# and open the template in the editor.
__author__="epasseto"
__date__ ="$16/10/2012 15:10:27$"
#
# Design and implement an algorithm that can preprocess a
# graph and then answer the question "is x connected to y in the
# graph" for any x and y in constant time Theta(1).
#
#
# `process_graph` will be called only once on each graph. If you want,
# you can store whatever information you need for `is_connected` in
# global variables
#
def process_graph(G):
# your code here
pass
#
# When being graded, `is_connected` will be called
# many times so this routine needs to be quick
#
def is_connected(i, j):
# your code here
pass
#######
# Testing
#
def test():
G = {1:{2:1},
2:{1:1},
3:{4:1},
4:{3:1},
5:{}}
process_graph(G)
assert is_connected(1, 2) == True
assert is_connected(1, 3) == False
G = {1:{2:1, 3:1},
2:{1:1},
3:{4:1, 1:1},
4:{3:1},
5:{}}
process_graph(G)
assert is_connected(1, 2) == True
assert is_connected(1, 3) == True
assert is_connected(1, 5) == False
| [
"epasseto@gmail.com"
] | epasseto@gmail.com |
c3c2aa72cb36ac951353c2003f75bd5edc2a4a7b | c191b4c36a9ae3c08ff6805909877047e18b15b4 | /next_happy_number.py | c0dedf9fbd74556d90cfb078b2514e8e94986010 | [] | no_license | jguerra7/geeksforgeeks-1 | 1c52f291e054d0161ea76781b7cebfbbee3928e1 | 245d85e27af9509d3111471f39e73660f305bd93 | refs/heads/master | 2023-03-19T20:07:24.413824 | 2019-11-13T11:53:44 | 2019-11-13T11:53:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 957 | py | """
Next Happy Number
Problem Link: https://practice.geeksforgeeks.org/problems/next-happy-number/0
Author: Shyam Kumar
Date: 12-09-2019
"""
def digit_square_sum(n):
sum = 0
while n > 0:
rem = n % 10
sum += rem*rem
n = n // 10
return sum
def next_happy_number(n):
"""Max 100 times the value of sum is calculated and
checked, if the value of sum is not found to be 1
then it is considered as NOT HAPPY VALUE """
for _ in range(100):
dss = digit_square_sum(n)
if dss == 1:
return True
n = dss
""" If after 100 times, the value of sum is never found
to be 1, so we considering this as limit and hence
the number is not happy number """
return False
def main():
t = int(input())
while(t>0):
n = int(input())
n+=1
while True:
ans=next_happy_number(n)
if ans == True:
break
n+=1
print(n)
t-=1
if __name__ == "__main__":
main()
| [
"svshyam111@gmail.com"
] | svshyam111@gmail.com |
5aced8e5e922dc001abe5acb56e451da0b9de87a | 14e22dfbd49f610e89d72f990dd49ea54332826d | /bin/pcreate | d50c4bddba7544a005a6edf8b1c24b4987aa7670 | [] | no_license | pyj4104/FOTransBaseBE | 7933aa747fe79372168956439d83f60aedc67a3d | a4194928a83881bfd31b06618d49a00f9af20b9a | refs/heads/master | 2021-01-21T06:49:23.231775 | 2015-11-10T04:42:39 | 2015-11-10T04:42:39 | 44,083,505 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 361 | #!/Users/yeounjunpark/Desktop/CurrentWork/FOTrans/FOTransBaseBE/bin/python3.4
# EASY-INSTALL-ENTRY-SCRIPT: 'pyramid==1.6a2','console_scripts','pcreate'
__requires__ = 'pyramid==1.6a2'
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.exit(
load_entry_point('pyramid==1.6a2', 'console_scripts', 'pcreate')()
)
| [
"pyj4104@hotmail.com"
] | pyj4104@hotmail.com | |
89d4093011b308c9daa195ae82ef70017af8485a | 2d280c8225a14f97b2bf26b69fcbc7985f537662 | /configUI.py | 4c920661e3b0f5a269b0aa21c77a5d56ae15e0ef | [] | no_license | bgwtix/myCashier | 3f18dda77b32eeb0a5bd413e1d396f1625ce23cd | c6cb81bc70565702b50bcee2bc4fc0311f273137 | refs/heads/master | 2023-01-19T01:09:01.915982 | 2020-11-22T13:48:33 | 2020-11-22T13:54:02 | 308,891,853 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 998 | py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class configUIInit(QTabWidget):
"""
进货界面
"""
# 构造函数
def __init__(self):
super().__init__()
self.configTab = QWidget()
self.customConfigBox = QGroupBox('基本设置')
self.purchaseMode = QCheckBox("进货模式关闭")
self.addCustomConfigBoxLayout()
self.showConfigUILayout()
def showConfigUILayout(self):
"""
显示配置界面
"""
Layout = QGridLayout()
Layout.addWidget(self.customConfigBox, 0, 0, 1, 1)
Layout.setColumnStretch(1, 1)
Layout.setRowStretch(5, 1)
self.configTab.setLayout(Layout)
def addCustomConfigBoxLayout(self):
"""
新增自定义界面
"""
Layout = QFormLayout()
Layout.addRow(self.purchaseMode)
self.customConfigBox.setLayout(Layout)
| [
"969367669@qq.com"
] | 969367669@qq.com |
6fc087d7f6e6afff6a8f0b41db7088f0c249a146 | 1e11b91d67cc28763e6a913d6ae3f73c9f8167d0 | /filav/routing.py | ee5a3004514b48e77ca05e5060986884155e5da1 | [] | no_license | sebasgoldberg/filav | 62f00aa98213823d142ab3c8893cb78bb4938a21 | c7a2ae60051e4074b24f5f65a7a02935f84fcb09 | refs/heads/master | 2021-09-07T15:08:09.801999 | 2018-02-24T17:04:29 | 2018-02-24T17:04:29 | 115,515,939 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 443 | py | from channels.routing import route, include, route_class
from fila.consumers import *
posto_routing = [
route_class(PostoConsumer, path=r"^/"),
]
fila_routing = [
route_class(FilaConsumer, path=r"^/"),
]
scanner_routing = [
route_class(ScannerConsumer, path=r"^/"),
]
channel_routing = [
include(posto_routing, path=r'^/posto'),
include(fila_routing, path=r'^/fila'),
include(scanner_routing, path=r'^/scanner'),
]
| [
"sebas.goldberg@gmail.com"
] | sebas.goldberg@gmail.com |
c976231583a859049e630eb8884e38d9f1fe2e87 | 0b842bcb3bf20e1ce628d39bf7e11abd7699baf9 | /oscar/a/sys/blinky/example/lake_example/lake/fish_/fish__maapi_list_gen.py | 9f6681918fff221d1a074cca1206d0e8ba3a53c3 | [] | no_license | afeset/miner2-tools | 75cc8cdee06222e0d81e39a34f621399e1ceadee | 81bcc74fe7c0ca036ec483f634d7be0bab19a6d0 | refs/heads/master | 2016-09-05T12:50:58.228698 | 2013-08-27T21:09:56 | 2013-08-27T21:09:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 30,371 | py |
# Copyright Qwilt, 2012
#
# The code contained in this file may not be used by any other entities without explicit written permission from Qwilt.
#
# Author: naamas
from a.infra.misc.enum_with_value import EnumWithValue
from a.infra.basic.return_codes import ReturnCodes
from a.infra.misc.init_guard import InitGuard
from a.sys.confd.pyconfdlib.tag_values import TagValues
from a.sys.confd.pyconfdlib.value import Value
from a.sys.confd.pyconfdlib.key_path import KeyPath
from fish__maapi_list_base_gen import FishMaapiListBase
from fish__maapi_gen import BlinkyFishMaapi
class BlinkyFishMaapiList(FishMaapiListBase):
def __init__ (self, logger):
self.myInitGuard = InitGuard()
self._log=logger.createLogger("sys-blinky-oper-example","blinky-maapi-fish_")
self.domain = None
self.fish_s = {}
self.fish_Keys = []
def init (self, domain):
self.myInitGuard.crashIfInitDone()
for logFunc in self._log('init').debug3Func(): logFunc('called. domain=%s', domain)
self.domain = domain
self.myInitGuard.initDone()
def newFish_ (self):
self.myInitGuard.isInitOrCrash()
for logFunc in self._log('new-fish_').debug3Func(): logFunc('called.')
fish_ = BlinkyFishMaapi(self._log)
fish_.init(self.domain)
return fish_
def setFish_Obj (self, key, fish_Obj):
self.myInitGuard.isInitOrCrash()
for logFunc in self._log('set-fish_-obj').debug3Func(): logFunc('called. key=%s, fish_Obj=%s', key, fish_Obj)
if key not in self.fish_s:
self.fish_Keys.append(key)
self.fish_s[str(key)] = fish_Obj
def getFish_Obj (self, key):
self.myInitGuard.isInitOrCrash()
for logFunc in self._log('get-fish_-obj').debug3Func(): logFunc('called. key=%s', key)
if str(key) in self.fish_s.keys():
for logFunc in self._log('get-fish_-obj-done').debug3Func(): logFunc('Done. found key=%s, obj=%s', key, self.fish_s[str(key)])
return self.fish_s[str(key)]
for logFunc in self._log('get-fish_-obj-missing').errorFunc(): logFunc('fish_ %s not in fish_s. existing items: %s', key, self.fish_s.keys())
return None
def deleteFish_ (self, key):
self.myInitGuard.isInitOrCrash()
for logFunc in self._log('delete-fish_').debug3Func(): logFunc('called. key=%s', key)
if str(key) not in self.fish_Keys:
for logFunc in self._log('delete-fish_-not-found').warningFunc(): logFunc('key=%s is missing from the fish_Keys list', key)
if str(key) in self.fish_s.keys():
# internal problem - list & dictionary are not synced
for logFunc in self._log('delete-fish_-not-found-but-in-dict').errorFunc(): logFunc('fish_s dictionary & fish_Keys list are out-of-sync. key %s exists in dict but not in list', key)
return ReturnCodes.kGeneralError
if str(key) not in self.fish_s.keys():
# internal problem - list & dictionary are not synced
for logFunc in self._log('delete-fish_-not-found-but-in-list').errorFunc(): logFunc('fish_s dictionary & fish_Keys list are out-of-sync. key %s exists in list but not in dict', key)
return ReturnCodes.kGeneralError
self.fish_Keys.remove(str(key))
del self.fish_s[str(key)]
def hasFish_Obj (self, key):
self.myInitGuard.isInitOrCrash()
has = False
if str(key) in self.fish_s.keys():
if self.fish_s[str(key)]:
has = True
for logFunc in self._log('has-fish_-done').debug3Func(): logFunc('done. key=%s exists=%s', key, has)
return has
def getListKeys (self):
self.myInitGuard.isInitOrCrash()
for logFunc in self._log('get-list-keys').debug3Func(): logFunc('called. keys=%s', [str(x) for x in self.fish_Keys])
return self.fish_Keys
def requestConfigAndOper (self):
self.myInitGuard.isInitOrCrash()
for logFunc in self._log('request-config-and-oper').debug3Func(): logFunc('called.')
for fish_ in self.fish_s.values():
fish_.requestConfigAndOper()
def requestConfig (self):
self.myInitGuard.isInitOrCrash()
for logFunc in self._log('request-config').debug3Func(): logFunc('called.')
for fish_ in self.fish_s.values():
fish_.requestConfig()
def requestOper (self):
self.myInitGuard.isInitOrCrash()
for logFunc in self._log('request-oper').debug3Func(): logFunc('called.')
for fish_ in self.fish_s.values():
fish_.requestOper()
def clearAllRequested (self):
self.myInitGuard.isInitOrCrash()
for logFunc in self._log('clear-all-requested').debug3Func(): logFunc('called.')
for fish_ in self.fish_s.values():
fish_.clearAllRequested()
def _clearAllReadData (self):
self.myInitGuard.isInitOrCrash()
for logFunc in self._log('clear-all-read-data').debug3Func(): logFunc('called')
for fish_ in self.fish_s.values():
if fish_:
fish_._clearAllReadData()
def clearAllSet (self):
self.myInitGuard.isInitOrCrash()
for logFunc in self._log('clear-all-set').debug3Func(): logFunc('called, PARAMS')
for key in self.fish_s.keys():
if self.fish_s[key]:
self.fish_s[key].clearAllSet()
else:
self.fish_Keys.remove(str(key))
del self.fish_s[str(key)]
def _getSelfKeyPath (self, lake
, junkForTemplate):
for logFunc in self._log('get-self-key-path').debug3Func(): logFunc('called. PARAMS. junkForTemplate=%s', junkForTemplate)
keyPath = KeyPath()
ancestorVal = Value()
ancestorVal.setString(lake);
keyPath.addKeyPathPrefix(ancestorVal)
xmlVal = Value()
xmlVal.setXmlTag(("lake", "http://qwilt.com/model/lake-example", "lake-example"))
keyPath.addKeyPathPrefix(xmlVal)
for logFunc in self._log('get-self-key-path-done').debug3Func(): logFunc('done. keyPath=%s. PARAMS', keyPath)
return keyPath
def readListKeys (self
, lake
, trxContext=None):
self.myInitGuard.isInitOrCrash()
for logFunc in self._log('read-list-keys').debug3Func(): logFunc('called')
# clear the old map
self.fish_s = {}
self.fish_Keys = []
keyPath = self._getSelfKeyPath(lake,
None)
xmlVal = Value()
xmlVal.setXmlTag(("fish", "http://qwilt.com/model/lake-example", "lake-example"))
keyPath.addKeyPathPostfix(xmlVal)
keys = []
res = self.domain.readMaapiKeys(keyPath, keys, trxContext)
if res != ReturnCodes.kOk:
for logFunc in self._log('read-list-keys-domain-failed').errorFunc(): logFunc('domain.readMaapiKeys() failed')
return ReturnCodes.kGeneralError
for key in keys:
self.fish_Keys.append(key.getCannonicalStr())
self.fish_s[key.getCannonicalStr()] = None
return ReturnCodes.kOk
def write (self
, lake
, trxContext=None
):
self.myInitGuard.isInitOrCrash()
for logFunc in self._log('write').debug3Func(): logFunc('called, PARAMS')
return self._internalWrite(lake,
trxContext)
def read (self
, lake
, trxContext=None):
for logFunc in self._log('read').debug3Func(): logFunc('called, PARAMS')
return self._internalRead(lake,
False,
trxContext)
def readAllOrFail (self
, lake
, trxContext=None):
self.myInitGuard.isInitOrCrash()
for logFunc in self._log('read-all-or-fail').debug3Func(): logFunc('called, PARAMS')
return self._internalRead(lake,
True,
trxContext)
def _internalWrite (self,
lake,
trxContext):
self.myInitGuard.isInitOrCrash()
for logFunc in self._log('internal-write').debug3Func(): logFunc('called.')
tagValueList = TagValues()
res = self._fillWriteTagValues(tagValueList)
if res != ReturnCodes.kOk:
for logFunc in self._log('internal-write-fill-write-tag-value-failed').errorFunc(): logFunc('_fillWriteTagValues() failed')
return ReturnCodes.kGeneralError
itemsToDelete = []
res = self._collectItemsToDelete(lake,
itemsToDelete)
if res != ReturnCodes.kOk:
for logFunc in self._log('write-collect-items-to-delete-failed').errorFunc(): logFunc('_collectItemsToDelete() failed. PARAMS')
return ReturnCodes.kGeneralError
keyPath = self._getSelfKeyPath(lake,
None)
res = self.domain.writeMaapi(tagValueList, keyPath, trxContext, itemsToDelete)
if res != ReturnCodes.kOk:
for logFunc in self._log('write-domain-failed').errorFunc(): logFunc('domain.writeMaapi() failed. PARAMS')
return ReturnCodes.kGeneralError
for logFunc in self._log('internal-write-done').debug3Func(): logFunc('done. PARAMS')
return ReturnCodes.kOk
def _internalRead (self,
lake,
readAllOrFail,
trxContext):
self.myInitGuard.isInitOrCrash()
for logFunc in self._log('internal-read').debug3Func(): logFunc('called. readAllOrFail=%s', readAllOrFail)
if readAllOrFail:
self._clearAllReadData()
tagValueList = TagValues()
res = self._fillReadTagValues(tagValueList)
if res != ReturnCodes.kOk:
for logFunc in self._log('internal-read-fill-read-tag-values-failed').errorFunc(): logFunc('_fillReadTagValues() failed')
return ReturnCodes.kGeneralError
keyPath = self._getSelfKeyPath(lake,
None)
res = self.domain.readMaapi(tagValueList, keyPath, trxContext)
if res != ReturnCodes.kOk:
for logFunc in self._log('internal-read-domain-failed').errorFunc(): logFunc('domain.readMaapi() failed.')
return ReturnCodes.kGeneralError
res = self._readTagValues(tagValueList, readAllOrFail)
if res != ReturnCodes.kOk:
for logFunc in self._log('internal-read-read-tag-values-failed').errorFunc(): logFunc('_readTagValues() failed.')
return ReturnCodes.kGeneralError
for logFunc in self._log('internal-read-done').debug3Func(): logFunc('done. readAllOrFail=%s', readAllOrFail)
return ReturnCodes.kOk
def _collectItemsToDelete (self,
lake,
itemsToDelete):
self.myInitGuard.isInitOrCrash()
for logFunc in self._log('collect-items-to-delete').debug3Func(): logFunc('called: itemsToDelete=%s. PARAMS', itemsToDelete)
for key in self.fish_s.keys():
if self.fish_s[key]:
res = self.fish_s[key]._collectItemsToDelete(lake,
key,
itemsToDelete)
if res != ReturnCodes.kOk:
for logFunc in self._log('collect-items-to-delete-fish_-failed').errorFunc(): logFunc('fish_Obj._collectItemsToDelete() failed. key=%s. PARAMS', key)
return ReturnCodes.kGeneralError
else:
keyPath = self._getSelfKeyPath(lake,
None)
xmlVal = Value()
xmlVal.setXmlTag(("fish", "http://qwilt.com/model/lake-example", "lake-example"))
keyPath.addKeyPathPostfix(xmlVal)
valKey = Value()
valKey.setString(key)
keyPath.addKeyPathPostfix(valKey)
itemsToDelete.append(keyPath)
for logFunc in self._log('collect-items-to-delete-done').debug3Func(): logFunc('done: itemsToDelete=%s. PARAMS', itemsToDelete)
return ReturnCodes.kOk
def _fillWriteTagValues (self, tagValueList):
self.myInitGuard.isInitOrCrash()
for logFunc in self._log('fill-write-tag-values').debug3Func(): logFunc('called: tagValueList=%s', tagValueList)
for key in self.fish_s.keys():
if self.fish_s[key]:
valBegin = Value()
(tag, ns, prefix) = ("fish", "http://qwilt.com/model/lake-example", "lake-example")
valBegin.setXmlBegin((tag, ns, prefix))
tagValueList.push((tag, ns), valBegin)
valKey = Value()
valKey.setString(key)
tagValueList.push(("id", "http://qwilt.com/model/lake-example"), valKey)
tagValueListLen = tagValueList.getLen()
res = self.fish_s[key]._fillWriteTagValues(tagValueList)
if res != ReturnCodes.kOk:
for logFunc in self._log('fill-write-tag-values-fish_-failed').errorFunc(): logFunc('fish_._fillWriteTagValues() failed. key=%s', key)
return ReturnCodes.kGeneralError
if tagValueList.getLen() == tagValueListLen:
# descendant didn't add anything, no need to read it.
tagValueList.pop()
tagValueList.pop()
else:
valEnd = Value()
valEnd.setXmlEnd((tag, ns, prefix))
tagValueList.push((tag, ns), valEnd)
return ReturnCodes.kOk
def _fillReadTagValues (self, tagValueList):
self.myInitGuard.isInitOrCrash()
for logFunc in self._log('fill-read-tag-values').debug3Func(): logFunc('called: tagValueList=%s', tagValueList)
for key in self.fish_s.keys():
if self.fish_s[key]:
valBegin = Value()
(tag, ns, prefix) = ("fish", "http://qwilt.com/model/lake-example", "lake-example")
valBegin.setXmlBegin((tag, ns, prefix))
tagValueList.push((tag, ns), valBegin)
valKey = Value()
valKey.setString(key)
tagValueList.push(("id", "http://qwilt.com/model/lake-example"), valKey)
tagValueListLen = tagValueList.getLen()
res = self.fish_s[key]._fillReadTagValues(tagValueList)
if res != ReturnCodes.kOk:
for logFunc in self._log('fill-read-tag-values-fish_-failed').errorFunc(): logFunc('fish_._fillReadTagValues() failed. key=%s', key)
return ReturnCodes.kGeneralError
if tagValueList.getLen() == tagValueListLen:
# descendant didn't add anything, no need to read it.
tagValueList.pop()
tagValueList.pop()
else:
valEnd = Value()
valEnd.setXmlEnd((tag, ns, prefix))
tagValueList.push((tag, ns), valEnd)
return ReturnCodes.kOk
def _readTagValues (self, tagValueList, readAllOrFail):
self.myInitGuard.isInitOrCrash()
for logFunc in self._log('read-tag-values').debug3Func(): logFunc('called. tagValueList=%s, readAllOrFail=%s', tagValueList, readAllOrFail)
res = ReturnCodes.kOk
for key in self.fish_s.keys():
if self.fish_s[key]:
((tag, ns), valBegin) = tagValueList.popFront()
if (tag != "fish") or \
(ns != "http://qwilt.com/model/lake-example") or \
(valBegin.getType() != Value.kXmlBegin):
for logFunc in self._log('reag-tag-values-unexpected-tag-begin').errorFunc(): logFunc('got unexpected tag-value. expected: (%s, %s, type=%s), got: (%s, %s, type=%s)',
"fish", "http://qwilt.com/model/lake-example", Value.kXmlBegin,
tag, ns, valBegin.getType())
self._clearAllReadData()
return ReturnCodes.kGeneralError
((tag, ns), valKey) = tagValueList.popFront()
if (tag != "id") or \
(ns != "http://qwilt.com/model/lake-example"):
for logFunc in self._log('reag-tag-values-unexpected-tag-key').errorFunc(): logFunc('got unexpected tag-value for key. expected: (%s, %s), got: (%s, %s)',
"id", "http://qwilt.com/model/lake-example", tag, ns)
self._clearAllReadData()
return ReturnCodes.kGeneralError
key = valKey.asString()
if res != ReturnCodes.kOk:
if readAllOrFail:
self._clearAllReadData()
return ReturnCodes.kGeneralError
res = self.fish_s[key]._readTagValues(tagValueList, readAllOrFail)
if res != ReturnCodes.kOk:
for logFunc in self._log('read-tag-values-fish_-failed').errorFunc(): logFunc('fish_._readTagValues() failed. key=%s', key)
if readAllOrFail:
self._clearAllReadData()
return ReturnCodes.kGeneralError
((tag, ns), valEnd) = tagValueList.popFront()
if (tag != "fish") or \
(ns != "http://qwilt.com/model/lake-example") or \
(valEnd.getType() != Value.kXmlEnd):
for logFunc in self._log('reag-tag-values-unexpected-tag-end').errorFunc(): logFunc('got unexpected tag-value. expected: (%s, %s, type=%s), got: (%s, %s, type=%s)',
"fish", "http://qwilt.com/model/lake-example", Value.kXmlEnd,
tag, ns, valEnd.getType())
self._clearAllReadData()
return ReturnCodes.kGeneralError
for logFunc in self._log('read-tag-values-done').debug3Func(): logFunc('done. tagValueList=%s, readAllOrFail=%s', tagValueList, readAllOrFail)
return ReturnCodes.kOk
"""
Extracted from the below data:
{
"node": {
"containerClassName": "BlinkyFishMaapi",
"name": "fish_",
"keyLeaf": {
"varName": "fish_",
"yangName": "id",
"typeHandler": "handler: StringHandler"
},
"yangName": "fish",
"namespace": "fish_",
"moduleYangNamespacePrefix": "lake-example",
"className": "FishMaapiList",
"importStatement": "from a.sys.blinky.example.lake_example.lake.fish_.fish__maapi_list_gen import FishMaapiList",
"baseClassName": "FishMaapiListBase",
"moduleYangNamespace": "http://qwilt.com/model/lake-example",
"containerModule": "fish__maapi_gen",
"baseModule": "fish__maapi_list_base_gen"
},
"ancestors": [
{
"moduleYangNamespacePrefix": "lake-example",
"isCurrent": false,
"yangName": "lake",
"namespace": "lake",
"isList": true,
"moduleYangNamespace": "http://qwilt.com/model/lake-example",
"keyLeaf": {
"varName": "lake",
"yangName": "name",
"typeHandler": "handler: StringHandler"
},
"name": "lake"
},
{
"moduleYangNamespacePrefix": "lake-example",
"isCurrent": true,
"yangName": "fish",
"namespace": "fish_",
"isList": true,
"moduleYangNamespace": "http://qwilt.com/model/lake-example",
"keyLeaf": {
"varName": "fish_",
"yangName": "id",
"typeHandler": "handler: StringHandler"
},
"name": "fish_"
}
],
"descendants": [
{
"moduleYangNamespacePrefix": "lake-example",
"memberName": "mood",
"yangName": "mood",
"className": "BlinkyMoodMaapi",
"importStatement": "from a.sys.blinky.example.lake_example.lake.fish_.mood.mood_maapi_list_gen import BlinkyMoodMaapi",
"isList": false,
"moduleYangNamespace": "http://qwilt.com/model/lake-example"
},
{
"moduleYangNamespacePrefix": "lake-example",
"memberName": "antenna",
"yangName": "antenna",
"className": "BlinkyAntennaMaapi",
"importStatement": "from a.sys.blinky.example.lake_example.lake.fish_.antenna.antenna_maapi_list_gen import BlinkyAntennaMaapi",
"isList": false,
"moduleYangNamespace": "http://qwilt.com/model/lake-example"
},
{
"moduleYangNamespacePrefix": "lake-example",
"memberName": "testGenerationUnderscoreList",
"yangName": "test-generation_underscore",
"className": "BlinkyTestGenerationUnderscoreMaapiList",
"importStatement": "from a.sys.blinky.example.lake_example.lake.fish_.test_generation_underscore.test_generation_underscore_maapi_list_list_gen import BlinkyTestGenerationUnderscoreMaapiList",
"isList": true,
"moduleYangNamespace": "http://qwilt.com/model/lake-example"
},
{
"moduleYangNamespacePrefix": "lake-example",
"memberName": "design",
"yangName": "design",
"className": "BlinkyDesignMaapi",
"importStatement": "from a.sys.blinky.example.lake_example.lake.fish_.design.design_maapi_list_gen import BlinkyDesignMaapi",
"isList": false,
"moduleYangNamespace": "http://qwilt.com/model/lake-example"
},
{
"moduleYangNamespacePrefix": "lake-example",
"memberName": "transparentContainer",
"yangName": "transparent-container",
"className": "BlinkyTransparentContainerMaapi",
"importStatement": "from a.sys.blinky.example.lake_example.lake.fish_.transparent_container.transparent_container_maapi_list_gen import BlinkyTransparentContainerMaapi",
"isList": false,
"moduleYangNamespace": "http://qwilt.com/model/lake-example"
}
],
"conditionalDebugName": null,
"operLeaves": [],
"module": {},
"configLeaves": [
{
"moduleYangNamespace": "http://qwilt.com/model/lake-example",
"moduleYangNamespacePrefix": "lake-example",
"typeHandler": "handler: BoolPyHandler",
"memberName": "transparentField",
"yangName": "transparent-field",
"object": "",
"leafrefPath": null,
"defaultVal": null,
"hasDefaultRef": false
},
{
"moduleYangNamespace": "http://qwilt.com/model/lake-example",
"moduleYangNamespacePrefix": "lake-example",
"typeHandler": "handler: EnumHandlerPy",
"memberName": "color",
"yangName": "color",
"object": "",
"leafrefPath": null,
"defaultVal": null,
"hasDefaultRef": false
},
{
"moduleYangNamespace": "http://qwilt.com/model/lake-example",
"moduleYangNamespacePrefix": "lake-example",
"typeHandler": "handler: IntHandler",
"memberName": "eyeNumber",
"yangName": "eye-number",
"object": "",
"leafrefPath": null,
"defaultVal": null,
"hasDefaultRef": false
},
{
"moduleYangNamespace": "http://qwilt.com/model/lake-example",
"moduleYangNamespacePrefix": "lake-example",
"typeHandler": "handler: BoolPyHandler",
"memberName": "hasTail",
"yangName": "has-tail",
"object": "",
"leafrefPath": null,
"defaultVal": null,
"hasDefaultRef": false
},
{
"moduleYangNamespace": "http://qwilt.com/model/lake-example",
"moduleYangNamespacePrefix": "lake-example",
"typeHandler": "handler: IntHandler",
"memberName": "finNumber",
"yangName": "fin-number",
"object": "",
"leafrefPath": null,
"defaultVal": null,
"hasDefaultRef": false
},
{
"moduleYangNamespace": "http://qwilt.com/model/lake-example",
"moduleYangNamespacePrefix": "lake-example",
"typeHandler": "handler: IntHandler",
"memberName": "length",
"yangName": "length",
"object": "",
"leafrefPath": null,
"defaultVal": null,
"hasDefaultRef": true
},
{
"moduleYangNamespace": "http://qwilt.com/model/lake-example",
"moduleYangNamespacePrefix": "lake-example",
"typeHandler": "handler: Ipv6AddressHandlerPy",
"memberName": "ip6",
"yangName": "ip6",
"object": "",
"leafrefPath": null,
"defaultVal": null,
"hasDefaultRef": false
},
{
"moduleYangNamespace": "http://qwilt.com/model/lake-example",
"moduleYangNamespacePrefix": "lake-example",
"typeHandler": "handler: StringHandler",
"memberName": "id",
"yangName": "id",
"object": "",
"leafrefPath": null,
"defaultVal": null,
"hasDefaultRef": false
}
],
"env": {
"namespaces": [
"a",
"sys",
"blinky",
"example",
"lake_example"
]
},
"leaves": [
{
"moduleYangNamespace": "http://qwilt.com/model/lake-example",
"moduleYangNamespacePrefix": "lake-example",
"typeHandler": "handler: BoolPyHandler",
"memberName": "transparentField",
"yangName": "transparent-field",
"object": "",
"leafrefPath": null,
"defaultVal": null,
"hasDefaultRef": false
},
{
"moduleYangNamespace": "http://qwilt.com/model/lake-example",
"moduleYangNamespacePrefix": "lake-example",
"typeHandler": "handler: EnumHandlerPy",
"memberName": "color",
"yangName": "color",
"object": "",
"leafrefPath": null,
"defaultVal": null,
"hasDefaultRef": false
},
{
"moduleYangNamespace": "http://qwilt.com/model/lake-example",
"moduleYangNamespacePrefix": "lake-example",
"typeHandler": "handler: IntHandler",
"memberName": "eyeNumber",
"yangName": "eye-number",
"object": "",
"leafrefPath": null,
"defaultVal": null,
"hasDefaultRef": false
},
{
"moduleYangNamespace": "http://qwilt.com/model/lake-example",
"moduleYangNamespacePrefix": "lake-example",
"typeHandler": "handler: BoolPyHandler",
"memberName": "hasTail",
"yangName": "has-tail",
"object": "",
"leafrefPath": null,
"defaultVal": null,
"hasDefaultRef": false
},
{
"moduleYangNamespace": "http://qwilt.com/model/lake-example",
"moduleYangNamespacePrefix": "lake-example",
"typeHandler": "handler: IntHandler",
"memberName": "finNumber",
"yangName": "fin-number",
"object": "",
"leafrefPath": null,
"defaultVal": null,
"hasDefaultRef": false
},
{
"moduleYangNamespace": "http://qwilt.com/model/lake-example",
"moduleYangNamespacePrefix": "lake-example",
"typeHandler": "handler: IntHandler",
"memberName": "length",
"yangName": "length",
"object": "",
"leafrefPath": null,
"defaultVal": null,
"hasDefaultRef": true
},
{
"moduleYangNamespace": "http://qwilt.com/model/lake-example",
"moduleYangNamespacePrefix": "lake-example",
"typeHandler": "handler: Ipv6AddressHandlerPy",
"memberName": "ip6",
"yangName": "ip6",
"object": "",
"leafrefPath": null,
"defaultVal": null,
"hasDefaultRef": false
},
{
"moduleYangNamespace": "http://qwilt.com/model/lake-example",
"moduleYangNamespacePrefix": "lake-example",
"typeHandler": "handler: StringHandler",
"memberName": "id",
"yangName": "id",
"object": "",
"leafrefPath": null,
"defaultVal": null,
"hasDefaultRef": false
}
],
"createTime": "2013"
}
"""
| [
"afeset@gmail.com"
] | afeset@gmail.com |
af46e0d99344ae9ea07801381c2eadd48d4e9295 | f70da0d011ad2d96ffd6a693e6cd36f1e1df56cb | /Proyecto2/Instruction/Loops/Break.py | cd345f76842b765cdeaa1eac3dbd634554b1bd4c | [] | no_license | diemorales96/OLC_Proyecto2_201503958 | aeaa2ba013f9ed643b324537cc6493710d407226 | 7779c619e635b7dc7cc2e47130a1c654ac84889a | refs/heads/main | 2023-09-02T05:11:57.732595 | 2021-11-13T04:54:04 | 2021-11-13T04:54:04 | 427,418,116 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 470 | py | from Abstract.Instruction import *
from Abstract.Return import *
from Symbol.Generator import *
class Break(Instruction):
def __init__(self, line, column):
Instruction.__init__(self, line, column)
def compile(self, environment):
if environment.breakLbl == '':
print("Break fuera de ciclo")
return
genAux = Generator()
generator = genAux.getInstance()
generator.addGoto(environment.breakLbl) | [
"diemorab@gmail.com"
] | diemorab@gmail.com |
16604f725a712c0a76a445ec2ed1bbfafa4d791d | 791af5ecca96d9dacc70443ff6dc90126072cc30 | /screener/screener/urls.py | 8fad2c635b85e5c038abcb120a67d8c188f6fa91 | [] | no_license | morningstar899/resume-screening | 2d9f4b85d3f4ae6f44b46b418ab1a07b62c412b0 | 085825dd49fdf2cae1ac5d87cb028e759248f73c | refs/heads/master | 2020-08-02T00:00:02.541234 | 2019-07-21T04:49:26 | 2019-07-21T04:49:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 894 | py | """screener URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('resumeScreen.urls')),
path('accounts/', include('django.contrib.auth.urls')),
]
| [
"yodingrg93@gmail.com"
] | yodingrg93@gmail.com |
f394c5cbbab0818ed304742ddc70b2448f35c1dc | 3b99fec4688b1d253a395a5949f2bf77ff8c5bec | /collatz.py | 1df2e990fd0a1631e999705d4248ac3fba43a569 | [] | no_license | eddieatkinson/Python101 | 032327fb86287acd18474bcbefeb40e62d7f6884 | 8a465dd4a2699abaee88af5b2ee7a81125b0597e | refs/heads/master | 2021-01-23T11:59:22.263700 | 2019-06-24T14:57:51 | 2019-06-24T14:57:51 | 102,638,723 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 436 | py | count = 0
num = 0
highest_count = 0
highest_count_num = 0
def collatz(num, count):
count += 1
if num == 1:
return count
if num % 2 == 0:
return collatz(num / 2, count)
else:
return collatz((3 * num) + 1, count)
while num < 1000000:
num += 1
this_count = collatz(num, count)
if this_count > highest_count:
highest_count = this_count
highest_count_num = num
print(highest_count_num, highest_count)
| [
"eddiebatkinson@gmail.com"
] | eddiebatkinson@gmail.com |
e073a962aa67bd5e004148fe34f2d6843e4c91a5 | 7d9848f49b01df85d2d4ab6f594c13f1ef53db4e | /terminal_progress.py | 62045669e4dc407e3d8ba7e236086b7131d42b0a | [] | no_license | baudrly/instaGRAAL | 85d1609ff46a46465b3d48448a9f88130c0942d8 | a1adb2cfdfbe6cef78f163fd11338ba1e2e0e19e | refs/heads/master | 2020-03-27T18:13:14.733988 | 2018-08-30T13:18:36 | 2018-08-30T13:18:36 | 131,966,807 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,727 | py | #!/usr/bin/env python3
"""Terminal controller module
Example of usage:
print BG_BLUE + 'Text on blue background' + NORMAL
print BLUE + UNDERLINE + 'Blue underlined text' + NORMAL
print BLUE + BG_YELLOW + BOLD + 'text' + NORMAL
"""
import sys
# The current module
MODULE = sys.modules[__name__]
COLORS = "BLUE GREEN CYAN RED MAGENTA YELLOW WHITE BLACK".split()
# List of terminal controls, you can add more to the list.
CONTROLS = {
"BOL": "cr",
"UP": "cuu1",
"DOWN": "cud1",
"LEFT": "cub1",
"RIGHT": "cuf1",
"CLEAR_SCREEN": "clear",
"CLEAR_EOL": "el",
"CLEAR_BOL": "el1",
"CLEAR_EOS": "ed",
"BOLD": "bold",
"BLINK": "blink",
"DIM": "dim",
"REVERSE": "rev",
"UNDERLINE": "smul",
"NORMAL": "sgr0",
"HIDE_CURSOR": "cinvis",
"SHOW_CURSOR": "cnorm",
}
# List of numeric capabilities
VALUES = {
"COLUMNS": "cols", # Width of the terminal (None for unknown)
"LINES": "lines", # Height of the terminal (None for unknown)
"MAX_COLORS": "colors",
}
def default():
"""Set the default attribute values"""
for color in COLORS:
setattr(MODULE, color, "")
setattr(MODULE, "BG_%s" % color, "")
for control in CONTROLS:
setattr(MODULE, control, "")
for value in VALUES:
setattr(MODULE, value, None)
def setup():
"""Set the terminal control strings"""
# Initializing the terminal
curses.setupterm()
# Get the color escape sequence template or '' if not supported
# setab and setaf are for ANSI escape sequences
bgColorSeq = curses.tigetstr("setab") or curses.tigetstr("setb") or ""
fgColorSeq = curses.tigetstr("setaf") or curses.tigetstr("setf") or ""
for color in COLORS:
# Get the color index from curses
colorIndex = getattr(curses, "COLOR_%s" % color)
# Set the color escape sequence after filling the template with index
setattr(MODULE, color, curses.tparm(fgColorSeq, colorIndex))
# Set background escape sequence
setattr(MODULE, "BG_%s" % color, curses.tparm(bgColorSeq, colorIndex))
for control in CONTROLS:
# Set the control escape sequence
setattr(MODULE, control, curses.tigetstr(CONTROLS[control]) or "")
for value in VALUES:
# Set terminal related values
setattr(MODULE, value, curses.tigetnum(VALUES[value]))
def render(text):
"""Helper function to apply controls easily
Example:
apply("%(GREEN)s%(BOLD)stext%(NORMAL)s") -> a bold green text
"""
return text % MODULE.__dict__
try:
import curses
setup()
except Exception as e:
# There is a failure; set all attributes to default
print("Warning: %s" % e)
default()
| [
"noreply@github.com"
] | baudrly.noreply@github.com |
dccb76a36c0bd82d032375ed0b376ea2b5a6967e | f736eca3773cb232903d1e94506ef40ae5b160d7 | /voting/admin.py | a7cb09ba4c25543186ef750d9a54c0b17fb23678 | [] | no_license | gkomarov/best-photo | a16c16671f38bf7f1e38631ce22664f8a892116f | ec0f0729a05014c6d0e10ecbe79fd0926fb68adc | refs/heads/master | 2022-09-21T14:10:24.943479 | 2020-05-14T09:29:52 | 2020-05-14T09:29:52 | 263,871,399 | 0 | 0 | null | 2020-06-06T01:53:34 | 2020-05-14T09:28:15 | Python | UTF-8 | Python | false | false | 155 | py | from django.contrib import admin
from .models import Voting
class VotingPerson(admin.ModelAdmin):
list_display = 'name'
admin.site.register(Voting) | [
"gr.komarov@ya.ru"
] | gr.komarov@ya.ru |
964dde6dfe12075376a53bad62460082327840aa | 5333aeb532c2cfb7015397df2a77fcd7d5652fef | /MODEL.py | 57a8523cb9f9c1f02161ab3c58e61d21eef170ab | [] | no_license | bregord/eritas | 5bc03db32f87819b2fe3851806578f9ba26e89b2 | b66c753b1eaaa5ceeca954d8c7a904e5b3d3df46 | refs/heads/master | 2020-06-11T09:23:55.560680 | 2017-04-06T05:15:27 | 2017-04-06T05:15:27 | 75,700,570 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 946 | py | import numpy as np
from sklearn import svm
from sklearn.metrics import accuracy_score
from sklearn import linear_model, datasets
from sklearn.metrics import precision_recall_fscore_support
tot = ALL.npy
print(np.shape(tot))
tot = tot.astype(np.float)
print(np.shape(tot))
X = tot[:,1:][0:1500]
Y = tot[:,0][0:1500]
X1 = tot[:,1:][1500:]
Y1 = tot[:,0][1500:]
print(np.shape(tot))
logreg = linear_model.LogisticRegression(C=1e5)
logreg.fit(X, Y)
pred_log = logreg.predict(X1)
print(np.count_nonzero(Y))
print(Y[Y==1])
print(accuracy_score(Y1,pred_log))
clf = svm.SVC()
clf.fit(X,Y)
pred = clf.predict(X1)
print(pred_log)
print("SVM")
print(accuracy_score(Y1, pred))
print(precision_recall_fscore_support(Y1, pred,pos_label=1,average='binary'))
#print(precision_recall_fscore_support(Y1, pred,))
print("LOG_REG")
print(accuracy_score(Y1,pred_log))
print(precision_recall_fscore_support(Y1, pred_log,pos_label=1,average='binary'))
| [
"sirbrendang@gmail.com"
] | sirbrendang@gmail.com |
c9048def34f381b159956536e21de0c8dbd303fd | df3ab6693c3af447df265f4ebe2a576eec6637da | /Hello coding/selection_sort.py | 510824956a099e0817d4a9c182b2014c3bfb0912 | [
"MIT"
] | permissive | wooooooogi/Algorithm-study | 9aa509d87acd0ffe7fe1ebd19e7b28361e14d25e | bf76bb721785a52b6abf158077b554b0626ee1f7 | refs/heads/master | 2020-06-26T05:01:20.715593 | 2019-07-30T08:23:09 | 2019-07-30T08:23:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 723 | py | # Coded by Sungwook Kim
# Date: 2019-07-30
# Python version: 3.6.5
# IDE: Spyder 3
# Sort, information = [Name, Date, E-mail]
# Sample code is 2001 year's 메리츠화재 stock information. (Downloaded in KRX)
# Sort by price (When is the highest price in 2001)
import pandas as pd
import numpy as np
import os
# Use pandas library to get csv information.
Data = pd.read_csv(os.getcwd() + "/selection_sort_sample_code.csv", encoding="ms949", index_col=False)
print(Data)
Data = Data[:-1]
#print(Data)
sorting_variable = "종가"
sorted_variable = "년/월/일"
SV = Data[sorting_variable]
SV = [SV]
#SV = np.array()
#print(SV)
#for i in SV:
# for j in SV:
# if i < J:
# break
| [
"wooooooogi@gmail.com"
] | wooooooogi@gmail.com |
d035dfa6abc8726fdbae95fbf2b8705c7d1eb81e | 06b0f031ad483783dde68206392a747612964093 | /PistolShrimpStoreDB/venv/Scripts/pip3.6-script.py | 12defafe7e9d77d5438a916b7d05c80b2a85935f | [] | no_license | Bookworm100/PistolShrimpDB | a41e6389f32535b187ac1bcc13803d6a16f828ad | edc99aa7a5c853a9c38e3740ad5bf89b72c160ef | refs/heads/master | 2020-05-16T02:23:21.161896 | 2019-06-21T23:37:34 | 2019-06-21T23:37:34 | 182,627,434 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 455 | py | #!"C:\Users\vibha\Documents\Spring 2018-2019\Classes\CS 123\AirQualityStateDB\venv\Scripts\python.exe"
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==10.0.1','console_scripts','pip3.6'
__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', 'pip3.6')()
)
| [
"vvijayak@caltech.edu"
] | vvijayak@caltech.edu |
4a855a4e32f8487e6f27627af54594814e4a74b2 | e404d16cb454389b457c8b1c8bdc4a7c77690776 | /dashboard/views.py | beaf11dd2801a409cd8f2e312cb03b544d4d4d99 | [] | no_license | openarun/flower_detection | ed2ef28bfea61a842cb0c67f6ac42c5a810d81b5 | ae1a7848e6b0dd683f99668e693773f1556edc00 | refs/heads/master | 2022-01-19T00:11:40.368759 | 2019-06-25T00:00:25 | 2019-06-25T00:00:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,519 | py | from django.shortcuts import render
from django.http import HttpResponse
from django.core.files.storage import FileSystemStorage
# Create your views here.
from .classifier import label
import operator
def index(request):
return render(request, 'index.html')
def detect(request):
if request.method == 'POST' and request.FILES['myfile']:
myfile = request.FILES['myfile']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
classfied_dict = classify("media/"+filename)
detected_flower = max(classfied_dict.items(), key=operator.itemgetter(1))[0]
print(detected_flower)
return render(request, 'detect.html', {
'uploaded_file_url': uploaded_file_url,
'detected_flower': detected_flower,
})
return render(request, 'detect.html')
def classify(file_url):
classified = label.classify('retrained_graph.pb', file_url, 'retrained_labels.txt', 'final_result', 'Placeholder')
top_k, labels, results = classified
classified_dict = {}
for i in top_k:
classified_dict[labels[i]]=results[i]
return classified_dict
def sunflower(request):
return render(request, 'sunflower.html')
def rose(request):
return render(request, 'rose.html')
def daisy(request):
return render(request, 'daisy.html')
def dandelion(request):
return render(request, 'dandelion.html')
def tulip(request):
return render(request, 'tulip.html') | [
"expertaruncorp@gmail.com"
] | expertaruncorp@gmail.com |
04835fcb58cf9438f14178cf8c882964d6bcf6af | 2261f2020adf036054562fa1fcfd3920b8675aeb | /working_db.py | 53241d80029ccd77742a80b5617a25ab7d106d34 | [] | no_license | ramheinzelmann/MySQL-database-with-python | b0cd48bd6033c251b7e9bc930a0dc32a1ee917ac | 532865a96997b958fea163def9f8c60c4d9d697b | refs/heads/master | 2022-04-24T03:40:02.875005 | 2020-04-24T17:23:31 | 2020-04-24T17:23:31 | 258,353,206 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,486 | py | #!/usr/bin/python
# coding: utf8
"""
Date: 19/06/2018
Autor: Renato Machado
Abjective: Executes the SQL commands.
Alteration:
"""
import pymysql
from connect import connection_db
class Execute_Sql(object):
@staticmethod
def create_table(database, table, query_sql):
cursor = connection_db(database)
if cursor[1] == 401:
print(cursor[0])
return cursor[0]
try:
cursor[0].execute(query_sql)
print(f'Table {table} successfully created.')
except pymysql.err.InternalError:
print(f'Table {table} already exists')
return {'erro': f'Table {table} already exists'}
@staticmethod
def insert_user(database, payload):
cursor = connection_db(database)
if cursor[1] == 401:
print(cursor[0])
return cursor[0]
try:
sql = f"select * from users where username='{payload['username']}'"
user_exists = cursor[0].execute(sql)
if not user_exists:
import password
passwd = password.create_password(16)
password = password.TrataHash.insere_hash(passwd)
val = (payload['username'], payload['email'], str(password))
sql = f"insert into users (username, email, password) values {val}"
cursor[0].execute(sql)
cursor[1].commit()
cursor[1].close()
print(f"Record ID {cursor[0].lastrowid} successfully inserted. Password {passwd}", )
else:
print(f'User {payload["username"]} already exists.')
return {'msg': f'User {payload["username"]} already exists.'}
except pymysql.err.InternalError:
cursor[1].rollback()
cursor[1].close()
print('Failed to insert the record.')
return {'erro': 'Failed to insert the record.'}
@staticmethod
def select_users(database, payload):
cursor = connection_db(database)
if cursor[1] == 401:
print(cursor[0])
return cursor[0]
try:
sql = f"select * from {payload['name_table']} where username='{payload['username']}'"
cursor[0].execute(sql)
lines = cursor[0].fetchall()
cursor[0].close()
print(lines)
return lines
except pymysql.err.InternalError:
print('Data recovery failed.')
return {'erro': 'Data recovery failed.'}
@staticmethod
def delete_user(database, username):
cursor = connection_db(database)
if cursor[1] == 401:
print(cursor[0])
return cursor[0]
try:
sql = f"select * from users where username='{username}'"
user_exists = cursor[0].execute(sql)
if user_exists:
sql = f"delete from users where username='{username}'"
cursor[0].execute(sql)
cursor[1].commit()
cursor[1].close()
print(f"User {username} successfully deleted.")
else:
print(f'User {username} not found.')
return {'msg': f'User {username} not found.'}
except pymysql.err.InternalError:
cursor[1].rollback()
cursor[1].close()
print('Failed to insert the record.')
return {'erro': 'Failed to insert the record.'}
| [
"renato.machado@bb.com.br"
] | renato.machado@bb.com.br |
105db73230d910d55c510986030ef3137aa8fadc | cdb7bb6215cc2f362f2e93a040c7d8c5efe97fde | /W/WalkingRobotSimulation.py | 212531c27d7ba7fb215264e9577680ddadbc597d | [] | no_license | bssrdf/pyleet | 8861bbac06dfe0f0f06f6ad1010d99f8def19b27 | 810575368ecffa97677bdb51744d1f716140bbb1 | refs/heads/master | 2023-08-20T05:44:30.130517 | 2023-08-19T21:54:34 | 2023-08-19T21:54:34 | 91,913,009 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,967 | py | '''
-Easy-
*Greedy*
A robot on an infinite grid starts at point (0, 0) and faces north. The
robot can receive one of three possible types of commands:
-2: turn left 90 degrees,
-1: turn right 90 degrees, or
1 <= x <= 9: move forward x units
Some of the grid squares are obstacles. The ith obstacle is at grid
point obstacles[i] = (xi, yi).
If the robot would try to move onto them, the robot stays on the previous
grid square instead (but still continues following the rest of the route.)
Return the square of the maximum Euclidean distance that the robot will
be from the origin.
Example 1:
Input: commands = [4,-1,3], obstacles = []
Output: 25
Explanation: robot will go to (3, 4)
Example 2:
Input: commands = [4,-1,4,-2,4], obstacles = [[2,4]]
Output: 65
Explanation: robot will be stuck at (1, 4) before turning left and
going to (1, 8)
Constraints:
1 <= commands.length <= 10^4
commands[i] is in the list [-2,-1,1,2,3,4,5,6,7,8,9].
0 <= obstacles.length <= 10^4
-3 * 10^4 <= xi, yi <= 3 * 10^4
The answer is guaranteed to be less than 2^31.
'''
class Solution(object):
def robotSim(self, commands, obstacles):
"""
:type commands: List[int]
:type obstacles: List[List[int]]
:rtype: int
"""
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]
x = y = di = 0
obstacleSet = set(map(tuple, obstacles))
ans = 0
for c in commands:
if c == -2:
di = (di-1)%4
elif c == -1:
di = (di+1)%4
else:
for _ in range(c):
xi = x + dx[di]
yi = y + dy[di]
if (xi,yi) not in obstacleSet:
x, y = xi, yi
ans = max(ans, x*x+y*y)
else:
break
return ans
if __name__ == "__main__":
print(Solution().robotSim([4,-1,4,-2,4], [[2,4]])) | [
"merlintiger@hotmail.com"
] | merlintiger@hotmail.com |
3760acc1632b5df7a0937f222d45d8351b59a256 | 0e4dc82a94563dacb0c25d0d43fbcbe3def21f72 | /223-Rectangle-Area/solution01.py | 2095481fc76cfe49764531b43a0ff276daaeb5c8 | [
"CC-BY-3.0",
"MIT"
] | permissive | Eroica-cpp/LeetCode | 3ce3b05b3098e8097c1090e2116b813efaadd2a3 | 07276bd11558f3d0e32bec768b09e886de145f9e | refs/heads/master | 2021-06-20T05:41:30.506250 | 2017-03-16T05:17:39 | 2017-03-16T05:17:39 | 35,126,816 | 7 | 2 | null | null | null | null | UTF-8 | Python | false | false | 1,918 | py | #!/usr/bin/python
# ==============================================================================
# Author: Tao Li (taoli@ucsd.edu)
# Date: Jun 11, 2015
# Question: 223-Rectangle-Area
# Link: https://leetcode.com/problems/rectangle-area/
# ==============================================================================
# Find the total area covered by two rectilinear rectangles in a 2D plane.
#
# Each rectangle is defined by its bottom left corner and top right corner
# as shown in the figure.
#
# Assume that the total area is never beyond the maximum possible value of int.
# ==============================================================================
# Method: simple math
# Time Complexity: O(1)
# Space Complexity: O(1)
# ==============================================================================
class Solution:
# @param {integer} A
# @param {integer} B
# @param {integer} C
# @param {integer} D
# @param {integer} E
# @param {integer} F
# @param {integer} G
# @param {integer} H
# @return {integer}
def computeArea(self, A, B, C, D, E, F, G, H):
area = abs(A-C)*abs(B-D) + abs(E-G)*abs(F-H)
area -= self.interact(A,C,E,G) * self.interact(B,D,F,H)
return area
def interact(self, x1, y1, x2, y2):
if y1 < x1:
x1, y1 = y1, x1
if y2 < x2:
x2, y2 = y2, x2
if x1 < x2:
if y1 <= x2:
return 0
elif y1 > x2 and y1 <= y2:
return y1 - x2
elif y1 > y2:
return y2 - x2
if x1 >= x2 and x1 <= y2:
if y1 <= y2:
return y1 - x1
elif y1 > y2:
return y2 - x1
if x1 > y2:
return 0
if __name__ == '__main__':
A, B, C, D, E, F, G, H = -2, -2, 2, 2, -1, -1, 1, 1
print Solution().computeArea(A, B, C, D, E, F, G, H) | [
"eroicacmcs@gmail.com"
] | eroicacmcs@gmail.com |
ed3a0d5ac7ba95576efb62c2ee0f6eaa702fa3eb | f295a11c688867ea83cb7b0d22f2e80d1d0652ed | /generat.py | aae7abe844da1edf1a2ed9d953e2c660fc9efb0b | [] | no_license | yangzigy/pseudo-color-table-gen | cd9be2bed00702fdea6e6c2522d1f26710345345 | 02e694cc4343c2a0402531274e00dabf8a8c6014 | refs/heads/master | 2021-01-20T20:08:41.678228 | 2016-06-14T07:39:16 | 2016-06-14T07:39:16 | 61,102,346 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,087 | py | #!/usr/bin/python
# -*- coding:utf-8 -*-
import pylab
import inspect
import numpy
import sys
f=open("color.cpp","w")
f.write("""
#include "color.h"
map<string,vector<vector<Vec3f> > > createNamedMaps(void)
{
map<string,vector<vector<Vec3f> > > m;
""")
discrete_n = 10
for name in pylab.cm.cmap_d:
if not type(pylab.cm.cmap_d[name]) is pylab.matplotlib.colors.LinearSegmentedColormap:
continue
f.write(" {\n")
for channel in ('red','green','blue'):
f.write(" vector<Vec3f> %s;\n"%(channel[0]))
d = pylab.cm.cmap_d[name]._segmentdata[channel]
if inspect.isfunction(d):
newd = []
x = numpy.linspace(0,1,discrete_n)
y = numpy.clip(numpy.array(d(x), dtype=numpy.float), 0, 1)
for i in range(discrete_n):
newd.append((x[i], y[i], y[i]))
d = newd
for i in d:
f.write(" %s.push_back(Vec3f("%(channel[0]))
f.write(str.join(",",map(str,i)))
f.write("));\n")
f.write(" vector<vector<Vec3f> > a; a.push_back(r);a.push_back(g);a.push_back(b);\n")
f.write(" m[\"%s\"] = a;\n"%(name))
f.write(" }\n")
f.write(" return m;\n")
f.write("}\n")
f.close()
| [
"yangzigy@sina.com"
] | yangzigy@sina.com |
049d6b0aca9052f2c1ff1783f61f804f37551bc3 | 1f308be82b88260fcf447bae4bbccf26e06e5c48 | /AlgoAndDS_Python/algo/hackerrank/big_sorting.py | 1b10b850d05cb2fe10a11630e88794a90f5fdfcc | [] | no_license | sachinshikhare/AlgorithmAndDataStructure | f6eb849ab93f9f2d88b0fd355674f3be2cf20210 | b84e06bd4ef03dd746ad3e5de777af04a1777c87 | refs/heads/master | 2020-03-06T00:49:37.050750 | 2017-06-06T14:20:23 | 2017-06-06T14:20:23 | 80,536,805 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 346 | py | """
https://www.hackerrank.com/challenges/big-sorting
"""
count = int(input())
bucket = {}
for _ in range(count):
number = input().strip()
length = len(number)
if length not in bucket:
bucket[length] = []
bucket[length].append(number)
for key in sorted(bucket):
for val in sorted(bucket[key]):
print(val)
| [
"shikhare.sachin@gmail.com"
] | shikhare.sachin@gmail.com |
f84d978c5b2c39a8c74e857b04ef070de65fe5aa | 36f6ff62399bf730156b70344a4fd739cb96976d | /042-04-NumPy-Sortin Array.py | 30bd6bc4499f0ac69b2255123d65e85681124246 | [] | no_license | MyHackInfo/Python-3-on-geeksforgeeks | 9de46b041c822082a6efe7ca5025069571d20bd1 | 3d3f3a24731ba75e6491652d855f2d983bd2fe13 | refs/heads/master | 2020-03-31T05:08:56.927912 | 2018-10-07T11:45:29 | 2018-10-07T11:45:29 | 151,935,168 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,092 | py | '''
## Sorting array:
-There is a simple np.sort method for sorting NumPy arrays.
-Let’s explore it a bit.
'''
import numpy as np
a = np.array([[1, 4, 2],
[3, 4, 6],
[0, -1, 5]])
# sorted array
print ("Array elements in sorted order:\n",
np.sort(a, axis = None))
# sort array row-wise
print ("Row-wise sorted array:\n",
np.sort(a, axis = 1))
# specify sort algorithm
print ("Column wise sort by applying merge-sort:\n",
np.sort(a, axis = 0, kind = 'mergesort'))
# Example to show sorting of structured array
# set alias names for dtypes
dtypes = [('name', 'S10'), ('grad_year', int), ('cgpa', float)]
# Values to be put in array
values = [('Hrithik', 2009, 8.5), ('Ajay', 2008, 8.7),
('Pankaj', 2008, 7.9), ('Aakash', 2009, 9.0)]
# Creating array
arr = np.array(values, dtype = dtypes)
print ("\nArray sorted by names:\n",
np.sort(arr, order = 'name'))
print ("Array sorted by grauation year and then cgpa:\n",
np.sort(arr, order = ['grad_year', 'cgpa']))
| [
"myhackinfo"
] | myhackinfo |
f050b3ca3315c9fc4f855038e59943fa7c274308 | 74002cc8fde7a9ac9d84e12e2fc813b79770ad38 | /scripts/whq_generator.py | 82cbf99dc5d8418af867257620a1e22749fa5b15 | [] | no_license | runtime-technologies/mcq-quiz-generator | 28965c145e1666dddf0166b51439afbbd7760c3c | b048b42f6c7539028d0e8ba4efd8c3bc128185c4 | refs/heads/master | 2023-02-08T21:26:34.360756 | 2020-12-25T15:01:21 | 2020-12-25T15:01:21 | 319,366,621 | 0 | 0 | null | 2020-12-20T15:31:52 | 2020-12-07T15:45:29 | Python | UTF-8 | Python | false | false | 4,962 | py | from textblob import TextBlob
import nltk
from textblob import Word
import sys
class WHQ_Generator:
def __init__(self, text):
self.text = text
def parse(self, text):
"""
Parse a paragraph. Devide it into sentences and try to generate quesstions from each sentences.
"""
question_list = []
try:
txt = TextBlob(text)
# Each sentence is taken from the string input and passed to genQuestion() to generate questions.
for sentence in txt.sentences:
question_list.append(self.genQuestion(sentence))
except Exception as e:
raise e
return question_list
def genQuestion(self, line):
"""
outputs question from the given text
"""
if type(line) is str: # If the passed variable is of type string.
line = TextBlob(line) # Create object of type textblob.blob.TextBlob
bucket = {} # Create an empty dictionary
for i,j in enumerate(line.tags): # line.tags are the parts-of-speach in English
if j[1] not in bucket:
bucket[j[1]] = i # Add all tags to the dictionary or bucket variable
question = '' # Create an empty string
# These are the english part-of-speach tags used in this demo program.
#.....................................................................
# NNS Noun, plural
# JJ Adjective
# NNP Proper noun, singular
# VBG Verb, gerund or present participle
# VBN Verb, past participle
# VBZ Verb, 3rd person singular present
# VBD Verb, past tense
# IN Preposition or subordinating conjunction
# PRP Personal pronoun
# NN Noun, singular or mass
#.....................................................................
# Create a list of tag-combination
l1 = ['NNP', 'VBG', 'VBZ', 'IN']
l2 = ['NNP', 'VBG', 'VBZ']
l3 = ['PRP', 'VBG', 'VBZ', 'IN']
l4 = ['PRP', 'VBG', 'VBZ']
l5 = ['PRP', 'VBG', 'VBD']
l6 = ['NNP', 'VBG', 'VBD']
l7 = ['NN', 'VBG', 'VBZ']
l8 = ['NNP', 'VBZ', 'JJ']
l9 = ['NNP', 'VBZ', 'NN']
l10 = ['NNP', 'VBZ']
l11 = ['PRP', 'VBZ']
l12 = ['NNP', 'NN', 'IN']
l13 = ['NN', 'VBZ']
# With the use of conditional statements the dictionary is compared with the list created above
if all(key in bucket for key in l1): #'NNP', 'VBG', 'VBZ', 'IN' in sentence.
question = 'What' + ' ' + line.words[bucket['VBZ']] +' '+ line.words[bucket['NNP']]+ ' '+ line.words[bucket['VBG']] + '?'
elif all(key in bucket for key in l2): #'NNP', 'VBG', 'VBZ' in sentence.
question = 'What' + ' ' + line.words[bucket['VBZ']] +' '+ line.words[bucket['NNP']] +' '+ line.words[bucket['VBG']] + '?'
elif all(key in bucket for key in l3): #'PRP', 'VBG', 'VBZ', 'IN' in sentence.
question = 'What' + ' ' + line.words[bucket['VBZ']] +' '+ line.words[bucket['PRP']]+ ' '+ line.words[bucket['VBG']] + '?'
elif all(key in bucket for key in l4): #'PRP', 'VBG', 'VBZ' in sentence.
question = 'What ' + line.words[bucket['PRP']] +' '+ ' does ' + line.words[bucket['VBG']]+ ' '+ line.words[bucket['VBG']] + '?'
elif all(key in bucket for key in l7): #'NN', 'VBG', 'VBZ' in sentence.
question = 'What' + ' ' + line.words[bucket['VBZ']] +' '+ line.words[bucket['NN']] +' '+ line.words[bucket['VBG']] + '?'
elif all(key in bucket for key in l8): #'NNP', 'VBZ', 'JJ' in sentence.
question = 'What' + ' ' + line.words[bucket['VBZ']] + ' ' + line.words[bucket['NNP']] + '?'
elif all(key in bucket for key in l9): #'NNP', 'VBZ', 'NN' in sentence
question = 'What' + ' ' + line.words[bucket['VBZ']] + ' ' + line.words[bucket['NNP']] + '?'
elif all(key in bucket for key in l11): #'PRP', 'VBZ' in sentence.
if line.words[bucket['PRP']] in ['she','he']:
question = 'What' + ' does ' + line.words[bucket['PRP']].lower() + ' ' + line.words[bucket['VBZ']].singularize() + '?'
elif all(key in bucket for key in l10): #'NNP', 'VBZ' in sentence.
question = 'What' + ' does ' + line.words[bucket['NNP']] + ' ' + line.words[bucket['VBZ']].singularize() + '?'
elif all(key in bucket for key in l13): #'NN', 'VBZ' in sentence.
question = 'What' + ' ' + line.words[bucket['VBZ']] + ' ' + line.words[bucket['NN']] + '?'
# When the tags are generated 's is split to ' and s. To overcome this issue.
if 'VBZ' in bucket and line.words[bucket['VBZ']] == "’":
question = question.replace(" ’ ","'s ")
return(question) | [
"pllvsisodiya@gmail.com"
] | pllvsisodiya@gmail.com |
439862eddb5f3df10d1bcb50ab85b4f58108fee1 | 44829de8d0f8a88295d1c7227d0fad32201ad492 | /automata/__init__.py | 5e30749189deab6a230739471778ca91b2f242f4 | [] | no_license | hydraseq/automata | 1e27713bd643b34edc253f56d7228cd125a2d7c1 | e3d0e93f735638fa9a346f38eb891444a48c6e82 | refs/heads/master | 2020-09-07T02:09:20.599903 | 2019-11-10T00:33:53 | 2019-11-10T00:33:53 | 220,625,721 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 154 | py | name = "hydraseq"
__version__ = '0.0.27'
from hydraseq.hydraseq import Node
from hydraseq.hydraseq import Hydraseq
from hydraseq.automata import DFAstate
| [
"efrain.olivares@gmail.com"
] | efrain.olivares@gmail.com |
617ae779826ed3c052a896b6398442ef68c1c1d1 | 5e929b91e11d5de1bf87c548e95b49ccb88dbb85 | /line-detection.py | 6db1715f87b57c4532d74324d2cad774e2849e5c | [] | no_license | kiranmanicka/object-detection | c8b3e297cd92c37eb0405ccfe7c7bd848cce4cc9 | 932f844cd5063be27c13c751206421edabec182e | refs/heads/master | 2023-07-28T15:34:59.853948 | 2021-08-26T19:30:58 | 2021-08-26T19:30:58 | 274,205,370 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 443 | py | import cv2
import numpy as np
img = cv2.imread('NlLrx.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,150,apertureSize = 3)
minLineLength = 10
maxLineGap = 1
lines = cv2.HoughLinesP(edges,1,np.pi/180,100, minLineLength,maxLineGap)
print(lines)
for line in lines:
x1,y1,x2,y2=line[0]
cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)
cv2.imshow('img',img)
cv2.imshow("edges",edges)
cv2.waitKey(0)
cv2.destroyAllWindows() | [
"noreply@github.com"
] | kiranmanicka.noreply@github.com |
119cc346aca6f640b97296ba89abfd6d2b53a316 | bc9f66258575dd5c8f36f5ad3d9dfdcb3670897d | /lib/surface/functions/__init__.py | cf43cc459bde27a212cfebd25ccb5d8b5cfc2675 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | google-cloud-sdk-unofficial/google-cloud-sdk | 05fbb473d629195f25887fc5bfaa712f2cbc0a24 | 392abf004b16203030e6efd2f0af24db7c8d669e | refs/heads/master | 2023-08-31T05:40:41.317697 | 2023-08-23T18:23:16 | 2023-08-23T18:23:16 | 335,182,594 | 9 | 2 | NOASSERTION | 2022-10-29T20:49:13 | 2021-02-02T05:47:30 | Python | UTF-8 | Python | false | false | 1,503 | py | # -*- coding: utf-8 -*- #
# Copyright 2015 Google LLC. 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.
"""The main command group for Google Cloud Functions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import argparse
from googlecloudsdk.api_lib.functions import transforms
from googlecloudsdk.calliope import actions
from googlecloudsdk.calliope import base
from googlecloudsdk.core import properties
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
class Functions(base.Group):
"""Manage Google Cloud Functions."""
category = base.COMPUTE_CATEGORY
@staticmethod
def Args(parser):
parser.display_info.AddTransforms(transforms.GetTransforms())
def Filter(self, context, args):
# TODO(b/190534642): Determine if command group works with project number
base.RequireProjectID(args)
del context, args
base.DisableUserProjectQuota()
| [
"cloudsdk.mirror@gmail.com"
] | cloudsdk.mirror@gmail.com |
69da4f5a911f83423caf6d2ba93e5f462c644040 | 3df96d29f6ea980cfa2627f26233166cbf5b6c2a | /Bin/PASPipeline.py | 604cf0c951aa2dd51a57f19a3b2dea107a11b2f7 | [] | no_license | 452990729/PAS-seq | 17710c80d35451f1c9eedea1b6e169d2dc9d9410 | ef252370e87bf51532dc39802afef0af38e5fd2a | refs/heads/master | 2020-05-31T05:40:02.476934 | 2019-06-04T03:12:59 | 2019-06-04T03:12:59 | 190,109,969 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,064 | py | #!/usr/bin/env python2
import sys
import re
import os
import argparse
import ConfigParser
BasePath = os.path.split(os.path.realpath(__file__))[0]
config = ConfigParser.ConfigParser()
config.read(BasePath+'/../Bin/config.ini')
#### SOFT
FASTP = config.get('SOFTWARE', 'fastp')
BOWTIE2 = config.get('SOFTWARE', 'bowtie2')
SAMTOOLS = config.get('SOFTWARE', 'samtools')
BEDTOOLS = config.get('SOFTWARE', 'bedtools')
PYTHON = config.get('SOFTWARE', 'python')
### SCRIPT
FilterPositions = config.get('SCRIPT', 'FilterPosition')
MergeDepths = config.get('SCRIPT', 'MergeDepth')
#### DATABASE
HG19 = config.get('DATABASE', 'hg19')
class ReadList(object):
def __init__(self, line_in):
list_split = re.split('\s+', line_in)
self.Sample = list_split[0]
self.Group = list_split[1]
self.Name = '_'.join(list_split[:2])
list_fq = re.split(',', list_split[2])
self.fq1 = list_fq[0]
self.fq2 = list_fq[1]
class Snake(object):
def __init__(self, process):
self.process = process
self.input = ''
self.output = ''
self.params = ''
self.log = ''
self.threads = ''
self.shell = ''
def UpdateInput(self, line_in):
self.input = line_in
def UpdateOutput(self, line_in):
self.output = line_in
def UpdateParams(self, line_in):
self.params = line_in
def UpdateLog(self, line_in):
self.log = line_in
def UpdateThreads(self, line_in):
self.threads = line_in
def UpdateShell(self, line_in):
self.shell = line_in
def WriteStr(self, fn):
fn.write('rule '+self.process+':\n')
fn.write('\tinput:\n\t\t'+self.input+'\n')
if self.output:
fn.write('\toutput:\n\t\t'+self.output+'\n')
if self.params:
fn.write('\tparams:\n\t\t'+self.params+'\n')
if self.log:
fn.write('\tlog:\n\t\t'+self.log+'\n')
if self.threads:
fn.write('\tthreads: '+self.threads+'\n')
if self.shell:
fn.write('\tshell:\n\t\t'+self.shell+'\n')
fn.write('\n')
def main():
parser = argparse.ArgumentParser(description="PAS pipeline")
parser.add_argument('-c', help='the input fasta list', required=True)
parser.add_argument('-o', help='the output path', required=True)
parser.add_argument('-a1', help='the read1 adapter', default='AGATCGGAAGAGCACACGTCTGAACTCCAGTCA')
parser.add_argument('-a2', help='the read2 adapter', default='AGATCGGAAGAGCGTCGTGTAGGGAAAGAGTGT')
argv=vars(parser.parse_args())
outpath = argv['o']
snakefile = open(os.path.join(outpath, 'snakefile.txt'), 'w')
RawData = os.path.join(outpath, 'RawData')
list_ob = []
if not os.path.exists(RawData):
os.mkdir(RawData)
else:
os.system('rm -rf '+RawData)
os.mkdir(RawData)
with open(argv['c'], 'r') as f:
os.chdir(RawData)
for line in f:
if not line.startswith('#'):
ob = ReadList(line.strip())
list_ob.append(ob)
if ob.fq1.endswith('.gz'):
lb = '.fq.gz'
else:
lb = '.fastq'
os.system('ln -s {} {}'.format(ob.fq1, ob.Name+'_1'+lb))
os.system('ln -s {} {}'.format(ob.fq2, ob.Name+'_2'+lb))
os.chdir(outpath)
### config file
snakefile.write('Samples = "{}".split()\n'.format(' '.join([i.Name for i in\
list_ob])))
snakefile.write('adapter1 = "{}"\nadapter2 = "{}"\n'.format(argv['a1'], argv['a2']))
snakefile.write('HG19 = "{}"\n'.format(HG19+'/hg19.fa'))
snakefile.write('HG19Bed = "{}"\n'.format(HG19+'/hg19.genome'))
###all
All = Snake('All')
All.UpdateInput('expand(dir("4.Coverage/{sample}"), sample=Samples)')
All.WriteStr(snakefile)
###QC
QC = Snake('QC')
QC.UpdateInput('"RawData/{sample}_1.fq.gz"')
QC.UpdateOutput('"1.QC/{sample}_1.clean.fq.gz"')
QC.UpdateLog('e = "logs/{sample}.qc.e", o = "logs/{sample}.qc.o"')
QC.UpdateShell(r'"'+FASTP+r' -i RawData/{wildcards.sample}_1.fq.gz -o 1.QC/{wildcards.sample}_1.clean.fq.gz -I RawData/{wildcards.sample}_2.fq.gz -O 1.QC/{wildcards.sample}_2.clean.fq.gz --adapter_sequence {adapter1} --adapter_sequence_r2 {adapter2} -j 1.QC/{wildcards.sample}_QC_report.json -h 1.QC/{wildcards.sample}_QC_report.html"')
QC.WriteStr(snakefile)
### Align
Align = Snake('Align')
Align.UpdateInput('"1.QC/{sample}_1.clean.fq.gz"')
Align.UpdateOutput('"2.Align/{sample}.bam"')
Align.UpdateThreads('5')
Align.UpdateLog('e = "logs/{sample}.align.e", o = "logs/{sample}.align.o"')
Align.UpdateShell(r'"'+BOWTIE2+r' --sensitive-local -p 5 -x {HG19} -1 1.QC/{wildcards.sample}_1.clean.fq.gz -2 1.QC/{wildcards.sample}_2.clean.fq.gz |'+SAMTOOLS+r' view -Sb -@ 4 -T {HG19} -o {output}"')
Align.WriteStr(snakefile)
### bamtobed
Bamtobed = Snake('Bamtobed')
Bamtobed.UpdateInput('"2.Align/{sample}.bam"')
Bamtobed.UpdateOutput('"3.Bed/{sample}.bed"')
Bamtobed.UpdateLog('e = "logs/{sample}.bamtobed.e", o = "logs/{sample}.bamtobed.o"')
Bamtobed.UpdateShell(r'"'+BEDTOOLS+r' bamtobed -i 2.Align/{wildcards.sample}.bam -cigar > {output}"')
Bamtobed.WriteStr(snakefile)
### FilterPosition
FilterPosition = Snake('FilterPosition')
FilterPosition.UpdateInput('"3.Bed/{sample}.bed"')
FilterPosition.UpdateOutput('"3.Bed/{sample}.bed.filter"')
FilterPosition.UpdateLog('e = "logs/{sample}.bedfilter.e", o = "logs/{sample}.bedfilter.o"')
FilterPosition.UpdateShell(r'"'+PYTHON+r' '+FilterPositions+r' 3.Bed/{wildcards.sample}.bed 2 > {output}"')
FilterPosition.WriteStr(snakefile)
### Sort
Sort = Snake('Sort')
Sort.UpdateInput('"3.Bed/{sample}.bed.filter"')
Sort.UpdateOutput('"3.Bed/{sample}.bed.filter.sort"')
Sort.UpdateLog('e = "logs/{sample}.sort.e", o = "logs/{sample}.sort.o"')
Sort.UpdateShell(r'"'+BEDTOOLS+r' sort -i 3.Bed/{wildcards.sample}.bed.filter > {output}"')
Sort.WriteStr(snakefile)
### Genomecov
Genomecov = Snake('Genomecov')
Genomecov.UpdateInput('"3.Bed/{sample}.bed.filter.sort"')
Genomecov.UpdateOutput('"4.Coverage/{sample}.depth"')
Genomecov.UpdateLog('e = "logs/{sample}.depth.e", o = "logs/{sample}.depth.o"')
Genomecov.UpdateShell(r'"'+BEDTOOLS+r' genomecov -bg -i 3.Bed/{wildcards.sample}.bed.filter.sort -g {HG19Bed} > {output}"')
Genomecov.WriteStr(snakefile)
### MergeDepth
MergeDepth = Snake('MergeDepth')
MergeDepth.UpdateInput('expand("4.Coverage/{sample}.depth", sample=Samples)')
MergeDepth.UpdateOutput('expand(dir("4.Coverage/{sample}/"), sample=Samples)')
# MergeDepth.UpdateLog('e = "logs/{sample}.merge.e", o = "logs/{sample}.merge.o"')
MergeDepth.UpdateShell(r'"'+PYTHON+' '+MergeDepths+r' 4.Coverage/{wildcards.sample}.depth {output} 24"')
MergeDepth.WriteStr(snakefile)
if __name__ == '__main__':
main()
| [
"452990729@qq.com"
] | 452990729@qq.com |
86b8d07d7fb4dd65f02637729dd22d0128005269 | 7c0ac2ec69f6bcf0ff366af3be22e71dc7dbbf75 | /app.py | 64d5a994ebaae3687d9a8a3b4c9206bb1aff100a | [] | no_license | quaqua/flink_demo | 9553202c4994595248649ba26f59d8e9d6a34476 | 5c782c30c80e89506bc218406ccb330407a18451 | refs/heads/master | 2016-09-06T07:27:56.305614 | 2015-05-13T15:37:06 | 2015-05-13T15:37:06 | 35,556,497 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 904 | py | from flask import Flask, request, send_from_directory
from flask.ext.restful import reqparse, abort, Api, Resource, fields,\
marshal_with
from flask_restful_swagger import swagger
from results_api import NodeList
from results_api import NodeItem
app = Flask(__name__)
###################################
# This is important:
api = swagger.docs(Api(app), apiVersion='0.1',
basePath='http://localhost:5000',
resourcePath='/',
produces=["application/json", "text/html"],
api_spec_url='/api/spec',
description='A Basic API')
###################################
api.add_resource(NodeList, '/api/nodes')
api.add_resource(NodeItem, '/api/nodes/<result_id>')
@app.route('/')
def index(name=None):
return send_from_directory('templates', 'index.html')
if __name__ == '__main__':
app.run(debug=True)
| [
"thorsten.zerha@tastenwerk.com"
] | thorsten.zerha@tastenwerk.com |
7ef30f75cc5116b9b1b0ba89fa54d9677458d590 | e1d07b0fa2ca0d13d485436ff0286797302617de | /update_vector_file.py | 3e1de4097c21240cde0a2efaf9a7d374d11e72de | [] | no_license | a-davi5/operating | 60d0902ae0787bc407ca527f7581473d49193ec6 | 4c87de4d0f6c331cf68e0b5aec116b75eca4d272 | refs/heads/master | 2020-03-24T04:42:31.880082 | 2018-08-23T15:33:39 | 2018-08-23T15:33:39 | 142,462,367 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,277 | py | #!/usr/bin/python
#script to find the -ve clock references in init section of the supplied vector file for DAQclk and DAQdata
#Adam Davis, STFC, 27/04/2018
#imports required
import sys
import numpy as np
import pickle, pprint
import time
import h5py
# extract command line parmeters. Usually use for ADC calibration so will use this as defualt
if len(sys.argv) == 1:
print "use: analyse_vector_file.p <filename>"
exit(0)
elif len(sys.argv) == 2:
vector_file_name = sys.argv[1]
else:
print "use: analyse_vector_file.p <filename>"
exit(0)
#extract lines into array
with open(vector_file_name, 'r') as f:
data = f.readlines()
f.close()
length=len(data)
#extract the data from tmp3.pkl (new settings)
pkl_file = open('tmp3.pkl', 'rb')
new_data = pickle.load(pkl_file)
#close file
pkl_file.close()
#open a newfle with the orifional name appended with _mod.txt
f=open("%s_mod.txt" %vector_file_name, 'w')
#write the first three lines, don't change!!
f.write(data[0]) #
f.write(data[1])
f.write(data[2])
k=len(new_data) # assign k to the length of the new data array
j=0 # number used to increment through the new_data array
m=0 # number that increments by o after changing the lines
n=5 # change number of lines before -ve clock edge
p=3 # number of lines to change from to new value after the -ve clock edge
o=n+1+p # total number of lines to change from 'n' to new value, default is 1 extra + p
for i in range((length-3)-(k*(o-1))):
if (j < k) : # if array increment value of new data is less than k (length of new data) do this, else just write the line to file
if((i+m+n) == new_data[j][0]): # looking forward by n, if the line number is equal to the first elemnt of array do this, else just write data to the file
for l in range(o): # do this for the next 'o' number of lines
line = data[(i+m+l+3)] # extract line from origional file
f.write(line[0:43]) # write up to the reference point
f.write(new_data[j][1]) # add new data from the file
f.write(line[44:]) # add the rest of the origional line
j=j+1
m=m+(o-1)
else:
f.write(data[i+m+3])
else:
f.write(data[i+m+3])
f.close()
print("\nNew file has been created, check folder")
| [
"adam.davis@stfc.ac.uk"
] | adam.davis@stfc.ac.uk |
9c463f58016e2d0eda6c9b7ef0e7a941fd09fca7 | f555d47b7eb095b288f7253dc5a8c658ee9b6a4a | /restaurants/models.py | 5d066d57cf73df4fbe97801ef7e6a011c02051ff | [] | no_license | codeitloadit/letseat | a8f451cd34738ff3645cc2b4d6ccde896efc354a | 41daa80bb45ecaac770bda36e45484b9587a922b | refs/heads/master | 2016-09-06T00:13:36.331466 | 2015-05-15T05:52:57 | 2015-05-15T05:52:57 | 35,530,939 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 622 | py | from django.contrib.auth.models import User
from django.db import models
class Restaurant(models.Model):
created_by = models.ForeignKey(User, related_name='restaurant_created_by')
created_at = models.DateTimeField(auto_now_add=True)
modified_by = models.ForeignKey(User, related_name='restaurant_modified_by')
modified_at = models.DateTimeField(auto_now=True)
name = models.CharField(max_length=32, unique=True)
phone_number = models.CharField(max_length=16)
address = models.TextField()
menus = models.URLField()
logo = models.URLField()
class Meta:
ordering = ['name']
| [
"brian@codeitload.it"
] | brian@codeitload.it |
6139c3223381b146251d65715200dbe1fd1c71b6 | ef18634f64fc520b7dd3e467c54cd9949b2af68f | /project 1/my_answers.py | 2592dfd9b32b7d7bb284e98191994155dec2eedb | [] | no_license | abhilashpandurangan/Udacity_DeepLearning | 532d026280400d324a42030f77c09ed9a4bd4b9e | f187c6ba0b37d8ca99e95f1131483acf3c31a8f8 | refs/heads/master | 2021-05-25T22:23:02.837204 | 2020-04-08T04:34:19 | 2020-04-08T04:34:19 | 253,945,327 | 0 | 0 | null | 2020-04-08T00:49:34 | 2020-04-08T00:34:47 | Jupyter Notebook | UTF-8 | Python | false | false | 6,477 | py | import numpy as np
class NeuralNetwork(object):
def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate):
# Set number of nodes in input, hidden and output layers.
self.input_nodes = input_nodes
self.hidden_nodes = hidden_nodes
self.output_nodes = output_nodes
# Initialize weights
self.weights_input_to_hidden = np.random.normal(0.0, self.input_nodes**-0.5,
(self.input_nodes, self.hidden_nodes))
self.weights_hidden_to_output = np.random.normal(0.0, self.hidden_nodes**-0.5,
(self.hidden_nodes, self.output_nodes))
self.lr = learning_rate
#### TODO: Set self.activation_function to your implemented sigmoid function ####
#
# Note: in Python, you can define a function with a lambda expression,
# as shown below.
self.activation_function = lambda x : (1 / (1 + np.exp(-x)))
# Replace 0 with your sigmoid calculation.
### If the lambda code above is not something you're familiar with,
# You can uncomment out the following three lines and put your
# implementation there instead.
#
#def sigmoid(x):
# return 0 # Replace 0 with your sigmoid calculation here
#self.activation_function = sigmoid
def train(self, features, targets):
''' Train the network on batch of features and targets.
Arguments
---------
features: 2D array, each row is one data record, each column is a feature
targets: 1D array of target values
'''
n_records = features.shape[0]
delta_weights_i_h = np.zeros(self.weights_input_to_hidden.shape)
delta_weights_h_o = np.zeros(self.weights_hidden_to_output.shape)
for X, y in zip(features, targets):
final_outputs, hidden_outputs = self.forward_pass_train(X)
# Implement the forward pass function below
# Implement the backproagation function below
delta_weights_i_h, delta_weights_h_o = self.backpropagation(final_outputs, hidden_outputs, X, y,
delta_weights_i_h, delta_weights_h_o)
self.update_weights(delta_weights_i_h, delta_weights_h_o, n_records)
def forward_pass_train(self, X):
''' Implement forward pass here
Arguments
---------
X: features batch
'''
#### Implement the forward pass here ####
### Forward pass ###
# TODO: Hidden layer - Replace these values with your calculations.
hidden_inputs = np.dot(X, self.weights_input_to_hidden) # signals into hidden layer
hidden_outputs = self.activation_function(hidden_inputs) # signals from hidden layer
# TODO: Output layer - Replace these values with your calculations.
final_inputs = np.dot(hidden_outputs,self.weights_hidden_to_output) # signals into final output layer
final_outputs = final_inputs # signals from final output layer
return final_outputs, hidden_outputs
def backpropagation(self, final_outputs, hidden_outputs, X, y, delta_weights_i_h, delta_weights_h_o):
''' Implement backpropagation
Arguments
---------
final_outputs: output from forward pass
y: target (i.e. label) batch
delta_weights_i_h: change in weights from input to hidden layers
delta_weights_h_o: change in weights from hidden to output layers
'''
#### Implement the backward pass here ####
### Backward pass ###
# TODO: Output error - Replace this value with your calculations.
error = y - final_outputs
# Output layer error is the difference between desired target and actual output.
output_error_term = error
# TODO: Calculate the hidden layer's contribution to the error
hidden_error = np.dot(self.weights_hidden_to_output, output_error_term)
# TODO: Backpropagated error terms - Replace these values with your calculations.
hidden_error_term = hidden_error * hidden_outputs * (1 - hidden_outputs)
# Weight step (input to hidden)
delta_weights_i_h += hidden_error_term * X[:, None]
# Weight step (hidden to output)
delta_weights_h_o += output_error_term * hidden_outputs[:, None]
return delta_weights_i_h, delta_weights_h_o
def update_weights(self, delta_weights_i_h, delta_weights_h_o, n_records):
''' Update weights on gradient descent step
Arguments
---------
delta_weights_i_h: change in weights from input to hidden layers
delta_weights_h_o: change in weights from hidden to output layers
n_records: number of records
'''
self.weights_hidden_to_output += self.lr * delta_weights_h_o / n_records
# update hidden-to-output weights with gradient descent step
self.weights_input_to_hidden += self.lr * delta_weights_i_h / n_records
# update input-to-hidden weights with gradient descent step
def run(self, features):
''' Run a forward pass through the network with input features
Arguments
---------
features: 1D array of feature values
'''
#### Implement the forward pass here ####
# TODO: Hidden layer - replace these values with the appropriate calculations.
hidden_inputs = np.dot(features, self.weights_input_to_hidden) # signals into hidden layer
hidden_outputs = self.activation_function(hidden_inputs) # signals from hidden layer
# TODO: Output layer - Replace these values with the appropriate calculations.
final_inputs = np.dot(hidden_outputs,self.weights_hidden_to_output) # signals into final output layer
final_outputs = final_inputs # signals from final output layer
return final_outputs
#########################################################
# Set your hyperparameters here
##########################################################
iterations = 2500
learning_rate = 0.7
hidden_nodes = 15
output_nodes = 1
| [
"noreply@github.com"
] | abhilashpandurangan.noreply@github.com |
abe97c2100965cac08f1c905a9927addc1bcdc1e | 000dfbda8109a1f3d208a7f30f4f8a22e03709c9 | /oehealth_extension/oeha_calllog/models/oeha_medical_calllog.py | 53fc75ffe2ca72ecaaccd5b2ef5ad1d9f0b325a1 | [] | no_license | donvikky/clinic_upgrade_11 | a117578d99980e3becc387980c7e3c4e0cbb7370 | 8e522aae26a1efa2f9a0d64b6886ca1cd8ac1302 | refs/heads/master | 2020-05-09T10:02:47.745587 | 2019-04-12T16:01:23 | 2019-04-12T16:01:23 | 181,026,835 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 705 | py | # extension to oehealth
from odoo import api, fields, models, _
import time
import datetime
class CallLog(models.Model):
_name = 'oeha.medical.calllog'
_description = 'Call Logs'
name = fields.Many2one('oeh.medical.patient', string='Patient', required=True, help="Patient Name")
patient_id = fields.Char(string="Patient ID",related="name.identification_code",readonly=True)
person_in_charge = fields.Many2one('res.users','Completed By', default=lambda self: self.env.user)
call_type = fields.Selection( [('phone', 'Phone'), ('email', 'Email'),('sms','SMS'),('other','Other')],'Call Type')
date = fields.Datetime(string="Date / Time")
log = fields.Text(string="Call Log") | [
"vokrobodo@gmail.com"
] | vokrobodo@gmail.com |
8e1c90c80d19452ac4816f63247d1c45d3e3c438 | 6c91c7e945979ca37e7091c7b3ad27e7bab26c9c | /clinic/clinic/apps/schedule/urls.py | 8060d6048c1938ddffb512a5df6cd0d77215a65a | [] | no_license | stpnk/clinic | 8c5c25b4a952bb1f0eb376e86e4a7477bff1bfbd | f4415fa792e80e62c03fdb8e89673c30c3b20bb5 | refs/heads/master | 2021-01-21T12:39:49.812527 | 2015-04-25T21:18:05 | 2015-04-25T21:18:05 | 34,586,954 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 447 | py | from django.conf.urls import include, url
urlpatterns = [
url(r'^$', 'clinic.apps.schedule.views.index', name="index"),
url(r'^appointment-success/',
'clinic.apps.schedule.views.appointment_success',
name="appointment_success"
),
url(r'^get-schedule/(?P<doctor>\d+)/(?P<date>\d{1,2}-\d{1,2}-\d{4})/$',
'clinic.apps.schedule.views.get_schedule',
name="get_schedule"
),
]
| [
"aastapp@gmail.com"
] | aastapp@gmail.com |
b49d90a995fb53ab925e1f49c4f9e5eaf968a864 | 83de24182a7af33c43ee340b57755e73275149ae | /aliyun-python-sdk-kms/aliyunsdkkms/request/v20160120/PutSecretValueRequest.py | cc2f08d8f6b48376b9d2a1d2afc6a42b9ddf008e | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-python-sdk | 4436ca6c57190ceadbc80f0b1c35b1ab13c00c7f | 83fd547946fd6772cf26f338d9653f4316c81d3c | refs/heads/master | 2023-08-04T12:32:57.028821 | 2023-08-04T06:00:29 | 2023-08-04T06:00:29 | 39,558,861 | 1,080 | 721 | NOASSERTION | 2023-09-14T08:51:06 | 2015-07-23T09:39:45 | Python | UTF-8 | Python | false | false | 2,296 | py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from aliyunsdkcore.request import RpcRequest
from aliyunsdkkms.endpoint import endpoint_data
class PutSecretValueRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'Kms', '2016-01-20', 'PutSecretValue','kms')
self.set_protocol_type('https')
self.set_method('POST')
if hasattr(self, "endpoint_map"):
setattr(self, "endpoint_map", endpoint_data.getEndpointMap())
if hasattr(self, "endpoint_regional"):
setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional())
def get_VersionId(self): # String
return self.get_query_params().get('VersionId')
def set_VersionId(self, VersionId): # String
self.add_query_param('VersionId', VersionId)
def get_VersionStages(self): # String
return self.get_query_params().get('VersionStages')
def set_VersionStages(self, VersionStages): # String
self.add_query_param('VersionStages', VersionStages)
def get_SecretData(self): # String
return self.get_query_params().get('SecretData')
def set_SecretData(self, SecretData): # String
self.add_query_param('SecretData', SecretData)
def get_SecretName(self): # String
return self.get_query_params().get('SecretName')
def set_SecretName(self, SecretName): # String
self.add_query_param('SecretName', SecretName)
def get_SecretDataType(self): # String
return self.get_query_params().get('SecretDataType')
def set_SecretDataType(self, SecretDataType): # String
self.add_query_param('SecretDataType', SecretDataType)
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
cebaad06774ef9a218dad8d97d1dfaec18a8893f | 64bf7d3dac9795a7384c1d68005e7efbee17b4a2 | /jira_cloud_backup/jira_cloud_backup.py | d938e88480b6d6ea592ed7ba1cf1a5f682eb6a55 | [] | no_license | techact/bigboo_labs | fbefcb0448d9cf7653a72296d414424559a331f1 | 74f3e9709bbbc6fc4047238f28494da3f92eb287 | refs/heads/master | 2021-08-24T02:12:35.194785 | 2017-12-07T15:58:34 | 2017-12-07T15:58:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,160 | py | import json
import time
import requests
from requests.auth import HTTPBasicAuth
def download_file(url, auth):
local_filename = url.split('/')[-1]
# NOTE the stream=True parameter
r = requests.get(url, stream=True, auth=auth)
with open(local_filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
return local_filename
JIRA_HOST = "company.atlassian.net"
URL_backup = "https://%(jira_host)s/rest/backup/1/export/runbackup" % {'jira_host': JIRA_HOST}
URL_download = "https://%(jira_host)s/plugins/servlet/export/download" % {'jira_host': JIRA_HOST}
auth = HTTPBasicAuth("_user", "_pass")
payload = {"cbAttachments": "true", "exportToCloud": "false"}
headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
backup_status = {}
backup_run = requests.post(URL_backup, data=json.dumps(payload), headers=headers, auth=auth)
if backup_run.status_code != 200:
print(backup_run, backup_run.text)
else:
print('Backup process successfully started')
task_id = json.loads(backup_run.text)['taskId']
URL_progress = "https://%(jira_host)s/rest/internal/2/task/progress/%(task_id)s" % {'jira_host': JIRA_HOST,
'task_id': task_id}
time.sleep(10)
backup_status = {}
while "result" not in backup_status.keys():
backup_status = json.loads(requests.get(URL_progress, auth=auth).text)
print("Current status: {} {}; {}".format(backup_status['status'],
backup_status['progress'],
backup_status['description']
)
)
time.sleep(300)
print("Downloading backup file")
result = json.loads(backup_status['result'])
download_file(URL_download + "/%(mediaFileId)s/%(fileName)s" % {'mediaFileId': result['mediaFileId'],
'fileName': result['fileName']},
auth)
| [
"ilagutin@tickeron.com"
] | ilagutin@tickeron.com |
b7ca2b428b6d592d3b500876f37f9ce45eada6c7 | 4dc5dc475e64d65119f02694ecc3a09a01a20296 | /getsessionsJson.py | 40c70300d2cf2db99f08c0af0a2a0df207a5c8f7 | [
"MIT"
] | permissive | selkieupsilon/euroismar-indicoscripts | 3ed16d9f53b3ab74e1d13f584ac109af57e04303 | 80c956b7a627d42f88542892f549c3f266f0e2b6 | refs/heads/master | 2020-06-10T20:10:27.079505 | 2019-06-28T16:08:45 | 2019-06-28T16:08:45 | 193,732,858 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,485 | py | # Script to obtain JSON of sessions for the typesetters to put into the program pages
import json
import hashlib
import hmac
import urllib
import time
import requests
from ConfigParser import SafeConfigParser as ConfigParser
from datetime import datetime as dt
import argparse
from collections import OrderedDict
def jsonGet(jsonFile):
try:
with open (jsonFile,"r") as read_file:
jsonData = json.load(read_file)
return jsonData
except:
signedUrl = signedSessionsUrl()
print signedUrl
print ("requesting JSON")
response = requests.get(signedUrl)
rawdata = json.loads(response.text)
print ("tidy up JSON")
sessionsdata = rawdata.get('results')[0].get('sessions')
outputJsonFile(sessionsdata, filename=jsonFile, timestamp=False)
return sessionsdata
def build_indico_request(path, params, api_key=None, secret_key=None, only_public=False, persistent=False):
items = params.items() if hasattr(params, 'items') else list(params)
if api_key:
items.append(('apikey', api_key))
if only_public:
items.append(('onlypublic', 'yes'))
if secret_key:
if not persistent:
items.append(('timestamp', str(int(time.time()))))
items = sorted(items, key=lambda x: x[0].lower())
url = '%s?%s' % (path, urllib.urlencode(items))
signature = hmac.new(secret_key, url, hashlib.sha1).hexdigest()
items.append(('signature', signature))
if not items:
return path
return '%s?%s' % (path, urllib.urlencode(items))
def signedSessionsUrl():
config = ConfigParser()
config.read('config.ini')
API_KEY = config.get('default','API_KEY')
SECRET_KEY = config.get('default','SECRET_KEY')
PATH = config.get('default','PATH')
PREFIX = config.get('default','PREFIX')
PARAMS = {
'pretty': 'yes',
'detail': 'sessions'
}
return PREFIX+build_indico_request(PATH, PARAMS, API_KEY, SECRET_KEY)
def outputJsonFile(data,fileprefix=None, filesuffix="all", timestamp=True, filename=None):
if not filename:
if not fileprefix:
fileprefix = "sessions-"
filename = fileprefix + filesuffix
if timestamp:
now = dt.now()
timestamp = now.strftime("%Y%m%d-%H%M")
filename = filename + "_" + timestamp
filename += ".json"
print ("writing "+filename)
with open (filename,"w") as write_file:
json.dump(data, write_file)
def sortByStartTime(talks): # works also for sessions
for talk in talks:
try:
starttimeDict = talk.get("startDate")
starttimeStr = starttimeDict["date"] + " " + starttimeDict["time"]
except:
print ("Warning: unscheduled talk in exported JSON list.")
return
#print (starttimeStr)
talks.sort(key=lambda t: dt.strptime(t['startDate']['date']+' '+t['startDate']['time'],"%Y-%m-%d %H:%M:%S"))
return talks
# def checkRoomStartTime(paralleltalks):
# for talk in paralleltalks:
# try:
# room = talk.get("room")
# starttimeDict = talk.get("startDate")
# starttimeStr = starttimeDict["date"] + " " + starttimeDict["time"]
# except:
# print ("Warning: something wrong.")
# return
# print (room, starttimeStr)
def sortByRoomTime(paralleltalks): # works also for sessions
for talk in paralleltalks:
try:
room = talk.get("room")
except:
print ("Warning: talk without assigned room in exported JSON list.")
return
#print (room)
sortRoomOrder = {
"Max Kade Auditorium": 0,
"Lecture Hall A": 1,
"Lecture Hall B": 2,
"Lecture Hall C": 3,
"Lecture Hall D": 4,
"": 5
}
paralleltalks.sort(key=lambda t: sortRoomOrder[str(t['room'])])
paralleltalks = sortByStartTime(paralleltalks)
return paralleltalks
# def TTtextoutput(x):
# textList = []
# textList.append(x["startDate"]["date"]+" "+x["startDate"]["time"]+" - "+x["endDate"]["time"])
# textList.append(x["room"])
# textList.append(x["session"])
# try:
# textList.append(x["speakers"][0]["first_name"]+" "+x["speakers"][0]["last_name"])
# except:
# textList.append("no speaker")
# pass
# textList.append(x["title"])
# return textList
def parseDateTime(item, timepoint):
# item - structured JSON data containing startDate, endDate
# timepoint - str, for Indico JSON export: starDate or endDate
dtDict = item.get(timepoint)
dtStr = dtDict["date"] + " " + dtDict["time"]
return dtStr[:-3] # strip seconds
def parseTime(item, timepoint):
# item - structured JSON data containing startDate, endDate
# timepoint - str, for Indico JSON export: starDate or endDate
dtDict = item.get(timepoint)
dtStr = dtDict["time"]
return dtStr[:-3] # strip seconds
def processTitle(title):
sep = ":"
titleNoSessionNum = title.rsplit(sep,1)[0]
return str(titleNoSessionNum)
def prettyStartEnd(data, start, end):
return parseDateTime(data, start) + "-" + parseTime(data, end)
def getInitials(name):
initials = ''.join([x[0].upper()+'.' for x in name.split(' ')])
initials = initials+' '
return initials
def parseSession(data):
parsedData = OrderedDict({})
#print processTitle(data["title"])
parsedData["session-title"] = processTitle(data["title"])
parsedData["session-time"] = prettyStartEnd(data, "startDate", "endDate")
parsedData["room"] = data["room"]
parsedContribs = []
contribsUnsorted = data["contributions"]
contribs = sortByStartTime(contribsUnsorted)
for talk in contribs:
parsedTalk = OrderedDict({})
if data["session"]["type"] != u"Plenary lecture":
try:
speaker = talk["speakers"][0]
parsedTalk["speaker"] = getInitials(speaker["first_name"])+speaker["last_name"]
except:
# posters
pass
else:
try:
speaker = talk["speakers"][0]
parsedTalk["speaker"] = speaker["first_name"]+' '+speaker["last_name"]
except:
# prizes to be announced
pass
parsedTalk["title"] = talk["title"]
parsedTalk["time"] = prettyStartEnd(talk, "startDate", "endDate")
parsedContribs.append(parsedTalk)
parsedData["talks"] = parsedContribs
return parsedData
if __name__ == '__main__':
data = jsonGet("session-all.json")
sorteddata = sortByRoomTime(data) # sessions are sorted, but talks within a session aren't
simplifiedSessions = []
for session in sorteddata:
simpleSession = parseSession(session)
simplifiedSessions.append(simpleSession)
parser = argparse.ArgumentParser(description = "Gets sessions from one event using HTTP API, then sort into JSON files for typesetting. See github: selkieupsilon/euroismar-indicoscripts")
parser.add_argument('--timestamp', action='store_true', help='add timestamp to output files')
args = parser.parse_args()
#outputJsonFile(sorteddata, fileprefix="sessionSorted_", timestamp=args.timestamp)
outputJsonFile(simplifiedSessions, fileprefix="sessionSimple_", timestamp=args.timestamp)
print ("done") | [
"wingying.chow@gmail.com"
] | wingying.chow@gmail.com |
23196db1784ea4fd529b170f1d61159ce0908cbc | 1c74dee0cf5efcdcebb52455cb8a11de210a02ab | /py2/38. Count and Say.py | c9a5156793e0a8dc94827fe70aaba1bf587393b1 | [] | no_license | vaankiller/leetcode | f8072abad23ee41bda2a80d1a536120f11ada50f | 88b434bd493e6cb2f70267b40a87c2d881d89cb0 | refs/heads/master | 2020-04-16T02:11:58.057867 | 2018-12-24T08:49:40 | 2018-12-24T08:49:40 | 61,943,789 | 6 | 1 | null | null | null | null | UTF-8 | Python | false | false | 594 | py | class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
if n == 1:
return '1'
else:
seq = self.countAndSay(n-1)
split_seq = self.split_seq(seq)
return "".join([str(len(nums)) + str(nums[0]) for nums in split_seq])
def split_seq(self, seq):
ret = [[seq[0]], ]
for num in seq[1:]:
if num in ret[-1]:
ret[-1].append(num)
else:
ret.append([num])
return ret
| [
"534895367@qq.com"
] | 534895367@qq.com |
4179bb9a80b6b5ed972b902429f87239f74faa9e | cc5fb4cb60f3d218a24be6fde2f479dac5ead8fe | /Agents/ReplayMemories/ReplayMemory_old.py | 18932f6658553ef330f336ca06d87bdec1c26949 | [
"MIT"
] | permissive | DEATH-FROM-AI/DQN-Atari-Agents | b78fa10e2e583dfc9cb219083ff043a6801f8d20 | 9ddff988ef2516e4752c0296cc88b06bb0221400 | refs/heads/master | 2023-02-02T18:45:42.940350 | 2020-12-18T09:49:48 | 2020-12-18T09:49:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,648 | py | import random
import torch
import numpy as np
from collections import namedtuple, deque
class ReplayBuffer:
"""Fixed-size buffer to store experience tuples."""
def __init__(self, buffer_size, batch_size, device, seed, gamma, n_step=1):
"""Initialize a ReplayBuffer object.
Params
======
buffer_size (int): maximum size of buffer
batch_size (int): size of each training batch
seed (int): random seed
"""
self.device = device
self.memory = deque(maxlen=buffer_size)
self.batch_size = batch_size
self.experience = namedtuple("Experience", field_names=["state", "action", "reward", "next_state", "done"])
self.seed = random.seed(seed)
self.gamma = gamma
self.n_step = n_step
self.n_step_buffer = deque(maxlen=self.n_step)
def add(self, state, action, reward, next_state, done):
"""Add a new experience to memory."""
#print("before:", state,action,reward,next_state, done)
self.n_step_buffer.append((state, action, reward, next_state, done))
if len(self.n_step_buffer) == self.n_step:
state, action, reward, next_state, done = self.calc_multistep_return()
#print("after:",state,action,reward,next_state, done)
e = self.experience(state, action, reward, next_state, done)
self.memory.append(e)
def calc_multistep_return(self):
Return = 0
for idx in range(self.n_step):
Return += self.gamma**idx * self.n_step_buffer[idx][2]
return self.n_step_buffer[0][0], self.n_step_buffer[0][1], Return, self.n_step_buffer[-1][3], self.n_step_buffer[-1][4]
def sample(self):
"""Randomly sample a batch of experiences from memory."""
experiences = random.sample(self.memory, k=self.batch_size)
states = torch.from_numpy(np.stack([e.state for e in experiences if e is not None])).float().to(self.device)
actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).long().to(self.device)
rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float().to(self.device)
next_states = torch.from_numpy(np.stack([e.next_state for e in experiences if e is not None])).float().to(self.device)
dones = torch.from_numpy(np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float().to(self.device)
return (states, actions, rewards, next_states, dones)
def __len__(self):
"""Return the current size of internal memory."""
return len(self.memory)
class PrioritizedReplay(object):
"""
Proportional Prioritization
"""
def __init__(self, capacity, batch_size, seed, gamma=0.99, n_step=1, alpha=0.6, beta_start = 0.4, beta_frames=100000):
self.alpha = alpha
self.beta_start = beta_start
self.beta_frames = beta_frames
self.frame = 1 #for beta calculation
self.batch_size = batch_size
self.capacity = capacity
self.buffer = []
self.pos = 0
self.priorities = np.zeros((capacity,), dtype=np.float32)
self.seed = np.random.seed(seed)
self.n_step = n_step
self.n_step_buffer = deque(maxlen=self.n_step)
self.gamma = gamma
def calc_multistep_return(self):
Return = 0
for idx in range(self.n_step):
Return += self.gamma**idx * self.n_step_buffer[idx][2]
return self.n_step_buffer[0][0], self.n_step_buffer[0][1], Return, self.n_step_buffer[-1][3], self.n_step_buffer[-1][4]
def beta_by_frame(self, frame_idx):
"""
Linearly increases beta from beta_start to 1 over time from 1 to beta_frames.
3.4 ANNEALING THE BIAS (Paper: PER)
We therefore exploit the flexibility of annealing the amount of importance-sampling
correction over time, by defining a schedule on the exponent
that reaches 1 only at the end of learning. In practice, we linearly anneal from its initial value 0 to 1
"""
return min(1.0, self.beta_start + frame_idx * (1.0 - self.beta_start) / self.beta_frames)
def add(self, state, action, reward, next_state, done):
assert state.ndim == next_state.ndim
state = np.expand_dims(state, 0)
next_state = np.expand_dims(next_state, 0)
# n_step calc
self.n_step_buffer.append((state, action, reward, next_state, done))
if len(self.n_step_buffer) == self.n_step:
state, action, reward, next_state, done = self.calc_multistep_return()
max_prio = self.priorities.max() if self.buffer else 1.0 # gives max priority if buffer is not empty else 1
if len(self.buffer) < self.capacity:
self.buffer.append((state, action, reward, next_state, done))
else:
# puts the new data on the position of the oldes since it circles via pos variable
# since if len(buffer) == capacity -> pos == 0 -> oldest memory (at least for the first round?)
self.buffer[self.pos] = (state, action, reward, next_state, done)
self.priorities[self.pos] = max_prio
self.pos = (self.pos + 1) % self.capacity # lets the pos circle in the ranges of capacity if pos+1 > cap --> new posi = 0
def sample(self):
N = len(self.buffer)
if N == self.capacity:
prios = self.priorities
else:
prios = self.priorities[:self.pos]
# calc P = p^a/sum(p^a)
probs = prios ** self.alpha
P = probs/probs.sum()
#gets the indices depending on the probability p
indices = np.random.choice(N, self.batch_size, p=P)
samples = [self.buffer[idx] for idx in indices]
beta = self.beta_by_frame(self.frame)
self.frame+=1
#Compute importance-sampling weight
weights = (N * P[indices]) ** (-beta)
# normalize weights
weights /= weights.max()
weights = np.array(weights, dtype=np.float32)
states, actions, rewards, next_states, dones = zip(*samples)
return np.concatenate(states), actions, rewards, np.concatenate(next_states), dones, indices, weights
def update_priorities(self, batch_indices, batch_priorities):
for idx, prio in zip(batch_indices, batch_priorities):
self.priorities[idx] = prio
def __len__(self):
return len(self.buffer) | [
"sebastian.dittert@gmx.de"
] | sebastian.dittert@gmx.de |
c87ada364ca089321bc02f17edf55413aa5f681a | 689cbee697660adb9b1e27fd5d10b31f68decb71 | /tests/test_managers.py | ed06a638de09bb5c77612bb366b9de5c3044af59 | [
"Apache-2.0"
] | permissive | tomzhang/fiber | 3bdcf2e220e36eec5dda071e6964711791242341 | ac119b1671f689ab54d7bc0ae4efffa3ca0a2464 | refs/heads/master | 2021-05-17T13:19:06.764760 | 2020-06-30T20:19:07 | 2020-07-01T00:17:57 | 250,793,362 | 0 | 0 | Apache-2.0 | 2020-03-28T12:48:30 | 2020-03-28T12:48:29 | null | UTF-8 | Python | false | false | 2,910 | py | import fiber
import time
import pytest
import docker
from fiber.managers import AsyncManager
@pytest.fixture(scope="module")
def client():
return docker.from_env()
def f(ns, ls, di):
ns.x += 1
ns.y[0] += 1
ns_z = ns.z
ns_z[0] += 1
ns.z = ns_z
ls[0] += 1
ls[1][0] += 1 # unmanaged, not assigned back
ls_2 = ls[2] # unmanaged...
ls_2[0] += 1
ls[2] = ls_2 # ... but assigned back
ls[3][0] += 1 # managed, direct manipulation
di[0] += 1
di[1][0] += 1 # unmanaged, not assigned back
di_2 = di[2] # unmanaged...
di_2[0] += 1
di[2] = di_2 # ... but assigned back
di[3][0] += 1 # managed, direct manipulation
class Calculator():
def add(self, a, b):
return a + b
def add_with_delay(self, a, b, delay=1):
# delay for 1 seconds
time.sleep(1)
return a + b
class MyManager(AsyncManager):
pass
class TestManagers():
@pytest.fixture(autouse=True)
def check_leak(self, request, client):
assert fiber.active_children() == []
if fiber.config.default_backend != "docker":
yield
return
pre_workers = client.containers.list()
yield
post_workers = client.containers.list()
assert pre_workers == post_workers
# This test is adapted from
# https://stackoverflow.com/questions/9436757/how-does-multiprocessing-manager-work-in-python
def test_managers_basic(self):
manager = fiber.Manager()
ns = manager.Namespace()
ns.x = 1
ns.y = [1]
ns.z = [1]
ls = manager.list([1, [1], [1], manager.list([1])])
di = manager.dict({0: 1, 1: [1], 2: [1], 3: manager.list([1])})
p = fiber.Process(target=f, args=(ns, ls, di), name="test_managers_basic")
p.start()
p.join()
assert ns.x == 2
assert ns.y == [1]
assert ns.z == [2]
assert ls[0] == 2
assert ls[1] == [1]
assert ls[2] == [2]
assert ls[3][0] == 2
assert len(ls) == 4
assert di[0] == 2
assert di[1] == [1]
assert di[2] == [2]
assert di[3][0] == 2
def test_async_manager_basic(self):
MyManager.register("Calculator", Calculator)
manager = MyManager()
manager.start()
calc = manager.Calculator()
res = calc.add(10, 32)
assert res.get() == 42
total = 4
managers = [MyManager() for i in range(total)]
[manager.start() for manager in managers]
calculators = [manager.Calculator() for manager in managers]
start_ts = time.time()
handles = [calc.add_with_delay(10, 32) for calc in calculators]
results = [handle.get() for handle in handles]
duration = time.time() - start_ts
assert duration < 2
assert results == [42 for i in range(total)]
| [
"jiale@uber.com"
] | jiale@uber.com |
9b3323db11bb20247a08ffd42118228eb5783dcd | 108155164cb1f49a082db1b20bab49148d275a27 | /sysmontask/log_plotter.py | 35b4c8ef36985c9f027d680861523506c1465023 | [
"BSD-3-Clause"
] | permissive | bostan39/SysMonTask | 13a317bd30dd213c14dcda431356a4cf20498930 | 77f2752ad367c6fcefd6436bfc1bdf53b9bd3886 | refs/heads/master | 2023-04-06T03:39:54.488563 | 2021-04-14T17:39:06 | 2021-04-14T17:39:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,918 | py |
from gi import require_version
require_version("Gtk","3.0")
from gi.repository import Gtk as g
def fun(filename):
try:
import matplotlib.pyplot as plt
except ImportError:
print("matplotlib not found")
not_found=g.Dialog(title="Can't Plot",parent=None,flags=g.DialogFlags.MODAL)
content=not_found.get_content_area()
label=g.Label()
label.set_markup(
"""
<b><big>matplotlib(python3-matplotlib) not found </big></b>.
Please install using pip or package manager.
"""
)
content.add(label)
label.show()
not_found.show_all()
r=not_found.run()
not_found.destroy()
return
data=[[],[],[],[],[],[]]
try:
with open(filename) as ifile:
ifile.readline()
for line in ifile.readlines():
line=line.split(',')
for i,k in enumerate(line):
k=k.split()
if "%" in k[1]:
data[i].append(float(k[0]))
elif "M" in k[1]:
data[i].append(float(k[0]))
elif "K" in k[1]:
data[i].append(float(k[0])/1024)
elif "G" in k[1]:
data[i].append(float(k[0])*1024)
step=5
navg=range(2,len(data[0])-2)
n=range(1,len(data[0])+1)
avg=[[],[]]
avg[0]=[sum(data[0][i-2:i+3])/step for i in range(2,len(data[0])-2) ]
avg[1]=[sum(data[1][i-2:i+3])/step for i in range(2,len(data[1])-2) ]
fig, axs = plt.subplots(3, 2)
fig.tight_layout()
fig.canvas.set_window_title(f"Log_plot: {filename}")
plt.sca(axs[0][0])
plt.ylabel('rCPU [%]')
plt.xlabel('Sample Number')
axs[0][0].plot(n, data[0])
axs[0][0].plot(navg, avg[0])
axs[0][0].legend(['Normal',"Average"])
plt.sca(axs[0][1])
plt.ylabel('CPU %')
plt.xlabel('Sample Number')
axs[0][1].plot(n, data[1])
axs[0][1].plot(navg, avg[1])
axs[0][1].legend(['Normal',"Average"])
plt.sca(axs[1][0])
plt.ylabel('rMemory [MiB]')
plt.xlabel('Sample Number')
plt.plot(n, data[2])
plt.sca(axs[1][1])
plt.ylabel('Memory [MiB]')
plt.xlabel('Sample Number')
plt.plot(n, data[3])
plt.sca(axs[2][0])
plt.ylabel('DiskRead [MiB/s]')
plt.xlabel('Sample Number')
plt.plot(n, data[4])
plt.sca(axs[2][1])
plt.ylabel('DiskWrite [MiB/s]')
plt.xlabel('Sample Number')
plt.plot(n, data[5])
plt.show()
except Exception as e:
print(f"error can't plot: {e}")
can_not_plot=g.Dialog(title="Can't Plot",parent=None,flags=g.DialogFlags.MODAL)
content=can_not_plot.get_content_area()
label=g.Label()
label.set_markup(
"""
<b><big>Error Encountered While Plotting.</big></b>
"<b>.csv</b>" type files required, check if the selected file
is of correct type and not currupted.
"""
)
content.add(label)
label.show()
can_not_plot.show_all()
r=can_not_plot.run()
can_not_plot.destroy()
# def on_plot_dialog_quit(widget,FigureCanvas,plt,NavigationToolbar):
# print("plot dialog quit")
# widget.destroy()
# def plot_log(filename):
# try:
# import matplotlib.pyplot as plt
# from matplotlib.backends.backend_gtk3agg import (
# FigureCanvasGTK3Agg as FigureCanvas)
# from matplotlib.backends.backend_gtk3 import (
# NavigationToolbar2GTK3 as NavigationToolbar)
# # from matplotlib.figure import Figure
# # raise ImportError
# except ImportError:
# print("matplotlib not found")
# not_found=g.Dialog(title="Can't Plot",parent=None,flags=g.DialogFlags.MODAL)
# content=not_found.get_content_area()
# label=g.Label()
# label.set_markup(
# """
# <b><big>matplotlib(python3-matplotlib) not found </big></b>.
# Please install using pip or package manager.
# """
# )
# content.add(label)
# label.show()
# not_found.show_all()
# r=not_found.run()
# not_found.destroy()
# return
# data=[[],[],[],[],[],[]]
# try:
# with open(filename) as ifile:
# ifile.readline()
# for line in ifile.readlines():
# line=line.split(',')
# for i,k in enumerate(line):
# k=k.split()
# if "%" in k[1]:
# data[i].append(float(k[0]))
# elif "M" in k[1]:
# data[i].append(float(k[0]))
# elif "K" in k[1]:
# data[i].append(float(k[0])/1024)
# elif "G" in k[1]:
# data[i].append(float(k[0])*1024)
# step=5
# navg=range(2,len(data[0])-2)
# n=range(1,len(data[0])+1)
# avg=[[],[]]
# avg[0]=[sum(data[0][i-2:i+3])/step for i in range(2,len(data[0])-2) ]
# avg[1]=[sum(data[1][i-2:i+3])/step for i in range(2,len(data[1])-2) ]
# fig, axs = plt.subplots(3, 2)
# fig.tight_layout()
# plt.sca(axs[0][0])
# plt.ylabel('rCPU [%]')
# plt.xlabel('Sample Number')
# axs[0][0].plot(n, data[0])
# axs[0][0].plot(navg, avg[0])
# axs[0][0].legend(['Normal',"Average"])
# plt.sca(axs[0][1])
# plt.ylabel('CPU %')
# plt.xlabel('Sample Number')
# axs[0][1].plot(n, data[1])
# axs[0][1].plot(navg, avg[1])
# axs[0][1].legend(['Normal',"Average"])
# plt.sca(axs[1][0])
# plt.ylabel('rMemory [MiB]')
# plt.xlabel('Sample Number')
# plt.plot(n, data[2])
# plt.sca(axs[1][1])
# plt.ylabel('Memory [MiB]')
# plt.xlabel('Sample Number')
# plt.plot(n, data[3])
# plt.sca(axs[2][0])
# plt.ylabel('DiskRead [MiB/s]')
# plt.xlabel('Sample Number')
# plt.plot(n, data[4])
# plt.sca(axs[2][1])
# plt.ylabel('DiskWrite [MiB/s]')
# plt.xlabel('Sample Number')
# plt.plot(n, data[5])
# plot_dialog=g.Window(title="SysMonTask Log Plot")
# plot_dialog.set_default_size(650,500)
# plot_box=g.VBox()
# plot_dialog.add(plot_box)
# swxx=g.ScrolledWindow()
# plot_box.pack_start(swxx, True, True, 0)
# canvas = FigureCanvas(fig)
# swxx.add(canvas)
# # Create toolbar
# toolbar = NavigationToolbar(canvas, plot_dialog)
# plot_box.pack_start(toolbar, False, False, 0)
# plot_dialog.connect("destroy",on_plot_dialog_quit,FigureCanvas,plt,NavigationToolbar)
# swxx.show_all()
# plot_dialog.show_all()
# # fig.clf()
# # gc.collect()
# except Exception as e:
# print(f"error can't plot: {e}")
# can_not_plot=g.Dialog(title="Can't Plot",parent=None,flags=g.DialogFlags.MODAL)
# content=can_not_plot.get_content_area()
# label=g.Label()
# label.set_markup(
# """
# <b><big>Error Encountered While Plotting.</big></b>
# "<b>.csv</b>" type files required, check if the selected file
# is correct and not currupted.
# """
# )
# content.add(label)
# label.show()
# can_not_plot.show_all()
# r=can_not_plot.run()
# can_not_plot.destroy()
# plot_log("/home/neeraj/sysmontask_log/code.csv")
import sys
fun(sys.argv[1]) | [
"neerajjangra4u@gmail.com"
] | neerajjangra4u@gmail.com |
335422803194b1cd8587eff445a6b3bec4fc5ad8 | 6fe824e9ec5bd5c7da28e8addf0badbda3d61411 | /webapp2/squares/migrations/0010_auto_20150729_0327.py | fe5bf8171bf37e694ed6a917a437928d1cb250da | [] | no_license | moment-x/web | dcdd9e7fad89522a1a51545718a6fccc5ea1503d | c4de993988bce91b36e0454fb2d2f1acd3dd890a | refs/heads/master | 2021-01-22T21:32:01.589267 | 2015-08-04T15:18:23 | 2015-08-04T15:18:23 | 40,176,340 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 500 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('squares', '0009_pendingdata'),
]
operations = [
migrations.RemoveField(
model_name='pendingdata',
name='json',
),
migrations.AddField(
model_name='pendingdata',
name='data',
field=models.BinaryField(null=True),
),
]
| [
"token@email.com"
] | token@email.com |
efeacb891135eccd38993b58b003c19502602b1b | 2ebcb93ea31e8b76307b35b2939d3d5b83ec0978 | /scripts/fk_basic_cnn_new_keras.py | 2acb4750852b78d124861c0fcebda575dbd05194 | [] | no_license | TBarry95/dmml2_deep_learning | f26c0398072e16df41204d3c13860e0c11d1c9ee | 3b740cefac8707ebed0f890857c4e101008e7802 | refs/heads/master | 2022-12-05T05:39:31.137732 | 2020-08-16T19:16:12 | 2020-08-16T19:16:12 | 277,293,575 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,654 | py | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 7 19:03:44 2020
@author: Frank
"""
##Repeat with the cleaned test/training dataset
import tensorflow as tf
import random as rn
import os
import tensorflow.keras as keras
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.optimizers import RMSprop
import math
print(keras.__version__)
from numpy.random import seed
seed(42)# keras seed fixing
import tensorflow as tf
tf.random.set_seed(42)# tensorflow seed fixing
#(x_train, y_train),(x_test, y_test) = mnist.load_data()
print("Current Working Directory " , os.getcwd())
os.chdir("C:\\Users\\Frank\\dmml2_deep_learning\\scripts")
print("Current Working Directory " , os.getcwd())
# Extract dataset from folder:
train_datagen = ImageDataGenerator(rescale = 1/255)
test_datagen = ImageDataGenerator(rescale = 1/255)
# Batch Gradient Descent. Batch Size = Size of Training Set
# Stochastic Gradient Descent. Batch Size = 1
# Mini-Batch Gradient Descent. 1 < Batch Size < Size of Training Set
# get training images
train_gen = train_datagen.flow_from_directory(
r'.\cleaned_data\train',
target_size = (224, 224), # target_size = (32, 32),
batch_size = 128,
class_mode='binary'
#classes = ['normal','viral']
)
# get testing images
test_gen = test_datagen.flow_from_directory(
r'.\cleaned_data\test',
target_size = (224, 224), #FK: Target size is the height and width of the images...
batch_size = 128,
class_mode='binary'
#classes = ['normal','viral']
)
imgs, labels = next(train_gen)
import matplotlib.pyplot as plt
print(imgs[0])
print(labels[0])
plt.imshow(imgs[0],cmap=plt.cm.binary)
plt.show()
print(labels[2])
plt.imshow(imgs[2],cmap=plt.cm.binary)
plt.show()
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) #FK: Added another layer
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) #FK: Added another layer
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) #FK: Added another layer
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) #FK: Added another layer
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) #FK: Added another layer
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) #FK: Added another layer
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) #FK: Added another layer
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) #FK: Added another layer
model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(train_gen,
steps_per_epoch=17, #NUMBER OF SAMPLES IN TRAINING/BATCH_SIZE : https://datascience.stackexchange.com/questions/47405/what-to-set-in-steps-per-epoch-in-keras-fit-generator
epochs=10,
validation_data=test_gen
)
#val_loss, val_acc = model.evaluate(train_gen, test_gen)
#print(val_loss)
#print(val_acc)
############################################################
# Validate Model: get final results
############################################################
####Save the model down....
# Save the entire model as a SavedModel.
#!mkdir -p saved_models
model.save('saved_models/frank_cnn_10layer_224_224')
model.save_weights('saved_models/frank_cnn_10layer_224_224/weights')
# load new unseen validate dataset
validation_datagen = ImageDataGenerator(rescale = 1 / 255)
val_generator = validation_datagen.flow_from_directory(
r'.\cleaned_data\validate',
target_size = (224, 224),
batch_size = 128, #Should be 18??
class_mode = 'binary' #,
#shuffle = False # see: https://github.com/keras-team/keras/issues/4875
)
eval_result = model.evaluate_generator(val_generator) #eval_result = model.evaluate_generator(val_generator, 300)
print('Loss rate for validation: ', eval_result[0])
print('Accuracy rate for validation: ', eval_result[1])
predictions = model.predict(val_generator)
print(predictions)
import numpy as np
for i in range(1,100):
print(np.argmax(predictions[i]))
imgs, labels = next(val_generator)
for i in range(1,100):
print(labels[i])
plt.imshow(imgs[0],cmap=plt.cm.binary)
plt.show()
#Load the saved model
new_model = tf.keras.models.load_model('saved_models/frank_cnn_10layer_224_224')
new_weights = new_model.load_weights('saved_models/frank_cnn_10layer_224_224/weights')
new_model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# Check its architecture
new_model.summary()
eval_result = new_model.evaluate_generator(val_generator) #eval_result = model.evaluate_generator(val_generator, 300)
print('Loss rate for validation: ', eval_result[0])
print('Accuracy rate for validation: ', eval_result[1])
print(tf.__version__)
#######################################################Save Model attempt 1##################
# from tensorflow.keras.models import model_from_json
# # serialize model to json
# json_model = model.to_json()
# #save the model architecture to JSON file
# with open('fashionmnist_model.json', 'w') as json_file:
# json_file.write(json_model)
# #saving the weights of the model
# model.save_weights('FashionMNIST_weights.h5')
# from tensorflow.keras.initializers import glorot_uniform
# #Reading the model from JSON file
# with open('fashionmnist_model.json', 'r') as json_file:
# json_savedModel= json_file.read()
# #load the model architecture
# model_j = tf.keras.models.model_from_json(json_savedModel)
# model_j.summary()
# ######################################Save Model attempt 2##################
# with open('saved_models/frank_cnn_5layer_32_32_attempt2.json', 'w') as f:
# f.write(model.to_json())
# model.save_weights('saved_models/frank_cnn_5layer_32_32_attempt2_weights.h5')
# with open('saved_models/frank_cnn_5layer_32_32_attempt2.json', 'w') as f:
# attempt2_model = tf.keras.models.model_from_json('saved_models/frank_cnn_5layer_32_32_attempt2.json')
# model.load_weights('saved_models/frank_cnn_5layer_32_32_attempt2_weights.h5')
###########################################################Number dataset...
# import tensorflow as tf
# mnist = tf.keras.datasets.mnist
# (x_train, y_train),(x_test, y_test) = mnist.load_data()
# print(x_train[0])
# import matplotlib.pyplot as plt
# plt.imshow(x_train[0],cmap=plt.cm.binary)
# plt.show()
# print(y_train[0])
# x_train = tf.keras.utils.normalize(x_train, axis=1)
# x_test = tf.keras.utils.normalize(x_test, axis=1)
# print(x_train[0])
# plt.imshow(x_train[0],cmap=plt.cm.binary)
# plt.show()
# model = tf.keras.models.Sequential()
# model.add(tf.keras.layers.Flatten())
# model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
# model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
# model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))
# model.compile(optimizer='adam',
# loss='sparse_categorical_crossentropy',
# metrics=['accuracy'])
# model.fit(x_train, y_train, epochs=3)
# val_loss, val_acc = model.evaluate(x_test, y_test)
# print(val_loss)
# print(val_acc)
# predictions = model.predict(x_test)
# print(predictions)
# import numpy as np
# print(np.argmax(predictions[0]))
# plt.imshow(x_test[0],cmap=plt.cm.binary)
# plt.show()
###################################################END OF NUMBER DATASET
| [
"kellyfb@tcd.ie"
] | kellyfb@tcd.ie |
7c7980134d1f62ac8a84180e57067ec5a35f0202 | a3522805fca9dc43102d32911546c8db4a62431f | /실력향상예제11.py | e5c724d6f74cea993fad713f92b7742feb12c47c | [] | no_license | Jangwoojin863/python | 409eef00f68e8f6aebf7de38dcd110081ec3f95d | 869ebe6df04e00ab9e2eccdeb8d99cbf093d904a | refs/heads/main | 2023-05-05T18:33:15.659662 | 2021-05-23T10:42:15 | 2021-05-23T10:42:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 204 | py | # 실력 향상 예제 11
total = 0
for i in range(1, 11):
print("%2i의 4승 = %5i" %(i, pow(i, 4)))
total += pow(i, 4) #total += i**4
print("\n전체 합계 = %i" % total)
| [
"noreply@github.com"
] | Jangwoojin863.noreply@github.com |
08503e60417f6f571232309d89aa9b710ead9b9a | 8e22b0e565ba39e4efcfe0db61da161314d2069f | /utils/csvTopd.py | d0725edb739fbd1ad1a2d1486375eb488792753c | [] | no_license | prakashpy/it-s-all-about-python | 060c8314daf58f994cd61224158774086a388e34 | 7b0eb9b87eb97d387615d634dcf33152f026ef26 | refs/heads/master | 2020-03-25T22:35:06.362825 | 2018-12-27T22:42:45 | 2018-12-27T22:42:45 | 144,230,646 | 0 | 2 | null | null | null | null | UTF-8 | Python | false | false | 861 | py | """
implementing code to filter csv file based on requested columns
"""
import pandas as pd
import os
def filter_csv(return_as="json"):
"""
Filter down our data to something displayable based on parameters from the main page.
:param return_as: json or numpy (default json)
:returns: the filtered dataset
"""
my_path = os.path.split(os.path.realpath(__file__))[0]
csv_path = os.path.join(my_path, "..", "..", "..", "data", "merged_data.csv")
data = pd.read_csv(csv_path)
columns = []
columns.extend("new_column_name")
data = data.loc[:, columns]
if return_as == "json":
return data.to_json(orient="records")
elif return_as == "numpy":
return data
else:
raise ValueError("return_as must be json or numpy, not " + str(return_as))
if __name__ == "__main__":
filter_csv() | [
"ppatel@bensonhillbio.com"
] | ppatel@bensonhillbio.com |
c920c8ee4670d550c86656634330be144a4ea5de | 2f634e9edf111ae7d3be5e529ae832dda7fc7114 | /automate.py | 1892580110dd92c05ead9b1effb6380091e68b96 | [] | no_license | amansr02/AutomateMDST | 55ae575b35dcb03f638be812f43dd8d7685e32f9 | 0ca87b7e15a8ce4f58adf38346b5e4fe5051f2f3 | refs/heads/master | 2021-05-19T03:47:10.570244 | 2020-03-31T06:10:41 | 2020-03-31T06:10:41 | 251,514,807 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,641 | py | import pickle
import sys
import json
import base64
import time
import os.path
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.firefox.options import Options
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
SAMPLE_SPREADSHEET_ID = ""
SAMPLE_RANGE_NAME = ""
def initial_auth():
username = "amansr@umich.edu"
#check password.txt for the missing line. Could have used file io but wanted to push to github asap.
passwd = b.decode("utf-8")
options = Options()
#options.headless = True
driver = webdriver.Firefox(options=options)
driver.get("https://accounts.google.com/signin/v2/identifier?continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&service=mail&sacu=1&rip=1&flowName=GlifWebSignIn&flowEntry=ServiceLogin")
assert "Gmail" in driver.title
elem = driver.find_element_by_id("identifierId")
elem.clear()
elem.send_keys("amansr@umich.edu")
elem.send_keys(Keys.RETURN)
time.sleep(5)
login = driver.find_element_by_id("login-visible")
login.clear()
login.send_keys(username)
password = driver.find_element_by_id("password")
password.send_keys(passwd)
currentURL = driver.current_url
password.send_keys(Keys.RETURN)
time.sleep(5)
driver.switch_to.frame('duo_iframe')
authButton = driver.find_element_by_xpath("/html/body/div/div/div[1]/div/form/div[1]/fieldset/div[1]/button").click()
while "https://mail.google.com/mail/u/0/#inbox" not in driver.current_url:
print("waiting...")
pass
print("success")
time.sleep(6)
return driver
def generate_email(name,standing,major):
#return this crap
email = """Hey """+name+""",
Hope you are well. I am Aman, a rising sophomore at MDST and I wanted to extend to you a warm welcome into the team.
We are excited to have you on board and have many projects and questions lined up for the fall semester. We value your expertise as a """+standing+""" in """+major+""" and encourage you to be an active member of the team.
To stay updated, join our slack channel-> https://bit.ly/2kTpR1b
Our First Mass Meeting is in -> Thursday, September 26th from 6-7pm in SPH 1755.
We also have an upcoming Data Challenge sponsored by MIDAS => MIDAS Data Challenge.
The registration page and info is here -> https://www.mdst.club/midas-data-challenge
Be on the lookout for emails and slack updates on project meetings for the fall semester!
Let me know if you have any questions!!
Warm Regards,
Aman Srivastav
VP of Recruitment - MDST
"""
return email
def selenium_interface(values):
driver = initial_auth()
driver.switch_to.default_content()
#loads gmail page
for element in values:
compose = driver.find_element_by_xpath("/html/body/div[7]/div[3]/div/div[2]/div[1]/div[1]/div[1]/div/div/div/div[1]/div/div").click()
time.sleep(2)
to = driver.find_element_by_name("to")
to.send_keys(element[1])
subject = driver.find_element_by_name("subjectbox")
subject.send_keys("Welcome to the Michigan Data Science Team")
body = driver.find_element_by_xpath("""//div[@aria-label="Message Body"]""")
name = element[2].split()
#setup conditional stuff
if(element[4]=="Literature, Science, and the Arts"):
element[4]= "LSA"
if "Freshman" in element[6]:
element[6]="Freshman"
elif "Sophomore" in element[6]:
element[6]="Sophomore"
elif "Junior" in element[6]:
element[6]="Junior"
elif "Senior" in element[6]:
element[6]="Senior"
email = generate_email(name[0],element[6],element[4])
body.send_keys(email)
body.send_keys(Keys.ESCAPE)
# submit = driver.find_element_by_xpath("""//*[@id=":nu"]""")
# submit.click()
def sheet_auth(start,end):
"""Shows basic usage of the Sheets API.
Prints values from a sample spreadsheet.
"""
global SAMPLE_SPREADSHEET_ID
global SAMPLE_RANGE_NAME
SAMPLE_SPREADSHEET_ID = '1iIS1nezxe1ddNzAYaTdV8TN93SamoKE2WRu9qbDkT68'
SAMPLE_RANGE_NAME = 'Form Responses 1!' + start + ':'+end
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server()
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('sheets', 'v4', credentials=creds)
return service
def main():
argv = sys.argv
#replace with metadata file
sender = "amansr@umich.edu"
to = ""
subject = "Welcome to MDST"
start = "A774"
end = "R863"
service = sheet_auth(start,end)
# Call the Sheets API
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
range=SAMPLE_RANGE_NAME).execute()
values = result.get('values', [])
if not values:
print('No data found.')
else:
with open("user-data.json","w") as outfile:
json.dump(values,outfile,indent=4)
selenium_interface(values)
if __name__ == '__main__':
main()
#deprecated methods
## in main:
#gmail
# userList = []
# service = gmail_auth()
# f = open("user-data.json")
# data = json.load(f)
# for element in data:
# name = element[2].split()
# name = name[0]
# userList.append({
# "name": name,
# "email": element[1],
# "major": element[4],
# "year": element[6],
# "experience": element[16]
# })
# with open("user-data.json","w") as outfile:
# json.dump(userList,outfile,indent=4)
# # Call the Gmail API
# #results = service.users().labels().list(userId='me').execute()
# user = userList[0]
# to = user["email"]
# message = create_message(sender,to,subject,"test")
# draft = create_draft(service,"amansr@umich.edu",message)
# def gmail_auth():
# """Shows basic usage of the Gmail API.
# Lists the user's Gmail labels.
# """
# creds = None
# # The file token.pickle stores the user's access and refresh tokens, and is
# # created automatically when the authorization flow completes for the first
# # time.
# if os.path.exists('gtoken.pickle'):
# with open('gtoken.pickle', 'rb') as token:
# creds = pickle.load(token)
# # If there are no (valid) credentials available, let the user log in.
# if not creds or not creds.valid:
# if creds and creds.expired and creds.refresh_token:
# creds.refresh(Request())
# else:
# flow = InstalledAppFlow.from_client_secrets_file(
# 'gcredentials.json', GSCOPES)
# creds = flow.run_local_server()
# # Save the credentials for the next run
# with open('gtoken.pickle', 'wb') as token:
# pickle.dump(creds, token)
# service = build('gmail', 'v1', credentials=creds)
# return service
# def create_message(sender, to, subject, message_text):
# # """Create a message for an email.
# # Args:
# # sender: Email address of the sender.
# # to: Email address of the receiver.
# # subject: The subject of the email message.
# # message_text: The text of the email message.
# # Returns:
# # An object containing a base64url encoded email object.
# # """
# message = MIMEText(message_text)
# message['to'] = to
# message['from'] = sender
# message['subject'] = subject
# encoded_message = base64.urlsafe_b64encode(message.as_bytes())
# return {'raw': encoded_message.decode()}
# def create_draft(service, user_id, message_body):
# # """Create and insert a draft email. Print the returned draft's message and id.
# # Args:
# # service: Authorized Gmail API service instance.
# # user_id: User's email address. The special value "me"
# # can be used to indicate the authenticated user.
# # message_body: The body of the email message, including headers.
# # Returns:
# # Draft object, including draft id and message meta data.
# # """
# try:
# message = {'message': message_body}
# draft = service.users().drafts().create(userId=user_id, body=message).execute()
# print('Draft id: %s\nDraft message: %s' % (draft['id'], draft['message']))
# return draft
# except HttpError as e:
# print('An error occurred',e)
# return None
| [
"amansr@umich.edu"
] | amansr@umich.edu |
a74fcd5f11c47ca89cb8faae836d664a7ecac83b | 8a83bb7acb9b62183fca817e1f196dd8075630a4 | /04_tree/31_make_tree_from_parent_array.py | e2495870b734992a534a4ea9a194f5aca19de043 | [] | no_license | sandeepkumar8713/pythonapps | ff5ad3da854aa58e60f2c14d27359f8b838cac57 | 5dcb5ad4873124fed2ec3a717bfa379a4bbd197d | refs/heads/main | 2023-09-01T04:12:03.865755 | 2023-08-31T07:04:58 | 2023-08-31T07:04:58 | 234,762,925 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,853 | py | # https://www.geeksforgeeks.org/construct-a-binary-tree-from-parent-array-representation/
# Question : Given an array that represents a tree in such a way that array indexes are
# values in tree nodes and array values give the parent node of that particular index (or node).
# The value of the root node index would always be -1 as there is no parent for root.
# Construct the standard linked representation of given Binary Tree from this given
# representation.
#
# Input: parent[] = {1, 5, 5, 2, 2, -1, 3}
# Output: root of below tree
# 5
# / \
# 1 2
# / / \
# 0 3 4
# /
# 6
#
# Question Type : Easy
# Used : For the given parent array, convert it into parentChildMap where :
# key is parentData and value is list of actual values (index).
# Maintain a queue. Insert the root node whose parent is -1.
# Run a loop while queue is not empty.
# Pop a node from queue, use its value to fetch its children from the parentChildMap
# Make a node out of each child.
# If node.left is None : node.left = newNode
# Else: node.right = newNode.
# Append the newNode to queue.
# return root
# Logic :
# while len(queue) > 0:
# node = queue.pop(0)
# parentData = node.data
# for data in parentChildMap[parentData]:
# newNode = Node(data)
# if node.left is None:
# node.left = newNode
# else:
# node.right = newNode
# queue.append(newNode)
# return root
# Complexity : O(n)
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def makeTree(parent):
parentChildMap = dict()
for index in range(len(parent)):
try:
parentChildMap[parent[index]].append(index)
except KeyError:
parentChildMap[parent[index]] = [index]
queue = []
# insert the root value
root = Node(parentChildMap[-1][0])
queue.append(root)
while len(queue) > 0:
node = queue.pop(0)
parentData = node.data
try:
for data in parentChildMap[parentData]:
newNode = Node(data)
if node.left is None:
node.left = newNode
else:
node.right = newNode
queue.append(newNode)
except KeyError:
pass
return root
def printInOrder(node):
if node is None:
return
printInOrder(node.left)
print(node.data, end=" ")
printInOrder(node.right)
if __name__ == "__main__":
# parent = [-1, 0, 0, 1, 1, 3, 5]
parent = [1, 5, 5, 2, 2, -1, 3]
root = makeTree(parent)
printInOrder(root)
print("")
| [
"sandeepkumar8713@gmail.com"
] | sandeepkumar8713@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.