blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
281
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
6
116
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
313 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
18.2k
668M
star_events_count
int64
0
102k
fork_events_count
int64
0
38.2k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
107 values
src_encoding
stringclasses
20 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
4
6.02M
extension
stringclasses
78 values
content
stringlengths
2
6.02M
authors
listlengths
1
1
author
stringlengths
0
175
5398a563c0de1db0f5989219d0edd118e020b7df
c1e4c88f57baf3b316fcf9379c318347fea63c33
/working files/win64/setup.py
b17bed60bad4a1ae1e8abcb40dd7002092b436dd
[]
no_license
finmonster-research/midasmlpy
7bee72e23f964f173a7876cd0355276966349e7d
80c1e69eb5e6e3667afe899228df64f0c9e13bb4
refs/heads/master
2023-02-07T08:07:20.049709
2020-12-23T15:25:20
2020-12-23T15:25:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
570
py
from setuptools import Extension,setup from Cython.Build import cythonize import numpy as np setup( ext_modules=cythonize(Extension( name="midasml2", sources=[ 'pyx/midasml2.pyx', 'src/wrapper1.cpp', 'src/wrapper2.cpp', 'src/fit_sgl.cpp', 'src/ld_estim.cpp' ], language='c++', extra_objects=["win64/lib_win64/blas_win64_MT.lib","win64/lib_win64/lapack_win64_MT.lib"], extra_compile_args=['-w'] ) ), language='c++', include_dirs=[np.get_include(),'include/'], )
c85b350ed4a297e47599a3bc232f94b2306625ad
03991a66fcea0d6cfc6055210ca99dd17b2e9e51
/app/seeds/__init__.py
4e5106d555a2bc5ca9118f6f9cce79e1e0ebc34f
[]
no_license
LifeJunkieRaj/FullstackSoloProjectGuruud
5830e59741ecd499daf2e9669679222c47ab0f13
8d7f4a14d895874239a0e7c53bc1c72cec461848
refs/heads/main
2023-06-12T04:42:30.642473
2021-07-06T13:30:54
2021-07-06T13:30:54
352,735,156
0
0
null
2021-05-29T12:27:07
2021-03-29T17:52:28
Python
UTF-8
Python
false
false
930
py
from flask.cli import AppGroup from .users import seed_users, undo_users, seed_second_user from .ask_a_guru import seed_ask_a_guru, undo_ask_a_guru from .categories import seed_categories, undo_categories from .responses import seed_responses, undo_responses from .comments import seed_comments, undo_comments from .votes import seed_votes, undo_votes # Creates a seed group to hold our commands # So we can type `flask seed --help` seed_commands = AppGroup('seed') # Creates the `flask seed all` command @seed_commands.command('all') def seed(): seed_users() seed_second_user() seed_categories() seed_ask_a_guru() seed_responses() seed_comments() seed_votes() # Creates the `flask seed undo` command @seed_commands.command('undo') def undo(): undo_votes() undo_comments() undo_responses() undo_ask_a_guru() undo_categories() undo_users() # Add other undo functions here
3f917518c79491dab54ba311e1e3639b00858968
0b1199679245d8d39fb41b3bd1b86405d8e6f281
/locallibrary/catalog/migrations/0004_alter_bookinstance_options.py
b6f508481c52dbdf144947e2e3c606a171b750f0
[ "MIT" ]
permissive
waltermaina/local-library-website
68460ac1dbc88414e9772ac463f83faa81201a32
ac0f6d9c6cd79f891d196c707327717282fcc9cb
refs/heads/main
2023-07-13T18:08:41.942090
2021-08-26T15:16:09
2021-08-26T15:16:09
398,514,004
0
0
null
null
null
null
UTF-8
Python
false
false
423
py
# Generated by Django 3.2.6 on 2021-08-26 14:43 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('catalog', '0003_bookinstance_borrower'), ] operations = [ migrations.AlterModelOptions( name='bookinstance', options={'ordering': ['due_back'], 'permissions': (('can_mark_returned', 'Set book as returned'),)}, ), ]
ca62342c43c23dfc47000c1aae015fc88579da3b
f0194c40b3e5c8b9e06eb1d70af862b6e465c9ef
/448-Find All Numbers Disappeared in an Array.py
616ae2c65c2c73616b35eff000b90511868fd712
[]
no_license
ElijahYG/Leetcode_Python
842ae9db71e7f70f7398aeec427ba51706fc2b26
79148047b27b19f1b581dd350fb9de849877bf73
refs/heads/master
2021-01-11T17:59:45.779227
2017-03-21T16:07:18
2017-03-21T16:07:18
79,895,401
0
0
null
null
null
null
UTF-8
Python
false
false
2,019
py
''' Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements of [1, n] inclusive that do not appear in this array. Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. Example: Input: [4,3,2,7,8,2,3,1] Output: [5,6] ''' # ------------------------------------------------------------------------------ #Best Result :此题自己没有AC,标记 # ------------------------------------------------------------------------------ class Solution(object): def findDisappearedNumbers(self, nums): """ :type nums: List[int] :rtype: List[int] """ ret = set(range(1, len(nums)+1)) ret = ret - set(nums) return list(ret) S = Solution() print(S.findDisappearedNumbers([1,2,2,9,4,7,6,6,5])) print(S.findDisappearedNumbers([])) print(S.findDisappearedNumbers([1,1])) # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ #以下方法可以正常执行,但是时间不合要求TLE(Time Limit Exceeded), # ------------------------------------------------------------------------------ # class Solution(object): # def findDisappearedNumbers(self, nums): # """ # :type nums: List[int] # :rtype: List[int] # """ # res = [] # for x in range(len(nums)): # if (x+1) not in nums: # res.append(x+1) # return res # S = Solution() # print(S.findDisappearedNumbers([1,2,2,9,4,7,6,6,5])) # print(S.findDisappearedNumbers([])) # print(S.findDisappearedNumbers([1,1])) # ------------------------------------------------------------------------------ # array = [1,2,3,2] # print(min(array)) # for x in range(max(array)): # print('x=%s'%x) # else: # print('NO') # print(array.index(2))
21d778e71520d07497ba9ff44ddf5c37293cb89b
22b6b1d4089c85164519507152828126967194a5
/videoanalyst/evaluation/vot_benchmark/pysot/datasets/vot.py
6765ad9d8353c0aeb3e46b9658897de697af4763
[]
no_license
Zacks-Zhang/SiamTrans
6c761a3d91df8454d894c7024a935adef300a90d
263bff18cca05d1326e41ece0915f025951dea9d
refs/heads/main
2023-08-02T07:23:51.527593
2021-08-26T03:14:41
2021-08-26T03:14:41
398,796,081
0
0
null
null
null
null
UTF-8
Python
false
false
8,775
py
import os from glob import glob import cv2 import numpy as np from PIL import Image from loguru import logger from tqdm import tqdm from ...benchmark_helper import get_json from .dataset import Dataset from .video import Video class VOTVideo(Video): """ Args: name: video name root: dataset root video_dir: video directory init_rect: init rectangle img_names: image names gt_rect: groundtruth rectangle camera_motion: camera motion tag illum_change: illum change tag motion_change: motion change tag size_change: size change occlusion: occlusion """ def __init__(self, name, root, video_dir, init_rect, img_names, gt_rect, camera_motion, illum_change, motion_change, size_change, occlusion, load_img=False): super(VOTVideo, self).__init__(name, root, video_dir, init_rect, img_names, gt_rect, None, load_img) self.tags= {'all': [1] * len(gt_rect)} self.tags['camera_motion'] = camera_motion self.tags['illum_change'] = illum_change self.tags['motion_change'] = motion_change self.tags['size_change'] = size_change self.tags['occlusion'] = occlusion # TODO # if len(self.gt_traj[0]) == 4: # self.gt_traj = [[x[0], x[1], x[0], x[1]+x[3]-1, # x[0]+x[2]-1, x[1]+x[3]-1, x[0]+x[2]-1, x[1]] # for x in self.gt_traj] # empty tag all_tag = [v for k, v in self.tags.items() if len(v) > 0] self.tags['empty'] = np.all(1 - np.array(all_tag), axis=1).astype(np.int32).tolist() # self.tags['empty'] = np.all(1 - np.array(list(self.tags.values())), # axis=1).astype(np.int32).tolist() self.tag_names = list(self.tags.keys()) if not load_img: img_name = os.path.join(os.path.abspath(root), os.path.abspath(self.img_names[0])) img = np.array(Image.open(img_name), np.uint8) self.width = img.shape[1] self.height = img.shape[0] def select_tag(self, tag, start=0, end=0): if tag == 'empty': return self.tags[tag] return self.tags[tag][start:end] def load_tracker(self, path, tracker_names=None, store=True): """ Args: path(str): path to result tracker_name(list): name of tracker """ if not tracker_names: tracker_names = [ x.split('/')[-1] for x in glob(path) if os.path.isdir(x) ] if isinstance(tracker_names, str): tracker_names = [tracker_names] for name in tracker_names: traj_files = glob( os.path.join(path, name, 'baseline', self.name, '*0*.txt')) if len(traj_files) == 15: traj_files = traj_files else: traj_files = traj_files[0:1] pred_traj = [] for traj_file in traj_files: with open(traj_file, 'r') as f: traj = [ list(map(float, x.strip().split(','))) for x in f.readlines() ] pred_traj.append(traj) if store: self.pred_trajs[name] = pred_traj else: return pred_traj class VOTDataset(Dataset): """ Args: name: dataset name, should be 'VOT2018', 'VOT2016' dataset_root: dataset root load_img: wether to load all imgs """ def __init__(self, name, dataset_root, load_img=False): super(VOTDataset, self).__init__(name, dataset_root) f = os.path.join(dataset_root, name + '.json') meta_data = get_json(f) # load videos pbar = tqdm(meta_data.keys(), desc='loading ' + name, ncols=100) self.videos = {} for video in pbar: pbar.set_postfix_str(video) self.videos[video] = VOTVideo(video, dataset_root, meta_data[video]['video_dir'], meta_data[video]['init_rect'], meta_data[video]['img_names'], meta_data[video]['gt_rect'], meta_data[video]['camera_motion'], meta_data[video]['illum_change'], meta_data[video]['motion_change'], meta_data[video]['size_change'], meta_data[video]['occlusion'], load_img=load_img) self.tags = [ 'all', 'camera_motion', 'illum_change', 'motion_change', 'size_change', 'occlusion', 'empty' ] class VOTLTVideo(Video): """ Args: name: video name root: dataset root video_dir: video directory init_rect: init rectangle img_names: image names gt_rect: groundtruth rectangle """ def __init__(self, name, root, video_dir, init_rect, img_names, gt_rect, load_img=False): super(VOTLTVideo, self).__init__(name, root, video_dir, init_rect, img_names, gt_rect, None) self.gt_traj = [[0] if np.isnan(bbox[0]) else bbox for bbox in self.gt_traj] if not load_img: img_name = os.path.join(root, self.img_names[0]) if not os.path.exists(img_name): img_name = img_name.replace("color/", "") img = cv2.imread(img_name) if img is None: logger.error("can not open img file {}".format(img_name)) self.width = img.shape[1] self.height = img.shape[0] self.confidence = {} def load_tracker(self, path, tracker_names=None, store=True): """ Args: path(str): path to result tracker_name(list): name of tracker """ if not tracker_names: tracker_names = [ x.split('/')[-1] for x in glob(path) if os.path.isdir(x) ] if isinstance(tracker_names, str): tracker_names = [tracker_names] for name in tracker_names: traj_file = os.path.join(path, name, 'longterm', self.name, self.name + '_001.txt') with open(traj_file, 'r') as f: traj = [ list(map(float, x.strip().split(','))) for x in f.readlines() ] if store: self.pred_trajs[name] = traj confidence_file = os.path.join(path, name, 'longterm', self.name, self.name + '_001_confidence.value') with open(confidence_file, 'r') as f: score = [float(x.strip()) for x in f.readlines()[1:]] score.insert(0, float('nan')) if store: self.confidence[name] = score return traj, score class VOTLTDataset(Dataset): """ Args: name: dataset name, 'VOT2018-LT' dataset_root: dataset root load_img: wether to load all imgs """ def __init__(self, name, dataset_root, load_img=False): super(VOTLTDataset, self).__init__(name, dataset_root) try: f = os.path.join(dataset_root, name + '.json') meta_data = get_json(f) except: download_str = 'Please download json file from https://pan.baidu.com/s/1js0Qhykqqur7_lNRtle1tA#list/path=%2F or https://drive.google.com/drive/folders/10cfXjwQQBQeu48XMf2xc_W1LucpistPI\n' logger.error("Can not open vot json file {}\n".format(f)) logger.error(download_str) exit() # load videos pbar = tqdm(meta_data.keys(), desc='loading ' + name, ncols=100) self.videos = {} for video in pbar: pbar.set_postfix_str(video) self.videos[video] = VOTLTVideo(video, os.path.join(dataset_root, name), meta_data[video]['video_dir'], meta_data[video]['init_rect'], meta_data[video]['img_names'], meta_data[video]['gt_rect'])
b476476e5bf5569b7c3e403e153af7d0eea3ebe0
b27e687b8666573702f5970301558718d02f7d4a
/retrain-models/utils/silence_removal.py
6e0dc0e36dce83efd5c15ab4755d1e2f2ab1a5c8
[]
no_license
hexoance/LPI_PROJ
270cda80c68b00b3ae167034ec8b4a614c3a1854
26ec62ae84948d48a56df69e5f38e17b62f1bc2b
refs/heads/master
2023-05-31T00:27:29.453527
2021-06-15T21:12:10
2021-06-15T21:12:10
345,213,794
2
0
null
2021-05-10T23:24:02
2021-03-06T23:03:21
Python
UTF-8
Python
false
false
1,149
py
from pydub import AudioSegment # Iterate over chunks until you find the first one with sound, where sound is a pydub.AudioSegment def detect_leading_silence(sound): silence_threshold = -50.0 # dB chunk_size = 10 # ms trim_ms = 0 # ms while sound[trim_ms:trim_ms+chunk_size].dBFS < silence_threshold and trim_ms < len(sound): trim_ms += chunk_size return trim_ms # Iterate over chunks of the sound, removing ones with silence, where sound is a pydub.AudioSegment def remove_middle_silence(sound): silence_threshold = -50.0 # dB chunk_size = 100 # ms sound_ms = 0 # ms trimmed_sound = AudioSegment.empty() while sound_ms < len(sound): if sound[sound_ms:sound_ms+chunk_size].dBFS >= silence_threshold: trimmed_sound += sound[sound_ms:sound_ms+chunk_size] sound_ms += chunk_size return trimmed_sound.set_sample_width(2) def trim_silence(sound): start_trim = detect_leading_silence(sound) end_trim = detect_leading_silence(sound.reverse()) duration = len(sound) trimmed_sound = sound[start_trim:duration - end_trim] return trimmed_sound
ea3e3e20813dd7c814e974b5e7d3ee59754282cd
80c315a21e1b1edeab236a6f19ec06cdfc81873d
/scripts/download_mggg.py
639054e3239bf0cb2579796c344a17b9ed819a88
[ "MIT" ]
permissive
mcullan-redistricting/redistricting-postgis
0bf99787decf66d19a6d41cf26f3896c4da5f62d
7adef1c1e2060122004ad050eea3b1e89565ef45
refs/heads/master
2022-04-06T03:19:52.730698
2020-02-17T11:11:16
2020-02-17T11:11:16
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,306
py
from io import BytesIO from bs4 import BeautifulSoup import requests import os import pandas as pd from constants import STATES from zipfile import ZipFile data_path = os.environ.get('DATA_PATH', '../data') def download_mggg_state_zip(state_abbreviation, filepath, overwrite = False): url = f'https://github.com/mggg-states/{state_abbreviation}-shapefiles/archive/master.zip' response = requests.get(url) if response.ok: full_path = filepath + f'/precincts-elections/' if not os.path.exists(full_path): os.mkdir(full_path) zip_name = f'{state_abbreviation}-shapefiles-master.zip' full_filepath = f'{full_path}/{zip_name}' if overwrite or not os.path.exists(full_filepath): with open(full_filepath, 'wb') as file: file.write(response.content) print(f'Extracting {state_abbreviation} zip file.') with ZipFile(full_filepath) as file: file.extractall(full_path) os.remove(full_filepath) if response.status_code == 404: print(f'404 returned for {state_abbreviation}.') return def get_mggg_states_metadata(state_abbreviation): url = f'https://github.com/mggg-states/{state_abbreviation}-shapefiles/blob/master/README.md' response = requests.get(url) if response.ok: print(f'Downloaded {state_abbreviation} metadata.') soup = BeautifulSoup(response.text, 'lxml') metadata = soup.select('li:has(code)') data_dict = {} for line in metadata: k,v = line.text.split(': ') data_dict[k] = v return data_dict if response.status_code == 404: print('Could not complete request due to 404 error.') def download_mggg_shapefile(state_abbreviation, filepath): url = f'https://github.com/mggg-states/{state_abbreviation}-shapefiles/raw/master/{state_abbreviation}_VTD.zip' response = requests.get(url) if response.ok: print(f'Downloaded {state_abbreviation} zip file.') full_path = filepath + f'/{state_abbreviation}_VTD' zip_name = f'{state_abbreviation}_VTD.zip' with open(f'{full_path}/{zip_name}', 'wb') as file: file.write(response.content) with ZipFile(f'{full_path}/{zip_name}') as file: file.extractall(filepath + '/NC_VTD') os.remove(f'{full_path}/{zip_name}') if response.status_code == 404: print(f'404 returned for {state_abbreviation}.') return def download_mggg_state(state_abbreviation, filepath): # If directory doesn't exist, create it full_path = filepath + f'/precincts-elections/{state_abbreviation}_VTD' if not os.path.exists(full_path): os.mkdir(full_path) # Download metadata and save to constants.py data_dict = get_mggg_states_metadata(state_abbreviation) with open(f'{full_path}/metadata.py', 'w') as file: file.write(f'DATA_DICT = {data_dict}') # Download shapefile and election data download_mggg_shapefile(state_abbreviation, filepath) if __name__ == '__main__': state_abbvreviations = STATES.values() for abbreviation in list(state_abbvreviations): download_mggg_state_zip(abbreviation, data_path)
310dcb908e8a2335caf82c31f7477f87ba3f3bbc
3f40317a3ec5a6347402bfe4a010a2dbc727f519
/applications/stm32-nucleo743/blinky/wscript
db14be6fcdf089d3b32a9502b931f80b593da11a
[ "BSD-2-Clause" ]
permissive
trigrass2/rtems-demo
0af45709f5889aa5e8526b0c7240ce07752b81aa
cdd6c760ab5e026efb3fb940e3097599241ec656
refs/heads/master
2023-04-09T16:46:42.102875
2021-04-19T15:24:39
2021-04-19T15:24:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,650
# # LED blink Waf script # from __future__ import print_function import sys sys.path.append('../../..') rtems_version = "6" try: # from ...rtems_waf import rtems as rtems import rtems_waf.rtems as rtems except ImportError: print('error: no rtems_waf git submodule') import sys sys.exit(1) def init(ctx): rtems.init(ctx, version = rtems_version, long_commands = True) def bsp_configure(conf, arch_bsp): # Add BSP specific configuration checks pass def options(opt): rtems.options(opt) opt.load('objcopy') def configure(conf): rtems.configure(conf, bsp_configure = bsp_configure) # RTEMS already loads objcopy # conf.load('objcopy') def build(bld): rtems.build(bld) root_src = ['bsp_stm32/init.c', 'bsp_stm32/led.c'] board_src = ['bsp_stm32/boardconfig/stm32h7xx_nucleo.c'] # Still need to add include paths here target_name = "blinky" target_bin_extension = ".bin" target_elf_extension = ".elf" target_elf_name = target_name + target_elf_extension target_bin_name = target_name + target_bin_extension # bld(features = 'c cprogram', target = target_elf_name, cflags = '-g -O2', # source = root_src + board_src, objcopy_target=target_bin_name, # objcopy_bfdname='binary') # Does not work, need to link output of previous task somehow.. # bld(features='objcopy', objcopy_target=target_bin_name, # objcopy_bfdname='binary') bld(features = 'c cprogram', target = target_elf_name, cflags = '-g -O2', source = root_src + board_src) bld(target=target_bin_name, source=target_elf_name, rule = "${OBJCOPY} -O binary ${SRC} ${TGT}", cls_keyword=lambda x: "Creating binary " + target_bin_name + " from")
77dddd35f973d46c1f2015c164c3cd6218db3ecc
8b37017853acfe108d0a06bc946f4f4e6ed8fe15
/apps/gas_app/views.py
47f14353f6e9a123babc5fe30569c42e956ef3a3
[]
no_license
mkemper31/gas_tracker
e7b313d2c554b45d785c2390fa08dd42a5e1a24f
40d50b63cac82cbae703d8d7eee81413e19e667b
refs/heads/master
2020-06-23T17:45:48.978787
2019-07-28T03:38:52
2019-07-28T03:38:52
198,703,723
0
0
null
null
null
null
UTF-8
Python
false
false
15,782
py
""" Define functions for each URL route """ from datetime import datetime from django.shortcuts import render, redirect, reverse from django.contrib import messages from django.db.models import Sum, F from apps.users.views import logged_in, cur_usr_id from apps.users.models import User from .models import Car, Entry # Create your views here. def index(request): #TODO GET USER DATA RENDER gas:home """ Returns the landing page, including graph and quick summary. """ if not logged_in(request): return redirect(reverse('users:home')) if not has_car(request): return redirect(reverse("gas:new_car")) if 'active_car' not in request.session or not owns_car(request): request.session['active_car'] = Car.objects.filter(owner=User.objects.get(id=cur_usr_id(request))).first().id current_car = Car.objects.get(id=cur_car_id(request)) current_user = User.objects.get(id=cur_usr_id(request)) if not Entry.objects.filter(car=current_car): return redirect(reverse('gas:new_entry')) all_entries = Entry.objects.annotate(price_per_gallon=F('price') / F('gallons')).filter(car=current_car).order_by('-id') entries = Entry.objects.annotate(price_per_gallon=F('price') / F('gallons')).filter(car=current_car).order_by('-id')[:6] comparison_dict = {} all_data = { "dates": [], "gallons": [], "odometer": [], "miles_since_last": [], "miles_per_gallon": [], "miles_per_day": [], "cost": [], "cost_per_gallon": [], } for i in range(len(all_entries)-1): date_string = all_entries[i].entry_date.strftime("%d %b %Y") all_data['dates'].append(date_string) all_data['gallons'].append(all_entries[i].gallons) all_data['odometer'].append(all_entries[i].odometer) mile_comparison = all_entries[i].odometer - all_entries[i+1].odometer all_data['miles_since_last'].append(mile_comparison) mpg_comparison = mile_comparison / all_entries[i].gallons all_data['miles_per_gallon'].append(mpg_comparison) days_between = all_entries[i].entry_date - all_entries[i+1].entry_date try: per_day_comparison = mile_comparison / days_between.days except ZeroDivisionError: per_day_comparison = 0 all_data['miles_per_day'].append(per_day_comparison) all_data['cost'].append(all_entries[i].price) all_data['cost_per_gallon'].append(round(all_entries[i].price_per_gallon, 2)) for key in all_data: all_data[key] = all_data[key][::-1] for i in range(len(entries)-1): mile_comparison = entries[i].odometer - entries[i+1].odometer mpg_comparison = mile_comparison / entries[i].gallons comparison_dict[entries[i]] = [mile_comparison, mpg_comparison] #data_json = json.dumps(all_data, sort_keys=False, indent=1, cls=DjangoJSONEncoder) #print(data_json) context = { "data_json": all_data, "current_car": current_car, "comp_dict": comparison_dict, "all_cars": Car.objects.filter(owner=current_user), "last_entry": Entry.objects.filter(car=current_car).last(), } return render(request, "gas_app/index.html", context) def new_car(request): #DONE GET NEW CAR FORM RENDER gas:new_car """ Returns the form to enter a new car. """ if not logged_in(request): return redirect(reverse('users:home')) current_user = User.objects.get(id=cur_usr_id(request)) context = { "all_cars": Car.objects.filter(owner=current_user), } return render(request, "gas_app/new_entry.html", context) def create_car(request): #DONE POST SUBMIT NEW CAR FORM REDIRECT gas:create_car """ POSTs the form for the new car """ if not logged_in(request): return redirect(reverse('users:home')) errors = Car.objects.validate(request.POST) if errors: for key, value in errors.items(): messages.error(request, value, extra_tags=key) return redirect(reverse('gas:new_car')) fields = { "car_name": request.POST['car-name'], "car_year": int(request.POST['car-years']), "car_make": request.POST['car-makes'], "car_model": request.POST['car-models'], "car_trim": request.POST['car-model-trims'], "car_owner": User.objects.get(id=cur_usr_id(request)) } if not request.POST['car-name']: fields["car_name"] = "My Car" car = Car.objects.create(name=fields['car_name'], year=fields['car_year'], make=fields['car_make'], model=fields['car_model'], trim=fields['car_trim'], owner=fields['car_owner']) request.session['active_car'] = car.id return redirect(reverse('gas:home')) def view_car(request, car_id): #DONE GET CAR DATA RENDER gas:view_car """ Returns page to view all the details for the desired call, including a quick summary and all the data entries for that car. """ if not logged_in(request): return redirect(reverse('users:home')) if not has_car(request): return redirect(reverse("gas:new_car")) request.session['active_car'] = car_id if not owns_car(request): request.session['active_car'] = Car.objects.filter(owner=User.objects.get(id=cur_usr_id(request))).first().id return redirect(reverse('gas:view_car', kwargs={'car_id': cur_car_id(request)})) current_car = Car.objects.get(id=cur_car_id(request)) current_user = User.objects.get(id=cur_usr_id(request)) if not Entry.objects.filter(car=current_car): limited_context = { "current_car": current_car, "all_cars": Car.objects.filter(owner=current_user), "no_entries": True } return render(request, "gas_app/entry_list.html", limited_context) total_miles = Entry.objects.filter(car=current_car).last().odometer - Entry.objects.filter(car=current_car).first().odometer total_gallons = Entry.objects.filter(car=current_car).aggregate(Sum('gallons')) total_spent = Entry.objects.filter(car=current_car).aggregate(Sum('price')) try: avg_price_per_mile = total_spent['price__sum'] / total_miles except ZeroDivisionError: avg_price_per_mile = 0 avg_price_per_mile = str(round(avg_price_per_mile, 2)) try: avg_mpg = total_miles / (total_gallons['gallons__sum'] - Entry.objects.filter(car=current_car).first().gallons) except ZeroDivisionError: avg_mpg = 0 avg_mpg = str(round(avg_mpg, 2)) avg_price_per_gal = total_spent['price__sum'] / total_gallons['gallons__sum'] avg_price_per_gal = str(round(avg_price_per_gal, 2)) try: avg_miles_per_day = total_miles / (Entry.objects.filter(car=current_car).last().entry_date - Entry.objects.filter(car=current_car).first().entry_date).days except ZeroDivisionError: avg_miles_per_day = 0 avg_miles_per_day = str(round(avg_miles_per_day, 2)) total_gallons = str(round(total_gallons['gallons__sum'], 3)) total_spent = str(round(total_spent['price__sum'], 2)) all_entries = Entry.objects.annotate(price_per_gallon=F('price') / F('gallons')).filter(car=current_car).order_by('-id') comparison_dict = {} for i in range(len(all_entries)-1): mile_comparison = all_entries[i].odometer - all_entries[i+1].odometer mpg_comparison = mile_comparison / all_entries[i].gallons comparison_dict[all_entries[i]] = [mile_comparison, mpg_comparison] context = { "no_entries": False, "all_entries": all_entries, "range": range(len(all_entries)), "comp_dict": comparison_dict, "last_entry": Entry.objects.filter(car=current_car).last(), "first_entry": Entry.objects.filter(car=current_car).first(), "total_miles": total_miles, "total_gallons": total_gallons, "total_spent": total_spent, "avg_miles_per_day": avg_miles_per_day, "avg_price_per_gal": avg_price_per_gal, "avg_price_per_mile": avg_price_per_mile, "avg_mpg": avg_mpg, "current_car": current_car, "all_cars": Car.objects.filter(owner=current_user), } return render(request, "gas_app/entry_list.html", context) def edit_car(request, car_id): #TODO GET EDIT CAR FORM RENDER gas:edit_car """ Returns a form to edit an owned car. """ if not logged_in(request): return redirect(reverse('users:home')) request.session['active_car'] = car_id current_car = Car.objects.get(id=cur_car_id(request)) current_user = User.objects.get(id=cur_usr_id(request)) context = { "current_car": current_car, "all_cars": Car.objects.filter(owner=current_user), } return render(request, "gas_app/new_entry.html", context) def update_car(request): #TODO POST SUBMIT EDIT CAR FORM REDIRECT gas:update_car """ POST the form to the database """ if not logged_in(request): return redirect(reverse('users:home')) errors = Car.objects.validate(request.POST) if errors: for key, value in errors.items(): messages.error(request, value, extra_tags=key) return redirect(reverse('gas:edit_car')) fields = { "car_name": request.POST['car-name'], "car_year": int(request.POST['car-years']), "car_make": request.POST['car-makes'], "car_model": request.POST['car-models'], "car_trim": request.POST['car-model-trims'], } if not request.POST['car-name']: fields["car_name"] = "My Car" car = Car.objects.get(id=cur_car_id(request)) car.name = fields['car_name'] car.year = fields['car_year'] car.make = fields['car_make'] car.model = fields['car_model'] car.trim = fields['car_trim'] car.save() return redirect(reverse('gas:home')) def delete_car(request, car_id): #TODO DELETE CAR REDIRECT gas:delete_car """ Delete an owned car, and delete all related entries. """ if not logged_in(request): return redirect(reverse('users:home')) request.session['active_car'] = car_id if not owns_car(request): request.session['active_car'] = None return redirect(reverse('gas:home')) c = Car.objects.get(id=cur_car_id(request)) c.delete() return redirect(reverse('gas:home')) def new_entry(request): #TODO GET NEW ENTRY FORM RENDER gas:new_entry """ Render form to create a new entry. """ if not logged_in(request): return redirect(reverse('users:home')) if not has_car(request): return redirect(reverse("gas:new_car")) if 'active_car' not in request.session or not owns_car(request): request.session['active_car'] = Car.objects.filter(owner=User.objects.get(id=cur_usr_id(request))).first().id current_car = Car.objects.get(id=cur_car_id(request)) current_user = User.objects.get(id=cur_usr_id(request)) context = { "current_car": current_car, "all_cars": Car.objects.filter(owner=current_user), } return render(request, "gas_app/new_entry.html", context) def create_entry(request): #TODO SUBMIT NEW ENTRY FORM REDIRECT gas:create_entry """ POST form to create a new entry. """ if not logged_in(request): return redirect(reverse('users:home')) if not has_car(request): return redirect(reverse("gas:new_car")) if 'active_car' not in request.session or not owns_car(request): request.session['active_car'] = Car.objects.filter(owner=User.objects.get(id=cur_usr_id(request))).first().id errors = Entry.objects.validate(request.POST, cur_usr_id(request)) if errors: for key, value in errors.items(): messages.error(request, value, extra_tags=key) return redirect(reverse('gas:new_entry')) fields = { 'entry_date': request.POST['date'], 'odometer': int(request.POST['odometer']), 'gallons': float(request.POST['gallons']), 'price': float(request.POST['price']), 'creator': User.objects.get(id=cur_usr_id(request)), 'car': Car.objects.get(id=request.POST['car_select']) } Entry.objects.create(entry_date=fields['entry_date'], odometer=fields['odometer'], gallons=fields['gallons'], price=fields['price'], creator=fields['creator'], car=fields['car']) return redirect(reverse('gas:home')) def view_entry(request): #TODO GET ENTRY DATA RENDER gas:view_entry """ Renders information for a specific entry. Maybe unnecessary. """ if not logged_in(request): return redirect(reverse('users:home')) return redirect(reverse('gas:home')) def edit_entry(request, entry_id): #TODO GET EDIT ENTRY FORM RENDER gas:edit_entry """ Return form to edit user's most recent entry. """ if not logged_in(request): return redirect(reverse('users:home')) if not has_car(request): return redirect(reverse("gas:new_car")) if 'active_car' not in request.session or not owns_car(request): request.session['active_car'] = Car.objects.filter(owner=User.objects.get(id=cur_usr_id(request))).first().id current_car = Car.objects.get(id=cur_car_id(request)) current_user = User.objects.get(id=cur_usr_id(request)) entry = Entry.objects.get(id=entry_id) context = { "current_car": current_car, "all_cars": Car.objects.filter(owner=current_user), "entry": entry, } return render(request, "gas_app/new_entry.html", context) def update_entry(request, entry_id): #TODO POST EDIT ENTRY FORM REDIRECT gas:update_entry """ Updates an entry. """ if not logged_in(request): return redirect(reverse('users:home')) if not has_car(request): return redirect(reverse("gas:new_car")) if 'active_car' not in request.session or not owns_car(request): request.session['active_car'] = Car.objects.filter(owner=User.objects.get(id=cur_usr_id(request))).first().id errors = Entry.objects.validate(request.POST, cur_usr_id(request)) if errors: for key, value in errors.items(): messages.error(request, value, extra_tags=key) return redirect(reverse('gas:new_entry')) fields = { 'entry_date': request.POST['date'], 'odometer': int(request.POST['odometer']), 'gallons': float(request.POST['gallons']), 'price': float(request.POST['price']), } e = Entry.objects.filder(id=entry_id)[0] e.entry_date = fields['entry_date'] e.odometer = fields['odometer'] e.gallons = fields['gallons'] e.price = fields['price'] e.save() return redirect(reverse('gas:home')) def delete_entry(request): #TODO DELETE ENTRY REDIRECT gas:delete_entry """ Deletes an entry. """ if not logged_in(request): return redirect(reverse('users:home')) return redirect(reverse('gas:home')) def has_car(request): """ Checks if current user has a car. """ user = User.objects.get(id=cur_usr_id(request)) cars = Car.objects.filter(owner=user) if not cars: return False return True def cur_car_id(request): """ If there is an `active_car` in session, returns its ID. Otherwise, return none. """ if 'active_car' not in request.session: return None return request.session['active_car'] def owns_car(request): """ Check if the current user owns the currently active car. """ if 'current_user' not in request.session or 'active_car' not in request.session or not Car.objects.filter(id=cur_car_id(request)): return False user = User.objects.get(id=cur_usr_id(request)) car = Car.objects.get(id=cur_car_id(request)) if car.owner != user: return False return True
6c043811b2da3f373efa06bc8156705996b15ee9
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/adverbs/_never.py
d9002c9003bf7b8c0007df237bda667fddc3bf4d
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
393
py
#calss header class _NEVER(): def __init__(self,): self.name = "NEVER" self.definitions = [u'not at any time or not on any occasion: '] self.parents = [] self.childen = [] self.properties = [] self.jsondata = {} self.specie = 'adverbs' def run(self, obj1, obj2): self.jsondata[obj2] = {} self.jsondata[obj2]['properties'] = self.name.lower() return self.jsondata
9f281fc9d686425e97b54cdc34eb570c1fe19b42
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02709/s208022099.py
7c3413420f8ed9fc0b8a40a4b007da745e363f1f
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
681
py
from sys import stdin def main(): n = int(stdin.readline()) a = list(map(int, stdin.readline().split())) a2 = [[a[i], i] for i in range(n)] a2.sort(reverse=True) dp = [[0 for _ in range(n + 1)] for _ in range(n + 1)] ans = 0 for i in range(n + 1): for j in range(n + 1 - i): s1 = s2 = 0 if i > 0: s1 = dp[i - 1][j] + a2[i + j - 1][0] * (a2[i + j - 1][1] - (i - 1)) if j > 0: s2 = dp[i][j - 1] + a2[i + j - 1][0] * ((n - j) - a2[i + j - 1][1]) dp[i][j] = max(s1, s2) ans = max(ans, dp[i][n - i]) print(ans) if __name__ == "__main__": main()
6d13ea298a8c4814de41ef50e5ca2ebf16d19711
c9b5a2cd00764ee4a0b889b5b602eb28fd08e989
/python/238-Product of Array Except Self.py
600d5102cd52a0453255a55f78ed445ca39932d5
[]
no_license
cwza/leetcode
39799a6730185fa06913e3beebebd3e7b2e5d31a
72136e3487d239f5b37e2d6393e034262a6bf599
refs/heads/master
2023-04-05T16:19:08.243139
2021-04-22T04:46:45
2021-04-22T04:46:45
344,026,209
0
0
null
null
null
null
UTF-8
Python
false
false
1,258
py
from typing import List class Solution: # def productExceptSelf(self, nums: List[int]) -> List[int]: # "Precompute L, R product, Time: O(n), Space: O(n)" # n = len(nums) # # L[i]: product of nums[0, i-1] # L = [1]*n # for i in range(1, n): # L[i] = L[i-1] * nums[i-1] # # R[i]: product of nums[i+1, n] # R = [1]*n # for i in reversed(range(n-1)): # R[i] = R[i+1] * nums[i+1] # # print(L, R) # result = [1]*n # for i in range(n): # result[i] = L[i] * R[i] # return result def productExceptSelf(self, nums: List[int]) -> List[int]: "Use output list as R and Compute L on the fly, Time: O(n), Space: O(1) exclude space used by output" n = len(nums) R = [1]*n # This is also be used as result list for i in reversed(range(n-1)): R[i] = R[i+1] * nums[i+1] cur_L = 1 for i in range(n): R[i] = cur_L * R[i] cur_L = cur_L * nums[i] return R nums = [2,3,4,5] result = Solution().productExceptSelf(nums) assert result == [60,40,30,24] nums = [2,3,0,5] result = Solution().productExceptSelf(nums) assert result == [0,0,30,0]
9643919ae1a5dc615ce744d74202bb1f561257c6
01e4b8866f86791767013fb59e2eb02a73c1c923
/blog/migrations/0035_auto_20210504_2141.py
420b68338a37e00e4884c2098052f03fb3a712a2
[]
no_license
shiv958277/Blog-Website
c4feb6cbdca1eefbf20de9d4dc6f32fa9f8e2204
57dd54b37d7ecc9485eb9b760ab9566e63683d62
refs/heads/master
2023-05-04T04:13:17.223621
2021-05-29T11:06:38
2021-05-29T11:06:38
366,366,666
0
0
null
null
null
null
UTF-8
Python
false
false
527
py
# Generated by Django 3.0.8 on 2021-05-04 16:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0034_auto_20210504_2132'), ] operations = [ migrations.AddField( model_name='post', name='dislikes', field=models.IntegerField(default=0), ), migrations.AddField( model_name='post', name='likes', field=models.IntegerField(default=0), ), ]
239de711038d222c388248ee584d39770975bd23
d53bc632503254ca0d5099fe457c02c07212a131
/middleware1/testApp/middleware.py
acbf1c0c7c41b9e5d9f591e64615887737e2f158
[]
no_license
srikar1993/django
ba8428f6e1162cc40f2d034126e7baf29eb62edc
2199d5d94accc7bce5b3fac4a4b7b1444e39b35f
refs/heads/master
2023-07-14T21:10:52.654992
2021-08-26T06:37:04
2021-08-26T06:37:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,950
py
from django.http import HttpResponse class ExecutionFlowMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Pre processing of request print('This line is printed at pre-processing of request...') # Forwarding the request to next level response = self.get_response(request) # Post processing of request print('This line is printed at post-processing of request...') return response class AppMaintainanceMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return HttpResponse('<h1>Application Under Maintainance...</h1><h1>Please Try Again After Some Time</h1>') class ErrorMessageMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_exception(self, request, exception): mymsg = ''' <h1>Please check the input you have provided...</h1><hr> ''' exceptioninfo = f''' <h1>Raised Exception: {exception.__class__.__name__}</h1> <h1>Exception Message: {exception}</h1> ''' return HttpResponse(mymsg + exceptioninfo) class FirstMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Pre processing of request print('This line is printed by First Middleware at pre-processing of request...') # Forwarding the request to next level response = self.get_response(request) # Post processing of request print('This line is printed by First Middleware at post-processing of request...') return response class SecondMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Pre processing of request print('This line is printed by Second Middleware at pre-processing of request...') # Forwarding the request to next level response = self.get_response(request) # Post processing of request print('This line is printed by Second Middleware at post-processing of request...') return response class ThirdMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Pre processing of request print('This line is printed by Third Middleware at pre-processing of request...') # Forwarding the request to next level response = self.get_response(request) # Post processing of request print('This line is printed by Third Middleware at post-processing of request...') return response
12d4e303ec37dc162f5cd4b655c882bf2ae8429b
0b77f11bfb68d465e99fdfcea8bef63013409df8
/reports/views.py
e7046593d76822fccfcdfe0b0bab740325b0bb42
[]
no_license
dbsiavichay/furb
dea1de7d3085bd41a668a6581a4997ff50a58afe
36dea81c23d614bceaf35b38a5861a2ca095ea98
refs/heads/master
2020-06-28T06:05:42.313533
2019-03-14T15:37:20
2019-03-14T15:37:20
74,506,200
0
0
null
null
null
null
UTF-8
Python
false
false
7,486
py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.shortcuts import render from django.http import HttpResponse from django.views.generic import ListView, TemplateView from wildlife.models import Animal, Kind from location.models import Parish from django.conf import settings from os.path import isfile, join from io import BytesIO from reportlab.lib import colors from reportlab.lib.pagesizes import A4, landscape from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import SimpleDocTemplate, Paragraph, TableStyle, Table, Image from reportlab.lib.units import cm, mm from wildlife.views import get_letterhead_page, NumberedCanvas class ParishListView(ListView): model = Parish template_name = 'reports/animal_by_parish.html' queryset = Parish.objects.filter(canton_code='1401') class StatsListView(ListView): model = Parish template_name = 'reports/animal_stats.html' queryset = Parish.objects.filter(canton_code='1401') def get_context_data(self, **kwargs): from datetime import date context = super(StatsListView, self).get_context_data(**kwargs) years = range(2017, date.today().year + 1) months = [ (1, 'ENERO'), (2, 'FEBRERO'), (3, 'MARZO'), (4, 'ABRIL'), (5, 'MAYO'), (6, 'JUNIO'), (7, 'JULIO'), (8, 'AGOSTO'), (9, 'SEPTIEMBRE'), (10, 'OCTUBRE'), (11, 'NOVIEMBRE'), (12, 'DICIEMBRE'), ] context.update({ 'months': months, 'years':years, }) return context def get_by_parish(request, parish): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename=reporte.pdf' sterilized = request.GET.get('sterilized', False) pdf = get_animal_by_parish_report(parish, sterilized) response.write(pdf) return response def get_animal_stats(request, month, year): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename=reporte.pdf' pdf = get_chart_by_month(month, year) response.write(pdf) return response def get_animal_by_parish_report(parish, sterilized): animals = Animal.objects.filter(parish=parish).order_by('owner') if sterilized: animals = animals.filter(want_sterilize=True) buff = BytesIO() doc = SimpleDocTemplate(buff,pagesize=A4,rightMargin=60, leftMargin=40, topMargin=75, bottomMargin=50,) styles = getSampleStyleSheet() path = join(settings.BASE_DIR, 'static/assets/report/checked.png') report = [ Paragraph("DIRECCIÓN DE GESTION AMBIENTAL Y SERVICIOS PÚBLICOS", styles['Title']), Paragraph("REPORTE DE FAUNA POR PARROQUIA", styles['Title']), ] tstyle = TableStyle([ ('LINEBELOW',(0,0),(-1,-1),0.1, colors.gray), ('TOPPADDING',(0,0),(-1,-1), 5), ('BOTTOMPADDING',(0,0),(-1,-1), 0), ('LEFTPADDING',(0,0),(-1,-1), 0), ('RIGHTPADDING',(0,0),(-1,-1), 0), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ]) # tstyle = TableStyle([ # ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), # ('LEFTPADDING',(0,0),(-1,-1), 3), # ('RIGHTPADDING',(0,0),(-1,-1), 3), # ('BOTTOMPADDING',(0,0),(-1,-1), 0), # ('BOX', (0, 0), (-1, -1), 0.5, colors.black), # ('ALIGN',(0,0),(0,-1),'RIGHT'), # ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), # ('BACKGROUND', (0, 0), (-1, 0), colors.gray) # ]) headingStyle = styles['Heading5'] headingStyle.fontSize = 6 contentStyle = styles['BodyText'] contentStyle.fontSize = 5 columns_width = [0.5*cm, 1.4*cm, 2.5*cm,1.2*cm,1.8*cm,1.5*cm,4.5*cm,3*cm] headings = ('N°', 'CÓDIGO', 'NOMBRE','ESPECIE', 'ESTERILIZAR?', 'UBICACIÓN', 'PROPIETARIO', 'CONTACTO') headings = (Paragraph(h, headingStyle) for h in headings) content = [( Paragraph(str(index + 1), contentStyle), Paragraph(animal.code, contentStyle), Paragraph(animal.name.title(), contentStyle), Paragraph(animal.breed.kind.name.title(), contentStyle), Image(path, width=2.5*mm, height=2.5*mm) if animal.want_sterilize else Paragraph('', contentStyle), Paragraph(animal.get_parish_name().title(), contentStyle), Paragraph(animal.get_owner_name().title(), contentStyle), Paragraph(animal.get_owner_contact().title(), contentStyle), ) for index, animal in enumerate(animals)] if len(animals) else [('Sin datos.',)] table = Table([headings] + content, columns_width, style=tstyle, ) report.append(table) doc.build(report,canvasmaker=NumberedCanvas,onFirstPage=get_letterhead_page,onLaterPages=get_letterhead_page) return buff.getvalue() def get_chart_by_month(month, year): buff = BytesIO() months = [ 'ENERO','FEBRERO','MARZO','ABRIL', 'MAYO','JUNIO','JULIO','AGOSTO', 'SEPTIEMBRE','OCTUBRE','NOVIEMBRE','DICIEMBRE', ] doc = SimpleDocTemplate(buff,pagesize=A4,rightMargin=60, leftMargin=40, topMargin=75, bottomMargin=50,) styles = getSampleStyleSheet() report = [ Paragraph("DIRECCIÓN DE GESTION AMBIENTAL Y SERVICIOS PÚBLICOS", styles['Title']), Paragraph('REPORTE ESTADISTICO %s %s' % (months[int(month)-1],year), styles['Title']), ] parishes = Parish.objects.filter(canton_code='1401') kinds = Kind.objects.all() for kind in kinds: _animals = Animal.objects.filter( breed__kind=kind, date_joined__year = int(year), date_joined__month = int(month) ) data = [] labels = [] for parish in parishes: animals = _animals.filter(parish=parish.code) if len(animals) > 0: percent = (len(animals) * 100.00) / len(_animals) data.append(len(animals)) labels.append('%s (%0.2f%%)' % (parish.name.encode('utf-8'), percent)) if len(data) > 0: report.append(Paragraph(kind.name, styles['Heading3'])) chart = create_pie_chart(data, labels, True) report.append(chart) doc.build(report,canvasmaker=NumberedCanvas,onFirstPage=get_letterhead_page,onLaterPages=get_letterhead_page) return buff.getvalue() colores = [ colors.HexColor('#7fffd4'), colors.HexColor('#0000ff'), colors.HexColor('#a52a2a'), colors.HexColor('#ff7f50'), colors.HexColor('#a9a9a9'), colors.HexColor('#008b8b'), colors.HexColor('#8b0000'), colors.HexColor('#ff00ff'), colors.HexColor('#00008b'), colors.HexColor('#008000'), colors.HexColor('#adff2f'), colors.HexColor('#00ff00'), colors.HexColor('#ff00ff'), colors.HexColor('#ffa500'), colors.HexColor('#ff0000'), colors.HexColor('#ee82ee'), colors.HexColor('#ffff00'), ] def add_legend(draw_obj, chart, data): from reportlab.graphics.charts.legends import Legend from reportlab.lib.validators import Auto legend = Legend() legend.alignment = 'right' legend.x = 90 legend.y = 50 legend.colorNamePairs = [(chart.slices[i].fillColor, (chart.labels[i].split('(')[0], '%s' % chart.data[i])) for i in range(0, len(data))] draw_obj.add(legend) def create_pie_chart(data, labels, legend=False): from reportlab.graphics.charts.piecharts import Pie from reportlab.graphics.shapes import Drawing d = Drawing(250, 275) pie = Pie() # required by Auto pie._seriesCount = len(data) pie.x = 175 pie.y = 100 pie.width = 150 pie.height = 150 pie.data = data pie.labels = labels pie.simpleLabels = 0 pie.sideLabels = True pie.slices.strokeWidth = 0.5 for i in range (0, len(colores)): pie.slices[i].fillColor = colores[i] if legend: add_legend(d, pie, data) d.add(pie) #d.save(formats=['pdf'], outDir='.', fnRoot='test-pie') return d
a23647b52f355989359adaa6265a6bedbe23c029
64bf39b96a014b5d3f69b3311430185c64a7ff0e
/intro-ansible/venv3/lib/python3.8/site-packages/ansible_collections/fortinet/fortios/plugins/modules/fortios_system_replacemsg_image.py
f4603def9e807083a0568dc573aa96c96a7409b3
[ "MIT" ]
permissive
SimonFangCisco/dne-dna-code
7072eba7da0389e37507b7a2aa5f7d0c0735a220
2ea7d4f00212f502bc684ac257371ada73da1ca9
refs/heads/master
2023-03-10T23:10:31.392558
2021-02-25T15:04:36
2021-02-25T15:04:36
342,274,373
0
0
MIT
2021-02-25T14:39:22
2021-02-25T14:39:22
null
UTF-8
Python
false
false
9,507
py
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019-2020 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: fortios_system_replacemsg_image short_description: Configure replacement message images in Fortinet's FortiOS and FortiGate. description: - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the user to set and modify system feature and replacemsg_image category. Examples include all parameters and values need to be adjusted to datasources before usage. Tested with FOS v6.0.0 version_added: "2.9" author: - Link Zheng (@chillancezen) - Jie Xue (@JieX19) - Hongbin Lu (@fgtdev-hblu) - Frank Shen (@frankshen01) - Miguel Angel Munoz (@mamunozgonzalez) - Nicolas Thomas (@thomnico) notes: - Legacy fortiosapi has been deprecated, httpapi is the preferred way to run playbooks requirements: - ansible>=2.9.0 options: access_token: description: - Token-based authentication. Generated from GUI of Fortigate. type: str required: false vdom: description: - Virtual domain, among those defined previously. A vdom is a virtual instance of the FortiGate that can be configured and used as a different unit. type: str default: root state: description: - Indicates whether to create or remove the object. type: str required: true choices: - present - absent system_replacemsg_image: description: - Configure replacement message images. default: null type: dict suboptions: image_base64: description: - Image data. type: str image_type: description: - Image type. type: str choices: - gif - jpg - tiff - png name: description: - Image name. required: true type: str ''' EXAMPLES = ''' - hosts: fortigates collections: - fortinet.fortios connection: httpapi vars: vdom: "root" ansible_httpapi_use_ssl: yes ansible_httpapi_validate_certs: no ansible_httpapi_port: 443 tasks: - name: Configure replacement message images. fortios_system_replacemsg_image: vdom: "{{ vdom }}" state: "present" access_token: "<your_own_value>" system_replacemsg_image: image_base64: "<your_own_value>" image_type: "gif" name: "default_name_5" ''' RETURN = ''' build: description: Build number of the fortigate image returned: always type: str sample: '1547' http_method: description: Last method used to provision the content into FortiGate returned: always type: str sample: 'PUT' http_status: description: Last result given by FortiGate on last operation applied returned: always type: str sample: "200" mkey: description: Master key (id) used in the last call to FortiGate returned: success type: str sample: "id" name: description: Name of the table used to fulfill the request returned: always type: str sample: "urlfilter" path: description: Path of the table used to fulfill the request returned: always type: str sample: "webfilter" revision: description: Internal revision number returned: always type: str sample: "17.0.2.10658" serial: description: Serial number of the unit returned: always type: str sample: "FGVMEVYYQT3AB5352" status: description: Indication of the operation's result returned: always type: str sample: "success" vdom: description: Virtual domain used returned: always type: str sample: "root" version: description: Version of the FortiGate returned: always type: str sample: "v5.6.3" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import Connection from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import FortiOSHandler from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import check_legacy_fortiosapi from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import FAIL_SOCKET_MSG def filter_system_replacemsg_image_data(json): option_list = ['image_base64', 'image_type', 'name'] dictionary = {} for attribute in option_list: if attribute in json and json[attribute] is not None: dictionary[attribute] = json[attribute] return dictionary def underscore_to_hyphen(data): if isinstance(data, list): for i, elem in enumerate(data): data[i] = underscore_to_hyphen(elem) elif isinstance(data, dict): new_data = {} for k, v in data.items(): new_data[k.replace('_', '-')] = underscore_to_hyphen(v) data = new_data return data def system_replacemsg_image(data, fos): vdom = data['vdom'] state = data['state'] system_replacemsg_image_data = data['system_replacemsg_image'] filtered_data = underscore_to_hyphen(filter_system_replacemsg_image_data(system_replacemsg_image_data)) if state == "present": return fos.set('system', 'replacemsg-image', data=filtered_data, vdom=vdom) elif state == "absent": return fos.delete('system', 'replacemsg-image', mkey=filtered_data['name'], vdom=vdom) else: fos._module.fail_json(msg='state must be present or absent!') def is_successful_status(status): return status['status'] == "success" or \ status['http_method'] == "DELETE" and status['http_status'] == 404 def fortios_system(data, fos): if data['system_replacemsg_image']: resp = system_replacemsg_image(data, fos) else: fos._module.fail_json(msg='missing task body: %s' % ('system_replacemsg_image')) return not is_successful_status(resp), \ resp['status'] == "success" and \ (resp['revision_changed'] if 'revision_changed' in resp else True), \ resp def main(): mkeyname = 'name' fields = { "access_token": {"required": False, "type": "str", "no_log": True}, "vdom": {"required": False, "type": "str", "default": "root"}, "state": {"required": True, "type": "str", "choices": ["present", "absent"]}, "system_replacemsg_image": { "required": False, "type": "dict", "default": None, "options": { "image_base64": {"required": False, "type": "str"}, "image_type": {"required": False, "type": "str", "choices": ["gif", "jpg", "tiff", "png"]}, "name": {"required": True, "type": "str"} } } } check_legacy_fortiosapi() module = AnsibleModule(argument_spec=fields, supports_check_mode=False) versions_check_result = None if module._socket_path: connection = Connection(module._socket_path) if 'access_token' in module.params: connection.set_option('access_token', module.params['access_token']) fos = FortiOSHandler(connection, module, mkeyname) is_error, has_changed, result = fortios_system(module.params, fos) versions_check_result = connection.get_system_version() else: module.fail_json(**FAIL_SOCKET_MSG) if versions_check_result and versions_check_result['matched'] is False: module.warn("Ansible has detected version mismatch between FortOS system and galaxy, see more details by specifying option -vvv") if not is_error: if versions_check_result and versions_check_result['matched'] is False: module.exit_json(changed=has_changed, version_check_warning=versions_check_result, meta=result) else: module.exit_json(changed=has_changed, meta=result) else: if versions_check_result and versions_check_result['matched'] is False: module.fail_json(msg="Error in repo", version_check_warning=versions_check_result, meta=result) else: module.fail_json(msg="Error in repo", meta=result) if __name__ == '__main__': main()
008c2410559f5c90fba341e155a2373e0d7ed56d
f6d0779fa4dc7f2d15f6b6e8c5e8f58788d4ea68
/cornerHarris/cornerHarris.py
862fee2bfc19501f666ec81d502e1d6c9ff7c099
[]
no_license
jjmmll0727/Graphics2
b49a4bc1370fa0bf3c79fdc4a4c3068740ccdf20
6685affe24f91814c3a92ee775e7001e2150a20c
refs/heads/master
2023-04-21T20:55:54.363003
2021-05-11T01:05:38
2021-05-11T01:05:38
262,746,857
0
0
null
null
null
null
UTF-8
Python
false
false
783
py
import cv2 import numpy as np filename = 'chess2.jpg' img = cv2.imread(filename) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) gray = np.float32(gray) dst = cv2.cornerHarris(gray,7,11,0.01) # ksize 가 클수록 특징점으로 추출되는 값이 많아져 # k가 작을수록 더 많이 추출된다 # block size가 클수록 더 많이 추출된다 # --> 더 많이 추출된다는 의미는 정해진 임계값보다 큰 특징 가능성 값이 많다는 뜻 + 이웃화소 보다 큰 값이 많다는 뜻 #result is dilated for marking the corners, not important dst = cv2.dilate(dst,None) # Threshold for an optimal value, it may vary depending on the image. img[dst>0.01*dst.max()]=[0,0,255] cv2.imshow('dst',img) if cv2.waitKey(0) & 0xff == 27: cv2.destroyAllWindows()
01f55eaa1dce56a464b611a1c9d81f93a1b1b74f
6f1f5bb1d495dcc9e3a3a8a9b333813c88d01704
/lbfgsb.py
c0d4b907a8cb8e0e89379cf5b784e997547a93e5
[]
no_license
mwhoffman/mogmdp
f9a7a954f7672bfb8c739c5519ddba5b336941a5
d45958d2c874c67c13b056f530d84dcf5f158d7c
refs/heads/master
2021-01-22T23:48:05.714520
2012-05-23T23:48:02
2012-05-23T23:48:02
4,611,353
1
1
null
null
null
null
UTF-8
Python
false
false
5,667
py
## Copyright (c) 2004 David M. Cooke <[email protected]> ## Modifications by Travis Oliphant and Enthought, Inc. for inclusion in SciPy ## Further modifications by M. Hoffman. ## Permission is hereby granted, free of charge, to any person obtaining a copy of ## this software and associated documentation files (the "Software"), to deal in ## the Software without restriction, including without limitation the rights to ## use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies ## of the Software, and to permit persons to whom the Software is furnished to do ## so, subject to the following conditions: ## The above copyright notice and this permission notice shall be included in all ## copies or substantial portions of the Software. ## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ## SOFTWARE. import numpy as np import scipy.optimize._lbfgsb as _lbfgsb def lbfgsb(func, x0, bounds=None, m=10, factr=1e7, pgtol=1e-5, maxfun=100): """ Minimize a function func using the L-BFGS-B algorithm. Arguments: func -- function to minimize. Called as func(x, *args) x0 -- initial guess to minimum bounds -- a list of (min, max) pairs for each element in x, defining the bounds on that parameter. Use None for one of min or max when there is no bound in that direction m -- the maximum number of variable metric corrections used to define the limited memory matrix. (the limited memory BFGS method does not store the full hessian but uses this many terms in an approximation to it). factr -- The iteration stops when (f^k - f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= factr*epsmch where epsmch is the machine precision, which is automatically generated by the code. Typical values for factr: 1e12 for low accuracy; 1e7 for moderate accuracy; 10.0 for extremely high accuracy. pgtol -- The iteration will stop when max{|proj g_i | i = 1, ..., n} <= pgtol where pg_i is the ith component of the projected gradient. maxfun -- maximum number of function evaluations. License of L-BFGS-B (Fortran code) ================================== The version included here (in fortran code) is 2.1 (released in 1997). It was written by Ciyou Zhu, Richard Byrd, and Jorge Nocedal <[email protected]>. It carries the following condition for use: This software is freely available, but we expect that all publications describing work using this software , or all commercial products using it, quote at least one of the references given below. References * R. H. Byrd, P. Lu and J. Nocedal. A Limited Memory Algorithm for Bound Constrained Optimization, (1995), SIAM Journal on Scientific and Statistical Computing , 16, 5, pp. 1190-1208. * C. Zhu, R. H. Byrd and J. Nocedal. L-BFGS-B: Algorithm 778: L-BFGS-B, FORTRAN routines for large scale bound constrained optimization (1997), ACM Transactions on Mathematical Software, Vol 23, Num. 4, pp. 550 - 560. """ n = len(x0) if bounds is None: bounds = [(None,None)] * n if len(bounds) != n: raise ValueError('length of x0 != length of bounds') nbd = np.zeros((n,), np.int32) low_bnd = np.zeros((n,), np.float64) upper_bnd = np.zeros((n,), np.float64) bounds_map = {(None, None): 0, (1, None): 1, (1, 1): 2, (None, 1): 3} for i in range(0, n): l,u = bounds[i] if l is not None: low_bnd[i] = l l = 1 if u is not None: upper_bnd[i] = u u = 1 nbd[i] = bounds_map[l, u] wa = np.zeros((2*m*n + 4*n + 12*m**2 + 12*m,), np.float64) iwa = np.zeros((3*n,), np.int32) task = np.zeros(1, 'S60') csave = np.zeros(1, 'S60') lsave = np.zeros((4, ), np.int32) isave = np.zeros((44,), np.int32) dsave = np.zeros((29,), np.float64) # allocate space for our path. ns = np.empty(maxfun+1, np.int32) xs = np.empty((maxfun+1, n), np.float64) fs = np.empty(maxfun+1, np.float64) gs = np.empty((maxfun+1, n), np.float64) # initialize the first step. x = np.array(x0, np.float64) f, g = func(x) ns[0], xs[0], fs[0], gs[0] = 0, x, f, g i = 1 numevals = 0 task[:] = 'START' while 1: _lbfgsb.setulb(m, x, low_bnd, upper_bnd, nbd, f, g, factr, pgtol, wa, iwa, task, -1, csave, lsave, isave, dsave) task_str = task.tostring() if task_str.startswith('FG'): # minimization routine wants f and g at the current x numevals += 1 f, g = func(x) elif task_str.startswith('NEW_X'): # new iteration ns[i], xs[i], fs[i], gs[i] = numevals, x, f, g i += 1 if numevals > maxfun: task[:] = 'STOP: TOTAL NO. of f AND g EVALUATIONS EXCEEDS LIMIT' else: break ns.resize(i) xs.resize((i, n)) fs.resize(i) gs.resize((i, n)) return x, f, dict(numevals=ns, x=xs, f=fs, g=gs)
7fb23836dea8df7c484419d39675673ff83ad1f1
2b3bed35a29bfd46d660e0c7ccad84416c76e5a2
/python/Activity_8.py
a561a351665c5d8661db11834c9644e8b16a4d9d
[]
no_license
Sreevara-lab/sdet
76a738dbeb91df6e2bff659ac6e8e2955517758e
e9bcfba1509b3cfa4ca64dd8c3846c9b0faefefd
refs/heads/main
2023-03-13T08:47:51.836330
2021-02-28T13:51:54
2021-02-28T13:51:54
336,749,624
0
0
null
2021-02-07T09:33:34
2021-02-07T09:33:34
null
UTF-8
Python
false
false
199
py
numList = [10, 20, 30, 40, 30] print("Given list is ", numList) firstElement = numList[0] lastElement = numList[-1] if (firstElement == lastElement): print(True) else: print(False)
81c308f3ade80af4440ab54a616b1b51236893cf
d7b3a0ae3b10f652459d9924771eda36a760b710
/apps/account/models.py
07ac8cdca386d8106c71241e9da8be62ba487351
[]
no_license
pooyamoini/web-project-backend
f81c0439b286b8b863ddfd074001dc859c8c921e
047edec3489bd2dbe9d3b9a06427941c1b055a12
refs/heads/master
2020-12-15T01:38:46.262769
2020-02-11T13:42:56
2020-02-11T13:42:56
234,946,642
1
0
null
2020-02-03T11:51:36
2020-01-19T18:37:01
Python
UTF-8
Python
false
false
1,075
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import datetime from django.db import models class AccountBasic(models.Model): username = models.CharField( max_length=15, null=False, primary_key=True, default="") name = models.CharField(max_length=40, null=False, default="") email = models.CharField(max_length=50, null=False, default="") password = models.CharField(max_length=200, null=False, default="") profile = models.CharField(max_length=100, default="") gender = models.CharField(max_length=20, default="") bio = models.CharField(max_length=500, default="") phone_number = models.BigIntegerField(default=0) country = models.CharField(max_length=20, default="") def __str__(self): return(self.name) class LoggInBasic(models.Model): account = models.ForeignKey( AccountBasic, primary_key=True, on_delete=models.CASCADE) token = models.CharField(max_length=110) token_gen_time = models.DateTimeField(auto_now=True) def __str__(self): return self.account.name
e920f9b21c0903e46af65c35a389422f3de893e0
bda65504f30285ee7c2edfef789f19d6b0a4da25
/src/spell checker/statefulRNNCell.py
e1dea2b54407b88d29f6165e9c0d5a1ee3d3d1ac
[]
no_license
RNN-Test/RNN-Test
c18fa8c584095096d64218a6ad0dd64b5d11a534
a7731d668d29e32c03a4c3bdd92a977145d6ac44
refs/heads/master
2022-04-07T18:14:21.561752
2022-03-29T12:43:06
2022-03-29T12:43:06
245,039,708
8
3
null
null
null
null
UTF-8
Python
false
false
551
py
import tensorflow as tf class StatefulRNNCell(tf.nn.rnn_cell.RNNCell): def __init__(self, inner_cell): super(StatefulRNNCell, self).__init__() self._inner_cell = inner_cell @property def state_size(self): return self._inner_cell.state_size @property def output_size(self): return self._inner_cell.state_size def call(self, input, *args, **kwargs): output, next_state = self._inner_cell(input, *args, **kwargs) emit_output = next_state return emit_output, next_state
4c6c5d18a00823a83ef35c263e076351815ec55a
98591a80b7881385dc15a7aee3298aed68efbc32
/MODEL1302010025/model.py
7776531980fb768cf4985182c7a6bdc908a3c3e7
[ "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
biomodels/MODEL1302010025
9f49612839a3c29dd8034bf17a58a6caa3e1a8eb
852113c7356661180c266a701e56dc8bc789a898
refs/heads/master
2020-12-24T14:44:47.764710
2014-10-16T05:57:03
2014-10-16T05:57:03
null
0
0
null
null
null
null
UTF-8
Python
false
false
427
py
import os path = os.path.dirname(os.path.realpath(__file__)) sbmlFilePath = os.path.join(path, 'MODEL1302010025.xml') with open(sbmlFilePath,'r') as f: sbmlString = f.read() def module_exists(module_name): try: __import__(module_name) except ImportError: return False else: return True if module_exists('libsbml'): import libsbml sbml = libsbml.readSBMLFromString(sbmlString)
b614b1cddfff224c044d48a2c548725eaceab370
c6a053873e7936744f06fb739210c1d0e5bdaf3e
/Credicoop_dashboard/funciones_para_dashboard/pagina_inicio.py
5d86496bfe0326d544cdf6c4fc5eb98e6badaebd
[]
no_license
sebasur90/Dashboard-Banco-Credicoop
e35c48ffc9aa8601ec4c18c4f33f9da06c2e2704
04f2445712d08bae688b3091b577f14de0a05a30
refs/heads/main
2023-07-08T02:43:31.764893
2021-08-12T00:19:38
2021-08-12T00:19:38
395,142,970
0
0
null
null
null
null
UTF-8
Python
false
false
5,458
py
from funciones_para_dashboard import clases import dash_html_components as html import pathlib import dash_bootstrap_components as dbc from datetime import datetime mov = clases.Movimientos() mov = mov.datos def total_dias(): fecha_inicio = mov.sort_values( by=['fecha']).reset_index(drop=True).fecha.iloc[0] fecha_inicio = datetime.strptime(fecha_inicio, '%Y-%m-%d') fecha_actual = datetime.now() fecha_total_dias = (fecha_actual-fecha_inicio).days fecha_total_anos = round((fecha_actual-fecha_inicio).days/365) fecha_total_meses = round((fecha_actual-fecha_inicio).days/30) return fecha_total_dias, fecha_total_anos, fecha_total_meses def total_datos(): return len(mov) def sumas(): cred_usd = round(mov.credito_usd_ccl.sum()) cred_p = round(mov.credito.sum()) deb_usd = round(mov.debito_usd_ccl.sum()) deb_p = round(mov.debito.sum()) return cred_usd, cred_p, deb_usd, deb_p def ultima_fecha_informada(): fecha = mov.sort_values(by=['fecha']).reset_index(drop=True).fecha.iloc[-1] return fecha def ultimo_valor_dolar(): dolar = round(mov.sort_values(by=['fecha']).reset_index( drop=True).ccl.iloc[-1], 2) return dolar layout = html.Div([ html.H1("Dashboard Credicoop", className='titulo'), html.Div([dbc.CardDeck([ dbc.Card( dbc.CardBody( [html.P("Total datos", className="card-text"), html.H2(total_datos(), className="card-dato"), ])), dbc.Card( dbc.CardBody( [html.P("Total dias transcurridos", className="card-text", ), html.H2(total_dias()[0], className="card-dato"), ])), dbc.Card( dbc.CardBody( [html.P("Total ingresos en USD", className="card-text", ), html.H2(sumas()[0], className="card-dato"), html.P("en pesos \n" + str(sumas()[1]), className="card-text", ), ])), dbc.Card( dbc.CardBody( [html.P("Cotizacion dolar CCL", className="card-text", ), html.H2(ultimo_valor_dolar(), className="card-dato"), ] ) ), ], className="div_tarjetas_deck" )], className="div_tarjetas_1"), html.Div([ dbc.CardDeck( [ dbc.Card( [ dbc.CardBody( [ html.H4( "Ingresos", className="card-title"), html.P( "Sueldos historicos y graficos comparativos en pesos y en dolar contado" "con liquidacion. " "Mapas de calor y mas...", className="card-text", ), dbc.Button("Ingresar", color="primary", href="/pagina_ingresos", className="boton_ir_pagina"), ] ), ], style={"width": "30rem"} ), dbc.Card( [ dbc.CardBody( [ html.H4("Egresos", className="card-title"), html.P( "Gastos historicos y graficos comparativos de su evolucion en el tiempo ", className="card-text", ), dbc.Button("Ingresar", color="primary", href="/pagina_egresos", className="boton_ir_pagina"), ] ), ], style={"width": "30rem"} ), dbc.Card( [ dbc.CardBody( [ html.H4("Movimientos", className="card-title"), html.P( "Detalle de movimientos de cuenta historicos. ", className="card-text", ), dbc.Button("Ingresar", color="primary", href="/movimientos", id="boton_ir_pagina"), ] ), ], style={"width": "30rem"} ) ])], className="div_tarjetas_2") ], className="fondo_inicio")
f4b252b91213c7a7b29801bbe7e8c5abe9637ff7
954cf0306f6b321519e25527d60f3901c40bf9a8
/test.py
bf5f4c4e948080e708e249e576396742a74df19e
[]
no_license
Lijer/self_rep_od
8e1c12f2f3b46a7c37267d2e183e7687832ad7e4
14da7dc7f304f9e9d65f66dce0c934baf96acd30
refs/heads/master
2022-12-17T10:35:58.584909
2020-09-22T07:59:16
2020-09-22T07:59:16
295,289,057
0
0
null
2020-09-22T07:59:17
2020-09-14T03:02:45
null
UTF-8
Python
false
false
3,750
py
""" Author: Bill Wang """ import argparse import numpy as np import torch from rdp_tree import RDPTree from util import dataLoading, aucPerformance, tic_time def arg_parse(verbose=True): parser = argparse.ArgumentParser() parser.add_argument('--data-path', dest='data_path', type=str, default="data/apascal.csv") parser.add_argument('--load-path', dest='load_path', type=str, default="save_model/") parser.add_argument('--method', dest='testing_method', type=str, default='last_layer', choices=['last_layer', 'first_layer', 'level']) parser.add_argument('--out-c', dest='out_c', type=int, default=50) parser.add_argument('--tree-depth', dest='tree_depth', type=int, default=8) parser.add_argument('--forest-Tnum', dest='forest_Tnum', type=int, default=30) parser.add_argument('--dropout-r', dest='dropout_r', type=float, default=0.1) parser.add_argument('--criterion', dest='criterion', type=str, default='distance', choices=['distance', 'lof', 'iforest']) args_parsed = parser.parse_args() if verbose: message = '' message += '-------------------------------- Args ------------------------------\n' for k, v in sorted(vars(args_parsed).items()): comment = '' default = parser.get_default(k) if v != default: comment = '\t[default: %s]' % str(default) message += '{:>35}: {:<30}{}\n'.format(str(k), str(v), comment) message += '-------------------------------- End ----------------------------------' print(message) return args_parsed # data_path = "data/apascal.csv" # # load_path = "save_model/" # out_c = 50 # USE_GPU = True # tree_depth = 8 # forest_Tnum = 30 # dropout_r = 0.1 # count from 1 # Set mode # dev_flag = True # if dev_flag: # print("Running in DEV_MODE!") # else: # # running on servers # print("Running in SERVER_MODE!") # data_path = sys.argv[1] # load_path = sys.argv[2] # tree_depth = int(sys.argv[3]) # testing_method = int(sys.argv[4]) def main(): args = arg_parse() # testing_methods_set = ['last_layer', 'first_layer', 'level'] # testing_method = 1 USE_GPU = torch.cuda.is_available() svm_flag = False if 'svm' in args.data_path: svm_flag = True from util import get_data_from_svmlight_file x, labels = get_data_from_svmlight_file(args.data_path) else: x, labels = dataLoading(args.data_path) data_size = labels.size # build forest forest = [] for i in range(args.forest_Tnum): forest.append(RDPTree(t_id=i + 1, tree_depth=args.tree_depth, )) sum_result = np.zeros(data_size, dtype=np.float64) print("Init tic time.") tic_time() # testing process for i in range(args.forest_Tnum): print("tree id:", i, "tic time.") tic_time() x_level, first_level_scores = forest[i].testing_process( x=x, out_c=args.out_c, USE_GPU=USE_GPU, load_path=args.load_path, dropout_r=args.dropout_r, testing_method=args.testing_method, svm_flag=svm_flag, criterion=args.criterion ) if args.testing_method == 'level': sum_result += x_level else: sum_result += first_level_scores print("tree id:", i, "tic time.") tic_time() scores = sum_result / args.forest_Tnum # clf = LocalOutlierFactor(novelty=True) # clf.fit(x) # scores = 1-clf.decision_function(x) aucPerformance(scores, labels) if __name__ == "__main__": main()
9e413afbb346364226c83f487e7d7eb9c8140cad
051c349298163f3ffd623e50baeea4efa14c89dd
/Pacman/searchAgents.py
187801b323c83b60fbf47053bfce0c82eb6f9f1f
[]
no_license
lewislin3/AI-Pacman
23ea6d75f55f3f70c2df913aad2890e04deac480
b95350b473e002eab8fc4656ba914305f69132ce
refs/heads/master
2021-01-20T01:43:59.528273
2017-04-25T05:51:32
2017-04-25T05:51:32
89,322,390
0
0
null
null
null
null
UTF-8
Python
false
false
25,030
py
# searchAgents.py # --------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to http://ai.berkeley.edu. # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). """ This file contains all of the agents that can be selected to control Pacman. To select an agent, use the '-p' option when running pacman.py. Arguments can be passed to your agent using '-a'. For example, to load a SearchAgent that uses depth first search (dfs), run the following command: > python pacman.py -p SearchAgent -a fn=depthFirstSearch Commands to invoke other search strategies can be found in the project description. Please only change the parts of the file you are asked to. Look for the lines that say "*** YOUR CODE HERE ***" The parts you fill in start about 3/4 of the way down. Follow the project description for details. Good luck and happy searching! """ from game import Directions from game import Agent from game import Actions import util import time import search class GoWestAgent(Agent): "An agent that goes West until it can't." def getAction(self, state): "The agent receives a GameState (defined in pacman.py)." if Directions.WEST in state.getLegalPacmanActions(): return Directions.WEST else: return Directions.STOP "P1-1" class CleanerAgent(Agent): "The floor is too dirty." def getAction(self, state): pos=state.getPacmanPosition() if state.hasFood(pos[0]+1,pos[1]): return Directions.EAST if state.hasFood(pos[0],pos[1]-1): return Directions.SOUTH if state.hasFood(pos[0]-1,pos[1]): return Directions.WEST if state.hasFood(pos[0],pos[1]+1): return Directions.NORTH return Directions.STOP "P1-2" class FroggerAgent(Agent): "It's dangerous to cross streets with eyes closed." def getAction(self, state): ppos=state.getPacmanPosition() gpos=state.getGhostPosition(1) qpos=state.getGhostPosition(2) #print(ppos,gpos,qpos) if ppos[0]==5 and (ppos[1]==qpos[1] or ppos[1]+1==qpos[1] or ppos[1]-1==qpos[1]): return Directions.STOP elif ppos[1]==8 and ppos[0]!=3 : return Directions.EAST elif ppos[0]==8 and ppos[1]==2: return Directions.SOUTH elif ppos[1]==2: return Directions.EAST elif ppos[1]-1==gpos[1] and (ppos[0]==gpos[0] or ppos[0]-1==gpos[0] or ppos[0]+1==gpos[0]) : return Directions.STOP else: return Directions.SOUTH return Directions.STOP "P1-3" class SnakeAgent(Agent): "But you don't have a sneaking suit." def getAction(self, state): "The agent receives a GameState (defined in pacman.py)." "[Project 1] YOUR CODE HERE" ppos=state.getPacmanPosition() gpos=state.getGhostPosition(1) qpos=state.getGhostPosition(2) #print(ppos,gpos,qpos) if ppos[0]==3 and ppos[1]==3 : if (gpos[0]==6 and qpos[0]>13) or (qpos[0]==6 and gpos[0]>13): return Directions.EAST else: return Directions.NORTH if ppos[0]==3 and ppos[1]==4: if (gpos[0]==5 and qpos[0]>13) or (qpos[0]==5 and gpos[0]>13) : return Directions.SOUTH else: return Directions.STOP if ppos[0]==12 and ppos[1]==3: if (gpos[0]==10 and qpos[0]<7) or (qpos[0]==10 and gpos[0]<7) : return Directions.EAST else: return Directions.SOUTH if ppos[0]==12 and ppos[1]==2: if (gpos[0]==11 and qpos[0]<7) or (qpos[0]==11 and gpos[0]<7) : return Directions.NORTH else: return Directions.STOP else: return Directions.EAST "P1-4" class DodgeAgent(Agent): "You can run, but you can't hide." def getAction(self, state): "The agent receives a GameState (defined in pacman.py)." "[Project 1] YOUR CODE HERE" ppos=state.getPacmanPosition() gpos=state.getGhostPosition(1) #print(ppos,gpos) if gpos[0]==4 and gpos[1]==8 and ppos[0]==1 and ppos[1]==8: return Directions.SOUTH elif gpos[0]==1 and gpos[1]==5 and ppos[0]==1 and ppos[1]==8: return Directions.EAST elif ppos[0]<=7 and ppos[0]>=2 and ppos[1]==8 : return Directions.EAST elif ppos[0]>=1 and ppos[0]<=7 and ppos[1]==1 : return Directions.EAST elif ppos[1]<=7 and ppos[1]>=2 and ppos[0]==1 : return Directions.SOUTH elif ppos[1]<=8 and ppos[1]>=1 and ppos[0]==8 : return Directions.SOUTH else : return Directions.STOP return Directions.STOP ####################################################### # This portion is written for you, but will only work # # after you fill in parts of search.py # ####################################################### class SearchAgent(Agent): """ This very general search agent finds a path using a supplied search algorithm for a supplied search problem, then returns actions to follow that path. As a default, this agent runs DFS on a PositionSearchProblem to find location (1,1) Options for fn include: depthFirstSearch or dfs breadthFirstSearch or bfs Note: You should NOT change any code in SearchAgent """ def __init__(self, fn='depthFirstSearch', prob='PositionSearchProblem', heuristic='nullHeuristic'): # Warning: some advanced Python magic is employed below to find the right functions and problems # Get the search function from the name and heuristic if fn not in dir(search): raise AttributeError, fn + ' is not a search function in search.py.' func = getattr(search, fn) if 'heuristic' not in func.func_code.co_varnames: print('[SearchAgent] using function ' + fn) self.searchFunction = func else: if heuristic in globals().keys(): heur = globals()[heuristic] elif heuristic in dir(search): heur = getattr(search, heuristic) else: raise AttributeError, heuristic + ' is not a function in searchAgents.py or search.py.' print('[SearchAgent] using function %s and heuristic %s' % (fn, heuristic)) # Note: this bit of Python trickery combines the search algorithm and the heuristic self.searchFunction = lambda x: func(x, heuristic=heur) # Get the search problem type from the name if prob not in globals().keys() or not prob.endswith('Problem'): raise AttributeError, prob + ' is not a search problem type in SearchAgents.py.' self.searchType = globals()[prob] print('[SearchAgent] using problem type ' + prob) def registerInitialState(self, state): """ This is the first time that the agent sees the layout of the game board. Here, we choose a path to the goal. In this phase, the agent should compute the path to the goal and store it in a local variable. All of the work is done in this method! state: a GameState object (pacman.py) """ if self.searchFunction == None: raise Exception, "No search function provided for SearchAgent" starttime = time.time() problem = self.searchType(state) # Makes a new search problem self.actions = self.searchFunction(problem) # Find a path totalCost = problem.getCostOfActions(self.actions) print('Path found with total cost of %d in %.1f seconds' % (totalCost, time.time() - starttime)) if '_expanded' in dir(problem): print('Search nodes expanded: %d' % problem._expanded) def getAction(self, state): """ Returns the next action in the path chosen earlier (in registerInitialState). Return Directions.STOP if there is no further action to take. state: a GameState object (pacman.py) """ if 'actionIndex' not in dir(self): self.actionIndex = 0 i = self.actionIndex self.actionIndex += 1 if i < len(self.actions): return self.actions[i] else: return Directions.STOP class PositionSearchProblem(search.SearchProblem): """ A search problem defines the state space, start state, goal test, successor function and cost function. This search problem can be used to find paths to a particular point on the pacman board. The state space consists of (x,y) positions in a pacman game. Note: this search problem is fully specified; you should NOT change it. """ def __init__(self, gameState, costFn = lambda x: 1, goal=(1,1), start=None, warn=True, visualize=True): """ Stores the start and goal. gameState: A GameState object (pacman.py) costFn: A function from a search state (tuple) to a non-negative number goal: A position in the gameState """ self.walls = gameState.getWalls() self.startState = gameState.getPacmanPosition() if start != None: self.startState = start self.goal = goal self.costFn = costFn self.visualize = visualize if warn and (gameState.getNumFood() != 1 or not gameState.hasFood(*goal)): print 'Warning: this does not look like a regular search maze' # For display purposes self._visited, self._visitedlist, self._expanded = {}, [], 0 # DO NOT CHANGE def getStartState(self): return self.startState def isGoalState(self, state): isGoal = state == self.goal # For display purposes only if isGoal and self.visualize: self._visitedlist.append(state) import __main__ if '_display' in dir(__main__): if 'drawExpandedCells' in dir(__main__._display): #@UndefinedVariable __main__._display.drawExpandedCells(self._visitedlist) #@UndefinedVariable return isGoal def getSuccessors(self, state): """ Returns successor states, the actions they require, and a cost of 1. As noted in search.py: For a given state, this should return a list of triples, (successor, action, stepCost), where 'successor' is a successor to the current state, 'action' is the action required to get there, and 'stepCost' is the incremental cost of expanding to that successor """ successors = [] for action in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]: x,y = state dx, dy = Actions.directionToVector(action) nextx, nexty = int(x + dx), int(y + dy) if not self.walls[nextx][nexty]: nextState = (nextx, nexty) cost = self.costFn(nextState) successors.append( ( nextState, action, cost) ) # Bookkeeping for display purposes self._expanded += 1 # DO NOT CHANGE if state not in self._visited: self._visited[state] = True self._visitedlist.append(state) return successors def getCostOfActions(self, actions): """ Returns the cost of a particular sequence of actions. If those actions include an illegal move, return 999999. """ if actions == None: return 999999 x,y= self.getStartState() cost = 0 for action in actions: # Check figure out the next state and see whether its' legal dx, dy = Actions.directionToVector(action) x, y = int(x + dx), int(y + dy) if self.walls[x][y]: return 999999 cost += self.costFn((x,y)) return cost class StayEastSearchAgent(SearchAgent): """ An agent for position search with a cost function that penalizes being in positions on the West side of the board. The cost function for stepping into a position (x,y) is 1/2^x. """ def __init__(self): self.searchFunction = search.uniformCostSearch costFn = lambda pos: .5 ** pos[0] self.searchType = lambda state: PositionSearchProblem(state, costFn, (1, 1), None, False) class StayWestSearchAgent(SearchAgent): """ An agent for position search with a cost function that penalizes being in positions on the East side of the board. The cost function for stepping into a position (x,y) is 2^x. """ def __init__(self): self.searchFunction = search.uniformCostSearch costFn = lambda pos: 2 ** pos[0] self.searchType = lambda state: PositionSearchProblem(state, costFn) def manhattanHeuristic(position, problem, info={}): "The Manhattan distance heuristic for a PositionSearchProblem" xy1 = position xy2 = problem.goal return abs(xy1[0] - xy2[0]) + abs(xy1[1] - xy2[1]) def euclideanHeuristic(position, problem, info={}): "The Euclidean distance heuristic for a PositionSearchProblem" xy1 = position xy2 = problem.goal return ( (xy1[0] - xy2[0]) ** 2 + (xy1[1] - xy2[1]) ** 2 ) ** 0.5 ##################################################### # This portion is incomplete. Time to write code! # ##################################################### class CornersProblem(search.SearchProblem): """ This search problem finds paths through all four corners of a layout. You must select a suitable state space and successor function """ def __init__(self, startingGameState): """ Stores the walls, pacman's starting position and corners. """ self.walls = startingGameState.getWalls() self.startingPosition = startingGameState.getPacmanPosition() top, right = self.walls.height-2, self.walls.width-2 self.corners = ((1,1), (1,top), (right, 1), (right, top)) for corner in self.corners: if not startingGameState.hasFood(*corner): print 'Warning: no food in corner ' + str(corner) self._expanded = 0 # DO NOT CHANGE; Number of search nodes expanded # Please add any code here which you would like to use # in initializing the problem "*** YOUR CODE HERE ***" def getStartState(self): """ Returns the start state (in your state space, not the full Pacman state space) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def isGoalState(self, state): """ Returns whether this search state is a goal state of the problem. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def getSuccessors(self, state): """ Returns successor states, the actions they require, and a cost of 1. As noted in search.py: For a given state, this should return a list of triples, (successor, action, stepCost), where 'successor' is a successor to the current state, 'action' is the action required to get there, and 'stepCost' is the incremental cost of expanding to that successor """ successors = [] for action in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]: # Add a successor state to the successor list if the action is legal # Here's a code snippet for figuring out whether a new position hits a wall: # x,y = currentPosition # dx, dy = Actions.directionToVector(action) # nextx, nexty = int(x + dx), int(y + dy) # hitsWall = self.walls[nextx][nexty] "*** YOUR CODE HERE ***" self._expanded += 1 # DO NOT CHANGE return successors def getCostOfActions(self, actions): """ Returns the cost of a particular sequence of actions. If those actions include an illegal move, return 999999. This is implemented for you. """ if actions == None: return 999999 x,y= self.startingPosition for action in actions: dx, dy = Actions.directionToVector(action) x, y = int(x + dx), int(y + dy) if self.walls[x][y]: return 999999 return len(actions) def cornersHeuristic(state, problem): """ A heuristic for the CornersProblem that you defined. state: The current search state (a data structure you chose in your search problem) problem: The CornersProblem instance for this layout. This function should always return a number that is a lower bound on the shortest path from the state to a goal of the problem; i.e. it should be admissible (as well as consistent). """ corners = problem.corners # These are the corner coordinates walls = problem.walls # These are the walls of the maze, as a Grid (game.py) "*** YOUR CODE HERE ***" return 0 # Default to trivial solution class AStarCornersAgent(SearchAgent): "A SearchAgent for FoodSearchProblem using A* and your foodHeuristic" def __init__(self): self.searchFunction = lambda prob: search.aStarSearch(prob, cornersHeuristic) self.searchType = CornersProblem class FoodSearchProblem: """ A search problem associated with finding the a path that collects all of the food (dots) in a Pacman game. A search state in this problem is a tuple ( pacmanPosition, foodGrid ) where pacmanPosition: a tuple (x,y) of integers specifying Pacman's position foodGrid: a Grid (see game.py) of either True or False, specifying remaining food """ def __init__(self, startingGameState): self.start = (startingGameState.getPacmanPosition(), startingGameState.getFood()) self.walls = startingGameState.getWalls() self.startingGameState = startingGameState self._expanded = 0 # DO NOT CHANGE self.heuristicInfo = {} # A dictionary for the heuristic to store information def getStartState(self): return self.start def isGoalState(self, state): return state[1].count() == 0 def getSuccessors(self, state): "Returns successor states, the actions they require, and a cost of 1." successors = [] self._expanded += 1 # DO NOT CHANGE for direction in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]: x,y = state[0] dx, dy = Actions.directionToVector(direction) nextx, nexty = int(x + dx), int(y + dy) if not self.walls[nextx][nexty]: nextFood = state[1].copy() nextFood[nextx][nexty] = False successors.append( ( ((nextx, nexty), nextFood), direction, 1) ) return successors def getCostOfActions(self, actions): """Returns the cost of a particular sequence of actions. If those actions include an illegal move, return 999999""" x,y= self.getStartState()[0] cost = 0 for action in actions: # figure out the next state and see whether it's legal dx, dy = Actions.directionToVector(action) x, y = int(x + dx), int(y + dy) if self.walls[x][y]: return 999999 cost += 1 return cost class AStarFoodSearchAgent(SearchAgent): "A SearchAgent for FoodSearchProblem using A* and your foodHeuristic" def __init__(self): self.searchFunction = lambda prob: search.aStarSearch(prob, foodHeuristic) self.searchType = FoodSearchProblem def foodHeuristic(state, problem): """ Your heuristic for the FoodSearchProblem goes here. This heuristic must be consistent to ensure correctness. First, try to come up with an admissible heuristic; almost all admissible heuristics will be consistent as well. If using A* ever finds a solution that is worse uniform cost search finds, your heuristic is *not* consistent, and probably not admissible! On the other hand, inadmissible or inconsistent heuristics may find optimal solutions, so be careful. The state is a tuple ( pacmanPosition, foodGrid ) where foodGrid is a Grid (see game.py) of either True or False. You can call foodGrid.asList() to get a list of food coordinates instead. If you want access to info like walls, capsules, etc., you can query the problem. For example, problem.walls gives you a Grid of where the walls are. If you want to *store* information to be reused in other calls to the heuristic, there is a dictionary called problem.heuristicInfo that you can use. For example, if you only want to count the walls once and store that value, try: problem.heuristicInfo['wallCount'] = problem.walls.count() Subsequent calls to this heuristic can access problem.heuristicInfo['wallCount'] """ position, foodGrid = state "*** YOUR CODE HERE ***" return 0 class ClosestDotSearchAgent(SearchAgent): "Search for all food using a sequence of searches" def registerInitialState(self, state): self.actions = [] currentState = state while(currentState.getFood().count() > 0): nextPathSegment = self.findPathToClosestDot(currentState) # The missing piece self.actions += nextPathSegment for action in nextPathSegment: legal = currentState.getLegalActions() if action not in legal: t = (str(action), str(currentState)) raise Exception, 'findPathToClosestDot returned an illegal move: %s!\n%s' % t currentState = currentState.generateSuccessor(0, action) self.actionIndex = 0 print 'Path found with cost %d.' % len(self.actions) def findPathToClosestDot(self, gameState): """ Returns a path (a list of actions) to the closest dot, starting from gameState. """ # Here are some useful elements of the startState startPosition = gameState.getPacmanPosition() food = gameState.getFood() walls = gameState.getWalls() problem = AnyFoodSearchProblem(gameState) "*** YOUR CODE HERE ***" util.raiseNotDefined() class AnyFoodSearchProblem(PositionSearchProblem): """ A search problem for finding a path to any food. This search problem is just like the PositionSearchProblem, but has a different goal test, which you need to fill in below. The state space and successor function do not need to be changed. The class definition above, AnyFoodSearchProblem(PositionSearchProblem), inherits the methods of the PositionSearchProblem. You can use this search problem to help you fill in the findPathToClosestDot method. """ def __init__(self, gameState): "Stores information from the gameState. You don't need to change this." # Store the food for later reference self.food = gameState.getFood() # Store info for the PositionSearchProblem (no need to change this) self.walls = gameState.getWalls() self.startState = gameState.getPacmanPosition() self.costFn = lambda x: 1 self._visited, self._visitedlist, self._expanded = {}, [], 0 # DO NOT CHANGE def isGoalState(self, state): """ The state is Pacman's position. Fill this in with a goal test that will complete the problem definition. """ x,y = state "*** YOUR CODE HERE ***" util.raiseNotDefined() def mazeDistance(point1, point2, gameState): """ Returns the maze distance between any two points, using the search functions you have already built. The gameState can be any game state -- Pacman's position in that state is ignored. Example usage: mazeDistance( (2,4), (5,6), gameState) This might be a useful helper function for your ApproximateSearchAgent. """ x1, y1 = point1 x2, y2 = point2 walls = gameState.getWalls() assert not walls[x1][y1], 'point1 is a wall: ' + str(point1) assert not walls[x2][y2], 'point2 is a wall: ' + str(point2) prob = PositionSearchProblem(gameState, start=point1, goal=point2, warn=False, visualize=False) return len(search.bfs(prob))
28d162b11564b44d04ca3f74ad9d17a49e06da3d
3edbad578df95971280e9e4e1bf44abe7aa99426
/scripts/balAPinc_multi_test.py
36459a592a7244553ee73c6f5972f005517ef8b4
[]
no_license
yogarshi/bisparse-dep
f7c655b4cf8af2cafad2b48e16bd5fbd7af783f6
21e4e3952afa311c3ee51067605e833bf39bde49
refs/heads/master
2021-03-24T10:18:40.542415
2018-04-23T20:16:25
2018-04-23T20:16:25
122,494,868
4
1
null
null
null
null
UTF-8
Python
false
false
7,671
py
__author__ = 'yogarshi' import sys import os import math import numpy as np import argparse sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from mono_nnse_analysis import load_vectors, read_word_file, vector_reps, get_top_words #from scipy.spatial.distance import cosine """ Implementation of the balAPinc score as explained in [1]. The function names exactly correspond to the ones used in [1] [1] Turney, P., & Mohammad, S. (2013). Experiments with three approaches to recognizing lexical entailment. Natural Language Engineering, 1(1), 1-42. http://doi.org/10.1017/S1351324913000387 """ feat_list = [] count = 0 def inc(r,f_u, f_v): """ :param r: Rank :param f_u: Ranked feature list for word u :param f_v: Ranked feature list for word v """ global count global feat_list inc = 0 #print r for i in range(r): if f_u[i] in f_v: if f_u[i] not in feat_list[count]: feat_list[count].append(f_u[i]) #print f_u[i], "\t", inc += 1 return inc def p(r, f_u, f_v): """ :param r: Rank :param f_u: Ranked feature list for word u :param f_v: Ranked feature list for word v """ return float(inc(r,f_u,f_v))/r def rank(f, f_w): """ :param f: feature id :param f_w: Ranked feature list for word w :return: """ if f in f_w: return f_w.index(f)+1 else: return 0 def rel(f,f_w): """ :param f: feature id :param f_w: Ranked feature list for word w :return: """ return 1 - float(rank(f, f_w))/(len(f_w) + 1) def APinc(f_u, f_v): """ :param vec1: Numpy array of shape (m,) :param vec2: Numpy array of shape (m,) :return: APinc(vec1, vec2) """ sum = 0 for r in range(1,len(f_u)+1): sum += p(r,f_u,f_v)*rel(f_u[r-1], f_v) if len(f_u) == 0: return 0 return sum/len(f_u) def lin(scored_f_u, scored_f_v): """ :param scored_f_u: Dict of features of word u with feature id as key and score as value :param scored_f_v: Dict of features of word v with feature id as key and score as value :return: """ numerator = 0 denominator = 0 for each_feat in scored_f_u: if each_feat in scored_f_v: numerator += scored_f_u[each_feat] + scored_f_v[each_feat] denominator += scored_f_u[each_feat] for each_feat in scored_f_v: denominator += scored_f_v[each_feat] if denominator == 0: return 0 return float(numerator)/denominator def balAPinc(f_u, scored_f_u, f_v, scored_f_v): #print f_u #print f_v #print return math.sqrt(APinc(f_u, f_v) * lin(scored_f_u, scored_f_v)) def main(argv): global count global feat_list threshold_hyp =0.05 num_features_hyp = 20 #print threshold_hyp, num_features_hyp parser = argparse.ArgumentParser(description="Analysis of lexical entailment dataset ") parser.add_argument("vector_file_fr", help='The file from which sparse vectors have to be loaded') parser.add_argument("vector_file_en", help='The file from which sparse vectors have to be loaded') parser.add_argument("word_pairs_file", help='File containing list of word pairs with class') parser.add_argument("threshold_hyp", help='Threshold hyperparameter') parser.add_argument("num_features_hyp", help='Num features hyperparameter') parser.add_argument("-p", "--prefix", help='Optional prefix for output file names', default="log") #parser.add_argument("word_pairs_file_neg", help='File containing list of negative examples') args = parser.parse_args(args=argv) cos = True #threshold_hyp =float(args.threshold_hyp) #num_features_hyp = int(args.num_features_hyp) words_e, embeddings_array_e = load_vectors(args.vector_file_en) #top_words_e = get_top_words(words_e, embeddings_array_e, 10) #words_f, embeddings_array_f = words_e, embeddings_array_e words_f, embeddings_array_f = load_vectors(args.vector_file_fr) #top_words_f = get_top_words(words_f, embeddings_array_f, 10) idxs_p, word_list1_p, word_list2_p, labels_list, uf_word_list1_p, uf_word_list2_p, uf_labels_list = read_word_file(args.word_pairs_file, words_e, words_f) #print word_list1_p #print word_list2_p #idxs_n, word_list1_n, word_list2_n = read_word_file(args.word_pairs_file_neg, words) rep1_array_p = vector_reps(word_list1_p, words_e, embeddings_array_e) rep2_array_p = vector_reps(word_list2_p, words_f, embeddings_array_f) #rep1_array_n, rep2_array_n = vector_reps(word_list1_n, word_list2_n, words, embeddings_array) balAPinc_pos = [] """ if cos: outf_name = "{0}".format(args.prefix) outf = open(outf_name, 'w') for i in range(len(rep1_array_p)): outf.write("{0}\t{1}\t{2}\t{3}\n".format(word_list1_p[i], word_list2_p[i], labels_list[i], 1.0 - cosine(rep1_array_p[i], rep2_array_p[i]))) outf.close() """ #balAPinc_neg = [] for num_features_hyp in [int(args.num_features_hyp)]: for threshold_hyp in [float(args.threshold_hyp)]: f_u_temp_p = [sorted([(i,x[i]) for i in range(len(x)) if x[i] != 0], reverse=True, key= lambda x:x[1])[:num_features_hyp] for x in rep1_array_p] f_v_temp_p = [sorted([(i,x[i]) for i in range(len(x)) if x[i] != 0], reverse=True, key= lambda x:x[1])[:num_features_hyp] for x in rep2_array_p] f_u_array_p = [[y[0] for y in x if y[1] > threshold_hyp] for x in f_u_temp_p] f_v_array_p = [[y[0] for y in x if y[1] > threshold_hyp] for x in f_v_temp_p] scored_f_u_array_p = [{each_key[0]:each_key[1] for each_key in x} for x in f_u_temp_p] scored_f_v_array_p = [{each_key[0]:each_key[1] for each_key in x} for x in f_v_temp_p] #f_u_temp_n = [ sorted([(i,x[i]) for i in range(len(x)) if x[i] != 0], reverse=True, key= lambda x:x[1]) # for x in rep1_array_n] #f_v_temp_n = [ sorted([(i,x[i]) for i in range(len(x)) if x[i] != 0], reverse=True, key= lambda x:x[1]) # for x in rep2_array_n] #f_u_array_n = [[y[0] for y in x] for x in f_u_temp_n] #f_v_array_n = [[y[0] for y in x] for x in f_v_temp_n] #scored_f_u_array_n = [{each_key[0]:each_key[1] for each_key in x} for x in f_u_temp_n] #scored_f_v_array_n = [{each_key[0]:each_key[1] for each_key in x} for x in f_v_temp_n] balAPinc_array_p = [] #balAPinc_array_n = [] a_in_top = 0 b_in_top = 0 avg_len = [] avg_top_score_a = 0 avg_top_score_b = 0 top_a_is_top_common = 0 outf_name = "{2}_{0}_{1}".format(num_features_hyp, threshold_hyp, args.prefix) outf = open(outf_name, 'w') for i in range(len(word_list1_p)): w1 = word_list1_p[i] w2 = word_list2_p[i] feat_list.append([]) balAPinc_array_p.append(balAPinc(f_u_array_p[i], scored_f_u_array_p[i], f_v_array_p[i], scored_f_v_array_p[i])) outf.write("{0}\t{1}\t{2}\t{3}\n".format(word_list1_p[i], word_list2_p[i], labels_list[i], balAPinc_array_p[i])) for i in range(len(uf_word_list1_p)): w1 = uf_word_list1_p[i] w2 = uf_word_list2_p[i] outf.write("{0}\t{1}\t{2}\t{3}\n".format(uf_word_list1_p[i], uf_word_list2_p[i], uf_labels_list[i], 0)) """ print for c in range(min(10, len(feat_list[count]) )): print top_words_e[feat_list[count][c]] print top_words_f[feat_list[count][c]] print scored_f_u_array_p[i][feat_list[count][c]], scored_f_v_array_p[i][feat_list[count][c]] count += 1 print "#######################\n" outf.close() """ #print avg_top_score_a/count, avg_top_score_b/count #print np.median(avg_len), np.mean(avg_len), np.std(avg_len) #print a_in_top, b_in_top, top_a_is_top_common #for i in range(len(word_list1_n)): # balAPinc_array_n.append(balAPinc(f_u_array_n[i], scored_f_u_array_n[i], f_v_array_n[i], scored_f_v_array_n[i])) #for i in range(len(word_list1_p)): # print word_list1_p[i], "\t", word_list2_p[i], "\t", balAPinc_array_p[i] ##Set up classification task if __name__ == "__main__": main(sys.argv[1:])
6eb93f1d511aaafd0e657c97367dabfad01aad66
ec2f55e8aa5f68988110c09cb73faad10db10b38
/blockbuster/tests/computeFrameTimesFromVerboseOutput.py
58ffedfd4bb61a84ad402b3f35ee3aec89090209
[]
no_license
LLNL/blockbuster
97270481ac2623eb06db57b5d03be4cc73ecddf2
f9b8532150f2a75c99ffc05109d803d43f523550
refs/heads/master
2023-06-03T19:46:12.480437
2016-02-04T19:24:08
2016-02-04T19:24:08
32,134,210
2
0
null
null
null
null
UTF-8
Python
false
false
4,603
py
#!/usr/bin/env python import sys, re startTime = endTime = None previousEnd = None frame=0 oldframe = 0 loop = 0 times={} totalrendertime = 0.0 totalinterframe = 0.0 totaltime = 0.0 frames = 0 highframetime = 20 highinterframe = 10 if len(sys.argv) < 2: print "Error: need a logfile name" sys.exit(1) files = [] for arg in sys.argv[1:]: if arg[0] == '-': if arg == '--stereo' or arg == '-s': highframetime = 40 else: errexit("Bad argument: %s"%arg) else: files.append(arg) frameRate = -1.0 frameratesearch = re.compile("mFrameRate=([0-9]+\.[0-9]+)") for infile in files: if '.log' in infile: outfilename = infile.replace('.log', '-analysis.log') else: outfilename = infile + '-analysis.log' print "writing results for file %s to file: %s"%(infile,outfilename) outfile = open(outfilename, "w") for line in open(infile, "r"): exp = frameratesearch.search(line) if exp: framerate = float(exp.group(0).split("=")[1]) # outfile.write("Found frame rate %f in line: %s"%(framerate, line)) if '"gl_stereo"' in line: outfile.write("stereo renderer detected, using higher frame time\n") highframetime = 40 if '"gl"' in line: outfile.write("gl renderer detected, using lower frame time\n") highframetime = 20 if "RenderActual begin" in line: tokens=line.split() try: frame=int(tokens[6].strip(',').strip(':')) startTime = float(tokens[len(tokens)-1].split("=")[1].strip(']')) if frame < oldframe: loop = loop + 1 except: startTime=None outfile.write( "warning: bad 'start time' line at frame %d: \"%s\"\n" %( frame, line)) elif "RenderActual end" in line: if not startTime: outfile.write( "Warning: skipping end time analysis at frame %d\n"%frame) continue tokens=line.split() try: endTime = float(tokens[10].split("=")[1].strip(']')) if previousEnd: interframe = 1000.0*(startTime - previousEnd) else: interframe = 0 previousEnd = endTime rendertime = 1000.0*(endTime - startTime) entry = {"frame": frame, "frame rate": framerate, "frame time": rendertime, "interframe time": interframe, "total frame time": rendertime+interframe, "start": startTime, "end": endTime } totalrendertime = totalrendertime + rendertime totalinterframe = totalinterframe + interframe totaltime = totaltime + rendertime+interframe frames = frames + 1 if loop not in times.keys(): # outfile.write( "Adding new dictionary to times\n") times[loop] = {} # outfile.write( "Adding new entry to loop %s: %s\n"%(loop, str(entry))) times[loop][frame] = entry except: endTime=None outfile.write( "warning: bad 'end time' line at frame %d: \"%s\"\n" %( frame, line)) continue outfile.write( "Total frames: %d\n"%frames) outfile.write( "Average frame time: %f\n"%(totaltime/frames)) outfile.write( "Average render time: %f\n"%(totalrendertime/frames)) outfile.write( "Average interframe time: %f\n"%(totalinterframe/frames)) # outfile.write( "times: %s\n"%str(times)) loops = times.keys() loops.sort() for loop in loops: outfile.write( "loop: %s\n"%loop) keys = times[loop].keys() keys.sort() for time in keys: if times[loop][time]["frame time"] > highframetime: outfile.write( "High frame time! ********************************\n") if times[loop][time]["interframe time"] > highinterframe: outfile.write( "High interframe time! ********************************\n") if times[loop][time]["total frame time"] > highframetime + highinterframe: outfile.write( "High total frame time! ********************************\n") outfile.write( str(times[loop][time]) + "\n")
40125cfd752c5de08af72a21e324f89b505db21d
2603f28e3dc17ae2409554ee6e1cbd315a28b732
/ABC38/prob_c.py
f33438f7f66d9238ccdeb20f211ec805df4b4225
[]
no_license
steinstadt/AtCoder
69f172280e89f4249e673cae9beab9428e2a4369
cd6c7f577fcf0cb4c57ff184afdc163f7501acf5
refs/heads/master
2020-12-23T12:03:29.124134
2020-11-22T10:47:40
2020-11-22T10:47:40
237,144,420
0
0
null
null
null
null
UTF-8
Python
false
false
346
py
# Problem C - 単調増加 # input N = int(input()) a_list = list(map(int, input().split())) # initialization ans = 0 # shakutori count right = 0 for left in range(N): while (right<N and a_list[right-1]<a_list[right]) or left==right: right += 1 ans += right - left if left==right: right += 1 # output print(ans)
05099d08b0153e6bc6ae06b6a81f2a9c98b9d394
ab00a1f8a8576f21f5f7d75ef212773e4c750473
/racetime/admin.py
9bdb5a8cac06c4cebd2bd6525ffe86778bfd51f1
[]
no_license
DragonAX/racetime
90e3cefd11bcdf8c5b7e7c3f30324dc88b5f05d0
f5fd26fe9709e1287ab6363052ec7bb81dfe7f0b
refs/heads/master
2016-09-05T19:25:24.531558
2014-07-30T00:27:58
2014-07-30T00:27:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
222
py
from mysite.racetime.models import * from django.contrib import admin admin.site.register(RaceEvent) admin.site.register(Qualification) admin.site.register(Final) admin.site.register(Car) admin.site.register(Transponder)
400b0ef45722986cf93750d299ddc0a2b9206853
693a129a17d879266a5ea933ec8e646d0d49db6c
/GroupContainer.py
291b4560ae5e15ba1297019d1fa79e4dec933d94
[]
no_license
coleTitze/PyRecipes
28d41fffaeb2f2a78e2f3cdfb55e72b1d006544d
497d4615f07978ac7189fd9925f5172d26dda135
refs/heads/master
2023-02-21T08:56:13.786443
2021-01-07T07:59:22
2021-01-07T07:59:22
327,200,790
0
0
null
null
null
null
UTF-8
Python
false
false
652
py
from Group import * class GroupContainer: def __init__(self): self.__groupList = [] self.__groupNameList = [] generalGroup = Group("General") self.addGroup(generalGroup) def getGroupList(self): return self.__groupList def getGroupNameList(self): return self.__groupNameList def contains(self, checkItem): for i, item in enumerate(self.__groupList): if item.getName() == checkItem: return True return False def addGroup(self, newGroup): self.__groupList.append(newGroup) self.__groupNameList.append(newGroup.getName())
e743e7599f4f34e6d2cb001d03d0ac09161cc32e
8862e98bce6d938ed07ce670cf48af9d3f660362
/sdk/coolsms.py
c07d975e6e973933005fa03c8021dcd7c385ee74
[ "BSD-4.3TAHOE", "BSD-3-Clause" ]
permissive
coolsms/python-sdk
c63ed29d88199623f38d9355c687957d66e770d1
9fb1b89ea5a498f05b63d658ed64feea4a0abbf8
refs/heads/master
2020-05-21T13:59:39.073644
2019-12-26T00:32:19
2019-12-26T00:32:19
38,469,744
8
9
null
2017-04-20T00:11:29
2015-07-03T03:23:31
Python
UTF-8
Python
false
false
9,388
py
# vi:set sw=4 ts=4 expandtab: # -*- coding: utf8 -*- import sys import hmac import mimetypes import uuid import json import time import platform from hashlib import md5 from sdk.exceptions import CoolsmsException from sdk.exceptions import CoolsmsSDKException from sdk.exceptions import CoolsmsSystemException from sdk.exceptions import CoolsmsServerException # sys.version_info.major is available in python version 2.7 # use sys.version_info[0] for python 2.6 if sys.version_info[0] == 2: from httplib import HTTPSConnection from httplib import HTTPConnection from urllib import urlencode else: from http.client import HTTPSConnection from http.client import HTTPConnection from urllib.parse import urlencode ## @mainpage PYTHON SDK # @section intro 소개 # - 소개 : Coolsms REST API SDK FOR PYTHON # - 버전 : 2.0.3 # - 설명 : Coolsms REST API 를 이용 보다 빠르고 안전하게 문자메시지를 보낼 수 있는 PYTHON으로 만들어진 SDK 입니다. # @section CreateInfo 작성 정보 # - 작성자 : Nurigo # - 작성일 : 2016/08/09 # @section common 기타 정보 # - 저작권 GPL v2 # - Copyright (C) 2008-2016 NURIGO # - http://www.coolsms.co.kr ## @class Coolsms # @brief Gateway access url : https://api.coolsms.co.kr/{api type}/{verson}/{resource name} class Coolsms: # SDK Version sdk_version = "2.0.3" # API Version api_version = "2" # SMS Gateway address host = 'api.coolsms.co.kr' # use secure channel as default port = 443 # API Key api_key = None # API Secret api_secret = None # API Name api_name = "sms" # error handle error_string = None # if True. use http connection use_http_connection = False ## @brief initialize # @param string api_key [required] # @param string api_secret [required] def __init__(self, api_key, api_secret): self.api_key = api_key self.api_secret = api_secret ## @brief get signature # @return string timestamp, string salt, string signature def __get_signature__(self): salt = str(uuid.uuid1()) timestamp = str(int(time.time())) data = timestamp + salt return timestamp, salt, hmac.new(self.api_secret.encode(), data.encode(), md5) ## @brief http GET method request # @param string resource [required] # @param dictionary params [optional] # @return JSONObject def request_get(self, resource, params=dict()): return self.request(resource, params) ## @brief http POST method request # @param string resource [required] # @param dictionary params [optional] # @return JSONObject def request_post(self, resource, params=dict()): return self.request(resource, params, "POST") ## @brief http POST & GET method request process # @param string resource [required] # @param dictionary params [required] # @param string method [optional] [default:"GET"] # @return JSONObject def request(self, resource, params, method="GET"): params = self.set_base_params(params) params_str = urlencode(params) headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain", "User-Agent": "sms-python"} try: # use_http_connection 이 True 라면 http 통신을 한다 if self.use_http_connection == True: conn = HTTPConnection(self.host) else: conn = HTTPSConnection(self.host, self.port) # request method 에 따라 다르게 요청 if method == "GET": conn.request("GET", "/%s/%s/%s?" % (self.api_name, self.api_version, resource) + params_str, None, headers) else: conn.request("POST", "/%s/%s/%s" % (self.api_name, self.api_version, resource), params_str, headers) response = conn.getresponse() data = response.read().decode() conn.close() except Exception as e: conn.close() raise CoolsmsSystemException(e, 399) # https status code is not 200, raise Exception if response.status != 200: error_msg = response.reason if data: error_msg = data raise CoolsmsServerException(error_msg, response.status) obj = None if data: obj = json.loads(data) return obj ## @brief http POST method multipart form request # @param string resource [required] # @param dictionary params [optional] # @param dictionary files [optional] # @return JSONObject def request_post_multipart(self, resource, params, files): host = self.host + ':' + str(self.port) selector = "/%s/%s/%s" % (self.api_name, self.api_version, resource) params = self.set_base_params(params) content_type, body = self.encode_multipart_formdata(params, files) try: # use_http_connection 이 True 라면 http 통신을 한다 if self.use_http_connection == True: conn = HTTPConnection(self.host) else: conn = HTTPSConnection(self.host, self.port) conn.putrequest('POST', selector) conn.putheader('Content-type', content_type) conn.putheader('Content-length', str(len(body))) conn.putheader('User-Agent', 'sms-python') conn.endheaders() conn.send(body) response = conn.getresponse() data = response.read().decode() conn.close() except Exception as e: conn.close() raise CoolsmsSystemException(e, 399) # https status code is not 200, raise Exception if response.status != 200: error_msg = response.reason if data: error_msg = data raise CoolsmsServerException(error_msg, response.status) # response data parsing obj = None if data: obj = json.loads(data) return obj ## @brief format multipart form # @param dictionary params [required] # @param dictionary files [required] # @return string content_type, string body def encode_multipart_formdata(self, params, files): boundary = str(uuid.uuid1()) crlf = '\r\n' l = [] for key, value in params.items(): l.append('--' + boundary) l.append('Content-Disposition: form-data; name="%s"' % key) l.append('') l.append(value) for key, value in files.items(): l.append('--' + boundary) l.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, value['filename'])) l.append('Content-Type: %s' % self.get_content_type(value['filename'])) l.append('') l.append(str(value['content'])) l.append('--' + boundary + '--') l.append('') body = crlf.join(l).encode('utf-8') content_type = 'multipart/form-data; boundary=%s' % boundary return content_type, body ## @brief get content type # @param string filesname [required] # @return string content_type def get_content_type(self, filename): return mimetypes.guess_type(filename)[0] or 'application/octet-stream' ## @brief set base parameter # @param dictionary params [required] # @return dictionary params def set_base_params(self, params): timestamp, salt, signature = self.__get_signature__() base_params = {'api_key': self.api_key, 'timestamp': timestamp, 'salt': salt, 'signature': signature.hexdigest()} params.update(base_params) return params ## @brief check send data # @param dictionary params [required] # @return dictionary params def check_send_data(self, params): # require fields check if all (k in params for k in ("to", "from", "text")) == False: raise CoolsmsSDKException("parameter 'to', 'from', 'text' are required", 201) for key, val in params.items(): # ptyhon 2 version 에서 unicode 문제 해결 if key == "text" and sys.version_info[0] == 2: text = val t_temp = text.decode('utf-8') text = t_temp.encode('utf-8') text = unicode(text, encoding='utf-8') params['text'] = text # convert list to a comma seperated string if key == "to" and val == list: params['to'] = ','.join(to) # message type check if key == "type" and val.lower() not in ['sms', 'lms', 'mms', 'ata', 'cta']: raise CoolsmsSDKException("message type is not supported", 201) return params ## @brief set api name and api version # @param string api_name [required] 'sms', 'senderid', 'image' # @param integer api_version [required] def set_api_config(self, api_name, api_version): self.api_name = api_name; self.api_version = api_version; ## @brief use http connection def use_http_connection(self): self.use_http_connection = True
ecbf91b09ce1d8762e531cb46dfd5fb182eac4b6
99b9530aad90fb2f3d775e247480650ea146cb8a
/Python Fundamentals/dojo_ninja/djnj/migrations/0001_initial.py
d211e87f04b92419bd6b7dd3ea345eb330dbfea3
[]
no_license
Marvin-Gerodias/PYTHON
713c5908485a03c002d2c30d64e83d7b84d56cfb
65f75c3180cf16171f7176555c53ab9a73f55c21
refs/heads/main
2023-04-25T16:53:17.043818
2021-05-02T13:15:25
2021-05-02T13:15:25
345,864,116
0
0
null
null
null
null
UTF-8
Python
false
false
1,285
py
# Generated by Django 2.2 on 2020-11-04 16:44 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Dojo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=25)), ('city', models.CharField(max_length=50)), ('state', models.CharField(max_length=50)), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ], ), migrations.CreateModel( name='Ninja', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('dojo_id', models.IntegerField()), ('first_name', models.CharField(max_length=25)), ('last_name', models.CharField(max_length=25)), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ], ), ]
d006fc415b4fe1c51b8845692542c12bc729eb38
9e14489270b26edbdafe7c168eb3cfa014df36a4
/tests/test_integration/test_smartcontract_event.py
73b0eda2ffb4171a8142b4404517d5461f850de4
[ "MIT" ]
permissive
aergoio/herapy
7b62a04bf9becb0b701594f7bfcb5530c8d477ab
cf8a6ab0fd50c12b0f5f3ca85ff015eda5108863
refs/heads/develop
2023-08-10T09:40:47.529167
2020-03-25T06:58:30
2020-03-25T06:58:30
148,101,359
7
4
MIT
2023-09-01T15:00:48
2018-09-10T05:00:38
Python
UTF-8
Python
false
false
6,108
py
import aergo.herapy as herapy def test_sc_event(aergo) -> None: print("------ Payload -----------") """ function constructor(name) contract.event("movie", "robocop", 1, "I'll be back") end function movie_event(name) contract.event("movie", "arnold", 2, "It's mine") contract.event("movie", "terminator", 3, "No, it's mine") end function ani_event(name) contract.event("a-time!!") contract.event("a-time!!", "pinn", "Adventure time!!", false, bignum.number("999999999999999"), {"princess bubble gum", 1} ) contract.event("a-time!!", "Jake", "Adventure time!!", false, {"whatever", 1, {true, false}, bignum.number("999999999999999")} ) contract.event("movie", "yoda", 3, "i'm not the ani character.") end abi.register(movie_event, ani_event) """ payload_str = "D1ZsfUyj4q8GA6AtbW81TzSTSvqaeUvcsePsaZufptRK5qSb83fyXRWdE" \ "gGhLWs17JfRNrM4iLjGe54fkyvsyjHVgFCHqTzJWK4Yz8uQwRqzF5x1g1twZ3jPP1Xt" \ "J95y43RD48qXGoeeoDsmmNErQJCux6d4eLZwE344bz5hM1DdWEd22yE6ogC37RLRtRZ" \ "5FFKm3HkxaM67G7VqWfsX5t2Tmd23Myn62hkAdNWjSBaWizqyi6ENB3VD2YJGG82bVe" \ "q9a4zMQdK58Wxnfcfqo14Vo9Y9jsY8A5QYNRi6uotRfiYt3LFrPjPBWgyQRn4qFQypS" \ "W5vfgFZvv9VBdFPGgoMN5zeBp7VNWXvE5o8CGAf3fuFu2gCGLS4DfCtQe7VNnsCUi7U" \ "1AdmdupqoxMHM6kCfEtk77YyiaaSTm4xUSt7R2hwzs2Xnfh8CLxMaH2cg3rsWF4fefs" \ "5KvnjN3F1q43og6BueK66o8NssyY41kAtincbYhDC8oHaBkMTdXD6mkhb3QECwn8dh8" \ "k9a3KTys1tdUzf99nqpK5YrAcZFDjbrmmmtcBYwZg6zdRAkQnJptvr25HzeHMfbfERH" \ "8P1XzYmjqYynFvUNv4utuWZ7avS2xvJoZph3nSa8Xuhbdw6TFLVCDZVfZB6j8kQbJnb" \ "1DoEEtvhPHLMP4StcgiE9grGQuduZ5iHYtS8Nk696Fq6Y9gzp19bWD3VKarq1XuueM6" \ "FNrzCQNY22nov4mxbM8vcxp4axdjmZNWLcdttFycazorxCNbn1YBQFzGPGzstJPN72R" \ "B9dxV17cb1TuREKTF7mVLLeahgHsY4eVnA1m5Z8U7tFKswRDTGeXv6vCt7MstVBztdd" \ "4sRfHTXKdFCgfoQk2zwzGS8FEVgxAP3Y4Tip4nuQd8hVyTiaApFmNnkD9byxUNCc44T" \ "r9LAnRycc239HGpZjWBwsJvmb4jsY2fuEELXfSgQf4yZhnbcPC4DYPQLDRXc8E6DdLz" \ "ixMk7cAfUZqododk9SWzjB9FSKtzVYWiKuyg2uZoRaxDmrtZpe6pXL8F4pzt2P2HEG6" \ "jyFn5MT9PBWhkj11vqAjWpdRgNAbTKEb5zk9ZeER9YUAT8etk2VFpAGqmGnv9CTEQr2" \ "rfDQeNgNYzoy44mNZonhi4n4zo9h2HmrSsatWa8oxbJJYihGs7zD65TiqRfnKg43Xx5" \ "qD" payload = herapy.utils.decode_address(payload_str) print(''.join('{:d} '.format(x) for x in payload)) byte_code_len = int.from_bytes(payload[:4], byteorder='little') print("payload: byte code length = ", byte_code_len) print("------ Set Sender Account -----------") sender_private_key = "6hbRWgddqcg2ZHE5NipM1xgwBDAKqLnCKhGvADWrWE18xAbX8sW" sender_account = aergo.new_account(private_key=sender_private_key) print(" > Sender Address: {}".format(sender_account.address)) print(herapy.utils.convert_bytes_to_int_str(bytes(sender_account.address))) print("------ Deploy SC -----------") tx, result = aergo.deploy_sc(amount=0, payload=payload, args=1234, retry_nonce=5) print(" > TX: {}".format(tx.tx_hash)) print("{}".format(str(tx))) assert result.status == herapy.CommitStatus.TX_OK, \ " > ERROR[{0}]: {1}".format(result.status, result.detail) print(" > result[{0}] : {1}".format(result.tx_id, result.status.name)) print(herapy.utils.convert_bytes_to_int_str(bytes(tx.tx_hash))) aergo.wait_tx_result(tx.tx_hash) print("------ Check deployment of SC -----------") print(" > TX: {}".format(tx.tx_hash)) result = aergo.get_tx_result(tx.tx_hash) assert result.status == herapy.TxResultStatus.CREATED, \ " > ERROR[{0}]:{1}: {2}".format( result.contract_address, result.status, result.detail) sc_address = result.contract_address print(" > SC Address: {}".format(sc_address)) print("------ Get events -----------") events = aergo.get_events(sc_address, "movie", with_desc=True, arg_filter={0: 'arnold'}) print("how many 'arnold' in movie? {}".format(len(events))) assert len(events) == 0 events = aergo.get_events(sc_address, "movie", with_desc=True, arg_filter={0: 'robocop'}) print("how many 'robocop' in movie? {}".format(len(events))) assert len(events) == 1 event_block_no = 0 for i, e in enumerate(events): event_block_no = e.block_height print("[{}] Event: {}".format(i, str(e))) events = aergo.get_events( sc_address, "movie", end_block_no=event_block_no - 1) print("in history: how many movie? {}".format(len(events))) assert len(events) == 0 events = aergo.get_events( sc_address, "movie", start_block_no=event_block_no + 1) print("after: how many movie? {}".format(len(events))) assert len(events) == 0 print("------ Call SC -----------") tx, result = aergo.call_sc(sc_address, "movie_event") print("movie_event tx hash: {}".format(str(tx.tx_hash))) aergo.wait_tx_result(tx.tx_hash) print("------ Get events -----------") events = aergo.get_events(sc_address, "movie") print("how many 'movie'? {}".format(len(events))) assert len(events) == 3 for i, e in enumerate(events): print("[{}] Event: {}".format(i, str(e))) events = aergo.get_events(sc_address, "a-time!!") print("how many 'a-time!!'? {}".format(len(events))) assert len(events) == 0 print("------ Call SC -----------") tx, result = aergo.call_sc(sc_address, "ani_event") print("ani_event tx hash: {}".format(str(tx.tx_hash))) aergo.wait_tx_result(tx.tx_hash) print("------ Get events -----------") events = aergo.get_events(sc_address, "movie") print("how many 'movie'? {}".format(len(events))) assert len(events) == 4 events = aergo.get_events(sc_address, "a-time!!") print("how many 'a-time!!'? {}".format(len(events))) assert len(events) == 3 for i, e in enumerate(events): print("[{}] Event: {}".format(i, str(e)))
53ef131a0b9babc5af8fa15c91c4fca6cc7de93c
69c882c678103b182988fb60d3e898d569980f1c
/Day 4/day4prog4.py
5f6224da0ba42f841f9b5541f0a3d0a63e87733b
[]
no_license
gittygupta/stcet-python
44be9d91cdd6215879d9f04497214819228821be
e77456172746ee76b6e2a901ddb0c3dbe457f82a
refs/heads/master
2022-03-05T11:37:08.720226
2019-12-01T00:56:03
2019-12-01T00:56:03
null
0
0
null
null
null
null
UTF-8
Python
false
false
135
py
n=2 while n<1000: flag=1 for i in range (2,n): if n%i==0: flag=0 if flag==1: print(n) n+=1
87066daea6b025f1f57bef0bebc6300a22a86811
ccd94d87e16876ae1df22cc790043a516bb60735
/Utility.py
e2cd8eb1626a442bbad302f0f6cfb59ff56914dc
[]
no_license
baixiaobest/modern_robotics
d1028300bb74086884a63ad87f50192189d72104
4578f87608c946442ee28cb365944dba7ff83be8
refs/heads/master
2021-03-24T21:03:24.600215
2020-04-07T01:15:30
2020-04-07T01:15:30
247,564,862
0
0
null
null
null
null
UTF-8
Python
false
false
19,673
py
import modern_robotics as mr ''' M: Configuration of end effector. Slist: A list of screw axes. thetas: A list of theta vales. ''' import numpy as np def forward_kinematics_space(M, Slist, thetas): T = np.array(M).copy().astype(np.float) for i in range(len(thetas)-1, -1, -1): T = mr.MatrixExp6(mr.VecTose3(Slist[:, i] * thetas[i])) @ T return T def forward_kinematics_body(M, Blist, thetas): T = np.array(M).copy().astype(np.float) for i in range(len(thetas)): T = T @ mr.MatrixExp6(mr.VecTose3(Blist[:, i] * thetas[i])) return T def jacobian_space(Slist, thetas): jac = np.array(Slist).copy().astype(np.float) T = np.identity(4) for i in range(1, len(thetas), 1): # Rigid body transformation from root to current joint i. T = T @ mr.MatrixExp6(mr.VecTose3(Slist[:, i - 1] * thetas[i - 1])) # Adjoint matrix of this transfomation. adj = mr.Adjoint(T) jac[:, i] = adj @ Slist[:, i] return jac def jacobian_body(Blist, thetas): jac = np.array(Blist).copy().astype(np.float) T = np.identity(4) for i in range(len(thetas)-2, -1, -1): T = T @ mr.MatrixExp6(mr.VecTose3(-Blist[:, i + 1] * thetas[i + 1])) adj = mr.Adjoint(T) jac[:, i] = adj @ Blist[:, i] return jac ''' Inverse kinematics Slist: List of screws at zero configuration. M: SE3 configuration of end effector in zero configuration. T: Desired end effector configuration thetas_guess: Initial theta guess. eomg: Angular error to satisfy. ev: Linear error to satisfy. max_iteration: Maximum number of iteration. return (thetas, success): thetas is joint configuration. success is true when result is found. ''' def IK_space(Slist, M, T, thetas_guess, eomg, ev, max_iteration=20): thetas = np.array(thetas_guess).copy().astype(np.float) Tsd = np.array(T).copy().astype(np.float) success = False for i in range(max_iteration): # Calculate space frame transform from end effector to desired position. Tsb = forward_kinematics_space(M, Slist, thetas) Tbd = Tsd @ np.linalg.inv(Tsb) # Twist in matrix form. Vs_se3 = mr.MatrixLog6(Tbd) Vs = mr.se3ToVec(Vs_se3) # Check if result is a success. if np.linalg.norm(Vs[0:3]) < eomg and np.linalg.norm(Vs[3:6]) < ev: success = True break Jac = jacobian_space(Slist, thetas) thetas = (thetas + np.linalg.pinv(Jac) @ Vs) % (2 * np.pi) return (thetas, success) def IK_body(Blist, M, T, thetas_guess, eomg, ev, max_iteration=20): thetas = np.array(thetas_guess).copy().astype(np.float) Tsd = np.array(T).copy().astype(np.float) success = False for i in range(max_iteration): # Calculate space frame transform from end effector to desired position. Tsb = forward_kinematics_body(M, Blist, thetas) Tbd = np.linalg.inv(Tsb) @ Tsd # Twist in matrix form. Vb_se3 = mr.MatrixLog6(Tbd) Vb = mr.se3ToVec(Vb_se3) # Check if result is a success. if np.linalg.norm(Vb[0:3]) < eomg and np.linalg.norm(Vb[3:6]) < ev: success = True break Jac = jacobian_body(Blist, thetas) thetas = (thetas + np.linalg.pinv(Jac) @ Vb) % (2 * np.pi) return (thetas, success) """Computes inverse dynamics in the space frame for an open chain robot :param thetalist: n-vector of joint variables :param dthetalist: n-vector of joint rates :param ddthetalist: n-vector of joint accelerations :param g: Gravity vector g :param Ftip: Spatial force applied by the end-effector expressed in frame {n+1} :param Mlist: List of link frames {i} relative to {i-1} at the home position :param Glist: Spatial inertia matrices Gi of the links :param Slist: Screw axes Si of the joints in a space frame, in the format of a matrix with axes as the columns :return: The n-vector of required joint forces/torques """ def InverseDynamics(thetalist, dthetalist, ddthetalist, g, Ftip, Mlist, Glist, Slist): V_i_list = [] dV_i_list = [] T_i_prev_list = [] A_i_list = [] torques = np.zeros(thetalist.shape[0]) ''' Begin forward iteration. ''' n = len(thetalist) # Previous twist V_prev = np.zeros(6) dV_prev = np.zeros(6) dV_prev[3:6] = -np.array(g) M_i = np.identity(4) for i in range(n): # Home position configuration of current i frame relative to space fixed frame. M_i = M_i @ Mlist[i] # Screw axis Si of the joint i expressed in i frame. A_i = mr.Adjoint(mr.TransInv(M_i)) @ Slist[:, i] # Configuration of i-1 frame relative to i frame with theta_i at joint i. T_i_prev = mr.MatrixExp6(-mr.VecTose3(A_i) * thetalist[i]) @ mr.TransInv(Mlist[i]) # Twist of link i in frame i. V_i = A_i * dthetalist[i] + mr.Adjoint(T_i_prev) @ V_prev dV_i = A_i * ddthetalist[i] + mr.Adjoint(T_i_prev) @ dV_prev + mr.ad(V_i) @ A_i * dthetalist[i] # Store these for backward iteration. A_i_list.append(A_i) V_i_list.append(V_i) dV_i_list.append(dV_i) T_i_prev_list.append(T_i_prev) # Store V and dV for next iteration. V_prev = V_i dV_prev = dV_i # Add the transformation from robotic arm tip to last link. T_i_prev_list.append(mr.TransInv(Mlist[n])) ''' Begin backward iteration. ''' # Wrench in frame i + 1 F_next = Ftip for i in range(n-1, -1, -1): F_i = mr.Adjoint(T_i_prev_list[i + 1]).T @ F_next \ + Glist[i] @ dV_i_list[i] - mr.ad(V_i_list[i]).T @ Glist[i] @ V_i_list[i] torques[i] = F_i.T @ A_i_list[i] F_next = F_i return torques """Computes the mass matrix of an open chain robot based on the given configuration :param thetalist: A list of joint variables :param Mlist: List of link frames i relative to i-1 at the home position :param Glist: Spatial inertia matrices Gi of the links :param Slist: Screw axes Si of the joints in a space frame, in the format of a matrix with axes as the columns :return: The numerical inertia matrix M(thetalist) of an n-joint serial chain at the given configuration thetalist """ def MassMatrix(thetalist, Mlist, Glist, Slist): n = len(thetalist) M = np.zeros((n, n)) dthetalist = np.zeros(n) Ftip = np.zeros(6) g = np.zeros(3) for i in range(n): ddthetalist = np.zeros(n) ddthetalist[i] = 1.0 tau = InverseDynamics(thetalist, dthetalist, ddthetalist, g, Ftip, Mlist, Glist, Slist) M[i, :] = tau return M """ Computes the Coriolis and centripetal terms in the inverse dynamics of an open chain robot :param thetalist: A list of joint variables, :param dthetalist: A list of joint rates, :param Mlist: List of link frames i relative to i-1 at the home position, :param Glist: Spatial inertia matrices Gi of the links, :param Slist: Screw axes Si of the joints in a space frame, in the format of a matrix with axes as the columns. :return: The vector c(thetalist,dthetalist) of Coriolis and centripetal terms for a given thetalist and dthetalist. """ def VelQuadraticForces(thetalist, dthetalist, Mlist, Glist, Slist): n = len(thetalist) ddthetalist = np.zeros(n) Ftip = np.zeros(6) g = np.zeros(3) return InverseDynamics(thetalist, dthetalist, ddthetalist, g, Ftip, Mlist, Glist, Slist) """Computes the joint forces/torques an open chain robot requires to overcome gravity at its configuration :param thetalist: A list of joint variables :param g: 3-vector for gravitational acceleration :param Mlist: List of link frames i relative to i-1 at the home position :param Glist: Spatial inertia matrices Gi of the links :param Slist: Screw axes Si of the joints in a space frame, in the format of a matrix with axes as the columns :return grav: The joint forces/torques required to overcome gravity at thetalist """ def GravityForces(thetalist, g, Mlist, Glist, Slist): n = len(thetalist) dthetalist = np.zeros(n) ddthetalist = np.zeros(n) Ftip = np.zeros(6) return InverseDynamics(thetalist, dthetalist, ddthetalist, g, Ftip, Mlist, Glist, Slist) """Computes the joint forces/torques an open chain robot requires only to create the end-effector force Ftip :param thetalist: A list of joint variables :param Ftip: Spatial force applied by the end-effector expressed in frame {n+1} :param Mlist: List of link frames i relative to i-1 at the home position :param Glist: Spatial inertia matrices Gi of the links :param Slist: Screw axes Si of the joints in a space frame, in the format of a matrix with axes as the columns :return: The joint forces and torques required only to create the end-effector force Ftip """ def EndEffectorForces(thetalist, Ftip, Mlist, Glist, Slist): n = len(thetalist) dthetalist = np.zeros(n) ddthetalist = np.zeros(n) g = np.zeros(3) return InverseDynamics(thetalist, dthetalist, ddthetalist, g, Ftip, Mlist, Glist, Slist) """Computes forward dynamics in the space frame for an open chain robot :param thetalist: A list of joint variables :param dthetalist: A list of joint rates :param taulist: An n-vector of joint forces/torques :param g: Gravity vector g :param Ftip: Spatial force applied by the end-effector expressed in frame {n+1} :param Mlist: List of link frames i relative to i-1 at the home position :param Glist: Spatial inertia matrices Gi of the links :param Slist: Screw axes Si of the joints in a space frame, in the format of a matrix with axes as the columns :return: The resulting joint accelerations """ def ForwardDynamics(thetalist, dthetalist, taulist, g, Ftip, Mlist, Glist, Slist): M = MassMatrix(thetalist, Mlist, Glist, Slist) VQF = VelQuadraticForces(thetalist, dthetalist, Mlist, Glist, Slist) G = GravityForces(thetalist, g, Mlist, Glist, Slist) EFF = EndEffectorForces(thetalist, Ftip, Mlist, Glist, Slist) return np.linalg.inv(M) @ (taulist - VQF - G - EFF) """Compute the joint angles and velocities at the next timestep using from here first order Euler integration :param thetalist: n-vector of joint variables :param dthetalist: n-vector of joint rates :param ddthetalist: n-vector of joint accelerations :param dt: The timestep delta t :return thetalistNext: Vector of joint variables after dt from first order Euler integration :return dthetalistNext: Vector of joint rates after dt from first order Euler integration """ def EulerStep(thetalist, dthetalist, ddthetalist, dt): thetalist_next = thetalist + dthetalist * dt dthetalist_next = dthetalist + ddthetalist * dt return thetalist_next, dthetalist_next """Calculates the joint forces/torques required to move the serial chain along the given trajectory using inverse dynamics :param thetamat: An N x n matrix of robot joint variables :param dthetamat: An N x n matrix of robot joint velocities :param ddthetamat: An N x n matrix of robot joint accelerations :param g: Gravity vector g :param Ftipmat: An N x 6 matrix of spatial forces applied by the end- effector (If there are no tip forces the user should input a zero and a zero matrix will be used) :param Mlist: List of link frames i relative to i-1 at the home position :param Glist: Spatial inertia matrices Gi of the links :param Slist: Screw axes Si of the joints in a space frame, in the format of a matrix with axes as the columns :return: The N x n matrix of joint forces/torques for the specified trajectory, where each of the N rows is the vector of joint forces/torques at each time step """ def InverseDynamicsTrajectory(thetamat, dthetamat, ddthetamat, g, Ftipmat, Mlist, Glist, Slist): N, n = thetamat.shape taulist = np.zeros((N, n)) for i in range(N): taulist[i, :] = InverseDynamics(thetamat[i, :], dthetamat[i, :], ddthetamat[i, :], g, Ftipmat[i, :], \ Mlist, Glist, Slist) return taulist """Simulates the motion of a serial chain given an open-loop history of joint forces/torques :param thetalist: n-vector of initial joint variables :param dthetalist: n-vector of initial joint rates :param taumat: An N x n matrix of joint forces/torques, where each row is the joint effort at any time step :param g: Gravity vector g :param Ftipmat: An N x 6 matrix of spatial forces applied by the end- effector (If there are no tip forces the user should input a zero and a zero matrix will be used) :param Mlist: List of link frames {i} relative to {i-1} at the home position :param Glist: Spatial inertia matrices Gi of the links :param Slist: Screw axes Si of the joints in a space frame, in the format of a matrix with axes as the columns :param dt: The timestep between consecutive joint forces/torques :param intRes: Integration resolution is the number of times integration (Euler) takes places between each time step. Must be an integer value greater than or equal to 1 :return thetamat: The N x n matrix of robot joint angles resulting from the specified joint forces/torques :return dthetamat: The N x n matrix of robot joint velocities """ def ForwardDynamicsTrajectory(thetalist, dthetalist, taumat, g, Ftipmat, Mlist, Glist, Slist, dt, intRes): euler_dt = dt / intRes N, n = taumat.shape thetamat = np.zeros((N, n)) dthetamat = np.zeros((N, n)) curr_thetalist = thetalist curr_dthetalist = dthetalist for i in range(N): for j in range(intRes): ddthetalist = ForwardDynamics(curr_thetalist, curr_dthetalist, taumat[i, :], g, Ftipmat[i, :], Mlist, Glist, Slist) curr_thetalist, curr_dthetalist = EulerStep(curr_thetalist, curr_dthetalist, ddthetalist, euler_dt) thetamat[i, :] = curr_thetalist.copy() dthetamat[i, :] = curr_dthetalist.copy() return thetamat, dthetamat """Computes s(t) for a cubic time scaling :param Tf: Total time of the motion in seconds from rest to rest :param t: The current time t satisfying 0 < t < Tf :return: The path parameter s(t) corresponding to a third-order polynomial motion that begins and ends at zero velocity """ def CubicTimeScaling(Tf, t): a2 = 3 / (Tf ** 2) a3 = -2 / (Tf ** 3) return a2 * t ** 2 + a3 * t ** 3 """Computes s(t) for a quintic time scaling :param Tf: Total time of the motion in seconds from rest to rest :param t: The current time t satisfying 0 < t < Tf :return: The path parameter s(t) corresponding to a fifth-order polynomial motion that begins and ends at zero velocity and zero acceleration """ def QuinticTimeScaling(Tf, t): return 10 * (1.0 * t / Tf) ** 3 - 15 * (1.0 * t / Tf) ** 4 \ + 6 * (1.0 * t / Tf) ** 5 """Computes a straight-line trajectory in joint space :param thetastart: The initial joint variables :param thetaend: The final joint variables :param Tf: Total time of the motion in seconds from rest to rest :param N: The number of points N > 1 (Start and stop) in the discrete representation of the trajectory :param method: The time-scaling method, where 3 indicates cubic (third- order polynomial) time scaling and 5 indicates quintic (fifth-order polynomial) time scaling :return: A trajectory as an N x n matrix, where each row is an n-vector of joint variables at an instant in time. The first row is thetastart and the Nth row is thetaend . The elapsed time between each row is Tf / (N - 1) """ def JointTrajectory(thetastart, thetaend, Tf, N, method=3): dt = Tf / (N - 1.0) trajectory = np.zeros((N, len(thetastart))) for i in range(N): t = i * dt s = 0 if method == 3: s = CubicTimeScaling(Tf, t) elif method == 5: s = QuinticTimeScaling(Tf, t) trajectory[i] = (1 - s) * thetastart + s * thetaend return trajectory """Computes a trajectory as a list of N SE(3) matrices corresponding to the screw motion about a space screw axis :param Xstart: The initial end-effector configuration :param Xend: The final end-effector configuration :param Tf: Total time of the motion in seconds from rest to rest :param N: The number of points N > 1 (Start and stop) in the discrete representation of the trajectory :param method: The time-scaling method, where 3 indicates cubic (third- order polynomial) time scaling and 5 indicates quintic (fifth-order polynomial) time scaling :return: The discretized trajectory as a list of N matrices in SE(3) separated in time by Tf/(N-1). The first in the list is Xstart and the Nth is Xend """ def ScrewTrajectory(Xstart, Xend, Tf, N, method=3): dt = Tf / (N - 1.0) trajectory = [] Xstart_end = mr.TransInv(Xstart) @ Xend for i in range(N): t = i * dt s = 0 if method == 3: s = CubicTimeScaling(Tf, t) elif method == 5: s = QuinticTimeScaling(Tf, t) trajectory.append(Xstart @ mr.MatrixExp6(mr.MatrixLog6(Xstart_end) * s)) return trajectory """Computes a trajectory as a list of N SE(3) matrices corresponding to the origin of the end-effector frame following a straight line :param Xstart: The initial end-effector configuration :param Xend: The final end-effector configuration :param Tf: Total time of the motion in seconds from rest to rest :param N: The number of points N > 1 (Start and stop) in the discrete representation of the trajectory :param method: The time-scaling method, where 3 indicates cubic (third- order polynomial) time scaling and 5 indicates quintic (fifth-order polynomial) time scaling :return: The discretized trajectory as a list of N matrices in SE(3) separated in time by Tf/(N-1). The first in the list is Xstart and the Nth is Xend This function is similar to ScrewTrajectory, except the origin of the end-effector frame follows a straight line, decoupled from the rotational motion. """ def CartesianTrajectory(Xstart, Xend, Tf, N, method): dt = Tf / (N - 1.0) trajectory = [] Rstart = Xstart[0:3, 0:3] Rend = Xend[0:3, 0:3] Rstart_end = mr.RotInv(Rstart) @ Rend tstart = Xstart[0:3, 3] tend = Xend[0:3, 3] for i in range(N): t = i * dt s = 0 if method == 3: s = CubicTimeScaling(Tf, t) elif method == 5: s = QuinticTimeScaling(Tf, t) Rs = Rstart @ mr.MatrixExp3(mr.MatrixLog3(Rstart_end) * s) ts = tstart * (1 - s) + tend * s T = np.identity(4) T[0:3, 0:3] = Rs T[0:3, 3] = ts trajectory.append(T) return trajectory
c729e3879f9d4d6d10dc2a19f15ce87f3e3c45ad
95ed61745cdbfd0382cf2227262f6d8db7907e58
/parkingmanagement/apps/parkings/models.py
df18e31d76e1519e8e0682f36a98af5063da0701
[ "Apache-2.0" ]
permissive
vivek-at-work/ridecell-code
4a856028fbb8df4d7cd14e1f860575e17618c008
93965a1437197102eca6cf6313ba3dbb4c3f5c3c
refs/heads/main
2022-12-31T22:16:16.902614
2020-10-21T05:42:02
2020-10-21T05:42:02
305,413,393
0
0
null
null
null
null
UTF-8
Python
false
false
3,817
py
from django.contrib.auth import get_user_model from django.contrib.gis.db import models as geo_models from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from parkings.exceptions import (NotAvailableToCancelError, ParkingSpotNotAvailableError) USER = get_user_model() class ParkingSpotQuerySet(models.QuerySet): def available(self): return self.filter(is_reserved=False) class ParkingSpot(models.Model): """ An Parking Spot that is registered to the system for further bookings. """ code = models.CharField( max_length=256, help_text=_('Human readable name/code'), ) is_reserved = models.BooleanField(default=False) point = geo_models.PointField( geography=True, help_text=_('Represented as (longitude, latitude)'), ) current_base_cost = models.FloatField( help_text=_('Price for the parking spot per minute'), ) objects = ParkingSpotQuerySet.as_manager() def reserve(self, **kwargs): """"Reserve this parking and create booking object Raises: ParkingSpotNotAvailableError: raises exception if trying to book already booked parking. Returns: Booking: A Booking object with booking details. """ if self.is_reserved: raise ParkingSpotNotAvailableError(self) self.is_reserved = True kwargs.update( {'applicable_base_cost': self.current_base_cost, 'parking_spot': self}, ) return Booking.objects.create(**kwargs) def release(self, **kwargs): # TODO We can change "is_reserved" to _is_reserved """" a setter method to release this parking object """ self.is_reserved = False def __str__(self): return '%s' % (self.code) class BookingQuerySet(models.QuerySet): def current(self): return self.filter(cancelled_at__isnull=True) class Booking(models.Model): """ An Parking Spot that is registered to the system for further bookings. """ parking_spot = models.ForeignKey( ParkingSpot, on_delete=models.CASCADE, related_name='bookings', help_text=_('Parking Spot for which booking is Created.'), ) from_time = models.DateTimeField( help_text=_('from what time this booking is valid.'), ) valid_up_to = models.DateTimeField( help_text=_('till what time this booking is valid.'), ) tenant = models.ForeignKey( USER, on_delete=models.CASCADE, related_name='bookings', help_text=_('User for whom booking is Created.'), ) cancelled_at = models.DateTimeField( blank=True, null=True, help_text=_('Till what time this booking is valid.'), ) applicable_base_cost = models.FloatField( blank=True, null=True, help_text=_('Cost at which the booking was done.'), ) objects = BookingQuerySet.as_manager() @property def total_cost(self): """total cost applicable for this booking Returns: float: total cost applicable """ from_time = self.from_time valid_up_to = self.valid_up_to calc = (valid_up_to - from_time).total_seconds() / 60 * self.applicable_base_cost return round(calc,2) def cancel(self): """ Cancels this booking and releses the parking spot """ if self.cancelled_at is not None: raise NotAvailableToCancelError(self) self.cancelled_at = timezone.now() self.parking_spot.release() self.parking_spot.save() def __str__(self): return f'{self.parking_spot} - {self.from_time} - {self.valid_up_to}'
7d338e5a8b5dc51316b80554dabd0cadfd5c5310
fc63292a3c809681b5befdcf222862865f7d8b48
/src/scripts/references/plotingMotion.py
96091bb18fd6bb55465214cf9a7e83d5e31ade04
[]
no_license
fbeltranmillalen/SimulacionRobot
94a979e2e69551f827c2bf5b882bcc88c7783284
cb6eb08b24ed8e31ee0c0388899dd2f1f28b53d0
refs/heads/master
2020-06-19T06:00:56.524304
2019-08-19T21:36:11
2019-08-19T21:36:11
196,590,126
1
0
null
null
null
null
UTF-8
Python
false
false
847
py
import math import matplotlib.pyplot as plt import numpy as np pathFile = "D:/Fun things/datosMecanicaPython/fallingtennisball02.d" time, position = np.loadtxt(pathFile, usecols=[0, 1], unpack=True) velocity = [] acceleration = [] for i in range(len(position) - 1): velocity.append((position[i+1] - position[i]) / (time[1] - time[0])) velocity.append(velocity[len(velocity) - 1]) for i in range(1, len(position) - 1): acceleration.append((velocity[i] - velocity[i-1]) / (time[1] - time[0])) acceleration.append(acceleration[len(acceleration) - 1]) acceleration.append(acceleration[len(acceleration) - 1]) print(len(time), len(acceleration)) #plt.scatter(time, velocity) plt.figure() plt.subplot(131) plt.scatter(time, position) plt.subplot(132) plt.scatter(time, velocity) plt.subplot(133) plt.scatter(time, acceleration) plt.show()
8395dfb10cc1f95b066ed45e0d94250331d4a1be
d3ae798467818b0bc860e0cc6827037e0493e1b7
/djstripe/safe_settings.py
72e22957502ab0a01929b273e4357d5dc120ac3b
[]
no_license
7WebPages/dj-stripe
7abc94e7a0d90b9e073b5a1f6c76ccc1dff946cd
7f7b97095f3899df7a92b19a9ac4d0ec88dd29c3
refs/heads/master
2021-01-15T21:49:04.639392
2015-08-03T04:52:42
2015-08-03T04:52:42
41,661,706
0
0
null
2015-08-31T07:23:51
2015-08-31T07:23:50
null
UTF-8
Python
false
false
848
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings STRIPE_PUBLIC_KEY = settings.STRIPE_PUBLIC_KEY INVOICE_FROM_EMAIL = getattr( settings, "DJSTRIPE_INVOICE_FROM_EMAIL", "[email protected]" ) PASSWORD_INPUT_RENDER_VALUE = getattr( settings, 'DJSTRIPE_PASSWORD_INPUT_RENDER_VALUE', False) PASSWORD_MIN_LENGTH = getattr( settings, 'DJSTRIPE_PASSWORD_MIN_LENGTH', 6) PRORATION_POLICY = getattr( settings, 'DJSTRIPE_PRORATION_POLICY', False) PRORATION_POLICY_FOR_UPGRADES = getattr( settings, 'DJSTRIPE_PRORATION_POLICY_FOR_UPGRADES', False) # TODO - need to find a better way to do this CANCELLATION_AT_PERIOD_END = not PRORATION_POLICY # Manages sending of receipt emails SEND_INVOICE_RECEIPT_EMAILS = getattr(settings, "DJSTRIPE_SEND_INVOICE_RECEIPT_EMAILS", True)
f530eb6a522913bea01696af029e4d6e9f51c865
cc103af2a562e636c0da80fb48c43178e5820bc5
/tensor/bin/pbr
2822693968f1d1487eb59f95eae35b658783b7a6
[]
no_license
refcell/FractalTreeModels
8cb9112c652fe4faeb0554ebd68f707191aceed6
d7bcb1c9942f52f98c49526c6e4aee3359e7ed68
refs/heads/master
2023-07-01T23:18:24.073965
2019-04-28T05:54:05
2019-04-28T05:54:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
265
#!/Users/andreasbigger/Desktop/FractalTreeModels/tensor/bin/python3.7 # -*- coding: utf-8 -*- import re import sys from pbr.cmd.main import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(main())
d5d44ca8acb60603aaa8f3eeb48c46474f89f745
ced798ec435423dcb06cec6bd998a19cba6ba4c8
/flask项目/home/lghome/tasks/sms/tasks.py
2182360a0c639803990a9aa0f2c120794b1453ce
[]
no_license
gengsini12345678/house-renting
bb58c2259c6f41e84affda30a6904aedc0be7b6e
d5c8ed9f5812774ede0a0385c13d25f90c1b17f6
refs/heads/master
2023-03-07T15:13:38.295423
2021-02-21T12:38:47
2021-02-21T12:38:47
340,880,800
0
0
null
null
null
null
UTF-8
Python
false
false
260
py
from lghome.tasks.main import celery_app from lghome.libs.ronglianyun.ccp_sms import CCP @celery_app.task def send_sms(mobile, datas, tid): """ 发送短信的异步任务 :return: """ ccp = CCP() ccp.send_message(mobile, datas, tid)
32406acc6653cdc29f431537283b1d45072e9a56
e89b15c6d2592f9c905e277c746e71d5100f8d8c
/_tests/test_permute_columns.py
abb2d80690576788c51726bbb153b052e20309fe
[ "Apache-2.0" ]
permissive
allison-cy-wu/utility_functions
92880e7427391621da1c1e29f0ebd28adb1289c0
d2c6246c96b9cd5e8c01292dd38ab0d572971698
refs/heads/master
2021-07-24T05:29:16.985318
2020-07-22T19:47:17
2020-07-22T19:47:17
201,665,640
0
0
Apache-2.0
2020-07-22T19:47:18
2019-08-10T18:02:58
Python
UTF-8
Python
false
false
1,464
py
import unittest from unittest import TestCase from utility_functions.stats_functions import permute_columns from utility_functions.databricks_uf import has_column from connect2Databricks.spark_init import spark_init if 'spark' not in locals(): spark, sqlContext, setting = spark_init() sc = spark.sparkContext class TestPermuteColumns(TestCase): def test_permute_columns(self): data = spark.createDataFrame([(1, 'a', 'a'), (2, 'b', 'b'), (3, 'c', 'c'), (4, 'd', 'd'), (5, 'e', 'e')], ['id', 'col1', 'col2']) permuted_data = permute_columns(data, columns_to_permute = ['col1', 'col2'], column_to_order = 'id', ind_permute = False) permuted_data.show() self.assertTrue(has_column(permuted_data, 'rand_id')) self.assertTrue(has_column(permuted_data, 'rand_col1')) self.assertTrue(has_column(permuted_data, 'rand_col2')) self.assertEqual(permuted_data.select('rand_col1').collect(), permuted_data.select('rand_col2').collect()) self.assertNotEqual(permuted_data.select('col1').collect(), permuted_data.select('rand_col1').collect()) if __name__ == '__main__': unittest.main()
2ffa3ff0ebf51a6f97b81338b4f1005ebcb68abd
302d239446b5493a0349130e20c6164df5691698
/node_modules/socket.io-client/node_modules/ws/build/config.gypi
c5412f841a5d806f243e18b929292cff0f752b9c
[ "MIT" ]
permissive
xgrommx/twitterbot
7097d91c3c5d0efac9efea45784608326032835c
ab91d003f42f18677d5a716a1aacd71e0992c6c6
refs/heads/master
2021-01-10T18:40:32.450473
2013-11-27T01:26:04
2013-11-27T01:26:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,217
gypi
# Do not edit. File was generated by node-gyp's "configure" step { "target_defaults": { "cflags": [], "default_configuration": "Release", "defines": [], "include_dirs": [], "libraries": [] }, "variables": { "clang": 0, "host_arch": "ia32", "node_install_npm": "true", "node_prefix": "", "node_shared_cares": "false", "node_shared_http_parser": "false", "node_shared_libuv": "false", "node_shared_openssl": "false", "node_shared_v8": "false", "node_shared_zlib": "false", "node_tag": "", "node_unsafe_optimizations": 0, "node_use_dtrace": "false", "node_use_etw": "true", "node_use_openssl": "true", "node_use_perfctr": "true", "node_use_systemtap": "false", "python": "c:\\python27\\python.exe", "target_arch": "x64", "v8_enable_gdbjit": 0, "v8_no_strict_aliasing": 1, "v8_use_snapshot": "true", "visibility": "", "nodedir": "C:\\Users\\Denis\\.node-gyp\\0.10.20", "copy_dev_lib": "true", "standalone_static_library": 1, "registry": "https://registry.npmjs.org/", "prefix": "C:\\Users\\Denis\\AppData\\Roaming\\npm", "always_auth": "", "bin_links": "true", "browser": "", "cache": "C:\\Users\\Denis\\AppData\\Roaming\\npm-cache", "cache_lock_stale": "60000", "cache_lock_retries": "10", "cache_lock_wait": "10000", "cache_max": "null", "cache_min": "10", "color": "true", "coverage": "", "depth": "null", "description": "true", "dev": "", "editor": "notepad.exe", "engine_strict": "", "force": "", "fetch_retries": "2", "fetch_retry_factor": "10", "fetch_retry_mintimeout": "10000", "fetch_retry_maxtimeout": "60000", "git": "git", "global": "", "globalconfig": "C:\\Users\\Denis\\AppData\\Roaming\\npm\\etc\\npmrc", "globalignorefile": "C:\\Users\\Denis\\AppData\\Roaming\\npm\\etc\\npmignore", "group": "", "ignore": "", "init_module": "C:\\Users\\Denis\\.npm-init.js", "init_version": "0.0.0", "init_author_name": "", "init_author_email": "", "init_author_url": "", "json": "", "link": "", "long": "", "message": "%s", "node_version": "v0.10.20", "npaturl": "http://npat.npmjs.org/", "npat": "", "onload_script": "", "optional": "true", "parseable": "", "pre": "", "production": "", "proprietary_attribs": "true", "https_proxy": "", "user_agent": "node/v0.10.20 win32 x64", "rebuild_bundle": "true", "rollback": "true", "save": "", "save_bundle": "", "save_dev": "", "save_optional": "", "searchopts": "", "searchexclude": "", "searchsort": "name", "shell": "C:\\WINDOWS\\system32\\cmd.exe", "shrinkwrap": "true", "sign_git_tag": "", "strict_ssl": "true", "tag": "latest", "tmp": "C:\\Users\\Denis\\AppData\\Local\\Temp", "unicode": "true", "unsafe_perm": "true", "usage": "", "user": "", "username": "", "userconfig": "C:\\Users\\Denis\\.npmrc", "userignorefile": "C:\\Users\\Denis\\.npmignore", "umask": "18", "version": "", "versions": "", "viewer": "browser", "yes": "" } }
316df07ff41eee45ba42637cebf15b17bbac0999
2cfe5a514f5ef0bb7a0803479fa280c6172953fc
/python3/koans/about_control_statements.py
a59c20fc13112a8d990109c909d4ed0633dc7d5d
[ "MIT" ]
permissive
sturivny/koans
34d99e8c14a5e04528964ad0240dba26a684fb20
67f093a55a38b470eb85428c9c26f206037825fc
refs/heads/master
2022-08-31T21:45:14.168819
2020-05-29T09:53:29
2020-05-29T09:53:29
263,155,020
0
0
null
null
null
null
UTF-8
Python
false
false
2,204
py
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutControlStatements(Koan): def test_if_then_else_statements(self): if True: result = 'true value' else: result = 'false value' self.assertEqual('true value', result) def test_if_then_statements(self): result = 'default value' if True: result = 'true value' self.assertEqual('true value', result) def test_if_then_elif_else_statements(self): if False: result = 'first value' elif True: result = 'true value' else: result = 'default value' self.assertEqual('true value', result) def test_while_statement(self): i = 1 result = 1 while i <= 10: result = result * i i += 1 self.assertEqual(3628800, result) def test_break_statement(self): i = 1 result = 1 while True: if i > 10: break result = result * i i += 1 self.assertEqual(3628800, result) def test_continue_statement(self): i = 0 result = [] while i < 10: i += 1 if (i % 2) == 0: continue result.append(i) self.assertEqual([1, 3, 5, 7, 9], result) def test_for_statement(self): phrase = ["fish", "and", "chips"] result = [] for item in phrase: result.append(item.upper()) self.assertEqual(['FISH', 'AND', 'CHIPS'], result) def test_for_statement_with_tuples(self): round_table = [ ("Lancelot", "Blue"), ("Galahad", "I don't know!"), ("Robin", "Blue! I mean Green!"), ("Arthur", "Is that an African Swallow or European Swallow?") ] result = [] for knight, answer in round_table: result.append("Contestant: '" + knight + "' Answer: '" + answer + "'") text = __ self.assertRegex(result[2], text) self.assertNotRegex(result[0], text) self.assertNotRegex(result[1], text) self.assertNotRegex(result[3], text)
ffdb5e9647923638ccfc7eb70b3d82fb1b8568ef
0099d15ea2291bf0a5d5ce31fbb6315009841221
/mysite/settings.py
0c9c63524595a1ebc5f6436d081daae5981a74eb
[]
no_license
kartiklucky9n/my-first-blog
0599621a44bbe1f8bf7cbbf94013777879d7bedf
43d46c600abbf209be244a707404d6afe992cf1a
refs/heads/master
2020-09-02T12:32:59.194048
2019-11-09T10:46:34
2019-11-09T10:46:34
219,213,088
0
0
null
null
null
null
UTF-8
Python
false
false
3,208
py
""" Django settings for mysite project. Generated by 'django-admin startproject' using Django 2.2.6. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '+$e^*_g2%gy&#ps___68hww1oef9k9s&&z#no#+6^p^w_*c#en' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', '.pythonanywhere.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog.apps.BlogConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Calcutta' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' #STATIC_ROOT = os.path.join(BASE_DIR, 'static')
e4f4c72c30322bb1881acb9b3893855462f80aca
bc784ed4db8ce628a13fa6d1a6606078f53ae7dc
/coincollector_mazes/refine_maze.py
b58f9ffdd0085773105d19a561bc4bc0e220ee0a
[]
no_license
AdeeshKolluru/TextWorld-Neural-Algorithmic-Reasoning
3daee4454567118dde3df526b2cdf8d206f4b445
6df5bc8f4e9df3a0e465dc9b042c0b1f83a2ff94
refs/heads/master
2023-06-24T17:16:16.503737
2021-07-21T11:17:10
2021-07-21T11:17:10
384,444,258
1
1
null
2021-07-20T21:46:17
2021-07-09T13:23:51
Jupyter Notebook
UTF-8
Python
false
false
6,194
py
import networkx as nx import random from coincollector_mazes.get_maze import get_maze, print_maze_info, add_shortest_path_info def identify_dangling_rooms(G: nx.DiGraph) -> dict: ''' Identifies rooms which have exactly one adjacent room. Args: G: A network-x DiGraph Returns: A dictionary with keys 0, 1, 2, 3, where key 0 [1/2/3] gives a list of string room names ('r_0', 'r_6' etc.) that have exactly one adjacent room and are north [east/south/west] of that adjacent room. ''' dangling_rooms = { 0: [], 1: [], 2: [], 3: [] } for node in G.nodes(): out_edges = list(G.edges(node)) if len(out_edges) == 1: # this means room is dangling dangling_direction = G.get_edge_data(*out_edges[0])['direction'] dangling_rooms[dangling_direction] += [node] return dangling_rooms def generate_exit_sentence(direction: int) -> str: sentences = [ 'There is an unguarded exit to the $.', 'There is an unblocked exit to the $.', "There is an exit to the $.Don't worry, it is unguarded.", "There is an exit to the $.Don't worry, it is unblocked.", "You don't like doors? Why not try going $, that entranceway is unguarded.", "You don't like doors? Why not try going $, that entranceway is unblocked.", ] directions = ['north','east','south','west'] sent = random.choice(sentences).replace('$', directions[direction]) return sent def count_left_right_turns(G: nx.DiGraph, path: list) -> tuple: left_turns = 0 right_turns = 0 for k in range(len(path)-2): if (G[path[k]][path[k+1]]['direction']+1)%4 == G[path[k+1]][path[k+2]]['direction']: right_turns += 1 elif (G[path[k]][path[k+1]]['direction']-1)%4 == G[path[k+1]][path[k+2]]['direction']: left_turns += 1 return left_turns, right_turns def determine_relative_room_position(G: nx.DiGraph, room1, room2, dangling_direction) -> int: connecting_path = nx.shortest_path(G, source=room1, target=room2) left_turns, right_turns = count_left_right_turns(G, connecting_path) if left_turns > right_turns: # start west/south of end return ((dangling_direction + 1) % 2) + 2 # if dangling south, then (2+1%2)+2=3 -> west elif left_turns < right_turns: # start north/east of end return (dangling_direction + 1) % 2 # if dangling south, then (2+1)%2=1 -> east elif left_turns == right_turns: # find the first step orthogonal to dangling direction for k in range(len(connecting_path)-1): if G[connecting_path[k]][connecting_path[k+1]]['direction']%2 == (dangling_direction+1)%2: first_orthogonal_step_direction = G[connecting_path[k]][connecting_path[k+1]]['direction'] return first_orthogonal_step_direction def dangling_room_list_depleted(dangling_rooms): for k in [0, 1, 2, 3]: if len(dangling_rooms[k]) < 2: return True return False def add_new_edges(G: nx.DiGraph, number_of_new_edges: int, seed: int) -> nx.DiGraph: ''' Adds new edges to a Coin-Collector maze to create circles in the graph. Args: G: A network-x graph representing a Coin-Collector world as generated by the function get_maze in coincollector_mazes.get_maze. number_of_new_edges: The number of new edges to be added. If more than one edge is added the maze may no longer be drawable in a grid. If one edge is added, it is added in such a way that the maze is still drawable in a grid. If this number is higher than can be constructed from joining dangling rooms an information is printed to stdout and the maximum possible number of circles is generated. seed: Random seed for choice of where to add the edge. Returns: A network-x graph representing a Coin-Collector world containing at least one circle if number_of_new_edges>=1. ''' dangling_rooms = identify_dangling_rooms(G) random.seed(seed) circles_requested = number_of_new_edges while number_of_new_edges > 0 and not dangling_room_list_depleted(dangling_rooms): direction_choices = [0, 1, 2, 3] random.shuffle(direction_choices) for direction in direction_choices: random.shuffle(dangling_rooms[direction]) if len(dangling_rooms[direction]) >= 2 and number_of_new_edges > 0: room1 = dangling_rooms[direction].pop() room2 = dangling_rooms[direction].pop() new_edge_direction = determine_relative_room_position(G, room1, room2, direction) # print('New edge: (%s, %s, direction=%s)' % (room1, room2, (new_edge_direction+2)%4)) G.add_edge( room1, room2, direction=(new_edge_direction+2)%4, contained_in_shortest_path=0 ) G.add_edge( room2, room1, direction=new_edge_direction, contained_in_shortest_path=0 ) # print('Old rooms:') # print(G.nodes[room1]) # print(G.nodes[room2]) G.nodes[room1]['description'] = G.nodes[room1]['description'] + generate_exit_sentence(new_edge_direction % 4) G.nodes[room2]['description'] = G.nodes[room2]['description'] + generate_exit_sentence( (new_edge_direction + 2)%4) # print('New rooms:') # print(G.nodes[room1]) # print(G.nodes[room2]) number_of_new_edges -= 1 print('Circles requested: %s. Circles constructed: %s.' % (circles_requested, number_of_new_edges)) # shortest path may have changed G = add_shortest_path_info(G) return G def test_maze_refinement(): G = get_maze(104, 100) print_maze_info(G) G = add_new_edges(G, 1, 100) print_maze_info(G) print("Edge ('r_4', 'r_5') was added with correct direction info") if __name__ == '__main__': G = get_maze(250, 100) G = add_new_edges(G, 5, 100)
339308d7c30e727a44370671bee1062867716538
8daf2ec35abfff6ccaedc5abbe9f25d03e4b5739
/get-clients.py
a5b62a7ccc30cb8b144253834e85a7d477d615a8
[]
no_license
5antoshernandez/Housekeeping-Service-Estimate
3cffcbec3d153b2683a245fddcc3a74357b31b7a
9b097148c5cd465e1a618584dcfa054fe3327abe
refs/heads/master
2020-04-13T21:01:14.136633
2019-01-19T23:38:54
2019-01-19T23:38:54
163,445,832
1
0
null
null
null
null
UTF-8
Python
false
false
180
py
import sqlite3 conn = sqlite3.connect('housekeeping.db') curr = conn.cursor() clientList = curr.execute('SELECT name FROM Clients') for client in clientList: print(client[0])
f5b323edda211f6994625eb9f7b4a4f34eaa4abc
349c9829279a9e99d18d1572d7aa9a31ec4e048c
/Topics/Time module/Easy convert/main.py
69179e696eb022d47901aed90bce5e6f36e9317e
[]
no_license
Helen-Sk-2020/JtBr_Arithmetic_Exam_Application
2b0eb871a89f3e4370f21e11c0c83b1885a8f4ae
a7e1b4a4c09df159c98da1a151db55848ba4d8a4
refs/heads/master
2023-08-18T22:42:11.809697
2021-10-14T10:07:36
2021-10-14T10:07:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
72
py
import time current_time = time.ctime(time.time()) print(current_time)
1e79fc8bd4c805d93043855b0299b73d0aee8363
fe53320ceb5d6b127f2514c4083d06e45aa5c4b1
/01_Jump_to_python/5_APP/1_Class/2_clac_class.py
16f37c63c8af4ddfadbfd5b4751b86627d816c36
[]
no_license
sss6391/iot_python2019
938100cb6a767259324309f0854f33452e2fa248
872cc2b2bc6ead6e67b6d158f71ab9537a9a2789
refs/heads/master
2020-06-14T22:17:43.160582
2019-10-04T07:01:01
2019-10-04T07:01:01
195,142,239
0
0
null
null
null
null
UTF-8
Python
false
false
323
py
class Calculator: def __init__(self): self.result = 0 def add(self, num): self.result += num return self.result cal1 = Calculator() cal2 = Calculator() cal3 = Calculator() print(cal1.add(3)) print(cal1.add(2)) print(cal2.add(3)) print(cal2.add(4)) print(cal3.add(3)) print(cal3.add(6))
[ "byungChan [email protected]" ]
6ab3a3c94a7787898acdc75cf997647c58e352a1
ef133e95e89e6e956421d47b25ea789557fe4620
/In-Class-Activities/Python/Day 9/Dictionaries.py
5a6b1c2e1d61a62f76420511280b8917df52a313
[]
no_license
pgupta321/Data-Analytics-Course
67c1c1dab8ed47c2f03869b0d1791d931da66fcc
43da35a7fb94dbec7bf80ab942a1756c794d23ad
refs/heads/master
2022-12-12T18:11:35.566436
2019-08-24T15:02:55
2019-08-24T15:02:55
192,400,471
0
0
null
2022-12-04T08:24:39
2019-06-17T18:43:38
Jupyter Notebook
UTF-8
Python
false
false
110
py
dictionary = {"name": "Toby", "age": 7, "gender": "male"} print(dictionary['gender'])
c73896b41397d024ffcb55baeaa9f677221d9361
6e8d58340f2be5f00d55e2629052c0bbc9dcf390
/eggs/Cheetah-2.2.2-py2.6-linux-x86_64-ucs4.egg/Cheetah/Tools/MondoReport.py
d0fada29f11cec17ce7def984ffabddd6bbf15ad
[ "CC-BY-2.5", "MIT" ]
permissive
JCVI-Cloud/galaxy-tools-prok
e57389750d33ac766e1658838cdb0aaf9a59c106
3c44ecaf4b2e1f2d7269eabef19cbd2e88b3a99c
refs/heads/master
2021-05-02T06:23:05.414371
2014-03-21T18:12:43
2014-03-21T18:12:43
6,092,693
0
2
NOASSERTION
2020-07-25T20:38:17
2012-10-05T15:57:38
Python
UTF-8
Python
false
false
12,935
py
""" @@TR: This code is pretty much unsupported. MondoReport.py -- Batching module for Python and Cheetah. Version 2001-Nov-18. Doesn't do much practical yet, but the companion testMondoReport.py passes all its tests. -Mike Orr (Iron) TODO: BatchRecord.prev/next/prev_batches/next_batches/query, prev.query, next.query. How about Report: .page(), .all(), .summary()? Or PageBreaker. """ import operator, types try: from Cheetah.NameMapper import valueForKey as lookup_func except ImportError: def lookup_func(obj, name): if hasattr(obj, name): return getattr(obj, name) else: return obj[name] # Raises KeyError. ########## CONSTANTS ############################## True, False = (1==1), (1==0) numericTypes = types.IntType, types.LongType, types.FloatType ########## PUBLIC GENERIC FUNCTIONS ############################## class NegativeError(ValueError): pass def isNumeric(v): return type(v) in numericTypes def isNonNegative(v): ret = isNumeric(v) if ret and v < 0: raise NegativeError(v) def isNotNone(v): return v is not None def Roman(n): n = int(n) # Raises TypeError. if n < 1: raise ValueError("roman numeral for zero or negative undefined: " + n) roman = '' while n >= 1000: n = n - 1000 roman = roman + 'M' while n >= 500: n = n - 500 roman = roman + 'D' while n >= 100: n = n - 100 roman = roman + 'C' while n >= 50: n = n - 50 roman = roman + 'L' while n >= 10: n = n - 10 roman = roman + 'X' while n >= 5: n = n - 5 roman = roman + 'V' while n < 5 and n >= 1: n = n - 1 roman = roman + 'I' roman = roman.replace('DCCCC', 'CM') roman = roman.replace('CCCC', 'CD') roman = roman.replace('LXXXX', 'XC') roman = roman.replace('XXXX', 'XL') roman = roman.replace('VIIII', 'IX') roman = roman.replace('IIII', 'IV') return roman def sum(lis): return reduce(operator.add, lis, 0) def mean(lis): """Always returns a floating-point number. """ lis_len = len(lis) if lis_len == 0: return 0.00 # Avoid ZeroDivisionError (not raised for floats anyway) total = float( sum(lis) ) return total / lis_len def median(lis): lis = lis[:] lis.sort() return lis[int(len(lis)/2)] def variance(lis): raise NotImplementedError() def variance_n(lis): raise NotImplementedError() def standardDeviation(lis): raise NotImplementedError() def standardDeviation_n(lis): raise NotImplementedError() class IndexFormats: """Eight ways to display a subscript index. ("Fifty ways to leave your lover....") """ def __init__(self, index, item=None): self._index = index self._number = index + 1 self._item = item def index(self): return self._index __call__ = index def number(self): return self._number def even(self): return self._number % 2 == 0 def odd(self): return not self.even() def even_i(self): return self._index % 2 == 0 def odd_i(self): return not self.even_i() def letter(self): return self.Letter().lower() def Letter(self): n = ord('A') + self._index return chr(n) def roman(self): return self.Roman().lower() def Roman(self): return Roman(self._number) def item(self): return self._item ########## PRIVATE CLASSES ############################## class ValuesGetterMixin: def __init__(self, origList): self._origList = origList def _getValues(self, field=None, criteria=None): if field: ret = [lookup_func(elm, field) for elm in self._origList] else: ret = self._origList if criteria: ret = filter(criteria, ret) return ret class RecordStats(IndexFormats, ValuesGetterMixin): """The statistics that depend on the current record. """ def __init__(self, origList, index): record = origList[index] # Raises IndexError. IndexFormats.__init__(self, index, record) ValuesGetterMixin.__init__(self, origList) def length(self): return len(self._origList) def first(self): return self._index == 0 def last(self): return self._index >= len(self._origList) - 1 def _firstOrLastValue(self, field, currentIndex, otherIndex): currentValue = self._origList[currentIndex] # Raises IndexError. try: otherValue = self._origList[otherIndex] except IndexError: return True if field: currentValue = lookup_func(currentValue, field) otherValue = lookup_func(otherValue, field) return currentValue != otherValue def firstValue(self, field=None): return self._firstOrLastValue(field, self._index, self._index - 1) def lastValue(self, field=None): return self._firstOrLastValue(field, self._index, self._index + 1) # firstPage and lastPage not implemented. Needed? def percentOfTotal(self, field=None, suffix='%', default='N/A', decimals=2): rec = self._origList[self._index] if field: val = lookup_func(rec, field) else: val = rec try: lis = self._getValues(field, isNumeric) except NegativeError: return default total = sum(lis) if total == 0.00: # Avoid ZeroDivisionError. return default val = float(val) try: percent = (val / total) * 100 except ZeroDivisionError: return default if decimals == 0: percent = int(percent) else: percent = round(percent, decimals) if suffix: return str(percent) + suffix # String. else: return percent # Numeric. def __call__(self): # Overrides IndexFormats.__call__ """This instance is not callable, so we override the super method. """ raise NotImplementedError() def prev(self): if self._index == 0: return None else: length = self.length() start = self._index - length return PrevNextPage(self._origList, length, start) def next(self): if self._index + self.length() == self.length(): return None else: length = self.length() start = self._index + length return PrevNextPage(self._origList, length, start) def prevPages(self): raise NotImplementedError() def nextPages(self): raise NotImplementedError() prev_batches = prevPages next_batches = nextPages def summary(self): raise NotImplementedError() def _prevNextHelper(self, start,end,size,orphan,sequence): """Copied from Zope's DT_InSV.py's "opt" function. """ if size < 1: if start > 0 and end > 0 and end >= start: size=end+1-start else: size=7 if start > 0: try: sequence[start-1] except: start=len(sequence) # if start > l: start=l if end > 0: if end < start: end=start else: end=start+size-1 try: sequence[end+orphan-1] except: end=len(sequence) # if l - end < orphan: end=l elif end > 0: try: sequence[end-1] except: end=len(sequence) # if end > l: end=l start=end+1-size if start - 1 < orphan: start=1 else: start=1 end=start+size-1 try: sequence[end+orphan-1] except: end=len(sequence) # if l - end < orphan: end=l return start,end,size class Summary(ValuesGetterMixin): """The summary statistics, that don't depend on the current record. """ def __init__(self, origList): ValuesGetterMixin.__init__(self, origList) def sum(self, field=None): lis = self._getValues(field, isNumeric) return sum(lis) total = sum def count(self, field=None): lis = self._getValues(field, isNotNone) return len(lis) def min(self, field=None): lis = self._getValues(field, isNotNone) return min(lis) # Python builtin function min. def max(self, field=None): lis = self._getValues(field, isNotNone) return max(lis) # Python builtin function max. def mean(self, field=None): """Always returns a floating point number. """ lis = self._getValues(field, isNumeric) return mean(lis) average = mean def median(self, field=None): lis = self._getValues(field, isNumeric) return median(lis) def variance(self, field=None): raiseNotImplementedError() def variance_n(self, field=None): raiseNotImplementedError() def standardDeviation(self, field=None): raiseNotImplementedError() def standardDeviation_n(self, field=None): raiseNotImplementedError() class PrevNextPage: def __init__(self, origList, size, start): end = start + size self.start = IndexFormats(start, origList[start]) self.end = IndexFormats(end, origList[end]) self.length = size ########## MAIN PUBLIC CLASS ############################## class MondoReport: _RecordStatsClass = RecordStats _SummaryClass = Summary def __init__(self, origlist): self._origList = origlist def page(self, size, start, overlap=0, orphan=0): """Returns list of ($r, $a, $b) """ if overlap != 0: raise NotImplementedError("non-zero overlap") if orphan != 0: raise NotImplementedError("non-zero orphan") origList = self._origList origList_len = len(origList) start = max(0, start) end = min( start + size, len(self._origList) ) mySlice = origList[start:end] ret = [] for rel in range(size): abs_ = start + rel r = mySlice[rel] a = self._RecordStatsClass(origList, abs_) b = self._RecordStatsClass(mySlice, rel) tup = r, a, b ret.append(tup) return ret batch = page def all(self): origList_len = len(self._origList) return self.page(origList_len, 0, 0, 0) def summary(self): return self._SummaryClass(self._origList) """ ********************************** Return a pageful of records from a sequence, with statistics. in : origlist, list or tuple. The entire set of records. This is usually a list of objects or a list of dictionaries. page, int >= 0. Which page to display. size, int >= 1. How many records per page. widow, int >=0. Not implemented. orphan, int >=0. Not implemented. base, int >=0. Number of first page (usually 0 or 1). out: list of (o, b) pairs. The records for the current page. 'o' is the original element from 'origlist' unchanged. 'b' is a Batch object containing meta-info about 'o'. exc: IndexError if 'page' or 'size' is < 1. If 'origlist' is empty or 'page' is too high, it returns an empty list rather than raising an error. origlist_len = len(origlist) start = (page + base) * size end = min(start + size, origlist_len) ret = [] # widow, orphan calculation: adjust 'start' and 'end' up and down, # Set 'widow', 'orphan', 'first_nonwidow', 'first_nonorphan' attributes. for i in range(start, end): o = origlist[i] b = Batch(origlist, size, i) tup = o, b ret.append(tup) return ret def prev(self): # return a PrevNextPage or None def next(self): # return a PrevNextPage or None def prev_batches(self): # return a list of SimpleBatch for the previous batches def next_batches(self): # return a list of SimpleBatch for the next batches ########## PUBLIC MIXIN CLASS FOR CHEETAH TEMPLATES ############## class MondoReportMixin: def batch(self, origList, size=None, start=0, overlap=0, orphan=0): bat = MondoReport(origList) return bat.batch(size, start, overlap, orphan) def batchstats(self, origList): bat = MondoReport(origList) return bat.stats() """ # vim: shiftwidth=4 tabstop=4 expandtab textwidth=79
3457d5a9fc1cb829b5810e28cb19b670b4a2c408
79f42fd0de70f0fea931af610faeca3205fd54d4
/base_lib/ChartDirector/pythondemo_cgi/finance2.py
d21cccb185021c83f32e480286c061357e3302a6
[ "IJG" ]
permissive
fanwen390922198/ceph_pressure_test
a900a6dc20473ae3ff1241188ed012d22de2eace
b6a5b6d324e935915090e791d9722d921f659b26
refs/heads/main
2021-08-27T16:26:57.500359
2021-06-02T05:18:39
2021-06-02T05:18:39
115,672,998
0
0
null
null
null
null
UTF-8
Python
false
false
2,647
py
#!/usr/bin/python from FinanceChart import * # Create a finance chart demo containing 100 days of data noOfDays = 100 # To compute moving averages starting from the first day, we need to get extra data points before # the first day extraDays = 30 # In this exammple, we use a random number generator utility to simulate the data. We set up the # random table to create 6 cols x (noOfDays + extraDays) rows, using 9 as the seed. rantable = RanTable(9, 6, noOfDays + extraDays) # Set the 1st col to be the timeStamp, starting from Sep 4, 2002, with each row representing one # day, and counting week days only (jump over Sat and Sun) rantable.setDateCol(0, chartTime(2002, 9, 4), 86400, 1) # Set the 2nd, 3rd, 4th and 5th columns to be high, low, open and close data. The open value starts # from 100, and the daily change is random from -5 to 5. rantable.setHLOCCols(1, 100, -5, 5) # Set the 6th column as the vol data from 5 to 25 million rantable.setCol(5, 50000000, 250000000) # Now we read the data from the table into arrays timeStamps = rantable.getCol(0) highData = rantable.getCol(1) lowData = rantable.getCol(2) openData = rantable.getCol(3) closeData = rantable.getCol(4) volData = rantable.getCol(5) # Create a FinanceChart object of width 640 pixels c = FinanceChart(640) # Add a title to the chart c.addTitle("Finance Chart Demonstration") # Set the data into the finance chart object c.setData(timeStamps, highData, lowData, openData, closeData, volData, extraDays) # Add a slow stochastic chart (75 pixels high) with %K = 14 and %D = 3 c.addSlowStochastic(75, 14, 3, 0x006060, 0x606000) # Add the main chart with 240 pixels in height c.addMainChart(240) # Add a 10 period simple moving average to the main chart, using brown color c.addSimpleMovingAvg(10, 0x663300) # Add a 20 period simple moving average to the main chart, using purple color c.addSimpleMovingAvg(20, 0x9900ff) # Add candlestick symbols to the main chart, using green/red for up/down days c.addCandleStick(0x00ff00, 0xff0000) # Add 20 days donchian channel to the main chart, using light blue (9999ff) as the border and # semi-transparent blue (c06666ff) as the fill color c.addDonchianChannel(20, 0x9999ff, 0xc06666ff) # Add a 75 pixels volume bars sub-chart to the bottom of the main chart, using green/red/grey for # up/down/flat days c.addVolBars(75, 0x99ff99, 0xff9999, 0x808080) # Append a MACD(26, 12) indicator chart (75 pixels high) after the main chart, using 9 days for # computing divergence. c.addMACD(75, 26, 12, 9, 0x0000ff, 0xff00ff, 0x008000) # Output the chart print("Content-type: image/png\n") binaryPrint(c.makeChart2(PNG))
b2ff512a0df75117ebd57c2d358a5b6aadc8575c
d55df3ef17af53557c3492eb3c88457b0317e2d4
/88.两个大数的总和.py
f107635a6d1aa650a9e5e5b8ac4d029f8dd2dcc6
[]
no_license
maryyang1234/hello-world
3b5e1aa0149089ccf171b0555a11b9f8b1c2575f
055ba2ee4f373b4abed1bf5d03860fd2e2d3b3f5
refs/heads/master
2020-05-03T23:28:34.367561
2019-05-26T10:02:26
2019-05-26T10:02:26
178,866,578
0
0
null
null
null
null
UTF-8
Python
false
false
145
py
def sumofTwo(str1,str2): return int(str1)+int(str2) str1 ="7777555511111111" str2 ="3332222221111" print(sumofTwo(str1, str2))
a36d8c6e12a0ca906a9ff8760fe9ccd1862fb318
cbf8deaf49aa264b9dfd1d5451d5ea89c579d10f
/remind_parse.py
cf18f81bbaf9703199538811b2e09053934d990c
[ "MIT" ]
permissive
crazyhubox/ChaoXin
fc770afb9e882355cc43152c8f08c77df7efd44c
8885d85081f79a5a2338958a308a76b3f64595f8
refs/heads/main
2023-05-05T07:51:29.400076
2021-05-13T01:21:53
2021-05-13T01:21:53
365,950,212
1
0
null
null
null
null
UTF-8
Python
false
false
2,724
py
from deadline.tasks import get_works from deadline import get_score_from_time from sign import get_params from Login import refresh_cookies, login_cookies from redis import Redis from datetime import datetime from time import sleep from Logger import Logger,Handler COURSES = [ ('/visit/stucoursemiddle?courseid=218148267&clazzid=40920416&vc=1&cpi=134538886', '教育学'), ('/visit/stucoursemiddle?courseid=218144539&clazzid=40910648&vc=1&cpi=136486695', '设置基础学'), ('/visit/stucoursemiddle?courseid=217817986&clazzid=40052686&vc=1&cpi=137312605', '小学数学'), ] rdb = Redis(host='your host of redis serer',db=2,password='your password',decode_responses=True) def get_remind_logname(): today = datetime.now().date() sign_log_filename = f'{today}-reminds.log' return f'./Logger/logs/{sign_log_filename}' # logger = Logger('file','remind_Parse_log') log_name = get_remind_logname() print(log_name) logger = Logger('file',log_name) def change_log_path(): log_name = get_remind_logname() if logger.handlers: logger.removeHandler(logger.handlers[0]) print(log_name) new_handler = Handler('file',log_name) logger.addHandler(new_handler) def Parse(cookies, s_t): logger.warning('登录....') for url, course_name in COURSES: # 每一节课 courseId, jclassId, cpi = get_params(url=url) logger.info(f'{url},{course_name}') for each_work in get_works(cookies, courseId, jclassId, cpi): '写入redis' # 时间每一分钟都在刷新 name, status, rest_time = each_work res_str = '{},{}'.format(name, status) change_exsist_task_status(course_name,name,status)# task的状态修改之后删除原来的值 logger.info(each_work) rdb.zadd(course_name, {res_str: get_score_from_time(rest_time)}) sleep(s_t) def main(): cookies = login_cookies() count = 0 yesterday = datetime.now().day while True: sleep_time = 1.5 cookies, count = refresh_cookies(cookies, count) now = datetime.now() if now.day > yesterday: # 切换日志文件 change_log_path() yesterday = now.day if now.hour > 6 and now.hour < 23: Parse(cookies, sleep_time) sleep(120) count += 1 def change_exsist_task_status(course_name:str,name:str,status:str): res = rdb.zrevrange(course_name,start=0,end=500) for each in res: n,s = each.split(',') if n == name and s != status: res = rdb.zrem(course_name,each) return res return if __name__ == '__main__': main()
670d093c5b40381c943145d32272491af454d9ac
61812e6e652746f83c753daf8a73a2b1bb17ce96
/profiles_api/models.py
d04b7e5a960efbda0bcc2388fa50ded165e5bf26
[ "MIT" ]
permissive
walidkm/profiles-rest-api
c6e56390046a9745788f2b417c85cbca29b2d435
1c71495c4877ee7e418002ba7d957e02e3dedea7
refs/heads/master
2021-09-28T22:40:59.561051
2020-04-26T16:19:48
2020-04-26T16:19:48
246,568,554
0
0
MIT
2021-09-22T18:43:40
2020-03-11T12:44:53
Python
UTF-8
Python
false
false
2,068
py
from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager from django.conf import settings class UserProfileManager(BaseUserManager): """manager for user profiles""" def create_user(self, email, name, password=None): """ctreate a new user profile""" if not email: raise ValueError('Users must have an email addres') email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name, password): """create and save a new superuser with given details""" user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class UserProfile(AbstractBaseUser, PermissionsMixin): """Database model for users in the system""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserProfileManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def get_full_name(self): """retrieve full name of user""" return self.name def get_short_name(self): """Retrieve short name of user""" return self.name def __str__(self): """return string representation of our user""" return self.email class ProfileFeedItem(models.Model): """Profile status update""" user_profile = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) status_text = models.CharField(max_length=255) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): """Return the model as a string""" return self.status_text
e10e22fe44f9af66f5922def28199ad6d3a04b8b
300e6ec81e11f449979597eeda9c01f4677741a4
/Project03/django_project/django_project/settings.py
e4777d48f1b1296911616a5c7690116e8b245410
[]
no_license
tapsonte/CS1XA3
c3ef9cc23755badfea4ded9bdfe6342315c6a7fd
07e8c2e6593426cc2a0b76a03632ffe197be52d6
refs/heads/master
2023-05-03T17:38:57.496915
2019-09-23T04:02:46
2019-09-23T04:02:46
167,879,609
0
1
null
2023-04-21T20:31:42
2019-01-28T01:24:20
Python
UTF-8
Python
false
false
3,340
py
""" Django settings for django_project project. Generated by 'django-admin startproject' using Django 2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '3fju77dmu7+yx)dsd0hbukfc$&y-z@i9*45j&&i$a%#l-ba+=9' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'posts.apps.PostsConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'django_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'django_project.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = 'e/tapsonte/static/' STATICFILES_DIRS = [ "/home/tapsonte/CS1XA3/public_html/", # '/var/www/static/', ] STATIC_ROOT = "/home/tapsonte/CS1XA3/django_project/static/"
cac0a5abf2773fcc99ea11ffa95ee477d3e645bb
3436a32fc9ddaaf600ccd29a9a52c78a580a15bc
/async_rx/observable/rx_list.py
6d7a1f07a010b3a7c1b92d2e145d36bb8300a7ad
[ "MIT" ]
permissive
geronimo-iia/async-rx
01c07a36bc1c06ff1bc9bcfad13dc0b06159b5d4
366a2fc5e4e717a0441f1ee8522ef6d5e857566c
refs/heads/master
2021-08-04T02:20:19.816225
2021-07-27T23:42:11
2021-07-27T23:42:11
193,953,979
4
0
NOASSERTION
2021-07-27T23:37:15
2019-06-26T17:59:37
Python
UTF-8
Python
false
false
3,295
py
from collections import UserList from typing import List, Optional, Union import curio from ..protocol import Observable, Observer, Subscription __all__ = ["rx_list"] class _RxList(UserList): def __init__(self, initlist: Optional[Union[List, "_RxList"]] = None): self._event = curio.UniversalEvent() self._subscribers = 0 super().__init__(initlist=initlist if initlist else []) async def subscribe(self, an_observer: Observer) -> Subscription: if self._subscribers > 0: raise RuntimeError("Only one subscription is supported") self._subscribers += 1 _consumer_task = None async def consumer(): try: while True: await self._event.wait() await an_observer.on_next(list(self.data)) self._event.clear() except curio.TaskCancelled: # it's time to finish pass async def _subscription(): nonlocal _consumer_task if _consumer_task: await _consumer_task.cancel() _consumer_task = None self._subscribers -= 1 _consumer_task = await curio.spawn(consumer()) await an_observer.on_next(list(self.data)) return _subscription def _set_event(self): if not self._event.is_set(): self._event.set() def __setitem__(self, i, item): super().__setitem__(i, item) self._set_event() def __delitem__(self, i): super().__delitem__(i) self._set_event() def __add__(self, other): result = super().__add__(other) self._set_event() return _RxList(result) def __iadd__(self, other): super().__iadd__(other) self._set_event() return self def __mul__(self, n): result = super().__mul__(n) self._set_event() return _RxList(result) def __imul__(self, n): super().__imul__(n) self._set_event() return self def append(self, item): super().append(item) self._set_event() def insert(self, i, item): super().insert(i, item) self._set_event() def pop(self, i=-1): super().pop(i) self._set_event() def remove(self, item): super().remove(item) self._set_event() def clear(self): super().clear() self._set_event() def copy(self): return _RxList(super().copy()) def reverse(self): super().reverse() self._set_event() def sort(self, *args, **kwds): super().sort(*args, **kwds) self._set_event() def extend(self, other): super().extend(other) self._set_event() def rx_list(initial_value: Optional[List] = None) -> Observable: """Create an observable on list. The observer receive the current value of list on subscribe and when an item change (added, updated or deleted, ...). This observable implements a UserList, so you can use it as a classic list. Args: initial_value (Optional[List]): intial value (default: []) Returns: (Observable): observable instance """ return _RxList(initlist=initial_value)
25c724ee779ec1d3fdd96581b62e411fcba9cf2a
9dab41a71bf19a9ad17ee3e9f77c0f58aebd1d6d
/python/uline/uline/uline/handlers/app/merchant/statistics/transactionStatisticsHandler.py
92e2b4165084bb877b87f18d86d5ef2703436b58
[]
no_license
apollowesley/Demo
f0ef8ec6c4ceb0aec76771da8dd9a62fb579eac8
471c4af95d3a7222d6933afc571a8e52e8fe4aee
refs/heads/master
2021-02-15T04:01:51.590697
2018-01-29T01:44:29
2018-01-29T01:44:29
null
0
0
null
null
null
null
UTF-8
Python
false
false
11,042
py
# -*- coding: utf-8 -*- from __future__ import division from collections import defaultdict from datetime import datetime, timedelta from tornado import gen from tornado.web import ( authenticated ) from uline.handlers.baseHandlers import MchAdminHandler from uline.public import log from uline.public import common from .form import TotalStatisticsSearch from uline.public.permit import check_permission class TransactionStatisticsHandler(MchAdminHandler): # executor = ThreadPoolExecutor(8) @authenticated @check_permission def prepare(self): form = TotalStatisticsSearch(self) if not form.validate(): f_rsp = common.f_rsp(code=406, msg='fail') self.finish(f_rsp) return self.query_date = 1 if not form.query_date.data else form.query_date.data self.create_at_start = form.create_at_start.data self.create_at_end = form.create_at_end.data self.order_by = 'pay_time' if not form.order_by.data else form.order_by.data self.pageindex = int(self.get_argument("p", 1)) # 模块上日期 self.last_create_at_start = datetime.today().strftime("%Y-%m-%d") self.last_create_at_end = ( datetime.now() + timedelta(1)).strftime("%Y-%m-%d") self.create_at_start, \ self.create_at_end, \ self.create_at_start_search, \ self.create_at_end_search = common.common_date_deal(self.query_date, self.create_at_start, self.create_at_end) @gen.coroutine def get(self): data = yield self.do_execute() self.render('merchant/statistics/transactionStatistics.html', data=data, query_date=int( self.query_date), order_by_form=self.order_by, create_at_start=self.create_at_start, create_at_end=self.create_at_end) @gen.coroutine def post(self): data = yield self.do_execute() self.render('merchant/statistics/transactionStatistics.html', data=data, query_date=int( self.query_date), order_by_form=self.order_by, create_at_start=self.create_at_start, create_at_end=self.create_at_end) @gen.coroutine def do_execute(self): last_day_count, total_count, total_count_search, search_count_details, charts = [0] * 6, [0] * 6, [ 0] * 6, [], [] last_day_count_fields = ['day_tx_count_last', 'day_tx_amount_last', 'day_refund_count_last', 'day_refund_amount_last', 'day_tx_net_amout_last', 'day_profit_amount_last'] total_count_fields = ['day_tx_count_total', 'day_tx_amount_total', 'day_refund_count_total', 'day_refund_amount_total', 'day_tx_net_amout_total', 'day_profit_amount_total'] total_count_search_fields = ['day_tx_count_total', 'day_tx_amount_total', 'day_refund_count_total', 'day_refund_amount_total', 'day_tx_net_amout_total', 'day_profit_amount_total'] with self.db.get_db() as cur: try: last_day_count = yield self.get_pay_count(cur, self.last_create_at_start, self.last_create_at_end) total_count = yield self.get_pay_count(cursor=cur, create_at_start=None, create_at_end=self.last_create_at_end) total_query_start = datetime.strptime(self.create_at_start_search, '%Y-%m-%d %H:%M:%S') + timedelta( 1) if int(self.query_date) == 2 else self.create_at_start_search total_count_search = yield self.get_pay_count(cur, total_query_start, self.create_at_end_search) search_count_details = yield self.get_pay_count_detail(cur, self.create_at_start_search, self.create_at_end_search, (self.pageindex - 1) * 10, self.query_date, page=True) chart_show_details = yield self.get_pay_count_detail(cur, self.create_at_start_search, self.create_at_end_search, 0, self.query_date, page=False) except Exception as err: cur.connection.rollback() log.exception.exception(err) else: cur.connection.commit() details, total_num = search_count_details if int(self.query_date) == 2: months = len(common.get_mon_seq( self.create_at_start, self.create_at_end)) if len(chart_show_details[0]) > months: del chart_show_details[0][0] if len(details) > months: del details[0] details = common.append_start_end(details, self.query_date) navigate_html = self.get_navigate_html(total_num) last_day_count_data = dict(zip(last_day_count_fields, last_day_count)) total_count_data = dict(zip(total_count_fields, total_count)) total_count_search_data = dict( zip(total_count_search_fields, total_count_search)) date_range_key = common.get_date_range(self.create_at_start, self.create_at_end) if int( self.query_date) == 1 else common.get_mon_seq(self.create_at_start, self.create_at_end) for index in range(1, 7): detail = yield common.deal_search_count_charts(index, date_range_key, chart_show_details[0]) charts.append(detail) data = dict(last_day_count_data=last_day_count_data, total_count_data=total_count_data, total_count_search_data=total_count_search_data, details=details, charts=charts, total_num=total_num, navigate_html=navigate_html) raise gen.Return(data) @gen.coroutine def get_pay_count(self, cursor, create_at_start=None, create_at_end=None): ''' :param cursor: :param create_at_start: :param create_at_end: :return: ''' query = """select sum(day_tx_count), round(sum(day_tx_amount)/100, 2), sum(day_refund_count), abs(round(sum(day_refund_amount)/100, 2)), round(sum(day_tx_net_amout)/100, 2), round(sum(day_profit_amount)/100, 2) from mch_daily_balance_info where mch_id = %(mch_id)s and (to_char(need_pay_time, 'YYYY-MM-DD')::timestamp between %(create_at_start)s::timestamp and %(create_at_end)s::timestamp or %(create_at_start)s is null or %(create_at_end)s is null)""" cursor.execute( query, { 'create_at_start': create_at_start, 'create_at_end': create_at_end, 'mch_id': self.current_user } ) ret = cursor.fetchone() raise gen.Return(ret) @gen.coroutine def get_pay_count_detail(self, cursor, create_at_start, create_at_end, offset, date_switch, page=False): ''' :param cursor: :param create_at_start: :param create_at_end: :return: ''' query = """select {switch} sum(day_tx_count) as day_tx_count, round(sum(day_tx_amount), 2) as day_tx_amount, sum(day_refund_count) as day_refund_count, abs(round(sum(day_refund_amount), 2)) as day_refund_amount, round(sum(day_tx_net_amout), 2) as day_tx_net_amout, abs(round(sum(day_profit_amount), 2)) as day_profit_amount, COUNT(*) over () as total from mch_daily_balance_info where to_char({date_query}, 'YYYY-MM-DD')::timestamp between %(create_at_start)s::timestamp and %(create_at_end)s::timestamp and mch_id=%(mch_id)s GROUP BY pay_time """ if page: query += 'order by {} DESC '\ 'OFFSET %(offset)s ROWS FETCH NEXT 10 ROWS ONLY;'.format( self.order_by) else: query += 'order by {} DESC;'.format(self.order_by) switch = " to_char(need_pay_time - INTERVAL '1 day', 'YYYY-MM-DD') as pay_time," if int( date_switch) == 1 else "to_char(need_pay_time - INTERVAL '1 day','YYYY-MM') as pay_time," date_query = "need_pay_time" if int( date_switch) == 1 else "need_pay_time - INTERVAL '1 day'" query = query.format(switch=switch, date_query=date_query) con_dict = {'mch_id': self.current_user, 'create_at_start': create_at_start, 'create_at_end': create_at_end} if page: con_dict.update({'offset': offset}) cursor.execute(query, con_dict) ret = cursor.fetchall() ret = [ ( d[0], int(d[1]), d[2] / 100, int(d[3]), abs(d[4]) / 100, d[5] / 100, d[6] / 100, int(d[7])) for d in ret ] if ret else [] if ret: raise gen.Return([ret, ret[0][-1]]) raise gen.Return([ret, 0]) # @gen.coroutine # def deal_search_count_details(self, search_count_details): # date_range_default = defaultdict(list) # # for ( # pay_start_time, # day_tx_count, # day_tx_amount, # day_refund_count, # day_refund_amount, # day_tx_net_amout, # day_profit_amount) in search_count_details: # if not date_range_default[pay_start_time]: # date_range_default[pay_start_time].extend( # [ # pay_start_time, # day_tx_count, # day_tx_amount, # day_refund_count, # day_refund_amount, # day_tx_net_amout, # day_profit_amount # ] # ) # else: # date_range_default[pay_start_time][1] += day_tx_count # date_range_default[pay_start_time][2] += day_tx_amount # date_range_default[pay_start_time][3] += day_refund_count # date_range_default[pay_start_time][4] += day_refund_amount # date_range_default[pay_start_time][5] += day_tx_net_amout # date_range_default[pay_start_time][6] += day_profit_amount # details = date_range_default.values() # raise gen.Return(sorted(details, reverse=True))
2c8a23982a2e3e37be1a57598f6aa1a20e31fe0d
45a2b3b08bdb343e645c7afde833b256fd25f6ef
/density_grid_formatter.py
ac843fb6284f2611a6e0d3c3bf2fcff5d50cdb5e
[]
no_license
iainkirkpatrick/SCIE441Code
ac49bb273921615716b3864c3dbc421e33cd7c11
3441d244fd80ffb1ff97aae2ff3e76f0f8b3506e
refs/heads/master
2020-05-26T09:18:56.298002
2012-10-26T02:13:53
2012-10-26T02:13:53
null
0
0
null
null
null
null
UTF-8
Python
false
false
959
py
'''Utility program to convert from a prepared ASCII density grid, exported from Arc, to a density grid suitable for CART''' # Opening target ASCII grid, and creating output file x.dat with write permissions dgrid = open('europop') f = open('europop.dat', 'w') s = '' final = '' previousValue = '' for line in dgrid.readlines(): line = line.split(' ') pop_value = line[2].rstrip('\n') if previousValue == '': #for the first pass through the lines s = pop_value previousValue = line[1] elif line[1] == previousValue: s = s + ' ' + pop_value else: s = s + '\n' + pop_value previousValue = line[1] # The grid is currently in reverse order - need to reverse the order of the rows holder = s.split('\n') holder.reverse() for i in holder: final = final + i + '\n' # Finally, strip the extra \n off of the end of the string final = final.strip('\n') f.write(final) f.close()
ce7373e5f2d9c30b4958356208d0130ebc49cf20
aba65f60a0e8b97290b014740456ba53a46dc400
/UniqueAI2021SummerCampMission-main/Bayes/Gaussian_Bayes.py
a0cb6822fd11f077c1a0fd48ba461e5f4d4c665b
[ "MIT" ]
permissive
MeteoricShower/UniqueAISummerCampMission--lxy
749576697a789ebb4915026b305efbcc48916502
86fef35961e49efdbe03d5433e055cef58cd2617
refs/heads/main
2023-06-30T13:50:09.064513
2021-07-24T02:04:05
2021-07-24T02:04:05
384,844,879
0
0
null
null
null
null
UTF-8
Python
false
false
3,644
py
# -*- coding=utf-8 -*- # @Time :2021/6/17 11:45 # @Author :LiZeKai # @Site : # @File : Gaussian_Bayes.py # @Software : PyCharm """ 对于连续性数据, 使用GaussBayes 以乳腺癌数据集为例 """ from collections import Counter import numpy as np import pandas as pd import sklearn.model_selection as sml import math from numpy import ndarray, exp, pi, sqrt class GaussBayes: def __init__(self): self.prior = None self.var = None self.avg = None self.likelihood = None self.tag_num = None # calculate the prior probability of p_c def GetPrior(self, label): count_0=0 count_1=0 for i in label: if i==0: count_0+=1 else: count_1+=1 self.prior = [count_0 / len(label), count_1 / len(label)] pass # calculate the average def GetAverage(self, data, label): self.avg=np.zeros((data.shape[1],2),dtype=np.double) for i in range(data.shape[1]): sum_0=0 sum_1=0 count_0 = 0 count_1 = 0 for j in range(data.shape[0]): if label[j]==0: sum_0+=data[j][i] count_0 += 1 elif label[j]==1: sum_1+=data[j][i] count_1 += 1 self.avg[i][0]=sum_0/count_0 self.avg[i][1]=sum_1/count_1 pass # calculate the std def GetStd(self, data, label): self.var = np.zeros((data.shape[1], 2), dtype=np.double) for i in range(data.shape[1]): temp_0 = np.zeros(data.shape[1],dtype=np.double) temp_1 = np.zeros(data.shape[1], dtype=np.double) for j in range(data.shape[0]): if label[j]==0: temp_0 = np.append(temp_0,data[j][i]) elif label[j]==1: temp_1 = np.append(temp_1,data[j][i]) self.var[i][0]=temp_0.var() self.var[i][1]=temp_1.var() pass # calculate the likelihood based on the density function def GetLikelihood(self, x): pc_0 = np.ones(x.shape[0], dtype=np.double) pc_1 = np.ones(x.shape[0], dtype=np.double) for i in range(x.shape[0]): for j in range(x.shape[1]): pc_0[i] *= 1 / (pow(2 * math.pi, 0.5) * self.var[j][0]) * math.exp( -(pow(x[i][j] - self.avg[j][0], 2) / (2 * self.var[j][0]))) pc_1[i] *= 1 / (pow(2 * math.pi, 0.5) * self.var[j][1]) * math.exp( -(pow(x[i][j] - self.avg[j][1], 2) / (2 * self.var[j][1]))) return pc_0, pc_1 pass def fit(self, data, label): self.tag_num = len(np.unique(label)) self.GetPrior(label) self.GetAverage(data, label) self.GetStd(data, label) def predict(self, data): result = [] for i in range(len(test_x)): if self.GetLikelihood(data)[0][i] * self.prior[0] > self.GetLikelihood(data)[1][i] * self.prior[1]: result.append(0) else: result.append(1) return result if __name__ == '__main__': data = pd.read_csv('breast_cancer.csv', header=None) x, y = np.array(data.iloc[:, :-1]), np.array(data.iloc[:, -1]) train_x, test_x, train_y, test_y = sml.train_test_split(x, y, test_size=0.2, random_state=0) model = GaussBayes() model.fit(train_x, train_y) pred_y = model.predict(test_x) correct = np.sum(pred_y == test_y).astype(float) print("Accuracy:", correct / len(test_y))
49982cbda6186d5804468863bfc7a8d00d46ef96
cac155c4a39b902213fe9efe39dbe761afb00a40
/回溯法/leetcode/排列问题/leetcode_46_permute.py
068c120de650f947bde4374dd12e8327b69c7a1c
[]
no_license
songyingxin/python-algorithm
51c8d2fc785ba5bc5c3c98a17dce33cbced8cb99
4b1bebb7d8eb22516119acc921dfc69a72420722
refs/heads/master
2022-06-29T05:04:14.300542
2022-05-22T10:11:34
2022-05-22T10:11:34
164,998,626
331
72
null
null
null
null
UTF-8
Python
false
false
696
py
# permute(nums[0...n-1]) = (取出一个数字) + permute(nums[0...n-1] - 这个数字) class Solution: def permute(self, nums: List[int]) -> List[List[int]]: def backtracking(nums, item): if not nums: result.append(item) return for index in range(len(nums)): tmp = nums[:index] + nums[index+1:] tmp_item = item[:] tmp_item.append(nums[index]) backtracking(tmp, tmp_item) result = [] backtracking(nums, []) return result if __name__ == "__main__": nums = [1,2,3] print(Solution().permute(nums))
eafc50663b8684bf03e900b31157f7dcd8da4a7c
4eb7cd8b80efd7c11c2871b45d7e0db0c6e0ba81
/canteen/migrations/0004_auto_20190401_1209.py
d3a77c134acb9f9fcd4d288692cc10c04efb9fa7
[]
no_license
AmanPatwa/Canteen-Management
6d6a14126d08f4e061adaaa32c23ee75331c794a
3f2f2cd160a61f87e2bb06d421f18b0e73648058
refs/heads/master
2020-05-04T06:10:06.496347
2019-04-02T04:49:25
2019-04-02T04:49:25
178,999,907
0
0
null
null
null
null
UTF-8
Python
false
false
386
py
# Generated by Django 2.1.5 on 2019-04-01 06:39 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('canteen', '0003_auto_20190401_0005'), ] operations = [ migrations.AlterField( model_name='foodname', name='image', field=models.FileField(upload_to=''), ), ]
a9ad672ca4dd8238fa346abbe949dbfff210252c
c3a90aee09b35388bb3a45dc332738486abb96ff
/listen.1/core/test.py
7ae4af1834aba3ca16f36f18d646ae696bb0051d
[]
no_license
abobodyyj/code_practice
0588fae5f51a2b71da4c6cc9c66b5d8dd5e9a536
04808f6769a95675e26250cbef0bab08600360f8
refs/heads/master
2021-05-13T19:57:59.324466
2018-01-10T04:23:05
2018-01-10T04:23:05
116,904,639
0
0
null
null
null
null
UTF-8
Python
false
false
1,894
py
#!/usr/bin/env python # -*- coding:utf8 -*- # Author:Dong Ye import time,datetime import os,sys BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_PATH) from conf import config #ATM用户交易事物: def tran(tran_log,acc_data,tran_type,tran_amount,*args): tran_tag = config.TRANSACTION_TYPE tran_amount = float(tran_amount) #用户输入额度(还、取) if tran_type in tran_tag: interest_balance = tran_amount * tran_tag[tran_type]['interest'] #利息 tip_balance = tran_tag[tran_type]['tip'] #手续费 old_balance = acc_data['balance'] #可用余额 credit = acc_data['credit'] #上线总额 seving = acc_data['seving'] #储蓄余额 if tran_tag['action'] == 'plus': plus_balace = old_balance + (tran_amount - interest_balance - tip_balance) #新可用额度 if plus_balace >= credit: exceed_credit = plus_balace - credit seving_avg = exceed_credit +seving acc_data['seving'] = seving_avg elif plus_balace < credit: acc_data['balance'] = plus_balace elif tran_tag['action'] == 'minus': minus_balace = old_balance - (tran_amount + interest_balance + tip_balance) #新取款额度 if minus_balace <= 0: print("可用余额不足") elif minus_balace <= seving: seving_avg = seving - minus_balace acc_data['seving'] = seving_avg elif minus_balace > seving: exceed_seving = minus_balace - seving acc_data['seving'] = 0 acc_data['balance'] = exceed_seving else: print('您当前%s交易类型不存在,请重新选择!!!' % (tran_type)) tran('log','u1','repay','10000')
e8260f00d26c3348cc6276437be51441e4c6c23d
63556137b4e0d590b6cc542bc97bac1ba9fbb1b0
/A06.Q005.py
3a1f816a0899cedd2ec38b0f4c2496cb2164088e
[]
no_license
BrennoBernardoDeAraujo/ALGORITMOS-2019.2
3217109d1258b23ce4f8ef5f65091803c249415f
f9f5ff7f47991a8998329eaeb80b83dfbef8058e
refs/heads/master
2020-07-10T07:57:29.052167
2019-11-29T04:23:11
2019-11-29T04:23:11
204,211,365
1
0
null
null
null
null
UTF-8
Python
false
false
699
py
""" A06.Q005 - Leia uma matriz de ordem n, informada pelo usuário. Calcule a soma dos elementos que estão acima da diagonal principal.""" ordem = int(input('Digite a ordem da matriz: ')) def cria_matriz(): matriz = [] for i in range(ordem): matriz.append([0]*ordem) return matriz elemento_matriz = cria_matriz() resultado = 0 for i in range(ordem): for j in range(ordem): elemento_matriz[i][j] = int( input(f'Digite os elementos [{str(i+1)}][{str(j+1)}]: ')) if j > i: resultado = resultado + elemento_matriz[i][j] print( f'O resultado da soma do diagonal principal da matriz é: {resultado} ')
8bde39144d8acee2bd36c7ff65890ffec18fda58
f5f781ef988d4fa2868c923597a132018eb14041
/build/ROBOTIS-OP3-msgs/op3_offset_tuner_msgs/cmake/op3_offset_tuner_msgs-genmsg-context.py
9e14c02a4f494952599bc5018c54c563cbb5ddc4
[]
no_license
greenechang/christmann_ws_2019fira
701374a30059ee63faf62cfc8dae8ea783f6c078
a1ba2846fe1326e54366627d8812fa1bf90c70e1
refs/heads/master
2022-11-15T20:55:15.891128
2020-07-15T09:52:17
2020-07-15T09:52:17
279,816,942
0
0
null
null
null
null
UTF-8
Python
false
false
1,063
py
# generated from genmsg/cmake/pkg-genmsg.context.in messages_str = "/home/robotis/christmann_ws/src/ROBOTIS-OP3-msgs/op3_offset_tuner_msgs/msg/JointOffsetData.msg;/home/robotis/christmann_ws/src/ROBOTIS-OP3-msgs/op3_offset_tuner_msgs/msg/JointOffsetPositionData.msg;/home/robotis/christmann_ws/src/ROBOTIS-OP3-msgs/op3_offset_tuner_msgs/msg/JointTorqueOnOff.msg;/home/robotis/christmann_ws/src/ROBOTIS-OP3-msgs/op3_offset_tuner_msgs/msg/JointTorqueOnOffArray.msg" services_str = "/home/robotis/christmann_ws/src/ROBOTIS-OP3-msgs/op3_offset_tuner_msgs/srv/GetPresentJointOffsetData.srv" pkg_name = "op3_offset_tuner_msgs" dependencies_str = "std_msgs" langs = "gencpp;geneus;genlisp;gennodejs;genpy" dep_include_paths_str = "op3_offset_tuner_msgs;/home/robotis/christmann_ws/src/ROBOTIS-OP3-msgs/op3_offset_tuner_msgs/msg;std_msgs;/opt/ros/kinetic/share/std_msgs/cmake/../msg" PYTHON_EXECUTABLE = "/usr/bin/python" package_has_static_sources = '' == 'TRUE' genmsg_check_deps_script = "/opt/ros/kinetic/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py"
4872c9f499225b41609f8f51dd238b18e51fe7d8
e079006d43a545baf2e63ef20dfefd6e778f42c2
/Stark/urls.py
d2264c2278b9bed2c799e1f8f8b6ca59594e745d
[]
no_license
wailaifeike/myAdmin
34a41f1f8c7b04defa92d1ed3872888ff5295445
8f79f8232767bae73d0fd0c326232ca33203c7e2
refs/heads/master
2020-04-07T11:10:29.225049
2018-11-20T01:55:46
2018-11-20T01:55:46
158,315,189
0
0
null
null
null
null
UTF-8
Python
false
false
115
py
from django.conf.urls import url,include from Stark import views urlpatterns = [ url(r'',views.acc_login) ]
b251b03e61f2ffd2c4af1727b8d399b439ad87c4
1d20782060308f5e3830d0ae1312cd8a6d221b9b
/Lesson17.py
31f18dfa7a4f4944dd951e4b9849750267107d2a
[]
no_license
KeetonMartin/HomemadeProgrammingIntro
dd4d61786ba2dfd83964e7acbb8f0e8fd39e2b7e
cc71f81b159264a7a4f9addf3ade1f6559d35c44
refs/heads/master
2022-07-04T07:11:23.783851
2020-05-07T02:53:37
2020-05-07T02:53:37
261,406,075
0
0
null
null
null
null
UTF-8
Python
false
false
2,084
py
#Lesson 17 #Student Name: """ Today's lesson will be mostly work on anticipating the actions of a program. """ teams = ["Warriors", "76ers", "Celtics", "Lakers", "Clippers"] print("Problem 1") for i in range(0, len(teams)): print(i) print(teams[i]) #Group: """ 0 Warriors 1 76ers 2 Celtics 3 Lakers 4 Clippers 0 1 2 3 4 Warriors 76ers """ # -3 Celtics # -2 Lakers # -1 Clippers # 0 Warriors # 1 76ers print("\nProblem 2") for i in range(1, len(teams)+1): print(i) print(teams[-i]) """ Group Guess: 1 Clippers 2 Lakers 3 Celtics 4 76ers 5 Warriors """ print("\nProblem 3") for team in teams: print(team) if team == "Warriors" or team == "76ers": print("That's a home team") else: print("We don't root for that team") """ Seth Guess: Warriors That's a home team 76ers That's a home team Celtics We don't root for that team Lakers We don't root for that team Clippers We don't root for that team """ fourByFour = [ [1,2,3,4], [5,6,7,8], [9,10,11,12] ] fourByFour.append([13,14,15,16]) print("\nProblem 4") for innerList in fourByFour: print("A") for num in innerList: if num % 3 == 0: print("B") print("C") """ Group Guess: A B A B A B B A B C """ #Keeton creates problem 4.5: for i in range(5, 9): for j in range(-3, 8): print(i + j) """ Solution: 2 3 4 """ #Seth creates problem 5: #Andrew creates problem 6: #Ryan creates problem 7: print("\nProblem 8") # def recur(num): # if num <= 0: # print("A") # else: # print("B") # return recur(num-1) # recur(5) # recur(-2) # recur(0) # recur(1) #A helper function: def printGrid(grid): for innerList in grid: print(innerList) #Homework Problem print("\nHomework Problem") def modifyArray(grid): pass #Test 1: threeByThree = [[1,2,3],[4,5,6],[7,8,9]] printGrid(threeByThree) print(modifyArray(threeByThree)) #Should give us: [[1,2,3],[2,1,6],[2,2,1]] print("above should match this:") printGrid([[1,2,3],[2,1,6],[2,2,1]]) #Test 2: #Test 3: print("\nHint Homework") #Hint for problem 1: threeByThree[1][1] = 100 printGrid(threeByThree)
5f7b311eb6289634e225a37a30b074d8e8d0c557
da3753e6d93a260442502c89a0dbc1718fed58a1
/apps/courses/adminx.py
20d7421e319df3b219c4cfc56d669174a2470d9f
[]
no_license
stepbystep999/OnlineCourse
64e44bf84cd630155bde68c7e8e846f6bba4ac66
769afec34a0f1d5d7a3875ce95967506eaec2b46
refs/heads/master
2021-05-08T05:18:14.614831
2017-11-02T23:13:19
2017-11-02T23:13:19
108,440,744
1
0
null
null
null
null
UTF-8
Python
false
false
1,290
py
# -*- coding:utf-8 -*- __author__ = 'stepbystep999' __date__ = '2017/10/27 17:16' import xadmin from .models import Course, Lesson, Video, CourseResource class CourseAdmin(object): list_display = ['name', 'desc', 'detail', 'degree', 'learn_times', 'students', 'fav_nums', 'image', 'click_nums', 'add_time'] search_fields = ['name', 'desc', 'detail', 'degree', 'learn_times', 'students', 'fav_nums', 'image', 'click_nums'] list_filter = ['name', 'desc', 'detail', 'degree', 'learn_times', 'students', 'fav_nums', 'image', 'click_nums', 'add_time'] class LessonAdmin(object): list_display = ['course', 'name', 'add_time'] search_fields = ['course', 'name'] list_filter = ['course', 'name', 'add_time'] class VideoAdmin(object): list_display = ['lesson', 'name', 'add_time'] search_fields = ['lesson', 'name'] list_filter = ['lesson', 'name', 'add_time'] class CourseResourceAdmin(object): list_display = ['course', 'name', 'download', 'add_time'] search_fields = ['course', 'name', 'download'] list_filter = ['course', 'name', 'download', 'add_time'] xadmin.site.register(Course, CourseAdmin) xadmin.site.register(Lesson, LessonAdmin) xadmin.site.register(Video, VideoAdmin) xadmin.site.register(CourseResource, CourseResourceAdmin)
83298552792fcfd14d4e95bcb86b7696d0c29cb8
e1c6b71ec2db74f5324d96094eb43beba1af78f6
/source/controle/models.py
2656fbbc5bce64d8074b6f9a68a3b0982540b5f4
[]
no_license
ItaloAbreu/estacionamento_django_rest
3a2675223535a75247b8bc802010ab0746f65972
39136858044737cd9968adf2909ec6eaffa62806
refs/heads/master
2021-09-25T09:38:24.762026
2020-03-21T21:49:43
2020-03-21T21:49:43
237,626,670
0
0
null
2021-09-22T18:30:31
2020-02-01T14:29:10
Python
UTF-8
Python
false
false
1,300
py
from django.db import models from django.utils import timezone from .validators import validate_plate # Create your models here. class Parking(models.Model): plate = models.CharField( max_length=8, validators=[validate_plate], verbose_name='Placa do Veículo') reservation = models.CharField( max_length=9, editable=False, verbose_name='Número da Reserva') arrival = models.DateTimeField(auto_now_add=True, verbose_name='Entrada') departure = models.DateTimeField( null=True, blank=True, editable=False, verbose_name='Saída') paid = models.BooleanField( null=True, blank=True, editable=False, verbose_name='Pagamento') def __str__(self): return f'{self.reservation} ({self.plate})' def make_reservation(self): last = Parking.objects.filter(arrival__gte=timezone.now().date()).last() prefix = 'RESV' if not last: return "{0}{1}".format(prefix, '001') current_number = last.reservation.replace(prefix, '') current_number = str(int(current_number) + 1) if len(current_number) < 3: current_number = ((3 - len(current_number)) * '0') + current_number return "{0}{1}".format(prefix, current_number.zfill(3)) def save(self, *args, **kwargs): if not self.reservation: self.reservation = self.make_reservation() super(Parking, self).save(*args, **kwargs)
c7a74b2f4908196f9e25fc6b23dbfddc606efd1e
859bff7114adf87d741e9060f7464d4b3faf47a6
/practice/dfs, bfs/dfs,bfs.py
4bbbefc17c1f087e61c7d9ab0121b4089088f323
[]
no_license
psy1088/Algorithm
3047b517e8ba9d6ea460b2d3217db75c638e8207
15d82d564d32cd422716c6396d6f2cfa09b0c8cd
refs/heads/main
2023-06-09T14:27:38.531995
2021-07-08T05:53:10
2021-07-08T05:53:10
318,183,984
0
0
null
null
null
null
UTF-8
Python
false
false
2,676
py
# # p151 음료수 얼려먹기 DFS 풀이 # N, M = map(int, input().split()) # N=행의 수, M=열의 수 # graph = [] # for i in range(N): # graph.append(list(map(int, input().split()))) # # # def dfs(row, col): # # 그래프 범위 내에 있고, 칸막이 부분이 0이라면 => 1로 바꿔주고, 상하좌우 재귀탐색 # if 0 <= row < N and 0 <= col < M and graph[row][col] == 0: # graph[row][col] = 1 # dfs(row + 1, col) # dfs(row - 1, col) # dfs(row, col + 1) # dfs(row, col - 1) # return True # else: # 범위 초과 or 칸막이 부분이면 False # return False # # # result = 0 # for i in range(N): # for j in range(M): # if dfs(i, j): # result += 1 # print(result) # # # p151 음료수 얼려먹기 BFS 풀이 # from collections import deque # # N, M = 4, 5 # data = [[0, 0, 1, 1, 0], [0, 0, 0, 1, 1], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0]] # # dr = [-1, 0, 1, 0] # 위 오 아 왼 # dc = [0, 1, 0, -1] # 위 오 아 왼 # # q = deque() # cnt = 0 # # 좌표별로 확인해가면서 0인놈이 없을때까지 반복 # for i in range(N): # for j in range(M): # if data[i][j] == 1: # 벽이거나, 방문했으면 continue # continue # # data[i][j] = 1 # q.append((i, j)) # while q: # 큐가 빌 때까지 # v = q.popleft() # row, col = v[0], v[1] # for k in range(4): # 상하좌우 연결되어있으면 큐에 삽입 # n_r, n_c = row + dr[k], col + dc[k] # if 0 <= n_r < N and 0 <= n_c < M: # 범위를 벗어나지 않았을 때 # if data[n_r][n_c] == 0: # 벽이 아닌데, 방문하지 않았다면 큐에 추가 # q.append((n_r, n_c)) # data[n_r][n_c] = 1 # cnt += 1 # # print(cnt) # # p152 미로탈출 from collections import deque N, M = 5, 6 game_map = [[1, 0, 1, 0, 1, 0], [1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]] def bfs(r, c): q.append((r, c)) while q: r, c = q.popleft() for d in range(4): # 상하좌우 탐색해서 범위 안에 있고, 이동 가능한 경우 큐에 추가 n_r, n_c = r + dr[d], c + dc[d] if 0 <= n_r < N and 0 <= n_c < M and game_map[n_r][n_c] == 1: q.append((n_r, n_c)) game_map[n_r][n_c] = game_map[r][c] + 1 if n_r == N - 1 and n_c == M - 1: # 도착지점이면 리턴 return game_map[n_r][n_c] dr = [-1, 0, 1, 0] dc = [0, -1, 0, 1] q = deque() print(bfs(0, 0))
6f83f7dc50cbc2028bf2c6b1e578b94c2a593cb0
d2c4934325f5ddd567963e7bd2bdc0673f92bc40
/tests/artificial/transf_Quantization/trend_Lag1Trend/cycle_12/ar_/test_artificial_1024_Quantization_Lag1Trend_12__100.py
009dead988ececca3e907ac0f1dc2250b82392ff
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jmabry/pyaf
797acdd585842474ff4ae1d9db5606877252d9b8
afbc15a851a2445a7824bf255af612dc429265af
refs/heads/master
2020-03-20T02:14:12.597970
2018-12-17T22:08:11
2018-12-17T22:08:11
137,104,552
0
0
BSD-3-Clause
2018-12-17T22:08:12
2018-06-12T17:15:43
Python
UTF-8
Python
false
false
275
py
import pyaf.Bench.TS_datasets as tsds import pyaf.tests.artificial.process_artificial_dataset as art art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "Lag1Trend", cycle_length = 12, transform = "Quantization", sigma = 0.0, exog_count = 100, ar_order = 0);
91435fe0101353d14673c598094ce8d75d7b6780
26c019f7dadceaf773cd292d7364582bc2a278d2
/user_app/tests/interactors/raw_inputs.py
0b9d1fcc1eb22362432905c8446daa399ba983be
[]
no_license
DilLip-Chowdary-Codes/Backend_Mini_Projects
289d5213a1c62d5b2ab26397e0d684632b139ad1
f69dc6e9de4d621b782b703f2aa41cd126d8a58b
refs/heads/master
2022-11-12T02:09:36.600636
2020-07-09T15:05:21
2020-07-09T15:05:21
272,417,611
0
0
null
null
null
null
UTF-8
Python
false
false
4,638
py
from user_app.dtos\ import TaskDetailsDto, ProjectDto,\ StateDto, UserDto, ProjectDetailsDto,\ TaskDto, TransitionDetailsDto, ChecklistDetailsDto,\ UpdateTransitionInputDto, ChecklistStatusDto project_data = { "name": "projectManagement", "description": "it's a blaw blaw blaw blaw blaw blaw ", "workflow_id": 1, "project_type": "Classic Software", "developers": [1] } task_data = { "project_id": 1, "issue_type": "Enhancement", "title": "Optimizing DB", "description": "string", "state_id": 1 } user_dto = UserDto( user_id=1, username="username_1", profile_pic="http://www.google.com", phone_no="8739835635", is_admin=True ) developer_dto = UserDto( user_id=2, username="username_2", profile_pic="http://www.google.com", phone_no="8739835635", is_admin=False ) state_dto = StateDto( name="In Progress") state_2_dto = StateDto( name="New State") project_dto = ProjectDto( name="projectManagement", description="it's a blaw blaw blaw blaw blaw blaw ", workflow_id=1, project_type="Classic Software", developers=[1] ) project_details_dto = ProjectDetailsDto( project_id=1, name="projectManagement", description="it's a blaw blaw blaw blaw blaw blaw ", workflow="", project_type="Classic Software", created_by=user_dto, created_at="2020-05-28 10:06:23", developers=[developer_dto] ) task_dto = TaskDto( project_id=1, issue_type="Enhancement", title="Optimizing DB", description="string", state_id=1) task_details_dto = TaskDetailsDto( task_id=1, project=project_details_dto, issue_type="Enhancement", title="Optimizing DB", assignee=user_dto, description="string", state=state_dto ) tasks_dtos = [task_dto] tasks_details_dtos = [task_details_dto] #task_transition checklist_input_dict= { "checklist_id": 1, "is_checked": True } checklist_input_dict_2 = { "checklist_id": 2, "is_checked": False } checklist_input_dicts_list = [ checklist_input_dict, checklist_input_dict_2] checklist_input_dict_unsatisfied_1 = { "checklist_id": 1, "is_checked": False } checklist_input_dicts_list_unsatisfied_mandatory_fields = [ checklist_input_dict_unsatisfied_1, checklist_input_dict_2 ] checklist_status_dto = ChecklistStatusDto( checklist_id=checklist_input_dict['checklist_id'], is_checked=checklist_input_dict['is_checked']) checklist_status_dto_2 = ChecklistStatusDto( checklist_id=checklist_input_dict_2['checklist_id'], is_checked=checklist_input_dict_2['is_checked']) checklist_status_dtos_list = [ checklist_status_dto, checklist_status_dto_2 ] checklist_status_dto_unsatisfied = ChecklistStatusDto( checklist_id=checklist_input_dict_unsatisfied_1['checklist_id'], is_checked=checklist_input_dict_unsatisfied_1['is_checked']) checklist_status_dtos_list_unsatisfied_mandatory_fields = [ checklist_status_dto_unsatisfied, checklist_status_dto_2 ] update_task_state_input_data = { "user_id": 1, "project_id": 1, "task_id": 1, "from_state_id": 1, "to_state_id": 2, "checklist": checklist_input_dicts_list } update_task_state_input_data_with_unchecked_mandatory_checklist = { "user_id": 1, "project_id": 1, "task_id": 1, "from_state_id": 1, "to_state_id": 2, "checklist": checklist_input_dicts_list_unsatisfied_mandatory_fields } transition_details_query_dict = { "project_id":1, "task_id":1, "to_state_id":2 } task_state_data = { "user_id": 1, "project_id": 1, "task_id": 1 } from_state_id = task_dto.state_id update_task_state_query_dto = UpdateTransitionInputDto( project_id=update_task_state_input_data['project_id'], task_id=update_task_state_input_data['task_id'], from_state_id=from_state_id, to_state_id=update_task_state_input_data['to_state_id'], checklist=checklist_status_dtos_list) update_task_state_query_dto_with_unchecked_mandatory_checklist\ = UpdateTransitionInputDto( project_id=\ update_task_state_input_data_with_unchecked_mandatory_checklist[ 'project_id'], task_id=\ update_task_state_input_data_with_unchecked_mandatory_checklist[ 'task_id'], from_state_id=from_state_id, to_state_id=\ update_task_state_input_data_with_unchecked_mandatory_checklist[ 'to_state_id'], checklist=checklist_status_dtos_list_unsatisfied_mandatory_fields )
8c2ff070a10e8771592850db1c845a53ec43629c
17c01c40b1324553dd44aa34a47481add27853e5
/main.py
6dbd2ff83121298ecd0f5f687d6109020dbad318
[ "MIT" ]
permissive
finn102/Python-Basics
691f156a9e40115cb9d64cbd75667ca514759aed
d36301f7ca9123fa46f1cd75c55eca0a369c522d
refs/heads/master
2020-04-14T15:38:12.151650
2019-01-03T06:53:36
2019-01-03T06:53:36
163,933,064
0
0
null
null
null
null
UTF-8
Python
false
false
33
py
import os import sys print("OK")
92476a49a95a1903850e0fff124bebc181d4136e
32f61223ae8818f64922d69dc8d279428cd568e3
/AlphaTwirl/AlphaTwirl/Loop/NullCollector.py
212e63c87a8b257d129830e32131f74f42176eca
[ "BSD-3-Clause" ]
permissive
eshwen/cutflowirl
959fdead7cc1f58e77e68074a9ee491c3259c6d6
e20372dc3ce276c1db4e684b8e9f1e719b9e8e7d
refs/heads/master
2020-04-05T11:20:49.000726
2017-11-23T16:15:10
2017-11-23T16:15:10
81,349,000
0
0
null
2017-11-23T16:15:11
2017-02-08T16:15:59
Python
UTF-8
Python
false
false
382
py
# Tai Sakuma <[email protected]> ##__________________________________________________________________|| class NullCollector(object): def __repr__(self): return '{}()'.format(self.__class__.__name__) def addReader(self, datasetName, reader): pass def collect(self): pass ##__________________________________________________________________||
fae7d19d653a4b12515cdbcd3f1631d31fd95118
247db0fd637c6eb357f4be4eb8440e80ab50c323
/captureandupload.py
e7966b68e6d8816cb183704cb979243e189ce2d0
[]
no_license
Akshitha296/Class102
40db773267a1773451da4360e353bdb10f89b5ad
127f32396daf4bb1d68c63da9b45b92acd09fb2e
refs/heads/main
2023-04-04T16:08:32.079047
2021-04-05T02:06:24
2021-04-05T02:06:24
354,690,884
0
0
null
null
null
null
UTF-8
Python
false
false
1,137
py
import cv2 import time import random import dropbox startTime = time.time() def take_snapshot(): rand = random.randint(1, 1000000) videoCaptureObject = cv2.VideoCapture(0) result = True while(result): ret, frame = videoCaptureObject.read() print(ret) img_name = "img"+str(rand)+".png" cv2.imwrite(img_name, frame) startTime = time.time() result = False return(img_name) print("Snapshot Taken. File name is " + img_name) videoCaptureObject.release() cv2.destroyAllWindows() def upload_file(img_name): access_token = 'OgTQw6cs2QcAAAAAAAAAAQzJXCPbcAV6gnWbO-83_A_4hb-ANP53LhNAkKWevbOP' file_from = img_name file_to = "/DontLookAtMyPCImWatchingU/" + img_name dbx = dropbox.Dropbox(access_token) with open(file_from, 'rb') as f: dbx.files_upload(f.read(), file_to, mode = dropbox.files.WriteMode.overwrite) print("File uploaded to dropbox.") def main(): while(True): if(time.time()-startTime>=300): name = take_snapshot() upload_file(name) main()
42217171feee863b0a0ff726b49a6e2c87bbddba
792018368b650d418933cde15944feec4d8f2e30
/testdata/sss_sume_metadata.py
1acb81f853e3464e25bbedc718b9111ec1fd040d
[]
no_license
sibanez12/perc-p4
a67e0c287e1a9269ee0154e09e77810771540960
aa8721523b171dbbd9d5b77cb42091298f270e04
refs/heads/master
2020-09-04T09:59:47.826784
2019-11-05T09:28:34
2019-11-05T09:28:34
219,704,657
2
1
null
null
null
null
UTF-8
Python
false
false
2,284
py
#!/usr/bin/env python # # Copyright (c) 2017 Stephen Ibanez # All rights reserved. # # This software was developed by Stanford University and the University of Cambridge Computer Laboratory # under National Science Foundation under Grant No. CNS-0855268, # the University of Cambridge Computer Laboratory under EPSRC INTERNET Project EP/H040536/1 and # by the University of Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-11-C-0249 ("MRC2"), # as part of the DARPA MRC research programme. # # @NETFPGA_LICENSE_HEADER_START@ # # Licensed to NetFPGA C.I.C. (NetFPGA) under one or more contributor # license agreements. See the NOTICE file distributed with this work for # additional information regarding copyright ownership. NetFPGA licenses this # file to you under the NetFPGA Hardware-Software License, Version 1.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.netfpga-cic.org # # Unless required by applicable law or agreed to in writing, Work 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. # # @NETFPGA_LICENSE_HEADER_END@ # """ Define the sume_metadata bus for SDNet simulations """ import collections """ SDNet Tuple format: unused; (88 bits) hp_dst_port; (8 bits) lp_dst_port; (8 bits) src_port; (8 bits) pkt_len; (16 bits) """ sume_field_len = collections.OrderedDict() sume_field_len['unused'] = 88 sume_field_len['hp_dst_port'] = 8 sume_field_len['lp_dst_port'] = 8 sume_field_len['src_port'] = 8 sume_field_len['pkt_len'] = 16 # initialize tuple_in sume_tuple_in = collections.OrderedDict() sume_tuple_in['unused'] = 0 sume_tuple_in['hp_dst_port'] = 0 sume_tuple_in['lp_dst_port'] = 0 sume_tuple_in['src_port'] = 0 sume_tuple_in['pkt_len'] = 0 #initialize tuple_expect sume_tuple_expect = collections.OrderedDict() sume_tuple_expect['unused'] = 0 sume_tuple_expect['hp_dst_port'] = 0 sume_tuple_expect['lp_dst_port'] = 0 sume_tuple_expect['src_port'] = 0 sume_tuple_expect['pkt_len'] = 0
91cbe9968b893032488177046dec7f4b360d210c
81a7055d0c48ca1d1e79c0f8b3f15a1393b10037
/src/ch03/sec22_category_name.py
ead4bce7211b9f475ebde60be141df3e767a9a9a
[]
no_license
struuuuggle/NLP100
4584c09e57f0ac1966af75588bb28cef7c1fcfe8
e2452ccfc01acb4af520ae262c2840b608198cd5
refs/heads/master
2021-05-10T18:44:22.926741
2018-12-02T13:49:12
2018-12-02T13:49:12
118,134,354
0
0
null
null
null
null
UTF-8
Python
false
false
399
py
# -*- coding: utf-8 -*- import re def category_name(filename): category_name_regex = re.compile(r'(?<=\[\[Category:).*(?=\]\])') with open(filename, 'r') as f: categories = category_name_regex.findall(f.read()) result = '\n'.join(categories) print(result) return result def main(): category_name('./test/uk.txt') if __name__ == '__main__': main()
d2cdceb7e15f8dc3a77542ed4221fa9098f904fe
8bf1228e9ec1211d3680b31b2e529d2035dc4bd6
/actions/spice.py
fa7331533c08a5cac42f56ff5d9d968126fbec1c
[ "MIT" ]
permissive
thomasrstorey/recipesfordisaster
061bf5e24b2fd3acc1b3b8ed665c849bf7ed19ba
7f8282e056a0d6351b88672e817dceb7b399cbd9
refs/heads/master
2021-01-10T02:34:48.222821
2016-03-11T18:37:30
2016-03-11T18:37:30
49,224,607
1
0
null
null
null
null
UTF-8
Python
false
false
4,373
py
''' add.py Takes a list of input ingredient names. Imports each if not already present. If already present, duplicates and rotates the ingredient. Thomas Storey 2016 ''' import sys import argparse import bpy import numpy as np import os import bmesh from math import * from mathutils import * import random def getObjectsBySubstring(objname): copies = [] for obj in bpy.data.objects: if(objname in obj.name): copies.append(obj) return copies def deleteObject(obj): bpy.context.scene.objects.unlink(obj) obj.user_clear() bpy.data.objects.remove(obj) def getObject(objdir, objname): if (bpy.data.objects.get(objname) == None): objpath = os.path.join(objdir, objname+".obj") bpy.ops.import_scene.obj(filepath=objpath, axis_forward='Y',axis_up='Z') return bpy.data.objects[objname] def setOriginToGeometry(scn, obj): obj.select = True; scn.objects.active = obj bpy.ops.object.origin_set(type="ORIGIN_GEOMETRY") obj.select = False; def joinObjects(scn, objs, name): bpy.ops.object.select_all(action='DESELECT') for obj in objs: obj.select = True activeobj = objs[0] scn.objects.active = activeobj bpy.ops.object.join() activeobj.name = name activeobj.data.name = name return activeobj def bakeObject(scn, obj): bpy.ops.object.select_all(action='DESELECT') obj.select = True scn.objects.active = obj mat = obj.material_slots[0].material tex = bpy.data.textures.new(name="baste", type="CLOUDS") tex_slot = mat.texture_slots.add() tex_slot.texture = tex tex.type = "MUSGRAVE" tex.type_recast() scn.update() tex.noise_scale = 0.03 + (random.random()*0.05) tex.intensity = 1.1 tex.contrast = 1.0 tex_slot.use_map_color_diffuse = True tex_slot.invert = True tex_slot.diffuse_color_factor = 1.0 tex_slot.use_map_alpha = True tex_slot.alpha_factor = 1.0 tex_slot.color = (0.073, 0.019, 0.010) # bpy.ops.texture.new() # baked_tex = bpy.data.textures["Texture"] # baked_tex.name = "baked" # baked_tex_slot = mat.texture_slots.create(2) # baked_tex_slot.texture = baked_tex # bpy.ops.image.new() # baked_img = bpy.data.images["Untitled"] # baked_img.name = "baked_img" # mat.active_texture_index = 2 # mat.active_texture = baked_tex # # bpy.ops.object.mode_set(mode="EDIT") # bpy.data.scenes["Scene"].render.bake_type = "TEXTURE" # for area in bpy.context.screen.areas : # if area.type == 'IMAGE_EDITOR' : # area.spaces.active.image = baked_img # bpy.ops.object.bake_image() # mat.texture_slots[0].texture.image = baked_img def execute(inputs, output): ctx = bpy.context scn = ctx.scene cwd = os.getcwd() objdir = os.path.join(cwd, 'objs') for objname in inputs: # import file, or get it if it's already here obj = getObject(objdir, objname) obj.location = Vector([0,0,0]) bakeObject(scn, obj) # save out .blend if not output == None: bpy.ops.wm.save_as_mainfile(filepath=output, check_existing=False,relative_remap=True) else: bpy.ops.wm.save_mainfile(check_existing=False,relative_remap=True) def main(): argv = sys.argv if "--" not in argv: argv = [] else: argv = argv[argv.index("--") + 1:] usage_text =\ "Usage: blender -b [.blend file] --python " + __file__ + " -- [options]" parser = argparse.ArgumentParser(description=usage_text) parser.add_argument("-i", "--input", dest="input", type=str, required=True, help="Comma delimited list of .objs to import. Exclude the file extension.") parser.add_argument("-o", "--output", dest="output", type=str, required=False, help="Name of blend file to save to, if not the same as the one being opened.") args = parser.parse_args(argv) output = "" if not argv: parser.print_help() return if not args.input: print("input argument not given. aborting.") parser.print_help() return if not args.output: output = None else: output = args.output+".blend" inputs = args.input.split(",") execute(inputs, output) print("basted " + ", ".join(inputs)) if __name__ == "__main__": main()
ddb052d3917074619f88e5c250e223b616556c1b
906c6abf6721303449a86c842a97193e86f1e88a
/sm/backup/NTCIR-Evaluation/src/GenerateXml.py
30fa4354df107cf7417f11691a505ef644d9dd60
[]
no_license
luochengleo/thuirwork
a5b5bedaa59dd94fde6c58d6c2ddba75fb99d374
2bf230949757401c15dee50249a0fa8aded595ad
refs/heads/master
2020-04-13T12:49:03.752647
2014-08-31T08:37:52
2014-08-31T08:37:52
22,720,301
1
0
null
null
null
null
UTF-8
Python
false
false
2,545
py
#coding=utf8 import xml.etree.ElementTree as ET from xml.etree.ElementTree import Element from collections import defaultdict import sys,csv import codecs from bs4 import BeautifulSoup reload(sys) sys.setdefaultencoding("utf8") def loadcsv(filename): return csv.reader(open(filename)) id2topic = dict() for l in open('../data/temp/IMine.Query.txt').readlines(): id,topic = l.replace(codecs.BOM_UTF8,'').strip().split('\t') id2topic[id] = topic print id,topic def evaid(): rtr = [] for i in range(1,34,1): if i <10: rtr.append('000'+str(i)) else: rtr.append('00'+str(i)) return rtr sls2id = dict() for l in open('../data/temp/slsposs.txt').readlines(): segs = l.strip().split('\t') sls2id[segs[1]] = segs[0] id2fls2sls2queries = defaultdict(lambda:defaultdict(lambda:defaultdict(lambda:set()))) for l in loadcsv('../data/csv/task6.csv'): query = l[1] fls = l[3] sls = l[4] if sls in sls2id: if query != '' and fls != '' and sls != '': id = sls2id[sls] id2fls2sls2queries[id][fls][sls].add(query) id2fls = defaultdict(lambda:list()) id2flsposs = defaultdict(lambda:dict()) for l in open('../data/temp/flsposs.txt'): segs = l.strip().split('\t') id = segs[0] fls = segs[1] poss = float(segs[2]) id2fls[id].append(fls) id2flsposs[id][fls] = poss id2sls = defaultdict(lambda:list()) id2slsposs = defaultdict(lambda:dict()) for l in open('../data/temp/slsposs.txt'): segs = l.strip().split('\t') id = segs[0] sls = segs[1] poss = float(segs[2]) id2sls[id].append(sls) id2slsposs[id][sls] = poss for l in open('../data/temp/flsposs.txt'): segs = '' root = ET.Element('root') for id in evaid(): topic = id2topic[id] topicnode = ET.Element('topic',{'id':id,'content':topic}) for fls in id2fls[id]: print id,fls flsnode = ET.Element('fls',{'content':fls,'poss':str(id2flsposs[id][fls])}) for sls in id2sls[id]: if sls in id2fls2sls2queries[id][fls]: slsnode = ET.Element('sls',{'content':sls,'poss':str(id2slsposs[id][sls])}) for q in id2fls2sls2queries[id][fls][sls]: expnode = ET.Element('example') expnode.text = q slsnode.append(expnode) flsnode.append(slsnode) topicnode.append(flsnode) root.append(topicnode) tree = ET.ElementTree(root) tree.write('../data/test.xml','utf8')
81735e35f02edc6bdacfd5c3832912d8cc1b5775
04abbae690a8e2a2dc9bfe54313d40703d06ec5b
/bookReview/api/views.py
5b65f5dc6dead09ba6acee116c658f1de8331719
[]
no_license
shivamsy/Django-Rest-Framework
b30a83d65cda38e01452e9be3a3f5a28498b7fd1
8cc3bb95a4b12e95bb28fed881b575660ac26bf9
refs/heads/master
2021-06-16T17:04:13.724630
2019-06-15T05:59:38
2019-06-15T05:59:38
177,078,803
0
0
null
2021-06-10T21:23:23
2019-03-22T05:46:02
Python
UTF-8
Python
false
false
762
py
from django.shortcuts import render, redirect, reverse, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from . import models from . import serializers # Create your views here. class ListCreateBook(APIView): def get(self, request, format=None): books = models.Book.objects.all() serializer = serializers.BookSerializer(books, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = serializers.BookSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED)
dd79f3465eec12b32953867a5708350596ad71c1
98d44c4e958bb4c6b053201e1918e785445c15ba
/bzt/modules/ab.py
6064be3085acca80e3b7515a88a2207fd860f2b1
[ "Apache-2.0" ]
permissive
mukteshkrmishra/taurus
472309a829e525ba06d76c3eac2dff2219322af2
cf891118b1f2cb3395e1b494a5344bfc3039b9af
refs/heads/master
2021-01-20T17:47:39.104580
2016-04-17T13:43:42
2016-04-17T13:43:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,234
py
""" Module holds all stuff regarding usage of Apache Benchmark Copyright 2016 BlazeMeter Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import logging import time from math import ceil from os import path from bzt.engine import ScenarioExecutor from bzt.modules.aggregator import ConsolidatingAggregator, ResultsReader from bzt.six import iteritems from bzt.utils import shell_exec, shutdown_process, RequiredTool, dehumanize_time class ApacheBenchmarkExecutor(ScenarioExecutor): """ Apache Benchmark executor module """ def __init__(self): super(ApacheBenchmarkExecutor, self).__init__() self.log = logging.getLogger('') self.process = None self.__tsv_file_name = None self.__out = None self.__err = None self.__rc_name = None self.__url_name = None self.tool_path = None self.scenario = None self.reader = None self.start_time = None def prepare(self): self.scenario = self.get_scenario() self.tool_path = self._check_installed() self.__tsv_file_name = self.engine.create_artifact("ab", ".tsv") out_file_name = self.engine.create_artifact("ab", ".out") self.reader = TSVDataReader(self.__tsv_file_name, self.log) if isinstance(self.engine.aggregator, ConsolidatingAggregator): self.engine.aggregator.add_underling(self.reader) self.__out = open(out_file_name, 'w') self.__err = open(self.engine.create_artifact("ab", ".err"), 'w') def startup(self): args = [self.tool_path] load = self.get_load() if load.hold: hold = int(ceil(dehumanize_time(load.hold))) args += ['-t', str(hold)] elif load.iterations: args += ['-n', str(load.iterations)] else: args += ['-n', '1'] # 1 iteration by default load_concurrency = load.concurrency if load.concurrency is not None else 1 args += ['-c', str(load_concurrency)] args += ['-d'] # do not print 'Processed *00 requests' every 100 requests or so args += ['-g', str(self.__tsv_file_name)] # dump stats to TSV file # add global scenario headers for key, val in iteritems(self.scenario.get_headers()): args += ['-H', "%s: %s" % (key, val)] requests = list(self.scenario.get_requests()) if not requests: raise ValueError("You must specify at least one request for ab") if len(requests) > 1: self.log.warning("ab doesn't support multiple requests." " Only first one will be used.") request = requests[0] # add request-specific headers for header in request.headers: for key, val in iteritems(header): args += ['-H', "%s: %s" % (key, val)] if request.method != 'GET': raise ValueError("ab supports only GET requests") keepalive = True if request.config.get('keepalive') is not None: keepalive = request.config.get('keepalive') elif self.scenario.get('keepalive') is not None: keepalive = self.scenario.get('keepalive') if keepalive: args += ['-k'] args += [request.url] self.reader.setup(load_concurrency, request.label) self.start_time = time.time() self.process = self.execute(args, stdout=self.__out, stderr=self.__err) def check(self): ret_code = self.process.poll() if ret_code is None: return False self.log.info("ab tool exit code: %s", ret_code) if ret_code != 0: raise RuntimeError("ab tool exited with non-zero code") return True def shutdown(self): shutdown_process(self.process, self.log) def post_process(self): if self.__out and not self.__out.closed: self.__out.close() if self.__err and not self.__err.closed: self.__err.close() def _check_installed(self): tool_path = self.settings.get('path', 'ab') ab_tool = ApacheBenchmark(tool_path, self.log) if not ab_tool.check_if_installed(): raise RuntimeError("You must install ab tool at first") return tool_path class TSVDataReader(ResultsReader): def __init__(self, filename, parent_logger): super(TSVDataReader, self).__init__() self.log = parent_logger.getChild(self.__class__.__name__) self.filename = filename self.fds = None self.skipped_header = False self.concurrency = None self.url_label = None def setup(self, concurrency, url_label): self.concurrency = concurrency self.url_label = url_label def __open_fds(self): if not path.isfile(self.filename): self.log.debug("File not appeared yet") return False if not path.getsize(self.filename): self.log.debug("File is empty: %s", self.filename) return False if not self.fds: self.fds = open(self.filename) return True def __del__(self): if self.fds: self.fds.close() def _read(self, last_pass=False): while not self.fds and not self.__open_fds(): self.log.debug("No data to start reading yet") yield None if last_pass: lines = self.fds.readlines() self.fds.close() else: lines = self.fds.readlines(1024 * 1024) for line in lines: if not self.skipped_header: self.skipped_header = True continue log_vals = [val.strip() for val in line.split('\t')] _error = None _rstatus = None _url = self.url_label _concur = self.concurrency _tstamp = int(log_vals[1]) # timestamp - moment of request sending _con_time = float(log_vals[2]) # connection time _etime = float(log_vals[4]) # elapsed time _latency = float(log_vals[5]) # latency (aka waittime) yield _tstamp, _url, _concur, _etime, _con_time, _latency, _rstatus, _error, '' class ApacheBenchmark(RequiredTool): def __init__(self, tool_path, parent_logger): super(ApacheBenchmark, self).__init__("ApacheBenchmark", tool_path) self.tool_path = tool_path self.log = parent_logger.getChild(self.__class__.__name__) def check_if_installed(self): self.log.debug('Checking ApacheBenchmark: %s' % self.tool_path) try: shell_exec([self.tool_path, '-h']) except OSError: return False return True
b330c7104d1f54f45acc711c95ac2a54cc1f740e
b83d59b6dcb847daad2265b04b75aeae3aded52e
/sad.py
d5a8861df40b30d89d742335b5583d67ae7f50db
[]
no_license
fmorisan/amaurascripts
9ce23f8cdda86b98289c6c915ad53a1192b405f0
3c1e0470a3a2942525bfda9088b8f0b6ba6dae32
refs/heads/master
2021-01-10T11:42:50.755458
2015-10-12T17:40:49
2015-10-12T17:40:49
43,343,028
0
0
null
null
null
null
UTF-8
Python
false
false
166
py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A simple sample module with Skype smileys """ import os print "dBot loves %s (hug)" % os.environ["SKYPE_FULLNAME"]
2c0baaccf388dbd4752cbe1e24dc4789986eda13
c7ed6ec9c49f54b6463d76a3d71d59e548f2283b
/backend/src/manage.py
72b64711362dd05b67802560f0eb9bc4a296a819
[]
no_license
dakotarudzik/oldmak
a3855bf798debefe2bf2b555983f5908c6c346fd
5a17342250349cbe6df4671e170e132be121f244
refs/heads/master
2022-06-09T06:21:42.871769
2020-05-08T00:21:51
2020-05-08T00:21:51
262,187,081
0
0
null
null
null
null
UTF-8
Python
false
false
628
py
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'makenzie.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
0c387477bf0f53b6d72288128e556464fcafa9e5
49d28b05f29cbf11c6ee826b539cb90e4858daac
/examples/actors/time/actor.py
cd88266739e3f0a890523c94033fbe8d758d8411
[ "MIT" ]
permissive
the01/python-alexander
2814c8879ff488145ec6ed5bbf87b38129d7b603
4ca0d0715c943cc8310e577857b20f76504e8633
refs/heads/master
2023-06-24T09:46:37.879699
2019-04-17T00:00:02
2019-04-17T00:00:02
88,805,948
0
0
MIT
2018-01-05T07:36:01
2017-04-20T01:12:21
Python
UTF-8
Python
false
false
1,518
py
# -*- coding: UTF-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __author__ = "d01" __email__ = "[email protected]" __copyright__ = "Copyright (C) 2017, Florian JUNG" __license__ = "MIT" __version__ = "0.1.1" __date__ = "2017-04-23" # Created: 2017-04-23 22:30 import datetime from nameko.rpc import rpc from flotils import get_logger from alexander_fw.dto import ActorMessage, serialize logger = get_logger() class EchoActorService(object): name = "service_actor_time" @rpc def status(self): return "OK" @rpc def act(self, message): logger.debug(message) # Return current time reply = ActorMessage.from_dict(serialize(message)) reply.result = datetime.datetime.utcnow() return reply if __name__ == "__main__": import logging.config import os import sys from flotils.logable import default_logging_config from nameko.cli.main import main from alexander_fw import setup_kombu logging.config.dictConfig(default_logging_config) logging.getLogger().setLevel(logging.DEBUG) logger = logging.getLogger(__name__) setup_kombu() pid = os.getpid() logger.info(u"Detected pid {}".format(pid)) logger.info(u"Using virtualenv {}".format(hasattr(sys, 'real_prefix'))) logger.info(u"Using supervisor {}".format( bool(os.getenv('SUPERVISOR_ENABLED', False))) ) main()
e13db41af418a2896e05121c9e2d591d24eaa882
9b6b3f4b30e9bd8a821d8df16bd71e62b9c6eb98
/day2/data_structs/conversion_4.py
eedfdf0af2d6d721cb076e44d17b34e8eb93b27a
[]
no_license
shobhit-nigam/snape_mar
b7f2155cfcd83482230c339fe45f9ea851061318
b7b33a767cc00d35a22e40c940b4331e4898c8d5
refs/heads/main
2023-03-25T05:44:21.244078
2021-03-26T05:27:28
2021-03-26T05:27:28
350,555,721
1
1
null
null
null
null
UTF-8
Python
false
false
330
py
# sorted avengers = {'captain':'shield', 'ironman':'suit', 'hulk':['smash', 'science'], 'black widow':'energy'} xmen = ['mystique', 'magneto', 'wolverine'] dc = ('wonder woman', 'batman', 'flash') stra = "hello" print(list(stra)) print(sorted(stra)) print(sorted(dc)) print(sorted(xmen)) print(sorted(avengers))
066c37e93a1c10c1dba403835de6856cbfc5ff06
2cd20d64e85d88aef32ed5376ca5b0e1505bbda6
/gama/__version__.py
06097df6d52a5146c5d78381f22cbde1692271d9
[ "Apache-2.0" ]
permissive
learsi1911/GAMA_pygmo_v12
996232936abe11cf7d5ec7017cddd646bbe1185b
f27838bfff9a5f1fcda9f3117ba8d1e0c640cf42
refs/heads/master
2023-08-18T21:27:22.368967
2021-10-19T08:14:03
2021-10-19T08:14:03
408,051,460
0
0
null
null
null
null
UTF-8
Python
false
false
52
py
# format: YY.minor.micro __version__ = "21.0.1.dev"
543bf879509906b36ef6b8b9af0b54794af05af1
5ae88a0a197a52086edffe9c031bc424634b55d4
/AizuOnlineJudge/ITP1/7/B.py
aedc1507f808064d4233dc41b670f6f0eec59703
[]
no_license
muck0120/contest
1b1226f62e0fd4cf3bd483e40ad6559a6f5401cb
de3877822def9e0fe91d21fef0fecbf025bb1583
refs/heads/master
2022-07-17T17:31:50.934829
2020-05-18T09:55:30
2020-05-18T09:55:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
283
py
while True: n, x = map(int, input().split()) if n == x == 0: break cnt = 0 for i in range(1, n + 1): for j in range(i + 1, n + 1): for k in range(j + 1, n + 1): if i + j + k == x: cnt += 1 print(cnt)
6ee9319386bee693895d2bbf8679a879cc4eb14a
9090a487059bf72163d6fe06db2c7c6653b82495
/website/canary/admin.py
f9d7b7cfd205658233cb1b394058c843eced5337
[]
no_license
frankcarey/canary-challenge
cb6d83cfa30324afcdc85e3408ae59d251378580
81cec6273d9eaba4edfedfa33a2b26149f08b06b
refs/heads/master
2020-05-17T00:51:14.812757
2013-08-31T03:14:45
2013-08-31T03:14:45
null
0
0
null
null
null
null
UTF-8
Python
false
false
446
py
from django.contrib import admin from canary.models import Customer, Device, Temperature class TemperatureInline(admin.TabularInline): model = Temperature class DeviceInline(admin.TabularInline): model = Device class CustomerAdmin(admin.ModelAdmin): inlines = [DeviceInline] class DeviceAdmin(admin.ModelAdmin): inlines = [TemperatureInline] admin.site.register(Device, DeviceAdmin) admin.site.register(Customer, CustomerAdmin)
7c28b71c606eb42adee5d5964c7085ee7823649b
680220a091061b5e74f55ade4e4826d27ce1c500
/PythonTEST.pyw
b324c03811960cd573fba7ece092198db666c088
[]
no_license
Proklinius897/Projet-BDD
5094f06db52e00dde82daa3ce34ee0cc68b98119
fe7f32dd5a6bacadb22fe03c54dd48ee0a3b393d
refs/heads/master
2022-09-17T06:20:10.435090
2020-06-01T21:43:05
2020-06-01T21:43:05
268,081,919
0
0
null
null
null
null
UTF-8
Python
false
false
24,868
pyw
#############PROJET BBD2 MARC TRAVERSO ---- SIMON TANCEV ########################### ##############SI il y a une erreur veuilliez lire le readme.txt ou le rapport############### #####################IL FAUT CONFIGURER votre root ou admin###########################"" ##################Il faut aussi créer un user =user################################ import mysql.connector from tkinter import * from datetime import * import re import calendar import numpy as np def getvalue(widget,widget2): tab =["0","0"] tab[0]=widget.get() tab[1]=widget2.get() return tab #####permet de se connecter, et lance la deuxieme page def connection(compte,mdp,thisroot): tab1 = getvalue(compte,mdp) global mydb try: mydb = mysql.connector.connect( host="localhost", user=tab1[0], passwd=tab1[1], auth_plugin='mysql_native_password', database="psychologue" ) if mydb!=None: deuxieme(thisroot) except: error("Mauvais mot de passe") ####Permet de se connecter en tant qu'utilisateur def connectionuser(email,password,root): ###on se connecte directement a la base de donnée mais on accede a la seconde page que si l'email et l'utilisateur sont correspondant global mydb try: mydb = mysql.connector.connect( host="localhost", user="user", passwd="", auth_plugin='mysql_native_password', database="psychologue" ) except: error("Mauvais mot de passe") tableau=gettable("user") for i in range(len(tableau)): if tableau[i][3]==email and tableau[i][4]==password: deuxiemebis(root,tableau[i][0]) """ sql = "INSERT INTO patient (Id_client,Id_couple,Nom,Prenom,Addresse,Mail,Telephone,Sexe,DateNaissance,Moyen) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" val = ("","123249","John", "Sim", "57 rue de tanger","[email protected]","0657","0","1999-12-16","jzal") mycursor.execute(sql,val) mydb.commit()""" ###permet de se déconnecter def confirmer(root): ###Ouvre une page pour confirmer la déconnexion confirmer=Tk() center(confirmer) confirmer.title("Confirmer") label=Label(confirmer,text="Êtes vous sur de vouloir quitter?") Oui=Button(confirmer,text="Oui", command=lambda:deconnect(root,confirmer)) Non=Button(confirmer,text="Non",command=lambda:deco(confirmer)) label.pack() Oui.pack() Non.pack() def deconnect(root,root2): ###Si oui est clické cela deconnecte la totalité root.destroy() premiere(root2) ### select lambda def printable(name): mycursor = mydb.cursor() mycursor.execute("SELECT * FROM "+name) myresult = mycursor.fetchall() lenght=len(myresult) for x in myresult: print(x) return myresult ####retourne une table sans la print def gettable(name): mycursor = mydb.cursor() mycursor.execute("SELECT * FROM "+name) myresult = mycursor.fetchall() return myresult ####destroy rapide def deco(root): root.destroy() #####generer la premiere du client def premiereclient(root2): if root2!=None: deco(root2) root = Tk() center(root) root.title("Connexion page client") lab1 = Label(root,text="Bienvenue, veuilliez vous connecter") lab2 = Label(root,text="Identifiant : ") lab3=Label(root,text="Mot de passe") entryname= Entry(root) entrypass= Entry(root,show='*') lab1.grid(column=0, row=0) lab2.grid(column=0, row=1) entryname.grid(column=1, row=1) lab3.grid(column=0, row=2) entrypass.grid(column=1, row=2) button = Button(root,text='Connexion',command = lambda : connectionuser(entryname.get(),entrypass.get(),root)) client=Button(root,text="psy",command=lambda:premiere(root)) button.grid(column=0,row=5) client.grid(column=0,row=6) ######premiere page de la psy def premiere (root2): if root2!=None: deco(root2) root = Tk() center(root) root.title("Connexion page") lab1 = Label(root,text="Bienvenue, veuilliez vous connecter") lab2 = Label(root,text="Identifiant : ") lab3=Label(root,text="Mot de passe") entryname= Entry(root) entrypass= Entry(root,show='*') ####show cache le mot de passe lab1.grid(column=0, row=0) lab2.grid(column=0, row=1) entryname.grid(column=1, row=1) lab3.grid(column=0, row=2) entrypass.grid(column=1, row=2) button = Button(root,text='Connexion',command = lambda : connection(entryname,entrypass,root)) client=Button(root,text="Client",command = lambda : premiereclient(root)) button.grid(column=0,row=5) client.grid(column=0,row=6) return root ######class qui créer un calendrier class TkinterCalendar(calendar.Calendar): def formatmonth(self, master, year, month): consult=gettable("consultation") datesrdv=[None]*len(consult) i=0 while i<len(consult): datesrdv[i]=consult[i][1] i+=1 datesrdv = np.array(datesrdv) datesnotoccur = np.unique(datesrdv) dates = self.monthdatescalendar(year, month) frame = Frame(master) self.labels = [] for r, week in enumerate(dates): labels_row = [] for c, date in enumerate(week): label = Button(frame, text=date.strftime('%Y\n%m\n%d')) label.grid(row=r, column=c) if date.month != month: label['bg'] = '#aaa' if c == 6: label['fg'] = 'red' for x in datesrdv : if date.month==x.month and date.day==x.day and date.year==x.year: ####permet de mettre en bleu les dates ou il existe un rdv label['bg']='blue' labels_row.append(label) self.labels.append(labels_row) return frame ##def onclick(): #####permet de voir les rendez-vous depuis le compte de la psy def consulterrdv(root2): ### root2.destroy() i=0 j=1 k=2 root = Tk() root.title("Rendez-vous planifiés") center(root) rdvpre=gettable("vue_psy") dates=[None]*len(rdvpre) dates2=[None]*len(rdvpre) x=1 y=0 année=[None] mois=[None] while i < len(rdvpre): dates[i]=rdvpre[i][0] dates2[i]=datetime(rdvpre[i][0].year,rdvpre[i][0].month,1) i+=1 année[0]=dates2[0] x = np.array(dates2) année = np.unique(x) varrdv=StringVar(root) varrdv.set(année[0]) OptionRDV = OptionMenu(root,varrdv,*année) tkcalendar = TkinterCalendar() today=date.today() currentyear = int(today.strftime("%Y")) currentmonth =int(today.strftime("%m")) for year, month in [(currentyear,currentmonth)]: Label(root, text = '{} / {}'.format(year, month)).pack() frame = tkcalendar.formatmonth(root, year, month) frame.pack() rdvexistant=Label(root,text="Selectionner une année parmis les rdv existants") OptionRDV.pack() afficher=Button(root,text="Afficher",command=lambda : afficherdatechoisi(varrdv.get(),root)) afficher.pack() retour=Button(root,text="retour",command= lambda: deuxieme(root)) retour.pack() return root ####cette fonction permet de générer l'interface sur laquelle l'utilsateur pourra voir ses rendez-vous ###elle est par défaut positionné sur la date du jour def consulterrdvbis(root2,id): root2.destroy() i=0 j=1 k=2 root = Tk() center(root) root.title("Vos rendez-vous") rdvpre=selectrdvclient(id) print(rdvpre) dates=[None]*len(rdvpre) dates2=[None]*len(rdvpre) x=1 y=0 année=[None] mois=[None] while i < len(rdvpre): dates[i]=rdvpre[i][0] dates2[i]=datetime(rdvpre[i][0].year,rdvpre[i][0].month,1) i+=1 try: année[0]=dates2[0] except: print("Vous n'avez pas de rendez vous") good("Vous n'avez pas de rendez-vous") deuxiemebis(root,id) x = np.array(dates2) année = np.unique(x) varrdv=StringVar(root) varrdv.set(année[0]) OptionRDV = OptionMenu(root,varrdv,*année) tkcalendar = TkinterCalendar() today=date.today() currentyear = int(today.strftime("%Y")) currentmonth =int(today.strftime("%m")) for year, month in [(currentyear,currentmonth)]: Label(root, text = '{} / {}'.format(year, month)).pack() frame = tkcalendar.formatmonth(root, year, month) frame.pack() rdvexistant=Label(root,text="Selectionner une année parmis les rdv existants") OptionRDV.pack() afficher=Button(root,text="Afficher",command=lambda : afficherdatechoisibis(varrdv.get(),root,id)) afficher.pack() retour=Button(root,text="retour",command= lambda: deuxiemebis(root,id)) retour.pack() return root #######permet de select une table en fonction de l'id pour nous donner def selectrdvclient(id): idstr=str(id) mycursor = mydb.cursor() mycursor.execute("SELECT A1.date Date, A1.heuredebut Debut, A1.heurefin Fin, A1.commentaires Commentaires, A1.anxiete Anxiete, A1.mode Mode FROM consultation A1, consult_patient WHERE consult_patient.id_user ="+ idstr +" AND consult_patient.id_consult = A1.id_consult") myresult = mycursor.fetchall() return myresult def afficherdatechoisi(date,rootr): rootr.destroy() date =datetime.strptime(date,'%Y-%m-%d %H:%M:%S') extractyear=date.year extractmonth=date.month root = Tk() center(root) rdvpre=gettable("vue_psy") dates=[None]*len(rdvpre) dates2=[None]*len(rdvpre) x=1 i=0 y=0 année=[None] mois=[None] while i < len(rdvpre): dates[i]=rdvpre[i][0] dates2[i]=datetime(rdvpre[i][0].year,rdvpre[i][0].month,1) i+=1 année[0]=dates2[0] x = np.array(dates2) année = np.unique(x) varrdv=StringVar(root) varrdv.set(année[0]) OptionRDV = OptionMenu(root,varrdv,*année) tkcalendar = TkinterCalendar() today=date.today() currentyear = int(today.strftime("%Y")) currentmonth =int(today.strftime("%m")) Label(root, text = '{} / {}'.format(extractyear, extractmonth)).pack() frame = tkcalendar.formatmonth(root, extractyear, extractmonth) frame.pack() rdvexistant=Label(root,text="Selectionner une année parmis les rdv existants") OptionRDV.pack() afficher=Button(root,text="Afficher",command=lambda : afficherdatechoisi(varrdv.get(),root)) afficher.pack() retour=Button(root,text="Retour",command=lambda:deuxieme(root)) retour.pack() return root def afficherdatechoisibis(date,rootr,id): rootr.destroy() date =datetime.strptime(date,'%Y-%m-%d %H:%M:%S') extractyear=date.year extractmonth=date.month root = Tk() root.title("Vos rendez-vous") center(root) rdvpre=selectrdvclient(id) dates=[None]*len(rdvpre) dates2=[None]*len(rdvpre) x=1 i=0 y=0 année=[None] mois=[None] while i < len(rdvpre): dates[i]=rdvpre[i][0] dates2[i]=datetime(rdvpre[i][0].year,rdvpre[i][0].month,1) i+=1 année[0]=dates2[0] x = np.array(dates2) année = np.unique(x) varrdv=StringVar(root) varrdv.set(année[0]) OptionRDV = OptionMenu(root,varrdv,*année) tkcalendar = TkinterCalendar() today=date.today() currentyear = int(today.strftime("%Y")) currentmonth =int(today.strftime("%m")) Label(root, text = '{} / {}'.format(extractyear, extractmonth)).pack() frame = tkcalendar.formatmonth(root, extractyear, extractmonth) frame.pack() rdvexistant=Label(root,text="Selectionner une année parmis les rdv existants") OptionRDV.pack() afficher=Button(root,text="Afficher",command=lambda : afficherdatechoisi(varrdv.get(),root)) afficher.pack() retour=Button(root,text="Retour",command=lambda:deuxiemebis(root,id)) retour.pack() return root def deuxiemebis(root3,id): #### on rajoute ID pour pouvoir reconnaitre le client a la connexion print(id) deco(root3) root2 = Tk() center(root2) root2.title("Menu") lab1 = Label(root2, text="----------------connexion établie-----------------") lab2 =Label(root2, text="Que voulez-vous faire ?") calendrier = Button(root2,text="Consulter les rendez-vous",command=lambda: consulterrdvbis(root2,id)) button3=Button(root2, text="Déconnexion", command = lambda : confirmer(root2)) lab1.grid(column=0, row=0) lab2.grid(column=0,row=1) calendrier.grid(column=0,row=3) button3.grid(column=0,row=6) return root2 ####menu pour le psy def deuxieme(root3): deco(root3) root2 = Tk() center(root2) root2.title("Menu") lab1 = Label(root2, text="----------------connexion établie-----------------") lab2 =Label(root2, text="Que voulez-vous faire ?") button1 =Button(root2, text="Organiser un rdv",command = lambda : inputrdv(root2)) calendrier = Button(root2,text="Consulter les rendez-vous",command=lambda: consulterrdv(root2)) button2 =Button(root2, text="Informations Clients", command = lambda: infoclients(root2)) inscrip= Button(root2,text='Inscription de clients ',command = lambda : inscription(root2)) button3=Button(root2, text="Déconnexion", command = lambda : confirmer(root2)) lab1.grid(column=0, row=0) lab2.grid(column=0,row=1) button1.grid(column=0,row=2) calendrier.grid(column=0,row=3) button2.grid(column=0,row=4) inscrip.grid(column=0,row=5) button3.grid(column=0,row=6) return root2 ######Nous donne les option pour les menu OptionMenu dans le code class option(): ###Cette classe nous permet de créer les option pour L'option menu et ainsi de pouvoir input les rdv OPTIONannée=[None]*4 OPTIONmois=[None]*12 OPTIONjour=[None]*32 OPTIONheure=[None]*24 i=0 j=0 k=0 l=0 l1=8.0 today=date.today() currentyear = int(today.strftime("%Y")) currentmonth=int(today.strftime("%m")) currentday=int(today.strftime("%d")) while i <3 : OPTIONannée[i]=currentyear currentyear=currentyear+1 i+=1 while j <12 : OPTIONmois[j]=j+1 j+=1 while k<31: OPTIONjour[k]=k+1 k+=1 while l1<20: OPTIONheure[l]=l1 l+=1 l1+=0.5 def toStringheure(self, OPTIONheure): #CELA CONVERTIT POUR L'UTILISATEUR LES HEURE EN FORMAT DOUBLE ----> EN FORMAT LISIBLE OPTIONheurestring=[None]*24 p=0 print(OPTIONheure) print(OPTIONheure[0]) while p<24: print (OPTIONheure[p]-float(int(OPTIONheure[p]))) if OPTIONheure[p]-float(int(OPTIONheure[p]))==0.5: OPTIONheurestring[p]=str(int(OPTIONheure[p]))+"h30" p+=1 else : OPTIONheurestring[p]=str(int(OPTIONheure[p]))+"h" p+=1 return OPTIONheurestring def selectname(id,name,name2,group,table): ###SELECT select pour affiche les utilisiteur et group by ce que l'on input mycursor = mydb.cursor() mycursor.execute("SELECT "+id+", "+name+", "+name2 + " FROM " + table +" GROUP BY "+ group ) myresult = mycursor.fetchall() lenght=len(myresult) for x in myresult: print(x) return myresult def sortdv (): ###On va ranger dans un tableau l'ordre des consultation mycursor = mydb.cursor() mycursor.execute("SELECT id_consult FROM consultation ") myresult = mycursor.fetchall() dernier=myresult[-1][0] return dernier def inscription(root): deco(root) root=Tk() center(root) root.title("Inscription") nomlabel=Label(root,text="Nom") nom=Entry(root,text="Nom") nomlabel.pack(side='top') nom.pack(side='top') prenomlabel=Label(root,text="Prenom") prenom=Entry(root,text="Prenom") prenomlabel.pack(side='top') prenom.pack(side='top') agelabel=Label(root,text="Age") age=Entry(root,text="Age") agelabel.pack(side='top') age.pack(side='top') emaillabel=Label(root,text="Email") email=Entry(root,text="Email") emaillabel.pack(side='top') email.pack(side='top') couplelabel=Label(root,text="Êtes vous en couple avec l'un de nos clients?") couple=Entry(root,text="Couple") couplelabel.pack(side='top') couple.pack(side='top') passwordlabel=Label(root,text="Veuilliez choisir un mot de passe") password=Entry(root,show="*") passwordlabel.pack(side='top') password.pack(side='top') password2label=Label(root,text="Veuilliez vérifier le mot de passe") password2=Entry(root,show="*") password2label.pack(side='top') password2.pack(side='top') connulabel=Label(root,text="Comment avez-vous connu ce cabinet?") connu=Entry(root,text="Moyen") connulabel.pack(side='top') connu.pack(side='top') vals = ['1', '2','3'] etiqs = ['Homme', 'Femme','Autre'] varGr = StringVar() varGr.set(vals[1]) for i in range(3): b = Radiobutton(root, variable=varGr, text=etiqs[i], value=vals[i]) b.pack(side='left', expand=1) retour=Button(root,text="Retour",command=lambda : deuxieme(root)) retour.pack(side="bottom") valider=Button(root,text="Valider",command= lambda : inscrire(nom.get(),prenom.get(),email.get(),password.get(),password2.get(),couple.get(),age.get(),varGr.get(),connu.get())) valider.pack(side="bottom") ###Pour l'instant vous ne pouvez pas rajouter de couple, il nous faut aller chercher les valeurs des utilisateurs existants, pour permettre au psy de rentrer le couple def getsexe(var): print(var.get()) def inscrire(nom,prenom,email,password,passwordmatch,couple,age,hf,connu): ###A finir, pour l'instant on ne peut rajouter de couple if couple=="": couple="NULL" if password == passwordmatch: mycursor=mydb.cursor() sql = "INSERT INTO psychologue.user (id_user, nom, prenom, email, password, couple, age, sexe,connu) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)" val = ("NULL",nom , prenom , email ,password,None,age,hf,connu) mycursor.execute(sql,val) mydb.commit() good("Le client a bien été ajouté") if password != passwordmatch: root=Tk() center(root) root.title("Le mot de passe ne correspond pas") label=Label(root,text="Attention le mot de passe ne correspond pas") Recommencer = Button(root,text="Ok",command=lambda : root.destroy()) label.pack() Recommencer.pack() def good(string): root=Tk() center(root) root.title(string) label=Label(root,text=string) button=Button(root,text="Retour",command= lambda : root.destroy()) label.pack() button.pack() def inputrdv(root): OPTION = option() x=int(OPTION.currentyear)-1 y=int(OPTION.currentmonth)-1 z=int(OPTION.currentday)-1 HstringOption=OPTION.toStringheure(OPTION.OPTIONheure) CLIENTS = selectname("id_user","nom","prenom","id_user","user") CLIENTS.append(None) deco(root) root4=Tk() center(root4) root4.geometry("350x300") labelNA=Label(root4,text="VEUILLIEZ ENTREZ LES INFORMATION DU CLIENT") ###LABELS labelClient=Label(root4,text="Clients") labelDaterdv=Label(root4,text="Date") varclients=StringVar(root4) varclients.set(CLIENTS[len(CLIENTS)-1]) varclients2=StringVar(root4) varclients2.set(CLIENTS[len(CLIENTS)-1]) varclients3=StringVar(root4) varclients3.set(CLIENTS[len(CLIENTS)-1]) variableyear=IntVar(root4) variableyear.set(OPTION.OPTIONannée[0]) variablemonth =IntVar(root4) variablemonth.set(OPTION.OPTIONmois[y]) variableday = IntVar(root4) variableday.set(OPTION.OPTIONjour[z]) variablehour=StringVar(root4) variablehournotstring=DoubleVar(root4) variablehournotstring.set(OPTION.OPTIONheure[0]) variablehour.set(HstringOption[0]) Optionpersonne = OptionMenu(root4,varclients,*CLIENTS) Optionpersonne2 = OptionMenu(root4,varclients2,*CLIENTS) Optionpersonne3 = OptionMenu(root4,varclients3,*CLIENTS) Optionyear = OptionMenu(root4,variableyear,*OPTION.OPTIONannée) Optionmois = OptionMenu(root4,variablemonth,*OPTION.OPTIONmois) Optionjour = OptionMenu(root4,variableday,*OPTION.OPTIONjour) OptionHeure = OptionMenu(root4,variablehour,*HstringOption) labelNA.pack(side=TOP) labelClient.pack(side=TOP) Optionpersonne.pack(padx=5,pady=5) Optionpersonne.config(width=20) Optionpersonne2.pack(padx=5,pady=7) Optionpersonne2.config(width=20) Optionpersonne3.pack(padx=5,pady=6) Optionpersonne3.config(width=20) labelDaterdv.pack(padx=5,pady=6) Optionyear.pack(padx=0,pady=7 ,side=LEFT) Optionmois.pack(padx=0, pady=7 ,side=LEFT) Optionjour.pack(padx=0,pady=7,side=LEFT) OptionHeure.pack(padx=0,pady=7,side=LEFT) retour=Button(root4,text="Retour",command=lambda : deuxieme(root4)) retour.pack(side="bottom") Valider= Button(root4,text="Valider/Vérifier", command= lambda : checkvalid(varclients.get(),varclients2.get(),varclients3.get(),variableyear.get(),variableday.get(),variablemonth.get(),variablehour.get())) Valider.pack(padx=5,pady=9,side=BOTTOM) return root4 def checkvalid(clientid,clientid2,clientid3,année,jour,mois,heure): client=clientid[1] if clientid2!="None": client2=re.sub("[^0-9]","",clientid2) if clientid3!="None": client3=re.sub("[^0-9]","",clientid3) heure = heure.split("h") heureadd = heure if heure[1] != '': heureadd=int(heure[0])*100+100 heure=int(heure[0])*100+int(heure[1]) else : heureadd=int(heure[0])*100+30 heure=int(heure[0])*100 today=date.today() currentyear = int(today.strftime("%Y")) currentmonth=int(today.strftime("%m")) currentday=int(today.strftime("%d")) currenthour=int(today.strftime("%H")) currentminutes=int(today.strftime("%M"))/60 x=1 if année==currentyear: if mois<currentmonth: print("Mois pas bon") x=0 if jour<currentday and mois<=currentmonth: print("le jour n'est pas valide") x=0 if x==1: mycursor = mydb.cursor() sql = "INSERT INTO consultation (id_consult, date, heuredebut, heurefin, prix, mode, anxiete, commentaires) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)" val = (None, str(année)+"-"+str(mois)+"-"+str(jour) , heure , heureadd ,100,""," "," ") mycursor.execute(sql,val) mydb.commit() id_consult=sortdv() sql2="INSERT INTO consult_patient (id_user, id_consult) VALUES (%s,%s)" ####On insert dans consult_patient les id qui nous importent val2 = (str(client),str(id_consult)) mycursor.execute(sql2,val2) mydb.commit() good("Le rendez vous a été ajouté") if clientid2 !="None": sql3="INSERT INTO consult_patient (id_user, id_consult) VALUES (%s,%s)" val3 = (str(client2),str(id_consult)) try: mycursor.execute(sql3,val3) mydb.commit() except: error("Vous avez rentré le client "+client2+" plusieurs fois") if clientid3 !="None": sql4="INSERT INTO consult_patient (id_user, id_consult) VALUES (%s,%s)" val4 = (str(client3),str(id_consult)) try: mycursor.execute(sql4,val4) mydb.commit() except: error("Vous avez rentré le client "+client3+" plusieurs fois") ##mycursor.execute("INSERT INTO `psychologue`.`consultation` (`id_consult`, `date`, `heuredebut`, `heurefin`, `prix`, `mode`, `anxiete`, `commentaires`) VALUES (NULL," +str(année)+"-"+str(mois)+"-"+str(jour)+" , " + str(heure)+ " , " +str(heureadd)+ " , " +"''"+","+"''" +","+ "' '" +","+"' ' );") print("Insert is successful") def error(string): error=Tk() center(error) error.title("Erreur") errorlabel=Label(error,text=string) errorbutton=Button(error,text="Ok",command= lambda : error.destroy()) errorlabel.pack() errorbutton.pack() def infoclients(root2): deco(root2) root3 = Tk() center(root3) Id=Label(root3,text="Id") Nom=Label(root3, text="Nom") PreNom=Label(root3, text="Prenom") Mail=Label(root3, text="Mail") textId=Text(root3,width=20,height=15) textPrenom=Text(root3,width=20,height=15) textNom=Text(root3,width=20,height=15) textMail=Text(root3,width=20,height=15) liste=printable("user") Retour=Button(root3,text="Retour",command= lambda: deuxieme(root3)) for x in liste: textId.insert(END,str(x[0])+'\n') textPrenom.insert(END,str(x[1])+'\n') textNom.insert(END,str(x[2])+'\n') textMail.insert(END,str(x[3])+'\n') lab1 = Label(root3, text="----------------Vos clients-----------------") ##lab2 = Label(root3, text=table) lab1.grid(column=0, row=0) Id.grid(column=0,row=1) textId.grid(column=0, row=2) PreNom.grid(column=1,row=1) textPrenom.grid(column=1, row=2) Nom.grid(column=2, row=1) textNom.grid(column=2, row=2) Mail.grid(column=3,row=1) textMail.grid(column=3, row=2) Retour.grid(column=5, row=5) ##lab2.grid(column=0, row=1) return root3 def center(root): # Gets the requested values of the height and widht. windowWidth = root.winfo_reqwidth() windowHeight = root.winfo_reqheight() # Gets both half the screen width/height and window width/height positionRight = int(root.winfo_screenwidth()/2 - windowWidth/2) positionDown = int(root.winfo_screenheight()/2 - windowHeight/2) # Positions the window in the center of the page. root.geometry("+{}+{}".format(positionRight, positionDown)) def menu(): root = premiere() root.mainloop() if __name__ == "__main__": root = premiere(None) root.mainloop()
2a8a2fea5ef6b27e5ad95edd93fb19dddb4b601a
f445450ac693b466ca20b42f1ac82071d32dd991
/generated_tempdir_2019_09_15_163300/generated_part005222.py
554f9ec93f4279524a546fb6081ae0f1d20c7b74
[]
no_license
Upabjojr/rubi_generated
76e43cbafe70b4e1516fb761cabd9e5257691374
cd35e9e51722b04fb159ada3d5811d62a423e429
refs/heads/master
2020-07-25T17:26:19.227918
2019-09-15T15:41:48
2019-09-15T15:41:48
208,357,412
4
1
null
null
null
null
UTF-8
Python
false
false
4,004
py
from sympy.abc import * from matchpy.matching.many_to_one import CommutativeMatcher from matchpy import * from matchpy.utils import VariableWithCount from collections import deque from multiset import Multiset from sympy.integrals.rubi.constraints import * from sympy.integrals.rubi.utility_function import * from sympy.integrals.rubi.rules.miscellaneous_integration import * from sympy import * class CommutativeMatcher68381(CommutativeMatcher): _instance = None patterns = { 0: (0, Multiset({0: 1}), [ (VariableWithCount('i2.2.1.2.2.0', 1, 1, S(0)), Add) ]), 1: (1, Multiset({1: 1}), [ (VariableWithCount('i2.4.0', 1, 1, S(0)), Add) ]) } subjects = {} subjects_by_id = {} bipartite = BipartiteGraph() associative = Add max_optional_count = 1 anonymous_patterns = set() def __init__(self): self.add_subject(None) @staticmethod def get(): if CommutativeMatcher68381._instance is None: CommutativeMatcher68381._instance = CommutativeMatcher68381() return CommutativeMatcher68381._instance @staticmethod def get_match_iter(subject): subjects = deque([subject]) if subject is not None else deque() subst0 = Substitution() # State 68380 subst1 = Substitution(subst0) try: subst1.try_add_variable('i2.2.1.2.2.1.0_1', S(1)) except ValueError: pass else: pass # State 68382 if len(subjects) >= 1: tmp2 = subjects.popleft() subst2 = Substitution(subst1) try: subst2.try_add_variable('i2.2.1.2.2.1.0', tmp2) except ValueError: pass else: pass # State 68383 if len(subjects) == 0: pass # 0: x*d yield 0, subst2 subjects.appendleft(tmp2) subst1 = Substitution(subst0) try: subst1.try_add_variable('i2.4.1.0_1', S(1)) except ValueError: pass else: pass # State 68600 if len(subjects) >= 1: tmp5 = subjects.popleft() subst2 = Substitution(subst1) try: subst2.try_add_variable('i2.4.1.0', tmp5) except ValueError: pass else: pass # State 68601 if len(subjects) == 0: pass # 1: x*f yield 1, subst2 subjects.appendleft(tmp5) if len(subjects) >= 1 and isinstance(subjects[0], Mul): tmp7 = subjects.popleft() associative1 = tmp7 associative_type1 = type(tmp7) subjects8 = deque(tmp7._args) matcher = CommutativeMatcher68385.get() tmp9 = subjects8 subjects8 = [] for s in tmp9: matcher.add_subject(s) for pattern_index, subst1 in matcher.match(tmp9, subst0): pass if pattern_index == 0: pass # State 68386 if len(subjects) == 0: pass # 0: x*d yield 0, subst1 if pattern_index == 1: pass # State 68602 if len(subjects) == 0: pass # 1: x*f yield 1, subst1 subjects.appendleft(tmp7) return yield from .generated_part005223 import * from matchpy.matching.many_to_one import CommutativeMatcher from collections import deque from matchpy.utils import VariableWithCount from multiset import Multiset
e11ebbf2f6b0f930bc6b9d4fbea99d7fa00e2abc
87b4f84d9642994626aba66ec4dafdb1799c5f52
/Console/consoleControler.py
c9401cfd13e30d499975bc1a380618c7d93e6963
[]
no_license
leopaixaoneto/LeagueOfLegendsAutoBot
5de4ef7f4c2ce058889557ad55f9bbba7eefe480
bc6643752b0435cf35b52a14681619fe900e1f0d
refs/heads/master
2023-08-24T15:18:19.696487
2021-10-22T22:41:16
2021-10-22T22:41:16
420,259,140
1
0
null
null
null
null
UTF-8
Python
false
false
2,514
py
import pyfiglet import datetime from clint.arguments import Args from clint.textui import puts, colored, indent from Console.infoLine import InfoLine import os import ctypes class ConsoleControler: BOLD = '\033[1m' ENDC = '\033[0m' version = "" infoVector = [] botTitle = " RodolBot" MaxLinesPerPanel = 19 INFO = 0 ERROR = 1 CAUTION = 2 GOOD = 3 def __init__(self, version): self.version = version self.setWindowTitle(f"Rodolbot ({version})") def printTitle(self): Title = pyfiglet.figlet_format(self.botTitle) print(Title) def printVersion(self): puts(colored.cyan( f' {self.BOLD}version: [{self.version}]{self.ENDC}')) print() def printInfo(self): for info in self.infoVector: colorfunc = None if info.colorType == self.INFO: puts(colored.cyan( f' {self.BOLD}[{info.Time}]: {self.ENDC}') + colored.white(info.Text)) if info.colorType == self.ERROR: puts(colored.cyan( f' {self.BOLD}[{info.Time}]: {self.ENDC}') + colored.red(info.Text)) if info.colorType == self.CAUTION: puts(colored.cyan( f' {self.BOLD}[{info.Time}]: {self.ENDC}') + colored.yellow(info.Text)) if info.colorType == self.GOOD: puts(colored.cyan( f' {self.BOLD}[{info.Time}]: {self.ENDC}') + colored.green(info.Text)) print() def printPanel(self): os.system('cls') self.printTitle() self.printVersion() self.printInfo() pass def addInfo(self, info, colorType): newInfo = InfoLine(info, self.getActualHour(), colorType) self.infoVector.insert(len(self.infoVector), newInfo) if len(self.infoVector) > self.MaxLinesPerPanel: self.infoVector.pop(0) # print() def printInConsole(self, info, type): color = self.INFO if(type == "INFO"): color = self.INFO if(type == "ERROR"): color = self.ERROR if(type == "GOOD"): color = self.GOOD self.addInfo(info, color) self.printPanel() def getActualHour(self): return datetime.datetime.now().strftime("%H:%M:%S") def setWindowTitle(self, title): ctypes.windll.kernel32.SetConsoleTitleW(title)
4bf7b0860054cb16f805325b58829ae3231735aa
5a8bc4219384d11645f96baf54c7d50e65962ca3
/main.py
e641694713e55e86b92f475468127839727ec541
[]
no_license
ajaydev17/Ping-Pong
d21b1076b2c302a81e70fb9a53f5bd99fc8491cd
ec143c121f64c082e28d3d89515f457505febf9e
refs/heads/main
2023-03-26T14:12:05.539624
2021-03-16T19:16:36
2021-03-16T19:16:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,034
py
from turtle import Screen from paddle import Paddle from ball import Ball from scoreboard import Scoreboard import time screen = Screen() screen.title("Ping Pong") screen.bgcolor("black") screen.setup(width=800, height=600) screen.tracer(0) right_paddle = Paddle(350, 0) left_paddle = Paddle(-350, 0) ball = Ball() score = Scoreboard() screen.listen() screen.onkey(right_paddle.go_up, "Up") screen.onkey(right_paddle.go_down, "Down") screen.onkey(left_paddle.go_up, "w") screen.onkey(left_paddle.go_down, "s") is_game_on = True while is_game_on: time.sleep(0.1) screen.update() ball.move_ball() if ball.ycor() > 280 or ball.ycor() < -280: ball.bounce_ball_y() if ball.distance(right_paddle) < 50 and ball.xcor() > 320 or ball.distance(left_paddle) < 50 and ball.xcor() < -320: ball.bounce_ball_x() if ball.xcor() > 380: ball.reset_position() score.l_point() if ball.xcor() < -380: ball.reset_position() score.r_point() screen.exitonclick()
4315721aacce6974be0f706628bdf91f2a2ca8ae
0e1bcbc109e028849b3767c71a4fed4508488c33
/youtube/migrations/0021_auto_20210121_1958.py
0e8d5e8e5e1355255169d181de24906484bd5fa7
[]
no_license
seunghyun1003/youtube
7dbc631d14556c15a767429caac45f7fc706c44c
59b88325693682a56f633bb68d7b4a78aaea0921
refs/heads/main
2023-03-24T03:39:04.300111
2021-03-24T06:48:32
2021-03-24T06:48:32
328,170,795
0
0
null
null
null
null
UTF-8
Python
false
false
552
py
# Generated by Django 3.1.5 on 2021-01-21 10:58 from django.db import migrations import private_storage.fields import private_storage.storage.files class Migration(migrations.Migration): dependencies = [ ('youtube', '0020_auto_20210121_1949'), ] operations = [ migrations.AlterField( model_name='video', name='file', field=private_storage.fields.PrivateFileField(storage=private_storage.storage.files.PrivateFileSystemStorage(), upload_to='', verbose_name='video'), ), ]
64d38f74718207d2ab1c1007df15e6ad86065323
c89baaaad3ed687439449ac31ff73f36e94aaa24
/exercises and examples/ch8_dicts/examples/nonzero_dinucleotide_dict.py
c2b49234a32f7356ad92a2facaa82ec531212a16
[]
no_license
MovmntR/PythonForBiologists
1b34d8e9e45d9a225acbbe7071f28f416eedf102
28c727ef5500927d974c8caf1671aef958eaf7e3
refs/heads/master
2023-02-07T12:02:26.102268
2020-12-30T13:19:21
2020-12-30T13:19:21
321,356,258
1
0
null
null
null
null
UTF-8
Python
false
false
339
py
dna = "AATGATGAACGAC" dinucleotides = ['AA','AT','AG','AC', 'TA','TT','TG','TC', 'GA','GT','GG','GC', 'CA','CT','CG','CT'] all_counts = {} for dinucleotide in dinucleotides: count = dna.count(dinucleotide) if count > 0: all_counts[dinucleotide] = count print(all_counts)
86f7502496929d1b837e4f7b9179086b9df7597c
2de9871c2bfdb181fa58fd2ac92774747b554cac
/trainmodel.py
47288396a26ea62dedb0c556bb061be7c4d54e85
[]
no_license
Evangelio99/PubBaybayinConvrtr75
816eb84d2d9e982527d027b4a5cdd23b62df2390
c6e171d1501c911c622ccc90b83f92b90085ede4
refs/heads/master
2023-06-15T05:21:59.900783
2021-07-02T07:46:14
2021-07-02T07:46:14
384,072,408
0
0
null
null
null
null
UTF-8
Python
false
false
3,567
py
#contains all of the methods used, from creating the ML model and the functions for image processing of input from PIL import Image import cv2 import os import numpy as np import pandas as pd import matplotlib.pyplot as plt import tensorflow as tf import tensorflow.keras as tfk from sklearn.preprocessing import OneHotEncoder from sklearn.model_selection import train_test_split input_shape = (64,64) syllables = ["a", "ba", "dara", "ei", "ga", "ha", "ka", "kuw", "la", "ma", "na", "nga", "ou", "pa", "sa", "ta", "tul", "wa", "ya"] syllable_encoding = {} #assigning the syllables to integers for i in range(len(syllables)): syllable_encoding[syllables[i]] = i print(syllable_encoding) #encoding the label def encode_label(label): return syllable_encoding[label] #decoding the label def decode_label(i): return syllables[i] #extracting pixels function def extract_pixels(filename): image_pil = Image.open(filename) image_np = np.asarray(image_pil) image_res = cv2.resize(image_np, dsize=input_shape, interpolation=cv2.INTER_CUBIC) if len(image_res.shape) == 3: image_res = cv2.cvtColor(image_res, cv2.COLOR_BGR2GRAY) return image_res / 255.0 #loading all images from dataset and extracting their pixels def load_all_images(directory): X_raw = [] Y_raw = [] for syllable in syllables: for filename in os.listdir(directory + '/' + syllable + '/'): image_matrix = extract_pixels(directory + '/' + syllable + '/' + filename) label_encoding = encode_label(syllable) X_raw.append(image_matrix) Y_raw.append(label_encoding) return X_raw, Y_raw #assigning the image matrix and their respective label encoding in a list X_raw, Y_raw = load_all_images(directory='Baybayin-Handwritten-Character-Dataset/raw') #visualization of data def display_image(image): plt.figure() plt.imshow(image, cmap=plt.cm.binary) plt.grid(False) plt.show() #preprocessing of data X_data = np.asarray(X_raw) Y_data = np.asarray(Y_raw).reshape((-1,1)) #one hot encoding def one_hot_encoding(data): return OneHotEncoder().fit_transform(data).toarray() Y_data = one_hot_encoding(Y_data) print(Y_data.shape) #argmax def argmax(probability_logits): return np.argmax(probability_logits) #splitting the dataset into training set and test set X_train, X_test, Y_train, Y_test = train_test_split(X_data, Y_data, test_size=0.20, random_state=0) #building the ML model model = tfk.Sequential([ tfk.layers.Flatten(input_shape = input_shape), tfk.layers.Dense(1024, activation='relu'), tfk.layers.Dense(256, activation='relu'), tfk.layers.Dense(64, activation='relu'), tfk.layers.Dense(19, activation='softmax'), ]) #compiling the ML model model.compile(optimizer='Adam', loss='categorical_crossentropy', metrics=['accuracy']) #training the model early_stopping = tfk.callbacks.EarlyStopping(monitor='val_loss', patience=5) history = model.fit(X_train, Y_train, epochs=100, validation_split=0.2, callbacks=[early_stopping]) #testing test_loss, test_acc = model.evaluate(X_test, Y_test, verbose=2) def neural_net_prediction(image): return model.predict(np.expand_dims(image, axis=0)) #predict function to use def predict(filename): return decode_label(argmax(neural_net_prediction(extract_pixels(filename)))) #saving the model that has the best accuracy model.save('baybayin.h5')
f20916f8c9c13c2a31dbcb18a07523b3185ae3d5
aca8fc8c2a2de84e94f120e9ca8b12d152bc7cfa
/tests/test_fields_email.py
b9787d20611a2eea1172b40efdcc788bb790da58
[]
no_license
habibutsu/yadm
de30b364edd40917b2b25457f76cec908f2ffd3d
b3b9f2fdd5987c718b9db600fd7881630bfef944
refs/heads/master
2022-12-14T22:14:57.190430
2019-03-20T15:52:13
2019-04-04T15:52:29
296,621,139
0
0
null
2020-09-18T12:55:49
2020-09-18T12:55:48
null
UTF-8
Python
false
false
417
py
import pytest from yadm.documents import Document from yadm.fields.email import EmailField, InvalidEmail class Doc(Document): e = EmailField() def test_ok(): doc = Doc() doc.e = '[email protected]' assert doc.e == '[email protected]' @pytest.mark.parametrize('bad_email', ['EmA.iL', 'E@mA@iL', 'EmAiL@']) def test_error(bad_email): doc = Doc() with pytest.raises(InvalidEmail): doc.e = bad_email
33fef298af439b6372958c4e1983f746e78a8c69
fceca4480813b9025ffaa9a6f0cebfc056e8dc3a
/market/graphcalcu.py
49810676a0a92b56f72e426e2e6f53852db51be7
[]
no_license
Abel-Moremi/Financial-Analytics-Botswana
c80997ad4833f3256d2879ce279f099aa95602e8
1a709c121e3ecea420a9c0f310e7ade9c427752f
refs/heads/master
2022-05-10T23:52:43.969357
2020-02-13T02:58:06
2020-02-13T02:58:06
176,990,916
0
0
null
null
null
null
UTF-8
Python
false
false
3,670
py
import market.resource as res import pandas as pd import json def barclays_df(): return data_to_df(pd.read_json(res.BarclaysDailyResource().export().json, dtype={ "date": str, "price": int})) def bihl_df(): return data_to_df(pd.read_json(res.BihlDailyResource().export().json, dtype={ "date": str, "price": int})) def choppies_df(): return data_to_df(pd.read_json(res.ChoppiesDailyResource().export().json, dtype={ "date": str, "price": int})) def data_to_df(data_pd): return pd.DataFrame(data_pd, columns=['date', 'price']) def stock_df(): return {'barclays': barclays_df(), 'bihl': bihl_df(), 'choppies': choppies_df(), } def single_graph_schema(graphname): schema = '[{"name": "date","type": "date","format": "%Y-%m-%d"},' \ ' {"name": "'+graphname+'","type": "number"}]' return json.loads(schema) def double_graph_schema(graphname01, graphname02): schema = '[' \ '{ "name": "date","type": "date","format": "%Y-%m-%d"}, ' \ '{"name": "'+graphname01+'","type": "number"}, ' \ '{"name": "'+graphname02+'","type": "number"}' \ ']' return json.loads(schema) def triple_graph_schema(graphname01, graphname02, graphname03): schema = '[' \ '{ "name": "date","type": "date","format": "%Y-%m-%d"}, ' \ '{"name": "'+graphname01+'","type": "number"}, ' \ '{"name": "'+graphname02+'","type": "number"},' \ '{"name": "'+graphname03+'","type": "number"}' \ ']' return json.loads(schema) def df_to_json(df): return df.to_json(orient='values') def single_graph(graphs, df): return [single_graph_schema(graphs[0]), df_to_json(df)] def double_graph(df_01, df_02, graphs): new_df = df_01.merge(df_02, left_on='date', right_on='date', how='outer') new_df.set_index('date') return [double_graph_schema(graphs[0], graphs[1]), df_to_json(new_df)] def triple_graph(df_01, df_02, df_03, graphs): double_df = df_02.merge(df_03, left_on='date', right_on='date', how='outer') double_df.set_index('date') triple_df = df_01.merge(double_df, left_on='date', right_on='date', how='outer') triple_df.set_index('date') return [triple_graph_schema(graphs[0], graphs[1], graphs[2]), df_to_json(triple_df)] def graph(selected_graphs, securities_index_selected): if len(selected_graphs) == 0: if len(securities_index_selected) > 0: temp_list = ['Index'] return single_graph(temp_list, index_df(securities_index_selected)) temp_list = ['barclays'] return single_graph(temp_list, stock_df()['barclays']) elif len(selected_graphs) == 2: return double_graph(stock_df()[selected_graphs[0]], stock_df()[selected_graphs[1]], selected_graphs) elif len(selected_graphs) == 3: return triple_graph(stock_df()[selected_graphs[0]], stock_df()[selected_graphs[1]], stock_df()[selected_graphs[2]], selected_graphs) return single_graph(selected_graphs, stock_df()[selected_graphs[0]]) # Index calculation def index_df(securities_index_selected): base_df = stock_df()[securities_index_selected[0]] for security in securities_index_selected: if security != securities_index_selected[0]: new_df = base_df.merge(stock_df()[security], left_on='date', right_on='date', how='outer') new_df.set_index('date') base_df = new_df base_df['index'] = base_df.mean(axis=1) base_df = base_df[['date', 'index']] # print(base_df.head()) return base_df
27b325ded01930a0aff78f6d3fb830b585851030
98ee0c5a481c37769ccf744ad1709569119507b1
/notes/forms.py
2ef34076979bb33b9eb8194ac6afe92d60267703
[]
no_license
hussainsajib/django_notebook_server
2b500040882041d312f381db2afef1e8817ad9f2
375edf5c752b7ed7b60e1a250ae41c7008fe635f
refs/heads/master
2023-08-07T20:57:56.901180
2020-08-19T05:28:36
2020-08-19T05:28:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
323
py
from django.forms import ModelForm, Textarea from .models import Note class NoteForm(ModelForm): class Meta: model = Note fields = ['title', 'category', 'sub_category', 'priority', 'body', ] widgets = { 'body': Textarea(attrs={'id': 'mytextarea', 'novalidate': 'true'}), }
a97f507d20a0aa26e54224831227833026e7eac6
b7fab13642988c0e6535fb75ef6cb3548671d338
/tools/ydk-py-master/cisco-ios-xr/ydk/models/cisco_ios_xr/openconfig_vlan.py
ef926795da3091805a43802d719560c409548218
[ "Apache-2.0" ]
permissive
juancsosap/yangtraining
6ad1b8cf89ecdebeef094e4238d1ee95f8eb0824
09d8bcc3827575a45cb8d5d27186042bf13ea451
refs/heads/master
2022-08-05T01:59:22.007845
2019-08-01T15:53:08
2019-08-01T15:53:08
200,079,665
0
1
null
2021-12-13T20:06:17
2019-08-01T15:54:15
Python
UTF-8
Python
false
false
41,152
py
""" openconfig_vlan This module defines configuration and state variables for VLANs, in addition to VLAN parameters associated with interfaces """ from ydk.entity_utils import get_relative_entity_path as _get_relative_entity_path from ydk.types import Entity, EntityPath, Identity, Enum, YType, YLeaf, YLeafList, YList, LeafDataList, Bits, Empty, Decimal64 from ydk.filters import YFilter from ydk.errors import YPYError, YPYModelError from ydk.errors.error_handler import handle_type_error as _handle_type_error class Vlans(Entity): """ Container for VLAN configuration and state variables .. attribute:: vlan Configured VLANs keyed by id **type**\: list of :py:class:`Vlan <ydk.models.openconfig.openconfig_vlan.Vlans.Vlan>` """ _prefix = 'oc-vlan' _revision = '2016-05-26' def __init__(self): super(Vlans, self).__init__() self._top_entity = None self.yang_name = "vlans" self.yang_parent_name = "openconfig-vlan" self.vlan = YList(self) def __setattr__(self, name, value): self._check_monkey_patching_error(name, value) with _handle_type_error(): if name in self.__dict__ and isinstance(self.__dict__[name], YList): raise YPYModelError("Attempt to assign value of '{}' to YList ldata. " "Please use list append or extend method." .format(value)) if isinstance(value, Enum.YLeaf): value = value.name if name in () and name in self.__dict__: if isinstance(value, YLeaf): self.__dict__[name].set(value.get()) elif isinstance(value, YLeafList): super(Vlans, self).__setattr__(name, value) else: self.__dict__[name].set(value) else: if hasattr(value, "parent") and name != "parent": if hasattr(value, "is_presence_container") and value.is_presence_container: value.parent = self elif value.parent is None and value.yang_name in self._children_yang_names: value.parent = self super(Vlans, self).__setattr__(name, value) class Vlan(Entity): """ Configured VLANs keyed by id .. attribute:: vlan_id <key> references the configured vlan\-id **type**\: int **range:** 1..4094 **refers to**\: :py:class:`vlan_id <ydk.models.openconfig.openconfig_vlan.Vlans.Vlan.Config>` .. attribute:: config Configuration parameters for VLANs **type**\: :py:class:`Config <ydk.models.openconfig.openconfig_vlan.Vlans.Vlan.Config>` .. attribute:: members Enclosing container for list of member interfaces **type**\: :py:class:`Members <ydk.models.openconfig.openconfig_vlan.Vlans.Vlan.Members>` .. attribute:: state State variables for VLANs **type**\: :py:class:`State <ydk.models.openconfig.openconfig_vlan.Vlans.Vlan.State>` """ _prefix = 'oc-vlan' _revision = '2016-05-26' def __init__(self): super(Vlans.Vlan, self).__init__() self.yang_name = "vlan" self.yang_parent_name = "vlans" self.vlan_id = YLeaf(YType.str, "vlan-id") self.config = Vlans.Vlan.Config() self.config.parent = self self._children_name_map["config"] = "config" self._children_yang_names.add("config") self.members = Vlans.Vlan.Members() self.members.parent = self self._children_name_map["members"] = "members" self._children_yang_names.add("members") self.state = Vlans.Vlan.State() self.state.parent = self self._children_name_map["state"] = "state" self._children_yang_names.add("state") def __setattr__(self, name, value): self._check_monkey_patching_error(name, value) with _handle_type_error(): if name in self.__dict__ and isinstance(self.__dict__[name], YList): raise YPYModelError("Attempt to assign value of '{}' to YList ldata. " "Please use list append or extend method." .format(value)) if isinstance(value, Enum.YLeaf): value = value.name if name in ("vlan_id") and name in self.__dict__: if isinstance(value, YLeaf): self.__dict__[name].set(value.get()) elif isinstance(value, YLeafList): super(Vlans.Vlan, self).__setattr__(name, value) else: self.__dict__[name].set(value) else: if hasattr(value, "parent") and name != "parent": if hasattr(value, "is_presence_container") and value.is_presence_container: value.parent = self elif value.parent is None and value.yang_name in self._children_yang_names: value.parent = self super(Vlans.Vlan, self).__setattr__(name, value) class Config(Entity): """ Configuration parameters for VLANs .. attribute:: name Interface VLAN name **type**\: str .. attribute:: status Admin state of the VLAN **type**\: :py:class:`Status <ydk.models.openconfig.openconfig_vlan.Vlans.Vlan.Config.Status>` **default value**\: ACTIVE .. attribute:: tpid Optionally set the tag protocol identifier field (TPID) that is accepted on the VLAN **type**\: :py:class:`Tpid_Types <ydk.models.openconfig.openconfig_vlan_types.Tpid_Types>` **default value**\: oc-vlan-types:TPID_0x8100 .. attribute:: vlan_id Interface VLAN id **type**\: int **range:** 1..4094 """ _prefix = 'oc-vlan' _revision = '2016-05-26' def __init__(self): super(Vlans.Vlan.Config, self).__init__() self.yang_name = "config" self.yang_parent_name = "vlan" self.name = YLeaf(YType.str, "name") self.status = YLeaf(YType.enumeration, "status") self.tpid = YLeaf(YType.identityref, "tpid") self.vlan_id = YLeaf(YType.uint16, "vlan-id") def __setattr__(self, name, value): self._check_monkey_patching_error(name, value) with _handle_type_error(): if name in self.__dict__ and isinstance(self.__dict__[name], YList): raise YPYModelError("Attempt to assign value of '{}' to YList ldata. " "Please use list append or extend method." .format(value)) if isinstance(value, Enum.YLeaf): value = value.name if name in ("name", "status", "tpid", "vlan_id") and name in self.__dict__: if isinstance(value, YLeaf): self.__dict__[name].set(value.get()) elif isinstance(value, YLeafList): super(Vlans.Vlan.Config, self).__setattr__(name, value) else: self.__dict__[name].set(value) else: if hasattr(value, "parent") and name != "parent": if hasattr(value, "is_presence_container") and value.is_presence_container: value.parent = self elif value.parent is None and value.yang_name in self._children_yang_names: value.parent = self super(Vlans.Vlan.Config, self).__setattr__(name, value) class Status(Enum): """ Status Admin state of the VLAN .. data:: ACTIVE = 0 VLAN is active .. data:: SUSPENDED = 1 VLAN is inactive / suspended """ ACTIVE = Enum.YLeaf(0, "ACTIVE") SUSPENDED = Enum.YLeaf(1, "SUSPENDED") def has_data(self): return ( self.name.is_set or self.status.is_set or self.tpid.is_set or self.vlan_id.is_set) def has_operation(self): return ( self.yfilter != YFilter.not_set or self.name.yfilter != YFilter.not_set or self.status.yfilter != YFilter.not_set or self.tpid.yfilter != YFilter.not_set or self.vlan_id.yfilter != YFilter.not_set) def get_segment_path(self): path_buffer = "" path_buffer = "config" + path_buffer return path_buffer def get_entity_path(self, ancestor): path_buffer = "" if (ancestor is None): raise YPYModelError("ancestor cannot be None as one of the ancestors is a list") else: path_buffer = _get_relative_entity_path(self, ancestor, path_buffer) leaf_name_data = LeafDataList() if (self.name.is_set or self.name.yfilter != YFilter.not_set): leaf_name_data.append(self.name.get_name_leafdata()) if (self.status.is_set or self.status.yfilter != YFilter.not_set): leaf_name_data.append(self.status.get_name_leafdata()) if (self.tpid.is_set or self.tpid.yfilter != YFilter.not_set): leaf_name_data.append(self.tpid.get_name_leafdata()) if (self.vlan_id.is_set or self.vlan_id.yfilter != YFilter.not_set): leaf_name_data.append(self.vlan_id.get_name_leafdata()) entity_path = EntityPath(path_buffer, leaf_name_data) return entity_path def get_child_by_name(self, child_yang_name, segment_path): child = self._get_child_by_seg_name([child_yang_name, segment_path]) if child is not None: return child return None def has_leaf_or_child_of_name(self, name): if(name == "name" or name == "status" or name == "tpid" or name == "vlan-id"): return True return False def set_value(self, value_path, value, name_space, name_space_prefix): if(value_path == "name"): self.name = value self.name.value_namespace = name_space self.name.value_namespace_prefix = name_space_prefix if(value_path == "status"): self.status = value self.status.value_namespace = name_space self.status.value_namespace_prefix = name_space_prefix if(value_path == "tpid"): self.tpid = value self.tpid.value_namespace = name_space self.tpid.value_namespace_prefix = name_space_prefix if(value_path == "vlan-id"): self.vlan_id = value self.vlan_id.value_namespace = name_space self.vlan_id.value_namespace_prefix = name_space_prefix class State(Entity): """ State variables for VLANs .. attribute:: name Interface VLAN name **type**\: str .. attribute:: status Admin state of the VLAN **type**\: :py:class:`Status <ydk.models.openconfig.openconfig_vlan.Vlans.Vlan.State.Status>` **default value**\: ACTIVE .. attribute:: tpid Optionally set the tag protocol identifier field (TPID) that is accepted on the VLAN **type**\: :py:class:`Tpid_Types <ydk.models.openconfig.openconfig_vlan_types.Tpid_Types>` **default value**\: oc-vlan-types:TPID_0x8100 .. attribute:: vlan_id Interface VLAN id **type**\: int **range:** 1..4094 """ _prefix = 'oc-vlan' _revision = '2016-05-26' def __init__(self): super(Vlans.Vlan.State, self).__init__() self.yang_name = "state" self.yang_parent_name = "vlan" self.name = YLeaf(YType.str, "name") self.status = YLeaf(YType.enumeration, "status") self.tpid = YLeaf(YType.identityref, "tpid") self.vlan_id = YLeaf(YType.uint16, "vlan-id") def __setattr__(self, name, value): self._check_monkey_patching_error(name, value) with _handle_type_error(): if name in self.__dict__ and isinstance(self.__dict__[name], YList): raise YPYModelError("Attempt to assign value of '{}' to YList ldata. " "Please use list append or extend method." .format(value)) if isinstance(value, Enum.YLeaf): value = value.name if name in ("name", "status", "tpid", "vlan_id") and name in self.__dict__: if isinstance(value, YLeaf): self.__dict__[name].set(value.get()) elif isinstance(value, YLeafList): super(Vlans.Vlan.State, self).__setattr__(name, value) else: self.__dict__[name].set(value) else: if hasattr(value, "parent") and name != "parent": if hasattr(value, "is_presence_container") and value.is_presence_container: value.parent = self elif value.parent is None and value.yang_name in self._children_yang_names: value.parent = self super(Vlans.Vlan.State, self).__setattr__(name, value) class Status(Enum): """ Status Admin state of the VLAN .. data:: ACTIVE = 0 VLAN is active .. data:: SUSPENDED = 1 VLAN is inactive / suspended """ ACTIVE = Enum.YLeaf(0, "ACTIVE") SUSPENDED = Enum.YLeaf(1, "SUSPENDED") def has_data(self): return ( self.name.is_set or self.status.is_set or self.tpid.is_set or self.vlan_id.is_set) def has_operation(self): return ( self.yfilter != YFilter.not_set or self.name.yfilter != YFilter.not_set or self.status.yfilter != YFilter.not_set or self.tpid.yfilter != YFilter.not_set or self.vlan_id.yfilter != YFilter.not_set) def get_segment_path(self): path_buffer = "" path_buffer = "state" + path_buffer return path_buffer def get_entity_path(self, ancestor): path_buffer = "" if (ancestor is None): raise YPYModelError("ancestor cannot be None as one of the ancestors is a list") else: path_buffer = _get_relative_entity_path(self, ancestor, path_buffer) leaf_name_data = LeafDataList() if (self.name.is_set or self.name.yfilter != YFilter.not_set): leaf_name_data.append(self.name.get_name_leafdata()) if (self.status.is_set or self.status.yfilter != YFilter.not_set): leaf_name_data.append(self.status.get_name_leafdata()) if (self.tpid.is_set or self.tpid.yfilter != YFilter.not_set): leaf_name_data.append(self.tpid.get_name_leafdata()) if (self.vlan_id.is_set or self.vlan_id.yfilter != YFilter.not_set): leaf_name_data.append(self.vlan_id.get_name_leafdata()) entity_path = EntityPath(path_buffer, leaf_name_data) return entity_path def get_child_by_name(self, child_yang_name, segment_path): child = self._get_child_by_seg_name([child_yang_name, segment_path]) if child is not None: return child return None def has_leaf_or_child_of_name(self, name): if(name == "name" or name == "status" or name == "tpid" or name == "vlan-id"): return True return False def set_value(self, value_path, value, name_space, name_space_prefix): if(value_path == "name"): self.name = value self.name.value_namespace = name_space self.name.value_namespace_prefix = name_space_prefix if(value_path == "status"): self.status = value self.status.value_namespace = name_space self.status.value_namespace_prefix = name_space_prefix if(value_path == "tpid"): self.tpid = value self.tpid.value_namespace = name_space self.tpid.value_namespace_prefix = name_space_prefix if(value_path == "vlan-id"): self.vlan_id = value self.vlan_id.value_namespace = name_space self.vlan_id.value_namespace_prefix = name_space_prefix class Members(Entity): """ Enclosing container for list of member interfaces .. attribute:: member List of references to interfaces / subinterfaces associated with the VLAN **type**\: list of :py:class:`Member <ydk.models.openconfig.openconfig_vlan.Vlans.Vlan.Members.Member>` """ _prefix = 'oc-vlan' _revision = '2016-05-26' def __init__(self): super(Vlans.Vlan.Members, self).__init__() self.yang_name = "members" self.yang_parent_name = "vlan" self.member = YList(self) def __setattr__(self, name, value): self._check_monkey_patching_error(name, value) with _handle_type_error(): if name in self.__dict__ and isinstance(self.__dict__[name], YList): raise YPYModelError("Attempt to assign value of '{}' to YList ldata. " "Please use list append or extend method." .format(value)) if isinstance(value, Enum.YLeaf): value = value.name if name in () and name in self.__dict__: if isinstance(value, YLeaf): self.__dict__[name].set(value.get()) elif isinstance(value, YLeafList): super(Vlans.Vlan.Members, self).__setattr__(name, value) else: self.__dict__[name].set(value) else: if hasattr(value, "parent") and name != "parent": if hasattr(value, "is_presence_container") and value.is_presence_container: value.parent = self elif value.parent is None and value.yang_name in self._children_yang_names: value.parent = self super(Vlans.Vlan.Members, self).__setattr__(name, value) class Member(Entity): """ List of references to interfaces / subinterfaces associated with the VLAN. .. attribute:: interface_ref Reference to an interface or subinterface **type**\: :py:class:`InterfaceRef <ydk.models.openconfig.openconfig_vlan.Vlans.Vlan.Members.Member.InterfaceRef>` """ _prefix = 'oc-vlan' _revision = '2016-05-26' def __init__(self): super(Vlans.Vlan.Members.Member, self).__init__() self.yang_name = "member" self.yang_parent_name = "members" self.interface_ref = Vlans.Vlan.Members.Member.InterfaceRef() self.interface_ref.parent = self self._children_name_map["interface_ref"] = "interface-ref" self._children_yang_names.add("interface-ref") class InterfaceRef(Entity): """ Reference to an interface or subinterface .. attribute:: state Operational state for interface\-ref **type**\: :py:class:`State <ydk.models.openconfig.openconfig_vlan.Vlans.Vlan.Members.Member.InterfaceRef.State>` """ _prefix = 'oc-vlan' _revision = '2016-05-26' def __init__(self): super(Vlans.Vlan.Members.Member.InterfaceRef, self).__init__() self.yang_name = "interface-ref" self.yang_parent_name = "member" self.state = Vlans.Vlan.Members.Member.InterfaceRef.State() self.state.parent = self self._children_name_map["state"] = "state" self._children_yang_names.add("state") class State(Entity): """ Operational state for interface\-ref .. attribute:: interface Reference to a base interface. If a reference to a subinterface is required, this leaf must be specified to indicate the base interface **type**\: str **refers to**\: :py:class:`name <ydk.models.openconfig.openconfig_interfaces.Interfaces.Interface>` .. attribute:: subinterface Reference to a subinterface \-\- this requires the base interface to be specified using the interface leaf in this container. If only a reference to a base interface is requuired, this leaf should not be set **type**\: int **range:** 0..4294967295 **refers to**\: :py:class:`index <ydk.models.openconfig.openconfig_interfaces.Interfaces.Interface.Subinterfaces.Subinterface>` """ _prefix = 'oc-vlan' _revision = '2016-05-26' def __init__(self): super(Vlans.Vlan.Members.Member.InterfaceRef.State, self).__init__() self.yang_name = "state" self.yang_parent_name = "interface-ref" self.interface = YLeaf(YType.str, "interface") self.subinterface = YLeaf(YType.str, "subinterface") def __setattr__(self, name, value): self._check_monkey_patching_error(name, value) with _handle_type_error(): if name in self.__dict__ and isinstance(self.__dict__[name], YList): raise YPYModelError("Attempt to assign value of '{}' to YList ldata. " "Please use list append or extend method." .format(value)) if isinstance(value, Enum.YLeaf): value = value.name if name in ("interface", "subinterface") and name in self.__dict__: if isinstance(value, YLeaf): self.__dict__[name].set(value.get()) elif isinstance(value, YLeafList): super(Vlans.Vlan.Members.Member.InterfaceRef.State, self).__setattr__(name, value) else: self.__dict__[name].set(value) else: if hasattr(value, "parent") and name != "parent": if hasattr(value, "is_presence_container") and value.is_presence_container: value.parent = self elif value.parent is None and value.yang_name in self._children_yang_names: value.parent = self super(Vlans.Vlan.Members.Member.InterfaceRef.State, self).__setattr__(name, value) def has_data(self): return ( self.interface.is_set or self.subinterface.is_set) def has_operation(self): return ( self.yfilter != YFilter.not_set or self.interface.yfilter != YFilter.not_set or self.subinterface.yfilter != YFilter.not_set) def get_segment_path(self): path_buffer = "" path_buffer = "state" + path_buffer return path_buffer def get_entity_path(self, ancestor): path_buffer = "" if (ancestor is None): raise YPYModelError("ancestor cannot be None as one of the ancestors is a list") else: path_buffer = _get_relative_entity_path(self, ancestor, path_buffer) leaf_name_data = LeafDataList() if (self.interface.is_set or self.interface.yfilter != YFilter.not_set): leaf_name_data.append(self.interface.get_name_leafdata()) if (self.subinterface.is_set or self.subinterface.yfilter != YFilter.not_set): leaf_name_data.append(self.subinterface.get_name_leafdata()) entity_path = EntityPath(path_buffer, leaf_name_data) return entity_path def get_child_by_name(self, child_yang_name, segment_path): child = self._get_child_by_seg_name([child_yang_name, segment_path]) if child is not None: return child return None def has_leaf_or_child_of_name(self, name): if(name == "interface" or name == "subinterface"): return True return False def set_value(self, value_path, value, name_space, name_space_prefix): if(value_path == "interface"): self.interface = value self.interface.value_namespace = name_space self.interface.value_namespace_prefix = name_space_prefix if(value_path == "subinterface"): self.subinterface = value self.subinterface.value_namespace = name_space self.subinterface.value_namespace_prefix = name_space_prefix def has_data(self): return (self.state is not None and self.state.has_data()) def has_operation(self): return ( self.yfilter != YFilter.not_set or (self.state is not None and self.state.has_operation())) def get_segment_path(self): path_buffer = "" path_buffer = "interface-ref" + path_buffer return path_buffer def get_entity_path(self, ancestor): path_buffer = "" if (ancestor is None): raise YPYModelError("ancestor cannot be None as one of the ancestors is a list") else: path_buffer = _get_relative_entity_path(self, ancestor, path_buffer) leaf_name_data = LeafDataList() entity_path = EntityPath(path_buffer, leaf_name_data) return entity_path def get_child_by_name(self, child_yang_name, segment_path): child = self._get_child_by_seg_name([child_yang_name, segment_path]) if child is not None: return child if (child_yang_name == "state"): if (self.state is None): self.state = Vlans.Vlan.Members.Member.InterfaceRef.State() self.state.parent = self self._children_name_map["state"] = "state" return self.state return None def has_leaf_or_child_of_name(self, name): if(name == "state"): return True return False def set_value(self, value_path, value, name_space, name_space_prefix): pass def has_data(self): return (self.interface_ref is not None and self.interface_ref.has_data()) def has_operation(self): return ( self.yfilter != YFilter.not_set or (self.interface_ref is not None and self.interface_ref.has_operation())) def get_segment_path(self): path_buffer = "" path_buffer = "member" + path_buffer return path_buffer def get_entity_path(self, ancestor): path_buffer = "" if (ancestor is None): raise YPYModelError("ancestor cannot be None as one of the ancestors is a list") else: path_buffer = _get_relative_entity_path(self, ancestor, path_buffer) leaf_name_data = LeafDataList() entity_path = EntityPath(path_buffer, leaf_name_data) return entity_path def get_child_by_name(self, child_yang_name, segment_path): child = self._get_child_by_seg_name([child_yang_name, segment_path]) if child is not None: return child if (child_yang_name == "interface-ref"): if (self.interface_ref is None): self.interface_ref = Vlans.Vlan.Members.Member.InterfaceRef() self.interface_ref.parent = self self._children_name_map["interface_ref"] = "interface-ref" return self.interface_ref return None def has_leaf_or_child_of_name(self, name): if(name == "interface-ref"): return True return False def set_value(self, value_path, value, name_space, name_space_prefix): pass def has_data(self): for c in self.member: if (c.has_data()): return True return False def has_operation(self): for c in self.member: if (c.has_operation()): return True return self.yfilter != YFilter.not_set def get_segment_path(self): path_buffer = "" path_buffer = "members" + path_buffer return path_buffer def get_entity_path(self, ancestor): path_buffer = "" if (ancestor is None): raise YPYModelError("ancestor cannot be None as one of the ancestors is a list") else: path_buffer = _get_relative_entity_path(self, ancestor, path_buffer) leaf_name_data = LeafDataList() entity_path = EntityPath(path_buffer, leaf_name_data) return entity_path def get_child_by_name(self, child_yang_name, segment_path): child = self._get_child_by_seg_name([child_yang_name, segment_path]) if child is not None: return child if (child_yang_name == "member"): for c in self.member: segment = c.get_segment_path() if (segment_path == segment): return c c = Vlans.Vlan.Members.Member() c.parent = self local_reference_key = "ydk::seg::%s" % segment_path self._local_refs[local_reference_key] = c self.member.append(c) return c return None def has_leaf_or_child_of_name(self, name): if(name == "member"): return True return False def set_value(self, value_path, value, name_space, name_space_prefix): pass def has_data(self): return ( self.vlan_id.is_set or (self.config is not None and self.config.has_data()) or (self.members is not None and self.members.has_data()) or (self.state is not None and self.state.has_data())) def has_operation(self): return ( self.yfilter != YFilter.not_set or self.vlan_id.yfilter != YFilter.not_set or (self.config is not None and self.config.has_operation()) or (self.members is not None and self.members.has_operation()) or (self.state is not None and self.state.has_operation())) def get_segment_path(self): path_buffer = "" path_buffer = "vlan" + "[vlan-id='" + self.vlan_id.get() + "']" + path_buffer return path_buffer def get_entity_path(self, ancestor): path_buffer = "" if (ancestor is None): path_buffer = "openconfig-vlan:vlans/%s" % self.get_segment_path() else: path_buffer = _get_relative_entity_path(self, ancestor, path_buffer) leaf_name_data = LeafDataList() if (self.vlan_id.is_set or self.vlan_id.yfilter != YFilter.not_set): leaf_name_data.append(self.vlan_id.get_name_leafdata()) entity_path = EntityPath(path_buffer, leaf_name_data) return entity_path def get_child_by_name(self, child_yang_name, segment_path): child = self._get_child_by_seg_name([child_yang_name, segment_path]) if child is not None: return child if (child_yang_name == "config"): if (self.config is None): self.config = Vlans.Vlan.Config() self.config.parent = self self._children_name_map["config"] = "config" return self.config if (child_yang_name == "members"): if (self.members is None): self.members = Vlans.Vlan.Members() self.members.parent = self self._children_name_map["members"] = "members" return self.members if (child_yang_name == "state"): if (self.state is None): self.state = Vlans.Vlan.State() self.state.parent = self self._children_name_map["state"] = "state" return self.state return None def has_leaf_or_child_of_name(self, name): if(name == "config" or name == "members" or name == "state" or name == "vlan-id"): return True return False def set_value(self, value_path, value, name_space, name_space_prefix): if(value_path == "vlan-id"): self.vlan_id = value self.vlan_id.value_namespace = name_space self.vlan_id.value_namespace_prefix = name_space_prefix def has_data(self): for c in self.vlan: if (c.has_data()): return True return False def has_operation(self): for c in self.vlan: if (c.has_operation()): return True return self.yfilter != YFilter.not_set def get_segment_path(self): path_buffer = "" path_buffer = "openconfig-vlan:vlans" + path_buffer return path_buffer def get_entity_path(self, ancestor): path_buffer = "" if (not ancestor is None): raise YPYModelError("ancestor has to be None for top-level node") path_buffer = self.get_segment_path() leaf_name_data = LeafDataList() entity_path = EntityPath(path_buffer, leaf_name_data) return entity_path def get_child_by_name(self, child_yang_name, segment_path): child = self._get_child_by_seg_name([child_yang_name, segment_path]) if child is not None: return child if (child_yang_name == "vlan"): for c in self.vlan: segment = c.get_segment_path() if (segment_path == segment): return c c = Vlans.Vlan() c.parent = self local_reference_key = "ydk::seg::%s" % segment_path self._local_refs[local_reference_key] = c self.vlan.append(c) return c return None def has_leaf_or_child_of_name(self, name): if(name == "vlan"): return True return False def set_value(self, value_path, value, name_space, name_space_prefix): pass def clone_ptr(self): self._top_entity = Vlans() return self._top_entity
af2cb68ec3da39fbb3dd682fd47add56b2af8dc8
c5256bd3b675b65805eef504df508274d26f37a7
/cirtorch/datasets/landmarks_downloader.py
e9b36e4c80b861290645719b1c6469f09c0c68ef
[]
no_license
peternara/Google-Landmarks-Retrieval-and-Recognition-2019-19h-Place-Solution
e5547fd91352c81fd6eb06db8080383abf8ababb
d0a1d42635779facca0c1c36f9e52e8cd76fb4e4
refs/heads/master
2023-03-16T05:32:36.136369
2019-08-14T05:30:49
2019-08-14T05:30:49
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,165
py
#!/usr/bin/python # Note to Kagglers: This script will not run directly in Kaggle kernels. You # need to download it and run it on your local machine. # Downloads images from the Google Landmarks dataset using multiple threads. # Images that already exist will not be downloaded again, so the script can # resume a partially completed download. All images will be saved in the JPG # format with 90% compression quality. import sys, os, multiprocessing, urllib.request, csv from PIL import Image from io import StringIO from io import BytesIO def ParseData(data_file): csvfile = open(data_file, 'r') csvreader = csv.reader(csvfile) key_url_list = [line[:2] for line in csvreader] return key_url_list[1:] # Chop off header def DownloadImage(key_url): out_dir = sys.argv[2] (key, url) = key_url filename = os.path.join(out_dir, '%s.jpg' % key) if os.path.exists(filename): print('Image %s already exists. Skipping download.' % filename) return try: response = urllib.request.urlopen(url) # response = urllib.request.urlopen('http://img31.nipic.com/20120205/1369025_145850127064_1.jpg') # response = open("/home/iap205/Pictures/all_souls_000013.jpg", 'rb') image_data = response.read() except: print('Warning: Could not download image %s from %s' % (key, url)) return try: # pil_image = Image.open(StringIO(image_data)) pil_image = Image.open(BytesIO(image_data)) except: print('Warning: Failed to parse image %s' % key) return try: pil_image_rgb = pil_image.convert('RGB') except: print('Warning: Failed to convert image %s to RGB' % key) return try: pil_image_rgb.save(filename, format='JPEG', quality=90) except: print('Warning: Failed to save image %s' % filename) return def Run(): if len(sys.argv) != 3: print('Syntax: %s <data_file.csv> <output_dir/>' % sys.argv[0]) sys.exit(0) (data_file, out_dir) = sys.argv[1:] if not os.path.exists(out_dir): os.mkdir(out_dir) key_url_list = ParseData(data_file) pool = multiprocessing.Pool(processes=50) pool.map(DownloadImage, key_url_list) if __name__ == '__main__': Run()
bf0b68b1a9dcd5ee671f47a1a2abb6d4f54d7744
d02b5fa06d6c37a977599019fb58b5d62760a6fa
/models/ctpn_tf.py
223f409ba7b1157fb32ebdc423c3392a0ff50041
[]
no_license
xinsuinizhuan/paddle.ctpn
ba4d45318ab1271e88316e251ee85b43ef0fbbf6
7bef0a8e4855cc88d0e56a4337a0eee9679ed3ff
refs/heads/main
2023-07-05T22:13:27.970056
2021-08-16T12:11:34
2021-08-16T12:11:34
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,265
py
import paddle import paddle.nn as nn from models.vgg import vgg16 from models.vggmy import vgg16_bn import paddle.nn.functional as F class BasicConv(nn.Layer): def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1, groups=1, relu=True, bn=True): super(BasicConv, self).__init__() self.out_channels = out_planes self.conv = nn.Conv2D(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups,weight_attr=nn.initializer.KaimingUniform()) self.bn = nn.BatchNorm2D(out_planes) if bn else None self.relu = nn.ReLU() if relu else None def forward(self, x): x = self.conv(x) if self.bn is not None: x = self.bn(x) if self.relu is not None: x = self.relu(x) return x class CTPN_Model(nn.Layer): def __init__(self): super(CTPN_Model, self).__init__() # self.cnn = VGG16(pretrained=True) self.cnn = vgg16_bn(pretrained=True) # self.cnn = vgg16(pretrained=True, batch_norm=False).features self.rpn = BasicConv(512, 512, 3,1,1,bn=False) self.brnn = nn.GRU(512,128,direction='bidirectional') self.lstm_fc = BasicConv(256, 512,1,1,relu=True, bn=False) ####################################################################################################### self.vertical_coordinate = nn.Conv2D(512, 4 * 10, 1) self.score = nn.Conv2D(512, 2 * 10, 1) def forward(self, x): x = self.cnn(x) x = self.rpn(x) x1 = paddle.transpose(x,(0,2,3,1)) # channels last b = x1.shape # batch_size, h, w, c x1 = paddle.reshape(x1,(b[0]*b[1], b[2], b[3])) x2, _ = self.brnn(x1) b = x.shape x2 = paddle.reshape(x2,(b[0], b[2], b[3], 256)) x2 = paddle.transpose(x2,(0,3,1,2)) # channels first x2 = self.lstm_fc(x2) ############################ vertical_pred = self.vertical_coordinate(x2) score = self.score(x2) return score,vertical_pred