hexsha stringlengths 40 40 | size int64 5 2.06M | ext stringclasses 10
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 248 | max_stars_repo_name stringlengths 5 125 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 248 | max_issues_repo_name stringlengths 5 125 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringdate 2015-01-01 00:00:47 2022-03-31 23:42:18 ⌀ | max_issues_repo_issues_event_max_datetime stringdate 2015-01-01 17:43:30 2022-03-31 23:59:58 ⌀ | max_forks_repo_path stringlengths 3 248 | max_forks_repo_name stringlengths 5 125 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 5 2.06M | avg_line_length float64 1 1.02M | max_line_length int64 3 1.03M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6db5c79371243a32af183f73744db734c3cd20b9 | 1,380 | py | Python | ETL/Data_Operations/data_operations.py | rohanharode/DRAW-Drug-Review-Analysis-Work | 89d8df82e1f0b67129727f16c32c038d64af35e2 | [
"MIT"
] | null | null | null | ETL/Data_Operations/data_operations.py | rohanharode/DRAW-Drug-Review-Analysis-Work | 89d8df82e1f0b67129727f16c32c038d64af35e2 | [
"MIT"
] | 2 | 2020-11-08T22:03:32.000Z | 2021-06-27T09:22:31.000Z | ETL/Data_Operations/data_operations.py | rohanharode/Drug-Review-Analysis-Work | 89d8df82e1f0b67129727f16c32c038d64af35e2 | [
"MIT"
] | 1 | 2021-07-08T10:50:36.000Z | 2021-07-08T10:50:36.000Z | from ETL.Data_Preprocessing.data_cleaning_and_filtering import cleaning_and_filtering
from ETL.Data_Transformation.drug_conditions_grouped import group_conditions
from ETL.Data_Transformation.jaccard_similarity import apply_jaccard_similarity
from ETL.Data_Transformation.drug_conditions_fuzzy_matching import fuzzy_matching
from ETL.Data_Transformation.updating_conditions import updating_conditions
from ETL.Data_Transformation.dataset_final_conditions import site_level_final_condition
from ETL.Data_Transformation.drug_final_dataset import site_level_datasets_creation
from ETL.Data_Aggregation.full_merge import final_dataset_creation
def all_data_operations():
# Task1: Data Preprocessing
cleaning_and_filtering()
# Task2: Condition grouping
group_conditions()
# Task3: Apply Jaccard similarity on condition and drugname
apply_jaccard_similarity()
# Task4: Fuzzy matching conditions
fuzzy_matching()
# Task5: Fuzzy matching conditions
updating_conditions()
# Task6: Finalizing site level conditions
site_level_final_condition()
# Task7: Creating site level datasets
site_level_datasets_creation()
# Task8: Creating final aggregated dataset (combining webmd, drugs.com, druglib
final_dataset_creation()
print('All Data Operations completed, processed data in full_merge.csv')
all_data_operations() | 37.297297 | 87 | 0.826087 |
6db6887534c339671321ea2ad6c3cae9fe067123 | 2,345 | py | Python | setup.py | Ezbob/dgDynamic | 394de1c138c1517c4cdfead879c43db189752d92 | [
"MIT"
] | null | null | null | setup.py | Ezbob/dgDynamic | 394de1c138c1517c4cdfead879c43db189752d92 | [
"MIT"
] | null | null | null | setup.py | Ezbob/dgDynamic | 394de1c138c1517c4cdfead879c43db189752d92 | [
"MIT"
] | null | null | null | from setuptools import setup
from setuptools.command.install import install
import os
import sys
import atexit
if __name__ == '__main__':
package_name = 'dgdynamic'
excludes = [
'__pycache__',
'StochKit'
]
extras = [
'default_config.ini',
'spim.ocaml',
'stochkit.tar.gz'
]
def find_package_dirs(package_dir_path, excludes):
return [path for path, dirs, files in os.walk(package_dir_path)
if not any(exclude_name in path for exclude_name in excludes)]
def get_requirements():
with open('requirements.txt', mode="r") as file:
return list(map(str.strip, file))
package_dirs = find_package_dirs(package_name, excludes)
internal_python_paths = {
".".join(p_name.split('/')): p_name
for p_name in package_dirs
}
class CustomInstall(install):
def run(self):
def _post_install():
def find_module_path():
for p in sys.path:
if os.path.isdir(p) and package_name in os.listdir(p):
return os.path.join(p, package_name)
install_path = find_module_path()
stochkit2_plugin_path = os.path.join(install_path, "plugins/stochastic/stochkit2/")
stochkit2_tar_path = os.path.join(stochkit2_plugin_path, "stochkit.tar.gz")
stochkit2_installer_path = os.path.join(stochkit2_plugin_path, "StochKit")
os.system("tar xvzf " + stochkit2_tar_path + " -C " + stochkit2_plugin_path)
os.system("cd " + stochkit2_installer_path + " && ./install.sh")
atexit.register(_post_install)
install.run(self)
setup(
cmdclass={'install': CustomInstall},
name=package_name,
version='1.0.0',
description='Dynamic simulation library for the MØD graph transformation framework',
url='https://bitbucket.org/Ezben/dgdynamic',
author='Anders Busch',
author_email='andersbusch@gmail.com',
license='MIT',
package_dir=internal_python_paths,
include_package_data=True,
package_data={'': extras},
packages=list(internal_python_paths.keys()),
install_requires=get_requirements(),
zip_safe=False
)
| 33.028169 | 99 | 0.612367 |
6db73ff6f5328cc7f6a179960f5ceb876377c833 | 5,543 | py | Python | Robotics/src/otonomsesli.py | ahmetakif/Voice-Controlled-Raspberry-Pi-Robot | 00dcc15dfbb7441d6403fb0467b2144e8750cc0c | [
"Apache-2.0"
] | 5 | 2019-08-21T08:08:27.000Z | 2021-06-14T06:56:50.000Z | Robotics/src/otonomsesli.py | ahmetakif/Voice-Controlled-Raspberry-Pi-Robot | 00dcc15dfbb7441d6403fb0467b2144e8750cc0c | [
"Apache-2.0"
] | null | null | null | Robotics/src/otonomsesli.py | ahmetakif/Voice-Controlled-Raspberry-Pi-Robot | 00dcc15dfbb7441d6403fb0467b2144e8750cc0c | [
"Apache-2.0"
] | 2 | 2019-08-21T08:16:58.000Z | 2021-04-07T11:56:11.000Z | import os
import RPi.GPIO as gpio
import time
from mesafe import distance
motorhizi = 1
aci2 = aci3 = aci4 = 6
aci = 5.5
in4 = 26
in3 = 4
in2 = 12
in1 = 8
solled = 9
sagled = 11
gpio.setwarnings(False)
def init():
gpio.setwarnings(False)
gpio.setmode(gpio.BCM)
gpio.setup(22,gpio.OUT)
gpio.setup(27,gpio.OUT)
gpio.setup(17,gpio.OUT)
gpio.setup(18,gpio.OUT)
gpio.setup(in4,gpio.OUT)
gpio.setup(in3,gpio.OUT)
gpio.setup(in2,gpio.OUT)
gpio.setup(in1,gpio.OUT)
gpio.setup(21,gpio.OUT)
gpio.setup(solled,gpio.OUT)
gpio.setup(sagled,gpio.OUT)
gpio.setup(23,gpio.IN)
gpio.setup(24,gpio.IN)
gpio.output(22,0)
gpio.output(18,0)
gpio.output(17,0)
gpio.output(27,0)
gpio.output(in4,0)
gpio.output(in3,0)
gpio.output(in2,0)
gpio.output(in1,0)
gpio.output(21,0)
gpio.output(solled,0)
gpio.output(sagled,0)
def ileri(tf,ff):
init()
gpio.output(17,0)
gpio.output(22,0)
ip = gpio.PWM(27,50)
ip2 = gpio.PWM(18,50)
ip.start(ff)
ip2.start(ff)
tf = float(tf)
tf = tf / motorhizi
time.sleep(tf)
gpio.cleanup()
def geri(tf,ff):
init()
gpio.output(18,0)
gpio.output(27,0)
gp = gpio.PWM(22,50)
gp2 = gpio.PWM(17,50)
gp.start(ff)
gp2.start(ff)
tf = float(tf)
tf = tf / motorhizi
time.sleep(tf)
gpio.cleanup()
def sol(tf,ff):
init()
gpio.output(17,0)
gpio.output(27,0)
sp = gpio.PWM(22,50)
sp2 = gpio.PWM(18,50)
sp.start(ff)
sp2.start(ff)
tf = float(tf)
tf = tf / motorhizi
time.sleep(tf)
gpio.cleanup()
def sag(tf,ff):
init()
gpio.output(18,0)
gpio.output(22,0)
sap = gpio.PWM(27,50)
sap2 = gpio.PWM(17,50)
sap.start(ff)
sap2.start(ff)
tf = float(tf)
tf = tf / motorhizi
time.sleep(tf)
gpio.cleanup()
def dur():
init()
gpio.output(22,0)
gpio.output(17,0)
gpio.output(18,0)
gpio.output(27,0)
gpio.cleanup()
def adim1(tf,y):
init()
if (y == 1): # sol
gpio.output(in1,1)
gpio.output(in2,0)
gpio.output(in3,0)
gpio.output(in4,0)
if (y == 0): # sag
gpio.output(in1,0)
gpio.output(in2,0)
gpio.output(in3,0)
gpio.output(in4,1)
time.sleep(tf)
gpio.cleanup()
def adim2(tf,y):
init()
if (y == 1): # sol
gpio.output(in1,0)
gpio.output(in2,1)
gpio.output(in3,0)
gpio.output(in4,0)
if (y == 0): # sag
gpio.output(in1,0)
gpio.output(in2,0)
gpio.output(in3,1)
gpio.output(in4,0)
time.sleep(tf)
gpio.cleanup()
def adim3(tf,y):
init()
if (y == 1): # sol
gpio.output(in1,0)
gpio.output(in2,0)
gpio.output(in3,1)
gpio.output(in4,0)
if (y == 0): # sag
gpio.output(in1,0)
gpio.output(in2,1)
gpio.output(in3,0)
gpio.output(in4,0)
time.sleep(tf)
gpio.cleanup()
def adim4(tf,y):
init()
if (y == 1): # sol
gpio.output(in1,0)
gpio.output(in2,0)
gpio.output(in3,0)
gpio.output(in4,1)
if (y == 0): # sag
gpio.output(in1,1)
gpio.output(in2,0)
gpio.output(in3,0)
gpio.output(in4,0)
time.sleep(tf)
gpio.cleanup()
def stepper(tf,ff,yf):
ff = float(ff)
ff = ff / 1000
if (yf == 0): # sag
for i in range(0,tf):
adim1(ff,0)
adim2(ff,0)
adim3(ff,0)
adim4(ff,0)
if (yf == 1): # sol
for i in range(0,tf):
adim1(ff,1)
adim2(ff,1)
adim3(ff,1)
adim4(ff,1)
def servo(tf):
gpio.setmode(gpio.BCM)
gpio.setup(5,gpio.OUT)
p = gpio.PWM(5,50)
p.start(5.5)
p.ChangeDutyCycle(tf)
time.sleep(0.7)
gpio.cleanup()
def servo2(tf):
gpio.setmode(gpio.BCM)
gpio.setup(6,gpio.OUT)
p2 = gpio.PWM(6,50)
p2.start(6)
p2.ChangeDutyCycle(tf)
time.sleep(0.7)
gpio.cleanup()
def servo3(tf):
gpio.setmode(gpio.BCM)
gpio.setup(20,gpio.OUT)
p3 = gpio.PWM(20,50)
p3.start(6)
p3.ChangeDutyCycle(tf)
time.sleep(0.7)
gpio.cleanup()
def servo4(tf):
gpio.setmode(gpio.BCM)
gpio.setup(16,gpio.OUT)
p3 = gpio.PWM(16,50)
p3.start(6)
p3.ChangeDutyCycle(tf)
time.sleep(0.7)
gpio.cleanup()
def ses(tf,ff):
init()
sp = gpio.PWM(21,ff)
sp.start(70)
time.sleep(tf)
gpio.cleanup()
def led(ff,tf,sf):
init()
sp = gpio.PWM(solled,500)
sap = gpio.PWM(sagled,500)
if (sf == 0):
sp.start(ff)
time.sleep(tf)
gpio.cleanup()
elif (sf == 1):
sap.start(ff)
time.sleep(tf)
gpio.cleanup()
elif (sf == 2):
sp.start(ff)
sap.start(ff)
time.sleep(tf)
gpio.cleanup()
print (" ")
print ("otonomgorev yazilimi google speech api sesli komutlari ile robotun otonom hareket etmesi için yazilmistir")
print (" ")
time.sleep(1)
def cizgi(lf):
os.system("aplay -vv /home/pi/Robotics/PortalTurret/Turret_active.wav &")
int = 0
for int in range(1,lf):
init()
if (gpio.input(23) == 0 and gpio.input(24) == 0):
ileri(0.1,100)
elif (gpio.input(23) == 1 and gpio.input(24) == 0):
sol(0.1,100)
elif (gpio.input(22) == 0 and gpio.input(24) == 1):
sag(0.1,100)
else:
dur()
dur()
main()
aci2 = aci3 = aci4 = 6
aci = 5.5
| 20.378676 | 115 | 0.541043 |
6db755c6b9c7ae3c58a95da2aa5e9301523ca9e8 | 632 | py | Python | src/models/discord_users.py | KirtusJ/BirdBot | 4440364caefa6ec9acf1bc7cf38605b1d90de20e | [
"MIT"
] | null | null | null | src/models/discord_users.py | KirtusJ/BirdBot | 4440364caefa6ec9acf1bc7cf38605b1d90de20e | [
"MIT"
] | null | null | null | src/models/discord_users.py | KirtusJ/BirdBot | 4440364caefa6ec9acf1bc7cf38605b1d90de20e | [
"MIT"
] | null | null | null | from sqlalchemy.sql import func
from sqlalchemy import Column, BigInteger, String, DateTime, Boolean
from .model import database
class DiscordUser(database.Base):
__tablename__='discord_users'
id = Column(BigInteger, primary_key=True, unique=True, nullable=False, autoincrement=False)
created = Column(DateTime(timezone=True), server_default=func.now())
updated = Column(DateTime(timezone=True), nullable=True)
blacklisted = Column(Boolean, unique=False, default=False)
owner = Column(Boolean, unique=False, default=False)
moderator = Column(Boolean, unique=False, default=False)
def __repr__(self):
return f"{self.id}" | 39.5 | 92 | 0.783228 |
6db800ff348f905ec48118d311341bb879f2f4fd | 2,036 | py | Python | algorithms/timer.py | terratenff/vrp-gen-alg | 3910ff7977a84b03e14c4f500909bcb86e6dd608 | [
"MIT"
] | null | null | null | algorithms/timer.py | terratenff/vrp-gen-alg | 3910ff7977a84b03e14c4f500909bcb86e6dd608 | [
"MIT"
] | null | null | null | algorithms/timer.py | terratenff/vrp-gen-alg | 3910ff7977a84b03e14c4f500909bcb86e6dd608 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
"""
timer.py:
Implementation of a CPU timer that is used as a part of stopping criteria.
"""
import time
def _time():
"""
Convenience function that returns current process time as milliseconds.
"""
return time.process_time() * 1000
class Timer:
"""
Captures CPU time and keeps track of it. In so doing,
various actions could be measured as milliseconds.
"""
def __init__(self, goal=None):
"""
Timer constructor. It is stopped upon initialization.
:params goal: Optional threshold time (as milliseconds) that is used
as a time limit.
"""
self.time_start = _time()
self.time_stop = _time()
if goal is None:
self.time_goal = float("inf")
else:
self.time_goal = goal
self.running = False
def start(self):
"""
Starts the timer.
"""
self.time_start = _time()
self.time_stop = 0
self.running = True
def reset(self):
"""
Resets the timer.
"""
self.time_start = _time()
self.time_stop = 0
def stop(self):
"""
Stops the timer.
"""
self.time_stop = _time() - self.time_start
self.running = False
def elapsed(self):
"""
Calculates total time that has passed since starting the timer.
"""
if self.running is False:
return _time() - self.time_start
else:
return (_time() - self.time_start) - self.time_stop
def difference(self):
"""
Calculates time difference between time threshold and total elapsed time.
"""
if self.running is False:
return self.time_goal - self.time_stop
else:
return self.time_goal - (_time() - self.time_start)
def past_goal(self):
"""
Checks whether total elapsed time has exceeded the threshold.
"""
return self.difference() < 0
| 22.130435 | 81 | 0.562868 |
6db82d6e06cc11fb7b83d45d0342ef4c6c52a44f | 6,093 | py | Python | experiments/livecell/validate_model.py | JonasHell/torch-em | 2e008e0cd2f0ea6681581374fce4f9f47b986d55 | [
"MIT"
] | 13 | 2021-03-09T21:31:09.000Z | 2022-03-21T05:24:26.000Z | experiments/livecell/validate_model.py | JonasHell/torch-em | 2e008e0cd2f0ea6681581374fce4f9f47b986d55 | [
"MIT"
] | 16 | 2021-03-02T23:19:34.000Z | 2022-03-25T19:43:41.000Z | experiments/livecell/validate_model.py | JonasHell/torch-em | 2e008e0cd2f0ea6681581374fce4f9f47b986d55 | [
"MIT"
] | 4 | 2021-05-18T08:29:33.000Z | 2022-02-11T12:16:20.000Z | import argparse
import os
from glob import glob
from pathlib import Path
import imageio
import h5py
import pandas as pd
from bioimageio.core import load_resource_description
from bioimageio.core.prediction import predict_with_padding
from bioimageio.core.prediction_pipeline import create_prediction_pipeline
from elf.evaluation import mean_average_precision
from torch_em.util.segmentation import (connected_components_with_boundaries,
mutex_watershed, size_filter)
from tqdm import tqdm
from xarray import DataArray
try:
import napari
except ImportError:
napari = None
def segment(prediction_pipeline, path, out_path, view, offsets=None, strides=None, min_seg_size=50):
image = imageio.imread(path)
assert image.ndim == 2
input_ = DataArray(image[None, None], dims=prediction_pipeline.input_specs[0].axes)
padding = {"x": 16, "y": 16}
prediction = predict_with_padding(prediction_pipeline, input_, padding)[0][0]
foreground, prediction = prediction[0], prediction[1:]
if offsets is None:
assert prediction.shape[0] == 1, f"{prediction.shape}"
prediction = prediction[0]
assert foreground.shape == prediction.shape
seg = connected_components_with_boundaries(foreground, prediction)
else:
assert len(offsets) == prediction.shape[0]
mask = foreground > 0.5
seg = mutex_watershed(prediction, offsets, mask=mask, strides=strides)
seg = size_filter(seg, min_seg_size, hmap=prediction, with_background=True)
# implement more postprocessing?
# - merge noisy foreground prediction (that only have very weak boundary predictions) into the background
if out_path is not None:
with h5py.File(out_path, "w") as f:
f.create_dataset("prediction", data=prediction, compression="gzip")
f.create_dataset("foreground", data=foreground, compression="gzip")
f.create_dataset("segmentation", data=seg, compression="gzip")
if view:
assert napari is not None
v = napari.Viewer()
v.add_image(image)
v.add_image(foreground)
v.add_image(prediction)
v.add_labels(seg)
napari.run()
return seg
def validate(seg, gt_path):
gt = imageio.imread(gt_path)
assert gt.shape == seg.shape
map_, scores = mean_average_precision(seg, gt, return_aps=True)
# map, iou50, iou75, iou90
return [map_, scores[0], scores[5], scores[-1]]
def run_prediction(model_path, input_files, target_files, output_folder, view, min_seg_size, device):
model = load_resource_description(model_path)
offsets, strides = None, None
if "mws" in model.config:
offsets = model.config["mws"]["offsets"]
strides = [4, 4]
if output_folder is not None:
os.makedirs(output_folder, exist_ok=True)
validation_results = []
devices = None if device is None else [device]
with create_prediction_pipeline(bioimageio_model=model, devices=devices) as pp:
for in_path, target_path in tqdm(zip(input_files, target_files), total=len(input_files)):
fname = str(Path(in_path).stem)
out_path = None if output_folder is None else os.path.join(output_folder, f"{fname}.h5")
seg = segment(pp, in_path, out_path, view,
offsets=offsets, strides=strides, min_seg_size=min_seg_size)
if target_path:
val = validate(seg, target_path)
validation_results.append([fname] + val)
if validation_results:
cols = ["name", "mAP", "IoU50", "IoU75", "IoU90"]
validation_results = pd.DataFrame(validation_results, columns=cols)
print("Validation results averaged over all", len(input_files), "images:")
print(validation_results[cols[1:]].mean(axis=0))
return validation_results
# TODO needs update for live-cell data structure
def _load_data(input_folder, ext):
input_data = glob(os.path.join(input_folder, "images", f"*.{ext}"))
input_data.sort()
if os.path.exists(os.path.join(input_folder, "masks")):
input_target = glob(os.path.join(input_folder, "masks", f"*.{ext}"))
input_target.sort()
else:
input_target = [None] * len(input_data)
assert len(input_data) == len(input_target)
return input_data, input_target
def main():
parser = argparse.ArgumentParser(
"Run prediction and segmentation with a bioimagie.io model and save or validate the results."
"If 'output_folder' is passed, the results will be saved as hdf5 files with keys:"
"prediction: the affinity or boundary predictions"
"foreground: the foreground predictions"
"segmentation: the nucleus instance segmentation"
)
parser.add_argument("-m", "--model", required=True, help="Path to the bioimage.io model.")
parser.add_argument("-i", "--input_folder", required=True,
help="The root input folder with subfolders 'images' and (optionally) 'masks'")
parser.add_argument("--ext", default="tif", help="The file extension of the input files.")
parser.add_argument("-o", "--output_folder", default=None, help="Where to save the results.")
parser.add_argument("-v", "--view", default=0,
help="Whether to show segmentation results (needs napari).", type=int)
parser.add_argument("--min_seg_size", default=25, type=int)
parser.add_argument("--device", default=None, help="The device used for inference.")
parser.add_argument("--save_path", "-s", default=None, help="Where to save a csv with the validation results.")
args = parser.parse_args()
input_files, target_files = _load_data(args.input_folder, args.ext)
res = run_prediction(args.model, input_files, target_files, args.output_folder,
view=bool(args.view), min_seg_size=args.min_seg_size, device=args.device)
if args.save_path is not None:
assert res is not None
res.to_csv(args.save_path, index=False)
if __name__ == "__main__":
main()
| 42.02069 | 115 | 0.683243 |
6dba80a9622a3df8b603c41e7552e6d4c8ed3c02 | 23 | py | Python | tests/res/foo.py | lepture/werkzeug | 627ac8370bc5aa3a04ba365b4ebcd32b6a859863 | [
"BSD-3-Clause"
] | 1 | 2019-04-14T19:58:21.000Z | 2019-04-14T19:58:21.000Z | tests/res/foo.py | lepture/werkzeug | 627ac8370bc5aa3a04ba365b4ebcd32b6a859863 | [
"BSD-3-Clause"
] | null | null | null | tests/res/foo.py | lepture/werkzeug | 627ac8370bc5aa3a04ba365b4ebcd32b6a859863 | [
"BSD-3-Clause"
] | null | null | null | from .bar import value
| 11.5 | 22 | 0.782609 |
6dbe230462ef91543db856cb4ff084f41755ca26 | 1,320 | py | Python | src/wa_kat/db/downloader.py | WebArchivCZ/WA-KAT | 719f7607222f5a4d917c535b2da6371184222101 | [
"MIT"
] | 3 | 2017-03-23T12:59:21.000Z | 2017-11-22T08:23:14.000Z | src/wa_kat/db/downloader.py | WebArchivCZ/WA-KAT | 719f7607222f5a4d917c535b2da6371184222101 | [
"MIT"
] | 89 | 2015-06-28T22:10:28.000Z | 2017-01-30T16:06:05.000Z | src/wa_kat/db/downloader.py | WebarchivCZ/WA-KAT | 719f7607222f5a4d917c535b2da6371184222101 | [
"MIT"
] | 1 | 2015-12-17T02:56:59.000Z | 2015-12-17T02:56:59.000Z | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
# Imports =====================================================================
import requests
from ..settings import USER_AGENT
from ..settings import REQUEST_TIMEOUT
# Functions & classes =========================================================
def download(url):
"""
Download `url` and return it as utf-8 encoded text.
Args:
url (str): What should be downloaded?
Returns:
str: Content of the page.
"""
headers = {"User-Agent": USER_AGENT}
resp = requests.get(
url,
timeout=REQUEST_TIMEOUT,
headers=headers,
allow_redirects=True,
verify=False,
)
def decode(st, alt_encoding=None):
encodings = ['ascii', 'utf-8', 'iso-8859-1', 'iso-8859-15']
if alt_encoding:
if isinstance(alt_encoding, basestring):
encodings.append(alt_encoding)
else:
encodings.extend(alt_encoding)
for encoding in encodings:
try:
return st.encode(encoding).decode("utf-8")
except UnicodeEncodeError, UnicodeDecodeError:
pass
raise UnicodeError('Could not find encoding.')
return decode(resp.text, resp.encoding)
| 25.882353 | 79 | 0.537879 |
6dbfcff192ece7ab414ec98a8d97692a952d7bdd | 7,506 | py | Python | main.py | qmn/pershing | ec3cc87d9bfb7ca0cf1da1449d695c36df548309 | [
"BSD-2-Clause"
] | 16 | 2017-05-20T05:30:59.000Z | 2022-02-08T05:41:52.000Z | main.py | qmn/pershing | ec3cc87d9bfb7ca0cf1da1449d695c36df548309 | [
"BSD-2-Clause"
] | null | null | null | main.py | qmn/pershing | ec3cc87d9bfb7ca0cf1da1449d695c36df548309 | [
"BSD-2-Clause"
] | 3 | 2016-09-18T15:55:37.000Z | 2020-12-27T15:36:09.000Z | #!/usr/bin/env python2.7
from __future__ import print_function
import json
import sys
import numpy as np
import os.path
import time
from math import ceil
import argparse
import nbt
from util import blif, cell, cell_library
from placer import placer
from router import router, extractor, minetime
from vis import png
from inserter import inserter
def underline_print(s):
print()
print(s)
print("-" * len(s))
if __name__ == "__main__":
placements = None
dimensions = None
routing = None
# Create parser
parser = argparse.ArgumentParser(description="An automatic place-and-route tool for Minecraft Redstone circuits.")
parser.add_argument('blif', metavar="<input BLIF file>")
parser.add_argument('-o', '--output_dir', metavar="output_directory", dest="output_dir")
parser.add_argument('--library', metavar="library_file", dest="library_file", default="lib/quan.yaml")
parser.add_argument('--placements', metavar="placements_file", dest="placements_file", help="Use this placements file rather than creating one. Must be previously generated from the supplied BLIF.")
parser.add_argument('--routings', metavar="routings_file", dest="routings_file", help="Use this routings file rather than creating one. Must be previously generated from the supplied BLIF and placements JSON.")
parser.add_argument('--world', metavar="world_folder", dest="world_folder", help="Place the extracted redstone circuit layout in this world.")
args = parser.parse_args()
# Load placements, if provided
if args.placements_file is not None:
print("Using placements file:", args.placements_file)
with open(args.placements_file) as f:
placements = json.loads(f.readline())
dimensions = json.loads(f.readline())
# Load library file
with open(args.library_file) as f:
cell_lib = cell_library.load(f)
# Load BLIF
with open(args.blif) as f:
blif = blif.load(f)
# Result directory
if args.output_dir is not None:
if os.path.isabs(args.output_dir):
result_dir = args.output_dir
else:
result_dir = os.path.abspath(args.output_dir)
else:
result_base, _ = os.path.splitext(args.blif)
result_dir = os.path.abspath(result_base + "_result")
# Try making the directory
if not os.path.exists(result_dir):
try:
os.mkdir(result_dir)
print("Made result dir: ", result_dir)
except OSError as e:
print(e)
pregenerated_cells = cell_library.pregenerate_cells(cell_lib, pad=1)
placer = placer.GridPlacer(blif, pregenerated_cells, grid_spacing=5)
start_time = time.time()
print("Started", time.strftime("%c", time.localtime(start_time)))
# PLACE =============================================================
if placements is None:
underline_print("Performing Initial Placement...")
placements, dimensions = placer.initial_placement()
score = placer.score(placements, dimensions)
print("Initial Placement Penalty:", score)
underline_print("Doing Placement...")
# Place cells
T_0 = 250
iterations = 2000
new_placements = placer.simulated_annealing_placement(placements, dimensions, T_0, iterations)
placements, dimensions = placer.shrink(new_placements)
# Place pins and resize
placements += placer.place_pins(dimensions)
placements, dimensions = placer.shrink(placements)
# print(new_placements)
print("Placed", len(placements), "cells")
with open(os.path.join(result_dir, "placements.json"), "w") as f:
json.dump(placements, f)
f.write("\n")
json.dump(dimensions, f)
# Visualize this layout
layout = placer.placement_to_layout(dimensions, placements)
png.layout_to_png(layout, filename_base=os.path.join(result_dir, "composite"))
print("Dimensions:", dimensions)
# ROUTE =============================================================
underline_print("Doing Routing...")
placements, dimensions = placer.shrink(placements)
layout = placer.placement_to_layout(dimensions, placements)
router = router.Router(blif, pregenerated_cells)
# Load routings, if provided
if args.routings_file is not None:
print("Using routings file:", args.routings_file)
with open(args.routings_file) as f:
routing = router.deserialize_routing(f)
if routing is None:
blocks, data = layout
print("Doing initial routing...")
routing = router.initial_routing(placements, blocks.shape)
print("done.")
routing = router.re_route(routing, layout)
# Preserve routing
with open(os.path.join(result_dir, "routing.json"), "w") as f:
router.serialize_routing(routing, dimensions, f)
print("Routed", len(routing), "nets")
# EXTRACT ===========================================================
underline_print("Doing Extraction...")
extractor = extractor.Extractor(blif, pregenerated_cells)
extracted_routing = extractor.extract_routing(routing)
extracted_layout = extractor.extract_layout(extracted_routing, layout)
with open(os.path.join(result_dir, "extraction.json"), "w") as f:
blocks, data = extracted_layout
json.dump(blocks.tolist(), f)
json.dump(data.tolist(), f)
print("Wrote extraction to extraction.json")
# VISUALIZE =========================================================
underline_print("Doing Visualization...")
# Get the pins
pins = placer.locate_circuit_pins(placements)
# png.nets_to_png(layout, routing)
png_fn = os.path.join(result_dir, "layout.png")
png.layout_to_composite(extracted_layout, pins=pins).save(png_fn)
print("Image written to ", png_fn)
# MINETIME =========================================================
underline_print("Doing Timing Analysis with MineTime...")
mt = minetime.MineTime()
path_delays = mt.compute_combinational_delay(placements, extracted_routing, cell_lib)
print("Path delays:")
for path_delay, path in sorted(path_delays, key=lambda x: x[0], reverse=True):
print(path_delay, " ", " -> ".join(path))
print()
crit_delay, crit_path = max(path_delays, key=lambda x: x[0])
print("Critical path delay: {} ticks".format(crit_delay))
print("Minimum period: {:.2f} s".format(crit_delay * 0.05))
print("Maximum frequency: {:.4f} Hz".format(1./(crit_delay * 0.05)))
underline_print("Design Statistics")
blocks, _ = layout
print("Layout size: {} x {} x {}".format(blocks.shape[0], blocks.shape[1], blocks.shape[2]))
print(" Blocks placed: {}".format(sum(blocks.flat != 0)))
print()
print("Total nets: {}".format(len(extracted_routing)))
print(" Segments routed: {}".format(sum(len(net["segments"]) for net in extracted_routing.itervalues())))
print()
end_time = time.time()
print("Finished", time.strftime("%c", time.localtime(end_time)), "(took", ceil(end_time - start_time), "s)")
# INSERTION ========================================================
if args.world_folder is not None:
underline_print("Inserting Design into Minecraft World...")
world = nbt.world.WorldFolder(args.world_folder)
inserter.insert_extracted_layout(world, extracted_layout, offset=(4, 0, 0))
| 37.158416 | 214 | 0.641886 |
6dc096d4b45dd4acd7b5d28912a696afdc093628 | 296 | py | Python | logtest.py | jonathanstrong/log-viewer | 83374de21ce807709217e3fffa87b75265b3edd6 | [
"MIT"
] | 1 | 2017-03-09T01:18:06.000Z | 2017-03-09T01:18:06.000Z | logtest.py | jonathanstrong/log-viewer | 83374de21ce807709217e3fffa87b75265b3edd6 | [
"MIT"
] | null | null | null | logtest.py | jonathanstrong/log-viewer | 83374de21ce807709217e3fffa87b75265b3edd6 | [
"MIT"
] | null | null | null | import logging
import logging.handlers
import time
logger = logging.getLogger(__name__)
handler = logging.handlers.SocketHandler('localhost', 9033)
stream = logging.StreamHandler()
logger.addHandler(handler)
logger.addHandler(stream)
while True:
logger.warning('ping')
time.sleep(.001)
| 22.769231 | 59 | 0.780405 |
6dc161a661b51dac6f78e1e2949123e1dfec52e8 | 5,032 | py | Python | text-builder.py | guskma/text-builder | e9de6178ef5ce71a6f022b7932d40a906200578e | [
"MIT"
] | null | null | null | text-builder.py | guskma/text-builder | e9de6178ef5ce71a6f022b7932d40a906200578e | [
"MIT"
] | null | null | null | text-builder.py | guskma/text-builder | e9de6178ef5ce71a6f022b7932d40a906200578e | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from argparse import ArgumentParser
from collections import OrderedDict
import jinja2
import csv
import sys
import os.path
import re
def store_keyval(src_dict, key, val):
if key is None:
return val
if type(src_dict) is not OrderedDict:
src_dict = OrderedDict()
matched = re.match(r'^([^\.\[\]]+?)(?:\[([\d]+|@?)\])?(?:\.(.+))?$', key)
if matched is None:
print(f'Invalid key name: {key}')
return src_dict
key_name = matched.group(1)
key_index_str = matched.group(2)
key_dict = matched.group(3)
is_array = key_index_str is not None
is_dict = key_dict is not None
key_exists = key_name in src_dict.keys()
if is_array and not key_exists:
src_dict[key_name] = [None]
elif is_dict and not key_exists:
src_dict[key_name] = OrderedDict()
if is_array:
if key_index_str == '@':
key_index = len(src_dict[key_name]) - 1
elif not key_index_str and src_dict[key_name][0] is None:
key_index = 0
elif not key_index_str:
key_index = len(src_dict[key_name])
else:
key_index = int(key_index_str)
key_len = len(src_dict[key_name])
if key_len < key_index + 1:
src_dict[key_name].extend([None] * (key_index - key_len + 1))
src_dict[key_name][key_index] = store_keyval(src_dict[key_name][key_index], key_dict, val)
elif is_dict:
src_dict[key_name] = store_keyval(src_dict[key_name], key_dict, val)
else:
src_dict[key_name] = val
return src_dict
def build_templates(args):
if args.DEBUG:
print('* === text-builder execute. ===')
templateLoader = jinja2.FileSystemLoader(searchpath='.', encoding=args.ENCODING)
templateEnv = jinja2.Environment( loader=templateLoader )
templateEnv.trim_blocks = True
newline = args.NEWLINE.replace(r'\r', "\r").replace(r'\n', "\n")
if args.DEBUG:
sys.stdout.write('* Loading INVENTORY file ... ')
f = open(args.INVENTORY, 'rt', encoding=args.ENCODING, newline=newline)
if args.DEBUG:
print('Done.')
try:
if args.DEBUG:
print('* Loading header.')
reader = list(csv.reader(f))
header = reader.pop(0)
header_cols = len(header)
parsed_files = 0
for row in reader:
if args.DEBUG:
sys.stdout.write(f'* Building row({parsed_files + 2}): ')
dict_row = OrderedDict()
cols = len(row)
for i in range(cols if cols > header_cols else header_cols):
if header_cols <= i:
continue
elif cols <= i:
col = ""
else:
col = row[i]
dict_row = store_keyval(dict_row, header[i], col)
if args.DEBUG:
print(dict_row)
template = templateEnv.get_template(args.TEMPLATE)
outputText = template.render(dict_row)
output_dir = args.OUTPUTS_DIR
if 'output_dir' in dict_row and dict_row['output_dir'].strip() != '':
output_dir = f"{output_dir}/{dict_row['output_dir'].strip()}"
os.makedirs(output_dir, exist_ok=True)
filename = dict_row['filename'] if 'filename' in dict_row else f"parsed_{parsed_files}.txt"
output_filename = f"{output_dir}/{filename}"
with open(output_filename, 'w', newline=newline, encoding=args.ENCODING) as output_file:
output_file.write(outputText)
print("wrote file: %s" % output_filename)
parsed_files += 1
print(f"\nDone. output {parsed_files} files in \"{output_dir}\" directory.")
finally:
f.close()
def cmd_options():
usage = f"text-builder <TEMPLATE> <INVENTORY> [-ehno]"
argparser = ArgumentParser(usage=usage)
argparser.add_argument(
'TEMPLATE',
type=str,
help='Template text file.')
argparser.add_argument(
'INVENTORY',
type=str,
help='Paramaters CSV file.')
argparser.add_argument(
'-d', '--debug',
dest='DEBUG',
action='store_true',
help='Output debug message.')
argparser.add_argument(
'-e', '--encoding',
type=str,
dest='ENCODING',
default='cp932',
help='Set encoding charset of template and inventory file. (default: "cp932")')
argparser.add_argument(
'-n', '--new-line',
type=str,
dest='NEWLINE',
default="\r\n",
help='Set new line charcode. (default: "\\r\\n")')
argparser.add_argument(
'-o', '--output-path',
type=str,
default='output',
dest='OUTPUTS_DIR',
help='Set output files path.')
args = argparser.parse_args()
return args
if __name__ == "__main__":
args = cmd_options()
build_templates(args)
| 29.775148 | 103 | 0.584261 |
6dc1f2e93753dd6196949aaa91494539baeb31b1 | 2,077 | py | Python | hard_grasp.py | bionicdl-sustech/AmphibiousManipulation | 397c7dfef6b4dda178a567c36aabfe0f4b05b821 | [
"MIT"
] | null | null | null | hard_grasp.py | bionicdl-sustech/AmphibiousManipulation | 397c7dfef6b4dda178a567c36aabfe0f4b05b821 | [
"MIT"
] | null | null | null | hard_grasp.py | bionicdl-sustech/AmphibiousManipulation | 397c7dfef6b4dda178a567c36aabfe0f4b05b821 | [
"MIT"
] | null | null | null | import yaml
import os
import sys
import time
import numpy as np
import cv2 as cv
from franka.FrankaController import FrankaController
def read_cfg(path):
with open(path, 'r') as stream:
out = yaml.safe_load(stream)
return out
if __name__ == '__main__':
ROOT = os.path.dirname(os.path.abspath(__file__))
sys.path.append(ROOT)
cfg = read_cfg(ROOT + '/config/grasping _colorseg.yaml')
arm = FrankaController(ROOT + '/config/franka.yaml')
# grasping config
initial_pose = cfg['initial_position']
initial_pose[2] -= 0.3
check_position = cfg['check_position']
drop_position = cfg['drop_position']
grasp_pre_offset = cfg['grasp_prepare_offset']
effector_offset = cfg['effector_offset']
check_threshold = cfg['check_threshold']
attmp_num = cfg['attmp_num']
print("Moving to initial position...")
arm.move_p(initial_pose)
print("Moving to initial position... Done")
stored_exception = None
arm.move_p(initial_pose)
current_num = 0
while current_num < attmp_num:
try:
if stored_exception:
break
target_in_base = drop_position.copy()
target_in_base[2] -= 0.37
prepare_pos = [target_in_base[0], target_in_base[1], target_in_base[2] + grasp_pre_offset + effector_offset, 3.14, 0, 0]
arm.move_p(prepare_pos)
arm.gripperOpen()
arm.move_p([target_in_base[0], target_in_base[1], target_in_base[2] + effector_offset, 3.14, 0, 0])
arm.gripperGrasp(width=0.05, force=2)
time.sleep(0.5)
# Move to check position
# arm.move_p(check_position)
arm.move_p(initial_pose)
# Move to drop position and drop object
arm.move_p(drop_position)
arm.gripperOpen()
# Back to initial position
arm.move_p(initial_pose)
current_num += 1
except KeyboardInterrupt:
stored_exception = sys.exc_info()
cv.destroyAllWindows()
| 25.9625 | 132 | 0.629273 |
6dc61ebe0b329b523bc43f68e083bb96cc389b67 | 2,913 | py | Python | src/server/api.py | Irsutoro/sesame | 142959a6e4c814c72f480b0252a028d8586b77da | [
"MIT"
] | null | null | null | src/server/api.py | Irsutoro/sesame | 142959a6e4c814c72f480b0252a028d8586b77da | [
"MIT"
] | null | null | null | src/server/api.py | Irsutoro/sesame | 142959a6e4c814c72f480b0252a028d8586b77da | [
"MIT"
] | null | null | null | import cherrypy
import sesame
from database import create_database
DATABASE = create_database({'System':'sqlite', 'Database':'testy.db'})
SERVER = None
def validate_password(realm, login, password):
#TODO autoryzacja JWT
return SERVER.authorize_user(login, password)
CHERRYPY_CONFIG = {
'server.socket_host': '127.0.0.1',
'server.socket_port': 8080,
'tools.auth_basic.on': True,
'tools.auth_basic.realm': '127.0.0.1',
'tools.auth_basic.checkpassword': validate_password,
}
def get_user_login():
return cherrypy.request.login
@cherrypy.expose
class AuthService:
#TODO aktywacja konta
""" #TODO przeniesienie do JWT service
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
def GET(self):
request = cherrypy.request.json
#TODO zmiana na zwracanie JWT
try:
auth_successful = SERVER.authorize_user(request['login'], request['password'])
except KeyError:
raise cherrypy.HTTPError(400)
if auth_successful:
#TODO zwrot JWT
return 'Authorized'
else:
raise cherrypy.HTTPError(401) """
@cherrypy.tools.json_in()
def POST(self):
request = cherrypy.request.json
try:
SERVER.register_user(request['username'], request['password'], request['email'])
except ValueError:
raise cherrypy.HTTPError(409, 'Username or email is already used')
except KeyError:
raise cherrypy.HTTPError(400)
@cherrypy.expose
class UserService:
@cherrypy.tools.json_out()
def GET(self):
return SERVER.get_user_info(get_user_login())
@cherrypy.expose
class PasswordService:
@cherrypy.tools.json_out()
def GET(self, label:str=None):
user = get_user_login()
if label:
return SERVER.get_password(user, label)
else:
return SERVER.get_password_labels(user)
@cherrypy.tools.json_in()
def POST(self):
request = cherrypy.request.json
try:
SERVER.add_password(get_user_login(), 'AES128', request['password'], request['label'], request['account_name'])
except KeyError:
raise cherrypy.HTTPError(400)
if __name__ == '__main__':
WITHOUT_AUTHENTICATION = {'/': {'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.auth_basic.on': False}}
WITH_AUTHENTICATION = {'/': {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}}
SERVER = sesame.Sesame(DATABASE)
SERVER.create_tables()
SERVER.add_encrypting_algorithm('AES128')
cherrypy.config.update(CHERRYPY_CONFIG)
cherrypy.tree.mount(UserService(), '/api/user', WITH_AUTHENTICATION)
cherrypy.tree.mount(AuthService(), '/api/auth', WITHOUT_AUTHENTICATION)
cherrypy.tree.mount(PasswordService(), '/api/password', WITH_AUTHENTICATION)
cherrypy.engine.start()
cherrypy.engine.block()
| 30.663158 | 124 | 0.6701 |
6dc710027aba9309fc1e58e6facfd13ec0253ff6 | 731 | py | Python | Domain_Knowledge_based/stanfordNER.py | Mount428/Hate-Speech-Detection | f8644844dda954ebd169aeec54cb4c7361d88a09 | [
"MIT"
] | null | null | null | Domain_Knowledge_based/stanfordNER.py | Mount428/Hate-Speech-Detection | f8644844dda954ebd169aeec54cb4c7361d88a09 | [
"MIT"
] | null | null | null | Domain_Knowledge_based/stanfordNER.py | Mount428/Hate-Speech-Detection | f8644844dda954ebd169aeec54cb4c7361d88a09 | [
"MIT"
] | null | null | null | from nltk.tag import StanfordNERTagger
import pandas as pd
from sklearn.metrics import f1_score, confusion_matrix
from loader import Load
train, test = Load('c')
ner = StanfordNERTagger('./stanford-ner-2018-10-16/classifiers/english.all.3class.distsim.crf.ser.gz', './stanford-ner-2018-10-16/stanford-ner.jar')
data = train
data['tweet'] = ner.tag_sents(data['tweet'].str.split(' '))
pred = []
for i, d in data.iterrows():
tweet = d['tweet']
tag = 'IND'
for w in tweet:
if w[1] == 'ORGANIZATION':
tag = 'GRP'
# elif w[1] == 'PEOPLE':
# tag = 'IND'
pred.append(tag)
print(confusion_matrix(data['label'], pred))
print(f1_score(data['label'], pred, average='macro'))
| 22.84375 | 148 | 0.641587 |
6dc79c5bcc11f79748762758e10ea27d0fe9f70f | 41,355 | py | Python | pyrif/FuXi/Rete/Network.py | mpetyx/pyrif | 2f7ba863030d7337bb39ad502d1e09e26ac950d2 | [
"MIT"
] | null | null | null | pyrif/FuXi/Rete/Network.py | mpetyx/pyrif | 2f7ba863030d7337bb39ad502d1e09e26ac950d2 | [
"MIT"
] | null | null | null | pyrif/FuXi/Rete/Network.py | mpetyx/pyrif | 2f7ba863030d7337bb39ad502d1e09e26ac950d2 | [
"MIT"
] | null | null | null | """
====================================================================================
A Rete Network Building and 'Evaluation' Implementation for RDFLib Graphs of
Notation 3 rules.
The DLP implementation uses this network to automatically building RETE
decision trees for OWL forms of DLP
Uses Python hashing mechanism to maximize the efficiency of the built
pattern network.
The network :
- compiles an RDFLib N3 rule graph into AlphaNode and BetaNode instances
- takes a fact (or the removal of a fact, perhaps?) and propagates down,
starting from its alpha nodes
- stores inferred triples in provided triple source (an RDFLib graph) or
a temporary IOMemory Graph by default
"""
from itertools import chain
import sys
import time
from pprint import pprint
try:
from functools import reduce
except ImportError:
pass
try:
from io import StringIO
except ImportError:
from StringIO import StringIO
from .BetaNode import (
BetaNode,
LEFT_MEMORY,
RIGHT_MEMORY,
PartialInstantiation,
)
from .AlphaNode import (
AlphaNode,
BuiltInAlphaNode,
ReteToken,
)
from FuXi.Horn import (
ComplementExpansion,
DATALOG_SAFETY_NONE,
DATALOG_SAFETY_STRICT,
DATALOG_SAFETY_LOOSE,
)
from FuXi.Syntax.InfixOWL import Class
from FuXi.Horn.PositiveConditions import (
Exists,
GetUterm,
Or,
SetOperator,
Uniterm,
)
from FuXi.DLP import (
MapDLPtoNetwork,
non_DHL_OWL_Semantics,
)
from FuXi.DLP.ConditionalAxioms import AdditionalRules
from .Util import (
generateTokenSet,
renderNetwork,
xcombine,
)
from rdflib.graph import (
ConjunctiveGraph,
Graph,
ReadOnlyGraphAggregate,
)
from rdflib.namespace import NamespaceManager
from rdflib import (
BNode,
Literal,
Namespace,
RDF,
RDFS,
URIRef,
Variable,
)
from rdflib import py3compat
from rdflib.util import first
from .ReteVocabulary import RETE_NS
from .RuleStore import (
Formula,
N3Builtin,
N3RuleStore,
)
OWL_NS = Namespace("http://www.w3.org/2002/07/owl#")
Any = None
LOG = Namespace("http://www.w3.org/2000/10/swap/log#")
#From itertools recipes
def iteritems(mapping):
return list(zip(iter(mapping.keys()), iter(mapping.values())))
def any(seq, pred=None):
"""Returns True if pred(x) is true for at least one element in the iterable"""
for elem in filter(pred, seq):
return True
return False
class HashablePatternList(object):
"""
A hashable list of N3 statements which are patterns of a rule. Order is disregarded
by sorting based on unicode value of the concatenation of the term strings
(in both triples and function builtins invokations).
This value is also used for the hash. In this way, patterns with the same terms
but in different order are considered equivalent and share the same Rete nodes
>>> nodes = {}
>>> a = HashablePatternList([(Variable('X'), Literal(1), Literal(2))])
>>> nodes[a] = 1
>>> nodes[HashablePatternList([None]) + a] = 2
>>> b = HashablePatternList([(Variable('Y'), Literal(1), Literal(2))])
>>> b in a #doctest: +SKIP
True
>>> a == b #doctest: +SKIP
True
"""
def __init__(self, items=None, skipBNodes=False):
self.skipBNodes = skipBNodes
if items:
self._l = items
else:
self._l = []
def _hashRulePattern(self, item):
"""
Generates a unique hash for RDF triples and N3 builtin invokations. The
hash function consists of the hash of the terms concatenated in order
"""
if isinstance(item, tuple):
return reduce(lambda x, y: x + y, [
i for i in item
if not self.skipBNodes or not isinstance(i, BNode)
])
elif isinstance(item, N3Builtin):
return reduce(lambda x, y: x + y, [item.argument, item.result])
def __len__(self):
return len(self._l)
def __getslice__(self, beginIdx, endIdx):
return HashablePatternList(self._l[beginIdx:endIdx])
def __hash__(self):
if self._l:
_concatPattern = [pattern and self._hashRulePattern(pattern) or "None" for pattern in self._l]
#nulify the impact of order in patterns
_concatPattern.sort()
return hash(reduce(lambda x, y: x + y, _concatPattern))
else:
return hash(None)
def __add__(self, other):
assert isinstance(other, HashablePatternList), other
return HashablePatternList(self._l + other._l)
def __repr__(self):
return repr(self._l)
def extend(self, other):
assert isinstance(other, HashablePatternList), other
self._l.extend(other._l)
def append(self, other):
self._l.append(other)
def __iter__(self):
return iter(self._l)
def __eq__(self, other):
return hash(self) == hash(other)
def _mulPatternWithSubstitutions(tokens, consequent, termNode):
"""
Takes a set of tokens and a pattern and returns an iterator over consequent
triples, created by applying all the variable substitutions in the given tokens against the pattern
>>> aNode = AlphaNode((Variable('S'), Variable('P'), Variable('O')))
>>> token1 = ReteToken((URIRef('urn:uuid:alpha'), OWL_NS.differentFrom, URIRef('urn:uuid:beta')))
>>> token2 = ReteToken((URIRef('urn:uuid:beta'), OWL_NS.differentFrom, URIRef('urn:uuid:alpha')))
>>> token1 = token1.bindVariables(aNode)
>>> token2 = token2.bindVariables(aNode)
>>> inst = PartialInstantiation([token1, token2])
"""
# success = False
for binding in tokens.bindings:
tripleVals = []
# if any(consequent,
# lambda term:isinstance(term, Variable) and term not in binding):# not mismatchedTerms:
# return
# else:
for term in consequent:
if isinstance(term, (Variable, BNode)) and term in binding:
#try:
tripleVals.append(binding[term])
#except:
# pass
else:
tripleVals.append(term)
yield tuple(tripleVals), binding
class InferredGoal(Exception):
def __init__(self, msg):
self.msg = msg
def __repr__(self):
return "Goal inferred.: %" % self.msg
class ReteNetwork:
"""
The Rete network. The constructor takes an N3 rule graph, an identifier (a BNode by default), an
initial Set of Rete tokens that serve as the 'working memory', and an rdflib Graph to
add inferred triples to - by forward-chaining via Rete evaluation algorithm),
"""
def __init__(self, ruleStore, name=None,
initialWorkingMemory=None,
inferredTarget=None,
nsMap={},
graphVizOutFile=None,
dontFinalize=False,
goal=None):
self.leanCheck = {}
self.goal = goal
self.nsMap = nsMap
self.name = name and name or BNode()
self.nodes = {}
self.alphaPatternHash = {}
self.ruleSet = set()
for alphaPattern in xcombine(('1', '0'), ('1', '0'), ('1', '0')):
self.alphaPatternHash[tuple(alphaPattern)] = {}
if inferredTarget is None:
self.inferredFacts = Graph()
namespace_manager = NamespaceManager(self.inferredFacts)
for k, v in list(nsMap.items()):
namespace_manager.bind(k, v)
self.inferredFacts.namespace_manager = namespace_manager
else:
self.inferredFacts = inferredTarget
self.workingMemory = initialWorkingMemory and initialWorkingMemory or set()
self.proofTracers = {}
self.terminalNodes = set()
self.instantiations = {}
start = time.time()
self.ruleStore = ruleStore
self.justifications = {}
self.dischargedBindings = {}
if not dontFinalize:
self.ruleStore._finalize()
self.filteredFacts = Graph()
#'Universal truths' for a rule set are rules where the LHS is empty.
# Rather than automatically adding them to the working set, alpha nodes are 'notified'
# of them, so they can be checked for while performing inter element tests.
self.universalTruths = []
from FuXi.Horn.HornRules import Ruleset
self.rules = set()
self.negRules = set()
for rule in Ruleset(n3Rules=self.ruleStore.rules, nsMapping=self.nsMap):
import warnings
warnings.warn(
"Rules in a network should be built *after* construction via " +
" self.buildNetworkClause(HornFromN3(n3graph)) for instance",
DeprecationWarning, 2)
self.buildNetworkFromClause(rule)
self.alphaNodes = [node for node in list(self.nodes.values()) if isinstance(node, AlphaNode)]
self.alphaBuiltInNodes = [node for node in list(self.nodes.values()) if isinstance(node, BuiltInAlphaNode)]
self._setupDefaultRules()
if initialWorkingMemory:
start = time.time()
self.feedFactsToAdd(initialWorkingMemory)
print("Time to calculate closure on working memory: %s m seconds" % (
(time.time() - start) * 1000))
if graphVizOutFile:
print("Writing out RETE network to ", graphVizOutFile)
renderNetwork(self, nsMap=nsMap).write(graphVizOutFile)
def getNsBindings(self, nsMgr):
for prefix, Uri in nsMgr.namespaces():
self.nsMap[prefix] = Uri
def buildFilterNetworkFromClause(self, rule):
lhs = BNode()
rhs = BNode()
builtins = []
for term in rule.formula.body:
if isinstance(term, N3Builtin):
#We want to move builtins to the 'end' of the body
#so they only apply to the terminal nodes of
#the corresponding network
builtins.append(term)
else:
self.ruleStore.formulae.setdefault(lhs, Formula(lhs)).append(term.toRDFTuple())
for builtin in builtins:
self.ruleStore.formulae.setdefault(lhs, Formula(lhs)).append(builtin.toRDFTuple())
nonEmptyHead = False
for term in rule.formula.head:
nonEmptyHead = True
assert not hasattr(term, 'next')
assert isinstance(term, Uniterm)
self.ruleStore.formulae.setdefault(rhs, Formula(rhs)).append(term.toRDFTuple())
assert nonEmptyHead, "Filters must conclude something."
self.ruleStore.rules.append((self.ruleStore.formulae[lhs], self.ruleStore.formulae[rhs]))
tNode = self.buildNetwork(iter(self.ruleStore.formulae[lhs]),
iter(self.ruleStore.formulae[rhs]),
rule,
aFilter=True)
self.alphaNodes = [node for node in list(self.nodes.values()) if isinstance(node, AlphaNode)]
self.rules.add(rule)
return tNode
def buildNetworkFromClause(self, rule):
lhs = BNode()
rhs = BNode()
builtins = []
for term in rule.formula.body:
if isinstance(term, N3Builtin):
#We want to move builtins to the 'end' of the body
#so they only apply to the terminal nodes of
#the corresponding network
builtins.append(term)
else:
self.ruleStore.formulae.setdefault(lhs, Formula(lhs)).append(term.toRDFTuple())
for builtin in builtins:
self.ruleStore.formulae.setdefault(lhs, Formula(lhs)).append(builtin.toRDFTuple())
nonEmptyHead = False
for term in rule.formula.head:
nonEmptyHead = True
assert not hasattr(term, 'next')
assert isinstance(term, Uniterm)
self.ruleStore.formulae.setdefault(rhs, Formula(rhs)).append(term.toRDFTuple())
if not nonEmptyHead:
import warnings
warnings.warn(
"Integrity constraints (rules with empty heads) are not supported: %s" % rule,
SyntaxWarning, 2)
return
self.ruleStore.rules.append((self.ruleStore.formulae[lhs], self.ruleStore.formulae[rhs]))
tNode = self.buildNetwork(iter(self.ruleStore.formulae[lhs]),
iter(self.ruleStore.formulae[rhs]),
rule)
self.alphaNodes = [node for node in list(self.nodes.values()) if isinstance(node, AlphaNode)]
self.rules.add(rule)
return tNode
def calculateStratifiedModel(self, database):
"""
Stratified Negation Semantics for DLP using SPARQL to handle the negation
"""
if not self.negRules:
return
from FuXi.DLP.Negation import StratifiedSPARQL
# from FuXi.Rete.Magic import PrettyPrintRule
import copy
noNegFacts = 0
for i in self.negRules:
#Evaluate the Graph pattern, and instanciate the head of the rule with
#the solutions returned
nsMapping = dict([(v, k) for k, v in list(self.nsMap.items())])
sel, compiler = StratifiedSPARQL(i, nsMapping)
query = compiler.compile(sel)
i.stratifiedQuery = query
vars = sel.projection
unionClosureG = self.closureGraph(database)
for rt in unionClosureG.query(query):
solutions = {}
if isinstance(rt, tuple):
solutions.update(dict([(vars[idx], i) for idx, i in enumerate(rt)]))
else:
solutions[vars[0]] = rt
i.solutions = solutions
head = copy.deepcopy(i.formula.head)
head.ground(solutions)
fact = head.toRDFTuple()
self.inferredFacts.add(fact)
self.feedFactsToAdd(generateTokenSet([fact]))
noNegFacts += 1
#Now we need to clear assertions that cross the individual, concept, relation divide
# toRemove = []
for s, p, o in self.inferredFacts.triples((None, RDF.type, None)):
if s in unionClosureG.predicates() or\
s in [_s for _s, _p, _o in
unionClosureG.triples_choices(
(None,
RDF.type,
[OWL_NS.Class,
OWL_NS.Restriction]))]:
self.inferredFacts.remove((s, p, o))
return noNegFacts
def setupDescriptionLogicProgramming(self,
owlN3Graph,
expanded=[],
addPDSemantics=True,
classifyTBox=False,
constructNetwork=True,
derivedPreds=[],
ignoreNegativeStratus=False,
safety=DATALOG_SAFETY_NONE):
rt = [rule
for rule in MapDLPtoNetwork(self,
owlN3Graph,
complementExpansions=expanded,
constructNetwork=constructNetwork,
derivedPreds=derivedPreds,
ignoreNegativeStratus=ignoreNegativeStratus,
safety=safety)]
if ignoreNegativeStratus:
rules, negRules = rt
rules = set(rules)
self.negRules = set(negRules)
else:
rules = set(rt)
if constructNetwork:
self.rules.update(rules)
additionalRules = set(AdditionalRules(owlN3Graph))
if addPDSemantics:
from FuXi.Horn.HornRules import HornFromN3
additionalRules.update(HornFromN3(StringIO(non_DHL_OWL_Semantics)))
if constructNetwork:
for rule in additionalRules:
self.buildNetwork(iter(rule.formula.body),
iter(rule.formula.head),
rule)
self.rules.add(rule)
else:
rules.update(additionalRules)
if constructNetwork:
rules = self.rules
# noRules = len(rules)
if classifyTBox:
self.feedFactsToAdd(generateTokenSet(owlN3Graph))
# print("##### DLP rules fired against OWL/RDF TBOX", self)
return rules
def reportSize(self, tokenSizeThreshold=1200, stream=sys.stdout):
for pattern, node in list(self.nodes.items()):
if isinstance(node, BetaNode):
for largeMem in [i for i in iter(node.memories.values()) if len(i) > tokenSizeThreshold]:
if largeMem:
print("Large apha node memory extent: ")
pprint(pattern)
print(len(largeMem))
def reportConflictSet(self, closureSummary=False, stream=sys.stdout):
tNodeOrder = [tNode
for tNode in self.terminalNodes
if self.instantiations.get(tNode, 0)]
tNodeOrder.sort(key=lambda x: self.instantiations[x], reverse=True)
for termNode in tNodeOrder:
print(termNode)
print("\t", termNode.clauseRepresentation())
print("\t\t%s instantiations" % self.instantiations[termNode])
if closureSummary:
print(self.inferredFacts.serialize(
destination=stream, format='turtle'))
def parseN3Logic(self, src):
store = N3RuleStore(additionalBuiltins=self.ruleStore.filters)
Graph(store).parse(src, format='n3')
store._finalize()
assert len(store.rules), "There are no rules passed in."
from FuXi.Horn.HornRules import Ruleset
for rule in Ruleset(n3Rules=store.rules,
nsMapping=self.nsMap):
self.buildNetwork(iter(rule.formula.body),
iter(rule.formula.head),
rule)
self.rules.add(rule)
self.alphaNodes = [node for node in list(self.nodes.values()) if isinstance(node, AlphaNode)]
self.alphaBuiltInNodes = [node for node in list(self.nodes.values()) if isinstance(node, BuiltInAlphaNode)]
def __repr__(self):
total = 0
for node in list(self.nodes.values()):
if isinstance(node, BetaNode):
total += len(node.memories[LEFT_MEMORY])
total += len(node.memories[RIGHT_MEMORY])
return "<Network: %s rules, %s nodes, %s tokens in working memory, %s inferred tokens>" % (
len(self.terminalNodes), len(self.nodes), total, len(self.inferredFacts))
def closureGraph(self, sourceGraph, readOnly=True, store=None):
if readOnly:
if store is None and not sourceGraph:
store = Graph().store
store = store is None and sourceGraph.store or store
roGraph = ReadOnlyGraphAggregate([sourceGraph, self.inferredFacts],
store=store)
roGraph.namespace_manager = NamespaceManager(roGraph)
for srcGraph in [sourceGraph, self.inferredFacts]:
for prefix, uri in srcGraph.namespaces():
roGraph.namespace_manager.bind(prefix, uri)
return roGraph
else:
cg = ConjunctiveGraph()
cg += sourceGraph
cg += self.inferredFacts
return cg
def _setupDefaultRules(self):
"""
Checks every alpha node to see if it may match against a 'universal truth' (one w/out a LHS)
"""
for node in list(self.nodes.values()):
if isinstance(node, AlphaNode):
node.checkDefaultRule(self.universalTruths)
def clear(self):
self.nodes = {}
self.alphaPatternHash = {}
self.rules = set()
for alphaPattern in xcombine(('1', '0'), ('1', '0'), ('1', '0')):
self.alphaPatternHash[tuple(alphaPattern)] = {}
self.proofTracers = {}
self.terminalNodes = set()
self.justifications = {}
self._resetinstantiationStats()
self.workingMemory = set()
self.dischargedBindings = {}
def reset(self, newinferredFacts=None):
"Reset the network by emptying the memory associated with all Beta Nodes nodes"
for node in list(self.nodes.values()):
if isinstance(node, BetaNode):
node.memories[LEFT_MEMORY].reset()
node.memories[RIGHT_MEMORY].reset()
self.justifications = {}
self.proofTracers = {}
self.inferredFacts = newinferredFacts if newinferredFacts is not None else Graph()
self.workingMemory = set()
self._resetinstantiationStats()
def fireConsequent(self, tokens, termNode, debug=False):
"""
"In general, a p-node also contains a specifcation of what production it corresponds to | the
name of the production, its right-hand-side actions, etc. A p-node may also contain information
about the names of the variables that occur in the production. Note that variable names
are not mentioned in any of the Rete node data structures we describe in this chapter. This is
intentional |it enables nodes to be shared when two productions have conditions with the same
basic form, but with different variable names."
Takes a set of tokens and the terminal Beta node they came from
and fires the inferred statements using the patterns associated
with the terminal node. Statements that have been previously inferred
or already exist in the working memory are not asserted
"""
if debug:
print("%s from %s" % (tokens, termNode))
# newTokens = []
termNode.instanciatingTokens.add(tokens)
def iterCondition(condition):
if isinstance(condition, Exists):
return condition.formula
return isinstance(condition, SetOperator) and condition or iter([condition])
def extractVariables(term, existential=True):
if isinstance(term, existential and BNode or Variable):
yield term
elif isinstance(term, Uniterm):
for t in term.toRDFTuple():
if isinstance(t, existential and BNode or Variable):
yield t
#replace existentials in the head with new BNodes!
BNodeReplacement = {}
for rule in termNode.rules:
if isinstance(rule.formula.head, Exists):
for bN in rule.formula.head.declare:
if not isinstance(rule.formula.body, Exists) or \
bN not in rule.formula.body.declare:
BNodeReplacement[bN] = BNode()
for rhsTriple in termNode.consequent:
if BNodeReplacement:
rhsTriple = tuple([BNodeReplacement.get(term, term) for term in rhsTriple])
if debug:
if not tokens.bindings:
tokens._generateBindings()
key = tuple([None if isinstance(item, BNode) else item for item in rhsTriple])
override, executeFn = termNode.executeActions.get(key, (None, None))
if override:
#There is an execute action associated with this production
#that is attaced to the given consequent triple and
#is meant to perform all of the production duties
#(bypassing the inference of triples, etc.)
executeFn(termNode, None, tokens, None, debug)
else:
for inferredTriple, binding in _mulPatternWithSubstitutions(tokens, rhsTriple, termNode):
if [term for term in inferredTriple if isinstance(term, Variable)]:
#Unfullfilled bindings (skip non-ground head literals)
if executeFn:
#The indicated execute action is supposed to be triggered
#when the indicates RHS triple is inferred for the
#(even if it is not ground)
executeFn(termNode, inferredTriple, tokens, binding, debug)
continue
# if rhsTriple[1].find('subClassOf_derived')+1:import pdb;pdb.set_trace()
inferredToken = ReteToken(inferredTriple)
self.proofTracers.setdefault(inferredTriple, []).append(binding)
self.justifications.setdefault(inferredTriple, set()).add(termNode)
if termNode.filter and inferredTriple not in self.filteredFacts:
self.filteredFacts.add(inferredTriple)
if inferredTriple not in self.inferredFacts and inferredToken not in self.workingMemory:
# if (rhsTriple == (Variable('A'), RDFS.RDFSNS['subClassOf_derived'], Variable('B'))):
# import pdb;pdb.set_trace()
if debug:
print("Inferred triple: ", inferredTriple, " from ", termNode.clauseRepresentation())
inferredToken.debug = True
self.inferredFacts.add(inferredTriple)
self.addWME(inferredToken)
currIdx = self.instantiations.get(termNode, 0)
currIdx += 1
self.instantiations[termNode] = currIdx
if executeFn:
#The indicated execute action is supposed to be triggered
#when the indicates RHS triple is inferred for the
#first time
executeFn(termNode, inferredTriple, tokens, binding, debug)
if self.goal is not None and self.goal in self.inferredFacts:
raise InferredGoal("Proved goal " + repr(self.goal))
else:
if debug:
print("Inferred triple skipped: ", inferredTriple)
if executeFn:
#The indicated execute action is supposed to be triggered
#when the indicates RHS triple is inferred for the
#first time
executeFn(termNode, inferredTriple, tokens, binding, debug)
def addWME(self, wme):
"""
procedure add-wme (w: WME) exhaustive hash table versiong
let v1, v2, and v3 be the symbols in the three fields of w
alpha-mem = lookup-in-hash-table (v1, v2, v3)
if alpha-mem then alpha-memory-activation (alpha-mem, w)
alpha-mem = lookup-in-hash-table (v1, v2, *)
if alpha-mem then alpha-memory-activation (alpha-mem, w)
alpha-mem = lookup-in-hash-table (v1, *, v3)
if alpha-mem then alpha-memory-activation (alpha-mem, w)
...
alpha-mem = lookup-in-hash-table (*, *, *)
if alpha-mem then alpha-memory-activation (alpha-mem, w)
end
"""
# print(wme.asTuple())
for termComb, termDict in iteritems(self.alphaPatternHash):
for alphaNode in termDict.get(wme.alphaNetworkHash(termComb), []):
# print("\t## Activated AlphaNode ##")
# print("\t\t", termComb, wme.alphaNetworkHash(termComb))
# print("\t\t", alphaNode)
alphaNode.activate(wme.unboundCopy())
def feedFactsToAdd(self, tokenIterator):
"""
Feeds the network an iterator of facts / tokens which are fed to the alpha nodes
which propagate the matching process through the network
"""
for token in tokenIterator:
self.workingMemory.add(token)
# print(token.unboundCopy().bindingDict)
self.addWME(token)
def _findPatterns(self, patternList):
rt = []
for betaNodePattern, alphaNodePatterns in \
[(patternList.__getslice__(0, -i), patternList.__getslice__(-i, len(patternList))) for i in range(1, len(patternList))]:
# [(patternList[:-i], patternList[-i:]) for i in xrange(1, len(patternList))]:
assert isinstance(betaNodePattern, HashablePatternList)
assert isinstance(alphaNodePatterns, HashablePatternList)
if betaNodePattern in self.nodes:
rt.append(betaNodePattern)
rt.extend([HashablePatternList([aPattern]) for aPattern in alphaNodePatterns])
return rt
for alphaNodePattern in patternList:
rt.append(HashablePatternList([alphaNodePattern]))
return rt
def createAlphaNode(self, currentPattern):
"""
"""
if isinstance(currentPattern, N3Builtin):
node = BuiltInAlphaNode(currentPattern)
else:
node = AlphaNode(currentPattern, self.ruleStore.filters)
self.alphaPatternHash[node.alphaNetworkHash()].setdefault(node.alphaNetworkHash(groundTermHash=True), []).append(node)
if not isinstance(node, BuiltInAlphaNode) and node.builtin:
s, p, o = currentPattern
node = BuiltInAlphaNode(N3Builtin(p, self.ruleStore.filters[p](s, o), s, o))
return node
def _resetinstantiationStats(self):
self.instantiations = dict([(tNode, 0) for tNode in self.terminalNodes])
def checkDuplicateRules(self):
checkedClauses = {}
for tNode in self.terminalNodes:
for rule in tNode.rules:
collision = checkedClauses.get(rule.formula)
assert collision is None, "%s collides with %s" % (
tNode, checkedClauses[rule.formula])
checkedClauses.setdefault(tNode.rule.formula, []).append(tNode)
def registerReteAction(self, headTriple, override, executeFn):
"""
Register the given execute function for any rule with the
given head using the override argument to determine whether or
not the action completely handles the firing of the rule.
The signature of the execute action is as follows:
def someExecuteAction(tNode, inferredTriple, token, binding):
.. pass ..
"""
for tNode in self.terminalNodes:
for rule in tNode.rules:
if not isinstance(rule.formula.head, (Exists, Uniterm)):
continue
headTriple = GetUterm(rule.formula.head).toRDFTuple()
headTriple = tuple(
[None if isinstance(item, BNode) else item for item in headTriple])
tNode.executeActions[headTriple] = (override, executeFn)
def buildNetwork(self, lhsIterator, rhsIterator, rule, aFilter=False):
"""
Takes an iterator of triples in the LHS of an N3 rule and an iterator of the RHS and extends
the Rete network, building / reusing Alpha
and Beta nodes along the way (via a dictionary mapping of patterns to the built nodes)
"""
matchedPatterns = HashablePatternList()
attachedPatterns = []
# hasBuiltin = False
LHS = []
while True:
try:
currentPattern = next(lhsIterator) if py3compat.PY3 else lhsIterator.next()
#The LHS isn't done yet, stow away the current pattern
#We need to convert the Uniterm into a triple
if isinstance(currentPattern, Uniterm):
currentPattern = currentPattern.toRDFTuple()
LHS.append(currentPattern)
except StopIteration:
#The LHS is done, need to initiate second pass to recursively build join / beta
#nodes towards a terminal node
#We need to convert the Uniterm into a triple
consequents = [isinstance(fact, Uniterm) and fact.toRDFTuple() or fact for fact in rhsIterator]
if matchedPatterns and matchedPatterns in self.nodes:
attachedPatterns.append(matchedPatterns)
elif matchedPatterns:
rt = self._findPatterns(matchedPatterns)
attachedPatterns.extend(rt)
if len(attachedPatterns) == 1:
node = self.nodes[attachedPatterns[0]]
if isinstance(node, BetaNode):
terminalNode = node
else:
paddedLHSPattern = HashablePatternList([None]) + attachedPatterns[0]
terminalNode = self.nodes.get(paddedLHSPattern)
if terminalNode is None:
#New terminal node
terminalNode = BetaNode(None, node, aPassThru=True)
self.nodes[paddedLHSPattern] = terminalNode
node.connectToBetaNode(terminalNode, RIGHT_MEMORY)
terminalNode.consequent.update(consequents)
terminalNode.rules.add(rule)
terminalNode.antecedent = rule.formula.body
terminalNode.network = self
terminalNode.headAtoms.update(rule.formula.head)
terminalNode.filter = aFilter
self.terminalNodes.add(terminalNode)
else:
moveToEnd = []
# endIdx = len(attachedPatterns) - 1
finalPatternList = []
for idx, pattern in enumerate(attachedPatterns):
assert isinstance(pattern, HashablePatternList), repr(pattern)
currNode = self.nodes[pattern]
if (isinstance(currNode, BuiltInAlphaNode) or
isinstance(currNode, BetaNode) and currNode.fedByBuiltin):
moveToEnd.append(pattern)
else:
finalPatternList.append(pattern)
terminalNode = self.attachBetaNodes(chain(finalPatternList, moveToEnd))
terminalNode.consequent.update(consequents)
terminalNode.rules.add(rule)
terminalNode.antecedent = rule.formula.body
terminalNode.network = self
terminalNode.headAtoms.update(rule.formula.head)
terminalNode.filter = aFilter
self.terminalNodes.add(terminalNode)
self._resetinstantiationStats()
#self.checkDuplicateRules()
return terminalNode
if HashablePatternList([currentPattern]) in self.nodes:
#Current pattern matches an existing alpha node
matchedPatterns.append(currentPattern)
elif matchedPatterns in self.nodes:
#preceding patterns match an existing join/beta node
newNode = self.createAlphaNode(currentPattern)
if len(matchedPatterns) == 1 \
and HashablePatternList([None]) + matchedPatterns in self.nodes:
existingNode = self.nodes[HashablePatternList([None]) + matchedPatterns]
newBetaNode = BetaNode(existingNode, newNode)
self.nodes[HashablePatternList([None]) + \
matchedPatterns + \
HashablePatternList([currentPattern])] = newBetaNode
matchedPatterns = HashablePatternList([None]) + \
matchedPatterns + \
HashablePatternList([currentPattern])
else:
existingNode = self.nodes[matchedPatterns]
newBetaNode = BetaNode(existingNode, newNode)
self.nodes[matchedPatterns + \
HashablePatternList([currentPattern])] = newBetaNode
matchedPatterns.append(currentPattern)
self.nodes[HashablePatternList([currentPattern])] = newNode
newBetaNode.connectIncomingNodes(existingNode, newNode)
#Extend the match list with the current pattern and add it
#to the list of attached patterns for the second pass
attachedPatterns.append(matchedPatterns)
matchedPatterns = HashablePatternList()
else:
#The current pattern is not in the network and the match list isn't
#either. Add an alpha node
newNode = self.createAlphaNode(currentPattern)
self.nodes[HashablePatternList([currentPattern])] = newNode
#Add to list of attached patterns for the second pass
attachedPatterns.append(HashablePatternList([currentPattern]))
def attachBetaNodes(self, patternIterator, lastBetaNodePattern=None):
"""
The second 'pass' in the Rete network compilation algorithm:
Attaches Beta nodes to the alpha nodes associated with all the patterns
in a rule's LHS recursively towards a 'root' Beta node - the terminal node
for the rule. This root / terminal node is returned
"""
try:
nextPattern = next(patternIterator) if py3compat.PY3 else patternIterator.next()
except StopIteration:
assert lastBetaNodePattern
if lastBetaNodePattern:
return self.nodes[lastBetaNodePattern]
else:
assert len(self.universalTruths), "should be empty LHSs"
terminalNode = BetaNode(None, None, aPassThru=True)
self.nodes[HashablePatternList([None])] = terminalNode
return terminalNode # raise Exception("Ehh. Why are we here?")
if lastBetaNodePattern:
firstNode = self.nodes[lastBetaNodePattern]
secondNode = self.nodes[nextPattern]
newBNodePattern = lastBetaNodePattern + nextPattern
newBetaNode = BetaNode(firstNode, secondNode)
self.nodes[newBNodePattern] = newBetaNode
else:
firstNode = self.nodes[nextPattern]
oldAnchor = self.nodes.get(HashablePatternList([None]) + nextPattern)
if not oldAnchor:
if isinstance(firstNode, AlphaNode):
newfirstNode = BetaNode(None, firstNode, aPassThru=True)
newfirstNode.connectIncomingNodes(None, firstNode)
self.nodes[HashablePatternList([None]) + nextPattern] = newfirstNode
else:
newfirstNode = firstNode
else:
newfirstNode = oldAnchor
firstNode = newfirstNode
secondPattern = next(patternIterator) if py3compat.PY3 else patternIterator.next()
secondNode = self.nodes[secondPattern]
newBetaNode = BetaNode(firstNode, secondNode)
newBNodePattern = HashablePatternList([None]) + nextPattern + secondPattern
self.nodes[newBNodePattern] = newBetaNode
newBetaNode.connectIncomingNodes(firstNode, secondNode)
return self.attachBetaNodes(patternIterator, newBNodePattern)
def ComplementExpand(tBoxGraph, complementAnnotation):
complementExpanded = []
for negativeClass in tBoxGraph.subjects(predicate=OWL_NS.complementOf):
containingList = first(tBoxGraph.subjects(RDF.first, negativeClass))
prevLink = None
while containingList:
prevLink = containingList
containingList = first(tBoxGraph.subjects(RDF.rest, containingList))
if prevLink:
for s, p, o in tBoxGraph.triples_choices((None,
[OWL_NS.intersectionOf,
OWL_NS.unionOf],
prevLink)):
if (s, complementAnnotation, None) in tBoxGraph:
continue
_class = Class(s)
complementExpanded.append(s)
print("Added %s to complement expansion" % _class)
ComplementExpansion(_class)
def test():
import doctest
doctest.testmod()
if __name__ == '__main__':
test()
# from FuXi.Rete.Network import iteritems
# from FuXi.Rete.Network import any
# from FuXi.Rete.Network import ComplementExpand
# from FuXi.Rete.Network import HashablePatternList
# from FuXi.Rete.Network import InferredGoal
# from FuXi.Rete.Network import ReteNetwork
| 44.182692 | 132 | 0.58363 |
6dc7ac77f93802122ddb1e47bec4538126c006a2 | 500 | py | Python | gcpy/functions/HTTPFunction.py | MaximBazarov/gcpy | 92c1d31a8133e19a5d2b27dc8f2e0b7e8fe1d609 | [
"MIT"
] | 1 | 2020-07-29T11:20:35.000Z | 2020-07-29T11:20:35.000Z | gcpy/functions/HTTPFunction.py | MaximBazarov/gcpy | 92c1d31a8133e19a5d2b27dc8f2e0b7e8fe1d609 | [
"MIT"
] | null | null | null | gcpy/functions/HTTPFunction.py | MaximBazarov/gcpy | 92c1d31a8133e19a5d2b27dc8f2e0b7e8fe1d609 | [
"MIT"
] | null | null | null | from gcpy.functions.CloudFunction import CloudFunctionTrigger, CloudFunction
from gcpy.utils.binary import binary_decode
class HTTPTrigger(CloudFunctionTrigger):
pass
class HTTPFunction(CloudFunction):
name = 'function_public_name'
trigger = HTTPTrigger()
def handle(self, request):
print('Handling {}'.format(request))
@staticmethod
def body(request):
result = request.data
if not result:
return
return binary_decode(result)
| 22.727273 | 76 | 0.7 |
6dcbed133eb3a7b3cdb7874d0063d3eca6ce4f69 | 792 | py | Python | flask_sqlalchemy/app.py | andreeaionescu/graphql-example | ceeff3888ea87312d4df138093d7f6fcaa1ae973 | [
"MIT"
] | null | null | null | flask_sqlalchemy/app.py | andreeaionescu/graphql-example | ceeff3888ea87312d4df138093d7f6fcaa1ae973 | [
"MIT"
] | null | null | null | flask_sqlalchemy/app.py | andreeaionescu/graphql-example | ceeff3888ea87312d4df138093d7f6fcaa1ae973 | [
"MIT"
] | null | null | null | '''
Unlike a RESTful API, there is only a single URL from which GraphQL is accessed.
We are going to use Flask to create a server that expose the GraphQL schema under /graphql and a interface for querying
it easily: GraphiQL (also under /graphql when accessed by a browser).
'''
from flask import Flask
from flask_graphql import GraphQLView
from flask_sqlalchemy.models import db_session
from flask_sqlalchemy.schema import schema, Department
app = Flask(__name__)
app.debug = True
app.add_url_rule(
'/graphql',
view_func=GraphQLView.as_view(
'graphql',
schema=schema,
graphiql=True # for having the GraphiQL interface
)
)
@app.teardown_appcontext
def shutdown_session(exception=None):
db_session.remove()
if __name__ == '__main__':
app.run() | 26.4 | 119 | 0.744949 |
6dcd1f0147fa6de6eaa3f0bce8b1c9dccea62eb4 | 1,305 | py | Python | The HackerRank Interview Preparation Kit/6 - Greedy Algorithms/Reverse Shuffle Merge.py | sohammanjrekar/HackerRank | 1f5010133a1ac1e765e855a086053c97d9e958be | [
"MIT"
] | null | null | null | The HackerRank Interview Preparation Kit/6 - Greedy Algorithms/Reverse Shuffle Merge.py | sohammanjrekar/HackerRank | 1f5010133a1ac1e765e855a086053c97d9e958be | [
"MIT"
] | null | null | null | The HackerRank Interview Preparation Kit/6 - Greedy Algorithms/Reverse Shuffle Merge.py | sohammanjrekar/HackerRank | 1f5010133a1ac1e765e855a086053c97d9e958be | [
"MIT"
] | null | null | null | #
# Complete the 'reverseShuffleMerge' function below.
#
# The function is expected to return a STRING.
# The function accepts STRING s as parameter.
#
import os
from collections import defaultdict
def frequency(s):
result = defaultdict(int)
for char in s:
result[char] += 1
return result
def reverseShuffleMerge(s):
# Write your code here
char_frequency = frequency(s)
used_chars = defaultdict(int)
remain_chars = dict(char_frequency)
result = []
def can_use(char):
return (char_frequency[char] // 2 - used_chars[char]) > 0
def can_pop(char):
needed_chars = char_frequency[char] // 2
return used_chars[char] + remain_chars[char] - 1 >= needed_chars
for char in reversed(s):
if can_use(char):
while result and result[-1] > char and can_pop(result[-1]):
removed_char = result.pop()
used_chars[removed_char] -= 1
used_chars[char] += 1
result.append(char)
remain_chars[char] -= 1
return "".join(result)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = reverseShuffleMerge(s)
fptr.write(result + '\n')
fptr.close()
| 24.166667 | 73 | 0.596169 |
6dcf6d8a2796f5c3d07f258930f33ef3e7528467 | 4,021 | py | Python | src/skansensor/datacollector.py | fadykuzman/Rodeo-App | 2972b371ed38fad4f93e6afcb699b51cec865510 | [
"BSD-3-Clause"
] | null | null | null | src/skansensor/datacollector.py | fadykuzman/Rodeo-App | 2972b371ed38fad4f93e6afcb699b51cec865510 | [
"BSD-3-Clause"
] | null | null | null | src/skansensor/datacollector.py | fadykuzman/Rodeo-App | 2972b371ed38fad4f93e6afcb699b51cec865510 | [
"BSD-3-Clause"
] | null | null | null | """
This class searches for data in a hierarchy of folders and sorts
them in a list.
Attributes to the data are:
path: path to the raw data file
type: whether from Picarro, DropSense sensors.
data: the data set after reading with the modules:
read_dropsense
read_picarro
Please refer to the documentation of the above data
reading modules to know the data structure of the
resultant datasets
"""
import os
from collections import namedtuple
import skansensor.skansensor as ss
class DataCollector:
dir_list = []
def __init__(self):
pass
def get_files(self, path = '.'):
"""
Loops through a folder hierarchy from a given path.
If no path is given, it searches through the current
directory.
The method returns a namedtuple of:
path, kind of file/folder, and if a file, the extension
Parameters:
-------------
path: path to the parent directory to loop through.
Default is current directory
returns:
-------------
dir_list: a list of all files or folders as a namedtuple.
Attributes of the namedtuple are:
path: path to file or folder
whatis: dir or data
whatext: what extension the data file has.
(only dropsense and picarro)
"""
# Opens an instance of a directory
with os.scandir(path) as it:
# loop through all items in a directory
for entry in it:
cat = namedtuple('cat', ['path', 'whatis', 'whatext'])
if entry.is_dir():
cat.path = entry.path
cat.whatis = 'dir'
self.dir_list.append(cat)
self.get_files(cat.path)
else:
filename, fileext = os.path.splitext(entry.path)
if (
(fileext == '.mta')
or (fileext == '.mtc')
or (fileext == '.mtzc')
):
cat.path = entry.path
cat.whatis = 'data'
cat.whatext = fileext
self.dir_list.append(cat)
elif fileext == '.dat':
cat.path = entry.path
cat.whatis = 'data'
cat.whatext = fileext
self.dir_list.append(cat)
else:
pass
return self.dir_list
def collect(self, dir_list):
"""
Parameters:
------------
dir_list: the list of files and folders.
Expected the result of the method get_files()
returns:
------------
data_list: a list of dictionaries that contain data read
from data files.
Refer to 'skansensor' module for the data structure.
"""
datalist = []
for a in dir_list:
if a.whatis == 'data':
if (a.whatext == '.mta') or (a.whatext == '.mtc') or (a.whatext == '.mtzc'):
d = {
'path' : a.path,
'type' : 'dropsense',
'data' : ss.read_dropsense(a.path)
}
elif a.whatext == '.dat':
d = {
'path' : a.path,
'type' : 'picarro',
'data' : ss.read_picarro(a.path)
}
if d not in datalist:
datalist.append(d)
return datalist
| 36.225225 | 92 | 0.437453 |
6dd2944b2ee1fbe92298d2147e16828378aa049e | 2,794 | py | Python | sonypyapi.py | Johannes-Vitt/sonypiapi | 74c347d8bdb05fe8955dd4478ecfdc19cfd4ec03 | [
"MIT"
] | 2 | 2017-05-12T11:23:48.000Z | 2021-06-12T09:38:24.000Z | sonypyapi.py | Johannes-Vitt/sonypiapi | 74c347d8bdb05fe8955dd4478ecfdc19cfd4ec03 | [
"MIT"
] | null | null | null | sonypyapi.py | Johannes-Vitt/sonypiapi | 74c347d8bdb05fe8955dd4478ecfdc19cfd4ec03 | [
"MIT"
] | null | null | null | #!/usr/bin/python
import sys
import json
import urllib2
import collections
url = "http://192.168.122.1:8080/sony/"
camera_url = url+"camera"
avContent_url = url+"avContent"
def create_params_dict(method,params=[],id_=1,version="1.0"):
params = collections.OrderedDict([
("method", method),
("params", params),
("id", id_),
("version", version)])
return params
def api_call(url,params):
return urllib2.urlopen(url,json.dumps(params))
def cast_params(param_list):
#first object on param list ist method name, second the first param for api
#call api_call for getMethodTypes
#cast type for every argument on the param list
## try:
parameter_types = json.load(api_call(camera_url,list_of_method_types()))
for i in parameter_types["results"]:
if(i[0]==param_list[0]):
if (i[1]!=None):
for counter, to_type in enumerate(i[1]):
param_list[counter+1] = cast(param_list[counter+1],to_type)
## except:
## parameter_types = json.load(api_call(avContent_url,list_of_method_types()))
## for i in parameter_types["results"]:
## if(param_list != []):
## if(i[0]==param_list[0]):
## if (i[1]!=None):
## for counter, to_tpye in enumerate(i[1]):
## param_list[counter+1] = cast(param_list[counter+1],to_type)
return param_list
def cast(value, to_type):
if (to_type=="int"):
return int(value)
if (to_type=="bool"):
return bool(value)
if (to_type=="string"):
return str(value)
if (to_type=="int*"):
help_int = []
for i in value:
help_int.append(int(i))
return help_int
if (to_type=="string*"):
help_string = []
for i in value:
help_string.append(str(i))
return help_string
if (to_type=="bool*"):
help_bool = []
for i in value:
help_bool.append(bool(i))
return help_bool
def list_of_method_types():
params_for_api_call = collections.OrderedDict([
("method", "getMethodTypes"),
("params", ["1.0"]),
("id", 1),
("version", "1.0")])
return params_for_api_call
def command_line_call():
if(len(sys.argv)==1):
raw_params = ["getAvailableApiList"]
else:
raw_params = sys.argv[1:]
clean_params = cast_params(raw_params)
if(len(clean_params)>1):
params_for_api_call = create_params_dict(clean_params[0],clean_params[1:])
else:
params_for_api_call = create_params_dict(clean_params[0])
print api_call(camera_url,params_for_api_call).read()
command_line_call()
| 29.410526 | 89 | 0.586256 |
6dd2c58e17cfa913515f063e288c4ff6d601590c | 875 | py | Python | pybuildtool/core/context.py | dozymoe/PyBuildTool | d938a8d6335b801e102159e82a6e0002dfaa1b1a | [
"MIT"
] | 5 | 2017-02-10T07:54:49.000Z | 2017-07-11T09:14:26.000Z | pybuildtool/core/context.py | dozymoe/PyBuildTool | d938a8d6335b801e102159e82a6e0002dfaa1b1a | [
"MIT"
] | null | null | null | pybuildtool/core/context.py | dozymoe/PyBuildTool | d938a8d6335b801e102159e82a6e0002dfaa1b1a | [
"MIT"
] | 1 | 2017-05-21T20:35:10.000Z | 2017-05-21T20:35:10.000Z | import os
from waflib import Context, Errors # pylint:disable=import-error
class WatchContext(Context.Context):
cmd = 'watch'
fun = 'watch'
variant = ''
def __init__(self, **kw):
super().__init__(**kw)
self.top_dir = kw.get('top_dir', Context.top_dir)
self.out_dir = kw.get('out_dir', Context.out_dir)
if not(os.path.isabs(self.top_dir) and os.path.isabs(self.out_dir)):
raise Errors.WafError('The project was not configured: ' +\
'run "waf configure" first!')
self.path = self.srcnode = self.root.find_dir(self.top_dir)
self.bldnode = self.root.make_node(self.variant_dir)
def get_variant_dir(self):
if not self.variant:
return self.out_dir
return os.path.join(self.out_dir, self.variant)
variant_dir = property(get_variant_dir, None)
| 31.25 | 76 | 0.637714 |
6dd3236b3617415b5e5c4905e33da2de283601a4 | 3,151 | py | Python | FindJenkins.py | realsanjay/DomainRecon_old | 936f66404c1a4163b119afc06dca03e588c0756e | [
"MIT"
] | 100 | 2018-04-06T13:50:57.000Z | 2018-10-01T14:33:46.000Z | FindJenkins.py | realsanjay/DomainRecon_old | 936f66404c1a4163b119afc06dca03e588c0756e | [
"MIT"
] | 3 | 2018-12-06T04:54:24.000Z | 2021-02-25T14:59:21.000Z | FindJenkins.py | realsanjay/DomainRecon_old | 936f66404c1a4163b119afc06dca03e588c0756e | [
"MIT"
] | 16 | 2018-10-09T13:50:14.000Z | 2021-09-01T06:53:34.000Z | import sys
import re
import requests
import requests.cookies
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
from time import sleep
from GlobalVariables import *
class FindJenkins(object):
def __init__(self):
super(FindJenkins, self).__init__()
self.globalVariables=GlobalVariables()
self.session = requests.Session()
def GetUser(self,IP,PORT,FILE,CRUMB):
URL = "http://"+IP+":"+PORT+""+FILE+""
paramsPost = {"Jenkins-Crumb":""+CRUMB+"","json":"{\"script\": \"println new ProcessBuilder(\\\"sh\\\",\\\"-c\\\",\\\"whoami\\\").redirectErrorStream(true).start().text\", \"\": \"\\\"\", \"Jenkins-Crumb\": \"4aa6395666702e283f9f3727c4a6df12\"}","Submit":"Run","script":"println new ProcessBuilder(\"sh\",\"-c\",\"whoami\").redirectErrorStream(true).start().text"}
headers = {"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Upgrade-Insecure-Requests":"1","User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0","Connection":"close","Accept-Language":"en-GB,en;q=0.5","Accept-Encoding":"gzip, deflate","Referer":URL,"Content-Type":"application/x-www-form-urlencoded"}
response = self.session.post(URL, data=paramsPost, headers=headers, timeout=15, verify=False)
result = response.text
user = re.compile('<h2>Result</h2><pre>(.+?)\n').findall(response.text)[0]
return user
def TestJenkins(self, IP,PORT):
FILE="/script"
URL = "http://"+IP+":"+PORT+""+FILE+""
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0","Connection":"close","Accept-Language":"en-US,en;q=0.5","Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Upgrade-Insecure-Requests":"1"}
response = self.session.get(URL, headers=headers, timeout=15, verify=False)
if "Jenkins" in response.text:
print "found"
if 'Jenkins-Crumb' in response.text:
CRUMB = re.compile('Jenkins-Crumb", "(.+?)"').findall(response.text)[0]
GetUser(IP,PORT,FILE,CRUMB)
else:
GetUser(IP,PORT,FILE,"")
else:
print "Not Found"
def EnumerateIPToFindJenkins(self, domain):
outUpIP="{}{}/{}".format(self.globalVariables.outputDir, domain, "upIP.txt")
outUpIPWithPort="{}{}/{}".format(self.globalVariables.outputDir, domain, "upIPWithPort.txt")
outIPv4Ranges="{}{}/{}".format(self.globalVariables.outputDir, domain, "ipv4ranges.txt")
self.globalVariables.CommandExecutor("nmap -sP -iL {} | grep -E -o '([0-9]{{1,3}}[\\.]){{3}}[0-9]{{1,3}}' > {}".format(outIPv4Ranges, outUpIP))
self.globalVariables.CommandExecutor("nmap -p8080,8081 -iL {} | grep -E -o '([0-9]{{1,3}}[\\.]){{3}}[0-9]{{1,3}}' | sort | uniq > {}".format(outUpIP, outUpIPWithPort))
#self.outIPv6Ranges="{}{}/{}".format(self.globalVariables.outputDir, domain, "ipv6ranges.txt")
upHostFile = open(outUpIPWithPort, "r")
for host in upHostFile:
try:
self.TestJenkins(host.strip(), '8080')
except:
print host.strip() + ": Not find"
try:
self.TestJenkins(host.strip(), '8081')
except:
print host.strip() + ": Not find" | 53.40678 | 369 | 0.679467 |
6dd35f03ff9bc671f79e8585b1d7db025e32de94 | 115 | py | Python | tests/conftest.py | techjacker/sitemapgenerator | 512d6ea6f36ac661d3e0b1275a055c381b0ce455 | [
"MIT"
] | null | null | null | tests/conftest.py | techjacker/sitemapgenerator | 512d6ea6f36ac661d3e0b1275a055c381b0ce455 | [
"MIT"
] | null | null | null | tests/conftest.py | techjacker/sitemapgenerator | 512d6ea6f36ac661d3e0b1275a055c381b0ce455 | [
"MIT"
] | null | null | null | import pytest
from pytest_httpbin.plugin import httpbin_ca_bundle
pytest.fixture(autouse=True)(httpbin_ca_bundle)
| 23 | 51 | 0.869565 |
6dd36722d7bc153d838406ca8e22b682264cbef0 | 187 | py | Python | freedom/tests/post_test.py | smbdsbrain/wind_of_freedom | b1b19205175db8c824ab5f4b2e8a8e4e2c5d6873 | [
"WTFPL"
] | null | null | null | freedom/tests/post_test.py | smbdsbrain/wind_of_freedom | b1b19205175db8c824ab5f4b2e8a8e4e2c5d6873 | [
"WTFPL"
] | null | null | null | freedom/tests/post_test.py | smbdsbrain/wind_of_freedom | b1b19205175db8c824ab5f4b2e8a8e4e2c5d6873 | [
"WTFPL"
] | null | null | null | from unittest import mock
async def test_post(anonym_client, mocker):
mocker.patch('aioga.GA')
r = await anonym_client.get('v1/wind')
assert r.status == 200, await r.text()
| 23.375 | 43 | 0.695187 |
6dd57794c6789b5f5554c5238dd5b5fff9f2b1a6 | 138 | py | Python | Exercise 10/exercise_code/util/__init__.py | CornellLenard/Deep-Learning-Course-Exercises | db32f2b9ab93a50580e93e9dd83be1db7c4c4a19 | [
"MIT"
] | null | null | null | Exercise 10/exercise_code/util/__init__.py | CornellLenard/Deep-Learning-Course-Exercises | db32f2b9ab93a50580e93e9dd83be1db7c4c4a19 | [
"MIT"
] | null | null | null | Exercise 10/exercise_code/util/__init__.py | CornellLenard/Deep-Learning-Course-Exercises | db32f2b9ab93a50580e93e9dd83be1db7c4c4a19 | [
"MIT"
] | null | null | null | """Util functions"""
from .vis_utils import visualizer
from .save_model import save_model
from .Util import checkParams, checkSize, test
| 23 | 46 | 0.797101 |
6dd5f7a4941e24796fe51eb9276d1b79188a16ea | 15,499 | py | Python | au/fixtures/dataset.py | pwais/au2018 | edd224e5fb649b9f0095ffad39b94f72f73e4853 | [
"Apache-2.0"
] | null | null | null | au/fixtures/dataset.py | pwais/au2018 | edd224e5fb649b9f0095ffad39b94f72f73e4853 | [
"Apache-2.0"
] | 3 | 2019-01-05T22:43:37.000Z | 2019-01-26T05:45:01.000Z | au/fixtures/dataset.py | pwais/au2018 | edd224e5fb649b9f0095ffad39b94f72f73e4853 | [
"Apache-2.0"
] | 1 | 2020-05-03T21:10:03.000Z | 2020-05-03T21:10:03.000Z | import io
import os
from collections import OrderedDict
import imageio
import numpy as np
from au import conf
from au.util import create_log
from au import util
##
## Images
##
class ImageRow(object):
"""For expected usage, see `test_imagerow_demo`"""
# NB: While pyspark uses cloudpickle for *user code*, it uses normal
# pickle for *data*, so the contents of ImageRow instances must be
# pickle-able. I.e. attributes cannot be free functions, since only
# cloudpickle can serialize functions. FMI:
# http://apache-spark-user-list.1001560.n3.nabble.com/pyspark-serializer-can-t-handle-functions-td7650.html
# https://github.com/apache/spark/blob/c3c45cbd76d91d591d98cf8411fcfd30079f5969/python/pyspark/worker.py#L50
# https://github.com/apache/spark/blob/c3c45cbd76d91d591d98cf8411fcfd30079f5969/python/pyspark/worker.py#L359
__slots__ = (
'dataset',
'split',
'uri',
'_image_bytes', # NB: see property image_bytes
'_cached_image_arr', # TODO: use __ for privates .. idk
'_cached_image_fobj',
'_arr_factory', # NB: must be a callable *object*; see above
'label',
'attrs',
# '_label_bytes', # NB: see property label and label_bytes
# '_cached_label',
# '_cached_label_arr',
# '_cached_label_fobj',
)
DEFAULT_PQ_PARTITION_COLS = ['dataset', 'split']
# NB: must be a list and not a tuple due to pyarrow c++ api
# Old pickle API requires __{get,set}state__ for classes that define
# __slots__. Some part of Spark uses this API for serializatio, so we
# provide an impl.
def __getstate__(self):
return {'as_tuple': self.astuple()}
def __setstate__(self, d):
for k, v in zip(self.__slots__, d['as_tuple']):
setattr(self, k, v)
# self._image_bytes = d.get('image_bytes', self._image_bytes)
def __init__(self, **kwargs):
for k in self.__slots__:
setattr(self, k, kwargs.get(k, ''))
if ('_image_bytes' not in kwargs and
kwargs.get('image_bytes', '') is not ''):
self._image_bytes = kwargs['image_bytes']
# if ('_label_bytes' not in kwargs and
# kwargs.get('label_bytes', '') is not ''):
# self._label_bytes = kwargs['label_bytes']
def astuple(self):
return tuple(getattr(self, k) for k in self.__slots__)
def __lt__(self, other):
# Important! Otherwise Python might break ties in unexpected ways
return self.astuple() < other.astuple()
@staticmethod
def from_np_img_labels(np_img, label='', **kwargs):
row = ImageRow(**kwargs)
row._cached_image_arr = np_img
row.label = label
return row
@staticmethod
def wrap_factory(np_img_factory, **kwargs):
row = ImageRow(**kwargs)
row._arr_factory = np_img_factory
return row
@staticmethod
def from_path(path, **kwargs):
# NB: The ImageRow instance will be a flyweight for the image data
row = ImageRow(uri=path, **kwargs)
row._cached_image_fobj = open(path, 'rb')
return row
def to_dict(self):
attrs = []
for k in self.__slots__:
if not k.startswith('_'):
# pyarrow + python 2.7 -> str gets interpreted as binary
# https://stackoverflow.com/a/49507268
# Can skip for python3 ...
v = getattr(self, k)
if isinstance(v, basestring):
v = unicode(v.encode('utf-8'))
attrs.append((k, v))
elif k == '_image_bytes':
attrs.append(('image_bytes', bytearray(self.image_bytes)))
# NB: must be bytearray to support parquet / pyspark type inference
# elif k == '_label_bytes':
# attrs.append(('label_bytes', self.label_bytes))
return OrderedDict(attrs)
def as_numpy(self):
if self._cached_image_arr is '':
if self._arr_factory is not '':
self._cached_image_arr = self._arr_factory()
else:
image_bytes = self.image_bytes
if image_bytes is '':
# Can't make an array
return np.array([])
self._cached_image_arr = imageio.imread(io.BytesIO(image_bytes))
return self._cached_image_arr
@property
def image_bytes(self):
if self._image_bytes is '':
# Read lazily
if self._arr_factory is not '' and self._cached_image_arr is '':
self._cached_image_arr = self._arr_factory()
if self._cached_image_arr is not '':
buf = io.BytesIO()
imageio.imwrite(buf, self._cached_image_arr, format='png')
self._image_bytes = buf.getvalue()
elif self._cached_image_fobj is not '':
self._image_bytes = self._cached_image_fobj.read()
self._cached_image_fobj = ''
return self._image_bytes
# @property
# def label_bytes(self):
# if self._label_bytes is '':
# # Read lazily
# if self._cached_label_arr is not '':
# buf = io.BytesIO()
# imageio.imwrite(buf, self._cached_image_arr, format='png')
# self._image_bytes = buf.getvalue()
# elif self._cached_image_fobj is not '':
# self._image_bytes = self._cached_image_fobj.read()
# self._cached_image_fobj = ''
# return self._image_bytes
#
# @property
# def label(self):
# if self._cached_label is '':
# if self.label_encoding == 'json':
#
#
# if self._label is '':
# # Read lazily
# if self._cached_label_arr is not '':
# buf = io.BytesIO()
# imageio.imwrite(buf, self._cached_label_arr, format='png')
# self._label_bytes = buf.getvalue()
# elif self._cached_label_fobj is not '':
# self._label_bytes = self._cached_label_fobj.read()
# self._cached_label_fobj = ''
# return self._label_bytes
def fname(self):
has_fnamable_label = (
self.label is not '' and
isinstance(self.label, (basestring, int, float)))
toks = (
self.dataset,
self.split,
'label_%s' % str(self.label).replace(' ', '-') if has_fnamable_label else '',
self.uri.split('/')[-1] if self.uri else '',
)
fname = '-'.join(str(tok) for tok in toks if tok) + '.png'
return fname
def to_debug(self, fname=''):
"""Convenience for dumping an image to a place on disk where the user can
view locally (e.g. using Apple Finder file preview, Ubuntu
image browser, an nginx instance pointed at the folder, etc).
FMI see conf.AU_CACHE_TMP
"""
if self.image_bytes == '':
return None
dest = os.path.join(conf.AU_CACHE_TMP, self.fname())
util.mkdir(conf.AU_CACHE_TMP)
with open(dest, 'wb') as f:
f.write(self.image_bytes)
return dest
@staticmethod
def rows_from_images_dir(img_dir, pattern='*', **kwargs):
import pathlib2 as pathlib
log = create_log()
log.info("Reading images from dir %s ..." % img_dir)
paths = pathlib.Path(img_dir).glob(pattern)
n = 0
for path in paths:
path = str(path) # pathlib uses PosixPath thingies ...
yield ImageRow.from_path(path, **kwargs)
n += 1
if (n % 100) == 0:
log.info("... read %s paths ..." % n)
log.info("... read %s total paths." % n)
@staticmethod
def from_pandas(df, **kwargs):
for row in df.to_dict(orient='records'):
row.update(**kwargs)
yield ImageRow(**row)
@staticmethod
def write_to_parquet(
rows,
dest_dir,
rows_per_file=-1,
partition_cols=DEFAULT_PQ_PARTITION_COLS,
compression='lz4',
spark=None):
is_rdd, is_pyspark_df = False, False
try:
import pyspark.rdd
import pyspark.sql
is_rdd = isinstance(rows, pyspark.rdd.RDD)
is_pyspark_df = isinstance(rows, pyspark.sql.dataframe.DataFrame)
if is_pyspark_df:
df = rows
except ImportError:
pass
if is_rdd:
assert spark is not None
from pyspark.sql import Row
# RDD[ImageRow] -> DataFrame[ImageRow]
rows_rdd = rows.map(lambda r: Row(**r.to_dict()))
df = spark.createDataFrame(rows_rdd)
is_pyspark_df = True
if is_pyspark_df:
util.log.info("Writing parquet to %s ..." % dest_dir)
df.printSchema() # NB: can't .show() b/c of binary data
df.write.parquet(
dest_dir,
mode='append',
partitionBy=partition_cols,
compression=compression)
util.log.info("... done! Wrote to %s ." % dest_dir)
else:
# Use Pyarrow to write Parquet in this process
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
log = create_log()
if rows_per_file >= 1:
irows = util.ichunked(rows, rows_per_file)
else:
rows = list(rows)
if not rows:
return
irows = iter([rows])
util.log.info("Writing parquet to %s ..." % dest_dir)
for row_chunk in irows:
r = row_chunk[0]
# Pandas wants dicts
if isinstance(r, ImageRow):
row_chunk = [r.to_dict() for r in row_chunk]
df = pd.DataFrame(row_chunk)
table = pa.Table.from_pandas(df)
util.mkdir(dest_dir)
pq.write_to_dataset(
table,
dest_dir,
partition_cols=partition_cols,
preserve_index=False, # Don't care about pandas index
compression='snappy',
# NB: pyarrow lz4 is totes broken https://github.com/apache/arrow/issues/3491
flavor='spark')
util.log.info("... wrote %s rows ..." % len(row_chunk))
util.log.info("... done writing to %s ." % dest_dir)
@staticmethod
def write_to_pngs(rows, dest_root=None):
dest_root = dest_root or conf.AU_DATA_CACHE
util.log.info("Writing PNGs to %s ..." % dest_root)
n = 0
for row in rows:
dest_dir = os.path.join(
dest_root,
row.dataset or 'default_dataset',
row.split or 'default_split')
util.mkdir(dest_dir)
fname = row.fname()
dest = os.path.join(dest_dir, fname)
with open(dest, 'wb') as f:
f.write(row.image_bytes)
n += 1
if n % 100 == 0:
util.log.info("... write %s PNGs ..." % n)
util.log.info("... wrote %s total PNGs to %s ." % (n, dest_root))
## Ops & Utils
import cv2
def _make_have_target_chan(img, nchan):
shape = img.shape
if len(shape) == 2:
img = np.expand_dims(img, axis=-1)
elif len(shape) != 3:
raise ValueError("Hmm input image has shape: %s" % (shape,))
shape = img.shape
if shape[-1] == nchan:
return img
elif nchan == 1:
if len(shape) == 3 and shape[-1] == 3:
# Make the image greyscale
img2 = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
return np.expand_dims(img2, axis=-1)
else:
raise ValueError("TODO input image has != 3 chan %s" % (shape,))
elif nchan == 3:
if len(shape) == 3 and shape[-1] == 1:
# Repeate the grey channel to create an RGB image
# (or BGR or who knows)
img = np.squeeze(img, axis=-1)
return np.stack([img, img, img], axis=-1)
else:
raise ValueError("TODO input image has != 1 chan %s" % (shape,))
else:
raise ValueError("TODO idk yet %s %s" % (nchan, shape,))
class FillNormalized(object):
def __init__(self, target_hw=None, target_nchan=None, norm_func=None):
self.norm_func = norm_func
self.target_hw = target_hw
self.target_nchan = target_nchan
self.thruput = util.ThruputObserver(
name='FillNormalized',
log_on_del=True)
def __call__(self, row):
self.thruput.start_block()
normalized = row.as_numpy()
bytes_in = normalized.nbytes
if self.target_hw is not None:
h, w = self.target_hw
normalized = cv2.resize(normalized, (w, h)) # Sneaky, opencv!
if self.target_nchan is not None:
normalized = _make_have_target_chan(normalized, self.target_nchan)
if self.norm_func is not None:
normalized = self.norm_func(normalized)
row.attrs = row.attrs or {}
row.attrs.update({
'normalized': normalized,
})
self.thruput.stop_block(n=1, num_bytes=bytes_in)
return row
##
## Tables of images
##
class ImageTable(object):
"""A (partitioned Parquet) table of images (perhaps use one table
per dataset / label type)."""
TABLE_NAME = 'default'
ROWS_PER_FILE = 100
@classmethod
def setup(cls, spark=None):
"""Subclasses should override to create a dataset from scratch
(e.g. download images, create a table, etc). The base class
is just a bunch of images from ImageNet.
"""
if os.path.exists(cls.table_root()):
util.log.info(
"Skipping setup for %s, %s exists." % (
cls.TABLE_NAME, cls.table_root()))
return
rows = ImageRow.rows_from_images_dir(
conf.AU_IMAGENET_SAMPLE_IMGS_DIR,
dataset=cls.TABLE_NAME,
split='__default')
rows = list(rows)
import json
with open(conf.AU_IMAGENET_SAMPLE_LABELS_PATH, 'rb') as f:
fname_to_label = json.load(f)
for row in rows:
fname = row.uri.split('/')[-1]
row.label = fname_to_label[fname]
cls.save_to_image_table(rows)
@classmethod
def table_root(cls):
return os.path.join(conf.AU_TABLE_CACHE, cls.TABLE_NAME)
@classmethod
def save_to_image_table(cls, rows):
dest = os.path.join(conf.AU_TABLE_CACHE, cls.TABLE_NAME)
if not os.path.exists(dest):
return ImageRow.write_to_parquet(
rows,
cls.table_root(),
rows_per_file=cls.ROWS_PER_FILE)
@classmethod
def get_rows_by_uris(cls, uris):
import pandas as pd
import pyarrow.parquet as pq
pa_table = pq.read_table(cls.table_root())
df = pa_table.to_pandas()
matching = df[df.uri.isin(uris)]
return list(ImageRow.from_pandas(matching))
@classmethod
def iter_all_rows(cls):
"""Convenience method (mainly for testing) using Pandas"""
import pandas as pd
import pyarrow.parquet as pq
pa_table = pq.read_table(cls.table_root())
df = pa_table.to_pandas()
for row in ImageRow.from_pandas(df):
yield row
@classmethod
def as_imagerow_rdd(cls, spark):
df = spark.read.parquet(cls.table_root())
row_rdd = df.rdd.map(lambda row: ImageRow(**row.asDict()))
return row_rdd
# @classmethod
# def show_stats(cls, spark=None):
#
# @staticmethod
# def write_tf_dataset_to_parquet(
# dataset,
# dest_dir,
#
"""
make a dataset for 1-channel mnist things
make a dataset for our handful of images
try to coerce dataset from mscoco
make one for bbd100k
record activations for mnist
then for mobilenet on bdd100k / mscoco
take note of deeplab inference: https://colab.research.google.com/github/tensorflow/models/blob/master/research/deeplab/deeplab_demo.ipynb#scrollTo=edGukUHXyymr
and we'll wanna add maskrcnn mebbe ?
SPARK_LOCAL_IP=127.0.0.1 $SPARK_HOME/bin/pyspark --packages databricks:tensorframes:0.5.0-s_2.11 --packages databricks:spark-deep-learning:1.2.0-spark2.3-s_2.11
class DatasetFactoryBase(object):
class ParamsBase(object):
def __init__(self):
self.BASE_DIR = ''
@classmethod
def create_dataset(cls):
pass
@classmethod
def get_ctx_for_entry(cls, entry_id):
pass
""" | 28.595941 | 160 | 0.623653 |
6dd85933e9edf9c201a35fe12dd563f0c97ddb8b | 417 | py | Python | Python Fundamentals/Regular Expressions/More Exercises/Task05.py | DonikaChervenkova/SoftUni | bff579c037ec48f39ed193b34bc3502a32e90732 | [
"MIT"
] | 1 | 2022-03-16T10:23:04.000Z | 2022-03-16T10:23:04.000Z | Python Fundamentals/Regular Expressions/More Exercise/Task05.py | IvanTodorovBG/SoftUni | 7b667f6905d9f695ab1484efbb02b6715f6d569e | [
"MIT"
] | null | null | null | Python Fundamentals/Regular Expressions/More Exercise/Task05.py | IvanTodorovBG/SoftUni | 7b667f6905d9f695ab1484efbb02b6715f6d569e | [
"MIT"
] | 1 | 2021-12-04T12:30:57.000Z | 2021-12-04T12:30:57.000Z | import re
title_regex = r'<title>([^<>]*)<\/title>'
info = input()
title = re.findall(title_regex, info)
title = ''.join(title)
print(f"Title: {title}")
body_regex = r'<body>.*<\/body>'
body = re.findall(body_regex, info)
body = ''.join(body)
content_regex = r">([^><]*)<"
content = re.findall(content_regex, body)
content = ''.join(content)
content = content.replace('\\n', '')
print(f'Content: {content}') | 17.375 | 41 | 0.630695 |
6dda593a7a7bdfb7cf3bae36d8a8315e4135dc5a | 230 | py | Python | OMS/helpers/idgenerator.py | RumaisaHabib/orphan-management-system | 4671f40fb2a979e54dec4d12cc522829c2aa739e | [
"MIT"
] | 1 | 2021-12-24T18:14:35.000Z | 2021-12-24T18:14:35.000Z | OMS/helpers/idgenerator.py | RumaisaHabib/orphan-management-system | 4671f40fb2a979e54dec4d12cc522829c2aa739e | [
"MIT"
] | null | null | null | OMS/helpers/idgenerator.py | RumaisaHabib/orphan-management-system | 4671f40fb2a979e54dec4d12cc522829c2aa739e | [
"MIT"
] | null | null | null | import random
def randomStr():
l = [x for x in range(9)]
l += [chr(x) for x in range(65, 65+26)]
string = ""
for x in range(32):
string += str(l[random.randint(0, len(l) - 1)])
return string
| 19.166667 | 63 | 0.521739 |
6ddb9acc38ebe942d14b28143c5d4ded77045159 | 320 | py | Python | code_references/graph.py | nathanShepherd/Intelligent-Interface | 4ab8a223ef6dfaed7cf5ebf61b24ec355d00b593 | [
"MIT"
] | 3 | 2018-03-26T21:08:45.000Z | 2018-11-16T21:16:57.000Z | code_references/graph.py | nathanShepherd/Intelligent-Interface | 4ab8a223ef6dfaed7cf5ebf61b24ec355d00b593 | [
"MIT"
] | null | null | null | code_references/graph.py | nathanShepherd/Intelligent-Interface | 4ab8a223ef6dfaed7cf5ebf61b24ec355d00b593 | [
"MIT"
] | 2 | 2018-03-26T21:08:51.000Z | 2020-05-06T09:22:52.000Z | # Testing various methods to graph with matplotlib
# Developed by Nathan Shepherd
import numpy as np
import matplotlib.pyplot as plt
n = 100
y = [round(np.random.normal(scale=n/10)) for _ in range(n)]
x = [i for i in range(-n, n)]
_y = []
for i in range(-n, n):
_y.append(y.count(i))
plt.plot(x, _y)
plt.show()
| 18.823529 | 59 | 0.671875 |
6ddc0994a3a96b2f0830b2f0c227911b21552e3f | 1,741 | py | Python | scripts/taxonomy_frequency.py | STRIDES-Codes/Exploring-the-Microbiome- | bd29c8c74d8f40a58b63db28815acb4081f20d6b | [
"MIT"
] | null | null | null | scripts/taxonomy_frequency.py | STRIDES-Codes/Exploring-the-Microbiome- | bd29c8c74d8f40a58b63db28815acb4081f20d6b | [
"MIT"
] | null | null | null | scripts/taxonomy_frequency.py | STRIDES-Codes/Exploring-the-Microbiome- | bd29c8c74d8f40a58b63db28815acb4081f20d6b | [
"MIT"
] | 2 | 2021-06-05T07:40:20.000Z | 2021-06-05T08:02:58.000Z | import sys
from Bio import Entrez
from collections import Counter
import pandas as pd
###########################################
def get_tax_id(species):
species = species.replace(" ", "+").strip()
search = Entrez.esearch(term = species, db = "taxonomy", retmode = "xml")
record = Entrez.read(search)
return record['IdList'][0]
###############################################
def get_tax_data(taxid):
search = Entrez.efetch(id = taxid, db = "taxonomy", retmode = "xml")
return Entrez.read(search)
###############################################
def tax_to_freq(in_file,out_file):
Entrez.email = 'idrissi.azami.abdellah@gmail.com'
print('Reading input file .....')
with open (in_file,'r', encoding='utf-8') as inpt:
sps = []
content = inpt.readlines()
print('Extracting nodes ...')
for i in content:
if '# Model Data:' in i:
sp = i.split ('|')[1].split('|')[0].replace('_',' ')
sps.append(sp)
print('Counting nodes....')
counter = dict(Counter(sps))
total = 0
for i in counter:
try:
taxid = get_tax_id(i)
taxdata = get_tax_data(taxid)
total = total + counter[i]
except:
pass
print ('Retriving taxonomy ...')
tax = []
for i in counter:
try:
taxid = get_tax_id(i)
taxdata = get_tax_data(taxid)
lineage = {d['Rank']:d['ScientificName'] for d in
taxdata[0]['LineageEx'] if d['Rank'] in ['superkingdom','phylum','class','order', 'family','genus','species']}
lineage['Strain']=i
lineage['#Hits']=counter[i]
lineage['Frequency (%)']=(counter[i]/total)*100
tax.append(lineage)
except:
pass
df = pd.DataFrame(tax)
df.to_csv(out_file,sep='\t',index=False)
return df
| 31.654545 | 118 | 0.564618 |
6dddd5e456a7ccaaa8659db73eee87ff70f0dccb | 91 | py | Python | 02-array-seq/2_13.py | 393562632/example-code | 4a5da5726408284aed9e01f93a25a0d8dd348fb5 | [
"MIT"
] | null | null | null | 02-array-seq/2_13.py | 393562632/example-code | 4a5da5726408284aed9e01f93a25a0d8dd348fb5 | [
"MIT"
] | null | null | null | 02-array-seq/2_13.py | 393562632/example-code | 4a5da5726408284aed9e01f93a25a0d8dd348fb5 | [
"MIT"
] | null | null | null | weird_board = [['_'] * 3] *3
print(weird_board)
weird_board[0][2] = 'X'
print(weird_board) | 18.2 | 28 | 0.659341 |
6dddfed29dba919369dee25697fc63339866499f | 12,754 | py | Python | gipf/GipfLogic.py | callix2/alphaZero-gipf | fd8dac7606611126d2d14beca0333b53bd5ee995 | [
"MIT"
] | null | null | null | gipf/GipfLogic.py | callix2/alphaZero-gipf | fd8dac7606611126d2d14beca0333b53bd5ee995 | [
"MIT"
] | null | null | null | gipf/GipfLogic.py | callix2/alphaZero-gipf | fd8dac7606611126d2d14beca0333b53bd5ee995 | [
"MIT"
] | null | null | null | '''
Author: Eric P. Nichols
Date: Feb 8, 2008.
Board class.
Board data:
1=white, -1=black, 0=empty
first dim is column , 2nd is row:
pieces[1][7] is the square in column 2,
at the opposite end of the board in row 8.
Squares are stored and manipulated as (x,y) tuples.
x is the column, y is the row.
'''
import numpy as np
class Board():
# list of all 6 directions on the board, as (x,y) offsets
__directions = [(2,0),(-2,0),(1,1),(1,-1),(-1,1),(-1,-1)]
# list of all entries of the matrix, which are actually spots on the board
actBoard = [(2,3),(3,2),(3,4),(4,1),(4,3),(4,5),(5,2),(5,4),(6,1),(6,3),(6,5),(7,2),(7,4),(8,1),(8,3),(8,5),(9,2),(9,4),(10,3)]
# list of all starting Points on the board
startingPoints = [(0,3),(1,2),(1,4),(2,1),(2,5),(3,0),(3,6),(5,0),(5,6),(7,0),(7,6),(9,0),(9,6),(10,1),(10,5),(11,2),(11,4),(12,3)]
# dictionary for the translation of the spot names into the entries of the matrix (as tuple)
move_dict = {"a1": (9,0), "a2": (7,0), "a3": (5,0), "a4": (3,0), "b1": (10,1), "b2": (8,1), "b3": (6,1), "b4": (4,1), "b5": (2,1), "c1": (11,2),
"c2": (9,2), "c5": (3,2), "c6": (1,2), "d1": (12,3), "d2": (10,3), "d6": (2,3), "d7": (0,3), "e1": (11,4), "e2": (9,4), "e5": (3,4),
"e6": (1,4), "f1": (10,5), "f2": (8,5), "f3": (6,5), "f4": (4,5), "f5": (2,5), "g1": (9,6), "g2": (7,6), "g3": (5,6), "g4": (3,6)}
def __init__(self, n):
"Set up initial board configuration."
self.n = n
# Create the empty board array.
self.pieces = [None]*self.n # rows: mini: 13, normal: 17
for i in range(self.n):
self.pieces[i] = [0]*(int(self.n//(1.8))) # columns: mini: 13//1.8=7 normal: 17//1.8=9
#Set up reserve in board corner
self.pieces[0][0] = 5
self.pieces[0][2] = 5
# Set up the initial 6 pieces.
self.pieces[4][1] = 1
self.pieces[4][5] = 1
self.pieces[10][3] = 1
self.pieces[8][1] = -1
self.pieces[8][5] = -1
self.pieces[2][3] = -1
"""
#Testfall Sym
self.pieces[8][1] = 1
self.pieces[10][3] = 1
self.pieces[4][5] = 1
self.pieces[2][3] = -1
self.pieces[7][4] = -1
self.pieces[8][5] = -1
#Testfall A
self.pieces[8][1] = -1
self.pieces[7][2] = -1
self.pieces[4][3] = -1
self.pieces[10][3] = 1
self.pieces[8][3] = 1
self.pieces[4][5] = 1
self.pieces[5][4] = 1
#Testfall B
self.pieces[7][2] = 1
self.pieces[6][1] = 1
self.pieces[10][3] = 1
self.pieces[8][3] = -1
self.pieces[4][3] = -1
self.pieces[2][3] = -1
#Testfall C
self.pieces[4][1] = 1
self.pieces[5][2] = -1
self.pieces[10][3] = 1
self.pieces[4][3] = -1
self.pieces[2][3] = -1
#Testfall D
self.pieces[6][1] = -1
self.pieces[7][2] = -1
self.pieces[9][4] = 1
self.pieces[10][3] = -1
self.pieces[6][3] = -1
self.pieces[4][3] = -1
self.pieces[2][3] = 1
"""
# add [][] indexer syntax to the Board
def __getitem__(self, index):
return self.pieces[index]
def __setitem__(self, index, color):
self.pieces[index] = color
def get_actBoard(self):
if self.n == 13:
return self.actBoard
else:
pass # return actBoard + ext
def get_startingPoints(self):
if self.n == 13:
return self.startingPoints
else:
pass # return actBoard + ext
@staticmethod
def translate_move(move):
"""Returns a tuple of the spot names as a tuple of the matrix
"""
try:
move_new = (Board.move_dict[move[0]],Board.move_dict[move[1]])
return move_new
except KeyError:
'Invalid Field'
def get_legal_moves(self):
"""Returns all the legal moves
"""
moves = set() # stores the legal moves.
# discover the possible moves for every starting point
for start in self.startingPoints:
newmoves = self.get_moves_for_dot(start)[1],[2]
moves.update(newmoves)
return list(moves)
def get_legal_moves_binary(self):
"""Returns all the legal moves
"""
moves = [] # stores the legal moves.
# discover the possible moves for every starting point
for start in self.startingPoints:
newmoves = self.get_moves_for_dot(start)[2]
moves.extend(newmoves)
return moves
def get_all_moves(self):
"""Returns all the legal moves
"""
moves = [] # stores the legal moves.
# discover the possible moves for every starting point
for start in self.startingPoints:
newmoves = self.get_moves_for_dot(start)[1]
moves.extend(newmoves)
return moves
def get_moves_for_dot(self, dot):
"""Returns all the legal moves that use the given dot as a base.
"""
# search all possible directions.
legal_moves = []
all_moves = []
all_moves_binary = []
for direction in self.__directions:
target = tuple(np.add(dot, direction))
if target in self.actBoard:
move = (dot, target)
all_moves.append(move)
if self.check_move(target, direction):
legal_moves.append(move)
all_moves_binary.extend([1])
else:
all_moves_binary.extend([0])
# return the generated move list
return legal_moves, all_moves, all_moves_binary
def check_move(self, target, direction):
"""Returns True if there is a free field along the given direction
if not returns Flase because the move is not valid
"""
s = target
while s in self.actBoard:
if self[s] == 0:
return True
s = tuple(np.add(s, direction))
return False
def execute_move(self, action, curPlayer):
"""Performs the given move on the board; does not remove pieces!
color gives the color of the piece to play (1=white,-1=black)
"""
all_moves = self.get_all_moves()
move = all_moves[action]
start=move[0]
target=move[1]
direction = tuple(np.subtract(target, start))
s=target
# Runs up to a gap and places the piece there
while s in self.actBoard:
if self[s] == 0:
break
s = tuple(np.add(s, direction))
self[start]=curPlayer
# Runs in opposite direction and moves the pieces
while s in self.actBoard:
s_prev = tuple(np.subtract(s, direction))
s_prev_color = self[s_prev]
self[s]= s_prev_color
s = tuple(np.subtract(s, direction))
self[s]=0
# Decreases reserve
#players[color+1].dec_reserve()
def remove_lines(self, curPlayer):
"""Checks for each field whether a row of four results.
If so, removes the entire line
"""
#prüfen ob mehrere 4er, wenn ja zuerst den der spielenden Farbe, wenn immer noch mehrere zuerst den der mehr schlägt
rows = []
add_reserve = [0, None, 0]
for spot in self.actBoard:
new_row = self.discover_row_of_4(spot)
if new_row and new_row not in rows:
rows.append(new_row)
while len(rows)>1:
#mehrere rows
rows_of_color = [] #alle rows der aktuellen Farbe (haben vorrang)
index_max = None
for row in rows:
row_color = self[list(row)[0]]
if row_color == curPlayer:
rows_of_color.append(row)
if len(rows_of_color)>1:
#mehrere rows der aktiven Farbe
#prüfen welche die meisten schlägt
c = [None]*len(rows_of_color)
for index, row in enumerate(rows_of_color):
c[index] = self.get_hit_count(row)
index_max = np.argmax(c)
add_reserve = np.add(add_reserve, self.remove_line(rows_of_color[index_max]), where=[1,0,1])
elif len(rows_of_color)>0:
#nur eine row der aktiven Farbe
add_reserve = np.add(add_reserve, self.remove_line(rows_of_color[0]), where=[1,0,1])
else:
#mehrer rows der anderen Farbe und keine der aktiven
#prüfen welche die meisten schlägt
c = [None]*len(rows)
for index, row in enumerate(rows):
c[index] = self.get_hit_count(row)
index_max = np.argmax(c)
add_reserve = np.add(add_reserve, self.remove_line(rows[index_max]), where=[1,0,1])
#prüfe ob rows noch aktuell
rows = self.check_rows(rows)
if len(rows)>0:
#nur eine row (egal welche Farbe)
add_reserve = np.add(add_reserve, self.remove_line(rows[0]), where=[1,0,1])
return add_reserve
def check_rows(self, rows):
rows_new = rows.copy()
for row in rows:
for spot in row:
if self[spot] == 0:
rows_new.remove(row)
break
return rows_new
def get_hit_count(self, row):
count = 0
row = list(row)
color_of_row = self[row[0]]
direction = tuple(np.subtract(row[0], row[1]))
s = row[0]
# Runs from the first of the 4 in one direction of the line
while s in self.actBoard:
if self[s] == 0:
break
else:
color = self[s]
if color != color_of_row:
count += 1
#self[s] = 0
s = tuple(np.add(s, direction))
# Runs in the opposite direction
s = tuple(np.subtract(row[0], direction))
while s in self.actBoard:
if self[s] == 0:
break
else:
color = self[s]
if color != color_of_row:
count += 1
#self[s] = 0
s = tuple(np.subtract(s, direction))
return count
def discover_row_of_4(self, spot):
"""Examines all directions for the given spot to see if a row of four exists
If found returns a array of the four, otherwise returns False
"""
color = self[spot]
for direction in self.__directions:
row_of_4 = [] #set() #weil unorderd
#row_of_4.update([spot])
row_of_4.append(spot)
s = tuple(np.add(spot, direction))
while s in self.actBoard:
if self[s] == 0 or self[s] != color:
break
else:
#row_of_4.update([s])
row_of_4.append(s)
s = tuple(np.add(s, direction))
if len(row_of_4)>2: #GipfMini: 3; Normal: 4
row_of_4.sort()
return row_of_4
def remove_line(self, row_of_4):
"""Removes the 4 pieces and the pieces that form a direct extension of these 4
The pieces with the color of the 4 return to his reserve
"""
add_reserve = [0, None, 0]
row_of_4 = list(row_of_4)
color_of_4 = self[row_of_4[0]]
direction = tuple(np.subtract(row_of_4[0], row_of_4[1]))
s = row_of_4[0]
# Runs from the first of the 4 in one direction of the line
while s in self.actBoard:
if self[s] == 0:
break
else:
color = self[s]
if color == color_of_4:
add_reserve[color+1]+=1
#players[color+1].inc_reserve()
self[s] = 0
s = tuple(np.add(s, direction))
# Runs in the opposite direction
s = tuple(np.subtract(row_of_4[0], direction))
while s in self.actBoard:
if self[s] == 0:
break
else:
color = self[s]
if color == color_of_4:
add_reserve[color+1]+=1
#players[color+1].inc_reserve()
self[s] = 0
s = tuple(np.subtract(s, direction))
return add_reserve
| 36.130312 | 148 | 0.509644 |
6dde1212ba406b7fb0a629963b918fa2448f2579 | 2,533 | py | Python | pcwg/reporting/colour.py | lcameron05/PCWG | 8ae8ea7d644aa5bec0d1651101d83d8f17994f4b | [
"MIT"
] | 14 | 2015-01-15T12:40:51.000Z | 2019-06-14T16:10:08.000Z | pcwg/reporting/colour.py | lzhiwen3090/PCWG | 795e3ea267c7b87187dce04721c91a9d9c7999a7 | [
"MIT"
] | 121 | 2015-01-06T11:31:25.000Z | 2018-05-29T21:13:23.000Z | pcwg/reporting/colour.py | lzhiwen3090/PCWG | 795e3ea267c7b87187dce04721c91a9d9c7999a7 | [
"MIT"
] | 26 | 2015-01-15T12:41:09.000Z | 2019-04-11T14:45:32.000Z | import xlwt
class ColourGradient:
def __init__(self, minimum, maximum, interval, book):
self.levels = {}
self.minimum = minimum
self.maximum = maximum
dataRange = maximum - minimum
steps = int(dataRange / interval) + 1
if (steps >= 4):
steps_4 = steps / 4
else:
steps_4 = 1
for i in range(steps):
if (i <= steps_4):
red = 255
elif (i > steps_4 and i <= steps_4 * 2):
red = 255 - (255 / steps_4) * (i - steps_4)
elif (i > steps_4 * 2 and i <= steps_4 * 3):
red = (255 / 2 / steps_4) * (i - steps_4 * 2)
elif i < steps:
red = (255 / 2) - (255 / 2 / steps_4) * (i - steps_4 * 3)
else:
red = 0
if (i <= steps_4):
green = (255 / steps_4) * i
elif (i > steps_4 and i <= steps_4 * 2):
green = 255 - (255 / steps_4) * (i - steps_4)
elif (i > steps_4 * 2 and i <= steps_4 * 3):
green = (255 / steps_4) * (i - steps_4 * 2)
else:
green = 255
if (i <= steps_4):
blue = 0
elif (i > steps_4 and i <= steps_4 * 2):
blue = 0 + (255 / steps_4) * (i - steps_4)
elif i < steps:
blue = 255 - (255 / steps_4 / 2) * (i - steps_4 * 2)
else:
blue = 0
red = abs(red)
green = abs(green)
blue = abs(blue)
if (red > 255): red = 255
if (green > 255): green = 255
if (blue > 255): blue = 255
value = self.roundValue(minimum + i * interval)
excelIndex = 8 + i
colourName = "custom_colour_%d" % excelIndex
xlwt.add_palette_colour(colourName, excelIndex)
book.set_colour_RGB(excelIndex, red, green, blue)
style = xlwt.easyxf('pattern: pattern solid, fore_colour %s' % colourName, num_format_str='0%')
self.levels[value] = (red, green, blue, value, excelIndex, colourName, style)
def roundValue(self, value):
return round(value, 2)
def getStyle(self, value):
value = max(self.minimum, value)
value = min(self.maximum, value)
return self.levels[self.roundValue(value)][6]
| 32.474359 | 107 | 0.446901 |
6dde7cdccad8c45c7dc62586357016b68fc1ea28 | 2,044 | py | Python | mwlib/serve.py | h4ck3rm1k3/mwlib | 11475c6ad7480e35a4a59f276c47f6a5203435cc | [
"Unlicense"
] | 1 | 2019-04-27T20:14:53.000Z | 2019-04-27T20:14:53.000Z | mwlib/serve.py | h4ck3rm1k3/mwlib | 11475c6ad7480e35a4a59f276c47f6a5203435cc | [
"Unlicense"
] | null | null | null | mwlib/serve.py | h4ck3rm1k3/mwlib | 11475c6ad7480e35a4a59f276c47f6a5203435cc | [
"Unlicense"
] | null | null | null | #! /usr/bin/env python
"""WSGI server interface to mw-render and mw-zip/mw-post"""
import sys, os, time, re, shutil, StringIO
from hashlib import md5
from mwlib import myjson as json
from mwlib import log, _version
from mwlib.metabook import calc_checksum
log = log.Log('mwlib.serve')
collection_id_rex = re.compile(r'^[a-z0-9]{16}$')
def make_collection_id(data):
sio = StringIO.StringIO()
for key in (
_version.version,
'base_url',
'script_extension',
'template_blacklist',
'template_exclusion_category',
'print_template_prefix',
'print_template_pattern',
'login_credentials',
):
sio.write(repr(data.get(key)))
mb = data.get('metabook')
if mb:
if isinstance(mb, str):
mb = unicode(mb, 'utf-8')
mbobj = json.loads(mb)
sio.write(calc_checksum(mbobj))
num_articles = len(list(mbobj.articles()))
sys.stdout.write("new-collection %s\t%r\t%r\n" % (num_articles, data.get("base_url"), data.get("writer")))
return md5(sio.getvalue()).hexdigest()[:16]
def get_collection_dirs(cache_dir):
"""Generator yielding full paths of collection directories"""
for dirpath, dirnames, filenames in os.walk(cache_dir):
for d in dirnames:
if collection_id_rex.match(d):
yield os.path.join(dirpath, d)
def purge_cache(max_age, cache_dir):
"""Remove all subdirectories of cache_dir whose mtime is before now-max_age
@param max_age: max age of directories in seconds
@type max_age: int
@param cache_dir: cache directory
@type cache_dir: basestring
"""
now = time.time()
for path in get_collection_dirs(cache_dir):
for fn in os.listdir(path):
if now - os.stat(os.path.join(path, fn)).st_mtime > max_age:
break
else:
continue
try:
shutil.rmtree(path)
except Exception, exc:
log.ERROR('could not remove directory %r: %s' % (path, exc))
| 28.788732 | 114 | 0.629159 |
6ddf22f66b957c8246b1badd12845d6735c4bf0d | 118 | py | Python | src/passport/use_cases/__init__.py | clayman-micro/passport | 37aeb548560458cd4ba9bf9db551e360ad219b9c | [
"MIT"
] | null | null | null | src/passport/use_cases/__init__.py | clayman-micro/passport | 37aeb548560458cd4ba9bf9db551e360ad219b9c | [
"MIT"
] | 5 | 2020-09-15T15:03:33.000Z | 2021-11-26T08:35:10.000Z | src/passport/use_cases/__init__.py | clayman74/passport | 37aeb548560458cd4ba9bf9db551e360ad219b9c | [
"MIT"
] | null | null | null | from aiohttp import web
class UseCase:
def __init__(self, app: web.Application) -> None:
self.app = app
| 16.857143 | 53 | 0.661017 |
6ddf36ca544a3c8ccbf3d16260d57ec9db94a87c | 2,021 | py | Python | amap_distance_matrix/schemas/amap.py | Euraxluo/distance_matrix | 680e3147c263ea5f1abb26998aeb0b1985442a4b | [
"MIT"
] | 1 | 2022-03-15T06:47:36.000Z | 2022-03-15T06:47:36.000Z | amap_distance_matrix/schemas/amap.py | Euraxluo/distance_matrix | 680e3147c263ea5f1abb26998aeb0b1985442a4b | [
"MIT"
] | null | null | null | amap_distance_matrix/schemas/amap.py | Euraxluo/distance_matrix | 680e3147c263ea5f1abb26998aeb0b1985442a4b | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Time: 2022-03-01 15:43
# Copyright (c) 2022
# author: Euraxluo
from typing import *
from amap_distance_matrix.helper import haversine,format_loc
class AMapDefaultResultRouteStep(object):
def __init__(self, start: str, end: str):
self.polyline: str
self.instruction = "到达途经地"
self.orientation = "北"
self.road = "road"
self.distance = haversine(format_loc(start),format_loc(end))*1.5
self.tolls = "0"
self.toll_distance = "0"
self.toll_road = []
self.duration = self.distance/(25000/60/60)
self.action = []
self.assistant_action = "到达途经地"
self.tmcs: List
self.polyline = start + ";" + end
self.tmcs = [
{
"lcode": [],
"distance": "0",
"status": "畅通",
"polyline": self.polyline
}
]
class AMapDefaultResultPath(object):
def __init__(self, steps: List[AMapDefaultResultRouteStep]):
self.distance = "0"
self.duration = "0"
self.strategy = "速度最快"
self.tolls = "0"
self.toll_distance = "0"
self.steps = [i.__dict__ for i in steps]
self.restriction = "0"
self.traffic_lights = "0"
class AMapDefaultResultRoute(object):
def __init__(self, paths: AMapDefaultResultPath):
self.origin = "0"
self.destination = "0"
self.taxi_cost = "0"
self.paths = [paths.__dict__]
class AMapDefaultResult(object):
def __init__(self, points: List[str]):
self.status = "1"
self.info = "OK"
self.infocode = "10000"
self.count = "1"
self.route: AMapDefaultResultRoute
steps = []
for i, point in enumerate(points):
if i == 0:
continue
steps.append(AMapDefaultResultRouteStep(start=points[i - 1], end=point))
self.route = AMapDefaultResultRoute(paths=AMapDefaultResultPath(steps=steps)).__dict__
| 29.720588 | 94 | 0.573973 |
6ddf53b03344bb1f12510f5ef0a187bb6b91724f | 1,589 | py | Python | linear_regression.py | michael-golfi/comp551_assignment1 | a4eb73bae4280d5934165ee8b8400dd1c24e9758 | [
"MIT"
] | null | null | null | linear_regression.py | michael-golfi/comp551_assignment1 | a4eb73bae4280d5934165ee8b8400dd1c24e9758 | [
"MIT"
] | null | null | null | linear_regression.py | michael-golfi/comp551_assignment1 | a4eb73bae4280d5934165ee8b8400dd1c24e9758 | [
"MIT"
] | null | null | null | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
import csv
import datetime
AGE = "Age Category"
SEX = "Sex"
TIME = "Time"
OUTPUT_BASE = "output/"
COLS_X = [AGE, SEX, TIME, "TotalRaces"]
COLS_Y = [TIME]
#training data
TRAIN_X = "output/Y2X_train.csv"
TRAIN_Y = "output/Y2Y_train.csv"
#testing data
TEST_X = "output/Y2X_test.csv"
TEST_Y = "output/Y2Y_test.csv"
#Prediction data
PREDICTION = "output/PREDICTION.csv"
#Read preprocessed data
df_X_train = pd.read_csv(TRAIN_X, usecols=COLS_X)
df_Y_train = pd.read_csv(TRAIN_Y, usecols=COLS_Y)
#Read test data
df_X_test = pd.read_csv(TEST_X, usecols=COLS_X)
df_Y_test = pd.read_csv(TEST_Y, usecols=COLS_Y)
df_2017 = pd.read_csv(PREDICTION, usecols=COLS_X)
#Closed form solution: w = (XTX)^(-1)XTY
a = np.linalg.inv(np.dot(df_X_train.as_matrix().transpose(),df_X_train.as_matrix()))
b = np.dot(df_X_train.as_matrix().transpose(),df_Y_train.as_matrix())
w = np.dot(a,b)
y = np.dot(df_X_test, w)
print w
print abs((y-df_Y_test.as_matrix())).mean()
print (y-df_Y_test.as_matrix()).max()
a = abs(((y-df_Y_test.as_matrix())/df_Y_test.as_matrix())*100)
print a.max()
print a.mean()
c=0
for threshold in range(0,21):
for i in range(len(a)):
if a[i] < threshold:
c = c + 1
d = (float(c)/float(len(a)))*100
print threshold,d
c = 0
y_2017 = np.dot(df_2017,w)
new_time = list()
for i in range(len(y_2017)):
m, s = divmod(y_2017[i], 60)
h, m = divmod(m, 60)
new_time.append("%d:%02d:%02d" % (h, m, s))
pd.DataFrame(new_time).to_csv(OUTPUT_BASE + "LR_Results.csv")
| 17.086022 | 84 | 0.69163 |
6de0dc175dbe4c23766558e81ec6b605bc401de8 | 185 | py | Python | problem_332/problem_332.py | oltionzefi/daily-coding-problem | 4fe3ec53e1f3c7d299849671fdfead462d548cd3 | [
"MIT"
] | null | null | null | problem_332/problem_332.py | oltionzefi/daily-coding-problem | 4fe3ec53e1f3c7d299849671fdfead462d548cd3 | [
"MIT"
] | null | null | null | problem_332/problem_332.py | oltionzefi/daily-coding-problem | 4fe3ec53e1f3c7d299849671fdfead462d548cd3 | [
"MIT"
] | null | null | null | def positive_integer_pairs(m, n):
results = list()
for a in range(m // 2 + 1 ):
b = m - a
if a ^ b == n:
results.append((a, b))
return results
| 18.5 | 34 | 0.475676 |
6de2331479d616c60c982b16b354a172879db20e | 393 | py | Python | at_learner_core/at_learner_core/models/init_model.py | hieuvecto/CASIA-SURF_CeFA | 71dfd846ce968b3ed26974392a6e0c9b40aa12ae | [
"MIT"
] | 133 | 2020-03-03T03:58:04.000Z | 2022-03-28T21:42:36.000Z | at_learner_core/at_learner_core/models/init_model.py | lucaslu1987/CASIA-SURF_CeFA | 205d3d976523ed0c15d1e709ed7f21d50d7cf19b | [
"MIT"
] | 24 | 2020-03-13T09:30:09.000Z | 2022-03-22T07:47:15.000Z | at_learner_core/at_learner_core/models/init_model.py | lucaslu1987/CASIA-SURF_CeFA | 205d3d976523ed0c15d1e709ed7f21d50d7cf19b | [
"MIT"
] | 29 | 2020-03-10T06:46:45.000Z | 2022-01-29T15:35:21.000Z | from .wrappers import SimpleClassifierWrapper
def get_wrapper(config, wrapper_func=None):
if wrapper_func is not None:
wrapper = wrapper_func(config)
elif config.wrapper_config.wrapper_name == 'SimpleClassifierWrapper':
wrapper = SimpleClassifierWrapper(config.wrapper_config)
else:
raise Exception('Unknown wrapper architecture type')
return wrapper
| 32.75 | 73 | 0.750636 |
6de2eb54f1f884015cd25862ba629bbde92b8312 | 11,739 | py | Python | register.py | khvmaths/Register_UM_Crawl | 2741bfe9267e9ad068b438b27141cfc664f140f2 | [
"MIT"
] | null | null | null | register.py | khvmaths/Register_UM_Crawl | 2741bfe9267e9ad068b438b27141cfc664f140f2 | [
"MIT"
] | null | null | null | register.py | khvmaths/Register_UM_Crawl | 2741bfe9267e9ad068b438b27141cfc664f140f2 | [
"MIT"
] | null | null | null | from bs4 import BeautifulSoup
from urllib.request import Request,urlopen
from urllib.error import HTTPError
from PyQt5 import QtCore, QtGui, QtWidgets, Qt
import sys
import threading
import datetime
import win32con
import os
import struct
import time
import pyttsx3
from win32api import *
from win32gui import *
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(1236, 996)
self.groupBox = QtWidgets.QGroupBox(Form)
self.groupBox.setGeometry(QtCore.QRect(10, 10, 361, 831))
self.groupBox.setObjectName("groupBox")
self.tableWidget = QtWidgets.QTableWidget(self.groupBox)
self.tableWidget.setGeometry(QtCore.QRect(10, 30, 341, 791))
self.tableWidget.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(0)
self.tableWidget.setRowCount(0)
self.tableWidget.horizontalHeader().setCascadingSectionResizes(True)
self.groupBox_2 = QtWidgets.QGroupBox(Form)
self.groupBox_2.setGeometry(QtCore.QRect(380, 10, 681, 831))
self.groupBox_2.setObjectName("groupBox_2")
self.tableWidget_2 = QtWidgets.QTableWidget(self.groupBox_2)
self.tableWidget_2.setGeometry(QtCore.QRect(10, 30, 651, 791))
self.tableWidget_2.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
self.tableWidget_2.setObjectName("tableWidget_2")
self.tableWidget_2.setColumnCount(0)
self.tableWidget_2.setRowCount(0)
self.tableWidget_2.horizontalHeader().setCascadingSectionResizes(True)
self.groupBox_3 = QtWidgets.QGroupBox(Form)
self.groupBox_3.setGeometry(QtCore.QRect(1070, 10, 141, 80))
self.groupBox_3.setObjectName("groupBox_3")
self.pushButton = QtWidgets.QPushButton(self.groupBox_3)
self.pushButton.setGeometry(QtCore.QRect(10, 50, 111, 28))
self.pushButton.setObjectName("pushButton")
self.lineEdit = QtWidgets.QLineEdit(self.groupBox_3)
self.lineEdit.setGeometry(QtCore.QRect(10, 20, 113, 22))
self.lineEdit.setObjectName("lineEdit")
self.groupBox_4 = QtWidgets.QGroupBox(Form)
self.groupBox_4.setGeometry(QtCore.QRect(1070, 100, 141, 61))
self.groupBox_4.setObjectName("groupBox_4")
self.lineEdit_2 = QtWidgets.QLineEdit(self.groupBox_4)
self.lineEdit_2.setGeometry(QtCore.QRect(10, 20, 113, 22))
self.lineEdit_2.setText("")
self.lineEdit_2.setObjectName("lineEdit_2")
self.groupBox_5 = QtWidgets.QGroupBox(Form)
self.groupBox_5.setGeometry(QtCore.QRect(1070, 170, 141, 51))
self.groupBox_5.setObjectName("groupBox_5")
self.lineEdit_3 = QtWidgets.QLineEdit(self.groupBox_5)
self.lineEdit_3.setGeometry(QtCore.QRect(10, 20, 113, 22))
self.lineEdit_3.setText("")
self.lineEdit_3.setObjectName("lineEdit_3")
self.groupBox_6 = QtWidgets.QGroupBox(Form)
self.groupBox_6.setGeometry(QtCore.QRect(1070, 230, 141, 51))
self.groupBox_6.setObjectName("groupBox_6")
self.lineEdit_4 = QtWidgets.QLineEdit(self.groupBox_6)
self.lineEdit_4.setGeometry(QtCore.QRect(10, 20, 113, 22))
self.lineEdit_4.setText("")
self.lineEdit_4.setObjectName("lineEdit_4")
self.groupBox_7 = QtWidgets.QGroupBox(Form)
self.groupBox_7.setGeometry(QtCore.QRect(10, 840, 1051, 151))
self.groupBox_7.setObjectName("groupBox_7")
self.listWidget = QtWidgets.QListWidget(self.groupBox_7)
self.listWidget.setGeometry(QtCore.QRect(10, 20, 1021, 121))
self.listWidget.setObjectName("listWidget")
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(1090, 930, 131, 41))
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName("label")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "REGISTER UM"))
self.groupBox.setTitle(_translate("Form", "Elective"))
self.tableWidget.setSortingEnabled(True)
self.groupBox_2.setTitle(_translate("Form", "KoK"))
self.tableWidget_2.setSortingEnabled(True)
self.groupBox_3.setTitle(_translate("Form", "Set Timer (sec)"))
self.pushButton.setText(_translate("Form", "START!!"))
self.lineEdit.setText(_translate("Form", "5"))
self.groupBox_4.setTitle(_translate("Form", "Targeted Elective 1"))
self.groupBox_5.setTitle(_translate("Form", "Targeted Elective 2"))
self.groupBox_6.setTitle(_translate("Form", "Targeted KoK 1"))
self.groupBox_7.setTitle(_translate("Form", "Command"))
self.label.setText(_translate("Form", "A program by\n"
"hongvin"))
class WindowsBalloonTip:
def __init__(self):
message_map = {
win32con.WM_DESTROY: self.OnDestroy,
}
# Register the Window class.
wc = WNDCLASS()
self.hinst = wc.hInstance = GetModuleHandle(None)
wc.lpszClassName = "PythonTaskbar"
wc.lpfnWndProc = message_map # could also specify a wndproc.
self.classAtom = RegisterClass(wc)
def ShowWindow(self,title, msg):
# Create the Window.
style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
self.hwnd = CreateWindow( self.classAtom, "Taskbar", style, \
0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, \
0, 0, self.hinst, None)
UpdateWindow(self.hwnd)
#iconPathName = os.path.abspath(os.path.join( sys.path[0], "favicon.ico" ))
icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE
hicon = LoadIcon(0, win32con.IDI_APPLICATION)
flags = NIF_ICON | NIF_MESSAGE | NIF_TIP
nid = (self.hwnd, 0, flags, win32con.WM_USER+20, hicon, "tooltip")
Shell_NotifyIcon(NIM_ADD, nid)
Shell_NotifyIcon(NIM_MODIFY, \
(self.hwnd, 0, NIF_INFO, win32con.WM_USER+20,\
hicon, "Balloon tooltip",msg,200,title))
# self.show_balloon(title, msg)
DestroyWindow(self.hwnd)
def OnDestroy(self, hwnd, msg, wparam, lparam):
nid = (self.hwnd, 0)
Shell_NotifyIcon(NIM_DELETE, nid)
PostQuitMessage(0) # Terminate the app.
w=WindowsBalloonTip()
engine = pyttsx3.init()
def TTS(text,grp=""):
split=" ".join(text)
if grp=="":
engine.say('Found!'+split)
else:
engine.say('Found!' + split+'Group '+str(grp))
engine.runAndWait()
class App(QtWidgets.QMainWindow,Ui_Form):
def __init__(self):
super(self.__class__,self).__init__()
self.setupUi(self)
self.pushButton.clicked.connect(self.startengine)
def startengine(self):
self.listWidget.scrollToBottom()
self.lineEdit.setEnabled(False)
timeout=float(self.lineEdit.text())
time_now=time.time()
e1=self.lineEdit_2.text()
e2=self.lineEdit_3.text()
k1=self.lineEdit_4.text()
e1b=False
e2b=False
k1b=False
courses=['','','']
url = 'http://register.um.edu.my/el_kosong_bi.asp'
request = Request(url)
try:
self.tableWidget.setEnabled(True)
json = urlopen(request).read().decode()
soup = BeautifulSoup(json,"html.parser")
a = soup.find_all('div')
self.tableWidget.setColumnCount(3)
self.tableWidget.setRowCount((len(a)-1)/3)
self.tableWidget.setHorizontalHeaderLabels(["Subject Code","Group","Vacant"])
j=-1
k=0
for i in range(0,len(a)):
if i%3==0:
j+=1
k=0
self.tableWidget.setItem(j,k,QtWidgets.QTableWidgetItem(a[i].text))
if e1==a[i].text:
self.listWidget.addItem('['+str(datetime.datetime.now().time())+']: Matched found for targeted elective '+a[i].text+' (Group '+a[i+1].text+')')
e1b=True
courses[0]=(a[i].text+'(G'+a[i+1].text+')')
TTS(a[i].text,a[i+1].text)
if e2==a[i].text:
self.listWidget.addItem('['+str(datetime.datetime.now().time())+']: Matched found for targeted elective '+a[i].text+' (Group '+a[i+1].text+')')
e2b=True
courses[1]=(a[i].text+'(G'+a[i+1].text+')')
TTS(a[i].text,a[i+1].text)
k+=1
except Exception as e:
print("Error",e)
self.tableWidget.setEnabled(False)
self.listWidget.addItem('['+str(datetime.datetime.now().time())+']: Error occured at Elective')
self.lineEdit.setEnabled(True)
url = 'http://register.um.edu.my/kok_kosong_bi.asp'
request = Request(url)
try:
self.tableWidget_2.setEnabled(True)
json = urlopen(request).read().decode()
soup = BeautifulSoup(json,"html.parser")
a = soup.find_all('td')
self.tableWidget_2.setColumnCount(3)
self.tableWidget_2.setRowCount((len(a)-10)/4)
self.tableWidget_2.setHorizontalHeaderLabels(["Subject Code","Course Name","Vacant"])
j=-1
k=0
m=1
for i in range(9,len(a)-1):
if (i-m)%4==0:
j+=1
k=0
continue
if a[i].text=='Bil' or a[i].text=='Code' or a[i].text=='Description' or a[i].text=='Vacant':
m=2
if a[i].text=='Vacant':
j-=1
self.tableWidget_2.setRowCount(((len(a)-10)/4)-1)
continue
if k1==a[i].text:
self.listWidget.addItem('['+str(datetime.datetime.now().time())+']: Matched found for targeted KoK '+a[i].text)
k1b=True
courses[2]=(a[i].text)
TTS(a[i].text)
self.tableWidget_2.setItem(j,k,QtWidgets.QTableWidgetItem(a[i].text))
k+=1
except Exception as e:
print("Error",e)
self.tableWidget.setEnabled(False)
self.listWidget.addItem('['+str(datetime.datetime.now().time())+']: Error occured at KoK')
self.lineEdit.setEnabled(True)
self.tableWidget.resizeColumnsToContents()
self.tableWidget_2.resizeColumnsToContents()
self.listWidget.scrollToBottom()
self.listWidget.addItem('['+str(datetime.datetime.now().time())+']: List refreshed')
if e1b==True or e2b==True or k1b==True:
w.ShowWindow("Matching course found!","Course Code: {0} {1} {2}".format(*courses))
next_time=time_now+timeout
t=threading.Timer(next_time-time.time(),self.startengine)
t.daemon=True
t.start()
def main():
app=QtWidgets.QApplication(sys.argv)
form=App()
form.show()
app.exec_()
if __name__ == '__main__':
main()
| 43.639405 | 164 | 0.597155 |
6de329be760fa541cce9f8961d309f42264a1df3 | 1,604 | py | Python | tests/utils.py | ofek/hatch-containers | dd57acc812db8e62994f2b00160a05292d5f35c1 | [
"MIT"
] | 3 | 2021-12-29T06:44:41.000Z | 2022-02-28T09:27:20.000Z | tests/utils.py | ofek/hatch-containers | dd57acc812db8e62994f2b00160a05292d5f35c1 | [
"MIT"
] | null | null | null | tests/utils.py | ofek/hatch-containers | dd57acc812db8e62994f2b00160a05292d5f35c1 | [
"MIT"
] | null | null | null | # SPDX-FileCopyrightText: 2021-present Ofek Lev <oss@ofek.dev>
#
# SPDX-License-Identifier: MIT
import subprocess
from textwrap import dedent as _dedent
import tomli
import tomli_w
def dedent(text):
return _dedent(text[1:])
def check_container_output(container_name, command):
return subprocess.check_output(['docker', 'exec', container_name, *command]).decode('utf-8')
def container_exists(container_name):
output = (
subprocess.check_output(['docker', 'ps', '-a', '--format', '{{.Names}}', '--filter', f'name={container_name}'])
.strip()
.decode('utf-8')
)
return any(line.strip() == container_name for line in output.splitlines())
def container_running(container_name):
output = (
subprocess.check_output(['docker', 'ps', '--format', '{{.Names}}', '--filter', f'name={container_name}'])
.strip()
.decode('utf-8')
)
return any(line.strip() == container_name for line in output.splitlines())
def update_project_environment(project, name, config):
project_file = project.root / 'pyproject.toml'
with open(str(project_file), 'r', encoding='utf-8') as f:
raw_config = tomli.loads(f.read())
env_config = raw_config.setdefault('tool', {}).setdefault('hatch', {}).setdefault('envs', {}).setdefault(name, {})
env_config.update(config)
project.config.envs[name] = project.config.envs.get(name, project.config.envs['default']).copy()
project.config.envs[name].update(env_config)
with open(str(project_file), 'w', encoding='utf-8') as f:
f.write(tomli_w.dumps(raw_config))
| 30.846154 | 119 | 0.667082 |
6de4785de957dcd93698e538204a1309d3d31d03 | 881 | py | Python | Question Set 3 - (Functions)/Version 1/main.py | Randula98/Python-For-Beginners | e41a6014be882f01c6ccdcbe2167e2b581646eee | [
"MIT"
] | 6 | 2021-12-14T17:52:11.000Z | 2021-12-19T20:22:44.000Z | Question Set 3 - (Functions)/Version 1/main.py | GIHAA/Python-For-Beginners | e41a6014be882f01c6ccdcbe2167e2b581646eee | [
"MIT"
] | null | null | null | Question Set 3 - (Functions)/Version 1/main.py | GIHAA/Python-For-Beginners | e41a6014be882f01c6ccdcbe2167e2b581646eee | [
"MIT"
] | 2 | 2021-12-19T18:50:30.000Z | 2022-01-01T23:05:18.000Z |
#define calcIncrement function
def calcIncrement(salary , noOfYearsWorked):
if(noOfYearsWorked > 2):
increment = (salary * 10 / 100)
else:
increment = 0
return increment
#define calcTotalSalary function
def calcTotalSalary(salary , increment):
total = salary + increment
return total
#get user inputs for salary
salary = input("Enter Salary : ")
salary = float(salary)
#get user inputs for number of years worked
years = input("Enter no of years worked : ")
years = int(years)
#calculate the increment by passing the given values to the function
increment = calcIncrement(salary , years)
#calculate the total salary by passing the given values to the function
totalSalary = calcTotalSalary(salary , increment)
#display the increment and the total salary
print("Increment : " + str(increment))
print("Total Salary : " + str(totalSalary))
| 26.69697 | 71 | 0.732123 |
6de4cb3c7c7e948bd05ee2500418fd79816b080a | 438 | py | Python | rubin_sim/maf/mafContrib/LSSObsStrategy/__init__.py | RileyWClarke/flarubin | eb7b1ee21c828523f8a5374fe4510fe6e5ec2a2a | [
"MIT"
] | null | null | null | rubin_sim/maf/mafContrib/LSSObsStrategy/__init__.py | RileyWClarke/flarubin | eb7b1ee21c828523f8a5374fe4510fe6e5ec2a2a | [
"MIT"
] | null | null | null | rubin_sim/maf/mafContrib/LSSObsStrategy/__init__.py | RileyWClarke/flarubin | eb7b1ee21c828523f8a5374fe4510fe6e5ec2a2a | [
"MIT"
] | null | null | null | from .newDitherStackers import *
from .newDitherStackers import *
from .maskingAlgorithmGeneralized import *
from .saveBundleData_npzFormat import *
from .numObsMetric import *
from .galaxyCountsMetric_extended import *
from .galaxyCounts_withPixelCalibration import *
from .artificialStructureCalculation import *
from .almPlots import *
from .coaddM5Analysis import *
from .constantsForPipeline import *
from .os_bias_analysis import *
| 33.692308 | 48 | 0.835616 |
6de56b62032d39a0f8c492c5d736fc6926aeb427 | 2,576 | py | Python | setup.py | vomaufgang/publish | 6e610c055118f9761d49962a12d9095cf2936386 | [
"MIT"
] | 1 | 2019-08-19T01:45:29.000Z | 2019-08-19T01:45:29.000Z | setup.py | vomaufgang/publish | 6e610c055118f9761d49962a12d9095cf2936386 | [
"MIT"
] | 11 | 2019-08-18T09:31:10.000Z | 2021-01-27T19:02:53.000Z | setup.py | vomaufgang/publish | 6e610c055118f9761d49962a12d9095cf2936386 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# anited. publish - Python package with cli to turn markdown files into ebooks
# Copyright (c) 2014 Christopher Knörndel
#
# Distributed under the MIT License
# (license terms are at http://opensource.org/licenses/MIT).
"""Setup script for easy_install and pip."""
import sys
import codecs
import os.path
MIN_SUPPORTED_PYTHON_VERSION = (3, 6)
if sys.version_info < MIN_SUPPORTED_PYTHON_VERSION:
sys.exit('Sorry, Python < {} is not supported.'.format(
'.'.join(map(str, MIN_SUPPORTED_PYTHON_VERSION))
))
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def read(rel_path):
"""Reads the contents of the file atthe relative path `rel_path`.
"""
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, rel_path), 'r') as file_:
return file_.read()
def get_version(rel_path):
"""Gets the version number declared in the `__version__` constant of
the Python file at `rel_path`.
"""
for line in read(rel_path).splitlines():
if line.startswith('__version__'):
delim = '"' if '"' in line else "'"
return line.split(delim)[1]
raise RuntimeError("Unable to find version string.")
README = open('README.md').read()
VERSION = get_version('publish/__init__.py')
REQUIREMENTS = open('requirements.txt').readlines()
DEV_REQUIREMENTS = open('dev-requirements.txt').readlines()[1:]
setup(
name='anited-publish',
version=VERSION,
description='Python package with command line interface to turn markdown '
'files into ebooks.',
long_description=README,
long_description_content_type='text/markdown',
author='Christopher Knörndel',
author_email='cknoerndel@anited.de',
url='https://gitlab.com/anited/publish',
packages=[
'publish',
],
package_data={
'publish': ['template.jinja', 'VERSION']
},
entry_points={
'console_scripts': [
'publish = publish.cli:main'
]
},
python_requires=">=3.6",
install_requires=REQUIREMENTS,
tests_require=DEV_REQUIREMENTS,
extras_require={
'dev': DEV_REQUIREMENTS
},
license="MIT",
zip_safe=False,
keywords='publish',
classifiers=[
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
)
| 28 | 78 | 0.65295 |
6de715d666507e3f3849eece5131f4cb5a8c80e7 | 1,187 | py | Python | main.py | brunofornazari/tcc | 57990d68ca196b4da7791faab717d67cfe5497d3 | [
"Unlicense"
] | null | null | null | main.py | brunofornazari/tcc | 57990d68ca196b4da7791faab717d67cfe5497d3 | [
"Unlicense"
] | null | null | null | main.py | brunofornazari/tcc | 57990d68ca196b4da7791faab717d67cfe5497d3 | [
"Unlicense"
] | null | null | null | """
main.py
Main.py é responsável por iniciar o processo o programa completamente, através de duas threads, uma para manter o
servidor de aplicação via flask para poder receber requisições e comunicar com o cliente, seus processos estão
detalhados em server.py e outra thread para manter o fluxo da aplicação, baseado no processo descrito em app.py.
Entre a inicialização de uma thread e outra, foi alocado um tempo de 3s de espera para que haja tempo hábil do
servidor de aplicação ativar seus serviços antes do restante do processo começar a enviar requisições.
Para casos onde for iniciado através de uma máquina diferente de um raspberry pi, é necessário inserir uma variável
de ambiente ENV_TYPE=DEV, para que as bilbiotecas exclusivas do microcomputador não sejam carregadas e causem erros
de importação, podendo ser então iniciado e testado em outros tipos de computadores e sistemas operacionais em geral.
"""
import threading
import time
import server
import app
if __name__ == '__main__' :
threadMain = threading.Thread(target=app.main)
threadServer = threading.Thread(target=server.startServer)
threadServer.start()
time.sleep(3)
threadMain.start() | 40.931034 | 117 | 0.795282 |
6de7ad1350d5b902468a609df5d16498912264b6 | 1,347 | py | Python | examples/DGL/alagnn.py | dongzizhu/GraphGallery | c65eab42daeb52de5019609fe7b368e30863b4ae | [
"MIT"
] | 1 | 2020-07-29T08:00:32.000Z | 2020-07-29T08:00:32.000Z | examples/DGL/alagnn.py | dongzizhu/GraphGallery | c65eab42daeb52de5019609fe7b368e30863b4ae | [
"MIT"
] | null | null | null | examples/DGL/alagnn.py | dongzizhu/GraphGallery | c65eab42daeb52de5019609fe7b368e30863b4ae | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# coding: utf-8
import random
import math
import torch
import dgl
import graphgallery
from graphgallery.datasets import Planetoid
print("GraphGallery version: ", graphgallery.__version__)
print("PyTorch version: ", torch.__version__)
print("DGL version: ", dgl.__version__)
'''
Load Datasets
- cora/citeseer/pubmed
'''
data = Planetoid('cora', root="~/GraphData/datasets/", verbose=False)
graph = data.graph
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
# splits = data.split_nodes()
graphgallery.set_backend("dgl")
# experimental setup in
# `When Do GNNs Work: Understanding and Improving Neighborhood Aggregation
# <https://www.ijcai.org/Proceedings/2020/0181.pdf>`
random.seed(2020)
split = 0.01
n_nodes = graph.num_nodes
sample_size = math.ceil(n_nodes * split)
train_idx = random.sample(range(n_nodes - 1000), sample_size)
train_nodes = [idx if idx < 500 else idx + 1000 for idx in train_idx]
test_nodes = list(range(500, 1500))
from graphgallery.gallery.nodeclas import ALaGCN, ALaGAT
# trainer = ALaGAT(device=device, seed=123).setup_graph(graph).build()
trainer = ALaGCN(device=device, seed=123).setup_graph(graph).build()
trainer.fit(train_nodes, verbose=1)
results = trainer.evaluate(test_nodes)
print(f'Test loss {results.loss:.5}, Test accuracy {results.accuracy:.2%}')
| 32.071429 | 83 | 0.76095 |
6de7d2a8bf2473e87c45ac2498b9443dac0b4f4e | 125 | py | Python | packit_service/service/api/errors.py | majamassarini/packit-service | 12baf67799412c8fa56e2a821cd9d584e2437141 | [
"MIT"
] | 20 | 2019-05-24T12:33:05.000Z | 2020-07-28T06:03:57.000Z | packit_service/service/api/errors.py | majamassarini/packit-service | 12baf67799412c8fa56e2a821cd9d584e2437141 | [
"MIT"
] | 735 | 2019-05-15T11:52:36.000Z | 2020-08-02T23:21:44.000Z | packit_service/service/api/errors.py | majamassarini/packit-service | 12baf67799412c8fa56e2a821cd9d584e2437141 | [
"MIT"
] | 28 | 2019-05-16T13:32:03.000Z | 2020-07-29T10:23:54.000Z | # Copyright Contributors to the Packit project.
# SPDX-License-Identifier: MIT
class ValidationFailed(Exception):
pass
| 17.857143 | 47 | 0.776 |
6dea6c9087b914af198d695841147682ba1f18e7 | 1,453 | py | Python | garden_test/setup.py | jad-b/garden | 44169c57fdaa08e0edd751d7459da99334e97323 | [
"MIT"
] | null | null | null | garden_test/setup.py | jad-b/garden | 44169c57fdaa08e0edd751d7459da99334e97323 | [
"MIT"
] | null | null | null | garden_test/setup.py | jad-b/garden | 44169c57fdaa08e0edd751d7459da99334e97323 | [
"MIT"
] | null | null | null | import subprocess
import os
from setuptools import setup, find_packages
def readme():
with open('README.md') as _file:
return _file.read()
def requirements():
reqs_file = 'reqs.txt'
if os.path.isfile(reqs_file):
with open('reqs.txt') as reqs:
return [line.strip() for line in reqs
if line and not line.startswith('#')]
return []
def latest_git_tag():
try:
tag = subprocess.check_output(
['git', 'describe', '--abbrev=0', '--tags']
).decode().rstrip()
except subprocess.CalledProcessError:
return '0.0.0'
return tag
setup(
name='garden_test',
version=latest_git_tag(),
long_description=readme(),
description='Python package for testing garden',
author='Jeremy Dobbins-Bucklad',
author_email='j.american.db@gmail.com',
url='https://github.com/jad-b/garden',
install_requires=requirements(),
packages = find_packages(),
package_dir = {'garden': 'garden_test'},
py_modules=['testfile'],
entry_points={
'garden.bump': ['garden_test = garden_test.bump:Bumper.bump'],
},
zip_safe=False,
include_package_data=True,
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5'
),
)
| 26.907407 | 70 | 0.618032 |
6dea9c8146d56fa2b4a9cdd2da0bad21ab08f14c | 1,078 | py | Python | test/solutions/test_checkout.py | DPNT-Sourcecode/CHK-mxxq01 | 85be1ef3e87a6490d1490b64596de25d7e3cb60e | [
"Apache-2.0"
] | null | null | null | test/solutions/test_checkout.py | DPNT-Sourcecode/CHK-mxxq01 | 85be1ef3e87a6490d1490b64596de25d7e3cb60e | [
"Apache-2.0"
] | null | null | null | test/solutions/test_checkout.py | DPNT-Sourcecode/CHK-mxxq01 | 85be1ef3e87a6490d1490b64596de25d7e3cb60e | [
"Apache-2.0"
] | null | null | null | import unittest
from lib.solutions.checkout import checkout
class TestSum(unittest.TestCase):
def test_checkout(self):
self.assertEqual(checkout("ABC"), 50+30+20)
self.assertEqual(checkout("ABCCCD"), 50+30+20*3+15)
self.assertEqual(checkout("AAA"), 130)
self.assertEqual(checkout("AAAAB"), 130+50+30)
self.assertEqual(checkout("AAAAAAAAB"), 130+200+30)
self.assertEqual(checkout("EEBB"), 40*2+30)
self.assertEqual(checkout("EEBBB"), 40*2+45)
self.assertEqual(checkout("EEEEBBB"), 40*4+30)
self.assertEqual(checkout("FF"), 20)
self.assertEqual(checkout("FFF"), 20)
self.assertEqual(checkout("FFFFF"), 40)
self.assertEqual(checkout("FFFFFF"), 40)
def test_group_buy(self):
self.assertEqual(checkout("ZZTSR"), 50+20+45)
self.assertEqual(checkout("ZZZ"), 45)
self.assertEqual(checkout("ZZZZ"), 45+21)
self.assertEqual(checkout("ZZZX"), 45+17)
self.assertEqual(checkout("ZZZZXS"), 45*2)
if __name__ == '__main__':
unittest.main()
| 35.933333 | 59 | 0.646568 |
6deb927562ea3e9179ad55bccae3b4caee1a3331 | 338 | py | Python | libs/imagemetadata.py | epinux/labelImg | a4002eb771f9c82b703a3fcd0b554e0030bf24e7 | [
"MIT"
] | null | null | null | libs/imagemetadata.py | epinux/labelImg | a4002eb771f9c82b703a3fcd0b554e0030bf24e7 | [
"MIT"
] | null | null | null | libs/imagemetadata.py | epinux/labelImg | a4002eb771f9c82b703a3fcd0b554e0030bf24e7 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from libs.imagemetadata_ui import Ui_imagemetadata
class ImageMetadata(QWidget, Ui_imagemetadata):
def __init__(self, parent=None):
super(ImageMetadata, self).__init__(parent)
self.setupUi(self)
| 18.777778 | 51 | 0.745562 |
6debe89876c11c370db73006de84c2358493d8ef | 19,992 | py | Python | test/coco_save.py | ZCDu/CenternessNet | 03f5d01999a4e1595eaceef9f62b4450ed017843 | [
"MIT"
] | null | null | null | test/coco_save.py | ZCDu/CenternessNet | 03f5d01999a4e1595eaceef9f62b4450ed017843 | [
"MIT"
] | null | null | null | test/coco_save.py | ZCDu/CenternessNet | 03f5d01999a4e1595eaceef9f62b4450ed017843 | [
"MIT"
] | null | null | null | import os
import cv2
import pdb
import json
import copy
import numpy as np
import torch
from PIL import Image, ImageDraw, ImageFont
import matplotlib.pyplot as plt
import matplotlib
import math
from tqdm import tqdm
from config import system_configs
from utils import crop_image, normalize_
from external.nms import soft_nms, soft_nms_merge
import pdb
colours = np.random.rand(80, 3)
def _rescale_dets(detections, ratios, borders, sizes):
xs, ys = detections[..., 0:4:2], detections[..., 1:4:2]
xs /= ratios[:, 1][:, None, None]
ys /= ratios[:, 0][:, None, None]
xs -= borders[:, 2][:, None, None]
ys -= borders[:, 0][:, None, None]
tx_inds = xs[:, :, 0] <= -5
bx_inds = xs[:, :, 1] >= sizes[0, 1] + 5
ty_inds = ys[:, :, 0] <= -5
by_inds = ys[:, :, 1] >= sizes[0, 0] + 5
np.clip(xs, 0, sizes[:, 1][:, None, None], out=xs)
np.clip(ys, 0, sizes[:, 0][:, None, None], out=ys)
detections[:, tx_inds[0, :], 4] = -1
detections[:, bx_inds[0, :], 4] = -1
detections[:, ty_inds[0, :], 4] = -1
detections[:, by_inds[0, :], 4] = -1
def save_image(data, fn):
sizes = np.shape(data)
height = float(sizes[0])
width = float(sizes[1])
fig = plt.figure()
fig.set_size_inches(width / height, 1, forward=False)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
ax.imshow(data)
plt.savefig(fn, dpi=height)
plt.close()
def kp_decode(nnet, images, K, ae_threshold=0.5, kernel=3):
detections, center = nnet.test([images],
ae_threshold=ae_threshold,
K=K,
kernel=kernel)
detections = detections.data.cpu().numpy()
center = center.data.cpu().numpy()
return detections, center
def kp_detection(db, nnet, result_dir, debug=False, decode_func=kp_decode):
debug_dir = os.path.join(result_dir, "debug")
if not os.path.exists(debug_dir):
os.makedirs(debug_dir)
if db.split != "trainval":
db_inds = db.db_inds[:100] if debug else db.db_inds
else:
db_inds = db.db_inds[:100] if debug else db.db_inds[:5000]
num_images = db_inds.size
K = db.configs["top_k"]
ae_threshold = db.configs["ae_threshold"]
nms_kernel = db.configs["nms_kernel"]
scales = db.configs["test_scales"]
weight_exp = db.configs["weight_exp"]
merge_bbox = db.configs["merge_bbox"]
categories = db.configs["categories"]
nms_threshold = db.configs["nms_threshold"]
max_per_image = db.configs["max_per_image"]
nms_algorithm = {
"nms": 0,
"linear_soft_nms": 1,
"exp_soft_nms": 2
}[db.configs["nms_algorithm"]]
top_bboxes = {}
num_images = 1
for root, dirs, files in os.walk(
"/media/dl/train_disk/zcdu/work/CenterNet/pic"):
for f in files:
#db_ind = db_inds[ind]
#image_id = db.image_ids(db_ind)
#image_file = db.image_file(db_ind)
#name = os.path.join(root, f)
#print('name':name)
#image_file = os.path.join('/media/dl/train_disk/zcdu/work/CenterNet',
# name)
image_file = os.path.join(root, f)
print("image:", image_file)
image = cv2.imread(image_file)
height, width = image.shape[0:2]
detections = []
center_points = []
for scale in scales:
new_height = int(height * scale)
new_width = int(width * scale)
new_center = np.array([new_height // 2, new_width // 2])
inp_height = new_height | 127
inp_width = new_width | 127
images = np.zeros((1, 3, inp_height, inp_width),
dtype=np.float32)
ratios = np.zeros((1, 2), dtype=np.float32)
borders = np.zeros((1, 4), dtype=np.float32)
sizes = np.zeros((1, 2), dtype=np.float32)
out_height, out_width = (inp_height + 1) // 4, (inp_width +
1) // 4
height_ratio = out_height / inp_height
width_ratio = out_width / inp_width
resized_image = cv2.resize(image, (new_width, new_height))
resized_image, border, offset = crop_image(
resized_image, new_center, [inp_height, inp_width])
resized_image = resized_image / 255.
normalize_(resized_image, db.mean, db.std)
images[0] = resized_image.transpose((2, 0, 1))
borders[0] = border
sizes[0] = [int(height * scale), int(width * scale)]
ratios[0] = [height_ratio, width_ratio]
images = np.concatenate((images, images[:, :, :, ::-1]),
axis=0)
images = torch.from_numpy(images)
dets, center = decode_func(nnet,
images,
K,
ae_threshold=ae_threshold,
kernel=nms_kernel)
dets = dets.reshape(2, -1, 8)
center = center.reshape(2, -1, 4)
dets[1, :, [0, 2]] = out_width - dets[1, :, [2, 0]]
center[1, :, [0]] = out_width - center[1, :, [0]]
dets = dets.reshape(1, -1, 8)
center = center.reshape(1, -1, 4)
_rescale_dets(dets, ratios, borders, sizes)
center[..., [0]] /= ratios[:, 1][:, None, None]
center[..., [1]] /= ratios[:, 0][:, None, None]
center[..., [0]] -= borders[:, 2][:, None, None]
center[..., [1]] -= borders[:, 0][:, None, None]
np.clip(center[..., [0]],
0,
sizes[:, 1][:, None, None],
out=center[..., [0]])
np.clip(center[..., [1]],
0,
sizes[:, 0][:, None, None],
out=center[..., [1]])
dets[:, :, 0:4] /= scale
center[:, :, 0:2] /= scale
if scale == 1:
center_points.append(center)
detections.append(dets)
detections = np.concatenate(detections, axis=1)
center_points = np.concatenate(center_points, axis=1)
classes = detections[..., -1]
classes = classes[0]
detections = detections[0]
center_points = center_points[0]
valid_ind = detections[:, 4] > -1
valid_detections = detections[valid_ind]
box_width = valid_detections[:, 2] - valid_detections[:, 0]
box_height = valid_detections[:, 3] - valid_detections[:, 1]
s_ind = (box_width * box_height <= 22500)
l_ind = (box_width * box_height > 22500)
s_detections = valid_detections[s_ind]
l_detections = valid_detections[l_ind]
s_left_x = (2 * s_detections[:, 0] + s_detections[:, 2]) / 3
s_right_x = (s_detections[:, 0] + 2 * s_detections[:, 2]) / 3
s_top_y = (2 * s_detections[:, 1] + s_detections[:, 3]) / 3
s_bottom_y = (s_detections[:, 1] + 2 * s_detections[:, 3]) / 3
s_temp_score = copy.copy(s_detections[:, 4])
s_detections[:, 4] = -1
center_x = center_points[:, 0][:, np.newaxis]
center_y = center_points[:, 1][:, np.newaxis]
s_left_x = s_left_x[np.newaxis, :]
s_right_x = s_right_x[np.newaxis, :]
s_top_y = s_top_y[np.newaxis, :]
s_bottom_y = s_bottom_y[np.newaxis, :]
ind_lx = (center_x - s_left_x) > 0
ind_rx = (center_x - s_right_x) < 0
ind_ty = (center_y - s_top_y) > 0
ind_by = (center_y - s_bottom_y) < 0
ind_cls = (center_points[:, 2][:, np.newaxis] -
s_detections[:, -1][np.newaxis, :]) == 0
ind_s_new_score = np.max(
((ind_lx + 0) & (ind_rx + 0) & (ind_ty + 0) & (ind_by + 0) &
(ind_cls + 0)),
axis=0) == 1
index_s_new_score = np.argmax(
((ind_lx + 0) & (ind_rx + 0) & (ind_ty + 0) & (ind_by + 0) &
(ind_cls + 0))[:, ind_s_new_score],
axis=0)
s_detections[:, 4][ind_s_new_score] = (
s_temp_score[ind_s_new_score] * 2 +
center_points[index_s_new_score, 3]) / 3
l_left_x = (3 * l_detections[:, 0] + 2 * l_detections[:, 2]) / 5
l_right_x = (2 * l_detections[:, 0] + 3 * l_detections[:, 2]) / 5
l_top_y = (3 * l_detections[:, 1] + 2 * l_detections[:, 3]) / 5
l_bottom_y = (2 * l_detections[:, 1] + 3 * l_detections[:, 3]) / 5
l_temp_score = copy.copy(l_detections[:, 4])
l_detections[:, 4] = -1
center_x = center_points[:, 0][:, np.newaxis]
center_y = center_points[:, 1][:, np.newaxis]
l_left_x = l_left_x[np.newaxis, :]
l_right_x = l_right_x[np.newaxis, :]
l_top_y = l_top_y[np.newaxis, :]
l_bottom_y = l_bottom_y[np.newaxis, :]
ind_lx = (center_x - l_left_x) > 0
ind_rx = (center_x - l_right_x) < 0
ind_ty = (center_y - l_top_y) > 0
ind_by = (center_y - l_bottom_y) < 0
ind_cls = (center_points[:, 2][:, np.newaxis] -
l_detections[:, -1][np.newaxis, :]) == 0
ind_l_new_score = np.max(
((ind_lx + 0) & (ind_rx + 0) & (ind_ty + 0) & (ind_by + 0) &
(ind_cls + 0)),
axis=0) == 1
index_l_new_score = np.argmax(
((ind_lx + 0) & (ind_rx + 0) & (ind_ty + 0) & (ind_by + 0) &
(ind_cls + 0))[:, ind_l_new_score],
axis=0)
l_detections[:, 4][ind_l_new_score] = (
l_temp_score[ind_l_new_score] * 2 +
center_points[index_l_new_score, 3]) / 3
detections = np.concatenate([l_detections, s_detections], axis=0)
detections = detections[np.argsort(-detections[:, 4])]
classes = detections[..., -1]
#for i in range(detections.shape[0]):
# box_width = detections[i,2]-detections[i,0]
# box_height = detections[i,3]-detections[i,1]
# if box_width*box_height<=22500 and detections[i,4]!=-1:
# left_x = (2*detections[i,0]+1*detections[i,2])/3
# right_x = (1*detections[i,0]+2*detections[i,2])/3
# top_y = (2*detections[i,1]+1*detections[i,3])/3
# bottom_y = (1*detections[i,1]+2*detections[i,3])/3
# temp_score = copy.copy(detections[i,4])
# detections[i,4] = -1
# for j in range(center_points.shape[0]):
# if (classes[i] == center_points[j,2])and \
# (center_points[j,0]>left_x and center_points[j,0]< right_x) and \
# ((center_points[j,1]>top_y and center_points[j,1]< bottom_y)):
# detections[i,4] = (temp_score*2 + center_points[j,3])/3
# break
# elif box_width*box_height > 22500 and detections[i,4]!=-1:
# left_x = (3*detections[i,0]+2*detections[i,2])/5
# right_x = (2*detections[i,0]+3*detections[i,2])/5
# top_y = (3*detections[i,1]+2*detections[i,3])/5
# bottom_y = (2*detections[i,1]+3*detections[i,3])/5
# temp_score = copy.copy(detections[i,4])
# detections[i,4] = -1
# for j in range(center_points.shape[0]):
# if (classes[i] == center_points[j,2])and \
# (center_points[j,0]>left_x and center_points[j,0]< right_x) and \
# ((center_points[j,1]>top_y and center_points[j,1]< bottom_y)):
# detections[i,4] = (temp_score*2 + center_points[j,3])/3
# break
# reject detections with negative scores
keep_inds = (detections[:, 4] > -1)
detections = detections[keep_inds]
classes = classes[keep_inds]
image_id = 0
top_bboxes[image_id] = {}
for j in range(categories):
keep_inds = (classes == j)
top_bboxes[image_id][j +
1] = detections[keep_inds][:, 0:7].astype(
np.float32)
if merge_bbox:
soft_nms_merge(top_bboxes[image_id][j + 1],
Nt=nms_threshold,
method=nms_algorithm,
weight_exp=weight_exp)
else:
soft_nms(top_bboxes[image_id][j + 1],
Nt=nms_threshold,
method=nms_algorithm)
top_bboxes[image_id][j + 1] = top_bboxes[image_id][j + 1][:,
0:5]
scores = np.hstack([
top_bboxes[image_id][j][:, -1]
for j in range(1, categories + 1)
])
if len(scores) > max_per_image:
kth = len(scores) - max_per_image
thresh = np.partition(scores, kth)[kth]
for j in range(1, categories + 1):
keep_inds = (top_bboxes[image_id][j][:, -1] >= thresh)
top_bboxes[image_id][j] = top_bboxes[image_id][j][
keep_inds]
if debug:
#image_file = db.image_file(db_ind)
#image_file = os.path.join(
# "/media/dl/train_disk/zcdu/work/CenterNet", name)
image = cv2.imread(image_file)
im = image[:, :, (2, 1, 0)]
fig, ax = plt.subplots(figsize=(12, 12))
fig = ax.imshow(im, aspect='equal')
plt.axis('off')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
#bboxes = {}
for j in range(1, categories + 1):
keep_inds = (top_bboxes[image_id][j][:, -1] >= 0.4)
cat_name = db.class_name(j)
bboxes = top_bboxes[image_id][j][keep_inds]
if len(bboxes) > 3:
bboxes = select_box(bboxes)
#print('test select_box bboxes later:', bboxes.shape)
if len(bboxes) == 0:
continue
p1 = 0
for bbox in bboxes:
p1 += 1
bbox = bbox[0:4].astype(np.int32)
xmin = bbox[0]
ymin = bbox[1]
xmax = bbox[2]
ymax = bbox[3]
#if (xmax - xmin) * (ymax - ymin) > 5184:
ax.add_patch(
plt.Rectangle((xmin, ymin),
xmax - xmin,
ymax - ymin,
fill=False,
edgecolor=colours[j - 1],
linewidth=4.0))
ax.text(xmin + 1,
ymin - 3,
'{:s}'.format(cat_name),
bbox=dict(facecolor=colours[j - 1],
ec='black',
lw=2,
alpha=0.5),
fontsize=15,
color='white',
weight='bold')
print("count:!!!!!!!!", p1)
out_name = f.replace('jpg', 'pdf')
debug_file1 = os.path.join(
"/media/dl/train_disk/zcdu/work/CenterNet", "result",
"centernet_lite", "{}".format(out_name))
debug_file2 = os.path.join(
"/media/dl/train_disk/zcdu/work/CenterNet", "result",
"centernet_lite", f)
plt.savefig(debug_file1)
plt.savefig(debug_file2)
plt.close()
debug_file = os.path.join(
"/media/dl/train_disk/zcdu/work/CenterNet", "result",
"centernet_lite", '{}'.format(f))
cv2.imwrite(debug_file, image,
[int(cv2.IMWRITE_JPEG_QUALITY), 100])
#result_json = os.path.join(result_dir, "results.json")
#detections = db.convert_to_coco(top_bboxes)
#with open(result_json, "w") as f:
# json.dump(detections, f)
#cls_ids = list(range(1, categories + 1))
#image_ids = [db.image_ids(ind) for ind in db_inds]
#db.evaluate(result_json, cls_ids, image_ids)
print('successful!!!!')
return 0
def select_box(boxes):
length = len(boxes)
if length > 3:
print('test coco_Save boxes:', boxes)
areas = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
#print('test coco_Save areas:', areas)
#print('test coco_Save areas:', areas.shape)
max_index = np.argsort(-areas)[0]
max_area = areas[max_index]
print('select_box max_index:', boxes[max_index])
count_m = 0
for i in range(length):
if i == max_index:
continue
else:
if (int(boxes[i][0]) >= int(boxes[max_index][0])
and int(boxes[i][1]) >= int(boxes[max_index][1])
and int(boxes[i][2]) <= int(boxes[max_index][2])
and int(boxes[i][3]) <= int(boxes[max_index][3])):
print('test inside max_area:', boxes[i])
count_m = 1
break
#for m in range(length):
# if (math.isclose(boxes[m][0],
# boxes[max_index][0],
# abs_tol=0.00001)
# and math.isclose(boxes[m][1],
# boxes[max_index][1],
# abs_tol=0.00001)):
# count_m = 1
# break
# elif (math.isclose(boxes[m][2],
# boxes[max_index][2],
# abs_tol=0.00001)
# and math.isclose(boxes[m][3],
# boxes[max_index][3],
# abs_tol=0.00001)):
# count_m = 1
# break
# else:
# continue
if (count_m == 1):
print('test coco delete!!!')
boxes = np.delete(boxes, max_index, axis=0)
count_m = 0
return boxes
def testing(db, nnet, result_dir, debug=False):
return globals()[system_configs.sampling_function](db,
nnet,
result_dir,
debug=debug)
| 42.626866 | 89 | 0.456633 |
6dec0625c10c417a63b087f29b4b429210299d04 | 752 | py | Python | lcd/interrupts/interrupt2.py | BornToDebug/homeStruction | 354e03c05cb363d8397d0e2d7afeb78a029266f9 | [
"Apache-2.0"
] | 6 | 2016-08-31T16:46:54.000Z | 2017-09-15T19:34:30.000Z | lcd/interrupts/interrupt2.py | BornToDebug/homeStruction | 354e03c05cb363d8397d0e2d7afeb78a029266f9 | [
"Apache-2.0"
] | 4 | 2016-09-02T09:18:41.000Z | 2016-09-02T09:24:08.000Z | lcd/interrupts/interrupt2.py | BornToDebug/homeStruction | 354e03c05cb363d8397d0e2d7afeb78a029266f9 | [
"Apache-2.0"
] | null | null | null | import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
#now we'll define the threaded callback function
#this will run in another threadwhen our event is detected
def my_callback(channel):
print "Rising edge detected on port 24 - even though, in the main thread,"
print "we are still waiting for a falling edge - how cool?\n"
raw_input("Press Enter when ready\n>")
GPIO.add_event_detect(24, GPIO.RISING, callback=my_callback, bouncetime=300)
try:
print "Waiting for falling edge on port 23"
GPIO.wait_for_edge(23, GPIO.FALLING)
print "Falling edge detected. Here endeth the second lesson."
except KetboardInterrupt:
GPIO.cleanup()
GPIO.cleanup()
| 30.08 | 76 | 0.772606 |
6dee89b3a35ae4ccdd9553002d458259723951b4 | 31,184 | py | Python | Apps/polls/Views/CourseArrangement.py | shadowofgost/WebEngineering | 693af827e3458806cdace959262cf393d29f6504 | [
"Apache-2.0"
] | 1 | 2021-04-05T05:40:17.000Z | 2021-04-05T05:40:17.000Z | Apps/polls/Views/CourseArrangement.py | shadowofgost/WebEngineering | 693af827e3458806cdace959262cf393d29f6504 | [
"Apache-2.0"
] | null | null | null | Apps/polls/Views/CourseArrangement.py | shadowofgost/WebEngineering | 693af827e3458806cdace959262cf393d29f6504 | [
"Apache-2.0"
] | null | null | null |
from django.http import HttpResponse
from django.db.models import Q
from drf_yasg.utils import swagger_auto_schema
from drf_yasg.openapi import Parameter, Schema, Response, TYPE_INTEGER, TYPE_OBJECT, TYPE_STRING, IN_QUERY
from json import dumps
from .. import models
from .Public import responses_success, responses_fail, get_request_args, data_page_response, content_type_tmp, post_search, put_success, put_error, post_error, data_base_error_specific, patch_success, patch_error, id_error, delete_schema
from rest_framework.views import APIView
from django.views.decorators.csrf import csrf_exempt
class CourseArrangement(APIView):
'''
list
list all information about Equipment
'''
data_schema = {
'id':
Schema(
title='课程id',
description='课程id,其中课程id是唯一的标识',
type=TYPE_INTEGER,
format='int32',
enum=None,
),
'id_curricula__name':
Schema(
title='课程名称',
description='课程名称 是课程安排表对应的课程课程名称',
type=TYPE_STRING,
format='string',
enum=None,
),
'timebegin':
Schema(
title='课程开时间 ',
description=' 项目开始时间记录最后更新时间;(2000-1-1 0:0:0 经过的秒),必须有值 ',
type=TYPE_INTEGER,
format='int32',
enum=None,
),
'timeend':
Schema(
title='课程结束时间',
description='项目结束时间记录最后更新时间;(2000-1-1 0:0:0 经过的秒),必须有值 ',
type=TYPE_INTEGER,
format='int32',
enum=None,
),
'id_location__name':
Schema(
title=' 课程所在教室的地点的名称 ',
description='课程所在教室的地点的名称 ',
type=TYPE_STRING,
format='string',
enum=None,
),
'id_speaker__name':
Schema(
title='主讲人',
description='主讲人也就是课程老师的姓名',
type=TYPE_STRING,
format='string',
enum=None,
),
'attr':
Schema(
title='课程属性',
description='1代表实验类型、2代表普通上课类型、3讲座考勤类型,必须有值',
type=TYPE_INTEGER,
format='int32',
enum=[1, 2, 3],
),
'charge':
Schema(
title=' 是否收费的字段 ',
description=' 免费0、收费1、开放2,必须有值 ',
type=TYPE_INTEGER,
format='int32',
enum=[0, 1, 2],
),
'pwaccess':
Schema(
title='派位',
description='不派位0、刷卡派位1(派位指用户刷卡时系统指定座位),必须有值',
type=TYPE_INTEGER,
format='int32',
enum=[0, 1],
),
'pwcontinuous':
Schema(
title='派位连续性',
description='连续派位0、随机派位1,必须有值',
type=TYPE_INTEGER,
format='int32',
enum=[0, 1],
),
'pwdirection':
Schema(
title='排位顺序',
description='顺序派位0、逆序派位1(当设置为随机派位时本功能无效),必须有值',
type=TYPE_INTEGER,
format='int32',
enum=[0, 1],
),
'dooropen':
Schema(
title='是否开门',
description='匹配的用户刷卡是否开门,0开门,1不开门',
type=TYPE_INTEGER,
format='int32',
enum=[0, 1],
),
'timebegincheckbegin':
Schema(
title='最早开始考勤的最早时间',
description=' 安排考勤开始的最早时间(单位为分钟,0代表无效),必须有值 ',
type=TYPE_INTEGER,
format='int32',
enum=None,
),
'timebegincheckend':
Schema(
title='最早签到结束时间 ',
description=' 安排考勤开始的最迟时间(单位为分钟,0代表无效),必须有值 ',
type=TYPE_INTEGER,
format='int32',
enum=None,
),
'timeendcheckbegin':
Schema(
title='考勤结束的最早时间(签退) ',
description=' 安排考勤结束的最早时间(单位为分钟,0代表无效),必须有值 ',
type=TYPE_INTEGER,
format='int32',
enum=None,
),
'timeendcheckend':
Schema(
title='考勤结束的最迟时间(签退)',
description=' 安排考勤结束的最迟时间(单位为分钟,0代表无效),必须有值',
type=TYPE_INTEGER,
format='int32',
enum=None,
),
'listdepts':
Schema(
title=' 参加本安排的学生部门列表 ',
description=' 参加本安排的学生部门列表 ',
type=TYPE_STRING,
format='string',
enum=None,
),
'rangeusers':
Schema(
title='参加本安排的学生学号列表(与RangeUser为相加的关系)',
description='参加本安排的学生学号列表(与RangeUser为相加的关系)',
type=TYPE_STRING,
format='string',
enum=None,
),
'rangeequs':
Schema(
title=' 座位表 ',
description=' 课程使用的座位范围列表 ',
type=TYPE_STRING,
format='string',
enum=None,
),
'listplaces':
Schema(
title=' 课程使用的地点 ',
description=' 课程使用的地点列表(与课程使用的座位范围列表为相加的关系)',
type=TYPE_STRING,
format='string',
enum=None,
),
'mapuser2equ':
Schema(
title='学生和座位对应表',
description='学生和座位对应表',
type=TYPE_STRING,
format='string',
enum=None,
),
'aboutspeaker':
Schema(
title='本课程主讲人介绍',
description=' 本课程主讲人也就是上课老师的介绍',
type=TYPE_STRING,
format='string',
enum=None,
),
'rem':
Schema(
title='课程介绍',
description='课程内容的介绍',
type=TYPE_STRING,
format='string',
enum=None,
),
'timeupdate':
Schema(
title='update time ',
description=' 记录最后更新时间;(2000-1-1 0:0:0 经过的秒),必须有值 ',
type=TYPE_INTEGER,
format='int32',
enum=None,
),
'idmanager__name':
Schema(
title=' 更新信息的管理员的姓名 ',
description=' 更新信息的管理员的姓名 ',
type=TYPE_STRING,
format='string',
enum=None,
)
}
data_schema_present = Schema(
title='查询成功的返回',
description='查询成功返回的函数值',
type=TYPE_OBJECT, # 类型
properties=data_schema
)
get_responses_success = Schema(
title='成功获取查询数据',
description='这个接口用于展示成功获取全部数据的格式',
type=TYPE_OBJECT,
properties={
'page': Schema(
title='页码',
description='用于表示展示的页码数',
type=TYPE_INTEGER,
format='int32',
),
'limits': Schema(
title='页码',
description='用于表示每页展示的行数',
type=TYPE_INTEGER,
format='int32',
),
'error_code': Schema(
title='是否有报错数据',
description='用于传达是否有报错数据,0表示没有报错数据,1表示有报错数据',
type=TYPE_INTEGER,
format='int32',
),
'data': Schema(
title='数据',
description='用于传递查询到的全部数据',
type=TYPE_OBJECT,
properties=[data_schema_present, data_schema_present]
),
}
)
CourseInformation_get_responses_success = Response(
description='查询课程信息成功的响应',
schema=get_responses_success,
examples=None,
)
CourseInformation_get_responses_fail = Response(
description='查询课程信息失败的响应',
schema=responses_fail,
examples={
'error_code': 1,
'message': '查询课程信息失败'
}
)
page_get_parammeter = Parameter(
name='page',
in_=IN_QUERY,
description='查询时设定的页码数',
required=True,
type=TYPE_INTEGER,
format='int32',
)
limits_get_parammeter = Parameter(
name='limits',
in_=IN_QUERY,
description='查询时设定的每页行数',
required=True,
type=TYPE_INTEGER,
format='int32',
)
@swagger_auto_schema(
request_body=None,
manual_parameters=[
page_get_parammeter, limits_get_parammeter],
operation_id=None,
operation_description='这个端口用于查询课程信息',
operation_summary=None,
security=None,
responses={
200: CourseInformation_get_responses_success, 401: CourseInformation_get_responses_fail
},
tags=None)
@get_request_args
@csrf_exempt
def get(self, request, args, session):
is_login = request.COOKIES.get('is_login')
if not request.session.get(is_login, None):
return HttpResponse(dumps({'code': 0}), content_type=content_type_tmp, charset='utf-8')
pages = int(args.get('page', 1))
limits = int(args.get('limits', 20))
data_equipment = models.TCyplan.objects.all().values('id',
'id_curricula__name', 'timebegin', 'timeend', 'id_location__name', 'id_speaker__name', 'attr', 'charge', 'pwaccess', 'pwcontinuous', 'pwdirection', 'dooropen', 'timebegincheckbegin', 'timebegincheckend', 'timeendcheckbegin', 'timeendcheckend', 'rangeusers', 'listdepts', 'rangeequs', 'timeupdate', 'listplaces', 'idmanager__name', 'mapuser2equ', 'aboutspeaker', 'rem').distinct().order_by('id')
return data_page_response(data_equipment, pages, limits)
'''
list
list all information about Equipment
'''
CourseArrangement_post_request_body = Schema(
title='查询课程安排所需要的信息', # 标题
description=' 输入查询字符串用于查询课程安排信息 ', # 接口描述
type=TYPE_OBJECT, # 类型 "object" ,"string" ,"number" ,"integer" ,"boolean" ,"array"" ,"boolean" ,"array" ,"file"
format=None, # 格式 date,date-time,password,binary,bytes,float,double,int32,int64,email,ipv4, ipv6, uri, uuid, slug, decimal
enum=None, # [列表]列举参数的请求值
pattern=None, # 当 format为 string是才填此项
# 当 type为object时,为dict对象 {'str1': Schema对象, 'str2': SchemaRef对象}
properties=post_search,
required=['input_string', 'page', 'limits'], # [必须的属性列表]
items=None, # 当type是array时,填此项
)
CourseArrangement_post_responses_success = Response(
description='查询课程安排表成功的响应',
schema=get_responses_success,
examples={
'error_code': 0,
'message': '查询成功'
})
CourseArrangement_post_responses_fail = Response(
description='查询课程安排表失败的响应',
schema=responses_fail,
examples={
'error_code': 1,
'message': post_error
})
@swagger_auto_schema(
request_body=CourseArrangement_post_request_body,
manual_parameters=None,
operation_id=None,
operation_description='这个端口用于查询课程安排表(某些条件下的课程安排表)',
operation_summary=None,
security=None,
responses={
201: CourseArrangement_post_responses_success,
400: CourseArrangement_post_responses_fail
},
tags=None)
@get_request_args
@csrf_exempt
def post(self, request, args, session):
is_login = request.COOKIES.get('is_login')
if not request.session.get(is_login, None):
return HttpResponse(dumps({'code': 0}), content_type=content_type_tmp, charset='utf-8')
input_string = args.get('input_string', None)
pages = int(args.get('page', 1))
limits = int(args.get('limits', 20))
if input_string == None:
data_equipment = models.TCyplan.objects.all().values(
'id',
'id_curricula__name',
'timebegin',
'timeend',
'id_location__name',
'id_speaker__name',
'attr',
'charge',
'pwaccess',
'pwcontinuous',
'pwdirection',
'dooropen',
'timebegincheckbegin',
'timebegincheckend',
'timeendcheckbegin',
'timeendcheckend',
'rangeusers',
'listdepts',
'rangeequs',
'timeupdate',
'listplaces',
'idmanager__name',
'mapuser2equ',
'aboutspeaker',
'rem'
).distinct().order_by('id')
else:
input_string = input_string.strip()
try:
test_input = eval(input_string)
except:
test_input = input_string
if isinstance(test_input, int):
data_equipment = models.TCyplan.objects.filter(
Q(id=test_input)
| Q(id_curricula=test_input)
| Q(timebegin=test_input)
| Q(timeend=test_input)
| Q(id_location=test_input)
| Q(id_speaker=test_input)
| Q(attr=test_input)
| Q(charge=test_input)
| Q(pwaccess=test_input)
| Q(pwcontinuous=test_input)
| Q(pwdirection=test_input)
| Q(dooropen=test_input)
| Q(timebegincheckbegin=test_input)
| Q(timebegincheckend=test_input)
| Q(timeendcheckbegin=test_input)
| Q(timeendcheckend=test_input)
| Q(timeupdate=test_input)
| Q(idmanager=test_input)).values(
'id',
'id_curricula',
'timebegin',
'timeend',
'id_location',
'id_speaker',
'attr',
'charge',
'pwaccess',
'pwcontinuous',
'pwdirection',
'dooropen',
'timebegincheckbegin',
'timebegincheckend',
'timeendcheckbegin',
'timeendcheckend',
'rangeusers',
'listdepts',
'rangeequs',
'timeupdate',
'listplaces',
'idmanager',
'mapuser2equ',
'aboutspeaker',
'rem'
).distinct().order_by('id')
else:
data_equipment = models.TCyplan.objects.filter(
Q(rem__icontains=test_input)
| Q(rangeequs__icontains=test_input)
| Q(rangeequs__icontains=test_input)
| Q(listdepts__icontains=test_input)
| Q(listplaces__icontains=test_input)
| Q(mapuser2equ__icontains=test_input)
| Q(aboutspeaker__icontains=test_input)
| Q(idmanager__name__icontains=test_input)
| Q(id_location__name__icontains=test_input)
| Q(id_speaker__name__icontains=test_input)).values(
'id',
'id_curricula',
'timebegin',
'timeend',
'id_location__name',
'id_speaker__name',
'attr',
'charge',
'pwaccess',
'pwcontinuous',
'pwdirection',
'dooropen',
'timebegincheckbegin',
'timebegincheckend',
'timeendcheckbegin',
'timeendcheckend',
'rangeusers',
'listdepts',
'rangeequs',
'timeupdate',
'listplaces',
'idmanager__name',
'mapuser2equ',
'aboutspeaker',
'rem',
).distinct().order_by('id')
return data_page_response(data_equipment, pages, limits)
'''
list
list all information about Equipment
'''
CourseArrangement_put_request_body = Schema(
title=' 增加课程安排表需要的数据 ', # 标题
description='向数据库增加课程安排表需要的数据和字段', # 接口描述
type=TYPE_OBJECT, # 类型 "object" ,"string" ,"number" ,"integer" ,"boolean" ,"array" ,"file"
properties=data_schema,
required=[
'id', 'id_curricula__name', 'timebegin', 'timeend', 'id_location__name', 'id_speaker__name',
'attr', 'charge', 'pwaccess', 'pwcontinuous',
'pwdirection', 'dooropen', 'timebegincheckbegin',
'timebegincheckend', 'timeendcheckbegin', 'timeendcheckend',
'rangeusers', 'listdepts', 'rangeequs', 'timeupdate', 'listplaces',
'idmanager__name', 'mapuser2equ', 'aboutspeaker', 'rem']
)
CourseArrangement_put_responses_success = Response(
description='增加课程安排表数据成功的响应',
schema=responses_success,
examples={
'error_code': 0,
'message': put_success
})
CourseArrangement_put_responses_fail = Response(
description='增加课程安排表数据失败的响应',
schema=responses_fail,
examples={
'error_code': 1,
'message': put_error
})
@swagger_auto_schema(
request_body=CourseArrangement_put_request_body,
manual_parameters=None,
operation_id=None,
operation_description='这个端口用于向数据库增加课程安排表的数据',
operation_summary=None,
security=None,
responses={
201: CourseArrangement_put_responses_success,
400: CourseArrangement_put_responses_fail
},
tags=None)
@get_request_args
@csrf_exempt
def put(self, request, args, session):
field_name = [
'id', 'id_curricula__name', 'timebegin', 'timeend', 'id_location__name', 'id_speaker__name', 'timeupdate',
'idmanager__name', 'aboutspeaker', 'rem'
]
is_login = request.COOKIES.get('is_login')
if not request.session.get(is_login, None):
return HttpResponse(dumps({'code': 0}), content_type=content_type_tmp, charset='utf-8')
variable_name = locals()
for i in field_name:
variable_name[i] = args.get(i, 0)
user_id = request.COOKIES.get('user_id')
user_id = request.session.get(user_id)
variable_name['idmanager'] = user_id
del variable_name['idmanager__name']
if isinstance(variable_name['id_location__name'], int) and isinstance(variable_name['id_speaker__name'], int) and isinstance(variable_name['id_curricula__name'], int):
variable_name['id_location'] = variable_name['id_location__name']
variable_name['id_speaker'] = variable_name['id_speaker__name']
variable_name['id_curricula'] = variable_name['id_curricula__name']
else:
return HttpResponse(dumps(
{'error_code': 1, 'message': '请确保所填的id类数据是数字'}),
content_type=content_type_tmp,
charset='utf-8')
# 批量命名变量
try:
curricula_object = models.TCycurricula.objects.get(
id=variable_name.get('id_curricula'))
location_object = models.TCylocation.objects.get(
id=variable_name.get('id_location'))
speaker_object = models.TCyuser.objects.get(
id=variable_name.get('id_speaker'))
idmanager_object = models.TCyuser.objects.get(
id=variable_name.get('idmanager'))
ueses_tmp = models.TCyplan.objects.create(
id=variable_name.get('id'),
id_curricula=curricula_object,
id_location=location_object,
id_speaker=speaker_object,
timebegin=variable_name.get('timebegin'),
timeend=variable_name.get('timeend'),
attr=variable_name.get('attr'),
charge=variable_name.get('charge'),
pwaccess=variable_name.get('pwaccess'),
pwcontinuous=variable_name.get('pwcontinuous'),
pwdirection=variable_name.get('pwdirection'),
dooropen=variable_name.get('dooropen'),
timebegincheckbegin=variable_name.get('timebegincheckbegin'),
timebegincheckend=variable_name.get('timebegincheckend'),
timeendcheckbegin=variable_name.get('timeendcheckbegin'),
timeendcheckend=variable_name.get('timeendcheckend'),
rangeusers=variable_name.get('rangeusers'),
listdepts=variable_name.get('listdepts'),
rangeequs=variable_name.get('rangeequs'),
timeupdate=variable_name.get('timeupdate'),
listplaces=variable_name.get('listplaces'),
idmanager=idmanager_object,
mapuser2equ=variable_name.get('mapuser2equ'),
aboutspeaker=variable_name.get('aboutspeaker'),
rem=variable_name.get('rem'))
return HttpResponse(dumps({'error_code': 0, 'message': put_success}),
content_type=content_type_tmp,
charset='utf-8')
except Exception as error:
return HttpResponse(dumps(
{'error_code': 1, 'message': data_base_error_specific + str(error)}),
content_type=content_type_tmp,
charset='utf-8')
'''
list
list all information about Equipment
'''
CourseArrangement_patch_request_body = Schema(
title=' 修改课程安排表所需要的数据 ', # 标题
description=' 修改课程安排表 ', # 接口描述
type=TYPE_OBJECT, # 类型 "object" ,"string" ,"number" ,"integer" ,"boolean" ,"array" ,"file"
format=None, # 格式 date,date-time,password,binary,bytes,float,double,int32,int64,email,ipv4, ipv6, uri, uuid, slug, decimal
enum=None, # [列表]列举参数的请求值
pattern=None, # 当 format为 string是才填此项
# 当 type为object时,为dict对象 {'str1': Schema对象, 'str2': SchemaRef对象}
properties=data_schema,
required=['id'], # [必须的属性列表]
items=None, # 当type是array时,填此项
)
CourseArrangement_patch_responses_success = Response(
description='修改课程安排表成功的响应',
schema=responses_success,
examples={
'error_code': 0,
'message': patch_success
})
CourseArrangement_patch_responses_fail = Response(
description='修改课程安排表失败的响应',
schema=responses_fail,
examples={
'error_code': 1,
'message': patch_error
})
@swagger_auto_schema(request_body=CourseArrangement_patch_request_body,
manual_parameters=None,
operation_id=None,
operation_description='这个端口用于修改课程安排表的数据',
operation_summary=None,
security=None,
responses={
201: CourseArrangement_patch_responses_success,
400: CourseArrangement_patch_responses_fail
},
tags=None)
@get_request_args
@csrf_exempt
def patch(self, request, args, session):
is_login = request.COOKIES.get('is_login')
if not request.session.get(is_login, None):
return HttpResponse(dumps({'code': 0}), content_type=content_type_tmp, charset='utf-8')
id_equipment = args.get('id')
data_equipment_initial = list(
models.TCyplan.objects.filter(id=id_equipment).values(
'id',
'id_curricula',
'timebegin',
'timeend',
'id_location',
'id_speaker',
'attr',
'charge',
'pwaccess',
'pwcontinuous',
'pwdirection',
'dooropen',
'timebegincheckbegin',
'timebegincheckend',
'timeendcheckbegin',
'timeendcheckend',
'rangeusers',
'listdepts',
'rangeequs',
'timeupdate',
'listplaces',
'idmanager',
'mapuser2equ',
'aboutspeaker',
'rem'))
if data_equipment_initial == []:
return HttpResponse(dumps({'error_code': 1, 'message': id_error}),
content_type=content_type_tmp,
charset='utf-8')
data_equipment = data_equipment_initial[0]
field_name = [
'id', 'id_curricula__name', 'timebegin', 'timeend', 'id_location__name', 'id_speaker__name',
'attr', 'charge', 'pwaccess', 'pwcontinuous',
'pwdirection', 'dooropen', 'timebegincheckbegin',
'timebegincheckend', 'timeendcheckbegin', 'timeendcheckend',
'rangeusers', 'listdepts', 'rangeequs', 'timeupdate', 'listplaces',
'idmanager__name', 'mapuser2equ', 'aboutspeaker', 'rem'
]
args['id_curricula'] = args.get(
'id_curricula__name', data_equipment['id_curricula'])
args['id_location'] = args.get(
'id_location__name', data_equipment['id_location'])
args['id_speaker'] = args.get(
'id_speaker__name', data_equipment['id_speaker'])
args['idmanager'] = args.get(
'idmanager__name', data_equipment['idmanager'])
if isinstance(args['id_location__name'], int) and isinstance(args['id_speaker__name'], int) and isinstance(args['id_curricula__name'], int) and isinstance(args['idmanager__name'], int):
args['id_location'] = args['id_location__name']
args['id_speaker'] = args['id_speaker__name']
args['id_curricula'] = args['id_curricula__name']
args['idmanager'] = args['idmanager__name']
else:
return HttpResponse(dumps(
{'error_code': 1, 'message': '请确保所填的id类数据是数字'}),
content_type=content_type_tmp,
charset='utf-8')
variable_name = locals()
for i in field_name:
if args[i] == 0:
variable_name[i] = data_equipment[i]
else:
variable_name[i] = args.get(i, data_equipment[i])
user_id = request.COOKIES.get('user_id')
user_id = request.session.get(user_id)
variable_name['idmanager'] = user_id
try:
models.TCyplan.objects.filter(id=id_equipment).update(
id=variable_name.get('id'),
id_curricula=variable_name.get('id_curricula'),
id_location=variable_name.get('id_location'),
id_speaker=variable_name.get('id_speaker'),
timebegin=variable_name.get('timebegin'),
timeend=variable_name.get('timeend'),
attr=variable_name.get('attr'),
charge=variable_name.get('charge'),
pwaccess=variable_name.get('pwaccess'),
pwcontinuous=variable_name.get('pwcontinuous'),
pwdirection=variable_name.get('pwdirection'),
dooropen=variable_name.get('dooropen'),
timebegincheckbegin=variable_name.get('timebegincheckbegin'),
timebegincheckend=variable_name.get('timebegincheckend'),
timeendcheckbegin=variable_name.get('timeendcheckbegin'),
timeendcheckend=variable_name.get('timeendcheckend'),
rangeusers=variable_name.get('rangeusers'),
listdepts=variable_name.get('listdepts'),
rangeequs=variable_name.get('rangeequs'),
timeupdate=variable_name.get('timeupdate'),
listplaces=variable_name.get('listplaces'),
idmanager=variable_name.get('idmanager'),
mapuser2equ=variable_name.get('mapuser2equ'),
aboutspeaker=variable_name.get('aboutspeaker'),
rem=variable_name.get('rem'))
return HttpResponse(dumps({'message': '修改课程安排表成功'}), content_type=content_type_tmp, charset='utf-8')
except Exception as error:
return HttpResponse(dumps(
{'error_code': 1, 'message': data_base_error_specific + str(error)}),
content_type=content_type_tmp,
charset='utf-8')
APIView_delete_request_body = Schema(
title=' 删除数据库中的信息 ', # 标题
description='删除数据库中具体的id名称', # 接口描述
type=TYPE_OBJECT, # 类型 "object" ,"string" ,"number" ,"integer" ,"boolean" ,"array" ,"file"
format=None, # 格式 date,date-time,password,binary,bytes,float,double,int32,int64,email,ipv4, ipv6, uri, uuid, slug, decimal
enum=None, # [列表]列举参数的请求值
pattern=None, # 当 format为 string是才填此项
# 当 type为object时,为dict对象 {'str1': Schema对象, 'str2': SchemaRef对象}
properties=delete_schema,
required=['ids'], # [必须的属性列表]
items=None, # 当type是array时,填此项
)
APIView_delete_responses_success = Response(
description='APIView_delete_responses is success',
schema=responses_success,
examples={
'error_code': 0,
'message': '删除成功'
}
)
APIView_delete_responses_fail = Response(
description='APIView_delete_responses is failure',
schema=responses_fail,
examples={
'error_code': 1,
'message': '删除失败,请输入正确的id'
}
)
@ swagger_auto_schema(
request_body=APIView_delete_request_body,
manual_parameters=None,
operation_id=None,
operation_description='api是用来删除数据库中的给定字段',
operation_summary=None,
security=None,
responses={
204: APIView_delete_request_body,
500: APIView_delete_request_body
},
tags=None)
@ get_request_args
def delete(self, request, args, session):
is_login = request.COOKIES.get('is_login')
if not request.session.get(is_login, None):
return HttpResponse(dumps({'code': 0}), content_type=content_type_tmp, charset='utf-8')
variable_name = locals()
delete_data = args.get('ids')
numbers_id = len(delete_data)
for i in range(numbers_id):
variable_name['id_'+str(i)] = delete_data[i].get('data_id')
try:
for i in range(numbers_id):
models.TCyplan.objects.filter(
id=variable_name.get('id_'+str(i), 'id_1')).delete()
return HttpResponse(dumps({'error_code': 0, 'message': '数据删除成功'}), content_type=content_type_tmp, charset='utf-8')
except Exception as error:
return HttpResponse(dumps({'error_code': 1, 'message': data_base_error_specific + str(error)}), content_type=content_type_tmp, charset='utf-8')
| 38.594059 | 455 | 0.536942 |
6def8fbc025a4ae631780ed754a16d15160b7b0b | 6,514 | py | Python | knx_stack/client/knxnet_ip_discovery.py | majamassarini/knx-stack | 11a9baac6b7600649b5fbca43c93b200b23676b4 | [
"MIT"
] | 2 | 2021-07-28T07:42:28.000Z | 2022-01-25T18:56:05.000Z | knx_stack/client/knxnet_ip_discovery.py | majamassarini/knx-stack | 11a9baac6b7600649b5fbca43c93b200b23676b4 | [
"MIT"
] | 6 | 2021-07-25T21:36:01.000Z | 2022-02-20T21:11:31.000Z | knx_stack/client/knxnet_ip_discovery.py | majamassarini/knx-stack | 11a9baac6b7600649b5fbca43c93b200b23676b4 | [
"MIT"
] | null | null | null | import struct
import socket
import asyncio
import logging
import knx_stack
class Request(asyncio.DatagramProtocol):
def __init__(self, local_addr: str, local_port: int):
"""
A KNXnet IP Discovery request service
:param local_addr: discovery request instance host ip address
:param local_port: discovery request instance binding port
Example::
async def send_discovery_request(local_addr: str, local_port: int):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('', knx_stack.knxnet_ip.DISCOVERY_MULTICAST_PORT))
group = socket.inet_aton(knx_stack.knxnet_ip.DISCOVERY_MULTICAST_ADDR)
mreq = struct.pack('!4sL', group, socket.INADDR_ANY)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
sock.setblocking(False)
transport, protocol = await loop.create_datagram_endpoint(
lambda: Request(local_addr, local_port), sock=sock,
)
return transport, protocol
"""
self._loop = asyncio.get_event_loop()
self._transport = None
self._local_addr = local_addr
self._local_port = local_port
self._state = knx_stack.knxnet_ip.State(knx_stack.Medium.knxnet_ip, None, None)
self.logger = logging.getLogger(__name__)
def connection_made(self, transport):
self._transport = transport
self.logger.info("Connection made: {}".format(str(self._transport)))
msg = knx_stack.encode_msg(
self._state,
knx_stack.knxnet_ip.core.search.req.Msg(
addr=self._local_addr, port=self._local_port
),
)
self.logger.info("encode: {}".format(msg))
self._transport.sendto(
bytearray.fromhex(str(msg)),
(
knx_stack.knxnet_ip.DISCOVERY_MULTICAST_ADDR,
knx_stack.knxnet_ip.DISCOVERY_MULTICAST_PORT,
),
)
def connection_lost(self, exc):
self.logger.error("Connection lost: {}".format(str(exc)))
self._transport = None
def error_received(self, exc):
self.logger.error("Error received: {}".format(str(exc)))
def datagram_received(self, data, addr):
self.logger.info("read data: {}".format(data.hex()))
self.logger.info("read from: {}".format(str(addr)))
class Listen(asyncio.DatagramProtocol):
"""
A KNXnet IP Discovery listener service
:param local_addr: discovery listener instance host ip address
:param local_port: discovery listener instance binding port
Example::
async def listen_discovery_responses(local_addr: str, local_port: int):
transport, protocol = await loop.create_datagram_endpoint(
lambda: Listen(), local_addr=(local_addr, local_port),
)
return transport, protocol
if __name__ == '__main__':
import sys
root = logging.getLogger()
root.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
root.addHandler(handler)
loop = asyncio.get_event_loop()
transport1, _ = loop.run_until_complete(loop.create_task(listen_discovery_responses('172.31.10.111', 5544)))
transport2, _ = loop.run_until_complete(loop.create_task(send_discovery_request('172.31.10.111', 5544)))
try:
loop.run_forever()
except KeyboardInterrupt:
pass
print("Closing transport...")
transport1.close()
transport2.close()
loop.close()
"""
def __init__(self):
self._transport = None
self._state = knx_stack.knxnet_ip.State(knx_stack.Medium.knxnet_ip, None, None)
self.logger = logging.getLogger(__name__)
def connection_made(self, transport):
self._transport = transport
self.logger.info("Connection made: {}".format(str(self._transport)))
def connection_lost(self, exc):
self.logger.error("Connection lost: {}".format(str(exc)))
self._transport = None
def error_received(self, exc):
self.logger.error("Error received: {}".format(str(exc)))
def datagram_received(self, data, addr):
self.logger.info("read {}".format(str(data.hex())))
self.logger.info("read {}".format(str(addr)))
search_response = knx_stack.decode_msg(
self._state, knx_stack.knxnet_ip.Msg.make_from_str(data.hex())
)
self.logger.info("read decoded: {}".format(str(search_response)))
async def send_discovery_request(local_addr: str, local_port: int):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("", knx_stack.knxnet_ip.DISCOVERY_MULTICAST_PORT))
group = socket.inet_aton(knx_stack.knxnet_ip.DISCOVERY_MULTICAST_ADDR)
mreq = struct.pack("!4sL", group, socket.INADDR_ANY)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
sock.setblocking(False)
transport, protocol = await loop.create_datagram_endpoint(
lambda: Request(local_addr, local_port),
sock=sock,
)
return transport, protocol
async def listen_discovery_responses(local_addr: str, local_port: int):
transport, protocol = await loop.create_datagram_endpoint(
lambda: Listen(),
local_addr=(local_addr, local_port),
)
return transport, protocol
if __name__ == "__main__":
import sys
root = logging.getLogger()
root.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
root.addHandler(handler)
loop = asyncio.get_event_loop()
if len(sys.argv):
transport1, _ = loop.run_until_complete(
loop.create_task(listen_discovery_responses(sys.argv[0], 5544))
)
transport2, _ = loop.run_until_complete(
loop.create_task(send_discovery_request(sys.argv[0], 5544))
)
try:
loop.run_forever()
except KeyboardInterrupt:
pass
print("Closing transport...")
transport1.close()
transport2.close()
loop.close()
| 34.648936 | 120 | 0.642462 |
6defac8f1015dd7e947197dcda96dec8473101d6 | 199 | py | Python | autodisc/representations/static/pytorchnnrepresentation/models/__init__.py | flowersteam/holmes | e38fb8417ec56cfde8142eddd0f751e319e35d8c | [
"MIT"
] | 6 | 2020-12-19T00:16:16.000Z | 2022-01-28T14:59:21.000Z | autodisc/representations/static/pytorchnnrepresentation/models/__init__.py | Evolutionary-Intelligence/holmes | e38fb8417ec56cfde8142eddd0f751e319e35d8c | [
"MIT"
] | null | null | null | autodisc/representations/static/pytorchnnrepresentation/models/__init__.py | Evolutionary-Intelligence/holmes | e38fb8417ec56cfde8142eddd0f751e319e35d8c | [
"MIT"
] | 1 | 2021-05-24T14:58:26.000Z | 2021-05-24T14:58:26.000Z | from autodisc.representations.static.pytorchnnrepresentation.models.encoders import EncoderBurgess
from autodisc.representations.static.pytorchnnrepresentation.models.decoders import DecoderBurgess
| 49.75 | 98 | 0.904523 |
6defdfc013df6a621f25fd5ffba934ad58dd3acd | 3,312 | py | Python | lights.py | team-7108/computer-vision-tutorials | cfb7e455b5d8bba8779c440907344d9763573f57 | [
"MIT"
] | 3 | 2018-09-12T02:56:46.000Z | 2020-11-13T13:48:44.000Z | lights.py | team-7108/computer-vision-tutorials | cfb7e455b5d8bba8779c440907344d9763573f57 | [
"MIT"
] | null | null | null | lights.py | team-7108/computer-vision-tutorials | cfb7e455b5d8bba8779c440907344d9763573f57 | [
"MIT"
] | 1 | 2020-11-13T13:48:45.000Z | 2020-11-13T13:48:45.000Z | # Import OpenCV module
import cv2
# Import numpy for array operations
import numpy as np
image = cv2.imread('images/five_cubes.jpeg')
# Show the image
cv2.imshow('Image',image)
# Resize the image if it is too big, also helps to speed up the processing
image = cv2.resize(image, (600, 600))
cv2.imshow('Resized Image',image)
# Equalizing histograms, we try to reduce the effect of light here
image = cv2.cvtColor(image,cv2.COLOR_BGR2YUV)
channel = cv2.split(image)
cv2.equalizeHist(channel[0], channel[0])
cv2.merge(channel,image)
image = cv2.cvtColor(image,cv2.COLOR_YUV2BGR)
cv2.imshow('Normalized Image',image)
# This is a dummy function needed for creating trackbars
def nothing(x):
pass
# Create a window named 'Colorbars'
cv2.namedWindow('Colorbars')
# Assign strings for ease of coding
bh='Blue High'
bl='Blue Low'
gh='Green High'
gl='Green Low'
rh='Red High'
rl='Red Low'
wnd = 'Colorbars'
# Begin Creating trackbars for each BGR value
cv2.createTrackbar(bl, wnd, 0, 255, nothing)
cv2.createTrackbar(bh, wnd, 149, 255, nothing)
cv2.createTrackbar(gl, wnd, 156, 255, nothing)
cv2.createTrackbar(gh, wnd, 255, 255, nothing)
cv2.createTrackbar(rl, wnd, 199, 255, nothing)
cv2.createTrackbar(rh, wnd, 255, 255, nothing)
while True:
mergedImage = np.zeros((600,150,3), np.uint8)
# Split image into four pieces and merge again
for i in range(0,4):
resizedImage = image[0:600, i*150:(i+1)*150]
cv2.imshow("cropped", resizedImage)
bLow = cv2.getTrackbarPos(bl, wnd)
bHigh = cv2.getTrackbarPos(bh, wnd)
gLow = cv2.getTrackbarPos(gl, wnd)
gHigh = cv2.getTrackbarPos(gh, wnd)
rLow = cv2.getTrackbarPos(rl, wnd)
rHigh = cv2.getTrackbarPos(rh, wnd)
rgbLow=np.array([bLow,gLow,rLow])
rgbHigh=np.array([bHigh,gHigh,rHigh])
maskedImage = cv2.inRange(resizedImage, rgbLow, rgbHigh)
cv2.imshow('Masked Image', maskedImage)
kernel = np.ones((15,15),np.uint8)
# the first morphological transformation is called opening, it will sweep out extra lone pixels around the image
openedImage = cv2.morphologyEx(maskedImage, cv2.MORPH_OPEN, kernel)
cv2.imshow("Open Image", openedImage)
outImage = resizedImage.copy()
try:
contourImage, contours, hierarchy = cv2.findContours(openedImage.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]
print(cnt) # contours are the points on the outline of the image
# bounding rectangle is the minimum rectangle that includes all the contours
# this bounding rectangle is perpendicular to image
x,y,w,h = cv2.boundingRect(cnt)
# We mark that bounding rectangle with green
cv2.rectangle(outImage,(x,y),(x+w,y+h),(255,0,0),4)
except:
pass
cv2.imshow("Bboxed",outImage)
mergedImage = np.concatenate((mergedImage,outImage), axis=1)
mergedImage = mergedImage[0:600, 150:750]
cv2.imshow("Merged",mergedImage)
keyPressed = cv2.waitKey(1) # Look for keys to be pressed
if keyPressed == 27: # if the key is ESC, check the ASCII table, 27 = ESC
break # Exit the loop
cv2.destroyAllWindows() # Destroy the windows and close the program
| 35.234043 | 128 | 0.679348 |
6df0403cfe638d0fa7c9fc0942bb17cdd38113df | 569 | py | Python | exastics/publish_github_api_releases.py | exastro-suite/exastics | de6193159943319333abc2688f543e7424810823 | [
"Apache-2.0"
] | null | null | null | exastics/publish_github_api_releases.py | exastro-suite/exastics | de6193159943319333abc2688f543e7424810823 | [
"Apache-2.0"
] | 1 | 2020-10-25T08:30:59.000Z | 2020-10-25T08:30:59.000Z | exastics/publish_github_api_releases.py | exastro-suite/exastics | de6193159943319333abc2688f543e7424810823 | [
"Apache-2.0"
] | 8 | 2020-10-09T13:11:08.000Z | 2021-11-04T06:26:27.000Z | import exastics.collect
import pathlib
import sys
import urllib.parse
if __name__ == '__main__':
github_account = sys.argv[1]
github_repository = sys.argv[2]
url_parts = (
'https',
'api.github.com',
urllib.parse.quote(f'/repos/{github_account}/{github_repository}/releases'),
'',
'',
''
)
headers = {
'Accept': 'application/vnd.github.v3+json'
}
output_dir = pathlib.PurePath(github_repository, 'github-releases')
exastics.collect.publish_api(url_parts, headers, output_dir)
| 21.074074 | 84 | 0.630931 |
6df0ee5285eb665d18e287fcf75e62d896c148dd | 1,471 | py | Python | cohesity_management_sdk/models/rpo_schedule.py | sachinthakare-cohesity/management-sdk-python | c95f67b7d387d5bab8392be43190e598280ae7b5 | [
"MIT"
] | null | null | null | cohesity_management_sdk/models/rpo_schedule.py | sachinthakare-cohesity/management-sdk-python | c95f67b7d387d5bab8392be43190e598280ae7b5 | [
"MIT"
] | null | null | null | cohesity_management_sdk/models/rpo_schedule.py | sachinthakare-cohesity/management-sdk-python | c95f67b7d387d5bab8392be43190e598280ae7b5 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
class RPOSchedule(object):
"""Implementation of the 'RPO Schedule.' model.
Specifies an RPO Schedule.
Attributes:
rpo_inteval_minutes (long|int): If this field is set, then at any
point, a recovery point should be available not older than the
given interval minutes.
"""
# Create a mapping from Model property names to API property names
_names = {
"rpo_inteval_minutes":'rpoIntevalMinutes'
}
def __init__(self,
rpo_inteval_minutes=None):
"""Constructor for the RPOSchedule class"""
# Initialize members of the class
self.rpo_inteval_minutes = rpo_inteval_minutes
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
rpo_inteval_minutes = dictionary.get('rpoIntevalMinutes')
# Return an object of this model
return cls(rpo_inteval_minutes)
| 26.745455 | 81 | 0.633583 |
6df1040ee952e6ce1e567165568234bfbe1f725c | 5,834 | py | Python | Gh compilation files/text.py | ibois-epfl/Manis-timber-plate-joinery-solver | fecdb1dfe23348de261f034f85baf24ac396e8cc | [
"MIT"
] | 3 | 2021-10-19T11:55:59.000Z | 2022-02-04T15:29:04.000Z | Gh compilation files/text.py | ibois-epfl/Manis-timber-plate-joinery-solver | fecdb1dfe23348de261f034f85baf24ac396e8cc | [
"MIT"
] | null | null | null | Gh compilation files/text.py | ibois-epfl/Manis-timber-plate-joinery-solver | fecdb1dfe23348de261f034f85baf24ac396e8cc | [
"MIT"
] | null | null | null | """Export a text file."""
from ghpythonlib.componentbase import dotnetcompiledcomponent as component
import Grasshopper, GhPython
import System
import os
import datetime
__author__ = "Nicolas Rogeau"
__laboratory__ = "IBOIS, Laboratory for Timber Construction"
__university__ = "EPFL, Ecole Polytechnique Federale de Lausanne"
__funding__ = "NCCR Digital Fabrication, ETH Zurich"
__version__ = "2021.09"
class MyComponent(component):
def __new__(cls):
instance = Grasshopper.Kernel.GH_Component.__new__(cls,
"Export Text File", "TextOut", """Export a text file.""", "Manis", "Utility")
return instance
def get_ComponentGuid(self):
return System.Guid("02ba4a11-7b1c-48b3-8376-55637e7a1ed2")
def SetUpParam(self, p, name, nickname, description):
p.Name = name
p.NickName = nickname
p.Description = description
p.Optional = True
def RegisterInputParams(self, pManager):
p = Grasshopper.Kernel.Parameters.Param_Boolean()
self.SetUpParam(p, "run", "run", "Export file if True.")
p.Access = Grasshopper.Kernel.GH_ParamAccess.item
self.Params.Input.Add(p)
p = Grasshopper.Kernel.Parameters.Param_String()
self.SetUpParam(p, "text", "text", "Text to export.")
p.Access = Grasshopper.Kernel.GH_ParamAccess.list
self.Params.Input.Add(p)
p = Grasshopper.Kernel.Parameters.Param_String()
self.SetUpParam(p, "folder", "folder", "Folder path.")
p.Access = Grasshopper.Kernel.GH_ParamAccess.item
self.Params.Input.Add(p)
p = Grasshopper.Kernel.Parameters.Param_String()
self.SetUpParam(p, "name", "name", "File name.")
p.Access = Grasshopper.Kernel.GH_ParamAccess.item
self.Params.Input.Add(p)
p = Grasshopper.Kernel.Parameters.Param_String()
self.SetUpParam(p, "extension", "extension", "(Optional) Custom file extension.")
p.Access = Grasshopper.Kernel.GH_ParamAccess.item
self.Params.Input.Add(p)
p = Grasshopper.Kernel.Parameters.Param_Boolean()
self.SetUpParam(p, "date", "date", "(Optional) Add the date of today to the file name.")
p.Access = Grasshopper.Kernel.GH_ParamAccess.item
self.Params.Input.Add(p)
p = Grasshopper.Kernel.Parameters.Param_Boolean()
self.SetUpParam(p, "x", "incremental", "(Optional) Check for existing file with the same name and increment if necessary.")
p.Access = Grasshopper.Kernel.GH_ParamAccess.item
self.Params.Input.Add(p)
def RegisterOutputParams(self, pManager):
pass
def SolveInstance(self, DA):
p0 = self.marshal.GetInput(DA, 0)
p1 = self.marshal.GetInput(DA, 1)
p2 = self.marshal.GetInput(DA, 2)
p3 = self.marshal.GetInput(DA, 3)
p4 = self.marshal.GetInput(DA, 4)
p5 = self.marshal.GetInput(DA, 5)
p6 = self.marshal.GetInput(DA, 6)
result = self.RunScript(p0, p1, p2, p3, p4, p5, p6)
def get_Internal_Icon_24x24(self):
o = "iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAJOgAACToAYJjBRwAAACKSURBVEhL7c3RCoQwDETR/v9Pq7dOSoygFDrggweGrhM2aT+3Ta8NB6xH4oDtyAZeZbl+APxWbvJwOlnqLzReg33KUAcj0We5rwmp61Sf6jeie5pV9Mr7Acz2YHbk/UB0T7OKXrn+Od4w+w06pVO9BvuUIZfTyVK/jFZ7lsO6HNblsC6HdfkXtLYDh4phuyx2L58AAAAASUVORK5CYII="
return System.Drawing.Bitmap(System.IO.MemoryStream(System.Convert.FromBase64String(o)))
def RunScript(self, run, text, folder, name, extension, date, incremental):
inc = incremental
ext = extension
if run is True:
# gh doc path
ghP = self.LocalScope.ghdoc.Path
# folder and file name
if name == None: name = 'this_script_has_no_name'
if folder == None: folder = os.path.dirname(os.path.realpath(ghP))
outputName = folder + '\\' + str(name)
# date
if date is True:
date = datetime.datetime.today()
outputName += '_' + str(date.year) + '_' + str(date.month) + '_' + str(date.day)
# extension
if ext == None: ext = '.txt'
# avoid overwrite
if inc is True:
i = 0
iter = outputName + '_' + str(i)
while os.path.exists(iter + str(ext)) and i<100: #safety
i += 1
iter = outputName + '_' + str(i)
outputName = iter
outputName += str(ext)
# create file
myFile = open(outputName,'w')
# pass values to file
if text != None:
for i in range(len(text)):
myFile.write(str(text[i]))
if i != len(text)-1:
myFile.write('\n')
# close file
myFile.close()
# confirm file write
if os.stat(outputName).st_size > 0:
print('File successfully written as ' + outputName)
else:
print('output file is empty - check your values')
return
class AssemblyInfo(GhPython.Assemblies.PythonAssemblyInfo):
def get_AssemblyName(self):
return "Text File Output"
def get_AssemblyDescription(self):
return """"""
def get_AssemblyVersion(self):
return "0.1"
def get_AuthorName(self):
return "Nicolas Rogeau"
def get_Id(self):
return System.Guid("bc9186be-9321-4eb3-ba5e-58a615f66a50") | 38.130719 | 343 | 0.594961 |
6df14879b950933abacc38dea90c26ad6c6515c2 | 97 | py | Python | component_tests/tests/features/steps/__init__.py | Cobalt0s/sommelier | d64943a5d7be4ecdf08aa18e9f184b757e408425 | [
"MIT"
] | null | null | null | component_tests/tests/features/steps/__init__.py | Cobalt0s/sommelier | d64943a5d7be4ecdf08aa18e9f184b757e408425 | [
"MIT"
] | null | null | null | component_tests/tests/features/steps/__init__.py | Cobalt0s/sommelier | d64943a5d7be4ecdf08aa18e9f184b757e408425 | [
"MIT"
] | null | null | null | from sommelier.steps.response_processing import *
from sommelier.steps.event_processing import *
| 32.333333 | 49 | 0.85567 |
6df14ec0665b31a613e368f74d43196adfd0df56 | 877 | py | Python | setup.py | anthonytw/dutyroll | 489dd452ba614a2214756eba0831b33111187225 | [
"MIT"
] | 2 | 2019-01-22T20:44:03.000Z | 2019-11-30T07:59:32.000Z | setup.py | anthonytw/dutyroll | 489dd452ba614a2214756eba0831b33111187225 | [
"MIT"
] | null | null | null | setup.py | anthonytw/dutyroll | 489dd452ba614a2214756eba0831b33111187225 | [
"MIT"
] | null | null | null | import sys
from packaging.version import LegacyVersion
from skbuild.exceptions import SKBuildError
from skbuild.cmaker import get_cmake_version
from skbuild import setup
setup_requires = []
# Require pytest-runner only when running tests.
if any(arg in sys.argv for arg in ('pytest', 'test')):
setup_requires.append('pytest-runner>=2.0')
# Add CMake as a build requirement if cmake is not installed or is too low a version.
try:
if LegacyVersion(get_cmake_version()) < LegacyVersion('3.10'):
setup_requires.append('cmake')
except SKBuildError:
setup_requires.append('cmake')
setup(
name='dutyroll',
version='1.0.1',
description='Parallel implementation of rolling window duty cycle.',
author='"Anthony Wertz"<awertz@cmu.edu>',
license='MIT',
packages=['dutyroll'],
tests_require=['pytest'],
setup_requires=setup_requires
)
| 28.290323 | 85 | 0.733181 |
6df1e73647be403745ebe4c69e672889f9a73f91 | 162 | py | Python | obdlive/obd/urls.py | hoke-t/OBDLive | 524fb53fad5924b8371d2fce8d7a482bd8112362 | [
"MIT"
] | 8 | 2018-12-15T16:41:21.000Z | 2021-10-03T21:19:11.000Z | obdlive/obd/urls.py | hoke-t/OBDLive | 524fb53fad5924b8371d2fce8d7a482bd8112362 | [
"MIT"
] | null | null | null | obdlive/obd/urls.py | hoke-t/OBDLive | 524fb53fad5924b8371d2fce8d7a482bd8112362 | [
"MIT"
] | 1 | 2020-07-27T18:15:58.000Z | 2020-07-27T18:15:58.000Z | from django.urls import path
from . import views
urlpatterns = [
path('', views.dashboard, name='dashboard'),
path('dtcs/', views.dtcs, name='dtcs'),
]
| 18 | 48 | 0.654321 |
6df2b3c71a785d6478f03f2023bb542307a17b8f | 1,195 | py | Python | crits/locations/forms.py | dutrow/crits | 6b357daa5c3060cf622d3a3b0c7b41a9ca69c049 | [
"MIT"
] | 738 | 2015-01-02T12:39:55.000Z | 2022-03-23T11:05:51.000Z | crits/locations/forms.py | deadbits/crits | 154097a1892e9d3960d6faaed4bd2e912a196a47 | [
"MIT"
] | 605 | 2015-01-01T01:03:39.000Z | 2021-11-17T18:51:07.000Z | crits/locations/forms.py | deadbits/crits | 154097a1892e9d3960d6faaed4bd2e912a196a47 | [
"MIT"
] | 316 | 2015-01-07T12:35:01.000Z | 2022-03-30T04:44:30.000Z | from django import forms
from crits.locations.location import Location
from crits.core.handlers import get_item_names
class AddLocationForm(forms.Form):
"""
Django form for adding a location to a TLO.
The list of names comes from :func:`get_item_names`.
"""
error_css_class = 'error'
required_css_class = 'required'
location_type = forms.ChoiceField(widget=forms.Select, required=True)
country = forms.ChoiceField(widget=forms.Select, required=True)
description = forms.CharField(
widget=forms.TextInput(attrs={'size': '50'}),
required=False)
latitude = forms.CharField(
widget=forms.TextInput(attrs={'size': '50'}),
required=False)
longitude = forms.CharField(
widget=forms.TextInput(attrs={'size': '50'}),
required=False)
def __init__(self, *args, **kwargs):
super(AddLocationForm, self).__init__(*args, **kwargs)
self.fields['location_type'].choices = [
('Originated From', 'Originated From'),
('Destined For', 'Destined For'),
]
self.fields['country'].choices = [
(c.name, c.name) for c in get_item_names(Location, True)]
| 34.142857 | 73 | 0.650209 |
6df4ba8add8eb7e8c911008f72f03e4dab32f5ab | 3,641 | py | Python | utils/utils_preprocess_v3.py | microsoft/normalized_trend_filtering | eb73f124243dfc3dc610abba35a3ad1a6303a227 | [
"MIT"
] | 2 | 2021-09-06T14:04:17.000Z | 2021-11-09T11:55:10.000Z | utils/utils_preprocess_v3.py | microsoft/normalized_trend_filtering | eb73f124243dfc3dc610abba35a3ad1a6303a227 | [
"MIT"
] | null | null | null | utils/utils_preprocess_v3.py | microsoft/normalized_trend_filtering | eb73f124243dfc3dc610abba35a3ad1a6303a227 | [
"MIT"
] | 1 | 2021-11-10T11:44:36.000Z | 2021-11-10T11:44:36.000Z | import pandas as pd
import numpy as np
import sys
import os
import itertools
import pandas as pd
import os
from tqdm import tqdm_notebook, tnrange
import numpy as np
import networkx as nx
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.optimize import minimize
import scipy
from sklearn import linear_model
from sklearn.preprocessing import StandardScaler
import cvxpy as cp
from scipy.sparse import csr_matrix, vstack, hstack
from copy import deepcopy
module_path = os.path.abspath(os.path.join('..'))
def getReducedGraph(sample_nodes, graph_nodes,
interactome):
'''
Reduce graph with only intersection nodes from sample and
interactome.
'''
#find intersection between sample nodes and graph nodes
sample_nodes = set(sample_nodes)
graph_nodes = set(graph_nodes)
intersection_nodes = sample_nodes.intersection(graph_nodes)
print('Number of Intersection Nodes : ', len(intersection_nodes))
g = []
for line in tqdm_notebook(range(len(interactome))):
if (interactome.iloc[line]['node1'] in intersection_nodes
and interactome.iloc[line]['node2'] in intersection_nodes):
g.append(interactome.iloc[line])
return pd.DataFrame(g)
def getNodeCharacterization(g, sample_nodes):
'''
Characterizes nodes based on if node is connected or orphan
'''
connected_nodes = set(g.nodes())
orphan_nodes = set(sample_nodes) - connected_nodes
return connected_nodes, orphan_nodes
def getDataSorting(connected_nodes, sample_df):
'''
Sorts covariant matrix such that connected nodes are first
followed by orphan nodes and nodes not in interactome
'''
sample_df_sorted = deepcopy(sample_df)
sample_df_sorted['IN_INTERACTOME'] = sample_df["node"].isin(list(connected_nodes)).tolist()
sample_df_sorted = sample_df_sorted.sort_values(by="IN_INTERACTOME", ascending=False).reset_index(drop=True)
#get dictionary to map node to number
num_to_node = {}
for i,nod in enumerate(sample_df_sorted['node'].tolist()):
num_to_node[i] = nod
#get ordered list of nodes in interactome
ordered_nodelist = sample_df_sorted.loc[sample_df_sorted['IN_INTERACTOME'] == True]['node'].tolist()
#delete 'IN_INTERACTOME' column
sample_df_sorted = sample_df_sorted.drop(columns = ['IN_INTERACTOME', 'node'])
return sample_df_sorted, ordered_nodelist, num_to_node
def getLaplacian(g, ordered_nodelist, orphan_nodes):
'''
Calculates laplacian matrix with respect to ordering of
covariant matrix
'''
L_norm = nx.normalized_laplacian_matrix(g, nodelist = ordered_nodelist, weight = 'confidence')
L = nx.laplacian_matrix(g, nodelist = ordered_nodelist, weight = 'confidence')
return csr_matrix(scipy.linalg.block_diag(L.todense(),np.eye(len(orphan_nodes)))), \
csr_matrix(scipy.linalg.block_diag(L_norm.todense(),np.eye(len(orphan_nodes))))
class Preprocessing():
def __init__(self):
self.g = None
self.connected_nodes = None
self.orphan_nodes = None
self.sorted_X = None
self.ordered_nodelist = None
self.num_to_node = None
self.L = None
self.L_norm = None
def transform(self,X_nodes, graph_nodes, graph, X, save_location, load_graph = False):
if load_graph == False:
self.g = getReducedGraph(X_nodes, graph_nodes, graph)
self.g.to_csv(save_location, header=None, index=None, sep='\t')
self.g = nx.read_edgelist(save_location,
data=(('confidence',float),))
self.connected_nodes, self.orphan_nodes = \
getNodeCharacterization(self.g, X_nodes)
self.sorted_X, self.ordered_nodelist, self.num_to_node = \
getDataSorting(self.connected_nodes,X)
self.L, self.L_norm = getLaplacian(self.g, self.ordered_nodelist, self.orphan_nodes, )
| 31.119658 | 109 | 0.762703 |
6df5916ec657908f3c7be4eae54758a97075100c | 791 | py | Python | server.py | marwano/remoterobot | 80409bde8e20de2b9fe97a8f214295aa5290decd | [
"BSD-3-Clause"
] | 1 | 2019-05-26T10:41:07.000Z | 2019-05-26T10:41:07.000Z | server.py | marwano/remoterobot | 80409bde8e20de2b9fe97a8f214295aa5290decd | [
"BSD-3-Clause"
] | 1 | 2018-02-28T23:47:23.000Z | 2018-02-28T23:47:23.000Z | server.py | marwano/remoterobot | 80409bde8e20de2b9fe97a8f214295aa5290decd | [
"BSD-3-Clause"
] | null | null | null | #!/usr/bin/env python3
import tornado.ioloop
import tornado.web
import json
import logging
from uf.wrapper.swift_api import SwiftAPI
class MainHandler(tornado.web.RequestHandler):
def initialize(self, swift):
self.swift = swift
def post(self):
data = json.loads(self.request.body.decode())
logging.info(repr(data))
func = getattr(self.swift, data['action'])
results = func(**data['kwargs'])
self.write(json.dumps(dict(results=results)))
def main():
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)
swift = SwiftAPI()
app = tornado.web.Application([('/', MainHandler, dict(swift=swift))])
app.listen(8000)
tornado.ioloop.IOLoop.current().start()
if __name__ == '__main__':
main()
| 25.516129 | 77 | 0.667509 |
6df62870aa4daf08157f0c702682542e2f8979fe | 2,765 | py | Python | open/core/betterself/serializers/daily_productivity_log_serializers.py | lawrendran/open | d136f694bafab647722c78be6f39ec79d589f774 | [
"MIT"
] | 105 | 2019-06-01T08:34:47.000Z | 2022-03-15T11:48:36.000Z | open/core/betterself/serializers/daily_productivity_log_serializers.py | lawrendran/open | d136f694bafab647722c78be6f39ec79d589f774 | [
"MIT"
] | 111 | 2019-06-04T15:34:14.000Z | 2022-03-12T21:03:20.000Z | open/core/betterself/serializers/daily_productivity_log_serializers.py | lawrendran/open | d136f694bafab647722c78be6f39ec79d589f774 | [
"MIT"
] | 26 | 2019-09-04T06:06:12.000Z | 2022-01-03T03:40:11.000Z | from rest_framework.exceptions import ValidationError
from rest_framework.fields import DateField, ChoiceField, CharField
from open.core.betterself.constants import (
BETTERSELF_LOG_INPUT_SOURCES,
WEB_INPUT_SOURCE,
)
from open.core.betterself.models.daily_productivity_log import DailyProductivityLog
from open.core.betterself.serializers.mixins import (
BaseCreateUpdateSerializer,
BaseModelReadSerializer,
)
from open.core.betterself.serializers.validators import ModelValidatorsMixin
from open.utilities.date_and_time import (
format_datetime_to_human_readable,
yyyy_mm_dd_format_1,
)
class DailyProductivityLogReadSerializer(BaseModelReadSerializer):
class Meta:
model = DailyProductivityLog
fields = (
"uuid",
"source",
"date",
"very_productive_time_minutes",
"productive_time_minutes",
"neutral_time_minutes",
"distracting_time_minutes",
"very_distracting_time_minutes",
"notes",
"mistakes",
"created",
"modified",
"display_name",
"pomodoro_count",
)
def get_display_name(self, instance):
model = self.Meta.model
model_name = model._meta.verbose_name
time_label = instance.date
serialized_time = format_datetime_to_human_readable(
time_label, yyyy_mm_dd_format_1
)
display_name = f"{model_name} | Date: {serialized_time}"
return display_name
class DailyProductivityLogCreateUpdateSerializer(
BaseCreateUpdateSerializer, ModelValidatorsMixin
):
# allow an regular isoformat of milliseconds also be passed
date = DateField(input_formats=["iso-8601"])
source = ChoiceField(choices=BETTERSELF_LOG_INPUT_SOURCES, default=WEB_INPUT_SOURCE)
mistakes = CharField(trim_whitespace=True, default="", allow_blank=True)
class Meta:
model = DailyProductivityLog
fields = (
"source",
"date",
"very_productive_time_minutes",
"productive_time_minutes",
"neutral_time_minutes",
"distracting_time_minutes",
"very_distracting_time_minutes",
"pomodoro_count",
"notes",
"mistakes",
"user",
)
def validate(self, validated_data):
user = self.context["request"].user
is_creating_instance = not self.instance
if is_creating_instance:
if self.Meta.model.objects.filter(
user=user, date=validated_data["date"],
).exists():
raise ValidationError(f"Fields user and date need to be unique!")
return validated_data
| 31.420455 | 88 | 0.654973 |
6df6536077ead8b5315b04728d254740d08d1ea8 | 5,423 | py | Python | twitch_bot.py | VDK45/Arkanoid_audio_command_for_twitch | 178a30fe85d3db5b4da127ee3de0c60dc8b0873d | [
"MIT"
] | null | null | null | twitch_bot.py | VDK45/Arkanoid_audio_command_for_twitch | 178a30fe85d3db5b4da127ee3de0c60dc8b0873d | [
"MIT"
] | null | null | null | twitch_bot.py | VDK45/Arkanoid_audio_command_for_twitch | 178a30fe85d3db5b4da127ee3de0c60dc8b0873d | [
"MIT"
] | null | null | null | import random
import cfg
import utils
import socket
import re
import time
from time import sleep
import sys
try:
file_c = open('chanel.txt', 'r', encoding='utf-8')
CHANEL = file_c.read()
print(f'chanel = {CHANEL}')
file_c.close()
except IOError as err:
print('Please enter your CHANEL!')
print(err)
try:
file_P = open('password.txt', 'r', encoding='utf-8')
PASSWORD = file_P.read()
print(f'password = {PASSWORD}')
file_P.close()
except IOError as err:
print('Please enter your PASSWORD!')
print(err)
command = ''
message = 'Hello world!'
chater = 'VDK_45'
loop_true = True
lst_chat = ['VDK45', 'Hello world!', 'VDK45', 'ARKANOID', 'VDK45', 'This is my first project', 'VDK45', 'Python']
sound = False
def send_mess(x):
global CHANEL
global PASSWORD
s = socket.socket()
s.connect((cfg.HOST, cfg.PORT))
try:
s.send("PASS {}\r\n".format(PASSWORD).encode("utf-8"))
s.send("NICK {}\r\n".format(cfg.NICK).encode("utf-8"))
s.send("JOIN #{}\r\n".format(CHANEL).encode("utf-8"))
except NameError:
print('Enter chanel an password!')
sys.exit()
#chat_message = re.compile(r"^w+")
utils.mess(s, x)
def run():
global CHANEL
global PASSWORD
global description
global description2
global description3
s = socket.socket()
try:
s.connect((cfg.HOST, cfg.PORT))
except TimeoutError:
print('Twitch connection failed')
sys.exit()
try:
s.send("PASS {}\r\n".format(PASSWORD).encode("utf-8"))
s.send("NICK {}\r\n".format(cfg.NICK).encode("utf-8"))
s.send("JOIN #{}\r\n".format(CHANEL).encode("utf-8"))
except NameError:
print('Enter chanel an password!!')
sys.exit()
chat_message = re.compile(r"^:\w+!\w+@\w+.tmi\.twitch\.tv PRIVMSG #\w+ :")
chat_message = re.compile(r"^w+")
description = utils.mess(s, "Arkanoid Начинается! Вводите команды для управления" )
description2 = utils.mess(s, "!left или !right" )
description
description2
global sound
global command
global message
global chater
global lst_chat
global loop_true
message = chater = ''
lst_chat = ['VDK45', 'Hello world!', 'VDK45', 'TF2D', 'VDK45', 'This is my first project', 'VDK45', 'Python']
while loop_true:
response = s.recv(1024).decode("utf-8")
sound = False
if response == "PING :tmi.twitch.tv\r\n":
s.send("POND :tmi.twitch.tv\r\n".encode("utf-8"))
else:
try:
username = re.search(r"\w+", response).group(0)
except AttributeError:
print('Enter your CHANEL and PASSWORD!')
message = chat_message.sub("", response).lower()
message = message[1:]
for i in message:
try:
if i == "@":
chater = message[message.index('@')+ 1:message.index('.')]
message = message[message.index(':')+ 1:]
if len(message) < 30:
lst_chat.insert(0, message)
lst_chat.insert(0, chater)
else:
lst_chat.insert(0, message[0:30])
lst_chat.insert(0, chater)
lst_chat.insert(0, f'-{message[30:60]}')
lst_chat.insert(0, chater)
lst_chat.pop()
lst_chat.pop()
lst_chat.pop()
lst_chat.pop()
except ValueError:
continue
print(f'{chater}: {message}')
st = message.split()
command = ''.join(st)
answers = ["Привет", "Хай", "Здарова", "Здравствуй", "Рад тебя видеть", "Салют", "Приветик", "Хэлло"]
hello = ["привет", "хай", "здарова", "здравствуй", "добрыйвечер", "здравствуйте", "добрыйдень", "хэлло",
"hi", "hello", 'privet']
if chater != 'nightbot':
sound = True
sleep(0.03)
sound = False
if command == "!time" or command == "!время":
named_tuple = time.localtime() # получить struct_time
time_string = time.strftime("Дата: %d/%m/%Y, Время: %H:%M", named_tuple)
utils.mess(s, time_string)
if command in hello:
utils.mess(s, answers[random.randint(0, 7)] + ' ' + chater + '!')
if command == '!help':
utils.mess(s, 'ARKANOID made by VDK45')
if command == '!l':
command = '!left'
sleep(0.1)
command = ''
if command == '!r':
command = '!right'
sleep(0.1)
command = ''
if command == '!left':
sleep(0.3)
command = ''
if command == '!right':
sleep(0.3)
command = ''
if command == '!reset':
sleep(0.3)
command = ''
if loop_true == False:
print('Twitch bot has stopped')
break
sleep(1)
| 32.088757 | 116 | 0.491425 |
6df6c6b55d592803eb12aa9541c59df303c76397 | 155 | py | Python | app/core/urls.py | kmnkit/web-todo | e06e42f5b68b2b9473fad820857634a9c5c0dadf | [
"MIT"
] | null | null | null | app/core/urls.py | kmnkit/web-todo | e06e42f5b68b2b9473fad820857634a9c5c0dadf | [
"MIT"
] | null | null | null | app/core/urls.py | kmnkit/web-todo | e06e42f5b68b2b9473fad820857634a9c5c0dadf | [
"MIT"
] | null | null | null | from django.urls import path
from teams.views import TeamListView
app_name = "core"
urlpatterns = [
path("", TeamListView.as_view(), name="home"),
]
| 17.222222 | 50 | 0.709677 |
6df927163bf069ad2144fb5439fa950c5da79469 | 1,409 | py | Python | Sources/Mavsdk/proto/pb_plugins/setup.py | obe711/MAVSDK-Swift | 3ed35bbb57754824f8235f9acf828c73cc10b72b | [
"BSD-3-Clause"
] | null | null | null | Sources/Mavsdk/proto/pb_plugins/setup.py | obe711/MAVSDK-Swift | 3ed35bbb57754824f8235f9acf828c73cc10b72b | [
"BSD-3-Clause"
] | null | null | null | Sources/Mavsdk/proto/pb_plugins/setup.py | obe711/MAVSDK-Swift | 3ed35bbb57754824f8235f9acf828c73cc10b72b | [
"BSD-3-Clause"
] | null | null | null | import os
import subprocess
import sys
from distutils.command.build import build
from distutils.spawn import find_executable
from setuptools import setup
def parse_requirements(filename):
"""
Helper which parses requirement_?.*.txt files
:param filename: relative path, e.g. `./requirements.txt`
:returns: List of requirements
"""
# Get absolute filepath
filepath = os.path.join(os.getcwd(), filename)
# Check if file exists
if not os.path.exists(filepath):
print("[!] File {} not found".format(filename))
return []
# Parse install requirements
with open(filepath, encoding="utf-8") as f:
return [requires.strip() for requires in f.readlines()]
setup(
name="protoc-gen-mavsdk",
version="1.0.1",
description="Protoc plugin used to generate MAVSDK bindings",
url="https://github.com/mavlink/MAVSDK-Proto",
maintainer="Jonas Vautherin, Julian Oes",
maintainer_email="jonas.vautherin@gmail.com, julian@oes.ch",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
],
packages=["protoc_gen_mavsdk"],
install_requires=parse_requirements("requirements.txt"),
entry_points={
"console_scripts": [
"protoc-gen-mavsdk= protoc_gen_mavsdk.__main__:main"
]
}
)
| 27.627451 | 65 | 0.66785 |
6df9c4e9ea68c87b17ca398c46b4ce7c864d776d | 109 | py | Python | src/osms/tts_modules/synthesizer/data/__init__.py | adasegroup/OSM---one-shot-multispeaker | 90c1bbea4db1d49667fcfecb51676ee3281f9458 | [
"MIT"
] | 12 | 2021-05-31T21:09:23.000Z | 2022-01-30T03:48:10.000Z | src/osms/tts_modules/synthesizer/data/__init__.py | adasegroup/OSM---one-shot-multispeaker | 90c1bbea4db1d49667fcfecb51676ee3281f9458 | [
"MIT"
] | null | null | null | src/osms/tts_modules/synthesizer/data/__init__.py | adasegroup/OSM---one-shot-multispeaker | 90c1bbea4db1d49667fcfecb51676ee3281f9458 | [
"MIT"
] | 6 | 2021-05-13T20:28:19.000Z | 2021-09-28T10:24:31.000Z | from .preprocess import SynthesizerPreprocessor
from .dataset import SynthesizerDataset, collate_synthesizer
| 36.333333 | 60 | 0.889908 |
6df9c88395294e4e4698984383fb2662d33b928e | 2,617 | py | Python | qtum_bridge/R8Blockchain/ethereumblockchain.py | Robin8Put/pmes | 338bec94162098f05b75bad035417317e1252fd2 | [
"Apache-2.0"
] | 5 | 2018-07-31T07:37:09.000Z | 2019-05-27T04:40:38.000Z | eth_bridge/R8Blockchain/ethereumblockchain.py | Robin8Put/pmes | 338bec94162098f05b75bad035417317e1252fd2 | [
"Apache-2.0"
] | 4 | 2018-08-01T11:11:54.000Z | 2022-03-11T23:20:53.000Z | qtum_bridge/R8Blockchain/ethereumblockchain.py | Robin8Put/pmes | 338bec94162098f05b75bad035417317e1252fd2 | [
"Apache-2.0"
] | 5 | 2018-06-09T07:42:04.000Z | 2018-12-28T21:15:52.000Z | from web3 import Web3, IPCProvider, HTTPProvider
from web3.middleware import geth_poa_middleware
from R8Blockchain.blockchain_handler import BlockchainHandler
from hashlib import sha256
import codecs
from web3.contract import ConciseContract
class EthereumBlockchain(BlockchainHandler):
def __init__(self, eth_rpc):
self.w3 = eth_rpc
self.w3.middleware_stack.inject(geth_poa_middleware, layer=0)
self.decode_hex = codecs.getdecoder("hex_codec")
self.encode_hex = codecs.getencoder("hex_codec")
@classmethod
def from_ipc_path(cls, ipc_path):
return cls(Web3(IPCProvider(ipc_path)))
@classmethod
def from_http_provider(cls, http_provider):
return cls(Web3(HTTPProvider(http_provider)))
def reload_http_provider(self, http_provider):
self.w3 = Web3(HTTPProvider(http_provider))
def reload_ipc_path(self, ipc_path):
self.w3 = Web3(IPCProvider(ipc_path))
def get_last_block_hash(self):
return self.encode_hex(self.w3.eth.getBlock('latest').hash)[0].decode()
def get_second_last_block_hash(self):
return self.encode_hex(self.w3.eth.getBlock(self.get_block_count()-1).hash)[0].decode()
def get_last_block_id(self):
return self.get_block_id(self.get_block_count())
def get_second_last_block_id(self):
return self.get_block_id(self.get_block_count()-1)
def get_block_id(self, height):
block_hash = self.get_block_hash(height)
l = sha256(self.decode_hex(block_hash)[0]).hexdigest()
r = hex(height)
return l[0:10] + r[2:].rjust(10, '0')
def get_block_hash(self, height):
return self.encode_hex(self.w3.eth.getBlock(height).hash)[0].decode()
def get_block_count(self):
return self.w3.eth.blockNumber
def get_unspent(self):
accounts = self.w3.personal.listAccounts
return {acc: self.w3.eth.getBalance(acc) for acc in accounts}
def get_accounts(self):
return self.w3.personal.listAccounts
def get_balance(self):
res = 0
for account in self.get_accounts():
res += self.w3.eth.getBalance(account)
return res
def from_hex_address(self, address):
return address
if __name__ == '__main__':
eth_blockchain = EthereumBlockchain.from_ipc_path(ipc_path='/home/artem/.ethereum/rinkeby/geth.ipc')
res = eth_blockchain.get_last_block_hash()
print(eth_blockchain.get_block_count())
res = eth_blockchain.get_block_hash(1200)
print(res)
print(eth_blockchain.get_balance())
print(eth_blockchain.get_unspent())
| 30.788235 | 104 | 0.704241 |
6dfaa0aa70efb8bfb33be6b88963dc80e3e7eb1f | 73 | py | Python | vis/test.py | Nathansong/OpenPCDdet-annotated | 2ca2239f3cd5cba8308b1be0744d541be4ff5093 | [
"Apache-2.0"
] | 4 | 2022-02-22T01:18:25.000Z | 2022-03-28T13:30:11.000Z | vis/test.py | Nathansong/OpenPCDdet-annotated | 2ca2239f3cd5cba8308b1be0744d541be4ff5093 | [
"Apache-2.0"
] | 1 | 2022-03-02T03:42:52.000Z | 2022-03-02T03:42:52.000Z | vis/test.py | Nathansong/OpenPCDdet-annotated | 2ca2239f3cd5cba8308b1be0744d541be4ff5093 | [
"Apache-2.0"
] | null | null | null |
path = "/home/nathan/OpenPCDet/data/kitti/training/velodyne/000000.bin" | 24.333333 | 71 | 0.780822 |
6dfb865d03b79b2e933642d474e469577e44cc93 | 690 | py | Python | count.py | sunray97/countrows_excel | 7a95e0f6901051942615c6c16d15fee8e6fd4ded | [
"MIT"
] | null | null | null | count.py | sunray97/countrows_excel | 7a95e0f6901051942615c6c16d15fee8e6fd4ded | [
"MIT"
] | null | null | null | count.py | sunray97/countrows_excel | 7a95e0f6901051942615c6c16d15fee8e6fd4ded | [
"MIT"
] | null | null | null | import xlrd
import os
import sys
# rootdir = 'D:/工作/code/electric/'
rootdir = sys.argv[1]
xlrd.Book.encoding = "gbk"
sumnum=0
filenum = 0
list = os.listdir(rootdir) #列出文件夹下所有的目录与文件
for i in range(0,len(list)):
path = os.path.join(rootdir,list[i])
if os.path.isfile(path):
print('正在处理:'+path)
data = xlrd.open_workbook(path)
table = data.sheet_by_index(0)
# table = data.sheet_by_name(u'Sheet1')
nrows = table.nrows
data.release_resources()
sumnum=sumnum+nrows
filenum=filenum+1
print('-------------------------------------------------------------------------')
print('共有%d个文件'%filenum)
print('共有%d行记录'%sumnum)
| 28.75 | 90 | 0.571014 |
6dfbe53d06b44a62a35e17a43905a5b258b2a411 | 1,442 | py | Python | 0_mesh2html/preprocess_segments.py | ygCoconut/volume2stl | bd95fc39620afd21ce08c8c805ac213583d9daaa | [
"MIT"
] | null | null | null | 0_mesh2html/preprocess_segments.py | ygCoconut/volume2stl | bd95fc39620afd21ce08c8c805ac213583d9daaa | [
"MIT"
] | null | null | null | 0_mesh2html/preprocess_segments.py | ygCoconut/volume2stl | bd95fc39620afd21ce08c8c805ac213583d9daaa | [
"MIT"
] | null | null | null | '''
0 Preprocess segments:
-
- specify segments you want to process
- dilate slightly the segments
- create mask for dilation.
- np.unique(my_masked_id) --> select only part with biggest uc
- eliminates ouliers too disconnected/far from main structure
'''
import numpy as np
import h5py
from scipy.ndimage import binary_dilation, label
from tqdm import tqdm
def writeh5_file(file, filename=None):
hf = h5py.File(filename, 'w')
hf.create_dataset('main', data=file)
hf.close()
if __name__=='__main__':
print('start')
segpath = '/n/pfister_lab2/Lab/donglai/mito/db/30um_human/seg_64nm.h5'
savepath = '/n/pfister_lab2/Lab/nils/snowproject/seg_64nm_maindendrite.h5'
seg = h5py.File(segpath, 'r')
seg = np.array(seg['main'], np.uint32) # x y z
dendrite_ids = np.loadtxt('seg_spiny_v2.txt', int)
for i, did in enumerate(tqdm(dendrite_ids)):
# dil = binary_dilation(seg==did)*did
# find all components of the dendrite, tolerate tiny gaps
s = np.ones((3, 3, 3), int)
dil, nf = label((seg==did)*did, structure=s)
# find main component
ui, uc = np.unique(dil, return_counts=True)
uc = uc[ui>0]; ui = ui[ui>0]
max_id = ui[np.argmax(uc)]
# remove non-main components from segmentation
seg[seg==did] = 0
seg[dil==max_id] = did
writeh5_file(seg, savepath)
print('start')
| 27.730769 | 78 | 0.640777 |
6dfdee78a36f76a22a8222a5f71ca90b9c824b58 | 2,665 | py | Python | branch/runner.py | sahibsin/Pruning | acc1db31c19c8b23599950cec4fe6399513ed306 | [
"MIT"
] | null | null | null | branch/runner.py | sahibsin/Pruning | acc1db31c19c8b23599950cec4fe6399513ed306 | [
"MIT"
] | null | null | null | branch/runner.py | sahibsin/Pruning | acc1db31c19c8b23599950cec4fe6399513ed306 | [
"MIT"
] | null | null | null | # Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import argparse
from dataclasses import dataclass
import sys
from cli import arg_utils
from foundations.runner import Runner
from branch import registry
@dataclass
class BranchRunner(Runner):
"""A meta-runner that calls the branch-specific runner."""
runner: Runner
@staticmethod
def description():
return "Run a branch."
@staticmethod
def add_args(parser):
# Produce help text for selecting the branch.
helptext = '='*82 + '\nOpenLTH: A Library for Research on Lottery Tickets and Beyond\n' + '-'*82
runner_name = arg_utils.maybe_get_arg('runner', positional=True, position=1)
# If the runner name is not present.
if runner_name is None or runner_name not in registry.registered_runners():
helptext = '\nChoose a runner on which to branch:\n'
helptext += '\n'.join([f' * {sys.argv[0]} branch {runner}' for runner in registry.registered_runners()])
helptext += '\n' + '='*82
print(helptext)
sys.exit(1)
# If the branch name is not present.
branch_names = registry.registered_branches(runner_name)
branch_name = arg_utils.maybe_get_arg('branch', positional=True, position=2)
if branch_name is None or branch_name not in branch_names:
helptext += '\nChoose a branch to run:'
for bn in branch_names:
helptext += "\n * {} {} {} [...] => {}".format(
sys.argv[0], sys.argv[1], bn,
registry.get(runner_name, bn).description())
helptext += '\n' + '='*82
print(helptext)
sys.exit(1)
# Add the arguments for the branch.
parser.add_argument('runner_name', type=str)
parser.add_argument('branch_name', type=str)
registry.get(runner_name, branch_name).add_args(parser)
@staticmethod
def create_from_args(args: argparse.Namespace):
runner_name = arg_utils.maybe_get_arg('runner', positional=True, position=1)
branch_name = arg_utils.maybe_get_arg('branch', positional=True, position=2)
return BranchRunner(registry.get(runner_name, branch_name).create_from_args(args))
def display_output_location(self):
self.runner.display_output_location()
def run(self) -> None:
self.runner.run()
class LotteryBranch(BranchRunner):
@staticmethod
def description():
return "Run a lottery branch."
| 36.013514 | 119 | 0.643152 |
6dff005711decae58a77ac5da887759206c11424 | 946 | py | Python | wulinfeng/L3/WordDic/AQICity.py | qsyPython/Python_play_now | 278b6d5d30082f8f93b26902c854737c4919405a | [
"MIT"
] | 2 | 2018-03-29T08:26:17.000Z | 2019-06-17T10:56:19.000Z | wulinfeng/L3/WordDic/AQICity.py | qsyPython/Python_play_now | 278b6d5d30082f8f93b26902c854737c4919405a | [
"MIT"
] | 1 | 2022-03-22T20:26:08.000Z | 2022-03-22T20:26:08.000Z | wulinfeng/L3/WordDic/AQICity.py | qsyPython/Python_play_now | 278b6d5d30082f8f93b26902c854737c4919405a | [
"MIT"
] | 1 | 2019-02-18T10:44:20.000Z | 2019-02-18T10:44:20.000Z | import requests # 导入requests 库
from bs4 import BeautifulSoup
import urllib.error
import re
class AQICityClass(object):
def cityAQI(self,url,cityName,header={}):
try:
urlName = url + cityName + '.html'
r = requests.get(urlName, header)
except urllib.error.URLError as e:
print("获取空气质量数据请求出错")
except Exception as e:
print('获取空气质量数据函数出现异常')
resp = BeautifulSoup(r.text, 'html.parser')
all_div = []
for tag in resp.find_all('div', class_='span12 data'):
all_div = tag.findAll('div')
all_divValues = []
for div in all_div:
value = div.find('div', class_='value')
if value != None:
title = value.text.strip() #取第一个<a>的文本数据
print(title.replace("\n", ""))
return title.replace("\n", "")
break | 32.62069 | 64 | 0.524313 |
6dff00eda6e7e13b33088c5ae46ed97a3a4cc3ce | 1,464 | py | Python | setup.py | hiradyazdan/nginx-amplify-agent-health-check | 7aa0fa2aba082491b1b47c2b6189a9266245f647 | [
"MIT"
] | 2 | 2018-05-23T17:34:28.000Z | 2018-07-09T21:55:53.000Z | setup.py | hiradyazdan/nginx-amplify-agent-health-check | 7aa0fa2aba082491b1b47c2b6189a9266245f647 | [
"MIT"
] | null | null | null | setup.py | hiradyazdan/nginx-amplify-agent-health-check | 7aa0fa2aba082491b1b47c2b6189a9266245f647 | [
"MIT"
] | null | null | null | from setuptools import setup
classifiers = [
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX'
] + [
('Programming Language :: Python :: %s' % x)
for x in '2.7'.split()
]
test_requirements = [
'pytest',
'pytest-cov',
'coveralls',
'mock',
'numpy',
# Only their Exceptions
'setuptools',
'psutil',
'requests'
]
with open('README.rst', 'r') as f:
long_description = f.read()
setup(
name='nginx-amplify-agent-health-check',
version='0.1.6',
description='Static and Dynamic Analysis for nginx-amplify-agent Health Status',
long_description=long_description,
url='https://github.com/hiradyazdan/nginx-amplify-agent-health-check',
author='Hirad Yazdanpanah',
author_email='hirad.y@gmail.com',
license='MIT',
platforms=["linux"],
packages=['amplifyhealthcheck'],
entry_points={
'console_scripts': [
'amphc=amplifyhealthcheck.cli:init_cli'
]
},
classifiers=classifiers,
keywords="nginx amplify nginx-amplify nginx-configuration health-check metrics",
install_requires=[
'psutil',
'setuptools',
'ntplib',
'crossplane',
'requests'
],
setup_requires=['pytest-runner'],
tests_require=test_requirements,
extras_require={
'test': test_requirements,
},
python_requires='==2.7.*',
zip_safe=False
)
| 24 | 84 | 0.623634 |
6dff3f59a4fe7a48fffadc9f63e01aeba249b8e0 | 580 | py | Python | koodous/exceptions.py | Koodous/python-sdk | 987a8d48d1fb1ba599375dc55cb2d283a8cd34c8 | [
"Apache-2.0"
] | 19 | 2016-11-24T06:13:20.000Z | 2021-07-02T05:06:38.000Z | koodous/exceptions.py | Koodous/python-sdk | 987a8d48d1fb1ba599375dc55cb2d283a8cd34c8 | [
"Apache-2.0"
] | 18 | 2015-12-05T14:09:24.000Z | 2021-06-07T11:55:53.000Z | koodous/exceptions.py | Koodous/python-sdk | 987a8d48d1fb1ba599375dc55cb2d283a8cd34c8 | [
"Apache-2.0"
] | 10 | 2015-12-04T20:01:53.000Z | 2020-12-02T07:30:03.000Z | class ApiException(Exception):
"""Koodous API base class."""
class ApiUnauthorizedException(ApiException):
"""Exception when is made a request without the correct token or insufficient privileges."""
class FeedException(ApiException):
"""Base class for the feed exceptions."""
class FeedPackageException(FeedException):
"""Exception related to the feed package."""
class PackageInvalidFormatException(FeedException):
"""Package format invalid exception. Check the koodous api docs."""
class ApkNotFound(ApiException):
"""Apk sample not found."""
| 25.217391 | 96 | 0.743103 |
6dff73cffaed94db5cb5e75fb80b3961ad0f9146 | 1,005 | py | Python | pybatfish/datamodel/aspath.py | li-ch/pybatfish | d406f87a2bdd8d3beb92dc1baa9a5c8d63391879 | [
"Apache-2.0"
] | 1 | 2019-05-09T13:00:39.000Z | 2019-05-09T13:00:39.000Z | pybatfish/datamodel/aspath.py | li-ch/pybatfish | d406f87a2bdd8d3beb92dc1baa9a5c8d63391879 | [
"Apache-2.0"
] | null | null | null | pybatfish/datamodel/aspath.py | li-ch/pybatfish | d406f87a2bdd8d3beb92dc1baa9a5c8d63391879 | [
"Apache-2.0"
] | null | null | null | # coding=utf-8
# Copyright 2018 The Batfish Open Source Project
#
# 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.
class AsPath(object):
"""Represents a BGP AS Path."""
def __init__(self, as_set_list):
self.asPath = [list(asSet) for asSet in as_set_list]
def __repr__(self):
return '[' + ','.join(
(asSet[0] if len(asSet) == 0 else '[' + ','.join(
str(asNumber) for asNumber in asSet)) for asSet in
self.asPath) + ']'
| 35.892857 | 76 | 0.664677 |
6dffaf2548225e608c4b2975db6390a9dca03d10 | 2,849 | py | Python | sherlock_scripts/pythonhops/sherlock_combine_restarts.py | apoletayev/anomalous_ion_conduction | badb91e971e4a5263a433cfa9fcbf914d53ed2a1 | [
"MIT"
] | 2 | 2021-05-20T03:49:51.000Z | 2021-06-21T08:41:10.000Z | sherlock_scripts/pythonhops/sherlock_combine_restarts.py | apoletayev/anomalous_ion_conduction | badb91e971e4a5263a433cfa9fcbf914d53ed2a1 | [
"MIT"
] | null | null | null | sherlock_scripts/pythonhops/sherlock_combine_restarts.py | apoletayev/anomalous_ion_conduction | badb91e971e4a5263a433cfa9fcbf914d53ed2a1 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 3 01:41:52 2020
Combines LAMMPS output files coming from a series of restarts with a * wildcard.
This works on expanded (mode scalar) fixes from LAMMPS where each line is a time.
The overlapping values of times due to restarts are averaged, but they should be identical.
Required command-line args : filenames= ,
Optional command-line args : file_out= ,
@author: andreypoletaev
"""
# =============================================================================
# %% Imports and constants
# =============================================================================
import pandas as pd
import sys
from glob import glob
# =============================================================================
# %% parse input and combine
# =============================================================================
## Parse inputs. Format: key=value
options = dict([ (x.split('=')[0],x.split('=')[1]) for x in sys.argv[1:] ])
keys = list(options.keys())
# print(options)
assert 'filenames' in keys, 'please pass filenames=... [path] as command-line option'
# template = f'/*_vacf_{int(options["duration"])}ps.csv' if 'template' not in keys else options['template']
file_out = options['filenames'].replace('*','') if 'file_out' not in keys else options['file_out']
print('looking for files that look like this: '+options['filenames'], flush=True)
output = pd.DataFrame()
counter = 0
files_to_combine = sorted(glob(options['filenames']))
assert len(files_to_combine) > 1, 'Only one file fits the bill, skipping combining.'
print(files_to_combine, flush=True)
for fin in files_to_combine:
try:
## read the header for column names
fp = open(fin, 'r')
line1 = fp.readline()
line2 = fp.readline()
fp.close()
colnames = line2[:-1].split(' ')[1:]
## read the actual numbers
df = pd.read_csv(fin, skiprows=1, sep=' ')
# colnames = df.iloc[0,1:-1].tolist()
df = df.iloc[:, :-1]
df.columns = colnames
df = df.apply(pd.to_numeric)
# print(df.columns)
# print(df.head(5))
# print(df.dtypes)
# print(df.head())
if len(df) > 0:
output = output.append(df, ignore_index=True)
counter += 1
print(f'appended data from file #{counter} : {fin}', flush=True)
except: print(f'could not load / add {fin}', flush=True)
## ensemble-average in all cases - but not always the first thing
output = output.groupby('TimeStep').agg('mean').reset_index().rename(columns={'TimeStep':line1[:-1]+'\n# '+'TimeStep'})
# output.TimeStep = output.TimeStep.astype(int)
## write file normally
output.to_csv(file_out, index=False, float_format='%.6g', sep=' ') | 32.011236 | 119 | 0.562654 |
a30096d1e64ea75464caa5c47e07ed034748bbc2 | 3,680 | py | Python | src/imephu/utils.py | saltastroops/imephu | 0c302a73d01fe3ad018e7adf4b91e0beaecc6709 | [
"MIT"
] | null | null | null | src/imephu/utils.py | saltastroops/imephu | 0c302a73d01fe3ad018e7adf4b91e0beaecc6709 | [
"MIT"
] | 3 | 2022-02-02T20:51:05.000Z | 2022-02-03T21:13:27.000Z | src/imephu/utils.py | saltastroops/imephu | 0c302a73d01fe3ad018e7adf4b91e0beaecc6709 | [
"MIT"
] | null | null | null | from dataclasses import dataclass
from datetime import datetime
from typing import List, Optional
from astropy.coordinates import SkyCoord
@dataclass
class MagnitudeRange:
"""A magnitude range.
Attributes
----------
bandpass: `str`
The bandpass for which the magnitudes are given.
min_magnitude: `float`
The minimum (brightest) magnitude.
max_magnitude: `float`
The maximum (faintest) magnitude.
"""
bandpass: str
min_magnitude: float
max_magnitude: float
@dataclass
class Ephemeris:
"""An ephemeris with an epoch, position and magnitude range.
Parameters
----------
epoch: `~datetime.datetime`
The epoch, i.e. the datetime for which the position is given. The epoch must be
a timezone-aware datetime.
position: `~astropy.coordinates.SkyCoord`
The position, in right ascension and declination.
magnitude_range: `~imephu.utils.MagnitudeRange`
The magnitude range.
"""
epoch: datetime
position: SkyCoord
magnitude_range: Optional[MagnitudeRange]
def __post_init__(self) -> None:
"""Check that the epoch is timezone-aware."""
if self.epoch.tzinfo is None or self.epoch.tzinfo.utcoffset(None) is None:
raise ValueError("The epoch must be a timezone-aware datetime object.")
def mid_position(start: SkyCoord, end: SkyCoord) -> SkyCoord:
"""Return the mid position between a start and end position on the sky.
The mid position is the mid position on the great arc between the start and end
position.
Taken from https://github.com/astropy/astropy/issues/5766.
Parameters
----------
start: `~astropy.coordinates.SkyCoords`
Start position on the sky.
end: `~astropy.coordinates.SkyCoords`
End position on the sky.
"""
pa = start.position_angle(end)
separation = start.separation(end)
return start.directional_offset_by(pa, separation / 2)
def ephemerides_magnitude_range(
ephemerides: List[Ephemeris],
) -> Optional[MagnitudeRange]:
"""Return the magnitude range for a list of ephemerides.
The minimum (maximum) magnitude is the minimum (maximum) magnitude for all
ephemerides. If none of the ephemerides has a magnitude range, ``None`` is returned.
Parameters
----------
ephemerides: list of `~imephu.utils.Ephemeris`
The list of ephemerides.
Returns
-------
`~imephu.utils.MagnitudeRange`, optional
The magnitude range for the list of ephemerides.
"""
min_magnitude: Optional[float] = None
max_magnitude: Optional[float] = None
bandpass: Optional[str] = None
for ephemeris in ephemerides:
if ephemeris.magnitude_range:
if (
min_magnitude is None
or ephemeris.magnitude_range.min_magnitude < min_magnitude
):
min_magnitude = ephemeris.magnitude_range.min_magnitude
if (
max_magnitude is None
or ephemeris.magnitude_range.max_magnitude > max_magnitude
):
max_magnitude = ephemeris.magnitude_range.max_magnitude
if bandpass is None:
bandpass = ephemeris.magnitude_range.bandpass
elif ephemeris.magnitude_range.bandpass != bandpass:
raise ValueError("The bandpass must be the same for all ephemerides.")
if min_magnitude is not None and max_magnitude is not None and bandpass is not None:
return MagnitudeRange(
min_magnitude=min_magnitude, max_magnitude=max_magnitude, bandpass=bandpass
)
else:
return None
| 31.186441 | 88 | 0.664402 |
a3009f5a1a8c11a46a1920015fba53e4cf3ae345 | 1,875 | py | Python | app.py | zorro1992/task-app-devops | 48312e53ce5711ce0d9508b481e73f78df411dd2 | [
"MIT"
] | 1 | 2021-08-19T11:54:08.000Z | 2021-08-19T11:54:08.000Z | app.py | zorro1992/task-app-devops | 48312e53ce5711ce0d9508b481e73f78df411dd2 | [
"MIT"
] | null | null | null | app.py | zorro1992/task-app-devops | 48312e53ce5711ce0d9508b481e73f78df411dd2 | [
"MIT"
] | null | null | null | """
app
"""
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
# /// = relative path, //// = absolute path
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class Todo(db.Model):
"""A dummy docstring."""
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100))
complete = db.Column(db.Boolean)
def pub1(self):
"""A dummy docstring."""
print("")
def pub2(self):
"""A dummy docstring."""
print("")
# Edit endpoint
@app.route("/edit")
def home1():
"""A dummy docstring."""
todo_list = Todo.query.all()
return render_template("base.html", todo_list=todo_list)
# Default home endpoint
@app.route("/")
def list1():
"""A dummy docstring."""
todo_list = Todo.query.all()
return render_template("list.html", todo_list=todo_list)
# Add endpoint
@app.route("/add", methods=["POST"])
def add():
"""A dummy docstring."""
title = request.form.get("title")
new_todo = Todo(title=title, complete=False)
db.session.add(new_todo)
db.session.commit()
return redirect(url_for("home1"))
# Update endpoint
@app.route("/update/<int:todo_id>")
def update(todo_id):
"""A dummy docstring."""
todo = Todo.query.filter_by(id=todo_id).first()
todo.complete = not todo.complete
db.session.commit()
return redirect(url_for("home1"))
# Delete endpoint
@app.route("/delete/<int:todo_id>")
def delete(todo_id):
"""A dummy docstring."""
todo = Todo.query.filter_by(id=todo_id).first()
db.session.delete(todo)
db.session.commit()
return redirect(url_for("home1"))
# Main function
if __name__ == "__main__":
db.create_all()
app.run(host="0.0.0.0", debug=True)
| 25 | 68 | 0.6544 |
a304245df7598c6937f92e93f9b38b346d5b4c9a | 2,009 | py | Python | app/models/version.py | akashtalole/python-flask-restful-api | 475d8fd7be1724183716a197aac4257f8fbbeac4 | [
"MIT"
] | 3 | 2019-09-05T05:28:49.000Z | 2020-06-10T09:03:37.000Z | app/models/version.py | akashtalole/python-flask-restful-api | 475d8fd7be1724183716a197aac4257f8fbbeac4 | [
"MIT"
] | null | null | null | app/models/version.py | akashtalole/python-flask-restful-api | 475d8fd7be1724183716a197aac4257f8fbbeac4 | [
"MIT"
] | null | null | null | from sqlalchemy.orm import backref
from app.models import db
class Version(db.Model):
"""Version model class"""
__tablename__ = 'versions'
id = db.Column(db.Integer, primary_key=True)
event_id = db.Column(db.Integer, db.ForeignKey('events.id', ondelete='CASCADE'))
events = db.relationship("Event", backref=backref('version', uselist=False))
event_ver = db.Column(db.Integer, nullable=False, default=0)
sessions_ver = db.Column(db.Integer, nullable=False, default=0)
speakers_ver = db.Column(db.Integer, nullable=False, default=0)
tracks_ver = db.Column(db.Integer, nullable=False, default=0)
sponsors_ver = db.Column(db.Integer, nullable=False, default=0)
microlocations_ver = db.Column(db.Integer, nullable=False, default=0)
def __init__(self,
event_id=None,
event_ver=None,
sessions_ver=None,
speakers_ver=None,
tracks_ver=None,
sponsors_ver=None,
microlocations_ver=None):
self.event_id = event_id
self.event_ver = event_ver
self.sessions_ver = sessions_ver
self.speakers_ver = speakers_ver
self.tracks_ver = tracks_ver
self.sponsors_ver = sponsors_ver
self.microlocations_ver = microlocations_ver
def __repr__(self):
return '<Version %r>' % self.id
def __str__(self):
return self.__repr__()
@property
def serialize(self):
"""Return object data in easily serializable format"""
return {
'version': [
{'id': self.id,
'event_id': self.event_id,
'event_ver': self.event_ver,
'sessions_ver': self.sessions_ver,
'speakers_ver': self.speakers_ver,
'tracks_ver': self.tracks_ver,
'sponsors_ver': self.sponsors_ver,
'microlocations_ver': self.microlocations_ver}
]
}
| 35.245614 | 84 | 0.60677 |
a304b175c7cbd222a910af9551f6a774a35e4ab2 | 4,642 | py | Python | pydatajson/catalog_readme.py | datosgobar/pydatajson | f26e3d5928ce9d455485e03fa63a8d8741588b7a | [
"MIT"
] | 13 | 2017-05-17T13:33:43.000Z | 2021-08-10T18:42:59.000Z | pydatajson/catalog_readme.py | datosgobar/pydatajson | f26e3d5928ce9d455485e03fa63a8d8741588b7a | [
"MIT"
] | 296 | 2016-11-29T14:01:09.000Z | 2020-10-27T22:42:26.000Z | pydatajson/catalog_readme.py | datosgobar/pydatajson | f26e3d5928ce9d455485e03fa63a8d8741588b7a | [
"MIT"
] | 11 | 2017-07-06T17:02:31.000Z | 2021-07-19T14:46:51.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import with_statement
import io
import logging
import os
from six import string_types
from pydatajson.helpers import traverse_dict
from pydatajson.indicators import generate_catalogs_indicators
from pydatajson.readers import read_catalog
from pydatajson.validation import validate_catalog
logger = logging.getLogger('pydatajson')
CENTRAL_CATALOG = "http://datos.gob.ar/data.json"
ABSOLUTE_PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
TEMPLATES_PATH = os.path.join(ABSOLUTE_PROJECT_DIR, "templates")
def generate_catalog_readme(_datajson, catalog,
export_path=None, verify_ssl=True):
"""Este método está para mantener retrocompatibilidad con versiones
anteriores. Se ignora el argumento _data_json."""
return generate_readme(catalog, export_path, verify_ssl=verify_ssl)
def generate_readme(catalog, export_path=None, verify_ssl=True):
"""Genera una descripción textual en formato Markdown sobre los
metadatos generales de un catálogo (título, editor, fecha de
publicación, et cetera), junto con:
- estado de los metadatos a nivel catálogo,
- estado global de los metadatos,
- cantidad de datasets federados y no federados,
- detalles de los datasets no federados
- cantidad de datasets y distribuciones incluidas
Es utilizada por la rutina diaria de `libreria-catalogos` para generar
un README con información básica sobre los catálogos mantenidos.
Args:
catalog (str o dict): Path a un catálogo en cualquier formato,
JSON, XLSX, o diccionario de python.
export_path (str): Path donde exportar el texto generado (en
formato Markdown). Si se especifica, el método no devolverá
nada.
Returns:
str: Texto de la descripción generada.
"""
# Si se paso una ruta, guardarla
if isinstance(catalog, string_types):
catalog_path_or_url = catalog
else:
catalog_path_or_url = None
catalog = read_catalog(catalog)
validation = validate_catalog(catalog, verify_ssl=verify_ssl)
# Solo necesito indicadores para un catalogo
indicators = generate_catalogs_indicators(
catalog, CENTRAL_CATALOG)[0][0]
with io.open(os.path.join(TEMPLATES_PATH, 'catalog_readme.txt'), 'r',
encoding='utf-8') as template_file:
readme_template = template_file.read()
not_federated_datasets_list = "\n".join([
"- [{}]({})".format(dataset[0], dataset[1])
for dataset in indicators["datasets_no_federados"]
])
federated_removed_datasets_list = "\n".join([
"- [{}]({})".format(dataset[0], dataset[1])
for dataset in indicators["datasets_federados_eliminados"]
])
federated_datasets_list = "\n".join([
"- [{}]({})".format(dataset[0], dataset[1])
for dataset in indicators["datasets_federados"]
])
non_federated_pct = 1.0 - indicators["datasets_federados_pct"] if \
indicators["datasets_federados_pct"] is not None else \
indicators["datasets_federados_pct"]
content = {
"title": catalog.get("title"),
"publisher_name": traverse_dict(
catalog, ["publisher", "name"]),
"publisher_mbox": traverse_dict(
catalog, ["publisher", "mbox"]),
"catalog_path_or_url": catalog_path_or_url,
"description": catalog.get("description"),
"global_status": validation["status"],
"catalog_status": validation["error"]["catalog"]["status"],
"no_of_datasets": len(catalog["dataset"]),
"no_of_distributions": sum([len(dataset["distribution"]) for
dataset in catalog["dataset"]]),
"federated_datasets": indicators["datasets_federados_cant"],
"not_federated_datasets": indicators["datasets_no_federados_cant"],
"not_federated_datasets_pct": non_federated_pct,
"not_federated_datasets_list": not_federated_datasets_list,
"federated_removed_datasets_list": federated_removed_datasets_list,
"federated_datasets_list": federated_datasets_list,
}
catalog_readme = readme_template.format(**content)
if export_path:
with io.open(export_path, 'w+', encoding='utf-8') as target:
target.write(catalog_readme)
else:
return catalog_readme
| 40.365217 | 79 | 0.667816 |
a304eeaa7c9f4ed5704a6d6deba75d5ddfdbb3d1 | 346 | py | Python | code-tk/scrollbar.py | shilpasayura/bk | 2b0a1aa9300da80e201264bcf80226b3c5ff4ad6 | [
"MIT"
] | 4 | 2018-09-08T10:30:27.000Z | 2021-07-23T07:59:24.000Z | code-tk/scrollbar.py | shilpasayura/bk | 2b0a1aa9300da80e201264bcf80226b3c5ff4ad6 | [
"MIT"
] | null | null | null | code-tk/scrollbar.py | shilpasayura/bk | 2b0a1aa9300da80e201264bcf80226b3c5ff4ad6 | [
"MIT"
] | 6 | 2018-09-07T05:54:17.000Z | 2021-07-23T07:59:25.000Z | from tkinter import *
import tkinter
root = Tk()
scrollbar = Scrollbar(root)
scrollbar.pack( side = RIGHT, fill=Y )
mylist = Listbox(root, yscrollcommand = scrollbar.set )
for line in range(100):
mylist.insert(END, "Line number : " + str(line))
mylist.pack( side = LEFT, fill = BOTH )
scrollbar.config( command = mylist.yview )
mainloop()
| 21.625 | 55 | 0.705202 |
a305196df6eec0820f9171fbedc0fc320734bad3 | 8,354 | py | Python | pkgs/sdk-pkg/src/genie/libs/sdk/apis/iosxe/sisf/get.py | patrickboertje/genielibs | 61c37aacf3dd0f499944555e4ff940f92f53dacb | [
"Apache-2.0"
] | 1 | 2022-01-16T10:00:24.000Z | 2022-01-16T10:00:24.000Z | pkgs/sdk-pkg/src/genie/libs/sdk/apis/iosxe/sisf/get.py | patrickboertje/genielibs | 61c37aacf3dd0f499944555e4ff940f92f53dacb | [
"Apache-2.0"
] | null | null | null | pkgs/sdk-pkg/src/genie/libs/sdk/apis/iosxe/sisf/get.py | patrickboertje/genielibs | 61c37aacf3dd0f499944555e4ff940f92f53dacb | [
"Apache-2.0"
] | null | null | null | """Common get functions for sisf"""
# Python
import logging
import re
# Genie
from genie.metaparser.util.exceptions import SchemaEmptyParserError
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
def get_device_tracking_policy_name_configurations(device, policy):
""" Get device-tracking policy configurations
Args:
device ('obj'): device object
policy ('str'): policy name
Returns:
Dictionary
None
Raises:
None
"""
try:
out = device.parse('show device-tracking policy {policy}'.format(policy=policy))
return out.get('configuration', None)
except SchemaEmptyParserError:
log.info("Command has not returned any results")
return None
def get_device_tracking_database_details_binding_table_configurations(device):
""" Get device-tracking policy configurations
Args:
device ('obj'): device object
Returns:
Dictionary
None
Raises:
None
"""
try:
out = device.parse('show device-tracking database details')
return out.get('binding_table_configuration', None)
except SchemaEmptyParserError:
log.info("Command has not returned any results")
return None
def get_device_tracking_database_details_binding_table_count(device, state=False):
""" Get device-tracking policy configurations
Args:
device ('obj'): device object
state('bool', optional): get state count if True. Defaults to False
Returns:
Dictionary
None
Raises:
None
"""
if state:
key = 'binding_table_state_count'
else:
key = 'binding_table_count'
try:
out = device.parse('show device-tracking database details')
return out.get(key, None)
except SchemaEmptyParserError:
log.info("Command has not returned any results")
return None
def get_ipv6_nd_raguard_policy_configurations(device, policy):
""" Get ipv6 nd raguard policy configurations
Args:
device ('obj'): device object
policy ('str'): policy name
Returns:
Dictionary
None
Raises:
None
"""
try:
out = device.parse('show ipv6 nd raguard policy {policy}'.format(policy=policy))
return out.get('configuration', None)
except SchemaEmptyParserError:
log.info("Command has not returned any results")
return None
def get_ipv6_source_guard_policy_configurations(device, policy):
""" Get ipv6 source guard policy configurations
Args:
device ('obj'): device object
policy ('str'): policy name
Returns:
Dictionary
None
Raises:
None
"""
try:
out = device.parse('show ipv6 source-guard policy {policy}'.format(policy=policy))
return out.get('configuration', None)
except SchemaEmptyParserError:
log.info("Command has not returned any results")
return None
def get_device_tracking_counters_vlan_message_type(device, vlanid, message_type="received"):
""" Get device_tracking vlan count message type
Args:
device ('obj'): device object
vlanid ('str'): vlan
message_type ('str', optional): message type. Defaults to "received"
Returns:
Dictionary
None
Raises:
None
"""
try:
out = device.parse('show device-tracking counters vlan {vlanid}'.format(vlanid=vlanid))
except SchemaEmptyParserError:
log.info("Command has not returned any results")
message_dict = out.get("vlanid", {}).get(int(vlanid), {})
if not message_dict:
log.info("There is no activity corresponding to the message type {type}"
.format(type=message_type))
return None
return message_dict
def get_device_tracking_counters_vlan_faults(device, vlanid):
""" Get device_tracking vlan count message type
Args:
device ('obj'): device object
vlanid ('str'): vlan
Returns:
List
None
Raises:
None
"""
try:
out = device.parse('show device-tracking counters vlan {vlanid}'.format(vlanid=vlanid))
except SchemaEmptyParserError:
log.info("Command has not returned any results")
fault_list = out.get("vlanid", {}).get(int(vlanid), {}).get("faults", [])
if not fault_list:
log.info("There are no faults on vlan {vlanid}".format(vlanid=vlanid))
return None
return fault_list
def get_ip_theft_syslogs(device):
"""Gets IP Theft syslog
Args:
device (obj): device object
Returns:
Dictionary
None
Raises:
None
"""
try:
out = device.parse('show logging | include %SISF-4-IP_THEFT')
except SchemaEmptyParserError:
return {}
# Need to perform additional parsing to extract IP Theft specific data
# *Sep 15 12:53:06.383 EST:
timematch = r'.(?P<timestamp>[A-Za-z]{3}\s+\d+ \d+:\d+:\d+\.\d+( [A-Z]+)?:)'
# *Sep 15 12:53:06.383 EST: %SISF-4-IP_THEFT: IP Theft IP=2001:DB8::101 VLAN=20 MAC=dead.beef.0001 IF=Twe1/0/1 New MAC=dead.beef.0002 New I/F=Twe1/0/1
theft1 = re.compile(
timematch +
r'\s+%SISF-4-IP_THEFT: IP Theft' +
r'\s+IP=(?P<ip>([a-fA-F\d\:]+)|(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))' +
r'\s+VLAN=(?P<vlan>\d+)' +
r'\s+MAC=(?P<mac>([a-fA-F\d]{4}\.){2}[a-fA-F\d]{4})' +
r'\s+IF=(?P<interface>[\w\/\.\-\:]+)' +
r'\s+New Mac=(?P<new_mac>([a-fA-F\d]{4}\.){2}[a-fA-F\d]{4})' +
r'\s+New I/F=(?P<new_if>[\w\/\.\-\:]+)'
)
# *Sep 16 19:22:29.392 EST: %SISF-4-IP_THEFT: IP Theft IP=2001:DB8::105 VLAN=20 Cand-MAC=dead.beef.0002 Cand-I/F=Twe1/0/1 Known MAC over-fabric Known I/F over-fabric
theft2 = re.compile(
timematch +
r'\s+%SISF-4-IP_THEFT: IP Theft' +
r'\s+IP=(?P<ip>([a-fA-F\d\:]+)|(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))' +
r'\s+VLAN=(?P<vlan>\d+)' +
r'\s+Cand-MAC=(?P<cand_mac>([a-fA-F\d]{4}\.){2}[a-fA-F\d]{4})' +
r'\s+Cand-I/F=(?P<cand_if>[\w\/\.\-\:]+)'
)
# *Oct 20 16:58:24.807 EST: %SISF-4-IP_THEFT: IP Theft IP=2001:DB8::105 VLAN=20 MAC=dead.beef.0001 IF=Twe1/0/1 New I/F over fabric
theft3 = re.compile(
timematch +
r'\s+%SISF-4-IP_THEFT: IP Theft' +
r'\s+IP=(?P<ip>([a-fA-F\d\:]+)|(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))' +
r'\s+VLAN=(?P<vlan>\d+)' +
r'\s+MAC=(?P<mac>([a-fA-F\d]{4}\.){2}[a-fA-F\d]{4})' +
r'\s+IF=(?P<if>[\w\/\.\-\:]+)'
)
log_dict = {}
for log_entry in out['logs']:
m = theft1.match(log_entry)
if m:
entry = {}
group = m.groupdict()
ip = group['ip']
vlan = group['vlan']
mac = group['mac']
interface = group['interface']
new_mac = group['new_mac']
new_interface = group['new_if']
entry['ip'] = ip
entry['vlan'] = vlan
entry['mac'] = mac
entry['interface'] = interface
entry['new_mac'] = new_mac
entry['new_interface'] = new_interface
log_dict.setdefault('entries', []).append(entry)
m = theft2.match(log_entry)
if m:
entry = {}
group = m.groupdict()
ip = group['ip']
vlan = group['vlan']
new_mac = group['cand_mac']
new_if = group['cand_if']
entry['ip'] = ip
entry['vlan'] = vlan
entry['new_mac'] = new_mac
entry['new_interface'] = new_if
log_dict.setdefault('entries', []).append(entry)
m = theft3.match(log_entry)
if m:
entry = {}
group = m.groupdict()
ip = group['ip']
vlan = group['vlan']
mac = group['mac']
new_if = group['if']
entry['ip'] = ip
entry['vlan'] = vlan
entry['mac'] = mac
entry['new_interface'] = new_if
log_dict.setdefault('entries', []).append(entry)
return log_dict | 30.268116 | 169 | 0.556739 |
a3052e2c0e4e4d32b495f5d940bc6dff09090dc4 | 1,742 | py | Python | Solutions/2021/13.py | Azurealistic/Winter | 4ef5d1fde10f9ba769c33597e1269f161068f18b | [
"Unlicense"
] | 1 | 2021-12-18T20:02:57.000Z | 2021-12-18T20:02:57.000Z | Solutions/2021/13.py | Azurealistic/Winter | 4ef5d1fde10f9ba769c33597e1269f161068f18b | [
"Unlicense"
] | null | null | null | Solutions/2021/13.py | Azurealistic/Winter | 4ef5d1fde10f9ba769c33597e1269f161068f18b | [
"Unlicense"
] | null | null | null | # Advent of Code 2021 - Day: 13
# Imports (Always imports data based on the folder and file name)
from aocd import data, submit
def solve(data):
# Parse input
# Split the input into two lists, based on where the empty line is
# Find the index of the line that is '', and use that to split the list
# Return the two lists
coordinates, instructions = data.strip().split("\n\n")
coordinates = [[int(x) for x in ln.split(",")] for ln in coordinates.strip().split("\n")]
instructions = [ln.split() for ln in instructions.strip().split("\n")]
for iteration, fold in enumerate(instructions):
direction, location = fold[-1].split('=')
location = int(location)
points = set()
# PLace the point based on the current fold.
for (x, y) in coordinates:
if direction == 'y':
if y < location:
points.add((x, y))
else:
points.add((x, location - (y - location)))
elif direction == 'x':
if x < location:
points.add((x, y))
else:
points.add((location - (x - location), y))
coordinates = points
if iteration == 0:
print("Star 1:", len(coordinates))
submit(len(coordinates), part="a", day=13, year=2021)
grid = []
for n in range(10):
grid.append(list(" " * 80))
for (x, y) in coordinates:
grid[y][x] = '█'
# Print the grid, by using each row as a string, and then joining them with newlines, only include rows that have a '#' and print up to the final '#'
print("Star 2:")
print("\n".join(["".join(row) for row in grid if '█' in row]))
# This has to be manually submitted, because it's a visual representation of the grid.
submit("RHALRCRA", part="b", day=13, year=2021)
# Solution
def main():
solve(data)
# Call the main function.
if __name__ == '__main__':
main() | 29.525424 | 150 | 0.647532 |
a3053ef8acac68ff1083564fcebe2d53409309ba | 13,598 | py | Python | hax/test/test_work_planner.py | ajaykumarptl/cortx-hare | 6eada402c3f90f2f56743efb959ea308b9e171e5 | [
"Apache-2.0"
] | 16 | 2020-09-25T09:34:07.000Z | 2022-03-29T17:26:39.000Z | hax/test/test_work_planner.py | ajaykumarptl/cortx-hare | 6eada402c3f90f2f56743efb959ea308b9e171e5 | [
"Apache-2.0"
] | 536 | 2020-09-24T14:59:10.000Z | 2022-03-31T15:44:52.000Z | hax/test/test_work_planner.py | ajaykumarptl/cortx-hare | 6eada402c3f90f2f56743efb959ea308b9e171e5 | [
"Apache-2.0"
] | 108 | 2020-09-24T15:09:29.000Z | 2022-03-25T10:13:19.000Z | # Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates
#
# 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.
#
# For any questions about this software or licensing,
# please email opensource@seagate.com or cortx-questions@seagate.com.
#
# flake8: noqa
import logging
import time
import unittest
from threading import Condition, Thread
from time import sleep
from typing import List
from unittest.mock import Mock
from hax.log import TRACE
from hax.message import (BaseMessage, BroadcastHAStates, Die,
EntrypointRequest,
HaNvecGetEvent)
from hax.motr.planner import WorkPlanner, State
from hax.motr.util import LinkedList
from hax.types import Fid, Uint128
LOG = logging.getLogger('hax')
class GroupTracker:
def __init__(self):
self.lock = Condition()
self.data = []
def log(self, cmd: BaseMessage):
with self.lock:
self.data.append(cmd.group)
def get_tracks(self) -> List[BaseMessage]:
with self.lock:
return list(self.data)
def entrypoint():
return EntrypointRequest(reply_context='test',
req_id=Uint128(1, 2),
remote_rpc_endpoint='endpoint',
process_fid=Fid(1, 2),
git_rev='HEAD',
pid=123,
is_first_request=False)
def broadcast():
return BroadcastHAStates(states=[], reply_to=None)
def nvec_get():
return HaNvecGetEvent(hax_msg=1, nvec=[])
class TestMessageOrder(unittest.TestCase):
@classmethod
def setUpClass(cls):
# It seems like when unittest is invoked from setup.py,
# some default logging configuration is already applied;
# invoking setup_logging() will make the log messages to appear twice.
logging.addLevelName(TRACE, 'TRACE')
logging.getLogger('hax').setLevel(TRACE)
def test_entrypoint_requests_share_same_group(self):
planner = WorkPlanner()
ep1 = entrypoint()
ep2 = entrypoint()
ep1 = planner._assign_group(ep1)
ep2 = planner._assign_group(ep2)
self.assertEqual([0, 0], [ep1.group, ep2.group])
def test_entrypoint_not_paralleled_with_broadcast(self):
planner = WorkPlanner()
bcast = broadcast()
ep1 = entrypoint()
bcast = planner._assign_group(bcast)
ep1 = planner._assign_group(ep1)
self.assertEqual([0, 1], [bcast.group, ep1.group])
def test_broadcast_starts_new_group(self):
planner = WorkPlanner()
assign = planner._assign_group
msgs = [
assign(broadcast()),
assign(broadcast()),
assign(broadcast()),
assign(entrypoint())
]
self.assertEqual([0, 1, 2, 3], [m.group for m in msgs])
def test_group_id_cycled(self):
def my_state():
return State(next_group_id=99999,
active_commands=LinkedList(),
taken_commands=LinkedList(),
current_group_id=99999,
next_group_commands=set(),
is_shutdown=False)
planner = WorkPlanner(init_state_factory=my_state)
assign = planner._assign_group
msgs = [
assign(broadcast()),
assign(broadcast()),
assign(broadcast()),
assign(entrypoint())
]
self.assertEqual([99999, 10**5, 0, 1], [m.group for m in msgs])
def test_ha_nvec_get_shares_group_always(self):
planner = WorkPlanner()
assign = planner._assign_group
msgs_after_bc = [
assign(broadcast()),
assign(nvec_get()),
assign(broadcast()),
assign(entrypoint())
]
msgs_after_ep = [
assign(entrypoint()),
assign(nvec_get()),
assign(broadcast()),
assign(entrypoint())
]
msgs_after_nvec = [
assign(entrypoint()),
assign(nvec_get()),
assign(nvec_get()),
assign(entrypoint())
]
self.assertEqual([0, 0, 1, 2], [m.group for m in msgs_after_bc])
self.assertEqual([2, 2, 3, 4], [m.group for m in msgs_after_ep])
self.assertEqual([4, 4, 4, 4], [m.group for m in msgs_after_nvec])
class TestWorkPlanner(unittest.TestCase):
@classmethod
def setUpClass(cls):
# It seems like when unittest is invoked from setup.py,
# some default logging configuration is already applied;
# invoking setup_logging() will make the log messages to appear twice.
logging.addLevelName(TRACE, 'TRACE')
logging.getLogger('hax').setLevel(TRACE)
def test_parallelism_is_possible(self):
planner = WorkPlanner()
for i in range(40):
planner.add_command(entrypoint())
for j in range(4):
planner.add_command(Die())
exc = None
def fn(planner: WorkPlanner):
nonlocal exc
try:
while True:
LOG.log(TRACE, "Requesting for a work")
cmd = planner.get_next_command()
LOG.log(TRACE, "The command is received")
if isinstance(cmd, Die):
LOG.log(TRACE,
"Poison pill is received - exiting. Bye!")
break
sleep(0.5)
LOG.log(TRACE, "The job is done, notifying the planner")
planner.notify_finished(cmd)
LOG.log(TRACE, "Notified. ")
except Exception as e:
LOG.exception('*** ERROR ***')
exc = e
workers = [Thread(target=fn, args=(planner, )) for t in range(4)]
time_1 = time.time()
for t in workers:
t.start()
for t in workers:
t.join()
time_2 = time.time()
logging.info('Processing time %s', time_2 - time_1)
if exc:
raise exc
self.assertTrue(planner.is_empty(), 'Not all commands were read out')
# Every thread sleeps for 500ms. 40 commands * 0.5 gives 20 seconds if
# the commands executed sequentially
self.assertLess(time_2 - time_1, 19, 'Suspiciously slow')
def test_groups_processed_sequentially_12_threads(self):
planner = WorkPlanner()
group_idx = 0
def ret_values(cmd: BaseMessage) -> bool:
nonlocal group_idx
# We don't care about the group distribution logic
# in this test. Instead, we concentrate how different group
# numbers are processed by the workers and the order
# in which they are allowed to process the messages.
#
# _assign_group is invoked under a lock acquired, so this
# increment is thread-safe.
values = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
ret = bool(values[group_idx])
group_idx += 1
return ret
setattr(planner, '_should_increase_group',
Mock(side_effect=ret_values))
tracker = GroupTracker()
thread_count = 12
for i in range(10):
planner.add_command(entrypoint())
for j in range(thread_count):
planner.add_command(Die())
exc = None
def fn(planner: WorkPlanner):
nonlocal exc
try:
while True:
LOG.log(TRACE, "Requesting for a work")
cmd = planner.get_next_command()
LOG.log(TRACE, "The command is received %s [group=%s]",
type(cmd), cmd.group)
if isinstance(cmd, Die):
LOG.log(TRACE,
"Poison pill is received - exiting. Bye!")
planner.notify_finished(cmd)
break
tracker.log(cmd)
LOG.log(TRACE, "The job is done, notifying the planner")
planner.notify_finished(cmd)
LOG.log(TRACE, "Notified. ")
except Exception as e:
LOG.exception('*** ERROR ***')
exc = e
workers = [
Thread(target=fn, args=(planner, )) for t in range(thread_count)
]
for t in workers:
t.start()
for t in workers:
t.join()
if exc:
raise exc
groups_processed = tracker.get_tracks()
self.assertEqual([0, 1, 1, 2, 2, 3, 3, 4, 4, 5], groups_processed)
def test_groups_processed_sequentially_4_threads(self):
planner = WorkPlanner()
group_idx = 0
def ret_values(cmd: BaseMessage) -> bool:
nonlocal group_idx
# We don't care about the group distribution logic
# in this test. Instead, we concentrate how different group
# numbers are processed by the workers and the order
# in which they are allowed to process the messages.
#
# _assign_group is invoked under a lock acquired, so this
# increment is thread-safe.
values = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
ret = bool(values[group_idx])
group_idx += 1
return ret
setattr(planner, '_should_increase_group',
Mock(side_effect=ret_values))
tracker = GroupTracker()
thread_count = 4
for i in range(10):
planner.add_command(entrypoint())
for j in range(thread_count):
planner.add_command(Die())
exc = None
def fn(planner: WorkPlanner):
nonlocal exc
try:
while True:
LOG.log(TRACE, "Requesting for a work")
cmd = planner.get_next_command()
LOG.log(TRACE, "The command is received %s [group=%s]",
type(cmd), cmd.group)
if isinstance(cmd, Die):
LOG.log(TRACE,
"Poison pill is received - exiting. Bye!")
planner.notify_finished(cmd)
break
tracker.log(cmd)
LOG.log(TRACE, "The job is done, notifying the planner")
planner.notify_finished(cmd)
LOG.log(TRACE, "Notified. ")
except Exception as e:
LOG.exception('*** ERROR ***')
exc = e
workers = [
Thread(target=fn, args=(planner, )) for t in range(thread_count)
]
for t in workers:
t.start()
for t in workers:
t.join()
if exc:
raise exc
groups_processed = tracker.get_tracks()
self.assertEqual([0, 1, 1, 2, 2, 3, 3, 4, 4, 5], groups_processed)
def test_no_hang_when_group_id_cycled(self):
planner = WorkPlanner()
def my_state():
return State(next_group_id=99999,
active_commands=LinkedList(),
taken_commands=LinkedList(),
current_group_id=99999,
next_group_commands=set(),
is_shutdown=False)
planner = WorkPlanner(init_state_factory=my_state)
tracker = GroupTracker()
thread_count = 4
for i in range(10):
planner.add_command(broadcast())
for j in range(thread_count):
planner.add_command(Die())
exc = None
def fn(planner: WorkPlanner):
nonlocal exc
try:
while True:
LOG.log(TRACE, "Requesting for a work")
cmd = planner.get_next_command()
LOG.log(TRACE, "The command is received %s [group=%s]",
type(cmd), cmd.group)
if isinstance(cmd, Die):
LOG.log(TRACE,
"Poison pill is received - exiting. Bye!")
planner.notify_finished(cmd)
break
tracker.log(cmd)
LOG.log(TRACE, "The job is done, notifying the planner")
planner.notify_finished(cmd)
LOG.log(TRACE, "Notified. ")
except Exception as e:
LOG.exception('*** ERROR ***')
exc = e
workers = [
Thread(target=fn, args=(planner, )) for t in range(thread_count)
]
for t in workers:
t.start()
for t in workers:
t.join()
if exc:
raise exc
groups_processed = tracker.get_tracks()
self.assertEqual([99999, 10**5, 0, 1, 2, 3, 4,
5, 6, 7], groups_processed)
| 33.492611 | 78 | 0.538241 |
a3056d3c0122f76cea061b47c7cebd71302eec5c | 248 | py | Python | packages/standard.py | jurikolo/la-intro-to-python | d15299662f71d7defe6ca178a8344e3c4d605654 | [
"Apache-2.0"
] | null | null | null | packages/standard.py | jurikolo/la-intro-to-python | d15299662f71d7defe6ca178a8344e3c4d605654 | [
"Apache-2.0"
] | null | null | null | packages/standard.py | jurikolo/la-intro-to-python | d15299662f71d7defe6ca178a8344e3c4d605654 | [
"Apache-2.0"
] | null | null | null | print("Modules documentation: https://docs.python.org/3/tutorial/modules.html")
print("Standard modules list: https://docs.python.org/3/py-modindex.html")
import math
print(math.pi)
from math import pi
print(pi)
from math import pi as p
print(p) | 22.545455 | 79 | 0.762097 |
a308348c02f7d05a6bdcec5e102eab0f328f25f9 | 1,329 | py | Python | biosimulators_utils/archive/utils.py | virtualcell/Biosimulators_utils | 1b34e1e0a9ace706d245e9d515d0fae1e55a248d | [
"MIT"
] | 2 | 2021-06-02T13:26:34.000Z | 2021-12-27T23:12:47.000Z | biosimulators_utils/archive/utils.py | virtualcell/Biosimulators_utils | 1b34e1e0a9ace706d245e9d515d0fae1e55a248d | [
"MIT"
] | 102 | 2020-12-06T19:47:43.000Z | 2022-03-31T12:56:17.000Z | biosimulators_utils/archive/utils.py | virtualcell/Biosimulators_utils | 1b34e1e0a9ace706d245e9d515d0fae1e55a248d | [
"MIT"
] | 4 | 2021-01-27T19:56:34.000Z | 2022-02-03T21:08:20.000Z | """ Utilities for creating archives
:Author: Jonathan Karr <karr@mssm.edu>
:Date: 2020-12-06
:Copyright: 2020, Center for Reproducible Biomedical Modeling
:License: MIT
"""
from .data_model import Archive, ArchiveFile
import glob
import os
__all__ = ['build_archive_from_paths']
def build_archive_from_paths(path_patterns, rel_path=None, recursive=True):
""" Build an archive from a list of glob path patterns
Args:
path_patterns (:obj:`list` of :obj:`str`): glob path patterns for files to bundle into an archive
rel_path (:obj:`str`, optional): if provided, set the archive file names to their path relative to this path
recursive (:obj:`bool`, optional): if :obj:`True`, match the path patterns recursively
Returns:
:obj:`Archive`: archive
"""
archive = Archive()
for path_pattern in path_patterns:
for local_path in glob.glob(path_pattern, recursive=recursive):
if os.path.isfile(local_path):
if rel_path:
archive_path = os.path.relpath(local_path, rel_path)
else:
archive_path = local_path
archive.files.append(ArchiveFile(
local_path=local_path,
archive_path=archive_path,
))
return archive
| 32.414634 | 116 | 0.645598 |
096461150c75c546d91d335a2584ba96fe70e040 | 845 | py | Python | v1/Commit.py | gzc/gitstats | d6e41c4f7ad5c3d754ef872fa9e615b88df0ccb8 | [
"MIT"
] | 26 | 2017-06-11T05:44:25.000Z | 2021-02-20T12:21:22.000Z | v1/Commit.py | gzc/gitstats | d6e41c4f7ad5c3d754ef872fa9e615b88df0ccb8 | [
"MIT"
] | 1 | 2020-04-22T15:48:19.000Z | 2020-04-22T15:52:51.000Z | v1/Commit.py | gzc/gitstats | d6e41c4f7ad5c3d754ef872fa9e615b88df0ccb8 | [
"MIT"
] | 1 | 2020-10-20T04:46:11.000Z | 2020-10-20T04:46:11.000Z | """
This class represents the info of one commit
"""
from Change import *;
class Commit:
def __init__(self, hash, author, authorEmail, date, commitMessage):
self.hash = hash;
self.author = author;
self.authorEmail = authorEmail
self.date = date;
self.commitMessage = commitMessage;
self.changes = None;
self.linesAdded = 0;
self.linesDeleted = 0;
self.filesAdded = 0;
self.filesDeleted = 0;
def __str__(self):
return ('commit hash {0}\ncommit author {1}\ncommit author email {2}\n'
'commit date {3}\n{4} lines added, {5} lines deleted\n'
'{6} files added, {7} files deleted\n'). \
format(self.hash, self.author, self.authorEmail, self.date,
self.linesAdded, self.linesDeleted, self.filesAdded, self.filesDeleted)
| 31.296296 | 79 | 0.622485 |
0966490b7f876064ed7777de569aec9aeed5aa61 | 3,758 | py | Python | htdocs/plotting/auto/scripts100/p172.py | trentford/iem | 7264d24f2d79a3cd69251a09758e6531233a732f | [
"MIT"
] | null | null | null | htdocs/plotting/auto/scripts100/p172.py | trentford/iem | 7264d24f2d79a3cd69251a09758e6531233a732f | [
"MIT"
] | null | null | null | htdocs/plotting/auto/scripts100/p172.py | trentford/iem | 7264d24f2d79a3cd69251a09758e6531233a732f | [
"MIT"
] | null | null | null | """YTD precip"""
import calendar
import datetime
from pandas.io.sql import read_sql
from pyiem.util import get_autoplot_context, get_dbconn
from pyiem.plot.use_agg import plt
from pyiem.network import Table as NetworkTable
def get_description():
""" Return a dict describing how to call this plotter """
desc = dict()
desc['data'] = True
desc['description'] = """This chart presents year to date accumulated
precipitation for a station of your choice. The year with the highest and
lowest accumulation is shown along with the envelop of observations and
long term average. You can optionally plot up to three additional years
of your choice.
"""
thisyear = datetime.date.today().year
desc['arguments'] = [
dict(type='station', name='station', default='IA2203',
label='Select Station:', network='IACLIMATE'),
dict(type='year', name='year1', default=thisyear,
label='Additional Year to Plot:'),
dict(type='year', name='year2', optional=True, default=(thisyear - 1),
label='Additional Year to Plot: (optional)'),
dict(type='year', name='year3', optional=True, default=(thisyear - 2),
label='Additional Year to Plot: (optional)'),
]
return desc
def plotter(fdict):
""" Go """
pgconn = get_dbconn('coop')
ctx = get_autoplot_context(fdict, get_description())
station = ctx['station']
network = ctx['network']
year1 = ctx.get('year1')
year2 = ctx.get('year2')
year3 = ctx.get('year3')
nt = NetworkTable(network)
table = "alldata_%s" % (station[:2],)
df = read_sql("""
WITH years as (SELECT distinct year from """ + table + """
WHERE station = %s and sday = '0101')
SELECT day, sday, year, precip,
sum(precip) OVER (PARTITION by year ORDER by day ASC) as accum from
""" + table + """ WHERE station = %s and year in (select year from years)
ORDER by day ASC
""", pgconn, params=(station, station), index_col='day')
if df.empty:
raise ValueError("No data found!")
(fig, ax) = plt.subplots(1, 1)
# Average
jday = df[['sday', 'accum']].groupby('sday').mean()
ax.plot(range(1, len(jday.index)+1), jday['accum'], lw=2, zorder=5,
color='k', label='Average - %.2f' % (jday['accum'].iloc[-1],))
# Min and Max
jmin = df[['sday', 'accum']].groupby('sday').min()
jmax = df[['sday', 'accum']].groupby('sday').max()
ax.fill_between(range(1, len(jday.index)+1), jmin['accum'],
jmax['accum'], zorder=2, color='tan')
# find max year
plotted = []
for year, color in zip([df['accum'].idxmax().year,
df[df['sday'] == '1231']['accum'].idxmin().year,
year1, year2, year3],
['b', 'brown', 'r', 'g', 'purple']):
if year is None or year in plotted:
continue
plotted.append(year)
df2 = df[df['year'] == year]
ax.plot(range(1, len(df2.index)+1), df2['accum'],
label='%s - %.2f' % (year, df2['accum'].iloc[-1]),
color=color, lw=2)
ax.set_title(("Year to Date Accumulated Precipitation\n"
"[%s] %s (%s-%s)"
) % (station, nt.sts[station]['name'],
nt.sts[station]['archive_begin'].year,
datetime.date.today().year))
ax.set_ylabel("Precipitation [inch]")
ax.grid(True)
ax.legend(loc=2)
ax.set_xlim(1, 366)
ax.set_xticks((1, 32, 60, 91, 121, 152, 182, 213, 244, 274,
305, 335, 365))
ax.set_xticklabels(calendar.month_abbr[1:])
return fig, df
if __name__ == '__main__':
plotter(dict())
| 37.207921 | 78 | 0.575838 |
096771220ae65d76d59e3b33fcd89cf0b500185d | 21,536 | py | Python | python/istio_api/networking/v1beta1/gateway_pb2.py | luckyxiaoqiang/api | f296986a5b6512d8d5da7b3f16f01f5733f5f32a | [
"Apache-2.0"
] | 1 | 2021-07-19T14:51:15.000Z | 2021-07-19T14:51:15.000Z | python/istio_api/networking/v1beta1/gateway_pb2.py | luckyxiaoqiang/api | f296986a5b6512d8d5da7b3f16f01f5733f5f32a | [
"Apache-2.0"
] | 11 | 2019-10-15T23:03:57.000Z | 2020-06-14T16:10:12.000Z | python/istio_api/networking/v1beta1/gateway_pb2.py | luckyxiaoqiang/api | f296986a5b6512d8d5da7b3f16f01f5733f5f32a | [
"Apache-2.0"
] | 7 | 2019-07-04T14:23:54.000Z | 2020-04-27T08:52:51.000Z | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: networking/v1beta1/gateway.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='networking/v1beta1/gateway.proto',
package='istio.networking.v1beta1',
syntax='proto3',
serialized_options=_b('Z\037istio.io/api/networking/v1beta1'),
serialized_pb=_b('\n networking/v1beta1/gateway.proto\x12\x18istio.networking.v1beta1\x1a\x1fgoogle/api/field_behavior.proto\"\xdb\x01\n\x07Gateway\x12@\n\x07servers\x18\x01 \x03(\x0b\x32 .istio.networking.v1beta1.ServerB\x04\xe2\x41\x01\x02R\x07servers\x12Q\n\x08selector\x18\x02 \x03(\x0b\x32/.istio.networking.v1beta1.Gateway.SelectorEntryB\x04\xe2\x41\x01\x02R\x08selector\x1a;\n\rSelectorEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n\x05value\x18\x02 \x01(\tR\x05value:\x02\x38\x01\"\xf0\x01\n\x06Server\x12\x38\n\x04port\x18\x01 \x01(\x0b\x32\x1e.istio.networking.v1beta1.PortB\x04\xe2\x41\x01\x02R\x04port\x12\x12\n\x04\x62ind\x18\x04 \x01(\tR\x04\x62ind\x12\x1a\n\x05hosts\x18\x02 \x03(\tB\x04\xe2\x41\x01\x02R\x05hosts\x12=\n\x03tls\x18\x03 \x01(\x0b\x32+.istio.networking.v1beta1.ServerTLSSettingsR\x03tls\x12)\n\x10\x64\x65\x66\x61ult_endpoint\x18\x05 \x01(\tR\x0f\x64\x65\x66\x61ultEndpoint\x12\x12\n\x04name\x18\x06 \x01(\tR\x04name\"\x81\x01\n\x04Port\x12\x1c\n\x06number\x18\x01 \x01(\rB\x04\xe2\x41\x01\x02R\x06number\x12 \n\x08protocol\x18\x02 \x01(\tB\x04\xe2\x41\x01\x02R\x08protocol\x12\x18\n\x04name\x18\x03 \x01(\tB\x04\xe2\x41\x01\x02R\x04name\x12\x1f\n\x0btarget_port\x18\x04 \x01(\rR\ntargetPort\"\xe9\x06\n\x11ServerTLSSettings\x12%\n\x0ehttps_redirect\x18\x01 \x01(\x08R\rhttpsRedirect\x12G\n\x04mode\x18\x02 \x01(\x0e\x32\x33.istio.networking.v1beta1.ServerTLSSettings.TLSmodeR\x04mode\x12-\n\x12server_certificate\x18\x03 \x01(\tR\x11serverCertificate\x12\x1f\n\x0bprivate_key\x18\x04 \x01(\tR\nprivateKey\x12\'\n\x0f\x63\x61_certificates\x18\x05 \x01(\tR\x0e\x63\x61\x43\x65rtificates\x12\'\n\x0f\x63redential_name\x18\n \x01(\tR\x0e\x63redentialName\x12*\n\x11subject_alt_names\x18\x06 \x03(\tR\x0fsubjectAltNames\x12\x36\n\x17verify_certificate_spki\x18\x0b \x03(\tR\x15verifyCertificateSpki\x12\x36\n\x17verify_certificate_hash\x18\x0c \x03(\tR\x15verifyCertificateHash\x12i\n\x14min_protocol_version\x18\x07 \x01(\x0e\x32\x37.istio.networking.v1beta1.ServerTLSSettings.TLSProtocolR\x12minProtocolVersion\x12i\n\x14max_protocol_version\x18\x08 \x01(\x0e\x32\x37.istio.networking.v1beta1.ServerTLSSettings.TLSProtocolR\x12maxProtocolVersion\x12#\n\rcipher_suites\x18\t \x03(\tR\x0c\x63ipherSuites\"Z\n\x07TLSmode\x12\x0f\n\x0bPASSTHROUGH\x10\x00\x12\n\n\x06SIMPLE\x10\x01\x12\n\n\x06MUTUAL\x10\x02\x12\x14\n\x10\x41UTO_PASSTHROUGH\x10\x03\x12\x10\n\x0cISTIO_MUTUAL\x10\x04\"O\n\x0bTLSProtocol\x12\x0c\n\x08TLS_AUTO\x10\x00\x12\x0b\n\x07TLSV1_0\x10\x01\x12\x0b\n\x07TLSV1_1\x10\x02\x12\x0b\n\x07TLSV1_2\x10\x03\x12\x0b\n\x07TLSV1_3\x10\x04\x42!Z\x1fistio.io/api/networking/v1beta1b\x06proto3')
,
dependencies=[google_dot_api_dot_field__behavior__pb2.DESCRIPTOR,])
_SERVERTLSSETTINGS_TLSMODE = _descriptor.EnumDescriptor(
name='TLSmode',
full_name='istio.networking.v1beta1.ServerTLSSettings.TLSmode',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='PASSTHROUGH', index=0, number=0,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SIMPLE', index=1, number=1,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='MUTUAL', index=2, number=2,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='AUTO_PASSTHROUGH', index=3, number=3,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='ISTIO_MUTUAL', index=4, number=4,
serialized_options=None,
type=None),
],
containing_type=None,
serialized_options=None,
serialized_start=1395,
serialized_end=1485,
)
_sym_db.RegisterEnumDescriptor(_SERVERTLSSETTINGS_TLSMODE)
_SERVERTLSSETTINGS_TLSPROTOCOL = _descriptor.EnumDescriptor(
name='TLSProtocol',
full_name='istio.networking.v1beta1.ServerTLSSettings.TLSProtocol',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='TLS_AUTO', index=0, number=0,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TLSV1_0', index=1, number=1,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TLSV1_1', index=2, number=2,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TLSV1_2', index=3, number=3,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TLSV1_3', index=4, number=4,
serialized_options=None,
type=None),
],
containing_type=None,
serialized_options=None,
serialized_start=1487,
serialized_end=1566,
)
_sym_db.RegisterEnumDescriptor(_SERVERTLSSETTINGS_TLSPROTOCOL)
_GATEWAY_SELECTORENTRY = _descriptor.Descriptor(
name='SelectorEntry',
full_name='istio.networking.v1beta1.Gateway.SelectorEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='istio.networking.v1beta1.Gateway.SelectorEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, json_name='key', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='value', full_name='istio.networking.v1beta1.Gateway.SelectorEntry.value', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, json_name='value', file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=_b('8\001'),
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=256,
serialized_end=315,
)
_GATEWAY = _descriptor.Descriptor(
name='Gateway',
full_name='istio.networking.v1beta1.Gateway',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='servers', full_name='istio.networking.v1beta1.Gateway.servers', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=_b('\342A\001\002'), json_name='servers', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='selector', full_name='istio.networking.v1beta1.Gateway.selector', index=1,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=_b('\342A\001\002'), json_name='selector', file=DESCRIPTOR),
],
extensions=[
],
nested_types=[_GATEWAY_SELECTORENTRY, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=96,
serialized_end=315,
)
_SERVER = _descriptor.Descriptor(
name='Server',
full_name='istio.networking.v1beta1.Server',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='port', full_name='istio.networking.v1beta1.Server.port', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=_b('\342A\001\002'), json_name='port', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='bind', full_name='istio.networking.v1beta1.Server.bind', index=1,
number=4, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, json_name='bind', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='hosts', full_name='istio.networking.v1beta1.Server.hosts', index=2,
number=2, type=9, cpp_type=9, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=_b('\342A\001\002'), json_name='hosts', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='tls', full_name='istio.networking.v1beta1.Server.tls', index=3,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, json_name='tls', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='default_endpoint', full_name='istio.networking.v1beta1.Server.default_endpoint', index=4,
number=5, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, json_name='defaultEndpoint', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='name', full_name='istio.networking.v1beta1.Server.name', index=5,
number=6, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, json_name='name', file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=318,
serialized_end=558,
)
_PORT = _descriptor.Descriptor(
name='Port',
full_name='istio.networking.v1beta1.Port',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='number', full_name='istio.networking.v1beta1.Port.number', index=0,
number=1, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=_b('\342A\001\002'), json_name='number', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='protocol', full_name='istio.networking.v1beta1.Port.protocol', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=_b('\342A\001\002'), json_name='protocol', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='name', full_name='istio.networking.v1beta1.Port.name', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=_b('\342A\001\002'), json_name='name', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='target_port', full_name='istio.networking.v1beta1.Port.target_port', index=3,
number=4, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, json_name='targetPort', file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=561,
serialized_end=690,
)
_SERVERTLSSETTINGS = _descriptor.Descriptor(
name='ServerTLSSettings',
full_name='istio.networking.v1beta1.ServerTLSSettings',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='https_redirect', full_name='istio.networking.v1beta1.ServerTLSSettings.https_redirect', index=0,
number=1, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, json_name='httpsRedirect', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='mode', full_name='istio.networking.v1beta1.ServerTLSSettings.mode', index=1,
number=2, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, json_name='mode', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='server_certificate', full_name='istio.networking.v1beta1.ServerTLSSettings.server_certificate', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, json_name='serverCertificate', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='private_key', full_name='istio.networking.v1beta1.ServerTLSSettings.private_key', index=3,
number=4, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, json_name='privateKey', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='ca_certificates', full_name='istio.networking.v1beta1.ServerTLSSettings.ca_certificates', index=4,
number=5, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, json_name='caCertificates', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='credential_name', full_name='istio.networking.v1beta1.ServerTLSSettings.credential_name', index=5,
number=10, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, json_name='credentialName', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='subject_alt_names', full_name='istio.networking.v1beta1.ServerTLSSettings.subject_alt_names', index=6,
number=6, type=9, cpp_type=9, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, json_name='subjectAltNames', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='verify_certificate_spki', full_name='istio.networking.v1beta1.ServerTLSSettings.verify_certificate_spki', index=7,
number=11, type=9, cpp_type=9, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, json_name='verifyCertificateSpki', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='verify_certificate_hash', full_name='istio.networking.v1beta1.ServerTLSSettings.verify_certificate_hash', index=8,
number=12, type=9, cpp_type=9, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, json_name='verifyCertificateHash', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='min_protocol_version', full_name='istio.networking.v1beta1.ServerTLSSettings.min_protocol_version', index=9,
number=7, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, json_name='minProtocolVersion', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='max_protocol_version', full_name='istio.networking.v1beta1.ServerTLSSettings.max_protocol_version', index=10,
number=8, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, json_name='maxProtocolVersion', file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='cipher_suites', full_name='istio.networking.v1beta1.ServerTLSSettings.cipher_suites', index=11,
number=9, type=9, cpp_type=9, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, json_name='cipherSuites', file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
_SERVERTLSSETTINGS_TLSMODE,
_SERVERTLSSETTINGS_TLSPROTOCOL,
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=693,
serialized_end=1566,
)
_GATEWAY_SELECTORENTRY.containing_type = _GATEWAY
_GATEWAY.fields_by_name['servers'].message_type = _SERVER
_GATEWAY.fields_by_name['selector'].message_type = _GATEWAY_SELECTORENTRY
_SERVER.fields_by_name['port'].message_type = _PORT
_SERVER.fields_by_name['tls'].message_type = _SERVERTLSSETTINGS
_SERVERTLSSETTINGS.fields_by_name['mode'].enum_type = _SERVERTLSSETTINGS_TLSMODE
_SERVERTLSSETTINGS.fields_by_name['min_protocol_version'].enum_type = _SERVERTLSSETTINGS_TLSPROTOCOL
_SERVERTLSSETTINGS.fields_by_name['max_protocol_version'].enum_type = _SERVERTLSSETTINGS_TLSPROTOCOL
_SERVERTLSSETTINGS_TLSMODE.containing_type = _SERVERTLSSETTINGS
_SERVERTLSSETTINGS_TLSPROTOCOL.containing_type = _SERVERTLSSETTINGS
DESCRIPTOR.message_types_by_name['Gateway'] = _GATEWAY
DESCRIPTOR.message_types_by_name['Server'] = _SERVER
DESCRIPTOR.message_types_by_name['Port'] = _PORT
DESCRIPTOR.message_types_by_name['ServerTLSSettings'] = _SERVERTLSSETTINGS
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
Gateway = _reflection.GeneratedProtocolMessageType('Gateway', (_message.Message,), {
'SelectorEntry' : _reflection.GeneratedProtocolMessageType('SelectorEntry', (_message.Message,), {
'DESCRIPTOR' : _GATEWAY_SELECTORENTRY,
'__module__' : 'networking.v1beta1.gateway_pb2'
# @@protoc_insertion_point(class_scope:istio.networking.v1beta1.Gateway.SelectorEntry)
})
,
'DESCRIPTOR' : _GATEWAY,
'__module__' : 'networking.v1beta1.gateway_pb2'
# @@protoc_insertion_point(class_scope:istio.networking.v1beta1.Gateway)
})
_sym_db.RegisterMessage(Gateway)
_sym_db.RegisterMessage(Gateway.SelectorEntry)
Server = _reflection.GeneratedProtocolMessageType('Server', (_message.Message,), {
'DESCRIPTOR' : _SERVER,
'__module__' : 'networking.v1beta1.gateway_pb2'
# @@protoc_insertion_point(class_scope:istio.networking.v1beta1.Server)
})
_sym_db.RegisterMessage(Server)
Port = _reflection.GeneratedProtocolMessageType('Port', (_message.Message,), {
'DESCRIPTOR' : _PORT,
'__module__' : 'networking.v1beta1.gateway_pb2'
# @@protoc_insertion_point(class_scope:istio.networking.v1beta1.Port)
})
_sym_db.RegisterMessage(Port)
ServerTLSSettings = _reflection.GeneratedProtocolMessageType('ServerTLSSettings', (_message.Message,), {
'DESCRIPTOR' : _SERVERTLSSETTINGS,
'__module__' : 'networking.v1beta1.gateway_pb2'
# @@protoc_insertion_point(class_scope:istio.networking.v1beta1.ServerTLSSettings)
})
_sym_db.RegisterMessage(ServerTLSSettings)
DESCRIPTOR._options = None
_GATEWAY_SELECTORENTRY._options = None
_GATEWAY.fields_by_name['servers']._options = None
_GATEWAY.fields_by_name['selector']._options = None
_SERVER.fields_by_name['port']._options = None
_SERVER.fields_by_name['hosts']._options = None
_PORT.fields_by_name['number']._options = None
_PORT.fields_by_name['protocol']._options = None
_PORT.fields_by_name['name']._options = None
# @@protoc_insertion_point(module_scope)
| 46.413793 | 2,637 | 0.751997 |
096a5172854a6f7ee1cbbe59f19ac4a86d87ac0c | 1,684 | py | Python | Steganalysis-CNN/dataload.py | 1129ljc/video-interpolation-detection | eb2931269b2ac19af28de750f0b719fb0d66aaef | [
"Apache-2.0"
] | 2 | 2022-03-29T06:46:21.000Z | 2022-03-30T09:13:10.000Z | Steganalysis-CNN/dataload.py | 1129ljc/video-interpolation-detection | eb2931269b2ac19af28de750f0b719fb0d66aaef | [
"Apache-2.0"
] | null | null | null | Steganalysis-CNN/dataload.py | 1129ljc/video-interpolation-detection | eb2931269b2ac19af28de750f0b719fb0d66aaef | [
"Apache-2.0"
] | null | null | null | '''
@Time : 2021/9/3 9:42
@Author : ljc
@FileName: dataload.py
@Software: PyCharm
'''
import os
import json
import cv2
import numpy as np
import torch
from PIL import Image
from torchvision import transforms
from torch.utils.data import DataLoader
from torch.utils.data import Dataset
transform = transforms.Compose(
[
# transforms.Resize(size=(224, 224)),
transforms.ToTensor(),
# transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
]
)
class DataSet(Dataset):
def __init__(self, data_file_path):
super(Dataset, self).__init__()
self.json_file_path = data_file_path
assert os.path.isfile(data_file_path), print('The dataset json file cannot be read')
with open(data_file_path, 'r', encoding='utf8')as fp:
data = fp.readlines()
self.image_path_list = []
self.image_label_list = []
for i in range(len(data)):
line = data[i].split(' ')
self.image_path_list.append(line[0])
self.image_label_list.append(int(line[1][0:-1]))
self.image_num = len(self.image_path_list)
def __len__(self):
return self.image_num
def __getitem__(self, item):
image_file = self.image_path_list[item]
label = self.image_label_list[item]
label_torch = torch.tensor(label)
# image_torch = transform(Image.open(image_file).convert('RGB'))
image_torch = torch.from_numpy(np.array(Image.open(image_file).convert('RGB')))
image_torch = image_torch.permute(2, 0, 1).float()
image_torch = torch.unsqueeze(image_torch[0, :, :], dim=0)
return image_file, image_torch, label_torch
| 30.618182 | 92 | 0.647862 |
096a75b1219f50f0c996c46826203e3429895949 | 15,833 | py | Python | model.py | lei-wang-github/unet | 1dcf41a2956b58358f14e00c0df4daf366d272b8 | [
"MIT"
] | null | null | null | model.py | lei-wang-github/unet | 1dcf41a2956b58358f14e00c0df4daf366d272b8 | [
"MIT"
] | null | null | null | model.py | lei-wang-github/unet | 1dcf41a2956b58358f14e00c0df4daf366d272b8 | [
"MIT"
] | null | null | null | import numpy as np
import os
import skimage.io as io
import skimage.transform as trans
import numpy as np
from tensorflow.keras.models import *
from tensorflow.keras.layers import *
from tensorflow.keras.optimizers import *
from tensorflow.keras.callbacks import ModelCheckpoint, LearningRateScheduler
from keras import backend as keras
import math
import configparser
config = configparser.ConfigParser()
config.read('configuration.txt')
img_height = int(config['data attributes']['image_height'])
img_width = int(config['data attributes']['image_width'])
model_reduction_ratio = int(config['model type']['modelReductionRatio'])
learningRate = float(config['training settings']['learningRate'])
def unet_original(pretrained_weights = None,input_size = (img_height,img_width,1)):
inputs = Input(input_size)
conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs)
conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv1)
pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)
conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool1)
conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv2)
pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)
conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool2)
conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv3)
pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)
conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool3)
conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv4)
drop4 = Dropout(0.5)(conv4)
pool4 = MaxPooling2D(pool_size=(2, 2))(drop4)
conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool4)
conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv5)
drop5 = Dropout(0.5)(conv5)
up6 = Conv2D(512, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(drop5))
merge6 = concatenate([drop4,up6], axis = 3)
conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge6)
conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv6)
up7 = Conv2D(256, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv6))
merge7 = concatenate([conv3,up7], axis = 3)
conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge7)
conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv7)
up8 = Conv2D(128, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv7))
merge8 = concatenate([conv2,up8], axis = 3)
conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge8)
conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv8)
up9 = Conv2D(64, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv8))
merge9 = concatenate([conv1,up9], axis = 3)
conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge9)
conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)
conv9 = Conv2D(2, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)
conv10 = Conv2D(1, 1, activation = 'sigmoid')(conv9)
model = Model(inputs = inputs, outputs = conv10)
model.compile(optimizer = Adam(lr = learningRate), loss = 'binary_crossentropy', metrics = ['accuracy'])
model.summary()
if(pretrained_weights):
model.load_weights(pretrained_weights)
return model
def unet(pretrained_weights=None, input_size=(img_height, img_width, 1)):
reduction_ratio = model_reduction_ratio
inputs = Input(input_size)
conv1 = Conv2D(int(math.ceil(64/reduction_ratio)), 3, activation='relu', padding='same', kernel_initializer='he_normal')(inputs)
conv1 = Conv2D(int(math.ceil(64/reduction_ratio)), 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv1)
pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)
conv2 = Conv2D(int(math.ceil(128/reduction_ratio)), 3, activation='relu', padding='same', kernel_initializer='he_normal')(pool1)
conv2 = Conv2D(int(math.ceil(128/reduction_ratio)), 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv2)
pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)
conv3 = Conv2D(int(math.ceil(256/reduction_ratio)), 3, activation='relu', padding='same', kernel_initializer='he_normal')(pool2)
conv3 = Conv2D(int(math.ceil(256/reduction_ratio)), 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv3)
pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)
conv4 = Conv2D(int(math.ceil(512/reduction_ratio)), 3, activation='relu', padding='same', kernel_initializer='he_normal')(pool3)
conv4 = Conv2D(int(math.ceil(512/reduction_ratio)), 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv4)
drop4 = Dropout(0.5)(conv4)
pool4 = MaxPooling2D(pool_size=(2, 2))(drop4)
conv5 = Conv2D(int(math.ceil(1024/reduction_ratio)), 3, activation='relu', padding='same', kernel_initializer='he_normal')(pool4)
conv5 = Conv2D(int(math.ceil(1024/reduction_ratio)), 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv5)
drop5 = Dropout(0.5)(conv5)
up6 = Conv2D(int(math.ceil(512/reduction_ratio)), 2, activation='relu', padding='same', kernel_initializer='he_normal')(UpSampling2D(size=(2, 2))(drop5))
merge6 = concatenate([drop4, up6], axis=3)
conv6 = Conv2D(int(math.ceil(512/reduction_ratio)), 3, activation='relu', padding='same', kernel_initializer='he_normal')(merge6)
conv6 = Conv2D(int(math.ceil(512/reduction_ratio)), 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv6)
up7 = Conv2D(int(math.ceil(256/reduction_ratio)), 2, activation='relu', padding='same', kernel_initializer='he_normal')(
UpSampling2D(size=(2, 2))(conv6))
merge7 = concatenate([conv3, up7], axis=3)
conv7 = Conv2D(int(math.ceil(256/reduction_ratio)), 3, activation='relu', padding='same', kernel_initializer='he_normal')(merge7)
conv7 = Conv2D(int(math.ceil(256/reduction_ratio)), 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv7)
up8 = Conv2D(int(math.ceil(128/reduction_ratio)), 2, activation='relu', padding='same', kernel_initializer='he_normal')(UpSampling2D(size=(2, 2))(conv7))
merge8 = concatenate([conv2, up8], axis=3)
conv8 = Conv2D(int(math.ceil(128/reduction_ratio)), 3, activation='relu', padding='same', kernel_initializer='he_normal')(merge8)
conv8 = Conv2D(int(math.ceil(128/reduction_ratio)), 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv8)
up9 = Conv2D(int(math.ceil(64/reduction_ratio)), 2, activation='relu', padding='same', kernel_initializer='he_normal')(
UpSampling2D(size=(2, 2))(conv8))
merge9 = concatenate([conv1, up9], axis=3)
conv9 = Conv2D(int(math.ceil(64/reduction_ratio)), 3, activation='relu', padding='same', kernel_initializer='he_normal')(merge9)
conv9 = Conv2D(int(math.ceil(64/reduction_ratio)), 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv9)
conv9 = Conv2D(2, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv9)
conv10 = Conv2D(1, 1, activation='sigmoid')(conv9)
model = Model(inputs=inputs, outputs=conv10)
# model.compile(optimizer=Adam(lr=1e-4), loss='binary_crossentropy', metrics=['accuracy'])
model.compile(optimizer=Adam(lr=learningRate), loss='binary_crossentropy', metrics=['accuracy'])
model.summary()
if (pretrained_weights):
model.load_weights(pretrained_weights)
return model
def unet_sepconv(pretrained_weights=None, input_size=(img_height, img_width, 1)):
reduction_ratio = model_reduction_ratio
inputs = Input(input_size)
conv1 = SeparableConv2D(int(64/reduction_ratio), 3, activation='relu', padding='same', depthwise_initializer='he_normal', pointwise_initializer='he_normal')(inputs)
conv1 = SeparableConv2D(int(64 / reduction_ratio), 3, activation='relu', padding='same', depthwise_initializer='he_normal', pointwise_initializer='he_normal')(conv1)
pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)
conv2 = SeparableConv2D(int(128/reduction_ratio), 3, activation='relu', padding='same', depthwise_initializer='he_normal', pointwise_initializer='he_normal')(pool1)
conv2 = SeparableConv2D(int(128/reduction_ratio), 3, activation='relu', padding='same', depthwise_initializer='he_normal', pointwise_initializer='he_normal')(conv2)
pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)
conv3 = SeparableConv2D(int(256/reduction_ratio), 3, activation='relu', padding='same', depthwise_initializer='he_normal', pointwise_initializer='he_normal')(pool2)
conv3 = SeparableConv2D(int(256/reduction_ratio), 3, activation='relu', padding='same', depthwise_initializer='he_normal', pointwise_initializer='he_normal')(conv3)
pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)
conv4 = SeparableConv2D(int(512/reduction_ratio), 3, activation='relu', padding='same', depthwise_initializer='he_normal', pointwise_initializer='he_normal')(pool3)
conv4 = SeparableConv2D(int(512/reduction_ratio), 3, activation='relu', padding='same', depthwise_initializer='he_normal', pointwise_initializer='he_normal')(conv4)
drop4 = Dropout(0.5)(conv4)
pool4 = MaxPooling2D(pool_size=(2, 2))(drop4)
conv5 = SeparableConv2D(int(1024/reduction_ratio), 3, activation='relu', padding='same', depthwise_initializer='he_normal', pointwise_initializer='he_normal')(pool4)
conv5 = SeparableConv2D(int(1024/reduction_ratio), 3, activation='relu', padding='same', depthwise_initializer='he_normal', pointwise_initializer='he_normal')(conv5)
drop5 = Dropout(0.5)(conv5)
up6 = SeparableConv2D(int(512/reduction_ratio), 2, activation='relu', padding='same', depthwise_initializer='he_normal', pointwise_initializer='he_normal')(
UpSampling2D(size=(2, 2))(drop5))
merge6 = concatenate([drop4, up6], axis=3)
conv6 = SeparableConv2D(int(512/reduction_ratio), 3, activation='relu', padding='same', depthwise_initializer='he_normal', pointwise_initializer='he_normal')(merge6)
conv6 = SeparableConv2D(int(512/reduction_ratio), 3, activation='relu', padding='same', depthwise_initializer='he_normal', pointwise_initializer='he_normal')(conv6)
up7 = SeparableConv2D(int(256/reduction_ratio), 2, activation='relu', padding='same', depthwise_initializer='he_normal', pointwise_initializer='he_normal')(
UpSampling2D(size=(2, 2))(conv6))
merge7 = concatenate([conv3, up7], axis=3)
conv7 = SeparableConv2D(int(256/reduction_ratio), 3, activation='relu', padding='same', depthwise_initializer='he_normal', pointwise_initializer='he_normal')(merge7)
conv7 = SeparableConv2D(int(256/reduction_ratio), 3, activation='relu', padding='same', depthwise_initializer='he_normal', pointwise_initializer='he_normal')(conv7)
up8 = SeparableConv2D(int(128/reduction_ratio), 2, activation='relu', padding='same', depthwise_initializer='he_normal', pointwise_initializer='he_normal')(
UpSampling2D(size=(2, 2))(conv7))
merge8 = concatenate([conv2, up8], axis=3)
conv8 = SeparableConv2D(int(128/reduction_ratio), 3, activation='relu', padding='same', depthwise_initializer='he_normal', pointwise_initializer='he_normal')(merge8)
conv8 = SeparableConv2D(int(128/reduction_ratio), 3, activation='relu', padding='same', depthwise_initializer='he_normal', pointwise_initializer='he_normal')(conv8)
up9 = SeparableConv2D(int(64/reduction_ratio), 2, activation='relu', padding='same', depthwise_initializer='he_normal', pointwise_initializer='he_normal')(
UpSampling2D(size=(2, 2))(conv8))
merge9 = concatenate([conv1, up9], axis=3)
conv9 = SeparableConv2D(int(64/reduction_ratio), 3, activation='relu', padding='same', depthwise_initializer='he_normal', pointwise_initializer='he_normal')(merge9)
conv9 = SeparableConv2D(int(64/reduction_ratio), 3, activation='relu', padding='same', depthwise_initializer='he_normal', pointwise_initializer='he_normal')(conv9)
conv9 = SeparableConv2D(2, 3, activation='relu', padding='same', depthwise_initializer='he_normal', pointwise_initializer='he_normal')(conv9)
conv10 = SeparableConv2D(1, 1, activation='sigmoid')(conv9)
model = Model(inputs=inputs, outputs=conv10)
# model.compile(optimizer=Adam(lr=1e-4), loss='binary_crossentropy', metrics=['accuracy'])
model.compile(optimizer=Adam(lr=learningRate), loss='binary_crossentropy', metrics=['accuracy'])
model.summary()
if (pretrained_weights):
model.load_weights(pretrained_weights)
return model
# https://github.com/orobix/retina-unet/blob/master/src/retinaNN_training.py
def unetSmall (n_ch=1,patch_height=img_height,patch_width=img_width):
inputs = Input(shape=(patch_height,patch_width, n_ch))
reduction_ratio = model_reduction_ratio
conv1 = Conv2D(int(math.ceil(32/reduction_ratio)), (3, 3), activation='relu', padding='same', kernel_initializer='he_normal')(inputs)
conv1 = Dropout(0.2)(conv1)
conv1 = Conv2D(int(math.ceil(32/reduction_ratio)), (3, 3), activation='relu', padding='same', kernel_initializer='he_normal')(conv1)
pool1 = MaxPooling2D((2, 2))(conv1)
#
conv2 = Conv2D(int(math.ceil(64/reduction_ratio)), (3, 3), activation='relu', padding='same', kernel_initializer='he_normal')(pool1)
conv2 = Dropout(0.2)(conv2)
conv2 = Conv2D(int(math.ceil(64/reduction_ratio)), (3, 3), activation='relu', padding='same', kernel_initializer='he_normal')(conv2)
pool2 = MaxPooling2D((2, 2))(conv2)
#
conv3 = Conv2D(int(math.ceil(128/reduction_ratio)), (3, 3), activation='relu', padding='same', kernel_initializer='he_normal')(pool2)
conv3 = Dropout(0.2)(conv3)
conv3 = Conv2D(int(math.ceil(128/reduction_ratio)), (3, 3), activation='relu', padding='same', kernel_initializer='he_normal')(conv3)
up1 = UpSampling2D(size=(2, 2))(conv3)
up1 = concatenate([conv2,up1],axis=3)
conv4 = Conv2D(int(math.ceil(64/reduction_ratio)), (3, 3), activation='relu', padding='same', kernel_initializer='he_normal')(up1)
conv4 = Dropout(0.2)(conv4)
conv4 = Conv2D(int(math.ceil(64/reduction_ratio)), (3, 3), activation='relu', padding='same', kernel_initializer='he_normal')(conv4)
#
up2 = UpSampling2D(size=(2, 2))(conv4)
up2 = concatenate([conv1,up2], axis=3)
conv5 = Conv2D(int(math.ceil(32/reduction_ratio)), (3, 3), activation='relu', padding='same', kernel_initializer='he_normal')(up2)
conv5 = Dropout(0.2)(conv5)
conv5 = Conv2D(int(math.ceil(32/reduction_ratio)), (3, 3), activation='relu', padding='same', kernel_initializer='he_normal')(conv5)
#
conv6 = Conv2D(2, (1, 1), activation='relu',padding='same', kernel_initializer='he_normal')(conv5)
conv7 = Conv2D(1, 1, activation='sigmoid', kernel_initializer='he_normal')(conv6)
model = Model(inputs=inputs, outputs=conv7)
model.compile(optimizer=Adam(lr=learningRate), loss='binary_crossentropy', metrics=['accuracy'])
model.summary()
return model
| 68.541126 | 169 | 0.718373 |
096b3b878c08f6ba21432355cfef1328654cf1dc | 23,998 | py | Python | run.py | kampta/PatchVAE | 816f4b49fd8b836641d7e1068c1e802ae0453742 | [
"MIT"
] | 9 | 2020-10-29T11:56:53.000Z | 2021-11-21T14:34:38.000Z | run.py | kampta/PatchVAE | 816f4b49fd8b836641d7e1068c1e802ae0453742 | [
"MIT"
] | null | null | null | run.py | kampta/PatchVAE | 816f4b49fd8b836641d7e1068c1e802ae0453742 | [
"MIT"
] | 2 | 2020-10-29T03:40:31.000Z | 2021-01-31T20:04:49.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" run.py
Code to run the PatchVAE on different datasets
Usage:
# Run with default arguments on mnist
python run.py
Basic VAE borrowed from
https://github.com/pytorch/examples/tree/master/vae
"""
__author__ = "Kamal Gupta"
__email__ = "kampta@cs.umd.edu"
__version__ = "0.1"
import sys
from collections import OrderedDict
import shutil
import numpy as np
import torch
import torch.nn as nn
from torchvision.utils import make_grid
from utils import Timer
from utils.torchsummary import summary
from utils.commons import data_loaders, load_vae_model, count_parameters, EdgeWeights
from loss import BetaVaeLoss, VaeConcreteLoss, BetaVaeConcreteLoss,\
BetaVaeConcretePartsLoss, BetaVaeConcretePartsEntropyLoss, DiscLoss
from model import Discriminator
import utils.commons as commons
from torch.utils.tensorboard import SummaryWriter
def train_vaegan(data_loader, model_d, model_v, opt_d, opt_v, d_loss_fn, v_loss_fn, writer):
model_v.train()
model_d.train()
fwd_clock = Timer()
bwd_clock = Timer()
num_batches = args.img_per_epoch // args.batch_size
data_iterator = iter(data_loader)
overall_losses = OrderedDict()
# for batch_idx, (x, _) in enumerate(data_loader):
for batch_idx in range(num_batches):
batch_losses = OrderedDict()
try:
x, _ = next(data_iterator)
except StopIteration:
data_iterator = iter(data_loader)
continue
x = x.to(args.device)
########################################################
# (1) Update D network: maximize log(D(x)) + log(1 - D(G(z)))
#######################################################
# train with real
model_d.zero_grad()
real_x = x
real_y = torch.ones(x.size(0)).cuda()
outputs = model_d(real_x)
err_d_real = d_loss_fn(outputs.squeeze(), real_y.squeeze())
err_d_real.backward()
batch_losses['err_d_real'] = err_d_real.item()
batch_losses['d_x'] = outputs.data.mean()
# train with fake
fake_y = torch.zeros(x.size(0)).cuda()
x_tilde, z_app_mean, z_app_var, z_vis_mean = model_v(x, args.temp)
# recon_x, _ = x_tilde
outputs = model_d(x_tilde.detach())
err_d_fake = d_loss_fn(outputs.squeeze(), fake_y.squeeze())
err_d_fake.backward()
batch_losses['err_d_fake'] = err_d_fake.item()
batch_losses['d_v1'] = outputs.data.mean()
opt_d.step()
###########################
# (2) Update G network: VAE
###########################
model_v.zero_grad()
loss, loss_dict = v_loss_fn(
x_tilde, x, z_app_mean, z_app_var, z_vis_mean,
categorical=args.categorical, py=args.py, beta_p=args.beta_p,
beta_a=args.beta_a, beta_v=args.beta_v,
beta_ea=args.beta_ea, beta_ew=args.beta_ew
)
loss.backward()
for loss_key, loss_value in loss_dict.items():
batch_losses[loss_key] = loss_value.item()
opt_v.step()
############################
# (3) Update G network: maximize log(D(G(z)))
###########################
x_tilde, z_app_mean, z_app_var, z_vis_mean = model_v(x, args.temp)
# recon_x, _ = x_tilde
outputs = model_d(x_tilde)
real_y.fill_(1)
err_g = d_loss_fn(outputs.squeeze(), real_y.squeeze())
err_g.backward()
batch_losses['err_g'] = err_g.item()
batch_losses['d_v2'] = outputs.data.mean()
opt_v.step()
# Logs
for loss_key, loss_value in batch_losses.items():
writer.add_scalar('loss/train/' + loss_key, loss_value, args.steps)
overall_losses[loss_key] = overall_losses[loss_key] + loss_value \
if loss_key in overall_losses else loss_value
args.steps += 1
if args.steps % 1000 == 1:
args.temp = max(args.temp * np.exp(-args.anneal * args.steps),
args.min_temp)
if batch_idx % args.log_interval != 0:
continue
logstr = '\t'.join(['{}: {:0.4f}'.format(k, v) for k, v in batch_losses.items()])
print('[{}/{} ({:0.0f}%)]\t{}'.format(batch_idx, num_batches,
100. * batch_idx / num_batches, logstr))
overall_losses = OrderedDict([(k, v / num_batches) for k, v in overall_losses.items()])
logstr = '\t'.join(['{}: {:0.4f}'.format(k, v) for k, v in overall_losses.items()])
print('[End of train epoch]\t# steps: {}\t# images: {}, temp: {:0.2f}'.format(
args.steps, num_batches * args.batch_size, args.temp))
print(logstr)
print('[End of train epoch]\t# calls: {}, Fwd: {:.3f} ms\tBwd: {:.3f} ms'.format(
fwd_clock.calls, 1000 * fwd_clock.average_time, 1000 * bwd_clock.average_time))
return overall_losses
def train(data_loader, model, optimizer, loss_function, writer):
model.train()
fwd_clock = Timer()
bwd_clock = Timer()
losses = OrderedDict()
losses['loss'] = 0
num_batches = args.img_per_epoch // args.batch_size
data_iterator = iter(data_loader)
for batch_idx in range(num_batches):
try:
x, _ = next(data_iterator)
x = x.to(args.device)
optimizer.zero_grad()
# Forward Pass
fwd_clock.tic()
x_tilde, z_app_mean, z_app_var, z_vis_mean = model(x, args.temp)
# Compute Loss
loss, loss_dict = loss_function(
x_tilde, x, z_app_mean, z_app_var, z_vis_mean,
categorical=args.categorical, py=args.py, beta_p=args.beta_p,
beta_a=args.beta_a, beta_v=args.beta_v,
beta_ea=args.beta_ea, beta_ew=args.beta_ew
)
fwd_clock.toc()
# Backprop
bwd_clock.tic()
loss.backward()
bwd_clock.toc()
# Update Adam
optimizer.step()
# Logs
losses['loss'] += loss.item()
writer.add_scalar('loss/train/loss', loss.item(), args.steps)
for loss_key, loss_value in loss_dict.items():
writer.add_scalar('loss/train/' + loss_key, loss_value.item(), args.steps)
losses[loss_key] = losses[loss_key] + loss_value.item() \
if loss_key in losses else loss_value.item()
args.steps += 1
if args.steps % 1000 == 1:
args.temp = max(args.temp * np.exp(-args.anneal * args.steps),
args.min_temp)
if batch_idx % args.log_interval != 0:
continue
logstr = '\t'.join(['{}: {:0.4f}'.format(k, v.item()) for k, v in loss_dict.items()])
print('[{}/{} ({:0.0f}%)]\t{}'.format(batch_idx, num_batches,
100. * batch_idx / num_batches, logstr))
except StopIteration:
data_iterator = iter(data_loader)
losses = OrderedDict([(k, v / num_batches) for k, v in losses.items()])
logstr = '\t'.join(['{}: {:0.4f}'.format(k, v) for k, v in losses.items()])
print('[End of train epoch]\t# steps: {}\t# images: {}, temp: {:0.2f}'.format(
args.steps, num_batches * args.batch_size, args.temp))
print(logstr)
print('[End of train epoch]\t# calls: {}, Fwd: {:.3f} ms\tBwd: {:.3f} ms'.format(
fwd_clock.calls, 1000 * fwd_clock.average_time, 1000 * bwd_clock.average_time))
return losses['loss']
def test(data_loader, model, loss_function, writer):
model.eval()
losses = OrderedDict()
losses['loss'] = 0
data_iterator = iter(data_loader)
with torch.no_grad():
for batch_idx, (x, _) in enumerate(data_iterator):
x = x.to(args.device)
x_tilde, z_app_mean, z_app_var, z_vis_mean = model(x, args.temp)
loss, loss_dict = loss_function(
x_tilde, x, z_app_mean, z_app_var, z_vis_mean,
categorical=args.categorical, py=args.py, beta_p=args.beta_p,
beta_a=args.beta_a, beta_v=args.beta_v,
beta_ea=args.beta_ea, beta_ew=args.beta_ew
)
losses['loss'] += loss.item()
for loss_key, loss_value in loss_dict.items():
losses[loss_key] = losses[loss_key] + loss_value.item() \
if loss_key in losses else loss_value.item()
losses = OrderedDict([(k, v / (batch_idx+1)) for k, v in losses.items()])
logstr = '\t'.join(['{}: {:0.4f}'.format(k, v) for k, v in losses.items()])
print('[End of test epoch]')
print(logstr)
# Logs
for loss_key, loss_value in losses.items():
writer.add_scalar('loss/test/' + loss_key, loss_value, args.steps)
return losses['loss']
def plot_graph(height, width, channels, model, writer):
fake = torch.from_numpy(np.random.randn(args.batch_size,
channels, height, width).astype(np.float32))
fake = fake.to(args.device)
writer.add_graph(model, fake)
def main():
np.random.seed(args.seed)
torch.manual_seed(args.seed)
args.steps = 0
writer = SummaryWriter(args.log_dir)
save_filename = args.model_dir
train_loader, test_loader, (channels, height, width), num_classes, _ = \
data_loaders(args.dataset, data_folder=args.data_folder,
classify=False, size=args.size, inet=args.inet,
batch_size=args.batch_size, num_workers=args.workers)
# Fixed images for Tensorboard
fixed_images, _ = next(iter(test_loader))
fixed_images = fixed_images.to(args.device)
fixed_grid = make_grid(commons.unnorm(fixed_images).cpu().data, nrow=32, pad_value=1)
writer.add_image('original', fixed_grid, 0)
# build a VAE model
vae_model, _ = load_vae_model((channels, height, width),
args.arch,
encoder_arch=args.encoder_arch,
decoder_arch=args.decoder_arch,
hidden_size=args.hidden_size,
num_parts=args.num_parts,
base_depth=args.ngf,
independent=args.independent,
hard=args.hard,
categorical=args.categorical,
scale=args.scale,
device=args.device)
args.py = 1 / args.num_parts if args.py is None else args.py
if torch.cuda.device_count() > 1:
print("Let's use", torch.cuda.device_count(), "GPUs!")
# dim = 0 [30, xxx] -> [10, ...], [10, ...], [10, ...] on 3 GPUs
vae_model = nn.DataParallel(vae_model)
vae_model.to(args.device)
if args.pretrained is not None:
print("Loading pretrained model from %s" % args.pretrained)
pretrained_dict = torch.load(args.pretrained, map_location=args.device)
if type(pretrained_dict) == OrderedDict:
vae_model.load_state_dict(pretrained_dict)
elif 'vae_dict' in pretrained_dict:
vae_model.load_state_dict(pretrained_dict['vae_dict'])
else:
print('debug')
sys.exit(0)
# Generate samples only, no training
if args.evaluate:
with torch.no_grad():
# Reconstructions after current epoch
if torch.cuda.device_count() > 1:
reconstructions = vae_model.module.get_reconstructions(
fixed_images, temp=args.temp)
else:
reconstructions = vae_model.get_reconstructions(
fixed_images, temp=args.temp)
for key in reconstructions:
grid = make_grid(reconstructions[key].cpu(), nrow=32, pad_value=1)
writer.add_image(key, grid, 0)
# Random samples after current epoch
if torch.cuda.device_count() > 1:
random_samples = vae_model.module.get_random_samples(py=args.py)
else:
random_samples = vae_model.get_random_samples(py=args.py)
for key in random_samples:
grid = make_grid(random_samples[key].cpu(), nrow=32, pad_value=1)
writer.add_image(key, grid, 0)
sys.exit(0)
opt_v = torch.optim.Adam(vae_model.parameters(), lr=args.lr, betas=(0.5, 0.999))
recon_mask = None
if args.recon_mask == 'edge':
recon_mask = EdgeWeights(nc=channels, scale=args.scale)
if args.arch == 'vae':
loss_function = BetaVaeLoss(beta=args.beta_a, mask_nn=recon_mask)
elif args.arch == 'convvae':
loss_function = VaeConcreteLoss(
beta_v=args.beta_v,
py=args.py,
categorical=args.categorical,
mask_nn=recon_mask
)
elif args.arch == 'patchy':
if args.beta_p == 0. and args.beta_ea == 0. and args.beta_ew == 0.:
loss_function = BetaVaeConcreteLoss(
beta_a=args.beta_a,
beta_v=args.beta_v,
py=args.py,
categorical=args.categorical,
mask_nn=recon_mask
)
elif args.beta_ea == 0. and args.beta_ew == 0.:
loss_function = BetaVaeConcretePartsLoss(
beta_a=args.beta_a,
beta_v=args.beta_v,
beta_p=args.beta_p,
py=args.py,
categorical=args.categorical,
)
else:
loss_function = BetaVaeConcretePartsEntropyLoss(
beta_a=args.beta_a,
beta_v=args.beta_v,
beta_p=args.beta_p,
beta_ea=args.beta_ea,
beta_ew=args.beta_ew,
py=args.py,
categorical=args.categorical,
)
else:
print('Unknown model architecture: %s' % args.arch)
sys.exit(0)
if args.gan:
gan_model = Discriminator(height, nc=channels, ndf=args.ndf, scale=args.scale).to(args.device)
opt_d = torch.optim.Adam(gan_model.parameters(), lr=args.lr, betas=(0.5, 0.999))
d_loss_fn = DiscLoss(args.beta_g)
# test after seeing approx. every 50000 images
# num_epochs = (args.num_epochs * len(train_loader.dataset)) // 50000
for epoch in range(1, args.num_epochs + 1):
print("================== Epoch: {} ==================".format(epoch))
if args.gan:
train_loss = train_vaegan(train_loader, gan_model, vae_model, opt_d, opt_v, d_loss_fn, loss_function, writer)
else:
train_loss = train(train_loader, vae_model, opt_v, loss_function, writer)
test_loss = test(test_loader, vae_model, loss_function, writer)
if epoch == 1:
best_loss = test_loss
if epoch % args.save_interval != 0:
continue
# Save model
with torch.no_grad():
# Reconstructions after current epoch
if torch.cuda.device_count() > 1:
reconstructions = vae_model.module.get_reconstructions(
fixed_images, temp=args.temp)
else:
reconstructions = vae_model.get_reconstructions(
fixed_images, temp=args.temp)
for key in reconstructions:
grid = make_grid(reconstructions[key].cpu(), nrow=32, pad_value=1, normalize=True)
writer.add_image(key, grid, epoch)
# Random samples after current epoch
if torch.cuda.device_count() > 1:
random_samples = vae_model.module.get_random_samples(py=args.py)
else:
random_samples = vae_model.get_random_samples(py=args.py)
for key in random_samples:
grid = make_grid(random_samples[key].cpu(), nrow=32, pad_value=1, normalize=True)
writer.add_image(key, grid, epoch)
f = '{0}/model_{1}.pt'.format(save_filename, epoch)
save_state = {
'args': args,
'vae_dict': vae_model.state_dict(),
'loss': train_loss,
}
if args.gan:
save_state['disc_dict'] = gan_model.state_dict()
torch.save(save_state, f)
if test_loss < best_loss:
best_loss = test_loss
shutil.copyfile(f, '{0}/best.pt'.format(save_filename))
print("Model saved at: {0}/best.pt".format(save_filename))
print("# Parameters: {}".format(count_parameters(vae_model)))
if torch.cuda.device_count() > 1:
summary(vae_model.module, (channels, height, width))
else:
summary(vae_model, (channels, height, width))
if __name__ == '__main__':
import argparse
import os
parser = argparse.ArgumentParser(description='Patchy VAE')
# Dataset
parser.add_argument('--dataset', type=str, default='cifar100',
help='name of the dataset (default: cifar100)')
parser.add_argument('--data-folder', type=str, default='./data',
help='name of the data folder (default: ./data)')
parser.add_argument('--workers', type=int, default=4,
help='number of threads (default: 4)')
parser.add_argument('--pretrained', default=None,
help='path of pre-trained model')
parser.add_argument('--evaluate', action='store_true', default=False,
help='just sample no training (default: False)')
parser.add_argument('--size', type=int, default=64,
help='size of image (default: 64)')
parser.add_argument('--inet', default=False, action='store_true',
help='Whether or not to do imagenet normalization')
# Model
parser.add_argument('--arch', type=str, default='patchy',
help='model architecture (default: patchy)')
parser.add_argument('--encoder-arch', type=str, default='resnet',
help='encoder architecture (default: resnet)')
parser.add_argument('--decoder-arch', type=str, default='pyramid',
help='decoder architecture (default: pyramid)')
parser.add_argument('--independent', action='store_true', default=False,
help='independent decoders (default: False)')
parser.add_argument('--ngf', type=int, default=64,
help='depth of first layer of encoder (default: 64)')
# Optimization
parser.add_argument('--recon-mask', type=str, default=None,
help="Use 'edge' mask for improved reconstruction (default: None.)")
parser.add_argument('--batch-size', type=int, default=128,
help='batch size (default: 128)')
parser.add_argument('--img-per-epoch', type=int, default=50000,
help='images per epoch (default: 50000)')
parser.add_argument('--num-epochs', type=int, default=30,
help='number of epochs (default: 30)')
parser.add_argument('--no-cuda', action='store_true', default=False,
help='enables CUDA training (default: False)')
parser.add_argument('--lr', type=float, default=1e-4,
help='learning rate for Adam optimizer (default: 1e-4)')
parser.add_argument('--beta-a', type=float, default=1.0,
help='contribution of KLD App loss (default: 1.0)')
parser.add_argument('--beta-v', type=float, default=10.,
help='contribution of KLD Vis loss (default: 10.)')
parser.add_argument('--beta-p', type=float, default=0.,
help='contribution of MSE Parts loss (default: 0.)')
parser.add_argument('--beta-ea', type=float, default=0.,
help='contribution of Entropy Across loss (default: 0.)')
parser.add_argument('--beta-ew', type=float, default=0.,
help='contribution of Entropy Within loss (default: 0.)')
# GAN
parser.add_argument('--gan', action='store_true', default=False,
help='enable gan (default: False)')
parser.add_argument('--ndf', type=int, default=64,
help='depth of first layer of discrimnator (default: 64)')
parser.add_argument('--beta-g', type=float, default=1.0,
help='contribution of GAN loss (default: 0.)')
# Latent space
parser.add_argument('--scale', type=int, default=8,
help='scale down by (default: 8)')
parser.add_argument('--num-parts', type=int, default=16,
help='number of parts (default: 16)')
parser.add_argument('--hidden-size', type=int, default=6,
help='size of the latent vectors (default: 6)')
parser.add_argument('--py', type=float, default=None,
help='part visibility prior (default: 1 / num_parts)')
parser.add_argument('--categorical', action='store_true', default=False,
help='take only 1 part per location (default: False)')
# Annealing
parser.add_argument('--hard', action='store_true', default=False,
help='hard samples from bernoulli (default: False)')
parser.add_argument('--temp', type=float, default=1.0,
help='Initial temperature (default: 1.0)')
parser.add_argument('--anneal', type=float, default=0.00003,
help='Anneal rate (default: 00003)')
parser.add_argument('--min-temp', type=float, default=0.1,
help='minimum temperature')
# Miscellaneous
parser.add_argument('--debug-grad', action='store_true', default=False,
help='debug gradients (default: False)')
parser.add_argument('--output-folder', type=str, default='./scratch',
help='name of the output folder (default: ./scratch)')
parser.add_argument('--seed', type=int, default=1,
help='random seed (default: 1)')
parser.add_argument('--log-interval', type=int, default=50,
help='how many batches to wait before logging training status')
parser.add_argument('--save-interval', type=int, default=1,
help='how many batches to wait before logging training status')
args = parser.parse_args()
print("All arguments")
print(args)
print("PID: ", os.getpid())
args.cuda = not args.no_cuda and torch.cuda.is_available()
args.device = torch.device("cuda:0"
if args.cuda and torch.cuda.is_available() else "cpu")
# Slurm
if 'SLURM_JOB_NAME' in os.environ and 'SLURM_JOB_ID' in os.environ:
# running with sbatch and not srun
if os.environ['SLURM_JOB_NAME'] != 'bash':
args.output_folder = os.path.join(args.output_folder,
os.environ['SLURM_JOB_ID'])
print("SLURM_JOB_ID: ", os.environ['SLURM_JOB_ID'])
else:
args.output_folder = os.path.join(args.output_folder, str(os.getpid()))
else:
args.output_folder = os.path.join(args.output_folder, str(os.getpid()))
# Create logs and models folder if they don't exist
if not os.path.exists(args.output_folder):
print("Creating output directory: %s" % args.output_folder)
os.makedirs(args.output_folder)
log_dir = os.path.join(args.output_folder, 'logs')
if not os.path.exists(log_dir):
print("Creating log directory: %s" % log_dir)
os.makedirs(log_dir)
model_dir = os.path.join(args.output_folder, 'models')
if not os.path.exists(model_dir):
print("Creating model directory: %s" % model_dir)
os.makedirs(model_dir)
args.log_dir = log_dir
args.model_dir = model_dir
main()
| 40.063439 | 121 | 0.580548 |
096bb429411e96f2d66472cdc1c72183b691a5bc | 3,521 | py | Python | backend/routes/todolist.py | BurnySc2/sanic-react-typescript-template | 02b1722c9230018402e4c5ffbb11204a0343e73b | [
"MIT"
] | 1 | 2020-12-20T16:09:46.000Z | 2020-12-20T16:09:46.000Z | backend/routes/todolist.py | BurnySc2/sanic-react-typescript-template | 02b1722c9230018402e4c5ffbb11204a0343e73b | [
"MIT"
] | null | null | null | backend/routes/todolist.py | BurnySc2/sanic-react-typescript-template | 02b1722c9230018402e4c5ffbb11204a0343e73b | [
"MIT"
] | null | null | null | import os
import sqlite3
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Optional
from fastapi import Request
from fastapi.routing import APIRouter
from loguru import logger
ENV = os.environ.copy()
USE_MONGO_DB: bool = ENV.get('USE_MONGO_DB', 'True') == 'True'
USE_POSTGRES_DB: bool = ENV.get('USE_POSTGRES_DB', 'True') == 'True'
USE_LOCAL_SQLITE_DB: bool = ENV.get('USE_LOCAL_SQLITE_DB', 'True') == 'True'
SQLITE_FILENAME: str = ENV.get('SQLITE_FILENAME', 'todos.db')
# TODO use different database tables when using stage = dev/staging/prod
todo_list_router = APIRouter()
db: Optional[sqlite3.Connection] = None
# TODO Communicate with postgresql and mongodb
def get_db() -> Optional[sqlite3.Connection]:
return db
def create_database_if_not_exist():
# pylint: disable=W0603
global db
todos_db = Path(__file__).parent.parent / 'data' / SQLITE_FILENAME
if not todos_db.is_file():
os.makedirs(todos_db.parent, exist_ok=True)
db = sqlite3.connect(todos_db)
db.execute('CREATE TABLE todos (id INTEGER PRIMARY KEY AUTOINCREMENT, task TEXT)')
db.commit()
logger.info(f'Created new database: {todos_db.name}')
else:
db = sqlite3.connect(todos_db)
@todo_list_router.get('/api')
async def show_all_todos() -> List[Dict[str, str]]:
todos = []
if db:
for row in db.execute('SELECT id, task FROM todos'):
todos.append({
'id': row[0],
'content': row[1],
})
return todos
@todo_list_router.post('/api/{todo_description}')
async def create_new_todo(todo_description: str):
# https://fastapi.tiangolo.com/advanced/using-request-directly/
if todo_description:
logger.info(f'Attempting to insert new todo: {todo_description}')
if db:
db.execute('INSERT INTO todos (task) VALUES (?)', [todo_description])
db.commit()
# Alternative to above with request body:
@todo_list_router.post('/api_body')
async def create_new_todo2(request: Request):
"""
Example with accessing request body.
Send a request with body {"new_todo": "<todo task description>"}
"""
# https://fastapi.tiangolo.com/advanced/using-request-directly/
request_body = await request.json()
todo_item = request_body.get('new_todo', None)
if todo_item:
logger.info(f'Attempting to insert new todo: {todo_item}')
if db:
db.execute('INSERT INTO todos (task) VALUES (?)', [todo_item])
db.commit()
@dataclass()
class Item:
todo_description: str
# Alternative to above with model:
@todo_list_router.post('/api_model')
async def create_new_todo3(item: Item):
"""
Example with accessing request body.
Send a request with body {"todo_description": "<todo task description>"}
"""
# https://fastapi.tiangolo.com/tutorial/body/#import-pydantics-basemodel
logger.info(f'Received item: {item}')
if item and item.todo_description:
logger.info(f'Attempting to insert new todo: {item.todo_description}')
if db:
db.execute('INSERT INTO todos (task) VALUES (?)', [item.todo_description])
db.commit()
@todo_list_router.delete('/api/{todo_id}')
async def remove_todo(todo_id: int):
""" Example of using /api/itemid with DELETE request """
logger.info(f'Attempting to remove todo id: {todo_id}')
if db:
db.execute('DELETE FROM todos WHERE id==(?)', [todo_id])
db.commit()
| 32.302752 | 90 | 0.672536 |
096bb8869bace9e3c4b6964fc661952242355ebd | 11,602 | py | Python | membership/management/commands/csvbills.py | guaq/sikteeri | 9a80790666edaa058e9cb42cb9e78626cfc0e565 | [
"MIT"
] | null | null | null | membership/management/commands/csvbills.py | guaq/sikteeri | 9a80790666edaa058e9cb42cb9e78626cfc0e565 | [
"MIT"
] | null | null | null | membership/management/commands/csvbills.py | guaq/sikteeri | 9a80790666edaa058e9cb42cb9e78626cfc0e565 | [
"MIT"
] | null | null | null | # encoding: UTF-8
from __future__ import with_statement
import logging
import codecs
import csv
import os
from datetime import datetime, timedelta
from decimal import Decimal
from django.db.models import Q, Sum
from django.core.management.base import BaseCommand
from django.core.exceptions import ObjectDoesNotExist
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from membership.models import Bill, BillingCycle, Payment
from membership.utils import log_change
from optparse import make_option
logger = logging.getLogger("membership.csvbills")
class UTF8Recoder:
"""
Iterator that reads an encoded stream and reencodes the input to UTF-8
<http://docs.python.org/library/csv.html#examples>
"""
def __init__(self, f, encoding):
self.reader = codecs.getreader(encoding)(f)
def __iter__(self):
return self
def next(self):
return self.reader.next().encode("utf-8")
class UnicodeReader:
"""
A CSV reader which will iterate over lines in the CSV file "f",
which is encoded in the given encoding.
<http://docs.python.org/library/csv.html#examples>
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
f = UTF8Recoder(f, encoding)
self.reader = csv.reader(f, dialect=dialect, **kwds)
def next(self):
row = self.reader.next()
return [unicode(s, "utf-8") for s in row]
def __iter__(self):
return self
class UnicodeDictReader(UnicodeReader):
"""A CSV reader which stores the headers from the first line
"""
def __init__(self, *args, **kw):
UnicodeReader.__init__(self, *args, **kw)
# Read headers from first line
self.headers = map(lambda x: x.strip(), UnicodeReader.next(self))
def next(self):
row = UnicodeReader.next(self)
return dict(zip(self.headers, row))
class RequiredFieldNotFoundException(Exception): pass
class DuplicateColumnException(Exception): pass
class PaymentFromFutureException(Exception): pass
class BillDictReader(UnicodeDictReader):
REQUIRED_COLUMNS = ['date', 'amount', 'transaction']
CSV_TRANSLATION = {}
def __init__(self, f, delimiter=';', encoding="iso8859-1", *args, **kw):
UnicodeDictReader.__init__(self, f, delimiter=delimiter,
encoding=encoding, *args, **kw)
# Translate headers
h = self.headers
for i in xrange(0, len(h)):
self.headers[i] = self._get_translation(h[i])
# Check that all required columns exist in the header
for name in self.REQUIRED_COLUMNS:
if name not in self.headers:
error = "CSV format is invalid: missing field '%s'." % name
raise RequiredFieldNotFoundException(error)
# Check that each field is unique
for name in self.headers:
if self.headers.count(name) != 1:
error = "The field '%s' occurs multiple times in the header"
raise DuplicateColumnException(error)
def _get_translation(self, h):
"""
Function for custom translations
"""
return self.CSV_TRANSLATION.get(h, h)
def _get_row(self, row):
"""
Function for custom data processing
"""
return row
def next(self):
row = self._get_row(UnicodeDictReader.next(self))
if len(row) == 0:
return None
row['amount'] = Decimal(row['amount'].replace(",", "."))
row['date'] = datetime.strptime(row['date'], "%d.%m.%Y")
row['reference'] = row['reference'].replace(' ', '').lstrip('0')
row['transaction'] = row['transaction'].replace(' ', '').replace('/', '')
if row.has_key('value_date'):
row['value_date'] = datetime.strptime(row['value_date'], "%d.%m.%Y")
return row
class OpDictReader(BillDictReader):
'''Reader for Osuuspankki CSV file format
The module converts Osuuspankki CSV format data into a more usable form.'''
# If these fields are not found on the first line, an exception is raised
REQUIRED_COLUMNS = ['date', 'amount', 'transaction']
# Translation table from Osuuspankki CSV format to short names
OP_CSV_TRANSLATION = {u'Kirjauspäivä' : 'date',
u'Arvopäivä' : 'value_date',
u'Tap.pv' : 'date', # old format
u'Määrä EUROA' : 'amount',
u'Määrä' : 'amount',
u'Tapahtumalajikoodi' : 'event_type_code',
u'Selitys' : 'event_type_description',
u'Saaja/Maksaja' : 'fromto',
u'Saajan tilinumero' : 'account', # old format
u'Saajan tilinumero ja pankin BIC' : 'account',
u'Viite' : 'reference',
u'Viesti' : 'message',
u'Arkistotunnus' : 'transaction', # old format
u'Arkistointitunnus' : 'transaction'}
def _get_translation(self, h):
# Quick and dirty, OP changes this field name too often!
if h.startswith(u"Määrä"):
return "amount"
return self.OP_CSV_TRANSLATION.get(h, h)
class ProcountorDictReader(BillDictReader):
REQUIRED_COLUMNS = ['date', 'amount', 'transaction']
CSV_TRANSLATION = {u'Kirjauspäivä' : 'date',
u'Arvopäivä' : 'value_date',
u'Maksupäivä' : 'date',
u'Maksu' : 'amount',
u'Summa' : 'amount',
u'Kirjausselite' : 'event_type_description',
u'Maksaja' : 'fromto',
u'Nimi' : 'fromto',
u'Tilinro' : 'account',
u'Viesti' : 'message',
u'Viitenumero' : 'reference',
u'Arkistointitunnus' : 'transaction',
u'Oikea viite' : 'real_reference',
}
def _get_row(self, row):
if 'real_reference' in row:
row['reference'] = row['real_reference']
return row
def row_to_payment(row):
try:
p = Payment.objects.get(transaction_id__exact=row['transaction'])
return p
except Payment.DoesNotExist:
p = Payment(payment_day=min(datetime.now(), row['date']),
amount=row['amount'],
type=row['event_type_description'],
payer_name=row['fromto'],
reference_number=row['reference'],
message=row['message'],
transaction_id=row['transaction'])
return p
def attach_payment_to_cycle(payment, user=None):
"""
Outside of this module, this function is mainly used by
generate_test_data.py.
"""
if payment.ignore == True or payment.billingcycle != None:
raise Exception("Unexpected function call. This shouldn't happen.")
reference = payment.reference_number
cycle = BillingCycle.objects.get(reference_number=reference)
if cycle.is_paid == False or cycle.amount_paid() < cycle.sum:
payment.attach_to_cycle(cycle, user=user)
else:
# Don't attach a payment to a cycle with enough payments
payment.comment = _('duplicate payment')
payment.duplicate = True
log_user = User.objects.get(id=1)
log_change(payment, log_user, change_message="Payment not attached due to duplicate payment")
payment.save()
return None
return cycle
def process_payments(reader, user=None):
"""
Actual CSV file processing logic
"""
return_messages = []
num_attached = num_notattached = 0
sum_attached = sum_notattached = 0
for row in reader:
if row == None:
continue
if row['amount'] < 0: # Transaction is paid by us, ignored
continue
# Payment in future more than 1 day is a fatal error
if row['date'] > datetime.now() + timedelta(days=1):
raise PaymentFromFutureException("Payment date in future")
payment = row_to_payment(row)
# Do nothing if this payment has already been assigned or ignored
if payment.billingcycle or payment.ignore:
continue
try:
cycle = attach_payment_to_cycle(payment, user=user)
if cycle:
msg = _("Attached payment %(payment)s to cycle %(cycle)s") % {
'payment': unicode(payment), 'cycle': unicode(cycle)}
logger.info(msg)
return_messages.append((None, None, msg))
num_attached = num_attached + 1
sum_attached = sum_attached + payment.amount
else:
# Payment not attached to cycle because enough payments were attached
msg = _("Billing cycle already paid for %s. Payment not attached.") % payment
return_messages.append((None, None, msg))
logger.info(msg)
num_notattached = num_notattached + 1
sum_notattached = sum_notattached + payment.amount
except BillingCycle.DoesNotExist:
# Failed to find cycle for this reference number
if not payment.id:
payment.save() # Only save if object not in database yet
logger.warning("No billing cycle found for %s" % payment.reference_number)
return_messages.append((None, payment.id, _("No billing cycle found for %s") % payment))
num_notattached = num_notattached + 1
sum_notattached = sum_notattached + payment.amount
log_message ="Processed %s payments total %.2f EUR. Unidentified payments: %s (%.2f EUR)" % \
(num_attached + num_notattached, sum_attached + sum_notattached, num_notattached, \
sum_notattached)
logger.info(log_message)
return_messages.append((None, None, log_message))
return return_messages
def process_op_csv(file_handle, user=None):
logger.info("Starting OP payment CSV processing...")
reader = OpDictReader(file_handle)
return process_payments(reader)
def process_procountor_csv(file_handle, user=None):
logger.info("Starting procountor payment CSV processing...")
reader = ProcountorDictReader(file_handle)
return process_payments(reader)
class Command(BaseCommand):
args = '<csvfile> [<csvfile> ...]'
help = 'Read a CSV list of payment transactions'
option_list = BaseCommand.option_list + (
make_option('--procountor',
dest='procountor',
default=None,
action="store_true",
help='Use procountor import csv format'),
)
def handle(self, *args, **options):
for csvfile in args:
logger.info("Starting the processing of file %s." %
os.path.abspath(csvfile))
# Exceptions of process_csv are fatal in command line run
with open(csvfile, 'r') as file_handle:
if options['procountor']:
process_procountor_csv(file_handle)
else:
process_op_csv(file_handle)
logger.info("Done processing file %s." % os.path.abspath(csvfile))
| 38.039344 | 104 | 0.589036 |
096c49cec3a4f594f36896910c20f3ffbf6d0451 | 1,962 | py | Python | apps/site/api/serializers/dataset_serializer.py | LocalGround/localground | aa5a956afe7a84a7763a3b23d62a9fd925831cd7 | [
"Apache-2.0"
] | 9 | 2015-05-29T22:22:20.000Z | 2022-02-01T20:39:00.000Z | apps/site/api/serializers/dataset_serializer.py | LocalGround/localground | aa5a956afe7a84a7763a3b23d62a9fd925831cd7 | [
"Apache-2.0"
] | 143 | 2015-01-22T15:03:40.000Z | 2020-06-27T01:55:29.000Z | apps/site/api/serializers/dataset_serializer.py | LocalGround/localground | aa5a956afe7a84a7763a3b23d62a9fd925831cd7 | [
"Apache-2.0"
] | 5 | 2015-03-16T20:51:49.000Z | 2017-02-07T20:48:49.000Z | from localground.apps.site.api.serializers.base_serializer import \
BaseSerializer, NamedSerializerMixin, ProjectSerializerMixin
from localground.apps.site.api.serializers.field_serializer import \
FieldSerializer
from django.conf import settings
from rest_framework import serializers
from localground.apps.site import models
class DatasetSerializerList(
NamedSerializerMixin, ProjectSerializerMixin, BaseSerializer):
data_url = serializers.SerializerMethodField()
fields_url = serializers.SerializerMethodField()
def create(self, validated_data):
# Call the Dataset's custom create method, which creates
# 2 fields "for free": Name and Description:
description = serializers.CharField(
source='description', required=False, allow_null=True, label='description',
style={'base_template': 'textarea.html', 'rows': 5}, allow_blank=True
)
validated_data.update(self.get_presave_create_dictionary())
self.instance = models.Dataset.create(**validated_data)
return self.instance
class Meta:
model = models.Dataset
fields = BaseSerializer.field_list + \
('id', 'name', 'description', 'tags', 'url') + \
ProjectSerializerMixin.field_list + ('data_url', 'fields_url')
depth = 0
def get_data_url(self, obj):
return '%s/api/0/datasets/%s/data/' % (settings.SERVER_URL, obj.pk)
def get_fields_url(self, obj):
return '%s/api/0/datasets/%s/fields/' % (settings.SERVER_URL, obj.pk)
class DatasetSerializerDetail(DatasetSerializerList):
fields = serializers.SerializerMethodField('get_dataset_fields')
class Meta:
model = models.Dataset
fields = DatasetSerializerList.Meta.fields + ('fields',)
depth = 0
def get_dataset_fields(self, obj):
return FieldSerializer(
obj.fields, many=True,
context={'request': {}}).data
| 37.730769 | 87 | 0.690622 |
096c52364e36a63ef84c11f7cd157e7b506deae2 | 1,447 | py | Python | example/0_Basic_usage_of_the_library/python_pyppeteer/7_PageClass_Cookie.py | RecluseXU/learning_spider | 45fa790ed7970be57a21b40817cc66856de3d99b | [
"MIT"
] | 38 | 2020-08-30T11:41:53.000Z | 2022-03-23T04:30:26.000Z | example/0_Basic_usage_of_the_library/python_pyppeteer/7_PageClass_Cookie.py | AndersonHJB/learning_spider | b855b7808fb5268e9564180cf73ba5b1fb133f58 | [
"MIT"
] | 2 | 2021-08-20T16:34:12.000Z | 2021-10-08T11:06:41.000Z | example/0_Basic_usage_of_the_library/python_pyppeteer/7_PageClass_Cookie.py | AndersonHJB/learning_spider | b855b7808fb5268e9564180cf73ba5b1fb133f58 | [
"MIT"
] | 10 | 2020-11-24T09:15:42.000Z | 2022-02-25T06:05:16.000Z | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : 7_PageClass_Cookie.py
@Time : 2020-8-23 01:33:25
@Author : Recluse Xu
@Version : 1.0
@Contact : 444640050@qq.com
@Desc : 页面类 Page Class
官方文档:https://miyakogi.github.io/pyppeteer/reference.html#pyppeteer.page.Page.target
Page类提供了与标签交互的方法,一个浏览器可以有多个Page对象
'''
# here put the import lib
import asyncio
from pyppeteer import launch
async def main():
browser = await launch({
'headless': False,
'ignorehttpserrrors': True,
'viewport': {'width': 1280, 'height': 800},
'autoClose': True,
})
page = await browser.newPage()
await page.goto('http://www.baidu.com')
# Page.cookies(*urls) → dict
# 获取Cookie
# 如果指定url那就返回那个url的Cookie,没指定就返回当前页面Cookie
c = await page.cookies()
print(c)
# Page.deleteCookie(*cookies)
# 删除Cookie
# cookies可以填入的参数
# name (str): 必须传入
# url (str)
# domain (str)
# path (str)
# secure (bool)
await page.deleteCookie({'name': 'BAIDUID'})
# Page.setCookie(*cookies) → None[source]
# 设置Cookie
# 可选Cookie的参数:
# name (str): required
# value (str): required
# url (str)
# domain (str)
# path (str)
# expires (number): Unix time in seconds
# httpOnly (bool)
# secure (bool)
# sameSite (str): 'Strict' or 'Lax'
asyncio.get_event_loop().run_until_complete(main()) | 23.721311 | 87 | 0.601935 |