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
fa791cbb653d2472098d0a3b028680e2bc9b6414
61432a6d3b25e5b3142fe1f154acf5764bc2d596
/custom_report/controllers/controllers.py
0d654793e8486cc3dde196ee71832650723dcae7
[]
no_license
halltech-ci/tfc_agro
8c2c7911901e8c7bcf548fb05ca8f7891ab4ef51
a737dfdccfca51136cb01894a00f21f5365a771a
refs/heads/master_1
2020-12-22T08:59:40.507801
2020-08-17T21:20:18
2020-08-17T21:20:18
236,734,216
0
3
null
2020-05-09T23:19:24
2020-01-28T12:50:00
Python
UTF-8
Python
false
false
788
py
# -*- coding: utf-8 -*- from odoo import http # class CustomReport(http.Controller): # @http.route('/custom_report/custom_report/', auth='public') # def index(self, **kw): # return "Hello, world" # @http.route('/custom_report/custom_report/objects/', auth='public') # def list(self, **kw): # return http.request.render('custom_report.listing', { # 'root': '/custom_report/custom_report', # 'objects': http.request.env['custom_report.custom_report'].search([]), # }) # @http.route('/custom_report/custom_report/objects/<model("custom_report.custom_report"):obj>/', auth='public') # def object(self, obj, **kw): # return http.request.render('custom_report.object', { # 'object': obj # })
[ "maurice.atche@halltech-africa.com" ]
maurice.atche@halltech-africa.com
8976b9d0a19b96ac46f5c6b8646da091f81333ad
4ddcec92fd322d2ecd89aaf323a59de5b628dc7d
/main.py
ceed23be1d12732750ed64d4d668d38383d8bacf
[]
no_license
ldev/ldevirc
cbf63a16df7f8417fa4a32597ef10153ef1195b5
776ab1732027c98be3c668b07e37b20bbfb20517
refs/heads/master
2016-09-11T02:09:02.500477
2014-02-19T09:12:09
2014-02-19T09:12:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
11,502
py
#!/usr/bin/python # -*- coding: utf-8 -*- # This is a python bot written by Jonas Lindstad (LDEV) # You are free to use this code, which is licensed under the "WTFPL license". # # --------------------------------------------------------------------- # # DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE # Version 2, December 2004 # # Copyright (C) 2004 Sam Hocevar <sam@hocevar.net> # # Everyone is permitted to copy and distribute verbatim or modified # copies of this license document, and changing it is allowed as long # as the name is changed. # # DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE # TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION # # 0. You just DO WHAT THE FUCK YOU WANT TO. # # --------------------------------------------------------------------- # # # TODO: # * http://stackoverflow.com/questions/930700/python-parsing-irc-messages # * Få nick-greia inn i en while-løkke, som sikrer at den får et unikt brukernavn # * Append users to auto-op file from IRC channel # * Skille ut config i egen fil # # MODULES # import socket import sys from random import choice import time import datetime import logging import logging.handlers # why? from subprocess import Popen, PIPE # For calling traceroute import signal # for ctrl-c catching import sys # for ctrl-c catching from platform import platform # Finne linuxversjon etc. from os import path # finding the current script path # import urllib2 # URL grabbing import simplejson as json # Config parsing import re # URL grabbing from urllib import request # URL grabbing # # VARIABLES # client_name = 'ldevirc' version = '0.1a' working_dir = path.dirname(path.realpath(__file__)) # no trailing slash # load configuration file with open('%s/config.json' % working_dir) as data_file: config = json.load(data_file) # # LOGGING # Good article about logging: http://victorlin.me/posts/2012/08/26/good-logging-practice-in-python # logger.<level> = debug, info, warn, error # logger_file = '%s/logs/%s_%s' % (working_dir, config['network'].lower(), config['channel'].lower()) logger = logging.getLogger(version) logger_level = logging.getLevelName(config['logging']['level']) logger.setLevel(logger_level) handler = logging.handlers.RotatingFileHandler(logger_file, 'a', maxBytes=config['logging']['max_file_size'], backupCount=config['logging']['max_number_of_files'], encoding=config['server_encoding']) handler.setLevel(logger_level) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') # left "%(name)" out on purpose handler.setFormatter(formatter) logger.addHandler(handler) logger.info('%s started' % version) # # FUNCTIONS # def find_user(str): return str.split('!')[0][1:] def traceroute(dest, user): dest = dest.replace('|', '').replace(';', '').replace('&', '') # somewhat securing against malicious input.. irc_cmd('PRIVMSG %s :Performing trace towards %s\r\n' % (user, dest)) trace_log_text = "Performing traceroute towards %s (requested by %s)" % (dest, user) logger.info(trace_log_text) p = Popen(['tracepath', dest], stdout=PIPE) while True: line = p.stdout.readline() # return bytes if not line: break line = line.decode("utf-8") irc.send(('PRIVMSG %s :%s\r\n' % (user, line)).encode()) # to remove b'' from line # send string to IRC server def irc_cmd(text): irc.send(("%s\r\n" % text).encode(config['server_encoding'])) def timestamp(): return datetime.datetime.now().isoformat().split('.')[0] # handle ctrl+c gracefully def signal_handler(signal, frame): print ('\nctrl+c detected. Disconnecting from %s' % config['server']) logger.warn(text.strip()) irc_cmd("QUIT :%s" % config['quit_message']) time.sleep(1) sys.exit(0) def grab_title(url): resource = request.urlopen(url) source = resource.read().decode(resource.headers.get_content_charset()) match = re.findall(r'<title>(.*?)</title>', source, re.S) if match: title = match[0].replace('\n', '').strip() logger.info('titlegrabber: Grabbed title "%s"' % title) irc_cmd('PRIVMSG %s :(%s)' % (config['channel'], title)) return title else: logger.info('titlegrabber: No match for <title></title>') # # PERFORM IRC CONNECTION # signal.signal(signal.SIGINT, signal_handler) print ('\r\npress ctrl+c to close the connection to the server') irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) logger.info("ldevirc connecting to %s (%s)" % (config['network'], config['server'])) irc.connect((config['server'], config['port'])) irc_cmd('USER %s Testing 0 * :...' % (config['botnick'])) time.sleep(1) # Prevent Excess flood at a couple of networks (EFnet for instance) irc_cmd('NICK %s' % config['botnick']) time.sleep(1) # Prevent Excess flood at a couple of networks (EFnet for instance) # # TODO: Replace with while-loop of some sort # text = irc.recv(4096).decode(config['server_encoding']) if text.find('ERR_ALREADYREGISTRED') != -1: logger.info('Nick %s taken. Attempting to use %s-' % (config['botnick'], config['botnick'])) irc_cmd('NICK %s-' % config['botnick']) else: logger.info('Registered nick %s' % config['botnick']) # prevents loop if the server closed the connection if text.find('ERROR') !=-1: # print('[%s] ERROR: %s' % timestamp(), text) log.error('%s' % text) sys.exit(1) # join channel irc_cmd("JOIN %s" % config['channel']) logger.info("Joined channel %s" % config['channel']) # # MAIN LOOP - PROCESSING # while 1: # receive data from IRC server text = irc.recv(4096).decode(config['server_encoding']) if len(text.strip()) == 0: logger.error('No data from IRC server - Either IRC server disconnected client or server crashed') sys.exit(1) # print text to terminal for line in text.split('\n'): if len(line.strip()) > 0: if text.find(config['botnick']) != -1: print('[%s] %s' % (timestamp(), line.strip())) logger.info(line.strip()) else: logger.debug(line.strip()) # # BOT CONTROL # if text.find('PING') != -1: logger.debug('PONG %s' % (text.split()[1])) irc_cmd(('PONG %s' % (text.split()[1]))) # Join on kick if text.find('KICK %s %s' % (config['channel'], config['botnick'])): if text.split(' ')[1] == 'KICK' and text.split(' ')[2] == config['channel'] and text.split(' ')[3] == config['botnick']: logger.warn(text) time.sleep(1) irc_cmd("JOIN %s" % config['channel']) time.sleep(0.5) irc_cmd('PRIVMSG %s :I\'m back, bitches!' % config['channel']) # # CTCP # http://www.irchelp.org/irchelp/rfc/ctcpspec.html # http://www.kvirc.net/doc/doc_ctcp_handling.html # Skipped CTCP commands: SOURCE, USERINFO, ERRMSG # # FINGER - Returns the user's full name, and idle time if text.find('PRIVMSG %s :\u0001FINGER\u0001' % (config['botnick'])) != -1: logger.debug('NOTICE %s :\u0001FINGER %s by ldev.no\u0001' % (find_user(text), config['botnick'])) irc_cmd('NOTICE %s :\u0001FINGER %s by ldev.no\u0001' % (find_user(text), config['botnick'])) # VERSION - The version and type of the client if text.find('PRIVMSG %s :\u0001VERSION\u0001' % (config['botnick'])) != -1: # logger.debug('NOTICE %s :\u0001VERSION %s:%s\u0001' % (find_user(text), version, platform())) # irc_cmd('NOTICE %s :\u0001VERSION %s:%s\u0001' % (find_user(text), version, platform())) logger.info('NOTICE %s :\u0001VERSION %s:%s:%s\u0001' % (find_user(text), client_name, version, platform())) irc_cmd('NOTICE %s :\u0001VERSION %s:%s:%s\u0001' % (find_user(text), client_name, version, platform())) # CLIENTINFO - Dynamic master index of what a client knows if text.find('PRIVMSG %s :\u0001CLIENTINFO\u0001' % (config['botnick'])) != -1: logger.debug('NOTICE %s :\u0001VERSION %s under development by Jonas Lindstad\u0001' % version) irc_cmd('NOTICE %s :\u0001VERSION %s under development by Jonas Lindstad\u0001' % version) # PING - Used to measure the delay of the IRC network between clients. if text.find('PRIVMSG %s :\u0001PING\u0001' % (config['botnick'])) != -1: logger.debug('NOTICE %s :\u0001PING %s\u0001' % (text.split()[2])) irc_cmd('NOTICE %s :\u0001PING %s\u0001' % (text.split()[2])) # TIME - Gets the local date and time from other clients. if text.find('PRIVMSG %s :\u0001TIME\u0001' % (config['botnick'])) != -1: logger.debug('NOTICE %s :\u0001TIME %s\u0001' % timestamp()) irc_cmd('NOTICE %s :\u0001TIME %s\u0001' % timestamp()) # # CAP - capabilities # http://www.leeh.co.uk/draft-mitchell-irc-capabilities-02.html # # # All the extra shit # # help if text.find('!help') !=-1 and text.find(config['botnick']) == -1: logger.info('PRIVMSG %s :This is %s. Commands: !help, !bully <user>, !trace <host>' % (config['channel'], version)) irc_cmd('PRIVMSG %s :This is %s. Commands: !help, !bully <user>, !trace <host>' % (config['channel'], version)) # bully if text.find(':!bully') != -1: with open('%s/bully.txt' % working_dir) as f: lines = f.read().splitlines() to = text.split(':!bully')[1].strip() phrase = choice(lines) logger.info('PRIVMSG %s :%s %s' % (config['channel'], to, phrase)) irc_cmd('PRIVMSG %s :%s %s' % (config['channel'], to, phrase)) # gay if text.find('gay') !=-1 and text.find(config['botnick']) == -1: logger.info('PRIVMSG %s :%s er gay!' % (config['channel'], find_user(text))) irc_cmd('PRIVMSG %s :%s er gay!' % (config['channel'], find_user(text))) # auto OP if text.find("JOIN :%s" % config['channel']) !=-1 and text.find(config['botnick']) == -1: auto_op_file = '%s/auto-op/%s_%s' % (working_dir, config['network'].lower(), config['channel'].lower()) logger.debug('Checking auto-op file "%s"' % auto_op_file) if path.isfile(auto_op_file): with open(auto_op_file) as f: operators = f.read().splitlines() if any(ext in text for ext in operators): to = text.split('!')[0][1:] irc_cmd(('PRIVMSG %s :Hei, deg kjenner jeg!' % config['channel'])) logger.info(('MODE %s +o %s' % (config['channel'], to))) irc_cmd(('MODE %s +o %s' % (config['channel'], to))) else: logger.debug('User not in auto-op file') else: logger.debug('No auto-op file for this network/channel') # trace if text.find(':!trace') != -1: dest = text.split(':!trace')[1].strip() traceroute(dest, find_user(text)) # URL title grabber if text.find(config['botnick']) == -1 and (text.find('http://') != -1 or text.find('https://') != -1): urls = re.findall(r'(https?://\S+)', text) try: logger.info('titlegrabber: Fetching title from %s' % urls[0]) grab_title(urls[0]) except: logger.info('titlegrabber: Failed to fetch title from %s' % urls[0]) # e = sys.exc_info()[0] logger.error(sys.exc_info()) # print(sys.exc_info()) pass
[ "jonaslindstad@gmail.com" ]
jonaslindstad@gmail.com
f8b32217c9daae58faab52a87b96758125de8793
4fe52c6f01afb05ac787a361a239466ceac69964
/pyjournal2/build_util.py
9acc2f6977346f32e542ec3806689de1074d6201
[ "BSD-3-Clause" ]
permissive
cmsquared/pyjournal2
85beec6e3a0423d0ee873d189c3a879dd9a7db7c
cfa67529033c5fd7bcd5c60b87c8122ef8c22425
refs/heads/master
2020-04-03T18:30:15.119923
2018-10-31T00:41:07
2018-10-31T00:41:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,934
py
"""This module controls building the journal from the entry sources""" import os import webbrowser import pyjournal2.shell_util as shell_util def get_source_dir(defs): """return the directory where we put the sources""" return "{}/journal-{}/source/".format(defs["working_path"], defs["nickname"]) def get_topics(defs): """return a list of the currently known topics""" source_dir = get_source_dir(defs) topics = [] # get the list of directories in source/ -- these are the topics for d in os.listdir(source_dir): if os.path.isdir(os.path.join(source_dir, d)) and not d.startswith("_"): topics.append(d) return topics def create_topic(topic, defs): """create a new topic directory""" source_dir = get_source_dir(defs) try: os.mkdir(os.path.join(source_dir, topic)) except: sys.error("unable to create a new topic") def build(defs, show=0): """build the journal. This entails writing the TOC files that link to the individual entries and then running the Sphinx make command """ source_dir = get_source_dir(defs) topics = get_topics(defs) # for each topic, we want to create a "topic.rst" that then has # things subdivided by year-month, and that a # "topic-year-month.rst" that includes the individual entries for topic in topics: tdir = os.path.join(source_dir, topic) os.chdir(tdir) # look over the directories here, they will be in the form YYYY-MM-DD years = [] entries = [] for d in os.listdir(tdir): if os.path.isdir(os.path.join(tdir, d)): y, _, _ = d.split("-") if y not in years: years.append(y) entries.append(d) years.sort() entries.sort() # we need to create ReST files of the form YYYY.rst. These # will each then contain the links to the entries for that # year for y in years: y_entries = [q for q in entries if q.startswith(y)] with open("{}.rst".format(y), "w") as yf: yf.write("****\n") yf.write("{}\n".format(y)) yf.write("****\n\n") yf.write(".. toctree::\n") yf.write(" :maxdepth: 2\n") yf.write(" :caption: Contents:\n\n") for entry in y_entries: yf.write(" {}/{}.rst\n".format(entry, entry)) # now write the topic.rst with open("{}.rst".format(topic), "w") as tf: tf.write(len(topic)*"*" + "\n") tf.write("{}\n".format(topic)) tf.write(len(topic)*"*" + "\n") tf.write(".. toctree::\n") tf.write(" :maxdepth: 2\n") tf.write(" :caption: Contents:\n\n") for y in years: tf.write(" {}.rst\n".format(y)) # now write the index.rst os.chdir(source_dir) with open("index.rst", "w") as mf: mf.write("Research Journal\n") mf.write("================\n\n") mf.write(".. toctree::\n") mf.write(" :maxdepth: 2\n") mf.write(" :caption: Contents:\n\n") for topic in sorted(topics): mf.write(" {}/{}\n".format(topic, topic)) mf.write("\n") mf.write("Indices and tables\n") mf.write("==================\n\n") mf.write("* :ref:`genindex`\n") mf.write("* :ref:`modindex`\n") mf.write("* :ref:`search`\n") # now do the building build_dir = "{}/journal-{}/".format(defs["working_path"], defs["nickname"]) os.chdir(build_dir) _, _, rc = shell_util.run("make html") if rc != 0: print("build may have been unsuccessful") index = os.path.join(build_dir, "build/html/index.html") # use webbrowser module if show == 1: webbrowser.open_new_tab(index)
[ "michael.zingale@stonybrook.edu" ]
michael.zingale@stonybrook.edu
de0beb1610545ee78ac1dcc707d7fc40e2c1a0fb
748bbab674d1a5ae6a59bfd4ac22efcb4355e82a
/Prog-II/Back_Front/back/modelo.py
500e048c4dda6a3d2bb759c389dc9ab5b947b11b
[]
no_license
Lima001/Tecnico-IFC
8819114a35080eb914a2d836a0accbf79d3268d8
771fa39dd6046a9d92860fbde70c10dcecd975a3
refs/heads/master
2021-02-07T01:31:04.929420
2020-06-24T02:09:38
2020-06-24T02:09:38
243,967,689
0
0
null
null
null
null
UTF-8
Python
false
false
439
py
from peewee import * arq = "dados.db" db = SqliteDatabase(arq) class BaseModel(Model): class Meta: database = db class Cachorro(BaseModel): nome = CharField() idade = IntegerField() raca = CharField() if __name__ == "__main__": db.connect() db.create_tables([Cachorro]) dog1 = Cachorro.create(nome="Rex",idade=1,raca="Pastor Alemao") print(dog1.nome + "|" + str(dog1.idade) + "|" + dog1.raca)
[ "limaedugabriel@gmail.com" ]
limaedugabriel@gmail.com
211b498888127f1226c08e00b409a8281cbe53d4
27953af4264bf68ccfeef3eac7b31f7b401e6345
/DeepSwapPackages/image_augmentation.py
89a78ad2727d943d4a586015e25a1e6d3bab158d
[]
no_license
rezabonyadi/deep_end_to_end_face_swap
ad0d931060fc51da0b99ffc51bffc69b1b62baa0
11fbb66c83e9fb41f22f56bad35e27fe8f8a3c42
refs/heads/master
2021-07-07T11:06:18.341839
2020-08-23T03:15:46
2020-08-23T03:15:46
174,415,611
1
0
null
null
null
null
UTF-8
Python
false
false
2,642
py
import cv2 import numpy from DeepSwapPackages.umeyama import umeyama # from skimage.transform import warp, AffineTransform # # def randRange(a, b): # ''' # a utility functio to generate random float values in desired range # ''' # return numpy.random.rand() * (b - a) + a # # # def randomAffine(im, rotation_range, zoom_range, shift_range, random_flip): # ''' # wrapper of Affine transformation with random scale, rotation, shear and translation parameters # ''' # sc = randRange(1-zoom_range, 1+zoom_range) # tform = AffineTransform(scale=(sc, sc), # rotation=randRange(-rotation_range, rotation_range), # # shear=randRange(-0.2, 0.2), # translation=(randRange(-im.shape[0]*shift_range, im.shape[0]*shift_range), # randRange(-im.shape[1]*shift_range, im.shape[1]*shift_range))) # warped_image = cv2.resize(warp(im, tform.inverse, mode='reflect'), (64, 64)) # target_image = cv2.resize(im, (64, 64)) # # return warped_image, target_image def random_transform( image, rotation_range, zoom_range, shift_range, random_flip ): h,w = image.shape[0:2] rotation = numpy.random.uniform( -rotation_range, rotation_range ) scale = numpy.random.uniform( 1 - zoom_range, 1 + zoom_range ) tx = numpy.random.uniform( -shift_range, shift_range ) * w ty = numpy.random.uniform( -shift_range, shift_range ) * h mat = cv2.getRotationMatrix2D( (w//2,h//2), rotation, scale ) mat[:,2] += (tx,ty) result = cv2.warpAffine( image, mat, (w,h), borderMode=cv2.BORDER_REPLICATE ) if numpy.random.random() < random_flip: result = result[:,::-1] return result # get pair of random warped images from aligened face image def random_warp( image ): assert image.shape == (256,256,3) range_ = numpy.linspace( 128-80, 128+80, 5 ) mapx = numpy.broadcast_to( range_, (5,5) ) mapy = mapx.T mapx = mapx + numpy.random.normal( size=(5,5), scale=5 ) mapy = mapy + numpy.random.normal( size=(5,5), scale=5 ) interp_mapx = cv2.resize( mapx, (80,80) )[8:72,8:72].astype('float32') interp_mapy = cv2.resize( mapy, (80,80) )[8:72,8:72].astype('float32') warped_image = cv2.remap( image, interp_mapx, interp_mapy, cv2.INTER_LINEAR ) src_points = numpy.stack( [ mapx.ravel(), mapy.ravel() ], axis=-1 ) dst_points = numpy.mgrid[0:65:16,0:65:16].T.reshape(-1,2) mat = umeyama( src_points, dst_points, True )[0:2] target_image = cv2.warpAffine( image, mat, (64,64) ) return warped_image, target_image
[ "Rezabny@gmail.com" ]
Rezabny@gmail.com
3771885ffc07cb6353782e4ba2a5ce9c33480434
d2af44cdecdf48f9edb052fdc29d406edb2ccfad
/utils/metrics.py
e82dd9cda80f23613143a4e8ab4e3d258bf361d2
[]
no_license
zx3Leonoardo/3d-medical
e3122f9e1f4602add26f97d9c258c5ff63a5b54c
9ec045fbbb0980679fb624db769cf096ed1ab8f8
refs/heads/main
2023-07-16T20:03:42.947066
2021-08-26T02:17:15
2021-08-26T02:17:15
390,895,389
0
0
null
null
null
null
UTF-8
Python
false
false
1,717
py
import torch.nn as nn import torch.nn.functional as F import torch import numpy as np class LossAverage(object): def __init__(self) -> None: self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = round(self.sum / self.count, 4) class DiceAverage(object): def __init__(self, class_num) -> None: self.class_num = class_num self.reset() def reset(self): self.value = np.asarray([0]*self.class_num, dtype='float64') self.avg = np.asarray([0]*self.class_num, dtype='float64') self.sum = np.asarray([0]*self.class_num, dtype='float64') self.count = 0 def update(self, logits, targets): self.value = DiceAverage.get_dices(logits, targets) self.sum += self.value self.count += 1 self.avg = np.around(self.sum / self.count, 4) @staticmethod def get_dices(logits, targets): dices = [] max_element, _ = logits.max(dim=1) max_element = max_element.unsqueeze(1).repeat(1, logits.size()[1], 1, 1, 1) ge = torch.ge(logits, max_element) one = torch.ones_like(logits) zero = torch.zeros_like(logits) res = torch.where(ge, one, zero) for class_id in range(res.size()[1]): inter = torch.sum(res[:, class_id, :, :, :] * res[:, class_id, :, :, :]) union = torch.sum(res[:, class_id, :, :, :] + res[:, class_id, :, :, :]) dice = (2. * inter+1)/(union+1) dices.append(dice.item()) return np.asarray(dices)
[ "57-qinzixin@163.com" ]
57-qinzixin@163.com
735b63875c4d13122c07d03e6bcdc3db602a5dc5
0282d9b7f865b74b5c7e8db1980ffec9b41b1a74
/virtual/bin/epylint
4b3605e0ce3a1ab03838bf5caac28f8798ff50b4
[ "MIT" ]
permissive
aluoch-sheila/GALLERY
3599ded0220144cfdcac403652e89593f2dcd5b4
3a910dc272ce5c731d5780749daeecec66bf2313
refs/heads/master
2020-04-10T03:32:47.755612
2018-12-13T06:52:00
2018-12-13T06:52:00
160,773,028
0
0
null
null
null
null
UTF-8
Python
false
false
263
#!/home/moringaschool/Django/my-gallery/virtual/bin/python # -*- coding: utf-8 -*- import re import sys from pylint import run_epylint if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(run_epylint())
[ "aluochsheila1999@gmail.com" ]
aluochsheila1999@gmail.com
a1607a63fe213a683271e64ccc48df84cac8cdf2
1a7dee4f8328a6be57e867d4bb165d176b4c2e1a
/laplace_v2.py
8d7f5ff176d3e1694a31d55bb2a41bceb8a77906
[]
no_license
Atroxon/laplace
9c2513ac16c6d0aa888e0ab6acdd1508303be334
26302cb2ca176e86bf7dbb32fbe93ce17fceba15
refs/heads/main
2023-01-14T08:42:16.242661
2020-11-10T23:30:06
2020-11-10T23:30:06
311,795,759
0
0
null
null
null
null
UTF-8
Python
false
false
4,102
py
import cv2 as cv import matplotlib.pyplot as plt import numpy as np import copy test_files = ['images/3.jpeg'] AVG_kernel = np.array([[1,1,1],[1,1,1],[1,1,1]]) L_kernel = np.array([[0,1,0],[1,-4,1],[0,1,0]]) E_kernel = np.array([[-1,-1,-1],[-1,8,-1],[-1,-1,-1]]) def main(): open_imgs = import_images(paths=test_files) derivatives = list() # First kernel for img in open_imgs: average_matrix = convolution_2D(img, AVG_kernel) laplace_matrix = convolution_2D(average_matrix, L_kernel) absolute_matrix = absolute(laplace_matrix) normalized_matrix = min_max(absolute_matrix,(0,255)) derivatives.append(normalized_matrix) # for i in range(len(open_imgs)): # plot_derivatives(open_imgs[i],derivatives[i]) # Second kernel for img in open_imgs: average_matrix = convolution_2D(img, AVG_kernel) laplace_matrix = convolution_2D(average_matrix, E_kernel) absolute_matrix = absolute(laplace_matrix) normalized_matrix = min_max(absolute_matrix,(0,255)) derivatives.append(normalized_matrix) plot_derivatives(open_imgs[0],derivatives[0]) plot_derivatives2(open_imgs[0],derivatives[1]) plt.show() def import_images(paths=None): """ Import images from input paths inputs: paths: list containing paths to images output: imgs: list containing cv2 objects """ imgs = list() if paths == None: out = dummy() imgs.append(out) test = copy.deepcopy(imgs) return test for path in paths: imgs.append(cv.imread(path, cv.IMREAD_GRAYSCALE)) return imgs def convolution_2D(image, kernel, padding=0, strides=1): #Add strides print(image) xImage = image.shape[0] yImage = image.shape[1] xKernel = kernel.shape[0] yKernel = kernel.shape[1] # Add padding pad_image = np.zeros((xImage+(padding*2),yImage+(padding*2)), np.int16) pad_image[padding:(xImage)+padding, padding:(yImage)+padding] = image print(pad_image) print(pad_image.shape) # Adjusted to the spaces where kernel "fits" out_matrix = np.zeros((pad_image.shape[0]-2*(xKernel//2),pad_image.shape[1]-2*(yKernel//2)), np.int16) print(out_matrix.shape) for x in range(pad_image.shape[0]): #Add strides here abs_x = x - (xKernel//2) if x < (xKernel//2): #Upper bounds continue if x >= pad_image.shape[0]-(xKernel//2): #Lower bounds break for y in range(pad_image.shape[1]): abs_y = y - (yKernel//2) if y < (yKernel//2): #Left bound continue if y >= pad_image.shape[1]-(yKernel//2): #Right bound break extract = pad_image[x-(xKernel//2):x+(xKernel//2)+1, y-(yKernel//2):y+(yKernel//2)+1] pixel_val = np.sum([kernel * extract]) out_matrix[abs_x, abs_y] = pixel_val return out_matrix def plot_derivatives(image, matrix): popFig,popAxs=plt.subplots(1,2) popFig.suptitle("Grayscale ") popAxs[0].imshow(image, cmap='gray') popAxs[1].imshow(matrix, cmap='gray') return def plot_derivatives2(image, matrix): ppFig,ppAxs=plt.subplots(1,2) ppFig.suptitle("Grayscale ") ppAxs[0].imshow(image, cmap='gray') ppAxs[1].imshow(matrix, cmap='gray') return def absolute(matrix): absolute_matrix = np.zeros((matrix.shape[0],matrix.shape[1]), np.int16) for x in range(matrix.shape[0]): for y in range(matrix.shape[1]): absolute_matrix[x,y] = abs(matrix[x,y]) return absolute_matrix def min_max(matrix, boundaries): LBound, UBound = boundaries m = matrix.min() M = matrix.max() normalized = np.zeros((matrix.shape[0],matrix.shape[1]), np.uint8) for x in range(matrix.shape[0]): for y in range(matrix.shape[1]): normalized[x,y] = (matrix[x,y]-LBound)*(UBound-LBound)/(M-m) # todo eso +LBound print(normalized) return normalized if __name__ == '__main__': main()
[ "danielsalinas.t@gmail.com" ]
danielsalinas.t@gmail.com
a58b76fab4d8fa60abf11ac71cab242a7beccad6
c5a1c95e9d8ce937f71caf8340cf11fe98e64f56
/day9/problem5/[이재형] 하샤드 수.py
ff36e229a9d9bb46a7cac28263c8e782cc36fcf6
[]
no_license
Boot-Camp-Coding-Test/Programmers
963e5ceeaa331d99fbc7465f7b129bd68e96eae3
83a4b62ba2268a47859a6ce88ae1819bc96dcd85
refs/heads/main
2023-05-23T08:21:57.398594
2021-06-12T16:39:21
2021-06-12T16:39:21
366,589,317
0
0
null
null
null
null
UTF-8
Python
false
false
171
py
def solution(x): a = [] for i in range(len(str(x))): a.append(int(str(x)[i])) if x % sum(a) == 0: return True else : return False
[ "noreply@github.com" ]
noreply@github.com
4aaf7f9daeeb93706d4bbb8c3bd8d49f690c0c93
d9b3289354d8f75ae8dd9988a89b08596bd4cae9
/pgadmin/pgadmin/browser/server_groups/servers/resource_groups/__init__.py
336fe7d01d25a73d9bfd68a2da083098d2be10c2
[]
no_license
DataCraft-AI/pgdevops
8827ab8fb2f60d97a22c03317903b71a12a49611
f489bfb22b5b17255f85517cb1443846133dc378
refs/heads/master
2023-02-10T05:44:00.117387
2020-01-22T13:40:58
2020-01-22T13:40:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
21,471
py
########################################################################## # # pgAdmin 4 - PostgreSQL Tools # # Copyright (C) 2013 - 2018, The pgAdmin Development Team # This software is released under the PostgreSQL Licence # ########################################################################## """Implements Resource Groups for PPAS 9.4 and above""" import simplejson as json from functools import wraps import pgadmin.browser.server_groups.servers as servers from flask import render_template, make_response, request, jsonify from flask_babel import gettext from pgadmin.browser.collection import CollectionNodeModule from pgadmin.browser.utils import NodeView from pgadmin.utils.ajax import make_json_response, \ make_response as ajax_response, internal_server_error, gone from pgadmin.utils.ajax import precondition_required from pgadmin.utils.driver import get_driver from config import PG_DEFAULT_DRIVER from pgadmin.utils import IS_PY2 # If we are in Python3 if not IS_PY2: unicode = str class ResourceGroupModule(CollectionNodeModule): """ class ResourceGroupModule(CollectionNodeModule) A module class for Resource Group node derived from CollectionNodeModule. Methods: ------- * __init__(*args, **kwargs) - Method is used to initialize the ResourceGroupModule and it's base module. * BackendSupported(manager, **kwargs) - This function is used to check the database server type and version. Resource Group only supported in PPAS 9.4 and above. * get_nodes(gid, sid, did) - Method is used to generate the browser collection node. * node_inode() - Method is overridden from its base class to make the node as leaf node. * script_load() - Load the module script for resource group, when any of the server node is initialized. """ NODE_TYPE = 'resource_group' COLLECTION_LABEL = gettext("Resource Groups") def __init__(self, *args, **kwargs): """ Method is used to initialize the ResourceGroupModule and it's base module. Args: *args: **kwargs: """ super(ResourceGroupModule, self).__init__(*args, **kwargs) self.min_ver = 90400 self.max_ver = None self.server_type = ['ppas'] def get_nodes(self, gid, sid): """ Method is used to generate the browser collection node Args: gid: Server Group ID sid: Server ID """ yield self.generate_browser_collection_node(sid) @property def node_inode(self): """ Override this property to make the node as leaf node. Returns: False as this is the leaf node """ return False @property def script_load(self): """ Load the module script for resource group, when any of the server node is initialized. Returns: node type of the server module. """ return servers.ServerModule.NODE_TYPE @property def module_use_template_javascript(self): """ Returns whether Jinja2 template is used for generating the javascript module. """ return False blueprint = ResourceGroupModule(__name__) class ResourceGroupView(NodeView): """ class ResourceGroupView(NodeView) A view class for resource group node derived from NodeView. This class is responsible for all the stuff related to view like create/update/delete resource group, showing properties of resource group node, showing sql in sql pane. Methods: ------- * __init__(**kwargs) - Method is used to initialize the ResourceGroupView and it's base view. * module_js() - This property defines (if javascript) exists for this node. Override this property for your own logic * check_precondition() - This function will behave as a decorator which will checks database connection before running view, it will also attaches manager,conn & template_path properties to self * list() - This function is used to list all the resource group nodes within that collection. * nodes() - This function will used to create all the child node within that collection. Here it will create all the resource group node. * properties(gid, sid, did, rg_id) - This function will show the properties of the selected resource group node * create(gid, sid, did, rg_id) - This function will create the new resource group object * update(gid, sid, did, rg_id) - This function will update the data for the selected resource group node * delete(self, gid, sid, rg_id): - This function will drop the resource group object * msql(gid, sid, did, rg_id) - This function is used to return modified SQL for the selected resource group node * get_sql(data, rg_id) - This function will generate sql from model data * sql(gid, sid, did, rg_id): - This function will generate sql to show it in sql pane for the selected resource group node. """ node_type = blueprint.node_type parent_ids = [ {'type': 'int', 'id': 'gid'}, {'type': 'int', 'id': 'sid'} ] ids = [ {'type': 'int', 'id': 'rg_id'} ] operations = dict({ 'obj': [ {'get': 'properties', 'delete': 'delete', 'put': 'update'}, {'get': 'list', 'post': 'create'} ], 'nodes': [{'get': 'node'}, {'get': 'nodes'}], 'sql': [{'get': 'sql'}], 'msql': [{'get': 'msql'}, {'get': 'msql'}], 'stats': [{'get': 'statistics'}], 'dependency': [{'get': 'dependencies'}], 'dependent': [{'get': 'dependents'}], 'module.js': [{}, {}, {'get': 'module_js'}] }) def __init__(self, **kwargs): """ Method is used to initialize the ResourceGroupView and it's base view. Also initialize all the variables create/used dynamically like conn, template_path. Args: **kwargs: """ self.conn = None self.template_path = None super(ResourceGroupView, self).__init__(**kwargs) def module_js(self): """ This property defines (if javascript) exists for this node. Override this property for your own logic. """ return make_response( render_template( "resource_groups/js/resource_groups.js", _=gettext ), 200, {'Content-Type': 'application/x-javascript'} ) def check_precondition(f): """ This function will behave as a decorator which will checks database connection before running view, it will also attaches manager,conn & template_path properties to self """ @wraps(f) def wrap(*args, **kwargs): # Here args[0] will hold self & kwargs will hold gid,sid,did self = args[0] self.driver = get_driver(PG_DEFAULT_DRIVER) self.manager = self.driver.connection_manager(kwargs['sid']) self.conn = self.manager.connection() # If DB not connected then return error to browser if not self.conn.connected(): return precondition_required( gettext( "Connection to the server has been lost." ) ) self.template_path = 'resource_groups/sql' return f(*args, **kwargs) return wrap @check_precondition def list(self, gid, sid): """ This function is used to list all the resource group nodes within that collection. Args: gid: Server Group ID sid: Server ID """ sql = render_template("/".join([self.template_path, 'properties.sql'])) status, res = self.conn.execute_dict(sql) if not status: return internal_server_error(errormsg=res) return ajax_response( response=res['rows'], status=200 ) @check_precondition def node(self, gid, sid, rg_id): """ This function will used to create all the child node within that collection. Here it will create all the resource group node. Args: gid: Server Group ID sid: Server ID """ sql = render_template("/".join([self.template_path, 'nodes.sql']), rgid=rg_id) status, result = self.conn.execute_2darray(sql) if not status: return internal_server_error(errormsg=result) if len(result['rows']) == 0: return gone(gettext("""Could not find the resource group.""")) res = self.blueprint.generate_browser_node( result['rows'][0]['oid'], sid, result['rows'][0]['name'], icon="icon-resource_group" ) return make_json_response( data=res, status=200 ) @check_precondition def nodes(self, gid, sid): """ This function will used to create all the child node within that collection. Here it will create all the resource group node. Args: gid: Server Group ID sid: Server ID """ res = [] sql = render_template("/".join([self.template_path, 'nodes.sql'])) status, result = self.conn.execute_2darray(sql) if not status: return internal_server_error(errormsg=result) for row in result['rows']: res.append( self.blueprint.generate_browser_node( row['oid'], sid, row['name'], icon="icon-resource_group" )) return make_json_response( data=res, status=200 ) @check_precondition def properties(self, gid, sid, rg_id): """ This function will show the properties of the selected resource group node. Args: gid: Server Group ID sid: Server ID rg_id: Resource Group ID """ sql = render_template("/".join([self.template_path, 'properties.sql']), rgid=rg_id) status, res = self.conn.execute_dict(sql) if not status: return internal_server_error(errormsg=res) if len(res['rows']) == 0: return gone(gettext("""Could not find the resource group.""")) return ajax_response( response=res['rows'][0], status=200 ) @check_precondition def create(self, gid, sid): """ This function will create the new resource group object Args: gid: Server Group ID sid: Server ID """ required_args = [ 'name' ] data = request.form if request.form else json.loads( request.data, encoding='utf-8' ) for arg in required_args: if arg not in data: return make_json_response( status=410, success=0, errormsg=gettext( "Could not find the required parameter (%s)." % arg ) ) try: # Below logic will create new resource group sql = render_template("/".join([self.template_path, 'create.sql']), rgname=data['name'], conn=self.conn) if sql and sql.strip('\n') and sql.strip(' '): status, res = self.conn.execute_scalar(sql) if not status: return internal_server_error(errormsg=res) # Below logic will update the cpu_rate_limit and dirty_rate_limit for resource group # we need to add this logic because in resource group you can't run multiple commands in one transaction. sql = render_template("/".join([self.template_path, 'update.sql']), data=data, conn=self.conn) # Checking if we are not executing empty query if sql and sql.strip('\n') and sql.strip(' '): status, res = self.conn.execute_scalar(sql) if not status: return internal_server_error(errormsg=res) # Below logic is used to fetch the oid of the newly created resource group sql = render_template("/".join([self.template_path, 'getoid.sql']), rgname=data['name']) # Checking if we are not executing empty query rg_id = 0 if sql and sql.strip('\n') and sql.strip(' '): status, rg_id = self.conn.execute_scalar(sql) if not status: return internal_server_error(errormsg=rg_id) return jsonify( node=self.blueprint.generate_browser_node( rg_id, sid, data['name'], icon="icon-resource_group" ) ) except Exception as e: return internal_server_error(errormsg=str(e)) @check_precondition def update(self, gid, sid, rg_id): """ This function will update the data for the selected resource group node Args: gid: Server Group ID sid: Server ID rg_id: Resource Group ID """ required_args = [ 'name', 'cpu_rate_limit', 'dirty_rate_limit' ] data = request.form if request.form else json.loads( request.data, encoding='utf-8' ) try: sql = render_template("/".join([self.template_path, 'properties.sql']), rgid=rg_id) status, res = self.conn.execute_dict(sql) if not status: return internal_server_error(errormsg=res) old_data = res['rows'][0] for arg in required_args: if arg not in data: data[arg] = old_data[arg] if data['name'] != old_data['name']: sql = render_template("/".join([self.template_path, 'update.sql']), oldname=old_data['name'], newname=data['name'], conn=self.conn) if sql and sql.strip('\n') and sql.strip(' '): status, res = self.conn.execute_scalar(sql) if not status: return internal_server_error(errormsg=res) # Below logic will update the cpu_rate_limit and dirty_rate_limit for resource group # we need to add this logic because in resource group you can't run multiple commands # in one transaction. if (data['cpu_rate_limit'] != old_data['cpu_rate_limit']) \ or (data['dirty_rate_limit'] != old_data['dirty_rate_limit']): sql = render_template("/".join([self.template_path, 'update.sql']), data=data, conn=self.conn) if sql and sql.strip('\n') and sql.strip(' '): status, res = self.conn.execute_scalar(sql) if not status: return internal_server_error(errormsg=res) return jsonify( node=self.blueprint.generate_browser_node( rg_id, sid, data['name'], icon="icon-%s" % self.node_type ) ) except Exception as e: return internal_server_error(errormsg=str(e)) @check_precondition def delete(self, gid, sid, rg_id): """ This function will drop the resource group object Args: gid: Server Group ID sid: Server ID rg_id: Resource Group ID """ try: # Get name for resource group from rg_id sql = render_template("/".join([self.template_path, 'delete.sql']), rgid=rg_id, conn=self.conn) status, rgname = self.conn.execute_scalar(sql) if not status: return internal_server_error(errormsg=rgname) if rgname is None: return make_json_response( success=0, errormsg=gettext( 'Error: Object not found.' ), info=gettext( 'The specified resource group could not be found.\n' ) ) # drop resource group sql = render_template("/".join([self.template_path, 'delete.sql']), rgname=rgname, conn=self.conn) status, res = self.conn.execute_scalar(sql) if not status: return internal_server_error(errormsg=res) return make_json_response( success=1, info=gettext("Resource Group dropped"), data={ 'id': rg_id, 'sid': sid, 'gid': gid, } ) except Exception as e: return internal_server_error(errormsg=str(e)) @check_precondition def msql(self, gid, sid, rg_id=None): """ This function is used to return modified SQL for the selected resource group node Args: gid: Server Group ID sid: Server ID rg_id: Resource Group ID """ data = dict() for k, v in request.args.items(): try: data[k] = json.loads(v, encoding='utf-8') except ValueError: data[k] = v sql, name = self.get_sql(data, rg_id) # Most probably this is due to error if not isinstance(sql, (str, unicode)): return sql sql = sql.strip('\n').strip(' ') if sql == '': sql = "--modified SQL" return make_json_response( data=sql, status=200 ) def get_sql(self, data, rg_id=None): """ This function will generate sql from model data Args: data: Contains the value of name, cpu_rate_limit, dirty_rate_limit rg_id: Resource Group Id """ required_args = [ 'name', 'cpu_rate_limit', 'dirty_rate_limit' ] if rg_id is not None: sql = render_template("/".join([self.template_path, 'properties.sql']), rgid=rg_id) status, res = self.conn.execute_dict(sql) if not status: return internal_server_error(errormsg=res) if len(res['rows']) == 0: return gone( _("The specified resource group could not be found.") ) old_data = res['rows'][0] for arg in required_args: if arg not in data: data[arg] = old_data[arg] sql = '' name_changed = False if data['name'] != old_data['name']: name_changed = True sql = render_template("/".join([self.template_path, 'update.sql']), oldname=old_data['name'], newname=data['name'], conn=self.conn) if (data['cpu_rate_limit'] != old_data['cpu_rate_limit']) \ or data['dirty_rate_limit'] != old_data['dirty_rate_limit']: if name_changed: sql += "\n-- Following query will be executed in a separate transaction\n" sql += render_template("/".join([self.template_path, 'update.sql']), data=data, conn=self.conn) else: sql = render_template("/".join([self.template_path, 'create.sql']), rgname=data['name'], conn=self.conn) if ('cpu_rate_limit' in data and data['cpu_rate_limit'] > 0) \ or ('dirty_rate_limit' in data and data['dirty_rate_limit'] > 0): sql += "\n-- Following query will be executed in a separate transaction\n" sql += render_template("/".join([self.template_path, 'update.sql']), data=data, conn=self.conn) return sql, data['name'] if 'name' in data else old_data['name'] @check_precondition def sql(self, gid, sid, rg_id): """ This function will generate sql for sql pane Args: gid: Server Group ID sid: Server ID rg_id: Resource Group ID """ sql = render_template("/".join([self.template_path, 'properties.sql']), rgid=rg_id) status, res = self.conn.execute_dict(sql) if not status: return internal_server_error(errormsg=res) if len(res['rows']) == 0: return gone( _("The specified resource group could not be found.") ) # Making copy of output for future use old_data = dict(res['rows'][0]) sql = render_template("/".join([self.template_path, 'create.sql']), display_comments=True, rgname=old_data['name'], conn=self.conn) sql += "\n" sql += render_template("/".join([self.template_path, 'update.sql']), data=old_data, conn=self.conn) return ajax_response(response=sql) ResourceGroupView.register_node_view(blueprint)
[ "denis@lussier.io" ]
denis@lussier.io
39d0a5fa54916c6b31eed02202ea9ba9fa284bf2
ad67b49b83d23ba2b0ade3da4db90d9b86d98650
/kafka/archived_scripts/kafka_rss.py
a92f06572dfc8dfb949ad37341f01ac88aace4eb
[ "MIT" ]
permissive
peterhogan/python
f58d08a67991e2822795ee9689544d43cb8fecad
bc6764f7794a862ff0d138bad80f1d6313984dcd
refs/heads/master
2021-01-01T18:41:50.338599
2017-05-13T07:51:54
2017-05-13T07:51:54
34,813,592
0
0
null
null
null
null
UTF-8
Python
false
false
2,215
py
####################################### ############### Imports ############### ####################################### from lxml import etree import os ############################################ ############### Inital setup ############### ############################################ # specify the directory to pull feeds from (default from get_rss_feeds.py) root_dir = 'newsfeeds/' # verbose output or brief (True => Verbose, False => short output) verbose = True # descriptions flag desc_on = True #################################################### ############### Defining the outputs ############### #################################################### def simple_output(rss_file): return def full_output(root_title, root_builddate, item_titles, item_descs, item_pubdates, item_guids): print(item_titles[i].text,"|",item_descs[i].text.split("<")[0],"|",rss_item_pubdates[i].text,"|",rss_item_guids[i].text,"|",rss_root_title[0].text)#,"|",rss_root_builddate[0].text) return # Function to print all the sources picked up in root_dir def print_sources(): return ################################################## ############### Scraping XML files ############### ################################################## for filerss in os.listdir(root_dir): rss_file = etree.parse(root_dir + filerss) rss_root_title = rss_file.xpath('//channel/title') rss_root_builddate = rss_file.xpath('//channel/lastBuildDate') rss_item_titles = rss_file.xpath('//channel/item/title') rss_item_descs = rss_file.xpath('//channel/item/description') rss_item_pubdates = rss_file.xpath('//channel/item/pubDate') rss_item_guids = rss_file.xpath('//channel/item/guid') for i in range(len(rss_item_titles)): #print(rss_root_title[0].text) print(rss_item_titles[i].text,"|",rss_item_descs[i].text,"|",rss_item_pubdates[i].text,"|",rss_item_guids[i].text,"|",rss_root_title[0].text)#,"|",rss_root_builddate[0].text) ''' for i in range(len(rss_item_titles)): print(rss_item_titles[i].text,"|",rss_item_descs[i].text,"|",rss_item_pubdates[i].text,"|",rss_item_guids[i].text,"|",rss_root_title[0].text)#,"|",rss_root_builddate[0].text) '''
[ "peterjameshogan@gmail.com" ]
peterjameshogan@gmail.com
cefccb4e18a42354913c1b1a7008faa1c4c580dc
50219c54e1e1ae1afb3844fe26bb24779c8939aa
/app/clients/email_send_client.py
7ebf66266a323f76ba3bb0c56f173b9abede6db3
[]
no_license
rajsshah23/brightwheel-interview-email-send
aac0de9a55ce95f45b280f9ac1c0bcbdfdbdaa71
86165ab65e976955bb9da4ee05ff2a653b2e3e4a
refs/heads/main
2023-07-18T06:41:09.391399
2021-09-08T03:12:21
2021-09-08T03:12:21
403,364,540
0
0
null
null
null
null
UTF-8
Python
false
false
673
py
from fastapi import Depends from app.dependencies import get_settings from app.models.get_email_status_models import ( GetEmailStatusRequest, GetEmailStatusResponse, ) from app.models.send_email_models import SendEmailRequest, SendEmailResponse from app.setup.settings import Settings class EmailSendClient: def __init__(self, settings: Settings = Depends(get_settings)): self._settings: Settings = settings def send_email(self, request: SendEmailRequest) -> SendEmailResponse: raise NotImplemented() def get_email_status( self, request: GetEmailStatusRequest ) -> GetEmailStatusResponse: raise NotImplemented()
[ "rajsshah23@gmail.com" ]
rajsshah23@gmail.com
66da12d1a46b2363ec995ed6684e46458403d42d
f027db78eb8e44c7d5994531157e910dabe37a6c
/Deep Learning/Unsupervised Learning/Self Organizing Maps (SOM)/Hybrid Supervised-Unsupervised Fraud Detection Model/mega_case_study_improved.py
484cb9e198bfc6e49dbfc918085cf98a404f247e
[]
no_license
jamesawgodwin/PythonMachineLearningTemplates
e6d8ac678ca483a49a2e73dc079faad9bba25147
320f76dabbd988f1c56774e89b5baf9b2767d10d
refs/heads/master
2021-08-08T17:44:35.442494
2020-04-19T04:03:51
2020-04-19T04:03:51
158,993,055
0
0
null
null
null
null
UTF-8
Python
false
false
4,304
py
# Mega Case Study - Make a Hybrid Deep Learning Model # Part 1 - Identify the Frauds with the Self-Organizing Map # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Credit_Card_Applications.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, -1].values # Feature Scaling from sklearn.preprocessing import MinMaxScaler sc = MinMaxScaler(feature_range = (0, 1)) X = sc.fit_transform(X) # Training the SOM from minisom import MiniSom som = MiniSom(x = 10, y = 10, input_len = 15, sigma = 1.0, learning_rate = 0.5) som.random_weights_init(X) som.train_random(data = X, num_iteration = 100) # Visualizing the results from pylab import bone, pcolor, colorbar, plot, show bone() pcolor(som.distance_map().T) colorbar() markers = ['o', 's'] colors = ['r', 'g'] for i, x in enumerate(X): w = som.winner(x) plot(w[0] + 0.5, w[1] + 0.5, markers[y[i]], markeredgecolor = colors[y[i]], markerfacecolor = 'None', markersize = 10, markeredgewidth = 2) show() # Finding the frauds rows = 10 # dimensions of SOM cols = 10 # Add indices to SOM values & sort by value helper = np.concatenate( (som.distance_map().reshape(rows*cols, 1), # the SOM map values np.arange(rows*cols).reshape(rows*cols, 1)), # concatenated with an index axis=1) # as a 2D matrix with 2 columns of data helper = helper[helper[:, 0].argsort()][::-1] # sort by first column (map values) and reverse (so top values are first) # First choose how many cells to take as outliers use_threshold = True # toggle usage for calculating indices (pick cells that exceed threshold or use hardcoded number of cells) top_cells = 4 # 4 out of 100 seems a valid idea, but ideally it might be chosen after inspecting the current SOM plot threshold = 0.8 # Use threshold to select top cells # Take indices that correspond to cells we're interested in idx = helper[helper[:, 0] > threshold, 1] if use_threshold else helper[:top_cells, 1] # Find the data entries assigned to cells corresponding to the selected indices result_map = [] mappings = som.win_map(X) for i in range(rows): for j in range(cols): if (i*rows+j) in idx: if len(result_map) == 0: result_map = mappings[(i,j)] else: # Sometimes a cell contains no observations (customers)... weird # This will cause numpy to raise an exception so guard against that! if len(mappings[(i,j)]) > 0: result_map = np.concatenate((result_map, mappings[(i,j)]), axis=0) # finally we get our fraudster candidates frauds = sc.inverse_transform(result_map) # This is the list of potential cheaters (customer ids) #print(frauds[:, 0]) # Part 2 - Going from Unsupervised to Supervised Deep Learning # Creating the matrix of features customers = dataset.iloc[:, 1:].values # Creating the dependent variable is_fraud = np.zeros(len(dataset)) for i in range(len(dataset)): if dataset.iloc[i,0] in frauds: is_fraud[i] = 1 # Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() customers = sc.fit_transform(customers) # Part 2 - Create the ANN! # Importing the Keras libraries and packages from keras.models import Sequential from keras.layers import Dense # Initialising the ANN classifier = Sequential() # Adding the input layer and the first hidden layer classifier.add(Dense(units = 2, kernel_initializer = 'uniform', activation = 'relu', input_dim = 15)) # Adding the output layer classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid')) # Compiling the ANN classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) # Fitting the ANN to the Training set classifier.fit(customers, is_fraud, batch_size = 1, epochs = 2) # Predicting the probabilities of frauds y_pred = classifier.predict(customers) y_pred = np.concatenate((dataset.iloc[:, 0:1].values, y_pred), axis = 1) # sort np array by index 1 (probability of being a cheater) y_pred = y_pred[y_pred[:, 1].argsort()]
[ "james.a.w.godwin@gmail.com" ]
james.a.w.godwin@gmail.com
20ae7bcc5afe279441ec8d3b9c315a60d9785feb
0a3ef6195220f510ba962c25280b1848b63b858b
/Django_bbs/asgi.py
62b376d760ffba23b0b66e2dc5e4b76f004fe1b6
[]
no_license
wykuro/django_bbs
4584659f42190b933fa26b5eea281b19a31a7885
01605676d6f79567c00f7e4aaadcc681014cf06e
refs/heads/master
2022-11-19T06:48:26.081021
2020-07-28T08:56:21
2020-07-28T08:56:21
283,153,068
0
0
null
null
null
null
UTF-8
Python
false
false
397
py
""" ASGI config for Django_bbs project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Django_bbs.settings') application = get_asgi_application()
[ "2350199078@qq.com" ]
2350199078@qq.com
1e1a220013ea65a97547f55b52bf0e6e8ba7ee32
4b742f57981b3db902e7048fe05faf263ff52138
/base/migrations/0010_pgpkey_passphrase.py
174c1f9c2f96097e66f55808d6348a2d55d10933
[ "MIT" ]
permissive
erichuang2015/Hiren-MailBox
eace0c90b5815f3e4a660dfda75910256704db96
ff4cad0998007e8c9a2a200af3a2e05a3d947d12
refs/heads/master
2020-04-02T01:31:55.680288
2018-09-13T15:21:46
2018-09-13T15:21:46
null
0
0
null
null
null
null
UTF-8
Python
false
false
418
py
# Generated by Django 2.0.4 on 2018-05-22 04:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('base', '0009_auto_20180504_0501'), ] operations = [ migrations.AddField( model_name='pgpkey', name='passphrase', field=models.TextField(default=''), preserve_default=False, ), ]
[ "git.pyprism@gmail.com" ]
git.pyprism@gmail.com
30a77a5b2a326c40c06e455066908091bac0870a
53fab060fa262e5d5026e0807d93c75fb81e67b9
/backup/user_113/ch44_2020_09_30_10_47_17_987015.py
f078ba9a9524ee5b166c21af69a4c0e35a23748f
[]
no_license
gabriellaec/desoft-analise-exercicios
b77c6999424c5ce7e44086a12589a0ad43d6adca
01940ab0897aa6005764fc220b900e4d6161d36b
refs/heads/main
2023-01-31T17:19:42.050628
2020-12-16T05:21:31
2020-12-16T05:21:31
306,735,108
0
0
null
null
null
null
UTF-8
Python
false
false
207
py
#x=True lista = ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'] #while x==True: mes = input('Qual o mês? ') print(lista[mes])
[ "you@example.com" ]
you@example.com
dc0cd9bf59857e086726029d8ff6c6aa608de145
51464779b985f9e4e67279eea4bf022fa8b687e6
/data/tools.py
e8067a800b1ebca972f374a637592ca7df76b585
[ "CC0-1.0", "WTFPL" ]
permissive
xinmingzhang/pyweek22
2b1ef5b11cfbf5c14d5b3d4ee0315d7a86eb98b0
07ef583507d5971b7e55dcd66cee22dc6f36f134
refs/heads/master
2020-04-17T18:43:29.846741
2016-09-10T07:55:00
2016-09-10T07:55:00
67,858,588
0
0
null
null
null
null
UTF-8
Python
false
false
11,906
py
""" This module contains the fundamental Control class and a prototype class for States. Also contained here are resource loading functions. """ import os import copy import pygame as pg class Control(object): """Control class for entire project. Contains the game loop, and contains the event_loop which passes events to States as needed. Logic for flipping states is also found here.""" def __init__(self, caption, icon = None): self.screen = pg.display.get_surface() self.caption = caption self.done = False self.clock = pg.time.Clock() self.fps = 60. self.show_fps = False self.current_time = 0.0 self.keys = pg.key.get_pressed() self.state_dict = {} self.state_name = None self.state = None self.fullscreen = False self.icon = icon if self.icon != None: pg.display.set_icon(self.icon) def setup_states(self, state_dict, start_state): """Given a dictionary of States and a State to start in, builds the self.state_dict.""" self.state_dict = state_dict self.state_name = start_state self.state = self.state_dict[self.state_name] def update(self, dt): """Checks if a state is done or has called for a game quit. State is flipped if neccessary and State.update is called.""" self.current_time = pg.time.get_ticks() if self.state.quit: pg.mouse.set_visible(True) self.done = True elif self.state.done: self.flip_state() self.state.update(dt) self.state.draw(self.screen) def flip_state(self): """When a State changes to done necessary startup and cleanup functions are called and the current State is changed.""" previous, self.state_name = self.state_name, self.state.next persist = self.state.cleanup() self.state = self.state_dict[self.state_name] self.state.startup(persist) self.state.previous = previous def event_loop(self): """Process all events and pass them down to current State. The f5 key globally turns on/off the display of FPS in the caption""" for event in pg.event.get(): if event.type == pg.QUIT: self.done = True elif event.type == pg.KEYDOWN: self.keys = pg.key.get_pressed() self.toggle_show_fps(event.key) elif event.type == pg.KEYUP: self.keys = pg.key.get_pressed() self.toggle_fullscreen(event.key) self.state.get_event(event) def toggle_show_fps(self, key): """Press f5 to turn on/off displaying the framerate in the caption.""" if key == pg.K_F5: self.show_fps = not self.show_fps if not self.show_fps: pg.display.set_caption(self.caption) def toggle_fullscreen(self, key): if key == pg.K_F1: screen_size = pg.display.get_surface().get_size() self.fullscreen = not self.fullscreen if self.fullscreen: self.screen = pg.display.set_mode(screen_size, pg.FULLSCREEN) else: self.screen = pg.display.set_mode(screen_size) def main(self): """Main loop for entire program.""" while not self.done: time_delta = self.clock.tick(self.fps) self.event_loop() self.update(time_delta) pg.display.update() if self.show_fps: fps = self.clock.get_fps() with_fps = "{} - {:.2f} FPS".format(self.caption, fps) pg.display.set_caption(with_fps) class _State(object): """This is a prototype class for States. All states should inherit from it. No direct instances of this class should be created. get_event and update must be overloaded in the childclass. startup and cleanup need to be overloaded when there is data that must persist between States.""" def __init__(self): self.start_time = 0.0 self.current_time = 0.0 self.done = False self.quit = False self.next = None self.previous = None self.persist = {} def get_event(self, event): """Processes events that were passed from the main event loop. Must be overloaded in children.""" pass def startup(self, current_time, persistent): """Add variables passed in persistent to the proper attributes and set the start time of the State to the current time.""" self.persist = persistent self.start_time = current_time def cleanup(self): """Add variables that should persist to the self.persist dictionary. Then reset State.done to False.""" self.done = False return self.persist def update(self, surface, keys, current_time): """Update function for state. Must be overloaded in children.""" pass def render_font(self, font, msg, color, center): """Returns the rendered font surface and its rect centered on center.""" msg = font.render(msg, 1, color) rect = msg.get_rect(center=center) return msg, rect class _KwargMixin(object): """ Useful for classes that require a lot of keyword arguments for customization. """ def process_kwargs(self, name, defaults, kwargs): """ Arguments are a name string (displayed in case of invalid keyword); a dictionary of default values for all valid keywords; and the kwarg dict. """ settings = copy.deepcopy(defaults) for kwarg in kwargs: if kwarg in settings: if isinstance(kwargs[kwarg], dict): settings[kwarg].update(kwargs[kwarg]) else: settings[kwarg] = kwargs[kwarg] else: message = "{} has no keyword: {}" raise AttributeError(message.format(name, kwarg)) for setting in settings: setattr(self, setting, settings[setting]) ### Resource loading functions. def load_all_gfx(directory, colorkey=(0, 0, 0), accept=(".png", ".jpg", ".bmp")): """Load all graphics with extensions in the accept argument. If alpha transparency is found in the image the image will be converted using convert_alpha(). If no alpha transparency is detected image will be converted using convert() and colorkey will be set to colorkey.""" graphics = {} for pic in os.listdir(directory): name, ext = os.path.splitext(pic) if ext.lower() in accept: img = pg.image.load(os.path.join(directory, pic)) if img.get_alpha(): img = img.convert_alpha() else: img = img.convert() img.set_colorkey(colorkey) graphics[name] = img return graphics def load_all_music(directory, accept=(".wav", ".mp3", ".ogg", ".mdi")): """Create a dictionary of paths to music files in given directory if their extensions are in accept.""" songs = {} for song in os.listdir(directory): name, ext = os.path.splitext(song) if ext.lower() in accept: songs[name] = os.path.join(directory, song) return songs def load_all_fonts(directory, accept=(".ttf",)): """Create a dictionary of paths to font files in given directory if their extensions are in accept.""" return load_all_music(directory, accept) def load_all_maps(directory, accept=(".tmx",)): """Create a dictionary of paths to map files in given directory if their extensions are in accept.""" return load_all_music(directory, accept) def load_all_movies(directory, accept=(".mpg",)): """Create a dictionary of paths to movie files in given directory if their extensions are in accept.""" return load_all_music(directory, accept) def load_all_sfx(directory, accept=(".wav", ".mp3", ".ogg", ".mdi")): """Load all sfx of extensions found in accept. Unfortunately it is common to need to set sfx volume on a one-by-one basis. This must be done manually if necessary in the setup module.""" effects = {} for fx in os.listdir(directory): name, ext = os.path.splitext(fx) if ext.lower() in accept: effects[name] = pg.mixer.Sound(os.path.join(directory, fx)) return effects def strip_from_sheet(sheet, start, size, columns, rows=1): """Strips individual frames from a sprite sheet given a start location, sprite size, and number of columns and rows.""" frames = [] for j in range(rows): for i in range(columns): location = (start[0] + size[0] * i, start[1] + size[1] * j) frames.append(sheet.subsurface(pg.Rect(location, size))) return frames def strip_coords_from_sheet(sheet, coords, size): """Strip specific coordinates from a sprite sheet.""" frames = [] for coord in coords: location = (coord[0] * size[0], coord[1] * size[1]) frames.append(sheet.subsurface(pg.Rect(location, size))) return frames def get_cell_coordinates(rect, point, size): """Find the cell of size, within rect, that point occupies.""" cell = [None, None] point = (point[0] - rect.x, point[1] - rect.y) cell[0] = (point[0] // size[0]) * size[0] cell[1] = (point[1] // size[1]) * size[1] return tuple(cell) def cursor_from_image(image): """Take a valid image and create a mouse cursor.""" colors = {(0, 0, 0, 255): "X", (255, 255, 255, 255): "."} rect = image.get_rect() icon_string = [] for j in range(rect.height): this_row = [] for i in range(rect.width): pixel = tuple(image.get_at((i, j))) this_row.append(colors.get(pixel, " ")) icon_string.append("".join(this_row)) return icon_string def color_swap(source_image, swap_map): """ Creates a new Surface from the source_image with some or all colors swapped for new colors. Colors are swapped according to the color pairs in the swap_map dict. The keys and values in swap_map can be RGB tuples or pygame color-names. For each key in swap_map, all pixels of that color will be replaced by the color that key maps to. For example, passing this dict: {(0,255,0): (255, 0, 255), "black": (255, 0, 0), "yellow": "green"} would result in green pixels recolored purple, black pixels recolored red and yellow pixels recolored green. NOTE: This will not work if Pygame's video mode has not been set (i.e., you need to call pygame.display.set_mode beforehand). """ img = source_image size = img.get_size() surf = pg.Surface(size) color_surf = pg.Surface(size) final = img.copy() for original_color, new_color in swap_map.items(): if isinstance(original_color, str): original = pg.Color(original_color) else: original = original_color if isinstance(new_color, str): recolor = pg.Color(new_color) else: recolor = new_color color_surf.fill(original) surf.set_colorkey(original) pg.transform.threshold(surf, img, original, (0, 0, 0, 0), recolor, 1, color_surf, True) final.blit(surf, (0, 0)) return final def lerp(color_1, color_2, lerp_val): """ Return a new color that is a linear interpolation of the two argument colors. lerp_val must be between 0 and 1 (inclusive). """ if not (0 <= lerp_val <= 1): raise ValueError("Lerp value must be in the range [0,1] inclusive.") new = [int(a * (1 - lerp_val) + b * lerp_val) for a, b in zip(color_1, color_2)] return pg.Color(*new)
[ "252004372@qq.com" ]
252004372@qq.com
ad4c71b1ccd1ad4b4495365ed76a0380fc1bfe1b
9539a9704b14545f81b5c60b9f3087b0bdb9661d
/bin/dadl
afb0bf9ba307761bee028311ea20d143d68c5da9
[ "MIT" ]
permissive
Galadirith/my-project-2
b0ef9de6caf2ac65dead527835d03284a901ee4b
5a2d71fc4c1c63d9479c7f57b0e5b335e2f664a3
refs/heads/master
2021-01-09T20:27:34.548747
2016-05-31T10:25:38
2016-05-31T10:25:38
60,062,635
1
0
null
null
null
null
UTF-8
Python
false
false
1,276
#! /usr/bin/env python import sys from dadownloader.auth import Auth from dadownloader.favourites import Favourites from getopt import getopt try: opts, args = getopt(sys.argv[1:], 'adfh', ['help']) except: print('Invalid options passed to dadl') sys.exit() download = {} def usage(): print\ ''' dadl [options] <username> Arguments: <username> The username of the DeviantArt user whos favourites you want to download. Options: -a Download the avatar of the creator of each deviations -d Download the description of each deviation -f Download the file (eg img file) associated with each deviation -h --help Show dadl help menu (this screen) ''' # Unpack command line options for opt, value in opts: # Download avatars? if opt == '-a': download['avatars'] = True # Download descriptions? if opt == '-d': download['descriptions'] = True # Download files? if opt == '-f': download['files'] = True # Show help if opt in ('-h', '--help'): usage() sys.exit() if len(args) == 1: session = Auth().auth() favourites = Favourites(args[0], session, **download) else: print('Wrong number of arguments: %i' % (len(sys.argv)-1))
[ "edward.fauchon.jones@gmail.com" ]
edward.fauchon.jones@gmail.com
dde187738c41353c5e9b347c6b755e131134564e
05fbf2dd9512528675867d1bf525b4bfb947816b
/main.py
4291e4bbfb32bbf6393874f49faa690cebad8523
[]
no_license
kimmobrunfeldt/kauko
efb46eea1a1ab9c1bdfd92436a88d5daba4f3e38
cbc0af6ec6b3aa1d9f717172d984c89f2a9eded2
refs/heads/master
2023-09-05T23:14:32.547518
2013-01-20T11:55:36
2013-01-20T11:55:36
7,545,552
1
1
null
2013-01-16T22:23:42
2013-01-10T17:41:25
JavaScript
UTF-8
Python
false
false
3,814
py
#!/usr/bin/env python """ Kauko server. Must be run as super user. Usage: sudo python main.py -v -d sudo python main.py -p 8080 Options: -h --help Prints this help. -v --verbose Used commands are printed to console. -d --debug Debug information is printed to console. -p --port=<port> Web server's listening port. """ import logging import socket import sys from gevent import pywsgi import kauko.wsgiserver as wsgiserver def setup_logging(root_logger, level=logging.DEBUG): if root_logger.handlers: for handler in root_logger.handlers: root_logger.removeHandler(handler) if level == logging.DEBUG: format = '%(asctime)-15s %(name)-15s %(levelname)-8s %(message)s' else: format = '%(message)s' formatter = logging.Formatter(format) root_logger.setLevel(level) console_handler = logging.StreamHandler(sys.stdout) console_handler.setFormatter(formatter) console_handler.setLevel(level) root_logger.addHandler(console_handler) def get_ip_address(): """Tries to find the ip address of the interface currently used.""" try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) ip_address = s.getsockname()[0] s.close() except socket.error: ip_address = socket.gethostbyname(socket.gethostname()) return ip_address class NullLog(object): """gevent writes directly to stdout, give instance of this class to gevent and it will shut up. Errors are still written to stderr though. """ def write(self, *args, **kwargs): pass def main(): argv = sys.argv[1:] if '-h' in argv or '--help' in argv: print(__doc__.strip()) sys.exit(0) port = 80 # Parse port from arguments success = True for param in ['-p', '--port']: if param in argv: # Find the index of -p or --port from argv list try: i = argv.index(param) except ValueError: success = False break # Try to convert the following argument to port number. try: port = int(argv[i + 1]) if not 1 <= port <= 65535: raise ValueError # Invalid port number except (ValueError, IndexError): success = False break if not success: print('Error: Invalid port number.\nUse number between 1-65535.') sys.exit(1) verbose_flag = '-v' in argv or '--verbose' in argv debug_flag = '-d' in argv or '--debug' in argv logging_level = logging.WARNING if verbose_flag: logging_level = logging.INFO # If debug is specified, it overrides the verbose flag. if debug_flag: logging_level = logging.DEBUG setup_logging(logging.getLogger(''), level=logging_level) print('\nKauko is now started, quit the program by pressing Ctrl - C') ip_address = get_ip_address() if not ip_address.startswith('127'): print('\nOpen the following address in your browser:') address = 'http://%s' % ip_address if port != 80: address += ':%s' % port print(address) else: print('\nCouldn\'t resolve your ip address.') # Serve static files and routes with wsgi app if logging_level > logging.DEBUG: log = NullLog() else: log = 'default' # Uses gevent's default logging -> stdout http_server = pywsgi.WSGIServer(('0.0.0.0', port), wsgiserver.main_app, log=log) http_server.serve_forever() if __name__ == '__main__': try: main() except KeyboardInterrupt: print('Quit.\n')
[ "kimmobrunfeldt@gmail.com" ]
kimmobrunfeldt@gmail.com
aabf23c2151534f4a361ed928fa3088942a201fb
cc7e0827e14f37331c6bd7f821a3e062e2fc7e9d
/houses/migrations/0006_auto_20211004_2059.py
8052304ef74e91c4354fcf6de4383bf8e909c6fc
[]
no_license
kudawoo2002/Ayelevi-estat
f8b7e43170d04ce3f64ca78269118f6df2248928
46fa19883aa360782f35e1c2b0d07233839350f4
refs/heads/main
2023-09-04T08:43:04.387373
2021-10-12T18:18:29
2021-10-12T18:18:29
416,324,409
0
0
null
null
null
null
UTF-8
Python
false
false
661
py
# Generated by Django 3.2.7 on 2021-10-04 20:59 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('houses', '0005_rename_sale_type_seller_seller_type'), ] operations = [ migrations.AddField( model_name='house', name='garage', field=models.IntegerField(default=0), preserve_default=False, ), migrations.AddField( model_name='seller', name='email', field=models.CharField(default=0, max_length=200), preserve_default=False, ), ]
[ "kudawoo2002@gmail.com" ]
kudawoo2002@gmail.com
3a61fda2b382065093425824bfebb1070e29668e
e5d8a863c55bda022f9b21561d8594ce55c237b5
/datamodel/tests.py
ad459397b4e90a1426a2e1d7b55f95385f15d5de
[]
no_license
artiimor/GatoRaton
637fad7c883d084a9e433d76e22812cc8ff92963
84233e7102c319816f5d382b89788d3fec50ddc3
refs/heads/master
2020-08-29T17:14:12.764387
2019-12-14T11:14:03
2019-12-14T11:14:03
218,106,585
1
1
null
2019-12-14T11:04:48
2019-10-28T17:29:25
Python
UTF-8
Python
false
false
976
py
""" @author: rlatorre """ from django.contrib.auth.models import User from django.test import TestCase MSG_ERROR_INVALID_CELL = "Invalid cell for a cat or the mouse|Gato o ratón en posición no válida" MSG_ERROR_GAMESTATUS = "Game status not valid|Estado no válido" MSG_ERROR_MOVE = "Move not allowed|Movimiento no permitido" MSG_ERROR_NEW_COUNTER = "Insert not allowed|Inseción no permitida" class BaseModelTest(TestCase): def setUp(self): self.users = [] for name in ['cat_user_test', 'mouse_user_test']: self.users.append(self.get_or_create_user(name)) @classmethod def get_or_create_user(cls, name): try: user = User.objects.get(username=name) except User.DoesNotExist: user = User.objects.create_user(username=name, password=name) return user @classmethod def get_array_positions(cls, game): return [game.cat1, game.cat2, game.cat3, game.cat4, game.mouse]
[ "amorcillop@gmail.com" ]
amorcillop@gmail.com
0de0fd9a7e56f15a58adbac9a8208ed4548f3d5d
988003149dd3cc82a554d38b2948b7a6dab7f0c5
/161278031/3/3.py
607d0268c8e7b1cc696cfc3d107849286369f7ec
[]
no_license
HomeworkNJU/Final
894cb0a17349f39677dd6ede29781d98484a887a
08906263f5c78e2d0a1828007bf15d6cd28e16d8
refs/heads/master
2020-03-20T01:00:33.201335
2018-06-20T04:04:41
2018-06-20T04:04:41
137,064,142
0
15
null
2018-06-20T04:04:42
2018-06-12T11:49:46
Python
UTF-8
Python
false
false
1,172
py
# -*- coding: utf-8 -*- """ Created on Wed Jun 20 10:15:36 2018 @author: lenovo """ def expense(price,count): money=price*0.002 if(money<5): money=5 money+=(count//1000) money+=1 return money m=int(input("please input the number of action:")) action=[] for i in range(0,m): s=input().split() action.append([int(s[0]),int(s[1]),int(s[2])]) n=int(input("input the change number:")) change=[] for i in range(0,n): s=input().split() change.append([int(s[0]),int(s[1])]) output=0 revenue=0 for i in range(0,len(action)): for j in range(0,len(change)-1): if(action[i][0]>=change[j][0] and action[i][0]<change[j+1][0]): price=change[j][1] break if(action[i][0]>=change[len(change)-1][0]): price=change[len(change)-1][1] if(action[i][2]==1): output+=price*action[i][1]*100 output+=expense(price*action[i][1]*100,action[i][1]*100) else: revenue+=price*action[i][1]*100 output+=expense(price*action[i][1]*100,action[i][1]*100)+price*action[i][1]*100*0.001 print("the allowance is: %.2f" %(revenue-output))
[ "noreply@github.com" ]
noreply@github.com
4dbead710f1b01e513a121fde157ac24452544dc
c9e71369de04b9c20fde8bd325a09260d3d81805
/dev/simulator/migrations/0001_initial.py
033608ccd7646c149a8dcdb37f1f967de2777b23
[]
no_license
bradleyrp/factory-beta
14a02c37279760a3d8b0186daf8544c351808be2
acf695129b87858b7cfec5d8b18b881d41548e28
refs/heads/master
2021-06-08T14:26:03.284946
2016-10-05T02:20:11
2016-10-05T02:20:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,473
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Simulation', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(unique=True, max_length=100)), ('program', models.CharField(default=b'protein', max_length=30, choices=[(b'protein', b'protein'), (b'cgmd-bilayer', b'cgmd-bilayer')])), ('started', models.BooleanField(default=False)), ('code', models.CharField(unique=True, max_length=200)), ('dropspot', models.TextField(default=b'./')), ], options={ 'verbose_name': 'AUTOMACS simulation', }, ), migrations.CreateModel( name='Source', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(default=b'', max_length=100)), ('dropspot', models.TextField(default=b'./')), ], ), migrations.AddField( model_name='simulation', name='sources', field=models.ManyToManyField(to='simulator.Source'), ), ]
[ "bradleyrp@gmail.com" ]
bradleyrp@gmail.com
611a492f714cd96b2ba9c94b3644617e50c8c6ce
86294539ffa65b34a862b200c84ee068187dc743
/do2things/manage.py
78b2063220ba03afa6e0bd0a501b0280f45ed107
[ "MIT" ]
permissive
tlake/do2things
6acb4f43990b0d0e4a9b80090e21246c1d39398a
4e83bea1fc579006200e9ca3a627c1bc04a6a53b
refs/heads/master
2021-01-21T04:24:57.108087
2016-08-22T08:56:11
2016-08-22T08:56:11
39,576,039
0
0
null
2015-08-27T01:28:15
2015-07-23T15:40:53
JavaScript
UTF-8
Python
false
false
252
py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "do2things.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
[ "tanner.lake@gmail.com" ]
tanner.lake@gmail.com
0dabd218576ed96dbe4a021fce762f03727b90ae
b4948c322401435a02370dd96708399fda4a48fc
/demo/simple_code/test_pass.py
453fa756db68194cdd14c29692c9fa5fb24807be
[]
no_license
fengbingchun/Python_Test
413e2c9bb844a5b3641e6e6daf37df277589006e
eaedcd55dbc156b685fa891538e1120ea68fa343
refs/heads/master
2023-06-21T02:28:07.310364
2023-06-11T04:46:29
2023-06-11T04:46:29
99,814,791
7
6
null
2022-09-30T00:38:06
2017-08-09T14:01:48
C++
UTF-8
Python
false
false
428
py
# Blog: https://blog.csdn.net/fengbingchun/article/details/125242357 # 1. empty function def func(): pass # remember to implement this func() # 2. empty class class fbc: pass fbc() # 3. loop num = 5 for i in range(num): pass # 4. conditional statement a = 5 b = 10 if (a < b): pass else: print("b<=a") for letter in "Python3": if letter == "h": pass else: print("", letter, end="") print("\ntest finish")
[ "fengbingchun@163.com" ]
fengbingchun@163.com
fbc7694ea37606dbb8b3d679815129d939c33700
ee7cde00d334cf625e309a7157e331e450a7056d
/scripts/json_toolpath_analyzer.py
205d254edb0b33031dba04f9af66c048882ae369
[]
no_license
makerbot/TestFiles
29a73a135b53ce2c447501c4788c8cceaa1075e4
ba16bccad29646e0ce4379adb33632fb9799b852
refs/heads/master
2021-01-19T02:15:42.711380
2016-07-29T17:45:20
2016-07-29T17:45:20
2,892,052
4
2
null
null
null
null
UTF-8
Python
false
false
15,145
py
import os import sys import re import math import argparse import copy import json layer_begin = re.compile('^(\(|;)(<layer>|Slice) [\d.]+.*(\)|:)?$') paramcodes = 'XYZFABE' g1re = re.compile('^G1\s+(?P<param>(['+paramcodes+']-?\d+(\.\d*)?\s*)+)(?P<comment>.*)$') paramre = re.compile('(?P<code>['+paramcodes+'])(?P<value>-?\d+(\.\d*)?)') def formatParamDict(params, category = ''): '''Convert a dict into an xml-like format''' return reduce(lambda a,b: '%s %s=\"%s\"' % ((a,) + b), params.iteritems(), category) def writeSvg(output, elements): '''Write elements (an iterable) to output (a file-like thing)''' output.write("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?>\n") output.write("<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n") for element in elements: if element: output.write(element + '\n') output.write("</svg>\n") def decodeCommand(command): '''Decode a G1 command or layer change into a dict.''' params = dict() params['line']=filter(lambda a: a!='\n',command) if layer_begin.match(command): params['layer']=True g1match = g1re.match(command) if None is not g1match: params['G1']=True data = paramre.finditer(g1match.group('param')) for match in data: params[match.group('code')] = float(match.group('value')) if 'layer' in params: sys.stdout.write('.') sys.stdout.flush() return params def encodeCommand(command): '''Reconstruct a decoded command.''' if 'G1' in command: foo = lambda a,b: ('%s%s')%(a,((' '+b+str(command[b])) if b in command else ''),) if 'old' in command: return reduce(foo, paramcodes, 'OLD: %s\nNEW: G1' % (encodeCommand(command['old']))) else: return reduce(foo, paramcodes, 'G1') else: try: return command['line'] except KeyError as ke: return '' def interpretCommand(command, md = None): '''Get a style string from a preprocessed command.''' def speedConvert(s): if None is md: s = (s / 5000.0) * 256.0 ** 2 c = [256.0 ** 2, 256.0, 256.0] sc = [math.fmod(s, p) * 256.0/p for p in c] ret = [int(sci) for sci in sc] else: clamp = 2.0 split = 0.5 if md[1] != 0: v = (s - md[0]) / md[1] else: v = 0.0 v = max(v, -clamp) v = min(v, clamp) v = (v + clamp) / (2.0 * clamp) b = 0.0 if v < split: a = v / split #a = math.sqrt(a) c = b else: a = b c = (v - split) / (1.0 - split) #c = math.sqrt(c) ret = [int(255 * j) for j in (a,b,c)] #print s, sc return ret def paramConvert(sc): return (sc[0], sc[1], sc[2], 2.0) speedParam = lambda s: paramConvert(speedConvert(s)) if 'G1' in command: for axis in 'ABE': if axis in command and axis in command['old']: volume = command[axis] - command['old'][axis] break if volume == 0: #travel move params = (0,255,0,1) else: params = speedParam(command['F']) return 'stroke:rgb(%s,%s,%s);stroke-width:%s' % params elif 'type' in command and command['type'] == 'movement': volume = command['volume'] if volume == 0: #travel move params = params = (0,255,0,1) else: params = speedParam(command['speed']) return 'stroke:rgb(%s,%s,%s);stroke-width:%s' % params else: return None def parseCommands(commands): '''Get a list of decoded commands from the commands iterable''' sys.stdout.write('\nReading Commands\n') sys.stdout.flush() return [decodeCommand(command) for command in commands] def dropInitCommands(commands): ''' Drop all things before the first layer label in decoded commands. Returns a list containing only commands from the first layer label ''' for index in range(len(commands)): if 'layer' in commands[index]: return commands[index:] def offsetCommands(commands, offset = (0.0,0.0), scale=10.0): ''' Make all X,Y coordinates in commands positive plus offset. commands is an iterable of decoded commands. offset is a coordinate pair. All commands will be moved such that no command is below offset. scale will increase the size of things ''' minimums = dict({'x':999.0, 'y':999.0}) maximums = dict({'x':-999.0, 'y':-999.0}) offset = dict({'x':offset[0], 'y':offset[1]}) sys.stdout.write('\nDetecting Extents\n') sys.stdout.flush() for command in commands: for axis in 'xy': if axis in command["command"]["parameters"]: minimums[axis] = min(minimums[axis],command["command"]["parameters"][axis]) maximums[axis] = max(maximums[axis],command["command"]["parameters"][axis]) print '\nMinimums:', '%s\t%s' % tuple([minimums[a] for a in 'xy']) print 'Maximums:', '%s\t%s' % tuple([maximums[a] for a in 'xy']) sys.stdout.write('\nTransforming Coordinates\n') sys.stdout.flush() for command in commands: for axis in 'xy': if axis in command["command"]["parameters"]: if 'x' == axis: command["command"]["parameters"][axis] = (command["command"]["parameters"][axis] - minimums[axis]) * scale + offset[axis] else: command["command"]["parameters"][axis] = (maximums[axis] - command["command"]["parameters"][axis]) * scale + offset[axis] def preprocessCommands(commands): '''Add relative information to each command for use in drawing svgs''' oldCommand = dict() currentCommand = dict() sys.stdout.write('\nParsing Command Transitions\n') sys.stdout.flush() for command in commands: currentCommand.update(command) currentCommand['old'] = copy.deepcopy(oldCommand) oldCommand.update(currentCommand) command.update(currentCommand) del oldCommand['old'] def postprocessCommands(commands): '''Convert preprocessed commands into a json-ready dict''' layers = [] movements = [] last_z = 0 for command in commands: if last_z != command["command"]["parameters"]["z"]: if len(movements) > 0: layers.append(movements) movements = [] if command["command"]["function"] == "move" and "command" in command["old"]: #try: movement = dict({'type': 'movement'}) oldPos = dict() newPos = dict() oldPos['x'] = command['old']["command"]["parameters"]['x'] oldPos['y'] = command['old']["command"]["parameters"]['y'] newPos['x'] = command["command"]["parameters"]['x'] newPos['y'] = command["command"]["parameters"]['y'] movement['from'] = oldPos movement['to'] = newPos movement['speed'] = command["command"]["parameters"]['feedrate'] movement['relative'] = dict() for axis in 'xy': movement['relative'][axis] = movement['to'][axis] - movement['from'][axis] movement['distance'] = math.sqrt(movement['relative']['x']**2 + movement['relative']['y']**2) tool = 'a' if 'a' in command["command"]["parameters"]: movement['volume'] = command["command"]["parameters"]['a'] - command['old']["command"]["parameters"]['a'] last_z = command["command"]["parameters"]["z"] movements.append(movement) #except KeyError as ke: # print("Key Error") # pass outDict = dict() outDict['layers'] = [] for layer in layers: curLayer = dict({'movements' : layer}) outDict['layers'].append(curLayer) return outDict def distribution(values): '''From list of numeric types get (mean, std deviation, min, max)''' E = 0.0 E2 = 0.0 counter = 0 M = None m = None for value in values: E += value E2 += value ** 2 counter += 1 if None is M: M = value else: M = max(M, value) if None is m: m = value else: m = min(m, value) E /= counter E2 /= counter return (E, math.sqrt(E2 - E ** 2), m, M) def processedDistribution(commands): ''' From a list of processed commands, get (mean, std deviation) ''' try: largest = max(c['speed'] for c in commands if c['volume'] != 0 and c['distance'] != 0) except ValueError as ve: largest = 0 try: d = distribution(c['speed'] for c in commands if c['volume'] != 0 and c['distance'] != 0) except ZeroDivisionError as zde: d = 0 return d def parseArgs(argv): parser=argparse.ArgumentParser( description="Generate customizable analysis of GCode in svg form.") #MONKEY PATCH BEGIN def argparse_error_override(message): parser.print_help() parser.exit(2) parser.error=argparse_error_override #MONKEY PATCH END parser.add_argument( 'json_path', help='path of json to analyze') parser.add_argument( 'OUTPUT_PATH', type=os.path.abspath, nargs='?', help='top folder where to place generated files', default=None) return parser.parse_args(argv) def commandToSvg(command, arg = None): '''Convert a single processed movement to an svg line''' if 'old' in command: #work on a preprocessed command relative = dict() for param in paramcodes: if param in command and param in command['old']: relative[param] = command[param] - command['old'][param] lineparams = dict() try: lineparams['x1'] = command['old']["command"]["parameters"]['x'] lineparams['y1'] = command['old']["command"]["parameters"]['y'] lineparams['x2'] = command["command"]["parameters"]['x'] lineparams['y2'] = command["command"]["parameters"]['y'] lineparams['style'] = interpretCommand(command, arg) return '<%s />' % (formatParamDict(lineparams, 'line'), ) except KeyError as ke: pass elif 'type' in command and command['type'] == 'movement': #work on a postprocessed command try: if command ['distance'] > 0: #line lineparams = dict({ 'x1': command['from']['x'], 'y1': command['from']['y'], 'x2': command['to']['x'], 'y2': command['to']['y'], 'style': interpretCommand(command, arg) }) return '<%s />' % (formatParamDict(lineparams, 'line'), ) else: #reversal? if command['volume'] < 0: #reverse color = 'blue' elif command['volume'] > 0: #restart color = 'red' else: color = 'rgb(0,255,0)' roundparams = dict({ 'cx': command['to']['x'], 'cy': command['to']['y'], 'r': 4.0, 'stroke': 'none', 'fill': color }) return '<%s />' % (formatParamDict(roundparams, 'circle'), ) except KeyError as ke: pass return None def monolithicPre(commands, out_dir): ''' Cause svg files to appear in out_dir/svg. Return a list of file names written ''' layer_num = 0 layer_name = None oldCommands = [] outFiles = [] sys.stdout.write('\nRendering SVG files\n') sys.stdout.flush() for command in commands: if 'layer' in command: sys.stdout.write('.') sys.stdout.flush() if None is not layer_name: ofilename = os.path.join(out_dir, 'svg', 'layer_%s.svg' % (layer_num)) with open(ofilename, 'w') as ofile: writeSvg(ofile, [commandToSvg(c) for c in oldCommands]) outFiles.append(ofilename) layer_name = command['layer'] layer_num += 1 oldCommands = [] else: oldCommands.append(command) return outFiles def monolithicPost(commands, out_dir): layer_num = 0 outFiles = [] sys.stdout.write('\nRendering SVG files\n') sys.stdout.flush() for layer in commands['layers']: sys.stdout.write('.') sys.stdout.flush() ofilename = os.path.join(out_dir, 'svg', 'layer_%s.svg' % (layer_num)) outFiles.append(ofilename) with open(ofilename, 'w') as ofile: md = processedDistribution(layer['movements']) lines = [commandToSvg(c, md) for c in layer['movements']] #circles = ['<%s />' % formatParamDict(c, 'circle') # for c in computeCurvature(layer['movements'])] writeSvg(ofile, lines) layer_num += 1 return outFiles def monolithicFunc(commands, out_dir): if isinstance(commands, dict) and 'layers' in commands: return monolithicPost(commands, out_dir) else: return monolithicPre(commands, out_dir) def renderIndex(listOfFiles, infile, output): output.write('<html><head><title>%s</title></head><body>\n' % (infile)) output.write('<table>\n') for file in listOfFiles: output.write('\t<tr>\n') output.write('\t\t<td>\n') output.write('\t\t\t<a href=\"%s\">%s</a>\n' % (file, os.path.basename(file))) output.write('\t\t</td>\n') output.write('\t</tr>\n') output.write('</table>\n') output.write('</body></html>') def main(argv = None): if None is argv: argv = sys.argv args = parseArgs(argv[1:]) if None is args.OUTPUT_PATH: args.OUTPUT_PATH = os.path.dirname(args.json_path) OUTPUT_SVG = os.path.join(args.OUTPUT_PATH, 'svg') if not os.path.exists(OUTPUT_SVG): os.makedirs(OUTPUT_SVG) f = open(args.json_path) json_file = json.load(f) offsetCommands(json_file, (32.0,32.0), 10) preprocessCommands(json_file) commandsDict = postprocessCommands(json_file) outFiles = monolithicFunc(commandsDict, args.OUTPUT_PATH) with open(os.path.join(args.OUTPUT_PATH, 'index.html'), 'w') as outIndex: renderIndex(outFiles, os.path.basename(args.json_path), outIndex) if __name__ == '__main__': main()
[ "alison.nj.leonard@gmail.com" ]
alison.nj.leonard@gmail.com
9958bee7ab67e7e9f94c168f40fd987b1ed06256
33ff78109f47d6efe1f3fd334733b8404472277c
/sketch_191203a.pyde
e2b3368b2b203a216e96563ca7a9fb8930c24d55
[ "MIT" ]
permissive
jadejieheng/processing.py-learning
ef29ad5d8f704461e2fb3486b8437a6467094738
aef8b990f4eec4a39def7c6444f7bea4753831a2
refs/heads/master
2020-09-23T11:44:24.663341
2019-12-16T23:46:47
2019-12-16T23:46:47
225,493,387
0
0
null
null
null
null
UTF-8
Python
false
false
2,570
pyde
""" pusedocode c = color(0) x = 0.0 y = 100.0 speed = 1.0 def setup(): size(500, 500) def draw(): background(255) move() display() def move(): global x x = x + speed if x > width: x = 0 def display(): fill(c) rect(x, y, 150, 50) """ """ rewrite the structure, object oriented class Car(object):#class name, data(global variables) def __init__(self): #initializing data self.c = color(255) self.x = 100 self.y = 100 self.xspeed = 1 def display(self): #functionality rectMode(CENTER) fill(self.c) rect(self.x, self.y, 100, 50) def drive(self): #functionality self.x += self.xspeed if self.x > width: self.x = 0 Note that the code for a class exists as its own block and can be placed anywhere outside of setup() and draw(), as long as it's defined before you use it. myCar = Car() #drive() must be called with Car instance as first argument #Car is a class, myCar = Car() is an instance #Car.drive() is not an argument def setup(): size(1000,1000) def draw(): background(255) myCar.drive() myCar.display() result is one """ """using the object""" class Car(object):#class name def __init__(self, c, x, y, xspeed, yspeed): #initializing data self.c = c self.x = x self.y = y self.xspeed = xspeed self.yspeed = yspeed def display(self): #functionality noStroke() rectMode(CENTER) fill(self.c) rect(self.x, self.y, 200, 100) def drive(self): #functionality self.x += self.xspeed if self.x > width: #this loop runs for +speed self.x = 0 if self.x < 0: #this loop runs for -speed self.x = width self.y += self.yspeed# this has no loop #myCar = Car() #initializing an object/object instantiation #object instantiation myCar1 = Car(color(204,14,66), 1000, 650, -5, 0) myCar2 = Car(color(33,45,201), 0, 350, 2, 0) myCar3 = Car(color(234,164,0), 500, 0, 0, 2) def setup(): size(1000,1000) def draw(): background(255) myCar1.drive() # Functions are called with the "dot syntax". myCar1.display() myCar2.drive() myCar2.display() myCar3.drive() myCar3.display()
[ "noreply@github.com" ]
noreply@github.com
224efd07081d700cef2f4bff2f9f658dcccc15e2
256efb0e9ff8b7420b412c260e6c05cd7c52c5ce
/B/resolve.py
5e0f2bb0fd1bde1c3ffc1f155dfc45171749a311
[ "MIT" ]
permissive
staguchi0703/ABC176
37a85f6d83570967696712a98dd39e1f1a08b04b
16f2f188ef5c73f85d08b028f14cd963b33d55af
refs/heads/master
2022-12-07T18:15:02.659948
2020-08-24T15:00:29
2020-08-24T15:00:29
289,476,704
0
0
null
null
null
null
UTF-8
Python
false
false
204
py
def resolve(): ''' code here ''' N = input() sum_num = 0 for item in N: sum_num += int(item) if sum_num % 9 == 0: print('Yes') else: print('No')
[ "s.taguchi0703@gmail.com" ]
s.taguchi0703@gmail.com
bddfab9694013cb5361590adc0e4269290af1cec
b82ebabc2568e34ba1db516abd5bb978fda69f2c
/Forming/urls.py
e0ed48947301b255a855f3ffcb08fce25ff8ab42
[]
no_license
msreenathreddy67/farming
3996f19f16a0e689e890687a661ffed46f63d58d
9d727f0297b0fa444da8b7383d84ba3f43decded
refs/heads/main
2023-06-17T07:29:07.520940
2021-07-09T11:04:17
2021-07-09T11:04:17
384,410,129
0
0
null
null
null
null
UTF-8
Python
false
false
863
py
"""Forming URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from app import views urlpatterns = [ path('admin/', admin.site.urls), path('index/',views.index,name='index'), path('about/',views.about,name='about') ]
[ "msreenathreddy67@gmail.com" ]
msreenathreddy67@gmail.com
23c2de5fd645c39cbadd4ecdb4a8572487884ba8
069c2295076c482afadfe6351da5ae02be8e18e6
/tests/urlpatterns/path_same_name_urls.py
d7ea5431b1e2e70e97338b78591e99ba67df435e
[ "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "GPL-1.0-or-later", "Python-2.0.1", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-other-permissive", "Python-2.0" ]
permissive
django/django
5eb557f57053631cd4f566f451e43197309dbeeb
c74a6fad5475495756a5bdb18b2cab2b68d429bc
refs/heads/main
2023-09-01T03:43:44.033530
2023-08-31T08:27:32
2023-08-31T08:27:32
4,164,482
73,530
38,187
BSD-3-Clause
2023-09-14T20:03:48
2012-04-28T02:47:18
Python
UTF-8
Python
false
false
1,483
py
from django.urls import path, re_path, register_converter from . import converters, views register_converter(converters.DynamicConverter, "to_url_value_error") urlpatterns = [ # Different number of arguments. path("number_of_args/0/", views.empty_view, name="number_of_args"), path("number_of_args/1/<value>/", views.empty_view, name="number_of_args"), # Different names of the keyword arguments. path("kwargs_names/a/<a>/", views.empty_view, name="kwargs_names"), path("kwargs_names/b/<b>/", views.empty_view, name="kwargs_names"), # Different path converters. path("converter/path/<path:value>/", views.empty_view, name="converter"), path("converter/str/<str:value>/", views.empty_view, name="converter"), path("converter/slug/<slug:value>/", views.empty_view, name="converter"), path("converter/int/<int:value>/", views.empty_view, name="converter"), path("converter/uuid/<uuid:value>/", views.empty_view, name="converter"), # Different regular expressions. re_path(r"^regex/uppercase/([A-Z]+)/", views.empty_view, name="regex"), re_path(r"^regex/lowercase/([a-z]+)/", views.empty_view, name="regex"), # converter.to_url() raises ValueError (no match). path( "converter_to_url/int/<value>/", views.empty_view, name="converter_to_url", ), path( "converter_to_url/tiny_int/<to_url_value_error:value>/", views.empty_view, name="converter_to_url", ), ]
[ "felisiak.mariusz@gmail.com" ]
felisiak.mariusz@gmail.com
529b1a3a2c7b1d1ca36401ac499afa8ce5891042
d602149c0bf94a178e9972b74f113d7412db0eca
/google-cloud-sdk/google-cloud-sdk/.install/.backup/lib/googlecloudsdk/third_party/apis/tpu/v1alpha1/tpu_v1alpha1_messages.py
46cde70eed13e0fc8a3c6175ab6450f73783066d
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
sarahdactyl71/gneiss-rocks
ffe19df02e77d8afdb2b96ae810e0e31490f2d77
45a4900a89638c1b6bc50d9ff4a83ae631a22c7a
refs/heads/development
2021-07-04T05:36:12.037156
2017-10-06T22:14:27
2017-10-06T22:14:27
102,655,986
0
1
null
2020-07-25T07:44:54
2017-09-06T20:38:11
Python
UTF-8
Python
false
false
25,050
py
"""Generated message classes for tpu version v1alpha1. TPU API provides customers with access to Google TPU technology. """ # NOTE: This file is autogenerated and should not be edited by hand. from apitools.base.protorpclite import messages as _messages from apitools.base.py import encoding from apitools.base.py import extra_types package = 'tpu' class Empty(_messages.Message): """A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON object `{}`. """ class ListLocationsResponse(_messages.Message): """The response message for Locations.ListLocations. Fields: locations: A list of locations that matches the specified filter in the request. nextPageToken: The standard List next-page token. """ locations = _messages.MessageField('Location', 1, repeated=True) nextPageToken = _messages.StringField(2) class ListNodesResponse(_messages.Message): """Response for ListNodes. Fields: nextPageToken: The next page token or empty if none. nodes: The listed nodes. """ nextPageToken = _messages.StringField(1) nodes = _messages.MessageField('Node', 2, repeated=True) class ListOperationsResponse(_messages.Message): """The response message for Operations.ListOperations. Fields: nextPageToken: The standard List next-page token. operations: A list of operations that matches the specified filter in the request. """ nextPageToken = _messages.StringField(1) operations = _messages.MessageField('Operation', 2, repeated=True) class Location(_messages.Message): """A resource that represents Google Cloud Platform location. Messages: LabelsValue: Cross-service attributes for the location. For example {"cloud.googleapis.com/region": "us-east1"} MetadataValue: Service-specific metadata. For example the available capacity at the given location. Fields: labels: Cross-service attributes for the location. For example {"cloud.googleapis.com/region": "us-east1"} locationId: The canonical id for this location. For example: `"us-east1"`. metadata: Service-specific metadata. For example the available capacity at the given location. name: Resource name for the location, which may vary between implementations. For example: `"projects/example-project/locations/us- east1"` """ @encoding.MapUnrecognizedFields('additionalProperties') class LabelsValue(_messages.Message): """Cross-service attributes for the location. For example {"cloud.googleapis.com/region": "us-east1"} Messages: AdditionalProperty: An additional property for a LabelsValue object. Fields: additionalProperties: Additional properties of type LabelsValue """ class AdditionalProperty(_messages.Message): """An additional property for a LabelsValue object. Fields: key: Name of the additional property. value: A string attribute. """ key = _messages.StringField(1) value = _messages.StringField(2) additionalProperties = _messages.MessageField('AdditionalProperty', 1, repeated=True) @encoding.MapUnrecognizedFields('additionalProperties') class MetadataValue(_messages.Message): """Service-specific metadata. For example the available capacity at the given location. Messages: AdditionalProperty: An additional property for a MetadataValue object. Fields: additionalProperties: Properties of the object. Contains field @type with type URL. """ class AdditionalProperty(_messages.Message): """An additional property for a MetadataValue object. Fields: key: Name of the additional property. value: A extra_types.JsonValue attribute. """ key = _messages.StringField(1) value = _messages.MessageField('extra_types.JsonValue', 2) additionalProperties = _messages.MessageField('AdditionalProperty', 1, repeated=True) labels = _messages.MessageField('LabelsValue', 1) locationId = _messages.StringField(2) metadata = _messages.MessageField('MetadataValue', 3) name = _messages.StringField(4) class Node(_messages.Message): """An instance. Enums: StateValueValuesEnum: This contains a current state for the accelerator. Output only. Fields: acceleratorType: The type of hardware accelerators associated with this node. cidrBlock: The user must supply a CIDR block that the TPU node will use when selecting an IP address. This CIDR block must be a /29 block; the GCE networks API forbids a smaller block, and using a larger block would be wasteful (a node can only consume one IP address). Errors will occur if the CIDR block has already been used for a currently existing TPU node, the CIDR block conflicts with any subnetworks in the user's provided network, or the provided network is peered with another network that is using that CIDR block. createTime: The time when the node was created. Output only. description: User-supplied description of the TPU. Maximum of 512 characters. healthDescription: Human readable description of why the service is unhealthy. Output only. ipAddress: The network address for the TPU as visible to other GCE instances. Output only. machineType: A string attribute. name: Immutable name of the TPU network: The user specifies the name of a network they wish to peer the TPU node to. It must be a preexisting GCE network inside of the project on which this API has been activated. If none is provided, "default" will be used. port: The network port for the TPU as visible to other GCE instances. Output only. serviceAccount: The service account used to run the tensor flow services within the node. To share resources, including Google Cloud Storage data, with the Tensorflow job running in the Node, this account must have permissions to that data. Output only. state: This contains a current state for the accelerator. Output only. tensorflowVersion: The version of Tensorflow running in the Node. """ class StateValueValuesEnum(_messages.Enum): """This contains a current state for the accelerator. Output only. Values: STATE_UNSPECIFIED: TPU node state is not known/set. CREATING: TPU node is being created. READY: TPU node has been created and is fully usable. RESTARTING: TPU node is restarting. REIMAGING: TPU node is undergoing reimaging. DELETING: TPU node is being deleted. REPAIRING: TPU node is being repaired and may be unusable. Details can be found in the `help_description` field. """ STATE_UNSPECIFIED = 0 CREATING = 1 READY = 2 RESTARTING = 3 REIMAGING = 4 DELETING = 5 REPAIRING = 6 acceleratorType = _messages.StringField(1) cidrBlock = _messages.StringField(2) createTime = _messages.StringField(3) description = _messages.StringField(4) healthDescription = _messages.StringField(5) ipAddress = _messages.StringField(6) machineType = _messages.StringField(7) name = _messages.StringField(8) network = _messages.StringField(9) port = _messages.StringField(10) serviceAccount = _messages.StringField(11) state = _messages.EnumField('StateValueValuesEnum', 12) tensorflowVersion = _messages.StringField(13) class Operation(_messages.Message): """This resource represents a long-running operation that is the result of a network API call. Messages: MetadataValue: Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. ResponseValue: The normal response of the operation in case of success. If the original method returns no data on success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`. Fields: done: If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. error: The error result of the operation in case of failure or cancellation. metadata: Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. name: The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should have the format of `operations/some/unique/name`. response: The normal response of the operation in case of success. If the original method returns no data on success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`. """ @encoding.MapUnrecognizedFields('additionalProperties') class MetadataValue(_messages.Message): """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. Messages: AdditionalProperty: An additional property for a MetadataValue object. Fields: additionalProperties: Properties of the object. Contains field @type with type URL. """ class AdditionalProperty(_messages.Message): """An additional property for a MetadataValue object. Fields: key: Name of the additional property. value: A extra_types.JsonValue attribute. """ key = _messages.StringField(1) value = _messages.MessageField('extra_types.JsonValue', 2) additionalProperties = _messages.MessageField('AdditionalProperty', 1, repeated=True) @encoding.MapUnrecognizedFields('additionalProperties') class ResponseValue(_messages.Message): """The normal response of the operation in case of success. If the original method returns no data on success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`. Messages: AdditionalProperty: An additional property for a ResponseValue object. Fields: additionalProperties: Properties of the object. Contains field @type with type URL. """ class AdditionalProperty(_messages.Message): """An additional property for a ResponseValue object. Fields: key: Name of the additional property. value: A extra_types.JsonValue attribute. """ key = _messages.StringField(1) value = _messages.MessageField('extra_types.JsonValue', 2) additionalProperties = _messages.MessageField('AdditionalProperty', 1, repeated=True) done = _messages.BooleanField(1) error = _messages.MessageField('Status', 2) metadata = _messages.MessageField('MetadataValue', 3) name = _messages.StringField(4) response = _messages.MessageField('ResponseValue', 5) class OperationMetadata(_messages.Message): """Represents the metadata of the long-running operation. Fields: apiVersion: [Output only] API version used to start the operation. cancelRequested: [Output only] Identifies whether the user has requested cancellation of the operation. Operations that have successfully been cancelled have Operation.error value with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`. createTime: [Output only] The time the operation was created. endTime: [Output only] The time the operation finished running. statusDetail: [Output only] Human-readable status of the operation, if any. target: [Output only] Server-defined resource path for the target of the operation. verb: [Output only] Name of the verb executed by the operation. """ apiVersion = _messages.StringField(1) cancelRequested = _messages.BooleanField(2) createTime = _messages.StringField(3) endTime = _messages.StringField(4) statusDetail = _messages.StringField(5) target = _messages.StringField(6) verb = _messages.StringField(7) class StandardQueryParameters(_messages.Message): """Query parameters accepted by all methods. Enums: FXgafvValueValuesEnum: V1 error format. AltValueValuesEnum: Data format for response. Fields: f__xgafv: V1 error format. access_token: OAuth access token. alt: Data format for response. bearer_token: OAuth bearer token. callback: JSONP fields: Selector specifying which fields to include in a partial response. key: API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. oauth_token: OAuth 2.0 token for the current user. pp: Pretty-print response. prettyPrint: Returns response with indentations and line breaks. quotaUser: Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. trace: A tracing token of the form "token:<tokenid>" to include in api requests. uploadType: Legacy upload protocol for media (e.g. "media", "multipart"). upload_protocol: Upload protocol for media (e.g. "raw", "multipart"). """ class AltValueValuesEnum(_messages.Enum): """Data format for response. Values: json: Responses with Content-Type of application/json media: Media download with context-dependent Content-Type proto: Responses with Content-Type of application/x-protobuf """ json = 0 media = 1 proto = 2 class FXgafvValueValuesEnum(_messages.Enum): """V1 error format. Values: _1: v1 error format _2: v2 error format """ _1 = 0 _2 = 1 f__xgafv = _messages.EnumField('FXgafvValueValuesEnum', 1) access_token = _messages.StringField(2) alt = _messages.EnumField('AltValueValuesEnum', 3, default=u'json') bearer_token = _messages.StringField(4) callback = _messages.StringField(5) fields = _messages.StringField(6) key = _messages.StringField(7) oauth_token = _messages.StringField(8) pp = _messages.BooleanField(9, default=True) prettyPrint = _messages.BooleanField(10, default=True) quotaUser = _messages.StringField(11) trace = _messages.StringField(12) uploadType = _messages.StringField(13) upload_protocol = _messages.StringField(14) class Status(_messages.Message): """The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). The error model is designed to be: - Simple to use and understand for most users - Flexible enough to meet unexpected needs # Overview The `Status` message contains three pieces of data: error code, error message, and error details. The error code should be an enum value of google.rpc.Code, but it may accept additional error codes if needed. The error message should be a developer-facing English message that helps developers *understand* and *resolve* the error. If a localized user-facing error message is needed, put the localized message in the error details or localize it in the client. The optional error details may contain arbitrary information about the error. There is a predefined set of error detail types in the package `google.rpc` that can be used for common error conditions. # Language mapping The `Status` message is the logical representation of the error model, but it is not necessarily the actual wire format. When the `Status` message is exposed in different client libraries and different wire protocols, it can be mapped differently. For example, it will likely be mapped to some exceptions in Java, but more likely mapped to some error codes in C. # Other uses The error model and the `Status` message can be used in a variety of environments, either with or without APIs, to provide a consistent developer experience across different environments. Example uses of this error model include: - Partial errors. If a service needs to return partial errors to the client, it may embed the `Status` in the normal response to indicate the partial errors. - Workflow errors. A typical workflow has multiple steps. Each step may have a `Status` message for error reporting. - Batch operations. If a client uses batch request and batch response, the `Status` message should be used directly inside batch response, one for each error sub- response. - Asynchronous operations. If an API call embeds asynchronous operation results in its response, the status of those operations should be represented directly using the `Status` message. - Logging. If some API errors are stored in logs, the message `Status` could be used directly after any stripping needed for security/privacy reasons. Messages: DetailsValueListEntry: A DetailsValueListEntry object. Fields: code: The status code, which should be an enum value of google.rpc.Code. details: A list of messages that carry the error details. There is a common set of message types for APIs to use. message: A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. """ @encoding.MapUnrecognizedFields('additionalProperties') class DetailsValueListEntry(_messages.Message): """A DetailsValueListEntry object. Messages: AdditionalProperty: An additional property for a DetailsValueListEntry object. Fields: additionalProperties: Properties of the object. Contains field @type with type URL. """ class AdditionalProperty(_messages.Message): """An additional property for a DetailsValueListEntry object. Fields: key: Name of the additional property. value: A extra_types.JsonValue attribute. """ key = _messages.StringField(1) value = _messages.MessageField('extra_types.JsonValue', 2) additionalProperties = _messages.MessageField('AdditionalProperty', 1, repeated=True) code = _messages.IntegerField(1, variant=_messages.Variant.INT32) details = _messages.MessageField('DetailsValueListEntry', 2, repeated=True) message = _messages.StringField(3) class TpuProjectsLocationsGetRequest(_messages.Message): """A TpuProjectsLocationsGetRequest object. Fields: name: Resource name for the location. """ name = _messages.StringField(1, required=True) class TpuProjectsLocationsListRequest(_messages.Message): """A TpuProjectsLocationsListRequest object. Fields: filter: The standard list filter. name: The resource that owns the locations collection, if applicable. pageSize: The standard list page size. pageToken: The standard list page token. """ filter = _messages.StringField(1) name = _messages.StringField(2, required=True) pageSize = _messages.IntegerField(3, variant=_messages.Variant.INT32) pageToken = _messages.StringField(4) class TpuProjectsLocationsNodesCreateRequest(_messages.Message): """A TpuProjectsLocationsNodesCreateRequest object. Fields: node: A Node resource to be passed as the request body. nodeId: The unqualified resource name. parent: The parent resource name. serviceAccount: Allows user to set the service account running on the TPU node's workers. """ node = _messages.MessageField('Node', 1) nodeId = _messages.StringField(2) parent = _messages.StringField(3, required=True) serviceAccount = _messages.StringField(4) class TpuProjectsLocationsNodesDeleteRequest(_messages.Message): """A TpuProjectsLocationsNodesDeleteRequest object. Fields: name: The resource name. """ name = _messages.StringField(1, required=True) class TpuProjectsLocationsNodesGetRequest(_messages.Message): """A TpuProjectsLocationsNodesGetRequest object. Fields: name: The resource name. """ name = _messages.StringField(1, required=True) class TpuProjectsLocationsNodesListRequest(_messages.Message): """A TpuProjectsLocationsNodesListRequest object. Fields: pageSize: The maximum number of items to return. pageToken: The next_page_token value returned from a previous List request, if any. parent: The parent resource name. """ pageSize = _messages.IntegerField(1, variant=_messages.Variant.INT32) pageToken = _messages.StringField(2) parent = _messages.StringField(3, required=True) class TpuProjectsLocationsNodesReimageRequest(_messages.Message): """A TpuProjectsLocationsNodesReimageRequest object. Fields: name: The resource name. tensorflowVersion: The version for reimage to create. """ name = _messages.StringField(1, required=True) tensorflowVersion = _messages.StringField(2) class TpuProjectsLocationsNodesResetRequest(_messages.Message): """A TpuProjectsLocationsNodesResetRequest object. Fields: name: The resource name. """ name = _messages.StringField(1, required=True) class TpuProjectsLocationsNodesUpdateStateRequest(_messages.Message): """A TpuProjectsLocationsNodesUpdateStateRequest object. Enums: StateValueValuesEnum: The state the node should be in after update. Fields: name: The resource name. state: The state the node should be in after update. """ class StateValueValuesEnum(_messages.Enum): """The state the node should be in after update. Values: STATE_UNSPECIFIED: <no description> CREATING: <no description> READY: <no description> RESTARTING: <no description> REIMAGING: <no description> DELETING: <no description> REPAIRING: <no description> """ STATE_UNSPECIFIED = 0 CREATING = 1 READY = 2 RESTARTING = 3 REIMAGING = 4 DELETING = 5 REPAIRING = 6 name = _messages.StringField(1, required=True) state = _messages.EnumField('StateValueValuesEnum', 2) class TpuProjectsLocationsOperationsDeleteRequest(_messages.Message): """A TpuProjectsLocationsOperationsDeleteRequest object. Fields: name: The name of the operation resource to be deleted. """ name = _messages.StringField(1, required=True) class TpuProjectsLocationsOperationsGetRequest(_messages.Message): """A TpuProjectsLocationsOperationsGetRequest object. Fields: name: The name of the operation resource. """ name = _messages.StringField(1, required=True) class TpuProjectsLocationsOperationsListRequest(_messages.Message): """A TpuProjectsLocationsOperationsListRequest object. Fields: filter: The standard list filter. name: The name of the operation's parent resource. pageSize: The standard list page size. pageToken: The standard list page token. """ filter = _messages.StringField(1) name = _messages.StringField(2, required=True) pageSize = _messages.IntegerField(3, variant=_messages.Variant.INT32) pageToken = _messages.StringField(4) encoding.AddCustomJsonFieldMapping( StandardQueryParameters, 'f__xgafv', '$.xgafv') encoding.AddCustomJsonEnumMapping( StandardQueryParameters.FXgafvValueValuesEnum, '_1', '1') encoding.AddCustomJsonEnumMapping( StandardQueryParameters.FXgafvValueValuesEnum, '_2', '2')
[ "kirkse710@gmail.com" ]
kirkse710@gmail.com
292069701c70dfc1310c0ae3d406323bae424447
41679cbf83a1339e26513ce1aee09eef9f9b7629
/tests/dependency-classic/setup.py
2fb80d725a7ccc6993867726b137062c62503e12
[ "MIT" ]
permissive
mtkennerly/poetry-dynamic-versioning
db68eb7a3487e042c12820e65844335b62ba9bd4
322fe62f5a5270d324ca8a12b42224f67e822d2e
refs/heads/master
2023-07-20T10:30:17.257360
2023-07-11T15:50:51
2023-07-11T15:50:51
190,498,619
486
31
MIT
2023-09-05T01:33:23
2019-06-06T02:13:29
Python
UTF-8
Python
false
false
117
py
from setuptools import setup setup(name="dependency-classic", version="0.0.666", py_modules=["dependency_classic"])
[ "mtkennerly@gmail.com" ]
mtkennerly@gmail.com
3d2281ceea099e3636a2d5593f4e69d3ab66ddbf
c7846ee0828539c2a2019928c1cbf3abd35665bf
/1226.py
e40445bed21211b32f058a29fb64d1cef368c25a
[]
no_license
whiteblue0/sw_problems
10476601c8d6d68d42e2f30af87fcde1e5dbbcc5
1cefc6236cccc20477bf4eadb458a0fd06b09126
refs/heads/master
2020-06-20T10:44:57.463275
2020-05-03T07:27:57
2020-05-03T07:27:57
197,098,448
0
0
null
null
null
null
UTF-8
Python
false
false
881
py
import sys sys.stdin = open('1226.txt') def ispass(y,x): if 0<=y<L and 0<=x<L and data[y][x] != 1 and visited[y][x] == 0: return True else: return False def DFS(sy,sx): global end visited[sy][sx] = 1 if data[sy][sx] == 3: end = 1 for i in range(4): ny = sy + dy[i] nx = sx + dx[i] if ispass(ny, nx): visited[ny][nx] = 1 DFS(ny,nx) # 우하좌상 dy = [0,1,0,-1] dx = [1,0,-1,0] T = 10 for tc in range(1,T+1): N = int(input()) L = 16 data = [list(map(int, input())) for _ in range(L)] visited = [[0]*L for _ in range(L)] for i in range(L): for j in range(L): if data[i][j] == 2: start = (i,j) end = 0 DFS(start[0],start[1]) # for i in range(L): # print(visited[i]) print('#{} {}'.format(tc,end))
[ "21port@naver.com" ]
21port@naver.com
b422f8f7fab0c031a2544141bf37274393b39d00
24192756f1275986078c083412ee0b209bae649f
/donghee_project/donghee_project/urls.py
2de9d8f673a9a270dad68cc545cab23c2460ba4e
[]
no_license
penpen-dongE/django_todolist_project
0128498a7a9973d4fffefbf320d77044b6916530
ceeb5d249d7988677b55a690ee92fb74257e311c
refs/heads/master
2022-05-10T03:24:18.132484
2020-04-23T12:13:48
2020-04-23T12:13:48
255,940,607
0
0
null
null
null
null
UTF-8
Python
false
false
1,432
py
"""donghee_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from home.views import home_view from home.views import quote_view from home.views import var_view from home.views import nums_view from todo.views import todo_view from todo.views import todo_progress_view from todo.views import delete_todo from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', home_view), path('quote/', quote_view), path('var/', var_view), path('num/', nums_view), path('todos/', todo_view, name="todos"), path('todos/in_progress', todo_progress_view, name="todos_in_progress"), path('todos/<pk>/delete', delete_todo, name="todo_del"), ] # urlpatterns += \ # static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
[ "dongheepark.dev@gmail.com" ]
dongheepark.dev@gmail.com
0296d247cff0d46ffe781196db159f2dc53ad9a7
0dc3e9b70da8ccd056e0a0fab2b1d8f850c3d470
/lantern/django/django_celery/src/apps/dealers/models.py
bc779127742bd20a2e9942ebdd4779103f3156e4
[]
no_license
ArturYefriemov/green_lantern
28e7150af7b9d2281a107ad80026828ad77af62a
2841b647e1bfae4a7505e91e8a8695d03f35a3a2
refs/heads/master
2021-03-01T16:54:58.881835
2020-11-17T19:42:23
2020-11-17T19:42:23
245,799,969
0
0
null
2020-07-14T18:51:13
2020-03-08T11:13:32
Python
UTF-8
Python
false
false
735
py
from django.contrib.auth.models import AbstractUser from django.db import models # Create your models here. class Country(models.Model): name = models.CharField(max_length=32, unique=True) class City(models.Model): name = models.CharField(max_length=32, db_index=True) country = models.ForeignKey(to='Country', on_delete=models.CASCADE, null=True) class Address(models.Model): address1 = models.CharField(max_length=128) address2 = models.CharField(max_length=128, blank=True) zip_code = models.PositiveSmallIntegerField() city = models.ForeignKey(to='City', on_delete=models.CASCADE) class Dealer(AbstractUser): address = models.ForeignKey(to='Address', on_delete=models.CASCADE, null=True)
[ "odarchenko@ex.ua" ]
odarchenko@ex.ua
127026945e89da6d871b6e151af9d6241f3867e5
200a7fb2a75151a8b83274ef53d661099da61047
/django1_workspace/test4(get)/blues/ddobaki/models.py
d6d5a45b52187cd3bb993d21ac6fa65d5fbb1010
[]
no_license
Minzard/Correctable-Pronunciation
9e967e428f38b2a142e81d1d181caba9bc56305a
4b94d6e07c0c682086595c202fc5fa41106a9df5
refs/heads/master
2021-06-21T03:13:44.751861
2020-12-29T02:05:22
2020-12-29T02:05:22
157,420,423
13
6
null
null
null
null
UTF-8
Python
false
false
353
py
from django.db import models class get_ddobaki(models.Model): user = models.CharField(max_length=100) label = models.CharField(max_length=50) stt = models.CharField(max_length=50) class post_ddobaki(models.Model): divided_stt = models.CharField(max_length=100) color = models.BooleanField(default=True) # Create your models here.
[ "eh@EHui-MacBook-Pro.local" ]
eh@EHui-MacBook-Pro.local
a0a0950be83e34b71b9196a40ad2399172c4477c
9636c75094a251fc931774c967df135b31012101
/school_mgnt/wsgi.py
a09c0a72615f55cd2c45d10991c74db785214fe0
[]
no_license
bimal125/school_mgnt
9e33bb7f9ae580292eb687dc4955bc54c07a8bd8
01fd33cb2547494cda2213061af443e706dc92d9
refs/heads/master
2022-12-10T00:53:13.106358
2020-08-27T15:07:05
2020-08-27T15:07:05
205,401,910
0
0
null
null
null
null
UTF-8
Python
false
false
399
py
""" WSGI config for school_mgnt project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'school_mgnt.settings') application = get_wsgi_application()
[ "pandeybi125@gmail.com" ]
pandeybi125@gmail.com
99102bee439d4e4060ed9c0a44aa1bfe3bb55191
29cc8671d2b4cfb3551bf822751130e769e2651d
/5multipless.py
9bfcc567ee6656d325b20c4dee4507fc11eb7655
[]
no_license
raghava430/Raghava-reddy
67360cf955e8c77e7fc7732eb70feb72fb19b3fe
5e952e0d129427705ad540052757b895ffb38542
refs/heads/master
2020-06-14T10:05:13.429124
2019-07-17T04:35:11
2019-07-17T04:35:11
194,976,566
0
1
null
null
null
null
UTF-8
Python
false
false
78
py
e=int(input()) f=1 while(f<6): g=e*f f=f+1 print(g,end=" ")
[ "noreply@github.com" ]
noreply@github.com
de172a8f044e0de1b739d483985f14cd2fb74c27
2d7d5673d78d6ef682e88845eab99dddd8fc0927
/pybaseball/pybaseball/league_pitching_stats.py
cc3eb29485ad7ce43526b1c031e88f3b522029c8
[ "MIT" ]
permissive
BunkyFeats/MLBpy
764026d42afcdd979084b28d851a7d536a0ac70d
d035f904bea08fb73545b333d6f3448b1cb20ab0
refs/heads/master
2021-04-26T23:40:06.190324
2018-03-04T22:35:48
2018-03-04T22:35:48
123,835,303
1
0
null
null
null
null
UTF-8
Python
false
false
5,262
py
import requests import pandas as pd import numpy as np import io from bs4 import BeautifulSoup import datetime def validate_datestring(date_text): try: datetime.datetime.strptime(date_text, '%Y-%m-%d') except ValueError: raise ValueError("Incorrect data format, should be YYYY-MM-DD") def sanitize_input(start_dt, end_dt): # if no dates are supplied, assume they want yesterday's data # send a warning in case they wanted to specify if start_dt is None and end_dt is None: today = datetime.datetime.today() start_dt = (today - datetime.timedelta(1)).strftime("%Y-%m-%d") end_dt = today.strftime("%Y-%m-%d") print("Warning: no date range supplied. Returning yesterday's data. For a different date range, try pitching_stats_range(start_dt, end_dt) or pitching_stats(season).") #if only one date is supplied, assume they only want that day's stats #query in this case is from date 1 to date 1 if start_dt is None: start_dt = end_dt if end_dt is None: end_dt = start_dt #if end date occurs before start date, swap them if end_dt < start_dt: temp = start_dt start_dt = end_dt end_dt = temp # now that both dates are not None, make sure they are valid date strings validate_datestring(start_dt) validate_datestring(end_dt) return start_dt, end_dt def get_soup(start_dt, end_dt): # get most recent standings if date not specified if((start_dt is None) or (end_dt is None)): print('Error: a date range needs to be specified') return None url = "http://www.baseball-reference.com/leagues/daily.cgi?user_team=&bust_cache=&type=p&lastndays=7&dates=fromandto&fromandto={}.{}&level=mlb&franch=&stat=&stat_value=0".format(start_dt, end_dt) s = requests.get(url).content return BeautifulSoup(s, "html.parser") def get_table(soup): table = soup.find_all('table')[0] data = [] headings = [th.get_text() for th in table.find("tr").find_all("th")][1:] data.append(headings) table_body = table.find('tbody') rows = table_body.find_all('tr') for row in rows: cols = row.find_all('td') cols = [ele.text.strip() for ele in cols] data.append([ele for ele in cols]) data = pd.DataFrame(data) data = data.rename(columns=data.iloc[0]) data = data.reindex(data.index.drop(0)) return data def pitching_stats_range(start_dt=None, end_dt=None): """ Get all pitching stats for a set time range. This can be the past week, the month of August, anything. Just supply the start and end date in YYYY-MM-DD format. """ # ensure valid date strings, perform necessary processing for query start_dt, end_dt = sanitize_input(start_dt, end_dt) if datetime.datetime.strptime(start_dt, "%Y-%m-%d").year < 2008: raise ValueError("Year must be 2008 or later") if datetime.datetime.strptime(end_dt, "%Y-%m-%d").year < 2008: raise ValueError("Year must be 2008 or later") # retrieve html from baseball reference soup = get_soup(start_dt, end_dt) table = get_table(soup) table = table.dropna(how='all') # drop if all columns are NA #fix some strange formatting for percentage columns table = table.replace('---%', np.nan) #make sure these are all numeric for column in ['Age', '#days', 'G', 'GS', 'W', 'L', 'SV', 'IP', 'H', 'R', 'ER', 'BB', 'SO', 'HR', 'HBP', 'ERA', 'AB', '2B', '3B', 'IBB', 'GDP', 'SF', 'SB', 'CS', 'PO', 'BF', 'Pit', 'WHIP', 'BAbip', 'SO9', 'SO/W']: table[column] = pd.to_numeric(table[column]) #convert str(xx%) values to float(0.XX) decimal values for column in ['Str', 'StL', 'StS', 'GB/FB', 'LD', 'PU']: table[column] = table[column].replace('%','',regex=True).astype('float')/100 table = table.drop('',1) return table def pitching_stats_bref(season=None): """ Get all pitching stats for a set season. If no argument is supplied, gives stats for current season to date. """ if season is None: season = datetime.datetime.today().strftime("%Y") season = str(season) start_dt = season + '-03-01' #opening day is always late march or early april end_dt = season + '-11-01' #season is definitely over by November return(pitching_stats_range(start_dt, end_dt)) def bwar_pitch(return_all=False): """ Get data from war_daily_pitch table. Returns WAR, its components, and a few other useful stats. To get all fields from this table, supply argument return_all=True. """ url = "http://www.baseball-reference.com/data/war_daily_pitch.txt" s = requests.get(url).content c=pd.read_csv(io.StringIO(s.decode('utf-8'))) if return_all: return c else: cols_to_keep = ['name_common', 'mlb_ID', 'player_ID', 'year_ID', 'team_ID', 'stint_ID', 'lg_ID', 'G', 'GS', 'RA','xRA', 'BIP', 'BIP_perc','salary', 'ERA_plus', 'WAR_rep', 'WAA', 'WAA_adj','WAR'] return c[cols_to_keep]
[ "noreply@github.com" ]
noreply@github.com
6f73725146e0aa41a0092ee3c4592b5a5dd9124d
b6282963725f1b44e29a11e4ea2479e0667c3b1a
/src/chapter04/demo01.py
f803bdb96f4e21d92e98b40c31dfdb70d8cb6bcd
[]
no_license
geekori/numpy
d2859f56e80a3ab0ea4a33bcb4bc8494dedbb879
e3b18aa6868c1f98963f01875f9afa7ee86f1bf2
refs/heads/master
2020-04-09T07:44:22.074173
2018-12-03T10:01:59
2018-12-03T10:01:59
160,168,662
0
1
null
null
null
null
UTF-8
Python
false
false
203
py
# NumPy高级函数:计算协方差矩阵 from numpy import * a = array([1,3,4,5]) b = array([2,6,2,2]) x = vstack((a,b)) print(x) print(cov(x)) # cov函数会将正常的结果缩小到原来的1/3
[ "282662996@qq.com" ]
282662996@qq.com
c92030d52698c79b7c903ded6e22f72bf6b89f32
3c176f8c73b157f6aba150d869cefe64b7f0a4d7
/app.py
a3686b206616eecff5056f175889e91a251507e1
[]
no_license
ddev790/image_recommender_selectivesearch
5be5a9659bb98b2f75bfd12ed7582e290d30522d
374904c7be88abfeba2b00df735fd26c519081ad
refs/heads/master
2021-08-11T21:00:59.213932
2017-11-14T04:50:52
2017-11-14T04:50:52
110,641,235
0
0
null
null
null
null
UTF-8
Python
false
false
2,653
py
import os import random import time import requests import sys import simplejson from flask import Flask, request, render_template, session, flash, redirect from celery import Celery import json from psycopg2.extensions import AsIs import psycopg2 from image_process import populate_db app = Flask(__name__) # Initialize Celery celery = Celery(app.name, broker='redis://localhost:6379/0') celery.conf.update(app.config) @celery.task(name="segmentation") def segmentation(image_url, enterprise_id, model_name, model_id): val = populate_db(image_url, enterprise_id, model_name, model_id) print(val) r = requests.post("/callback_url/", data=json.dumps(val)) dataJSON = json.dumps({"image_url": image_url, "callback_url": "/callback_url/"}) return dataJSON @app.route('/segment/<enterprise_id>/<model_name>/<model_id>', methods=['POST']) def insert_data(enterprise_id, model_name, model_id): if request.method == 'POST': content = request.json print(content) image_url = content["image_url"] # segmentation(image_url, enterprise_id, model_name, model_id) segmentation.delay(image_url, enterprise_id, model_name, model_id) return json.dumps({"image_url": image_url, "callback_url": "http://127.0.0.1:5000/callback_url/"}) # // celery process - insert into database - (url will be provided) @app.route('/callback_url', methods=["POST"]) def callback_response(image_name): if request.method == 'POST': content = request.json print(content) # return dataJSON @app.route('/features/<enterprise_id>/<model_name>/<model_id>/<segment_id>', methods=["GET"]) def features(enterprise_id, model_name, model_id, segment_id): dataJSON = {} con = None try: # connect to the PostgreSQL server con = psycopg2.connect("host='localhost' dbname='image_recommender' user='postgres' password='admin'") cur = con.cursor() query_select = "Select enterprise_id,model_name,segment_id,model_id,features from k where segment_id='" + segment_id + "'" cur.execute(query_select) columns = cur.description d = {} for value in cur.fetchall(): for index, column in enumerate(value): k = columns[index][0] if k == 'segment_id': d[k] = str(column) else: d[k] = column except (Exception, psycopg2.DatabaseError) as error: print(error) sys.exit(1) finally: if con is not None: con.close() return json.dumps(d) if __name__ == "__main__": app.run(debug=True)
[ "admin_yosemite_mac" ]
admin_yosemite_mac
0f12e75f326736ce1da7a7a6b1fb5297088bafd5
5bfbf31332a5c4750ab57d305f400aa5e20bf6bd
/contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_utah_zip.py
5c11f0c756f7c389107ebd4a9b7e6f5e7f2270a7
[ "Apache-2.0" ]
permissive
alexsherstinsky/great_expectations
9d4ae4c06546c5ab2ee0d04fb7840e3515c25677
2fc4bb36a5b3791c8ada97c5364531cd7510d4ed
refs/heads/develop
2023-08-04T13:13:38.978967
2023-07-24T18:29:46
2023-07-24T18:29:46
203,888,556
1
0
Apache-2.0
2020-07-27T09:12:21
2019-08-22T23:31:19
Python
UTF-8
Python
false
false
5,481
py
from typing import Optional import zipcodes from great_expectations.core.expectation_configuration import ExpectationConfiguration from great_expectations.execution_engine import PandasExecutionEngine from great_expectations.expectations.expectation import ColumnMapExpectation from great_expectations.expectations.metrics import ( ColumnMapMetricProvider, column_condition_partial, ) def is_valid_utah_zip(zip: str): list_of_dicts_of_utah_zips = zipcodes.filter_by(state="UT") list_of_utah_zips = [d["zip_code"] for d in list_of_dicts_of_utah_zips] if len(zip) > 10: return False elif type(zip) != str: return False elif zip in list_of_utah_zips: return True else: return False # This class defines a Metric to support your Expectation. # For most ColumnMapExpectations, the main business logic for calculation will live in this class. class ColumnValuesToBeValidUtahZip(ColumnMapMetricProvider): # This is the id string that will be used to reference your metric. condition_metric_name = "column_values.valid_utah_zip" # This method implements the core logic for the PandasExecutionEngine @column_condition_partial(engine=PandasExecutionEngine) def _pandas(cls, column, **kwargs): return column.apply(lambda x: is_valid_utah_zip(x)) # This method defines the business logic for evaluating your metric when using a SqlAlchemyExecutionEngine # @column_condition_partial(engine=SqlAlchemyExecutionEngine) # def _sqlalchemy(cls, column, _dialect, **kwargs): # raise NotImplementedError # This method defines the business logic for evaluating your metric when using a SparkDFExecutionEngine # @column_condition_partial(engine=SparkDFExecutionEngine) # def _spark(cls, column, **kwargs): # raise NotImplementedError # This class defines the Expectation itself class ExpectColumnValuesToBeValidUtahZip(ColumnMapExpectation): """Expect values in this column to be valid Utah zipcodes. See https://pypi.org/project/zipcodes/ for more information. """ # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [ { "data": { "valid_utah_zip": ["84001", "84320", "84713", "84791"], "invalid_utah_zip": ["-10000", "1234", "99999", "25487"], }, "tests": [ { "title": "basic_positive_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "valid_utah_zip"}, "out": {"success": True}, }, { "title": "basic_negative_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "invalid_utah_zip"}, "out": {"success": False}, }, ], } ] # This is the id string of the Metric used by this Expectation. # For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above. map_metric = "column_values.valid_utah_zip" # This is a list of parameter names that can affect whether the Expectation evaluates to True or False success_keys = ("mostly",) # This dictionary contains default values for any parameters that should have default values default_kwarg_values = {} def validate_configuration( self, configuration: Optional[ExpectationConfiguration] = None ) -> None: """ Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that necessary configuration arguments have been provided for the validation of the expectation. Args: configuration (OPTIONAL[ExpectationConfiguration]): \ An optional Expectation Configuration entry that will be used to configure the expectation Returns: None. Raises InvalidExpectationConfigurationError if the config is not validated successfully """ super().validate_configuration(configuration) configuration = configuration or self.configuration # # Check other things in configuration.kwargs and raise Exceptions if needed # try: # assert ( # ... # ), "message" # assert ( # ... # ), "message" # except AssertionError as e: # raise InvalidExpectationConfigurationError(str(e)) # This object contains metadata for display in the public Gallery library_metadata = { "maturity": "experimental", # "experimental", "beta", or "production" "tags": [ "hackathon", "typed-entities", ], # Tags for this Expectation in the Gallery "contributors": [ # Github handles for all contributors to this Expectation. "@luismdiaz01", "@derekma73", # Don't forget to add your github handle here! ], "requirements": ["zipcodes"], } if __name__ == "__main__": ExpectColumnValuesToBeValidUtahZip().print_diagnostic_checklist()
[ "noreply@github.com" ]
noreply@github.com
cb221e365a5489dbd72b5c99e681b6870802a23a
70ae772afdabea4213c64ac1e8b824a2dd258611
/FaceRecognition/recognize_specific_face_def.py
e5de6cd5d2c65262dd9fe9894366d3690ead13da
[]
no_license
IdoSeri/DavidsonProject
aa54dc3f07e09ac2a0a9c844a52f6ee5a4ff225c
87dbd48628ece0d55eed4c76d82b63100ce51ca4
refs/heads/master
2022-04-16T22:33:11.923149
2020-04-16T09:47:40
2020-04-16T09:47:40
250,328,967
1
1
null
null
null
null
UTF-8
Python
false
false
2,025
py
# import the necessary packages from imutils.video import VideoStream import face_recognition import imutils import pickle import time import cv2 def recognize_face(): # load the known faces and embeddings data = pickle.loads(open("FaceRecognition/encodings.pickle", "rb").read()) # initialize the video stream vs = VideoStream(src=0).start() time.sleep(2.0) name ="" # loop over frames from the video file stream while name=="": # grab the frame from the threaded video stream frame = vs.read() # convert the input frame from BGR to RGB then resize it to have # a width of 750px (to speedup processing) rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) rgb = imutils.resize(frame, width=750) r = frame.shape[1] / float(rgb.shape[1]) # detect the (x, y)-coordinates of the bounding boxes corresponding to each face in the frame boxes= face_recognition.face_locations(rgb, model="cnn") # compute the facial embeddings for each face encodings = face_recognition.face_encodings(rgb, boxes) # loop over the facial embeddings for encoding in encodings: # attempt to match each face in the input image to our known encodings matches = face_recognition.compare_faces(data["encodings"], encoding) # check to see if we have found a match if True in matches: # find the indexes of all matched faces then initialize a # dictionary to count the total number of times each face # was matched matchedIdxs = [i for (i, b) in enumerate(matches) if b] counts = {} # loop over the matched indexes and maintain a count for # each recognized face face for i in matchedIdxs: name = data["names"][i] counts[name] = counts.get(name, 0) + 1 # determine the recognized face with the largest number # of votes (note: in the event of an unlikely tie Python # will select first entry in the dictionary) name = max(counts, key=counts.get) # cleanup cv2.destroyAllWindows() vs.stop() # send the recognized name return name
[ "noreply@github.com" ]
noreply@github.com
6c77b0407a9a802d567bc0923cd32c4be391bf5a
6c47652bc93ceef2b054fa9759481e70a22de2f1
/225_Fig2g_diableN_y.py
4cca2a370829a583b5c2fbe0d662617cc0710a97
[]
no_license
peakqi/RaI
4c174840ce5affa4dde3990892fb48903b9766a2
6528cc100506e3a491d665d09d620ac9be3013a3
refs/heads/master
2020-05-25T10:47:43.976805
2019-05-22T05:08:09
2019-05-22T05:08:09
187,766,577
0
0
null
null
null
null
UTF-8
Python
false
false
15,991
py
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import matplotlib.pyplot as plt import numpy as np from imgaug import augmenters as iaa import os import scipy as sp from sklearn import linear_model from sklearn.metrics import r2_score from sklearn.metrics import mean_squared_error LearningRate = 0.001 # shrink to 0.60 def affine_transform_60(b_x): xx = np.random.uniform(low=0, high=0, size=1) # (-0.5,0.5) yy = np.random.uniform(low=0, high=0, size=1) sx = np.random.uniform(low=0.60, high=0.60, size=1) # (.5,1.2) sy = np.random.uniform(low=0.60, high=0.60, size=1) rr = np.random.uniform(low=0, high=0, size=1) # (-0.5,0.5) sz1, sz2 = b_x.shape images = b_x.reshape([sz1, 28, 28, 1]) seq = iaa.Sequential( [iaa.Affine(translate_percent={"x": xx, "y": yy}, scale={"x": sx, "y": sy}, rotate=rr * 180, )]) images_aug = seq.augment_images(images) b_x = np.reshape(images_aug, [sz1, sz2]) return b_x, np.concatenate((xx, yy, rr), axis=0) # mv x def affine_transform_rand_x(b_x): xx = np.random.uniform(low=-0.2, high=0.2, size=1) # (-0.5,0.5) yy = 0 sx = 1 # (.5,1.2) sy = 1 rr = 0 # (-0.5,0.5) sz1, sz2 = b_x.shape images = b_x.reshape([sz1, 28, 28, 1]) seq = iaa.Sequential( [iaa.Affine(translate_percent={"x": xx, "y": yy}, scale={"x": sx, "y": sy}, rotate=rr * 180, )]) images_aug = seq.augment_images(images) b_x = np.reshape(images_aug, [sz1, sz2]) return b_x # mv y def affine_transform_rand_y(b_x): xx = 0 # (-0.5,0.5) yy = np.random.uniform(low=-0.2, high=0.2, size=1) sx = 1 # (.5,1.2) sy = 1 rr = 0 # (-0.5,0.5) sz1, sz2 = b_x.shape images = b_x.reshape([sz1, 28, 28, 1]) seq = iaa.Sequential( [iaa.Affine(translate_percent={"x": xx, "y": yy}, scale={"x": sx, "y": sy}, rotate=rr * 180, )]) images_aug = seq.augment_images(images) b_x = np.reshape(images_aug, [sz1, sz2]) return b_x, np.concatenate((xx, yy, rr), axis=0) # rtt def affine_transform_rand_r(b_x): xx = 0 # (-0.5,0.5) yy = 0 sx = 1 # (.5,1.2) sy = 1 rr = np.random.uniform(low=-0.2, high=0.2, size=1) # (-0.5,0.5) sz1, sz2 = b_x.shape images = b_x.reshape([sz1, 28, 28, 1]) seq = iaa.Sequential( [iaa.Affine(translate_percent={"x": xx, "y": yy}, scale={"x": sx, "y": sy}, rotate=rr * 180, )]) images_aug = seq.augment_images(images) b_x = np.reshape(images_aug, [sz1, sz2]) return b_x #mv x=deltaX def affine_transform_delta_x(b_x,deltaX): xx = deltaX # (-0.5,0.5) yy = 0 sx = 1 # (.5,1.2) sy = 1 rr = 0 # (-0.5,0.5) sz1, sz2 = b_x.shape images = b_x.reshape([sz1, 28, 28, 1]) seq = iaa.Sequential( [iaa.Affine(translate_percent={"x": xx, "y": yy}, scale={"x": sx, "y": sy}, rotate=rr * 180, )]) images_aug = seq.augment_images(images) b_x = np.reshape(images_aug, [sz1, sz2]) return b_x def affine_transform_delta_y(b_x,deltaY): xx = 0 # (-0.5,0.5) yy = deltaY sx = 1 # (.5,1.2) sy = 1 rr = 0 # (-0.5,0.5) sz1, sz2 = b_x.shape images = b_x.reshape([sz1, 28, 28, 1]) seq = iaa.Sequential( [iaa.Affine(translate_percent={"x": xx, "y": yy}, scale={"x": sx, "y": sy}, rotate=rr * 180, )]) images_aug = seq.augment_images(images) b_x = np.reshape(images_aug, [sz1, sz2]) return b_x XX = 0.2 SX1 = .5 SX2 = 0.7 RX = 0.2 # total mv def affine_transform1(b_x): xx = np.random.uniform(low=-XX, high=XX, size=1) # (-0.5,0.5) yy = np.random.uniform(low=-XX, high=XX, size=1) sx = np.random.uniform(low=SX1, high=SX2, size=1) # (.5,1.2) sy = np.random.uniform(low=SX1, high=SX2, size=1) rr = np.random.uniform(low=-RX, high=RX, size=1) # (-0.5,0.5) sz1, sz2 = b_x.shape images = b_x.reshape([sz1, 28, 28, 1]) seq = iaa.Sequential( [iaa.Affine(translate_percent={"x": xx, "y": yy}, scale={"x": sx, "y": sy}, rotate=rr * 180, )]) images_aug = seq.augment_images(images) b_x = np.reshape(images_aug, [sz1, sz2]) return b_x, np.concatenate((xx, yy, rr), axis=0) def cal_w_stats(we, wep): wed = we - wep; wed_max = np.amax(wed); wed_min = np.amin(wed); wed_avg = np.average(wed); wed_abs_avg = np.average(np.abs(wed)); we_std = np.std(we); we_avg = np.average(we) we_absavg = np.average(np.abs(we)) return np.concatenate((wed_max.reshape([1]), wed_min.reshape([1]), wed_avg.reshape([1]), wed_abs_avg.reshape([1]), we_std.reshape([1]), we_avg.reshape([1]),we_absavg.reshape([1]))) tf.set_random_seed(1) BATCH_SIZE = 128 N_TEST_IMG = 10 x_step=100;x_step2=x_step/2; x=(np.arange(x_step)-x_step2)/x_step2*0.2 mnist = input_data.read_data_sets('./mnist', one_hot=False) # use not one-hotted target data test_x = mnist.test.images[:BATCH_SIZE] test_x, para = affine_transform_60(test_x) #(128, 784) All chg to 0.60 size for i in range(BATCH_SIZE): test_x[i, :] = affine_transform_rand_r(np.reshape(test_x[i], [1, 784])) #rtt test_x[i, :] = affine_transform_rand_x(np.reshape(test_x[i], [1, 784])) #mv y test_x_=np.zeros([x_step,BATCH_SIZE,784]) for i in range(x_step): test_x_[i,:,:]=affine_transform_delta_y(test_x,x[i]) #mv x=deltaX (deltx,Batch,784) v_step=10;v_step2=v_step/2;VIEW_SIZE=3 v=(np.arange(v_step)-v_step2)/v_step2*0.2 view_x = mnist.test.images[BATCH_SIZE+1:BATCH_SIZE+1+VIEW_SIZE] view_x, para = affine_transform_60(view_x) for i in range(VIEW_SIZE): view_x[i, :] = affine_transform_rand_r(np.reshape(view_x[i], [1, 784])) #rtt view_x[i, :] = affine_transform_rand_x(np.reshape(view_x[i], [1, 784])) #mv y view_x_=np.zeros([v_step,VIEW_SIZE,784]) for i in range(v_step): view_x_[i,:,:]=affine_transform_delta_y(view_x,v[i]) #mv x=deltaX (deltx,Batch,784) scale1 = 4 n_l0 = 64 * scale1; n_l1 = 32 * scale1; n_l2 = 16 * scale1; n_l3 = 8 * scale1; n_encoded = 32 # 4*scale1#pow(4,ii) n_d0 = 8 * scale1; n_d1 = 16 * scale1; n_d2 = 32 * scale1; n_d3 = 64 * scale1; n_decoded = 784 print(n_encoded) type = '_n_' + str(n_encoded) + '-batch' + str(BATCH_SIZE) + '-lr' + str(LearningRate) + '-' + str(XX) + '-' + str( SX1) + '-' + str(SX2) + '-' + str(RX) + '-' # tf placeholder tf_x = tf.placeholder(tf.float32, [None, 28 * 28]) # value in the range of (0, 1) ph_encoded = tf.placeholder(tf.float32, [None, n_encoded]) ph_switch = tf.placeholder(tf.float32, [1]) ph_lr = tf.placeholder(tf.float32, []) ph_dis_e = tf.placeholder(tf.float32, [None, n_encoded]) # encoder en0 = tf.layers.dense(tf_x, n_l0, tf.nn.sigmoid) en1 = tf.layers.dense(en0, n_l1, tf.nn.sigmoid) en2 = tf.layers.dense(en1, n_l2, tf.nn.sigmoid) en3 = tf.layers.dense(en2, n_l3, tf.nn.sigmoid) ff_encoded = tf.layers.dense(en3, n_encoded, tf.nn.sigmoid) enc = ff_encoded * ph_switch + ph_encoded * (1 - ph_switch) encoded = tf.multiply(enc, ph_dis_e) # decoder de0 = tf.layers.dense(encoded, n_d0, tf.nn.sigmoid) de1 = tf.layers.dense(de0, n_d1, tf.nn.sigmoid) de2 = tf.layers.dense(de1, n_d2, tf.nn.sigmoid) de3 = tf.layers.dense(de2, n_d3, tf.nn.sigmoid) decoded = tf.layers.dense(de3, n_decoded, tf.nn.sigmoid) loss = tf.losses.mean_squared_error(labels=tf_x, predictions=decoded) train = tf.train.AdamOptimizer(ph_lr).minimize(loss) weights_en0 = tf.get_default_graph().get_tensor_by_name(os.path.split(en0.name)[0] + '/kernel:0') weights_en1 = tf.get_default_graph().get_tensor_by_name(os.path.split(en1.name)[0] + '/kernel:0') weights_en2 = tf.get_default_graph().get_tensor_by_name(os.path.split(en2.name)[0] + '/kernel:0') weights_en3 = tf.get_default_graph().get_tensor_by_name(os.path.split(en3.name)[0] + '/kernel:0') weights_mid = tf.get_default_graph().get_tensor_by_name(os.path.split(ff_encoded.name)[0] + '/kernel:0') weights_de0 = tf.get_default_graph().get_tensor_by_name(os.path.split(de0.name)[0] + '/kernel:0') weights_de1 = tf.get_default_graph().get_tensor_by_name(os.path.split(de1.name)[0] + '/kernel:0') weights_de2 = tf.get_default_graph().get_tensor_by_name(os.path.split(de2.name)[0] + '/kernel:0') weights_de3 = tf.get_default_graph().get_tensor_by_name(os.path.split(de3.name)[0] + '/kernel:0') weights_ddr = tf.get_default_graph().get_tensor_by_name(os.path.split(decoded.name)[0] + '/kernel:0') sess = tf.Session() sess.run(tf.global_variables_initializer()) ph_encoded_ = np.zeros(shape=[BATCH_SIZE, n_encoded]) ph_switch_ = np.ones(shape=[1]) ph_dis_e_ = np.ones(shape=[BATCH_SIZE, n_encoded]) saver = tf.train.Saver() nx = 0 type = '_n_32-batch128-lr0.001-0.2-0.5-0.7-0.2-nx0' saver.restore(sess, '/Users/fengqi/Pycharm_py36/QF/4900000/' + type) rows = ['{}'.format(row) for row in ['x1', 'x1_', 'a', 'a1_', 'd_a', '|d_a|','e_chg-e']] LearningRate = 0.001 ph_lr_ = np.ones(shape=[]) * LearningRate col = np.ones([1, n_l0]); col = np.concatenate([col, np.ones([1, n_l1]) * 0.8, np.ones([1, n_l2]) * 0.6, np.ones([1, n_l3]) * 0.4, np.ones([1, n_encoded]) * 0.2, np.ones([1, n_d0]) * 0.4, np.ones([1, n_d1]) * 0.6, np.ones([1, n_d2]) * 0.8, np.ones([1, n_d3]) * 1.0], axis=1) ####### compute corr ####### #test_x_ (100,128,784) count = 0 cc=np.zeros([BATCH_SIZE,992]) pp=np.zeros([BATCH_SIZE,992]) for i in range(x_step): xdata=np.reshape(test_x_[i,:,:],(BATCH_SIZE,784)) view_decoded_data, we0, we1, we2, we3, wem, wd0, wd1, wd2, wd3, wdd, en0_, en1_, en2_, en3_, ff_encoded_, de0_, de1_, de2_, de3_, ddr_ = sess.run( [decoded, weights_en0, weights_en1, weights_en2, weights_en3, weights_mid, weights_de0, weights_de1, weights_de2, weights_de3, weights_ddr, en0, en1, en2, en3, ff_encoded, de0, de1, de2, de3, decoded], {tf_x: xdata, ph_encoded: ph_encoded_, ph_switch: ph_switch_, ph_dis_e: ph_dis_e_}) act = np.concatenate([en0_, en1_, en2_, en3_, ff_encoded_, de0_, de1_, de2_, de3_], axis=1) if i ==0: sz_act = act.shape; sz_act_length = sz_act[1]; act_mat=np.zeros([x_step,BATCH_SIZE,sz_act_length]) #(100, 128, 992) act_mat[i,:,:] = act for i in range(BATCH_SIZE): print(str(i)) for j in range(992): #corrcoeff=np.corrcoef(act_mat[:,i,j],x) [corrcoeff,pval]=sp.stats.pearsonr(act_mat[:,i,j],x) cc[i,j]=corrcoeff#(128, 992) pp[i,j]=pval # # cc_avg=np.average(cc,axis=0) # pp_avg=np.average(pp,axis=0) # ind=np.where(pp_avg<0.01) # nx_e = cc_avg[480:512] # ind_e = np.argsort(nx_e) # # # # for k in range(32): # print(k) # f, a = plt.subplots(12, v_step) # for i in range(v_step): #left-right # print(str(i)) # # for l in range(11): #up-down # if l==0: # a[0][i].clear() # a[0][i].imshow(np.reshape(view_x_[i,0 ], (28, 28)), cmap='gray') # a[0][i].set_xticks(()) # a[0][i].set_yticks(()) # # view_ph_encoded_ = np.zeros(shape=[VIEW_SIZE, n_encoded]) # view_ph_switch_ = np.ones(shape=[1]) # view_ph_dis_e_ = np.ones(shape=[VIEW_SIZE, n_encoded]) # view_decoded_data1, we0, we1, we2, we3, wem, wd0, wd1, wd2, wd3, wdd, en0_, en1_, en2_, en3_, ff_encoded_, encoded_1, de0_, de1_, de2_, de3_, ddr_ = sess.run( # [decoded, weights_en0, weights_en1, weights_en2, weights_en3, weights_mid, # weights_de0, weights_de1, weights_de2, weights_de3, weights_ddr, en0, en1, en2, en3, ff_encoded, # encoded, de0, de1, # de2, de3, decoded], # {tf_x: view_x_[i], # ph_encoded: view_ph_encoded_, # ph_switch: view_ph_switch_, # ph_dis_e: view_ph_dis_e_}) # if l==0: # flag_1=np.round(ff_encoded_[0,k]*10) # # view_ph_encoded_ = ff_encoded_ # view_ph_switch_ = np.zeros(shape=[1]) # view_ph_dis_e_ = np.ones(shape=[VIEW_SIZE, n_encoded]) # view_ph_encoded_[:,k]=1- l / 10 # view_decoded_data1, we0, we1, we2, we3, wem, wd0, wd1, wd2, wd3, wdd, en0_, en1_, en2_, en3_, ff_encoded_, encoded_1, de0_, de1_, de2_, de3_, ddr_ = sess.run( # [decoded, weights_en0, weights_en1, weights_en2, weights_en3, weights_mid, # weights_de0, weights_de1, weights_de2, weights_de3, weights_ddr, en0, en1, en2, en3, ff_encoded, # encoded, de0, de1, # de2, de3, decoded], # {tf_x: view_x_[i], # ph_encoded: view_ph_encoded_, # ph_switch: view_ph_switch_, # ph_dis_e: view_ph_dis_e_}) # # # a[l+1][i].clear() # a[l+1][i].imshow(np.reshape(view_decoded_data1[0], (28, 28)), cmap='gray') # a[l+1][i].set_xticks(()) # a[l+1][i].set_yticks(()) # if flag_1==10-l: # im=np.reshape(view_decoded_data1[0], (28, 28)) # im[25:27,:]=0.5; # a[l + 1][i].imshow(im, cmap='gray') # # plt.subplots_adjust(left=0.2, right=0.8, bottom=0, top=1, wspace=0.05, hspace=0.05) # plt.savefig('./test/5test_chg_ny_' + str(k) + '.png') # # # # aaaa = 1 # # # # cc_avg=np.average(cc,axis=0) pp_avg=np.average(pp,axis=0) ind=np.where(pp_avg<0.01) nx_e = cc_avg[480:512] ind_e = np.argsort(nx_e) for k in range(32): print(k) f, a = plt.subplots(12, v_step) for i in range(v_step): #left-right print(str(i)) for l in range(11): #up-down if l==0: a[0][i].clear() a[0][i].imshow(np.reshape(view_x_[i,1], (28, 28)), cmap='gray') a[0][i].set_xticks(()) a[0][i].set_yticks(()) view_ph_encoded_ = np.zeros(shape=[VIEW_SIZE, n_encoded]) view_ph_switch_ = np.ones(shape=[1]) view_ph_dis_e_ = np.ones(shape=[VIEW_SIZE, n_encoded]) view_decoded_data1, we0, we1, we2, we3, wem, wd0, wd1, wd2, wd3, wdd, en0_, en1_, en2_, en3_, ff_encoded_, encoded_1, de0_, de1_, de2_, de3_, ddr_ = sess.run( [decoded, weights_en0, weights_en1, weights_en2, weights_en3, weights_mid, weights_de0, weights_de1, weights_de2, weights_de3, weights_ddr, en0, en1, en2, en3, ff_encoded, encoded, de0, de1, de2, de3, decoded], {tf_x: view_x_[i], ph_encoded: view_ph_encoded_, ph_switch: view_ph_switch_, ph_dis_e: view_ph_dis_e_}) if l==0: flag_1=np.round(ff_encoded_[1,k]*10) view_ph_encoded_ = ff_encoded_ view_ph_switch_ = np.zeros(shape=[1]) view_ph_dis_e_ = np.ones(shape=[VIEW_SIZE, n_encoded]) view_ph_encoded_[:,k]=1- l / 10 view_decoded_data1, we0, we1, we2, we3, wem, wd0, wd1, wd2, wd3, wdd, en0_, en1_, en2_, en3_, ff_encoded_, encoded_1, de0_, de1_, de2_, de3_, ddr_ = sess.run( [decoded, weights_en0, weights_en1, weights_en2, weights_en3, weights_mid, weights_de0, weights_de1, weights_de2, weights_de3, weights_ddr, en0, en1, en2, en3, ff_encoded, encoded, de0, de1, de2, de3, decoded], {tf_x: view_x_[i], ph_encoded: view_ph_encoded_, ph_switch: view_ph_switch_, ph_dis_e: view_ph_dis_e_}) a[l+1][i].clear() a[l+1][i].imshow(np.reshape(view_decoded_data1[1], (28, 28)), cmap='gray') a[l+1][i].set_xticks(()) a[l+1][i].set_yticks(()) if flag_1==10-l: im=np.reshape(view_decoded_data1[1], (28, 28)) im[25:27,:]=0.5; a[l + 1][i].imshow(im, cmap='gray') plt.subplots_adjust(left=0.2, right=0.8, bottom=0, top=1, wspace=0.05, hspace=0.05) plt.savefig('./test/6test_chg_ny_' + str(k) + '.png') aaaa = 1
[ "noreply@github.com" ]
noreply@github.com
ec61f2c11c142888f2e43279e15779776f084d75
b75b3bb6a2c6dd8b4a5b89718eb83d6451000cd4
/hackbright.py
715553d9b927069928d6bfc85808ce5824d2e0b2
[]
no_license
CodeHotPink/project-tracking-flask
22efebeaddf83d2746ba9137f1b478da8c34b1a9
bdd58b17034406f28d5ceaa0c834eb0d6ad06be3
refs/heads/master
2020-04-03T18:46:04.010020
2018-10-31T04:02:38
2018-10-31T04:02:38
155,496,735
0
0
null
null
null
null
UTF-8
Python
false
false
5,034
py
"""Hackbright Project Tracker. A front-end for a database that allows users to work with students, class projects, and the grades students receive in class projects. """ from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) db = SQLAlchemy() def connect_to_db(app): """Connect the database to our Flask app.""" app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///hackbright' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.app = app db.init_app(app) def get_student_by_github(github): """Given a GitHub account name, print info about the matching student.""" QUERY = """ SELECT first_name, last_name, github FROM students WHERE github = :github """ db_cursor = db.session.execute(QUERY, {'github': github}) row = db_cursor.fetchone() print(row) print("Student: {} {}\nGitHub account: {}".format(row[0], row[1], row[2])) return row def make_new_student(first_name, last_name, github): """Add a new student and print confirmation. Given a first name, last name, and GitHub account, add student to the database and print a confirmation message. """ QUERY = """ INSERT INTO students (first_name, last_name, github) VALUES (:first_name, :last_name, :github) """ db.session.execute(QUERY, {'first_name': first_name, 'last_name': last_name, 'github': github,}) db.session.commit() print(f"Successully added student: {first_name} {last_name}") def get_project_by_title(title): """Given a project title, print information about the project.""" QUERY = """ SELECT title, description, max_grade FROM projects WHERE title = :title """ db_cursor = db.session.execute(QUERY, {'title': title}) row = db_cursor.fetchone() print(f"Title: {row[0]}\nDescription: {row[1]}\nMaximum Grade: {row[2]}") def get_grade_by_github_title(github, title): """Print grade student received for a project.""" QUERY = """ SELECT student_github, project_title, grade FROM grades WHERE student_github = :github AND project_title = :title """ db_cursor = db.session.execute(QUERY, {'github': github, 'title': title}) row = db_cursor.fetchone() print(f"Github: {row[0]}\nProject Title: {row[1]}\nGrade: {row[2]}") def assign_grade(github, title, grade): """Assign a student a grade on an assignment and print a confirmation.""" QUERY = """ INSERT INTO grades (student_github, project_title, grade) VALUES (:github, :title, :grade) """ db.session.execute(QUERY,{'github': github, 'title': title, 'grade': grade}) db.session.commit() print(f"Successfully added {github}'s grade for {title}") def add_project(title, description, max_grade): """Creates new project in projects table in Hackbright database. Will print confirmation.""" QUERY = """ INSERT INTO projects (title, description, max_grade) VALUES (:title,:description, :max_grade) """ db.session.execute(QUERY,{'title': title, 'description': description, 'max_grade': max_grade}) print(f"Successfully added {title}.") def handle_input(): """Main loop. Repeatedly prompt for commands, performing them, until 'quit' is received as a command. """ command = None while command != "quit": input_string = input("HBA Database> ") tokens = input_string.split() command = tokens[0] args = tokens[1:] print(args) if command == "student": github = args[0] get_student_by_github(github) elif command == "new_student": first_name, last_name, github = args # unpack! make_new_student(first_name, last_name, github) elif command == "project": title = args[0] get_project_by_title(title) elif command == "github_grade": github, title = args # unpack! get_grade_by_github_title(github, title) elif command == "assign_grade": github, title, grade = args # unpack! assign_grade(github, title, grade) elif command == "add_project": title = args[0] project_desc = args[1:-1] print(type(project_desc)) grade_max = args[-1] add_project(title, project_desc, grade_max) else: if command != "quit": print("Invalid Entry. Try again.") if __name__ == "__main__": connect_to_db(app) handle_input() # To be tidy, we close our database connection -- though, # since this is where our program ends, we'd quit anyway. db.session.close()
[ "no-reply@hackbrightacademy.com" ]
no-reply@hackbrightacademy.com
bde4160a1d045a92ee19fdc4d0e30366397bb41d
2ade3d231fe1fcc8a4e698845a98fa025197c06b
/dealproperty/dealproperty/wsgi.py
f4be6bfd492254876a4b5741075bafaac4c57faf
[]
no_license
anandraj8756/property_deal_web
d3d7012968ac6c7e0931c9207db61163c518f086
1dc220734b00e651b891741db82469d28079f442
refs/heads/main
2023-06-08T04:30:12.439249
2021-07-05T06:20:33
2021-07-05T06:20:33
null
0
0
null
null
null
null
UTF-8
Python
false
false
401
py
""" WSGI config for dealproperty project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dealproperty.settings') application = get_wsgi_application()
[ "anandallen95@gmail.com" ]
anandallen95@gmail.com
09cace0bf73c69539cf1e99a98b7a6f3ed08f833
5328f77114a898f1c75bf82176306a9ab83a3473
/models/clients.py
1ab3394ff6e1a3a584d126ddfc7b641f30095cee
[]
no_license
prabakaran04/prabakaran
2e207e0dc17cb0c39340b05683fda750eae45eaa
b6f8268192dcffcd095486527777d4edeaafdf68
refs/heads/master
2023-03-11T14:10:38.576472
2019-07-18T13:29:04
2019-07-18T13:29:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,325
py
from odoo import models,fields,api from odoo.exceptions import ValidationError class ClientDetails(models.Model): _name = 'client.details' _rec_name='client_name' client_id = fields.Char(default ='new') client_name = fields.Char(string ='Client name') address = fields.Char(string ='Address') client_email = fields.Char(string = 'Email') mobile = fields.Char(string = 'Mobile') status = fields.Selection(string = 'status' , selection=[('gold', 'Gold'),('silver','Silver'),('bronze','bronze')]) client_sex = fields.Selection(string = "Sex", selection=[('male','Male'),('female','Female')]) date =fields.Datetime(string = "created on" , default=fields.Datetime.now) @api.model def create(self , vals): if vals.get('client_id','new') =='new': vals['client_id'] = self.env['ir.sequence']. next_by_code('client.details') or '/' return super(ClientDetails , self). create(vals) @api.constrains('client_name') def _check_name(self): for val in self: if val['client_name']: if len(val["client_name"])<6: raise ValidationError("name is too short, must be more than 6 character") _sql_constraints =[('client_name_unique','unique(client_name)','name already exists')]
[ "prabakaran@sodexis.com" ]
prabakaran@sodexis.com
f9d9118938a3ba4499fe9302991d70005635b133
b88dbcf3619dd3af4896b4b15432ae2b2d390665
/main.py
59c59c21694156ed16b7333845e17b06d0bfdf16
[]
no_license
msubzero2000/bayesian-optimisation-metaflow-optuna
a43ccdb0150fde6ae7571798549210113826c0ea
00bda310bbe7ce42470acfc5d90198f27ad9c5d2
refs/heads/main
2023-08-06T03:27:55.980813
2021-10-06T07:22:19
2021-10-06T07:22:19
413,768,301
10
1
null
null
null
null
UTF-8
Python
false
false
4,302
py
""" Optuna example that optimizes a classifier configuration for cancer dataset using Catboost. In this example, we optimize the validation accuracy of cancer detection using Catboost. We optimize both the choice of booster model and their hyperparameters. """ import logging from datetime import datetime, timedelta from metaflow import FlowSpec, step, S3, current, resources, conda_base, Parameter, batch, project logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) @conda_base(libraries={'catboost': '0.26.1', 'optuna': '2.9.1', 'scikit-learn': '1.0', 'sqlalchemy': '1.4.22', 'psycopg2-binary':'2.9.1'}) class Optimisation(FlowSpec): def objective(self, trial): import optuna import numpy as np import catboost as cb from sklearn.datasets import load_breast_cancer from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split data, target = load_breast_cancer(return_X_y=True) train_x, valid_x, train_y, valid_y = train_test_split(data, target, test_size=0.3) param = { "objective": trial.suggest_categorical("objective", ["Logloss", "CrossEntropy"]), "colsample_bylevel": trial.suggest_float("colsample_bylevel", 0.01, 0.1), "depth": trial.suggest_int("depth", 1, 12), "boosting_type": trial.suggest_categorical("boosting_type", ["Ordered", "Plain"]), "bootstrap_type": trial.suggest_categorical( "bootstrap_type", ["Bayesian", "Bernoulli", "MVS"] ), "used_ram_limit": "3gb", } if param["bootstrap_type"] == "Bayesian": param["bagging_temperature"] = trial.suggest_float("bagging_temperature", 0, 10) elif param["bootstrap_type"] == "Bernoulli": param["subsample"] = trial.suggest_float("subsample", 0.1, 1) gbm = cb.CatBoostClassifier(**param) gbm.fit(train_x, train_y, eval_set=[(valid_x, valid_y)], verbose=0, early_stopping_rounds=100) preds = gbm.predict(valid_x) pred_labels = np.rint(preds) accuracy = accuracy_score(valid_y, pred_labels) return accuracy @batch(cpu=4) @step def start(self): import optuna from distributed_optuna import DistributedOptuna, DistributedOptunaInfo, DistributedOptunaWorkerInfo info = DistributedOptuna.create(num_workers=10, num_trials=10, timeout=600, study_name_prefix="catboost") print(f"Creating study {info.study_name} with {len(info.workers_info)} workers") study = optuna.create_study(direction="maximize", study_name=info.study_name, storage=info.storage) self.optimisation_params = info.workers_info self.next(self.optimise, foreach="optimisation_params") @batch(cpu=4) @step def optimise(self): import optuna from distributed_optuna import DistributedOptuna, DistributedOptunaInfo, DistributedOptunaWorkerInfo study = optuna.load_study(study_name=self.input.study_name, storage=self.input.storage) study.optimize(self.objective, n_trials=self.input.num_trials, timeout=self.input.timeout) print("Number of finished trials: {}".format(len(study.trials))) print("Record Best trial:") # Record this worker's best trial self.trial = study.best_trial self.next(self.join) @step def join(self, inputs): # Find the global best trial amongst worker's best trial best_trial = None best_trial_value = 0 for input in inputs: cur_best_trial = input.trial print(f"Best trial for this worker {cur_best_trial.value}") if best_trial is None or cur_best_trial.value > best_trial_value: best_trial = cur_best_trial best_trial_value = cur_best_trial.value print("Value: {}".format(best_trial.value)) print("Params: ") for key, value in best_trial.params.items(): print(" {}: {}".format(key, value)) self.next(self.end) @step def end(self): print("Completed") opt = Optimisation()
[ "msubzero2000@gmail.com" ]
msubzero2000@gmail.com
9e226cf7f1b347db514b5a6f6c603957fe867e63
c3eff34237f19885ee09c81f2eb869a53a66e76b
/app/generate_token.py
0b2dabf9bdc5880404676f02d9b10c6a15b73f1d
[]
no_license
victorvarza/hermes
e9f4bf3fe76b3f6949bfd9e8e23bab7951692f05
62d9c5ba0cb0851ae56bc33e8ac337cecd205f82
refs/heads/master
2021-11-05T13:40:02.298153
2021-01-10T21:51:11
2021-01-10T21:51:11
135,069,301
0
0
null
2021-03-25T22:53:52
2018-05-27T17:56:11
Python
UTF-8
Python
false
false
434
py
from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive cred_path = "app/conf/gdrive_cred.json" gauth = GoogleAuth() gauth.LoadCredentialsFile(cred_path) if gauth.credentials is None: gauth.LocalWebserverAuth() elif gauth.access_token_expired: gauth.Refresh() else: gauth.Authorize() print("Writing credentials to {0}".format(cred_path)) gauth.SaveCredentialsFile(cred_path) drive = GoogleDrive(gauth)
[ "victor.varza@gmail.com" ]
victor.varza@gmail.com
e1a1de36048d93300f9e84f3959504ed9e7d628d
35a2268f7f004ecd4c834eed7a68b54980a2a157
/action sequence generation.py
3658289acb07e626f917a29fea0775543bdae9db
[]
no_license
akagrecha/action-sequence-generation
cefa768b6250dd9968ad7e2068b991d94d7379bf
46ff1a7019d015709832e24c2244106d2dfb9fc7
refs/heads/master
2021-01-20T17:33:52.601183
2016-06-23T05:13:54
2016-06-23T05:13:54
61,200,018
0
0
null
null
null
null
UTF-8
Python
false
false
4,314
py
import cv2 import argparse def action_sequence_generator(video, gblur_ksize_width=21, gblur_ksize_height=21, gblur_sigmaX=0, fg_mask_lower_threshold=50, fg_mask_upper_threshold=255, required_frames=8): """ Action Sequence Generator converts a video containing an action sequence to an image that has the action sequence in it. Algorithm _________ 1. Foreground Extraction: A foreground mask is generated by thresholding a delta image of the first frame and the current frame. The foreground mask is applied to the frame to get foreground frames. Similarly, a background frames are also generated. 2. Recombination: The foreground frames and background frames are saved in an array. Selected foreground and background frames undergo bitwise operations for recombination. Finally, they are combined to get the result. Note ____ The algorithm for foreground extraction works properly when the first frame contains the background only i.e. the foreground object is not visible in the first frame. Function Signature __________________ : param video: the video file with an action sequence in it. : param gblur_ksize_width: kernel size width for the gaussian blur applied on the frame : param gblur_ksize_height: kernel size height for the gaussian blur applied on the frame : param gblur_ksize_sigmaX: Gaussian kernel standard deviation in X direction : param fg_mask_lower_threshold: Lower threshold applied to the delta image to generate foreground mask : param fg_mask_upper_threshold: Upper threshold applied to the delta image to generate foreground mask : param required_frames: Number of frames to be considered while generating the result : return: image having the action sequence of the given video Authors _______ Anmol Kagrecha Ranveer Aggarwal """ cap = cv2.VideoCapture(video) first_frame = None img_foreground_frames = [] img_background_frames = [] number_of_frames = int(cap.get(7)) while 1: ret, frame = cap.read() if ret == 0: break gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (gblur_ksize_width, gblur_ksize_height), gblur_sigmaX) if first_frame is None: first_frame = gray continue # difference of current frame and the first frame frame_delta = cv2.absdiff(first_frame, gray) # foreground mask and background mask foreground_mask = cv2.threshold(frame_delta, fg_mask_lower_threshold, fg_mask_upper_threshold, cv2.THRESH_BINARY)[1] background_mask = cv2.bitwise_not(foreground_mask) # foreground and background foreground = cv2.bitwise_and(frame, frame, mask=foreground_mask) background = cv2.bitwise_and(frame, frame, mask=background_mask) # appending foreground and background to the arrays img_foreground_frames.append(foreground) img_background_frames.append(background) cap.release() # frame numbers generated for the result frame_numbers = [i for i in range(0, number_of_frames + 1, int(number_of_frames/required_frames))] foreground_combined = img_foreground_frames[0] background_combined = img_background_frames[0] # recombination operations to generate the result for i in frame_numbers: foreground_combined = cv2.bitwise_or(img_foreground_frames[i], foreground_combined) background_combined = cv2.bitwise_and(img_background_frames[i], background_combined) result = cv2.bitwise_or(foreground_combined, background_combined) # uncomment to view the result """ cv2.namedWindow('result', 0) cv2.imshow('result', result) cv2.waitKey(0) & 0xFF cv2.destroyAllWindows() """ return result ap = argparse.ArgumentParser() ap.add_argument("-v", "--video", help="path to the video file") args = vars(ap.parse_args()) if args.get("video") is None: print("file not found") else: action_sequence_generator(args["video"])
[ "akagrecha@gmail.com" ]
akagrecha@gmail.com
f86a2ef5c5fa10d7f88154c33b7e6bf8420fc39d
cac58755bacb8cf144e05d86ddf0f590c1626aa7
/myPdf/pay_slip.py
111c94721de04117f1cf32a6b8815c0d92792ec5
[]
no_license
alaniomotosho2/automate
95d853bda06dc5279cdff894550b399a6ad5bec9
1bb7ee70941029c6092b329184c65935b6355d4c
refs/heads/master
2021-08-07T08:23:22.344109
2017-11-07T21:58:30
2017-11-07T21:58:30
108,914,450
0
0
null
null
null
null
UTF-8
Python
false
false
1,680
py
from datetime import datetime employee_data = [ { 'id': 123, 'name': 'Usman', 'payment': 10000, 'tax': 3000, 'total': 7000 }, { 'id': 245, 'name': 'Sophia', 'payment': 12000, 'tax': 4000, 'total': 8000 }, ] from fpdf import FPDF, HTMLMixin class PaySlip(FPDF, HTMLMixin): def footer(self): self.set_y(-15) self.set_font('Arial', 'I', 8) self.cell(0, 10, 'Page %s' % self.page_no(), 0, 0, 'C') def header(self): self.set_font('Arial', 'B', 15) self.cell(80) self.cell(30, 10, 'Google', 1, 0, 'C') self.ln(20) def generate_payslip(data): month = datetime.now().strftime("%B") year = datetime.now().strftime("%Y") pdf = PaySlip(format='letter') pdf.add_page() pdf.set_font("Times", size=12) pdf.cell(200, 10, txt="Pay Slip for %s, %s" %(month, year), ln=3, align="C") pdf.cell(50) pdf.cell(100, 10, txt="Employeed Id: %s" % employee_data[0]['id'],ln=1, align='L') pdf.cell(50) pdf.cell(100, 10, txt="Employeed Name: %s" % employee_data[0]['name'], ln=3, align='L') html = """ <table border="0" align="center" width="50%"> <thead><tr><th align="left" width="50%"> Pay Slip Details</th><th align="right" width="50%"> Amount in USD</th></tr></thead> <tbody> <tr><td>Payments</td><td align="right"> """ + str(employee_data[0]['payment']) + """ </td></tr> <tr><td>Tax</td><td align="right"> """ + str(employee_data[0]['tax']) + """ </td></tr> <tr><td>Total</td><td align="right"> """ + str(employee_data[0]['total']) + """</td></tr> </tbody> </table> """ pdf.write_html(html) pdf.output('payslip_%s.pdf' % employee_data[0]['id']) # this make sense,, slip is appeneded by the date for emp in employee_data: generate_payslip(emp)
[ "alaniomotosho2@gmail.com" ]
alaniomotosho2@gmail.com
00b42fcbfbde767ac076c1bdd0d7fb34c5b3382c
67b0379a12a60e9f26232b81047de3470c4a9ff9
/comments/models.py
27fec916d93089637204f146a37c7c27c5e70df4
[]
no_license
vintkor/whitemandarin
8ea9022b889fac718e0858873a07c586cf8da729
5afcfc5eef1bb1cc2febf519b04a4819a7b9648f
refs/heads/master
2021-05-06T03:35:09.367375
2017-12-20T15:43:08
2017-12-20T15:43:08
114,904,110
0
0
null
null
null
null
UTF-8
Python
false
false
3,969
py
# -*- coding: utf-8 -*- from django.db import models from mptt.models import MPTTModel, TreeForeignKey from tinymce import models as tinymce_model import datetime class Comments(MPTTModel): prod_name = models.CharField(max_length=250, blank=True, db_index=True, verbose_name="Название") paket = models.CharField(max_length=250, db_index=True, verbose_name="Пакет") item_model = models.CharField(max_length=250, db_index=True, verbose_name="Модель") item_id = models.IntegerField(db_index=True, null=True, verbose_name="id") published_in_category = models.BooleanField(default=False, verbose_name='Показывать в категории') parent = TreeForeignKey('self', null=True, blank=True, related_name='children', verbose_name=u"Родитель") name = models.CharField(max_length=250, verbose_name="Название") text = tinymce_model.HTMLField(blank=True, verbose_name="Полное описание") published = models.BooleanField(verbose_name="Опубликован") date_add = models.DateTimeField(default=datetime.datetime.today ,verbose_name="Дата публикации") vote = models.DecimalField(max_digits=2, decimal_places=1,db_index=True, null=True, verbose_name="Оценка") positive = models.IntegerField(null=True, blank=True, default=0, verbose_name="Позитивных") negative = models.IntegerField(null=True, blank=True, default=0, verbose_name="Негативных") def save(self): super(Comments, self).save() try: paket = self.paket item_model = self.item_model id = self.item_id count_comments = Comments.objects.filter(paket=paket, item_model=item_model, item_id=int(id), published = True).count() # assert False, count_comments exec "from %s.models import %s" % (paket, item_model) p = eval("%s.objects.get(pk=%d)" % (item_model, int(id))) p.comments_count = count_comments min_vote = 5 max_vote = 0 all_reit = 0.0 prod_votes = Comments.objects.filter(paket=paket, item_model=item_model, item_id=int(id), published = True).values('vote') for item in prod_votes: if min_vote > item['vote']: min_vote = item['vote'] if max_vote < item['vote']: max_vote = item['vote'] all_reit = all_reit + float(item['vote']) # assert False, min_vote p.min_reit = min_vote p.max_reit = max_vote p.reit = all_reit / count_comments p.save() self.prod_name = p.name except: pass super(Comments, self).save() if not self.date_add: self.date_add = datetime.datetime.today() super(Comments, self).save() def get_name(self): paket = self.paket item_model = self.item_model id = self.item_id # count_comments = Comments.objects.filter(paket=paket, item_model=item_model, item_id=int(id), published = True).count() # assert False, count_comments exec "from %s.models import %s" % (paket, item_model) p = eval("%s.objects.get(pk=%d)" % (item_model, int(id))) return p.name def __unicode__(self): return self.name class Meta: verbose_name_plural = "Коментарии " verbose_name = "Коментарий" ordering = ['-id'] class MPTTMeta: order_insertion_by = ['name'] class Utility(models.Model): comment = models.ForeignKey(Comments, blank=True, null=True, verbose_name="Коммент") positive = models.BooleanField(verbose_name="Позитивная оценка") def __unicode__(self): return self.comment.name class Meta: verbose_name_plural = "Оценки" verbose_name = "Оценка"
[ "alkv84@yandex.ru" ]
alkv84@yandex.ru
c49351323bd5706e1c5df7eba562dd7673b7e486
78fda83a9cd033d84e3ff47c8f9731b8ab3ff26d
/Scripts/part2.py
9cff5153f59ef3e22aa7bc8b87b3ecc37cb50871
[]
no_license
soham-shah/fireViz
61bea14cfb97bfb51a85c49b4a0740b4f57d1161
3e00a2ec68585be443a7a6eb859870a4f1898360
refs/heads/master
2021-01-19T15:50:30.886862
2017-08-21T16:59:25
2017-08-21T16:59:25
100,973,269
0
0
null
null
null
null
UTF-8
Python
false
false
10,549
py
#!/usr/bin/python import numpy as np import pandas as pd import os import sys sys.path.append("/curc/tools/x86_64/rh6/software/visit/2.10.0/2.10.0/linux-x86_64/lib/site-packages") from visit import * import time def closeDatabases(indexString): CloseDatabase("localhost:/projects/joki9146/week_13/Data_part2/wrfout_" + indexString + ".nc") CloseDatabase("localhost:/projects/joki9146/week_13/Data_part1/katrinaTerrain.png") #open db def openDB(indexString): filename = "localhost:/projects/joki9146/week_13/Data_part2/wrfout_" + indexString + ".nc" OpenDatabase(filename, 0, "NETCDF") ActivateDatabase(filename) #load bg image def loadBGImage(lat, lon): OpenDatabase("localhost:/projects/joki9146/week_13/Data_part1/katrinaTerrain.png", 0, "Image") ActivateDatabase("localhost:/projects/joki9146/week_13/Data_part1/katrinaTerrain.png") AddPlot("Truecolor", "color", 1, 0) TruecolorAtts = TruecolorAttributes() TruecolorAtts.opacity = 1 TruecolorAtts.lightingFlag = 0 SetPlotOptions(TruecolorAtts) #add elevate SetActivePlots(1) AddOperator("Elevate", 0) ElevateAtts = ElevateAttributes() ElevateAtts.zeroFlag = 1 SetOperatorOptions(ElevateAtts, 0) #add transform AddOperator("Transform", 0) TransformAtts = TransformAttributes() TransformAtts.doScale = 1 TransformAtts.scaleX = 0.43 TransformAtts.scaleY = 0.68 TransformAtts.scaleZ = 1 SetOperatorOptions(TransformAtts, 1) #add transform AddOperator("Transform", 0) TransformAtts = TransformAttributes() TransformAtts.doTranslate = 1 TransformAtts.translateX = -lon TransformAtts.translateY = -lat TransformAtts.translateZ = 0 SetOperatorOptions(TransformAtts, 2) def plotWind(): DefineVectorExpression("wind", "{U, V, W}") DefineScalarExpression("windMag", "magnitude(wind)") AddPlot("Vector", "wind") #add slice AddOperator("Slice", 0) SliceAtts = SliceAttributes() SliceAtts.originType = SliceAtts.Intercept # Point, Intercept, Percent, Zone, Node SliceAtts.originIntercept = 5 SliceAtts.normal = (0, 0, 1) SliceAtts.axisType = SliceAtts.ZAxis # XAxis, YAxis, ZAxis, Arbitrary, ThetaPhi SliceAtts.upAxis = (0, 1, 0) SliceAtts.project2d = 0 SliceAtts.meshName = "as_zonal/mesh315x309" SetOperatorOptions(SliceAtts, 0) #wind vec attrs VectorAtts = VectorAttributes() VectorAtts.nVectors = 4000 VectorAtts.lineStyle = VectorAtts.SOLID # SOLID, DASH, DOT, DOTDASH VectorAtts.scale = 0.08 VectorAtts.scaleByMagnitude = 1 VectorAtts.autoScale = 0 VectorAtts.headSize = 0.3 VectorAtts.headOn = 1 VectorAtts.colorByMag = 1 VectorAtts.lineStem = VectorAtts.Cylinder # Cylinder, Line VectorAtts.stemWidth = 0.1 VectorAtts.glyphType = VectorAtts.Arrow # Arrow, Ellipsoid VectorAtts.vectorOrigin = VectorAtts.Middle # Head, Middle, Tail VectorAtts.geometryQuality = VectorAtts.High # Fast, High VectorAtts.useLegend = 0 SetPlotOptions(VectorAtts) def plotStreamtline(): AddPlot("Streamline", "wind") StreamlineAtts = StreamlineAttributes() StreamlineAtts.sourceType = StreamlineAtts.SpecifiedCircle # SpecifiedPoint, SpecifiedPointList, SpecifiedLine, SpecifiedCircle, SpecifiedPlane, SpecifiedSphere, SpecifiedBox, Selection StreamlineAtts.planeOrigin = (155, 155, 5) StreamlineAtts.planeNormal = (0, 0, 1) StreamlineAtts.planeUpAxis = (0, 1, 0) StreamlineAtts.radius = 100 StreamlineAtts.sampleDensity0 = 9 StreamlineAtts.sampleDensity1 = 4 StreamlineAtts.integrationDirection = StreamlineAtts.Both # Forward, Backward, Both StreamlineAtts.maxSteps = 1000 StreamlineAtts.limitMaximumTimestep = 1 StreamlineAtts.maxTimeStep = 0.01 StreamlineAtts.displayMethod = StreamlineAtts.Tubes # Lines, Tubes, Ribbons StreamlineAtts.varyTubeRadius = StreamlineAtts.Scalar # None, Scalar StreamlineAtts.varyTubeRadiusFactor = 10 StreamlineAtts.colorTableName = "hot" StreamlineAtts.coloringMethod = StreamlineAtts.ColorByVariable # Solid, ColorBySpeed, ColorByVorticity, ColorByLength, ColorByTime, ColorBySeedPointID, ColorByVariable, ColorByCorrelationDistance, ColorByNumberDomainsVisited StreamlineAtts.coloringVariable = "windMag" StreamlineAtts.tubeRadiusAbsolute = 0.125 StreamlineAtts.tubeRadiusBBox = 0.0025 StreamlineAtts.showSeeds = 0 StreamlineAtts.varyTubeRadius = StreamlineAtts.Scalar # None, Scalar StreamlineAtts.varyTubeRadiusFactor = 6 StreamlineAtts.varyTubeRadiusVariable = "windMag" StreamlineAtts.legendFlag = 0 SetPlotOptions(StreamlineAtts) #SetActivePlots(3) #RemoveOperator(0, 0) #add clouds def addClouds(): AddPlot("Volume", "QCLOUD", 1, 0) SetActivePlots(4) AddOperator("Transform", 0) TransformAtts = TransformAttributes() TransformAtts.doScale = 1 TransformAtts.scaleOrigin = (0, 0, 0) TransformAtts.scaleX = 1 TransformAtts.scaleY = 1 TransformAtts.scaleZ = 3 SetOperatorOptions(TransformAtts, 0) VolumeAtts = VolumeAttributes() VolumeAtts.legendFlag = 0 VolumeAtts.colorControlPoints.GetControlPoints(0).colors = (220, 220, 220, 0) VolumeAtts.colorControlPoints.GetControlPoints(0).position = 0 VolumeAtts.colorControlPoints.GetControlPoints(1).colors = (240, 240, 240, 255) VolumeAtts.colorControlPoints.GetControlPoints(1).position = 0.34106 VolumeAtts.colorControlPoints.GetControlPoints(2).colors = (255, 255, 255, 255) VolumeAtts.colorControlPoints.GetControlPoints(2).position = 1 VolumeAtts.colorControlPoints.smoothing = VolumeAtts.colorControlPoints.Linear # None, Linear, CubicSpline VolumeAtts.colorControlPoints.equalSpacingFlag = 0 VolumeAtts.colorControlPoints.discreteFlag = 0 VolumeAtts.opacityAttenuation = 1 VolumeAtts.opacityMode = VolumeAtts.ColorTableMode # FreeformMode, GaussianMode, ColorTableMode VolumeAtts.resampleFlag = 1 VolumeAtts.resampleTarget = 10000000 VolumeAtts.rendererType = VolumeAtts.Splatting # Splatting, Texture3D, RayCasting, RayCastingIntegration, SLIVR, RayCastingSLIVR, Tuvok VolumeAtts.gradientType = VolumeAtts.SobelOperator # CenteredDifferences, SobelOperator VolumeAtts.transferFunctionDim = 1 SetPlotOptions(VolumeAtts) #add hot towers def addHotTowers(): AddPlot("Pseudocolor", "QCLOUD", 1, 0) SetActivePlots(5) AddOperator("Transform", 0) TransformAtts = TransformAttributes() TransformAtts.doScale = 1 TransformAtts.scaleOrigin = (0, 0, 0) TransformAtts.scaleX = 1 TransformAtts.scaleY = 1 TransformAtts.scaleZ = 3 SetOperatorOptions(TransformAtts, 0) AddOperator("Isovolume", 0) IsovolumeAtts = IsovolumeAttributes() IsovolumeAtts.lbound = 0.0005 IsovolumeAtts.ubound = 1e+37 IsovolumeAtts.variable = "default" SetOperatorOptions(IsovolumeAtts, 0) PseudocolorAtts = PseudocolorAttributes() PseudocolorAtts.maxFlag = 1 PseudocolorAtts.max = 0.0015 PseudocolorAtts.centering = PseudocolorAtts.Zonal # Natural, Nodal, Zonal PseudocolorAtts.colorTableName = "Reds" PseudocolorAtts.legendFlag = 0 PseudocolorAtts.smoothingLevel = 2 SetPlotOptions(PseudocolorAtts) #add rainfall def addRainfall(): AddPlot("Pseudocolor", "RAINNC", 1, 0) SetActivePlots(6) PseudocolorAtts = PseudocolorAttributes() PseudocolorAtts.colorTableName = "RAINNC" PseudocolorAtts.opacityType = PseudocolorAtts.ColorTable # ColorTable, FullyOpaque, Constant, Ramp, VariableRange PseudocolorAtts.lightingFlag = 0 PseudocolorAtts.legendFlag = 0 SetPlotOptions(PseudocolorAtts) AddOperator("Elevate", 0) ElevateAtts = ElevateAttributes() ElevateAtts.zeroFlag = 1 SetOperatorOptions(ElevateAtts, 0) AddOperator("Transform", 0) TransformAtts = TransformAttributes() TransformAtts.doTranslate = 1 TransformAtts.translateX = 0 TransformAtts.translateY = 0 TransformAtts.translateZ = 0.05 SetOperatorOptions(TransformAtts, 0) #add light def addLight(): light1 = LightAttributes() light1.enabledFlag = 1 light1.type = light1.Object # Ambient, Object, Camera light1.direction = (0, 0, -1) light1.color = (255, 255, 255, 255) light1.brightness = 0.5 SetLight(1, light1) def annotation(): AnnotationAtts = AnnotationAttributes() AnnotationAtts.axes2D.visible = 0 AnnotationAtts.axes3D.visible = 0 AnnotationAtts.axes3D.triadFlag = 0 AnnotationAtts.axes3D.bboxFlag = 0 AnnotationAtts.userInfoFlag = 0 AnnotationAtts.databaseInfoFlag = 0 AnnotationAtts.legendInfoFlag = 0 AnnotationAtts.axesArray.visible = 0 AnnotationAtts.backgroundColor = (0, 0, 0, 255) SetAnnotationAttributes(AnnotationAtts) #set view angle def setView(): View3DAtts = View3DAttributes() View3DAtts.viewNormal = (-0.745356, -0.596285, 0.298142) View3DAtts.focus = (153.99998, 156.99997, 0) View3DAtts.viewUp = (0, 0, 1) View3DAtts.imagePan = (0, .03) View3DAtts.imageZoom = 4 SetView3D(View3DAtts) def saveFile(fileIndex): SaveWindowAtts = SaveWindowAttributes() SaveWindowAtts.outputToCurrentDirectory = 0 SaveWindowAtts.outputDirectory = "/projects/joki9146/week_13/output/" SaveWindowAtts.fileName = "katrina"+fileIndex SaveWindowAtts.family = 0 SaveWindowAtts.format = SaveWindowAtts.PNG # BMP, CURVE, JPEG, OBJ, PNG, POSTSCRIPT, POVRAY, PPM, RGB, STL, TIFF, ULTRA, VTK, PLY SaveWindowAtts.width = 1024 SaveWindowAtts.height = 1024 SaveWindowAtts.compression = SaveWindowAtts.PackBits # None, PackBits, Jpeg, Deflate SaveWindowAtts.forceMerge = 0 SetSaveWindowAttributes(SaveWindowAtts) SaveWindow() def readLatsLons(file): fPath = os.path.join(cwDir, file) df = pd.read_csv(fPath) lats = df['Lat'].values lons = df['Lon'].values lat=[] lon=[] for i in range(0,lats.size): lat.append(lats[i]-lats[0]) for i in range(0,lons.size): lon.append(lons[i]-lons[0]) lat=np.asarray(lat) lon=np.asarray(lon) return lat, lon def readTimes(file): fPath = os.path.join(cwDir, file) df = pd.read_csv(fPath) time = df['Times'].values return time def convertLat(lat): print lat factor = 27.43435 coord = (lat) * factor print coord return coord def convertLon(lon): print lon factor = -24.07495 coord = (lon) * factor print coord return coord #main print "started" i = int(sys.argv[1]) print i cwDir = "/projects/joki9146/week_13/Data_part2/" lats, lons = readLatsLons("latslons.csv") times = readTimes("Times.csv") Launch() loadBGImage(convertLat(lats[i]), convertLon(lons[i])) openDB(str(i).zfill(3)) plotWind() plotStreamtline() addClouds() addHotTowers() addRainfall() addLight() annotation() setView() DrawPlots() saveFile(str(i).zfill(3)) DeleteAllPlots() closeDatabases(str(i).zfill(3)) Close()
[ "sohamshah225@gmail.com" ]
sohamshah225@gmail.com
ce9556d7e5b4f79026943d6b28014f74995039fa
bc38678b79fee6d92c5fe73ce6a56854421f5b70
/github_unit_1/Mod_5/sierra_python_module04-master orig/my_d_nesting.py
071f108ecf481fca1ba89863f26d8c846301b9c2
[]
no_license
JOYFLOWERS/joyflowers.github.io
8a6f757595e4a0cdca621fa4210ac021a87de679
c8417cd06489e04009a773c56f334ea629ff3905
refs/heads/master
2020-07-21T15:49:37.448128
2019-12-14T03:37:31
2019-12-14T03:37:31
206,913,024
0
0
null
null
null
null
UTF-8
Python
false
false
2,536
py
# List Nesting # Since a list can contain any type of object as an element, and a list is itself an object, a list can contain another list as an element. # Such embedding of a list inside another list is known as list nesting.Ex: The code my_list = [[5, 13], [50, 75, 100]] creates a list with two elements # that are each another list. my_list = [[10, 20], [30, 40]] print('First nested list:', my_list[0]) print('Second nested list:', my_list[1]) print('Element 0 of first nested list:', my_list[0][0]) # A list is a single-dimensional sequence of items, like a series of times, data samples, daily temperatures, etc. # List nesting allows for a programmer to also create a multi-dimensional data structure, the simplest being a two-dimensional table, # like a spreadsheet or tic-tac-toe board. The following code defines a two-dimensional table using nested lists: tic_tac_toe = [ ['X', 'O', 'X'], [' ', 'X', ' '], ['O', 'O', 'X'] ] print(tic_tac_toe[0][0], tic_tac_toe[0][1], tic_tac_toe[0][2]) print(tic_tac_toe[1][0], tic_tac_toe[1][1], tic_tac_toe[1][2]) print(tic_tac_toe[2][0], tic_tac_toe[2][1], tic_tac_toe[2][2]) # The example above creates a variable tic_tac_toe that represents a 2-dimensional table with 3 rows and 3 columns, for 3*3=9 total table entries. # Each row in the table is a nested list. Table entries can be accessed by specifying the desired row and column: tic_tac_toe [1][1] accesses the middle square # in row 1, column 1 (starting from 0), which has a value of 'X'. The following code illustrates: currency = [ [1.00, 5.00, 10.0], # US Dollars [0.75, 3.77, 7.53], # Euros [0.65, 3.25, 6.50] # British pounds ] for row in currency: for cell in row: print(cell, end=' ') print() ###Challenge 1### # Print the two-dimensional list mult_table by row and column. Hint: Use nested loops. # Sample output with input: '1 2 3,2 4 6,3 6 9': # 1 | 2 | 3 # 2 | 4 | 6 # 3 | 6 | 9 user_input= input('Enter nine numbers in the following format 1 2 3,2 4 6,3 6 9 ') lines = user_input.split(',') # # This line uses a construct called a list comprehension, introduced elsewhere, # # to convert the input string into a two-dimensional list. # # Ex: 1 2, 2 4 is converted to [ [1, 2], [2, 4] ] mult_table = [[int(num) for num in line.split()] for line in lines] for i in range(len(mult_table)): for j in range(len(mult_table)): print(mult_table[i][j],'|',end=' ') print('')
[ "noreply@github.com" ]
noreply@github.com
75058d90ba45ab474f758745b9903f613016ee98
3fc107a60ecf2144333b23401716020f8c2c6b2c
/apps/mantenimiento_equipo/models.py
88986d87fbd2fa651657ae39cef29373f9b84631
[]
no_license
TulioRafaelCuadradoHoyos/tcuadrado_parcialbase
8d00099f234bcb6f991ae0389a0792bead602e11
5818ffce00e6cb2322d0eb60ce2aca4200169214
refs/heads/master
2023-08-29T05:08:06.929208
2021-10-22T13:51:12
2021-10-22T13:51:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
538
py
from django.db import models from apps import mantenimiento from apps.equipo.models import Equipo from apps.mantenimiento.models import Mantenimiento # Create your models here. class Mantenimiento_equipo(models.Model): mantenimiento = models.ForeignKey(Mantenimiento, on_delete= models.CASCADE) equipo =models.ForeignKey(Equipo, on_delete= models.CASCADE) Descripcion =models.CharField(max_length= 50) Resultado =models.BooleanField() def __str__(self): return self.Descripcion
[ "tcuadrado@uniguajira.edu.co" ]
tcuadrado@uniguajira.edu.co
e0d3ddf444f96456a667218432e68df52fe04514
3c515d48bba2bd4dc2ecd797aaf66aa5a1ebf596
/app.py
0e59b8ca4a0597b9a814d00fc0a6345534e30c3f
[]
no_license
jason2133/flask_ai_translator
0696797644aec7a3eb9926efbba3deac9e820eaa
f3b3c1a934e2f8a1a4a551dd199c2ca5521835ac
refs/heads/master
2023-07-17T06:16:59.938651
2021-08-25T17:29:51
2021-08-25T17:29:51
399,882,270
1
0
null
null
null
null
UTF-8
Python
false
false
1,905
py
import requests, os, uuid, json from dotenv import load_dotenv load_dotenv() from flask import Flask, render_template from flask import request app = Flask(__name__) @app.route('/', methods=['GET']) def index(): return render_template('index.html') # 서비스를 호출하는 코드 @app.route('/', methods=['POST']) def index_post(): # Read the values from the form original_text = request.form['text'] target_language = request.form['language'] # Load the values from .env key = os.environ['KEY'] endpoint = os.environ['ENDPOINT'] location = os.environ['LOCATION'] # Indicate that we want to translate and the API version (3.0) and the target language path = '/translate?api-version=3.0' # Add the target language parameter target_language_parameter = '&to=' + target_language # Create the full URL constructed_url = endpoint + path + target_language_parameter # Set up the header information, which includes our subscription key headers = { 'Ocp-Apim-Subscription-Key': key, 'Ocp-Apim-Subscription-Region': location, 'Content-type': 'application/json', 'X-ClientTraceId': str(uuid.uuid4()) } # Create the body of the request with the text to be translated body = [{ 'text': original_text }] # Make the call using post translator_request = requests.post(constructed_url, headers=headers, json=body) # Retrieve the JSON response translator_response = translator_request.json() # Retrieve the translation translated_text = translator_response[0]['translations'][0]['text'] # Call render template, passing the translated text, # original text, and target language to the template return render_template( 'results.html', translated_text=translated_text, original_text=original_text, target_language=target_language )
[ "jason2133@likelion.org" ]
jason2133@likelion.org
16bc013e99ded0fe9f6941199abd40f35eefdcd6
b3ae6dc41b1930856ad70ff8a7a618112ba6c256
/nncf/definitions.py
5ca5eb73b46fad0321415b2bbec131a428039c5e
[ "Apache-2.0" ]
permissive
RikAllen/nncf_pytorch
05411fb9eb819971c5797524e6c09996b7a46aaa
db8c09d8a1f9efb6c22150ba285ce65bc879d88c
refs/heads/develop
2023-01-14T01:55:04.938358
2020-09-16T15:00:14
2020-09-16T15:00:14
289,278,649
0
0
Apache-2.0
2020-09-24T13:46:45
2020-08-21T13:39:04
Python
UTF-8
Python
false
false
1,057
py
""" Copyright (c) 2020 Intel Corporation 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 pkg_resources import os NNCF_PACKAGE_ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) HW_CONFIG_RELATIVE_DIR = "hw_configs" def get_install_type(): try: _ = pkg_resources.get_distribution('nncf') install_type = pkg_resources.resource_string(__name__, 'install_type').decode("ASCII") except pkg_resources.DistributionNotFound: # Working with NNCF while not installed as a package install_type = "GPU" return install_type
[ "noreply@github.com" ]
noreply@github.com
1c03b9aee293d47ae2cf1cba8865ea237699d603
b838762713aa551690532a7cdc8f2d4556766d2c
/sales/db/init_db.py
b8e0edfab3ff55a9fa9b11a2f0b07c7813ea6df7
[]
no_license
dmitriyignatiev/api_peewee
647ad98f9e3fda76e08f28eb4c2481f5a919db20
3d1a4a6830169a01302e37b7214ed0a1fad08ac1
refs/heads/master
2022-12-10T11:21:05.561156
2020-09-20T16:56:28
2020-09-20T16:56:28
297,037,032
0
0
null
null
null
null
UTF-8
Python
false
false
655
py
from sqlalchemy import create_engine, MetaData from sales.db.db import question from dynaconf import settings DSN = f"postgresql://{settings.DB_USER}:{settings.DB_PASSWORD}@{settings.DB_HOST}:{settings.DB_PORT}/{settings.DB_NASE}" def create_tables(engine): meta = MetaData() meta.create_all(bind=engine, tables=[question]) def sample_data(engine): conn = engine.connect() conn.execute(question.insert(), [ {'question_text': 'What\'s new?', 'pub_date': '2015-12-15 17:17:49.629+02'} ]) conn.close() if __name__ == '__main__': engine = create_engine(DSN) create_tables(engine) sample_data(engine)
[ "dmitriy.ignatiev83@gmail.com" ]
dmitriy.ignatiev83@gmail.com
c5673a94f94f72233370c9935ad7b182c58ba065
47a98fed42dc2e0b589e3f08ff9342a3d924c7ac
/pyblog/XDG_CACHE_HOME/Microsoft/Python Language Server/stubs.v1/epXVRECNA2MadRw60lZ38aCPhTXzoduilN38-UtKc2M=/python.sys.pyi
cb99aafec30445a55c1b4a04ac86042755257854
[]
no_license
mehedi432/python
bd1c592edd622ae435c9f81c0771684048290e0a
725236e1b700ef41612ccf4f2aaccdf9bc1586d4
refs/heads/master
2020-06-06T22:31:44.548167
2019-06-28T07:15:27
2019-06-28T07:15:27
145,439,734
0
0
null
null
null
null
UTF-8
Python
false
false
36,814
pyi
import _io as _mod__io import builtins as _mod_builtins import types as _mod_types def __displayhook__(): 'displayhook(object) -> None\n\nPrint an object to sys.stdout and also save it in builtins._\n' pass __doc__ = "This module provides access to some objects used or maintained by the\ninterpreter and to functions that interact strongly with the interpreter.\n\nDynamic objects:\n\nargv -- command line arguments; argv[0] is the script pathname if known\npath -- module search path; path[0] is the script directory, else ''\nmodules -- dictionary of loaded modules\n\ndisplayhook -- called to show results in an interactive session\nexcepthook -- called to handle any uncaught exception other than SystemExit\n To customize printing in an interactive session or to install a custom\n top-level exception handler, assign other functions to replace these.\n\nstdin -- standard input file object; used by input()\nstdout -- standard output file object; used by print()\nstderr -- standard error object; used for error messages\n By assigning other file objects (or objects that behave like files)\n to these, it is possible to redirect all of the interpreter's I/O.\n\nlast_type -- type of last uncaught exception\nlast_value -- value of last uncaught exception\nlast_traceback -- traceback of last uncaught exception\n These three are only available in an interactive session after a\n traceback has been printed.\n\nStatic objects:\n\nbuiltin_module_names -- tuple of module names built into this interpreter\ncopyright -- copyright notice pertaining to this interpreter\nexec_prefix -- prefix used to find the machine-specific Python library\nexecutable -- absolute path of the executable binary of the Python interpreter\nfloat_info -- a struct sequence with information about the float implementation.\nfloat_repr_style -- string indicating the style of repr() output for floats\nhash_info -- a struct sequence with information about the hash algorithm.\nhexversion -- version information encoded as a single integer\nimplementation -- Python implementation information.\nint_info -- a struct sequence with information about the int implementation.\nmaxsize -- the largest supported length of containers.\nmaxunicode -- the value of the largest Unicode code point\nplatform -- platform identifier\nprefix -- prefix used to find the Python library\nthread_info -- a struct sequence with information about the thread implementation.\nversion -- the version of this interpreter as a string\nversion_info -- version information as a named tuple\n__stdin__ -- the original stdin; don't touch!\n__stdout__ -- the original stdout; don't touch!\n__stderr__ -- the original stderr; don't touch!\n__displayhook__ -- the original displayhook; don't touch!\n__excepthook__ -- the original excepthook; don't touch!\n\nFunctions:\n\ndisplayhook() -- print an object to the screen, and save it in builtins._\nexcepthook() -- print an exception and its traceback to sys.stderr\nexc_info() -- return thread-safe information about the current exception\nexit() -- exit the interpreter by raising SystemExit\ngetdlopenflags() -- returns flags to be used for dlopen() calls\ngetprofile() -- get the global profiling function\ngetrefcount() -- return the reference count for an object (plus one :-)\ngetrecursionlimit() -- return the max recursion depth for the interpreter\ngetsizeof() -- return the size of an object in bytes\ngettrace() -- get the global debug tracing function\nsetcheckinterval() -- control how often the interpreter checks for events\nsetdlopenflags() -- set the flags to be used for dlopen() calls\nsetprofile() -- set the global profiling function\nsetrecursionlimit() -- set the max recursion depth for the interpreter\nsettrace() -- set the global debug tracing function\n" def __excepthook__(): 'excepthook(exctype, value, traceback) -> None\n\nHandle an exception by displaying it with a traceback on sys.stderr.\n' pass def __interactivehook__(): pass __name__ = 'sys' __package__ = '' __stderr__ = _mod__io.TextIOWrapper() __stdin__ = _mod__io.TextIOWrapper() __stdout__ = _mod__io.TextIOWrapper() def _clear_type_cache(): '_clear_type_cache() -> None\nClear the internal type lookup cache.' pass def _current_frames(): "_current_frames() -> dictionary\n\nReturn a dictionary mapping each current thread T's thread id to T's\ncurrent stack frame.\n\nThis function should be used for specialized purposes only." return dict() def _debugmallocstats(): "_debugmallocstats()\n\nPrint summary info to stderr about the state of\npymalloc's structures.\n\nIn Py_DEBUG mode, also perform some expensive internal consistency\nchecks.\n" pass def _getframe(depth=None): '_getframe([depth]) -> frameobject\n\nReturn a frame object from the call stack. If optional integer depth is\ngiven, return the frame object that many calls below the top of the stack.\nIf that is deeper than the call stack, ValueError is raised. The default\nfor depth is zero, returning the frame at the top of the call stack.\n\nThis function should be used for internal and specialized\npurposes only.' pass _git = _mod_builtins.tuple() _home = '/usr/bin' _xoptions = _mod_builtins.dict() abiflags = 'm' api_version = 1013 argv = _mod_builtins.list() base_exec_prefix = '/usr' base_prefix = '/usr' builtin_module_names = _mod_builtins.tuple() byteorder = 'little' def call_tracing(func, args): 'call_tracing(func, args) -> object\n\nCall func(*args), while tracing is enabled. The tracing state is\nsaved, and restored afterwards. This is intended to be called from\na debugger from a checkpoint, to recursively debug some other code.' pass def callstats(): 'callstats() -> tuple of integers\n\nReturn a tuple of function call statistics, if CALL_PROFILE was defined\nwhen Python was built. Otherwise, return None.\n\nWhen enabled, this function returns detailed, implementation-specific\ndetails about the number of function calls executed. The return value is\na 11-tuple where the entries in the tuple are counts of:\n0. all function calls\n1. calls to PyFunction_Type objects\n2. PyFunction calls that do not create an argument tuple\n3. PyFunction calls that do not create an argument tuple\n and bypass PyEval_EvalCodeEx()\n4. PyMethod calls\n5. PyMethod calls on bound methods\n6. PyType calls\n7. PyCFunction calls\n8. generator calls\n9. All other calls\n10. Number of stack pops performed by call_function()' pass copyright = 'Copyright (c) 2001-2018 Python Software Foundation.\nAll Rights Reserved.\n\nCopyright (c) 2000 BeOpen.com.\nAll Rights Reserved.\n\nCopyright (c) 1995-2001 Corporation for National Research Initiatives.\nAll Rights Reserved.\n\nCopyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\nAll Rights Reserved.' def displayhook(object): 'displayhook(object) -> None\n\nPrint an object to sys.stdout and also save it in builtins._\n' pass dont_write_bytecode = True def exc_info(): 'exc_info() -> (type, value, traceback)\n\nReturn information about the most recent exception caught by an except\nclause in the current stack frame or in an older stack frame.' return tuple() def excepthook(exctype, value, traceback): 'excepthook(exctype, value, traceback) -> None\n\nHandle an exception by displaying it with a traceback on sys.stderr.\n' pass exec_prefix = '/home/mehedi/python/blog/venv' executable = '/home/mehedi/python/blog/venv/bin/python' def exit(status=None): 'exit([status])\n\nExit the interpreter by raising SystemExit(status).\nIf the status is omitted or None, it defaults to zero (i.e., success).\nIf the status is an integer, it will be used as the system exit status.\nIf it is another kind of object, it will be printed and the system\nexit status will be one (i.e., failure).' pass class flags(_mod_builtins.tuple): 'sys.flags\n\nFlags provided through command line arguments or environment vars.' @staticmethod def __add__(self, value): 'Return self+value.' return __T__() __class__ = flags @staticmethod def __contains__(self, key): 'Return key in self.' return False @staticmethod def __delattr__(self, name): 'Implement delattr(self, name).' return None @staticmethod def __dir__(self): '__dir__() -> list\ndefault dir() implementation' return [''] @staticmethod def __eq__(self, value): 'Return self==value.' return False @staticmethod def __format__(self, format_spec): 'default object formatter' return '' @staticmethod def __ge__(self, value): 'Return self>=value.' return False @staticmethod def __getattribute__(self, name): 'Return getattr(self, name).' pass @staticmethod def __getitem__(self, key): 'Return self[key].' pass @staticmethod def __getnewargs__(self): return () @staticmethod def __gt__(self, value): 'Return self>value.' return False @staticmethod def __hash__(self): 'Return hash(self).' return 0 @staticmethod def __init__(self, *args, **kwargs): 'sys.flags\n\nFlags provided through command line arguments or environment vars.' pass @staticmethod def __init_subclass__(cls): 'This method is called when a class is subclassed.\n\nThe default implementation does nothing. It may be\noverridden to extend subclasses.\n' return None @staticmethod def __iter__(self): 'Implement iter(self).' return __T__() @staticmethod def __le__(self, value): 'Return self<=value.' return False @staticmethod def __len__(self): 'Return len(self).' return 0 @staticmethod def __lt__(self, value): 'Return self<value.' return False @staticmethod def __mul__(self, value): 'Return self*value.' return __T__() @staticmethod def __ne__(self, value): 'Return self!=value.' return False @staticmethod def __reduce__(self): return ''; return () @staticmethod def __reduce_ex__(self, protocol): 'helper for pickle' return ''; return () @staticmethod def __repr__(self): 'Return repr(self).' return '' @staticmethod def __rmul__(self, value): 'Return value*self.' return __T__() @staticmethod def __setattr__(self, name, value): 'Implement setattr(self, name, value).' return None @staticmethod def __sizeof__(self): '__sizeof__() -> int\nsize of object in memory, in bytes' return 0 @staticmethod def __str__(self): 'Return str(self).' return '' @staticmethod def __subclasshook__(cls, subclass): 'Abstract classes can override this to customize issubclass().\n\nThis is invoked early on by abc.ABCMeta.__subclasscheck__().\nIt should return True, False or NotImplemented. If it returns\nNotImplemented, the normal algorithm is used. Otherwise, it\noverrides the normal algorithm (and the outcome is cached).\n' return False bytes_warning = 0 @staticmethod def count(): 'T.count(value) -> integer -- return number of occurrences of value' return 1 debug = 0 dont_write_bytecode = 1 hash_randomization = 1 ignore_environment = 1 @staticmethod def index(): 'T.index(value, [start, [stop]]) -> integer -- return first index of value.\nRaises ValueError if the value is not present.' return 1 inspect = 0 interactive = 0 isolated = 0 n_fields = 13 n_sequence_fields = 13 n_unnamed_fields = 0 no_site = 0 no_user_site = 0 optimize = 0 quiet = 0 verbose = 0 class __float_info(_mod_builtins.tuple): "sys.float_info\n\nA structseq holding information about the float type. It contains low level\ninformation about the precision and internal representation. Please study\nyour system's :file:`float.h` for more information." def __add__(self, value): 'Return self+value.' return __float_info() __class__ = __float_info def __contains__(self, key): 'Return key in self.' return False def __delattr__(self, name): 'Implement delattr(self, name).' return None @classmethod def __dir__(self): '__dir__() -> list\ndefault dir() implementation' return [''] def __eq__(self, value): 'Return self==value.' return False @classmethod def __format__(self, format_spec): 'default object formatter' return '' def __ge__(self, value): 'Return self>=value.' return False def __getattribute__(self, name): 'Return getattr(self, name).' pass def __getitem__(self, key): 'Return self[key].' pass @classmethod def __getnewargs__(self): return () def __gt__(self, value): 'Return self>value.' return False def __hash__(self): 'Return hash(self).' return 0 def __init__(self, *args, **kwargs): "sys.float_info\n\nA structseq holding information about the float type. It contains low level\ninformation about the precision and internal representation. Please study\nyour system's :file:`float.h` for more information." pass @classmethod def __init_subclass__(cls): 'This method is called when a class is subclassed.\n\nThe default implementation does nothing. It may be\noverridden to extend subclasses.\n' return None def __iter__(self): 'Implement iter(self).' return __float_info() def __le__(self, value): 'Return self<=value.' return False def __len__(self): 'Return len(self).' return 0 def __lt__(self, value): 'Return self<value.' return False def __mul__(self, value): 'Return self*value.' return __float_info() def __ne__(self, value): 'Return self!=value.' return False @classmethod def __reduce__(self): return ''; return () @classmethod def __reduce_ex__(self, protocol): 'helper for pickle' return ''; return () def __repr__(self): 'Return repr(self).' return '' def __rmul__(self, value): 'Return value*self.' return __float_info() def __setattr__(self, name, value): 'Implement setattr(self, name, value).' return None @classmethod def __sizeof__(self): '__sizeof__() -> int\nsize of object in memory, in bytes' return 0 def __str__(self): 'Return str(self).' return '' @classmethod def __subclasshook__(cls, subclass): 'Abstract classes can override this to customize issubclass().\n\nThis is invoked early on by abc.ABCMeta.__subclasscheck__().\nIt should return True, False or NotImplemented. If it returns\nNotImplemented, the normal algorithm is used. Otherwise, it\noverrides the normal algorithm (and the outcome is cached).\n' return False @classmethod def count(cls): 'T.count(value) -> integer -- return number of occurrences of value' return 1 dig = 15 epsilon = 2.220446049250313e-16 @classmethod def index(cls): 'T.index(value, [start, [stop]]) -> integer -- return first index of value.\nRaises ValueError if the value is not present.' return 1 mant_dig = 53 max = 1.7976931348623157e+308 max_10_exp = 308 max_exp = 1024 min = 2.2250738585072014e-308 min_10_exp = -307 min_exp = -1021 n_fields = 11 n_sequence_fields = 11 n_unnamed_fields = 0 radix = 2 rounds = 1 float_repr_style = 'short' def get_asyncgen_hooks(): 'get_asyncgen_hooks()\n\nReturn a namedtuple of installed asynchronous generators hooks (firstiter, finalizer).' pass def get_coroutine_wrapper(): 'get_coroutine_wrapper()\n\nReturn the wrapper for coroutine objects set by sys.set_coroutine_wrapper.' pass def getallocatedblocks(): 'getallocatedblocks() -> integer\n\nReturn the number of memory blocks currently allocated, regardless of their\nsize.' return 1 def getcheckinterval(): 'getcheckinterval() -> current check interval; see setcheckinterval().' pass def getdefaultencoding(): 'getdefaultencoding() -> string\n\nReturn the current default string encoding used by the Unicode \nimplementation.' return '' def getdlopenflags(): 'getdlopenflags() -> int\n\nReturn the current value of the flags that are used for dlopen calls.\nThe flag constants are defined in the os module.' return 1 def getfilesystemencodeerrors(): 'getfilesystemencodeerrors() -> string\n\nReturn the error mode used to convert Unicode filenames in\noperating system filenames.' return '' def getfilesystemencoding(): 'getfilesystemencoding() -> string\n\nReturn the encoding used to convert Unicode filenames in\noperating system filenames.' return '' def getprofile(): 'getprofile()\n\nReturn the profiling function set with sys.setprofile.\nSee the profiler chapter in the library manual.' pass def getrecursionlimit(): 'getrecursionlimit()\n\nReturn the current value of the recursion limit, the maximum depth\nof the Python interpreter stack. This limit prevents infinite\nrecursion from causing an overflow of the C stack and crashing Python.' pass def getrefcount(object): 'getrefcount(object) -> integer\n\nReturn the reference count of object. The count returned is generally\none higher than you might expect, because it includes the (temporary)\nreference as an argument to getrefcount().' return 1 def getsizeof(object, default): 'getsizeof(object, default) -> int\n\nReturn the size of object in bytes.' return 1 def getswitchinterval(): 'getswitchinterval() -> current thread switch interval; see setswitchinterval().' pass def gettrace(): 'gettrace()\n\nReturn the global debug tracing function set with sys.settrace.\nSee the debugger chapter in the library manual.' pass class __hash_info(_mod_builtins.tuple): 'hash_info\n\nA struct sequence providing parameters used for computing\nhashes. The attributes are read only.' def __add__(self, value): 'Return self+value.' return __hash_info() __class__ = __hash_info def __contains__(self, key): 'Return key in self.' return False def __delattr__(self, name): 'Implement delattr(self, name).' return None @classmethod def __dir__(self): '__dir__() -> list\ndefault dir() implementation' return [''] def __eq__(self, value): 'Return self==value.' return False @classmethod def __format__(self, format_spec): 'default object formatter' return '' def __ge__(self, value): 'Return self>=value.' return False def __getattribute__(self, name): 'Return getattr(self, name).' pass def __getitem__(self, key): 'Return self[key].' pass @classmethod def __getnewargs__(self): return () def __gt__(self, value): 'Return self>value.' return False def __hash__(self): 'Return hash(self).' return 0 def __init__(self, *args, **kwargs): 'hash_info\n\nA struct sequence providing parameters used for computing\nhashes. The attributes are read only.' pass @classmethod def __init_subclass__(cls): 'This method is called when a class is subclassed.\n\nThe default implementation does nothing. It may be\noverridden to extend subclasses.\n' return None def __iter__(self): 'Implement iter(self).' return __hash_info() def __le__(self, value): 'Return self<=value.' return False def __len__(self): 'Return len(self).' return 0 def __lt__(self, value): 'Return self<value.' return False def __mul__(self, value): 'Return self*value.' return __hash_info() def __ne__(self, value): 'Return self!=value.' return False @classmethod def __reduce__(self): return ''; return () @classmethod def __reduce_ex__(self, protocol): 'helper for pickle' return ''; return () def __repr__(self): 'Return repr(self).' return '' def __rmul__(self, value): 'Return value*self.' return __hash_info() def __setattr__(self, name, value): 'Implement setattr(self, name, value).' return None @classmethod def __sizeof__(self): '__sizeof__() -> int\nsize of object in memory, in bytes' return 0 def __str__(self): 'Return str(self).' return '' @classmethod def __subclasshook__(cls, subclass): 'Abstract classes can override this to customize issubclass().\n\nThis is invoked early on by abc.ABCMeta.__subclasscheck__().\nIt should return True, False or NotImplemented. If it returns\nNotImplemented, the normal algorithm is used. Otherwise, it\noverrides the normal algorithm (and the outcome is cached).\n' return False algorithm = 'siphash24' @classmethod def count(cls): 'T.count(value) -> integer -- return number of occurrences of value' return 1 cutoff = 0 hash_bits = 64 imag = 1000003 @classmethod def index(cls): 'T.index(value, [start, [stop]]) -> integer -- return first index of value.\nRaises ValueError if the value is not present.' return 1 inf = 314159 modulus = 2305843009213693951 n_fields = 9 n_sequence_fields = 9 n_unnamed_fields = 0 nan = 0 seed_bits = 128 width = 64 hexversion = 50727152 implementation = _mod_types.SimpleNamespace() class __int_info(_mod_builtins.tuple): "sys.int_info\n\nA struct sequence that holds information about Python's\ninternal representation of integers. The attributes are read only." def __add__(self, value): 'Return self+value.' return __int_info() __class__ = __int_info def __contains__(self, key): 'Return key in self.' return False def __delattr__(self, name): 'Implement delattr(self, name).' return None @classmethod def __dir__(self): '__dir__() -> list\ndefault dir() implementation' return [''] def __eq__(self, value): 'Return self==value.' return False @classmethod def __format__(self, format_spec): 'default object formatter' return '' def __ge__(self, value): 'Return self>=value.' return False def __getattribute__(self, name): 'Return getattr(self, name).' pass def __getitem__(self, key): 'Return self[key].' pass @classmethod def __getnewargs__(self): return () def __gt__(self, value): 'Return self>value.' return False def __hash__(self): 'Return hash(self).' return 0 def __init__(self, *args, **kwargs): "sys.int_info\n\nA struct sequence that holds information about Python's\ninternal representation of integers. The attributes are read only." pass @classmethod def __init_subclass__(cls): 'This method is called when a class is subclassed.\n\nThe default implementation does nothing. It may be\noverridden to extend subclasses.\n' return None def __iter__(self): 'Implement iter(self).' return __int_info() def __le__(self, value): 'Return self<=value.' return False def __len__(self): 'Return len(self).' return 0 def __lt__(self, value): 'Return self<value.' return False def __mul__(self, value): 'Return self*value.' return __int_info() def __ne__(self, value): 'Return self!=value.' return False @classmethod def __reduce__(self): return ''; return () @classmethod def __reduce_ex__(self, protocol): 'helper for pickle' return ''; return () def __repr__(self): 'Return repr(self).' return '' def __rmul__(self, value): 'Return value*self.' return __int_info() def __setattr__(self, name, value): 'Implement setattr(self, name, value).' return None @classmethod def __sizeof__(self): '__sizeof__() -> int\nsize of object in memory, in bytes' return 0 def __str__(self): 'Return str(self).' return '' @classmethod def __subclasshook__(cls, subclass): 'Abstract classes can override this to customize issubclass().\n\nThis is invoked early on by abc.ABCMeta.__subclasscheck__().\nIt should return True, False or NotImplemented. If it returns\nNotImplemented, the normal algorithm is used. Otherwise, it\noverrides the normal algorithm (and the outcome is cached).\n' return False bits_per_digit = 30 @classmethod def count(cls): 'T.count(value) -> integer -- return number of occurrences of value' return 1 @classmethod def index(cls): 'T.index(value, [start, [stop]]) -> integer -- return first index of value.\nRaises ValueError if the value is not present.' return 1 n_fields = 2 n_sequence_fields = 2 n_unnamed_fields = 0 sizeof_digit = 4 def intern(string): "intern(string) -> string\n\n``Intern'' the given string. This enters the string in the (global)\ntable of interned strings whose purpose is to speed up dictionary lookups.\nReturn the string itself or the previously interned string object with the\nsame value." return '' def is_finalizing(): 'is_finalizing()\nReturn True if Python is exiting.' pass maxsize = 9223372036854775807 maxunicode = 1114111 meta_path = _mod_builtins.list() modules = _mod_builtins.dict() path = _mod_builtins.list() path_hooks = _mod_builtins.list() path_importer_cache = _mod_builtins.dict() platform = 'linux' prefix = '/home/mehedi/python/blog/venv' def set_asyncgen_hooks(*, firstiter=None, finalizer=None): 'set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\nSet a finalizer for async generators objects.' pass def set_coroutine_wrapper(wrapper): 'set_coroutine_wrapper(wrapper)\n\nSet a wrapper for coroutine objects.' pass def setcheckinterval(n): 'setcheckinterval(n)\n\nTell the Python interpreter to check for asynchronous events every\nn instructions. This also affects how often thread switches occur.' pass def setdlopenflags(n): 'setdlopenflags(n) -> None\n\nSet the flags used by the interpreter for dlopen calls, such as when the\ninterpreter loads extension modules. Among other things, this will enable\na lazy resolving of symbols when importing a module, if called as\nsys.setdlopenflags(0). To share symbols across extension modules, call as\nsys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\ncan be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).' pass def setprofile(function): 'setprofile(function)\n\nSet the profiling function. It will be called on each function call\nand return. See the profiler chapter in the library manual.' pass def setrecursionlimit(n): 'setrecursionlimit(n)\n\nSet the maximum depth of the Python interpreter stack to n. This\nlimit prevents infinite recursion from causing an overflow of the C\nstack and crashing Python. The highest possible limit is platform-\ndependent.' pass def setswitchinterval(n): 'setswitchinterval(n)\n\nSet the ideal thread switching delay inside the Python interpreter\nThe actual frequency of switching threads can be lower if the\ninterpreter executes long sequences of uninterruptible code\n(this is implementation-specific and workload-dependent).\n\nThe parameter must represent the desired switching delay in seconds\nA typical value is 0.005 (5 milliseconds).' pass def settrace(function): 'settrace(function)\n\nSet the global debug tracing function. It will be called on each\nfunction call. See the debugger chapter in the library manual.' pass stderr = _mod__io.TextIOWrapper() stdin = _mod__io.TextIOWrapper() stdout = _mod__io.TextIOWrapper() class __thread_info(_mod_builtins.tuple): 'sys.thread_info\n\nA struct sequence holding information about the thread implementation.' def __add__(self, value): 'Return self+value.' return __thread_info() __class__ = __thread_info def __contains__(self, key): 'Return key in self.' return False def __delattr__(self, name): 'Implement delattr(self, name).' return None @classmethod def __dir__(self): '__dir__() -> list\ndefault dir() implementation' return [''] def __eq__(self, value): 'Return self==value.' return False @classmethod def __format__(self, format_spec): 'default object formatter' return '' def __ge__(self, value): 'Return self>=value.' return False def __getattribute__(self, name): 'Return getattr(self, name).' pass def __getitem__(self, key): 'Return self[key].' pass @classmethod def __getnewargs__(self): return () def __gt__(self, value): 'Return self>value.' return False def __hash__(self): 'Return hash(self).' return 0 def __init__(self, *args, **kwargs): 'sys.thread_info\n\nA struct sequence holding information about the thread implementation.' pass @classmethod def __init_subclass__(cls): 'This method is called when a class is subclassed.\n\nThe default implementation does nothing. It may be\noverridden to extend subclasses.\n' return None def __iter__(self): 'Implement iter(self).' return __thread_info() def __le__(self, value): 'Return self<=value.' return False def __len__(self): 'Return len(self).' return 0 def __lt__(self, value): 'Return self<value.' return False def __mul__(self, value): 'Return self*value.' return __thread_info() def __ne__(self, value): 'Return self!=value.' return False @classmethod def __reduce__(self): return ''; return () @classmethod def __reduce_ex__(self, protocol): 'helper for pickle' return ''; return () def __repr__(self): 'Return repr(self).' return '' def __rmul__(self, value): 'Return value*self.' return __thread_info() def __setattr__(self, name, value): 'Implement setattr(self, name, value).' return None @classmethod def __sizeof__(self): '__sizeof__() -> int\nsize of object in memory, in bytes' return 0 def __str__(self): 'Return str(self).' return '' @classmethod def __subclasshook__(cls, subclass): 'Abstract classes can override this to customize issubclass().\n\nThis is invoked early on by abc.ABCMeta.__subclasscheck__().\nIt should return True, False or NotImplemented. If it returns\nNotImplemented, the normal algorithm is used. Otherwise, it\noverrides the normal algorithm (and the outcome is cached).\n' return False @classmethod def count(cls): 'T.count(value) -> integer -- return number of occurrences of value' return 1 @classmethod def index(cls): 'T.index(value, [start, [stop]]) -> integer -- return first index of value.\nRaises ValueError if the value is not present.' return 1 lock = 'semaphore' n_fields = 3 n_sequence_fields = 3 n_unnamed_fields = 0 name = 'pthread' version = 'NPTL 2.28' version = '3.6.8 (default, Apr 9 2019, 04:59:38) \n[GCC 8.3.0]' class __version_info(_mod_builtins.tuple): 'sys.version_info\n\nVersion information as a named tuple.' def __add__(self, value): 'Return self+value.' return __version_info() __class__ = __version_info def __contains__(self, key): 'Return key in self.' return False def __delattr__(self, name): 'Implement delattr(self, name).' return None @classmethod def __dir__(self): '__dir__() -> list\ndefault dir() implementation' return [''] def __eq__(self, value): 'Return self==value.' return False @classmethod def __format__(self, format_spec): 'default object formatter' return '' def __ge__(self, value): 'Return self>=value.' return False def __getattribute__(self, name): 'Return getattr(self, name).' pass def __getitem__(self, key): 'Return self[key].' pass @classmethod def __getnewargs__(self): return () def __gt__(self, value): 'Return self>value.' return False def __hash__(self): 'Return hash(self).' return 0 def __init__(self, *args, **kwargs): 'sys.version_info\n\nVersion information as a named tuple.' pass @classmethod def __init_subclass__(cls): 'This method is called when a class is subclassed.\n\nThe default implementation does nothing. It may be\noverridden to extend subclasses.\n' return None def __iter__(self): 'Implement iter(self).' return __version_info() def __le__(self, value): 'Return self<=value.' return False def __len__(self): 'Return len(self).' return 0 def __lt__(self, value): 'Return self<value.' return False def __mul__(self, value): 'Return self*value.' return __version_info() def __ne__(self, value): 'Return self!=value.' return False @classmethod def __reduce__(self): return ''; return () @classmethod def __reduce_ex__(self, protocol): 'helper for pickle' return ''; return () def __repr__(self): 'Return repr(self).' return '' def __rmul__(self, value): 'Return value*self.' return __version_info() def __setattr__(self, name, value): 'Implement setattr(self, name, value).' return None @classmethod def __sizeof__(self): '__sizeof__() -> int\nsize of object in memory, in bytes' return 0 def __str__(self): 'Return str(self).' return '' @classmethod def __subclasshook__(cls, subclass): 'Abstract classes can override this to customize issubclass().\n\nThis is invoked early on by abc.ABCMeta.__subclasscheck__().\nIt should return True, False or NotImplemented. If it returns\nNotImplemented, the normal algorithm is used. Otherwise, it\noverrides the normal algorithm (and the outcome is cached).\n' return False @classmethod def count(cls): 'T.count(value) -> integer -- return number of occurrences of value' return 1 @classmethod def index(cls): 'T.index(value, [start, [stop]]) -> integer -- return first index of value.\nRaises ValueError if the value is not present.' return 1 major = 3 micro = 8 minor = 6 n_fields = 5 n_sequence_fields = 5 n_unnamed_fields = 0 releaselevel = 'final' serial = 0 warnoptions = _mod_builtins.list() float_info = __float_info() hash_info = __hash_info() int_info = __int_info() thread_info = __thread_info() version_info = __version_info()
[ "aamehedi93@gmail.com" ]
aamehedi93@gmail.com
6c1be986fca786a6854705ef2349ec7574a2437b
36b6384001de57775b908234952d7f410402e715
/main.py
6260a322ce1f34873400488ad9182cb24be8b18e
[ "BSD-3-Clause" ]
permissive
furkankykc/AutomatedDocumentMailer
d3140660d3235ebe145f6a73abf4536f1cce920c
f5216e788f9570ed148652f83eb58d1f9a8ef5e8
refs/heads/master
2021-06-30T05:54:30.304651
2020-09-13T17:23:46
2020-09-13T17:23:46
130,085,577
0
0
null
null
null
null
UTF-8
Python
false
false
126
py
from Mailer.loginform import LoginGui from Mailer.gui import Gui if __name__ == '__main__': LoginGui() # Gui('xbet')
[ "furkankykc@gmail.com" ]
furkankykc@gmail.com
439a6cef4d180ab24ddfab790d339f28dba304de
e0def6cfcef03922758940ee1d5ec7a891fafaf0
/files/10_create_altered_rides_table.py
6cb774324fdab5252ebc9c6141eaf892a3b221e4
[]
no_license
DataLiftoff/Analysis_Of_The_Movement_Of_Rental_Bikes
8705845379c20c12267429cd2fc0448e32133423
f5656f247616ca84e2e9925a3437b3d86d7252a2
refs/heads/master
2023-01-05T08:54:17.745088
2020-10-01T21:46:20
2020-10-01T21:46:20
300,298,588
0
0
null
null
null
null
UTF-8
Python
false
false
3,270
py
##### Import Libraries # To load OpenStreetMap-data import osmnx as ox # To work with networks import networkx as nx # To connect to databases from helperFunctions import Graph from helperFunctions import alterRoute from helperFunctions import connectZEO from helperFunctions import connectMySQL from helperFunctions import connectMongo from helperFunctions import containerWait from helperFunctions import managementUpdate ##### Run Program # Wait for the MySQL server to start containerWait() try: # Connect to ZODB root = connectZEO() # Connect to MongoDb cluster, db_mongo, collection_altered = connectMongo(collection='altered') collection_shortest = db_mongo['shortest'] # Connect to MySQL and get cursor db_mysql, cur = connectMySQL() ##### Iterate Over All Cities And Alter The Path # Iterate over all cities while True: # SQL query sql_query = 'SELECT cluster_id FROM city_clusters WHERE city_analyse=1 AND last_osm_graph>last_rides_altered ORDER BY RAND() LIMIT 1' # Execute the query cur.execute(sql_query) cluster_id = cur.fetchall() # Check if clusters are left if not cluster_id: break # Extract data cluster_id = cluster_id[0][0] # Update timestamp for city managementUpdate('last_rides_altered', cur, db_mysql, table='city_clusters', row='cluster_id', id=cluster_id) # Load the graph from the ZODB graph = root[cluster_id].graph # Iterate over all shortest rides for item in collection_shortest.find({'Cluster_Id':cluster_id}): # Create key for dictionary key = item['_id'] # Get precomputed altered paths precomputed_altered = collection_altered.find_one({'_id':key}) # Stop to much computation if precomputed_altered and item['Count']==precomputed_altered['Count']: continue # Check if ride has to be recomputed if precomputed_altered: # Copy precomputed ride to rides rides = precomputed_altered['Rides'] lengths = precomputed_altered['Lengths'] count = precomputed_altered['Count'] else: # Set default values rides = [] lengths = [] count = 0 # Compute the number of missing rides n_missing_rides = item['Count'] - count # Create an altered ride for each count for _ in range(n_missing_rides): # Alter and save each ride ride_altered = alterRoute(item['Ride'], graph, p=0.2) # Compute ride length ride_length = sum(ox.utils_graph.get_route_edge_attributes(graph, ride_altered, attribute='length')) # Store the altered rides rides.append(list(map(int, ride_altered))) lengths.append(ride_length) count += 1 # Update the altered rides in the database collection_altered.update_one({'_id':key}, {'$set':{'_id':key, 'Rides':rides, 'Count':count, 'Lengths':lengths, 'Cluster_Id':cluster_id}}, upsert=True) except mysql.connector.Error as error: print(error) finally: if (db_mysql.is_connected()): db_mysql.close() print('Database has been closed.')
[ "noreply@github.com" ]
noreply@github.com
80d9fb03a91fc8eae47a8e9b11cc9d472ab29f0b
48285275958aba8f8f14ce505f03acf117870584
/src/handlers/HandlerFactory.py
f961b917d06c235f64305e5deaa2a39e94088b0e
[]
no_license
rchuso/Python-Web-Server
095609586c8fb403380752cd99408800d760d8e8
1fe8fdfc77d220923b8ebfafbc759bae1be4074c
refs/heads/master
2021-05-17T18:54:09.141504
2020-04-02T06:23:16
2020-04-02T06:23:16
250,927,592
0
0
null
null
null
null
UTF-8
Python
false
false
2,283
py
''' Created on 15/03/2020 @author: rand huso ''' import os from handlers.HandlerImage import HandlerImage from handlers.HandlerText import HandlerText from handlers.HandlerBad import HandlerBad class HandlerFactory(): handlerTypes = { 'html': {'handler': HandlerText, 'type':'html', 'contentType':'text/html', 'bytes': False }, 'css': {'handler': HandlerText, 'type':'css', 'contentType':'text/css', 'bytes': False }, 'js': {'handler': HandlerText, 'type':'js', 'contentType':'text/javascript', 'bytes': False }, 'json': {'handler': HandlerText, 'type':'json', 'contentType':'application/json', 'bytes': False }, 'ico': {'handler': HandlerImage, 'type':'ico', 'contentType':'image/vnd.microsoft.icon', 'bytes': True }, 'jpg': {'handler': HandlerImage, 'type':'jpg', 'contentType':'image/jpeg', 'bytes': True }, 'png': {'handler': HandlerImage, 'type':'png', 'contentType':'image/png', 'bytes': True }, } def __new__( self, host, URI, headers, postVars=None ): hostQueryFragment = URI.split( '#' ) # will be len=1 if none if 1 == len(hostQueryFragment): fragment = None else: fragment = hostQueryFragment[1] hostQuery = hostQueryFragment[0].split( '?' ) requestPath = hostQuery[0] if '/' == requestPath: requestPath = '/index.html' hostSuffix = os.path.splitext( requestPath ) query = {} if 1 < len(hostQuery): querySplit = hostQuery[1].split( '&' ) # cheap and dirty for qs in querySplit: qss = qs.split( '=' ) query[qss[0]] = qss[1] if postVars is not None: for postVar in postVars: pv = postVar.decode( 'utf-8' ) val = [ v.decode( 'utf-8' ) for v in postVars[postVar]] # it's an array, for some reason query[pv] = val[0] # lose the other information. TODO: could check to see if _is list_ suffix = hostSuffix[1][1:] try: if '..' in requestPath: response = HandlerBad( host, requestPath, query, fragment, headers, HandlerFactory.handlerTypes['html'] ) else: handlerInfo = HandlerFactory.handlerTypes[suffix] response = handlerInfo['handler']( host, requestPath, query, fragment, headers, handlerInfo ) except KeyError: response = HandlerBad( host, requestPath, query, fragment, headers, HandlerFactory.handlerTypes['html'] ) return response
[ "rchuso@gmail.com" ]
rchuso@gmail.com
e2274c4b1495ca6b6d568d9fbaeb1af253a5788c
13e2726a6e25fd4020713c111fc7eb2f3018fc3d
/Product_recommendation/wsgi.py
c231d1b341a002954b6c6cd20d5a424ba336b998
[]
no_license
Abishek-Balasubramaniam/Product-recommendation
e6d9bbf9e5c32cacda0bbb87d4a518fa26b36400
e307d6e0eaa7ee1a070fff3ecbb41034f67d78ea
refs/heads/main
2023-01-31T07:26:40.674404
2020-12-15T12:29:22
2020-12-15T12:29:22
321,660,980
0
0
null
null
null
null
UTF-8
Python
false
false
421
py
""" WSGI config for Product_recommendation project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Product_recommendation.settings') application = get_wsgi_application()
[ "2903abi@gmail.com" ]
2903abi@gmail.com
7d6af601707ee714c69284f9139215e5417fc341
895700e89119ef4140befdc38588e51af48793cf
/Hongik_Class/Circular_List.py
94a0053cfded54f194a6a56ee8db88555974e7b9
[]
no_license
yoonsangmin/Coding_Test
d17096c5f867c21c05ddcbd854b2a0f32367611c
122bccd2c584f4f2babad835ea22c12352f690c1
refs/heads/master
2023-01-08T06:47:53.276862
2020-11-13T01:42:36
2020-11-13T01:42:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,368
py
#원형 리스트 #https://blex.me/@baealex/%ED%8C%8C%EC%9D%B4%EC%8D%AC%EC%9C%BC%EB%A1%9C-%EA%B5%AC%ED%98%84%ED%95%9C-%EC%9E%90%EB%A3%8C%EA%B5%AC%EC%A1%B0-%EC%97%B0%EA%B2%B0-%EB%A6%AC%EC%8A%A4%ED%8A%B8 #위의 코드 중 오류 수정 버전 #Node는 [ Data | Next ] # <Head> <Tail> # CircleLinkedList는 [ Data | Next ] --> [ Data | Next ] --> [ Data | Next ] # | | # ----------------------------------------------- class Node: def __init__(self, data): self.data = data self.next = None class CircleLinkedList: def __init__(self, data): new_node = Node(data) self.head = new_node self.tail = None self.list_size = 1 def __str__(self): print_list = '[ ' node = self.head while True: if node: print_list += str(node.data) if node == self.tail: # 단순 연결 리스트와 달리 # 노드가 테일 노드면 끝난다 break node = node.next print_list += ', ' print_list += ' ]' return print_list #헤드 추가 함수 def insertFirst(self, data): new_node = Node(data) if self.tail == None: #테일 추가 self.tail = self.head temp_node = self.head self.head = new_node self.head.next = temp_node self.tail.next = new_node #테일 추가 self.list_size += 1 #중간에 넣는 함수는 동일 def insertMiddle(self, num, data): node = self.selectNode(num) new_node = Node(data) temp_next = node.next node.next = new_node new_node.next = temp_next self.list_size += 1 #맨 마지막에 넘느 함수는 tail 처리 필요 def insertLast(self, data): new_node = Node(data) if self.tail == None: self.tail = new_node self.head.next = self.tail else: self.tail.next = new_node self.tail = new_node self.tail.next = self.head self.list_size += 1 def selectNode(self, num): if self.list_size < num: print("Overflow") return node = self.head count = 0 while count < num: node = node.next count += 1 return node def deleteNode(self, num): if self.list_size < 1: return # Underflow elif self.list_size < num: return # Overflow if num == 0: self.deleteHead() return node = self.selectNode(num - 1) node.next = node.next.next del_node = node.next del del_node def deleteHead(self): node = self.head self.head = node.next del node def size(self): return str(self.list_size) def get_head_tail(self): return self.head.data, self.tail.data #메인 함수 if __name__ == "__main__": a = CircleLinkedList(100) print(a.size()) a.insertFirst(999) a.insertFirst(9990) a.insertLast(77) a.insertMiddle(2, 500) b, c = a.get_head_tail() print("head:{} tail:{}".format(b, c)) print(a)
[ "kacias@daum.net" ]
kacias@daum.net
cb4b16dd237ab801af0b21ca00cf08970de29bf8
e8c82271070e33bb6b181616a0a518d8f8fc6158
/fce/numpy/distutils/tests/f2py_ext/tests/PaxHeader/test_fib2.py
a56021af7be6b185d62870db000c6c9d53082297
[]
no_license
DataRozhlas/profil-volice-share
aafa0a93b26de0773fa6bf2b7d513a5ec856ce38
b4424527fe36e0cd613f7bde8033feeecb7e2e94
refs/heads/master
2020-03-18T01:44:26.136999
2018-05-20T12:19:24
2018-05-20T12:19:24
null
0
0
null
null
null
null
UTF-8
Python
false
false
136
py
17 gid=713727123 15 uid=3629613 20 ctime=1458667064 20 atime=1458667064 23 SCHILY.dev=16777220 23 SCHILY.ino=31296593 18 SCHILY.nlink=1
[ "honza@datastory.cz" ]
honza@datastory.cz
372ffb8f05abddeea2704b81e3dfd8ba8d5fa88e
236332a967f8f02291b58cab7addfeabdfe7b9a2
/experiments/tests/testing_2_3.py
207477ec55fb3dd07e0cb74d22864d4061c012cc
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ConsumerAffairs/django-experiments
2dbf04b7f0e7ebdff6d5e7879afeb26f7fdb5150
4f1591c9b40390f7302f3777df231ffe3629f00d
refs/heads/master
2021-01-20T11:10:30.199586
2018-04-20T21:26:18
2018-04-20T21:26:18
101,666,220
0
10
MIT
2018-04-20T21:26:19
2017-08-28T16:56:16
Python
UTF-8
Python
false
false
218
py
# coding=utf-8 try: from unittest import mock, skip except ImportError: import mock class DummyLockTests(object): @classmethod def new(cls): test_class = cls return skip(test_class)
[ "fran.hrzenjak@gmail.com" ]
fran.hrzenjak@gmail.com
7b04a97c368a3b4a75712cea5bdf04c07cc5ca00
e833c155f1bbc446dbf83fe9d09eb2eeaf676cf6
/Year1/CSCA48/Assignments/a1/a1_design.py
83177c2b87e4902065241d535781d23bf53a8964
[]
no_license
vincentt117/UTSC.CS
116ebb41caaafbfaea8172d72c7fd507cfa771cb
ffa1a5bea2b85f3afe75b01830786bc584d2da06
refs/heads/master
2020-09-22T12:48:09.539263
2017-01-30T15:58:39
2017-01-30T15:58:39
67,225,189
0
0
null
null
null
null
UTF-8
Python
false
false
8,249
py
class Matrix(): ''' A class which represents a mathematical matrix ''' def __init__(self, content): '''(Matrix, list of obj) -> None Creates a matrix where a dictionary with keys as two element lists containing the row (element zero) and column (element one) position of the object (stored as value). For example: {[1, 7]: 43}, 43 would be the object in the 1st row 7th column in the matrix. The values passed into init in the form of a list of objects. The list of integers, dimension, will dictate the dimensions of the matrix. Dimension exist in the form of [n, m] where n and m are positve integers that can be equal to one anther. The method will take n objects from content and form the first column, it will continue to do this until there are m columns. REQ: content must contain elements such that the matrix is a valid matrix; there are an appropriate number of elements given the number of rows and columns. ''' pass def add_sub(self, target, add_or_sub): '''(Matrix, Matrix, bool) -> None Given another Matrix, perform either matrix addition or subtraction based on the value of add_or_sub. If add_or_sub is True perform addition, else (it being False) perform subtraction. REQ: Elements which reside in the same coordinate of either matrices must be of the same object type and must be able to added/subtracted from one another by some context ''' pass def transpose(self): '''(Matrix) -> None Perform a matrix tranposition on the matrix calling the method. The operation will invert the coordinates of all objects contained in the matrix: row values become column values and vice versa ''' pass def multi(self, target): '''(Matrix, Matrix) -> None Given another Matrix, perform matrix multiplication with the calling matrix on the left hand side of the operation and the target matrix on the right. Method will perform multiplication as described by standard matrix operation. REQ: number of column of the calling matrix must be equal to the number of rows of the targe matrix REQ: All elements within the calling matrix and the matrix being called must be integers or floats ''' pass def switch(self, row_or_col, switched): '''(Matrix, bool, list of ints) -> None Switch two columns or two rows of a calling matrix. If row_or_col is True, switch the two rows contained in switched. For example, if row_or_col is True and switched is [1,3] switch the first and third rows of the matrix. If row_or_col is False, perform the same action, but switch columns instead. REQ: Matrix must possess the rows or columns contained in switch REQ: switched contains exactly two integers ''' pass def get_by_row_or_col(self, coordinate, row_or_col): '''(Matrix, list of ints) -> obj Return a particular object in the matrix by a certain column or row and a position in the row or column. row_or_col dictates whether or not the object is referenced by row or column. If row_or_col is True, it is referencing by row, else it is referencing by row. Coordinate contains two integers, where the first is the coordinate[0]-th row or column and the second is the coordinate[1]-th item in that row/column For example if coordinate is [3, 4], and row_or_col is True return the 4th item in the third column. REQ: Designate coordinate must exist within the matrix ''' pass def set_by_row_or_col(self, replace, coordinate, row_or_col): '''(Matrix, obj, list of ints, bool) -> None Replace a particular object in the matrix by a certain column or row and a position in the row or column. row_or_col dictates whether or not the object is referenced by row or column. If row_or_col is True, it is referencing by row, else it is referencing by row. Coordinate contains two integers, where the first is the coordinate[0]-th row or column and the second is the coordinate[1]-th item in that row/column For example if coordinate is [3, 4], and row_or_col is True return the 4th item in the third column. REQ: Designate coordinate must exist within the matrix REQ: Cannot be called upon by symmetric or identity matrix in a way that would compromise their property of being symmetric or an identity ''' pass def get_determinant(self): '''(Matrix) -> int Returns the determinant of the matrix. The determinant being the difference of the product of the item in the first row first column and item in the second row second column and the product of the item in the first row second column and the second row first column. REQ: Matrix must be 2 by 2 and contain only ints ''' pass def set_content(self, content): '''(Matrix, list of obj) -> None Sets the content of a given Matrix; replacing all elements. REQ: content must be appropriate to dimensions of calling matrix ''' pass class SquareMatrix(Matrix): '''A class which represents a n by n matrix ''' def get_by_daig(self, duel_coor): ''' (Matrix, int) -> obj Return the object at a diagonal position in the calling matrix. For example, if duel_coor is 6, return the item at the 6th column in the 6th row. REQ: Matrix must contain at least as many diagonals as illustraded by duel_coor ''' pass def set_by_diag(self, replace, duel_coor): ''' (Matrix, obj, int) -> None Replace the object at the diagonal specified by duel_coor with the object replace.For example, if duel_coor is 6, replace the item at the 6th column in the 6th row. REQ: Matrix must contain at least as many diagonals as illustraded by duel_coor ''' pass class SymmetricMatrix(SquareMatrix): '''A class which represents a n by n symmetrix matrix ''' def set_by_row_or_col(self, replace, coordinate, treat_as_sym): '''(Matrix, obj, list of ints, bool, bool) -> None Replace a particular object in the matrix by a certain column or row and a position in the row or column. row_or_col dictates whether or not the object is referenced by row or column. If row_or_col is True, it is referencing by row, else it is referencing by row. Coordinate contains two integers, where the first is the coordinate[0]-th row or column and the second is the coordinate[1]-th item in that row/column For example if coordinate is [3, 4], and row_or_col is True return the 4th item in the third column. REQ: Designate coordinate must exist within the matrix ''' pass class IdentityMatrix(SymmetricMatrix): ''' A class which represents an identity matrix ''' def __init__(self, value=1, dimension): ''' (Matrix, obj, int) -> None Create an indentity matrix with the object 'value' populating the diaglonal of the matrix and square dimensions as illustrated by dimension. By difault, the diagonals will be populated with integer 1. ''' pass class OneDMatrix(Matrix): ''' A class which represents a one dimentional matrix ''' def get_val(self, target_val): ''' (Matrix, int) -> obj Return the object held in the target_val-th position of the matrix. REQ: Matrix must have as many positions as illustrated by target_val ''' pass def set_val(self, target_val, replace): ''' (Matrix, int, obj) -> None Replace the object at the target_val-th position of the matrix with the replace value. REQ: Matrix must have as many positions as illustrated by target_val ''' pass
[ "vincentteng@wifihost-82-190.wireless.utsc.utoronto.ca" ]
vincentteng@wifihost-82-190.wireless.utsc.utoronto.ca
af891e3712afa7d736c6effa451ec60674ec01ed
8504d656fa7badf8aba07ee4930c4d6b7b886e3c
/news_portal_api/wsgi.py
b6a9ff44f93ecdff4d45e8d9d0ac81e58d81b71a
[]
no_license
SarojRajTiwari/web_api_final
a35a8cb4f55b22cf661901ad12b31c878b7db0a6
2ed85ce6566b59e25f554c5a976202954317ca76
refs/heads/master
2022-12-12T06:44:13.643069
2019-12-02T07:50:07
2019-12-02T07:50:07
225,308,743
0
0
null
null
null
null
UTF-8
Python
false
false
407
py
""" WSGI config for news_portal_api project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'news_portal_api.settings') application = get_wsgi_application()
[ "sarojrajtiwari5@gmail.com" ]
sarojrajtiwari5@gmail.com
8596d664d4d312c1676cc07523a9763a6db80efd
50364def388dfcf4015109cc634dc10fc205edb5
/FaceVerify.py
8d8e14c1a9a7324c471b99b5b31b72e26ae522d7
[]
no_license
malhotraguy/traspod
73bb18221226362035188cb6eade71d9de8ccc16
5d9fd5c9ea266bc6660f532a360cb7f538a50796
refs/heads/master
2021-01-24T01:13:51.033523
2018-03-01T21:57:23
2018-03-01T21:57:23
122,801,097
2
0
null
null
null
null
UTF-8
Python
false
false
3,594
py
import requests from io import BytesIO from PIL import Image, ImageDraw import cognitive_face as CF import urllib import urllib.request as ur import cv2 import numpy as np import matplotlib.pyplot as plt KEY = '6a294681f0f640f3a8b60b1c7de8ea85' # Replace with a valid subscription key (keeping the quotes in place). CF.Key.set(KEY) # If you need to, you can change your base API url with: # CF.BaseUrl.set('https://westus.api.cognitive.microsoft.com/face/v1.0/detect') BASE_URL = 'https://eastus.api.cognitive.microsoft.com/face/v1.0/' # Replace with your regional Base URL CF.BaseUrl.set(BASE_URL) # You can use this example JPG or replace the URL below with your own URL to a JPEG image. img_url = 'https://raw.githubusercontent.com/malhotraguy/traspod/master/1.jpg' result = CF.face.detect(img_url) print(result) #Convert width height to a point in a rectangle def getRectangle(faceDictionary): rect = faceDictionary['faceRectangle'] left = rect['left'] top = rect['top'] bottom = left + rect['height'] right = top + rect['width'] return ((left, top), (bottom, right)) #Download the image from the url response = requests.get(img_url) img = Image.open(BytesIO(response.content)) #For each face returned use the face rectangle and draw a red box. draw = ImageDraw.Draw(img) for face in result: draw.rectangle(getRectangle(face), outline='red') #Display the image in the users default image browser. img.show() def url_to_image(url): """ a helper function that downloads the image, converts it to a NumPy array, and then reads it into OpenCV format """ resp = ur.urlopen(url) image = np.asarray(bytearray(resp.read()), dtype="uint8") image = cv2.imdecode(image, cv2.IMREAD_COLOR) # return the image return image img = url_to_image(img_url) plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) plt.axis('off') height = result[0]['faceRectangle']['height'] left = result[0]['faceRectangle']['left'] top = result[0]['faceRectangle']['top'] width = result[0]['faceRectangle']['width'] plt.imshow(cv2.cvtColor(img[top:top+height, left:left+width], cv2.COLOR_BGR2RGB)) plt.axis('off') url1 = 'https://raw.githubusercontent.com/malhotraguy/traspod/master/10.jpg' url2 = 'https://raw.githubusercontent.com/malhotraguy/traspod/master/5.jpg' url3 = 'https://raw.githubusercontent.com/malhotraguy/traspod/master/4.jpg' url4 = 'https://raw.githubusercontent.com/malhotraguy/traspod/master/3.jpg' urls = [url1, url2, url3, url4] for url in urls: plt.imshow(cv2.cvtColor(url_to_image(url), cv2.COLOR_BGR2RGB)) plt.axis('off') plt.show() results = [] for url in urls: r = CF.face.detect(url) results += r, all_faceid = [f['faceId'] for image in results for f in image] test_url = 'https://raw.githubusercontent.com/malhotraguy/traspod/master/2.jpg' plt.imshow(cv2.cvtColor(url_to_image(test_url), cv2.COLOR_BGR2RGB)) test_result = CF.face.detect(test_url) test_faceId = test_result[0]['faceId'] for f in all_faceid: r = CF.face.verify(f, test_faceId) print(r) identical_face_id = [f for f in all_faceid if CF.face.verify(f, test_faceId)['isIdentical'] == True] for i in range(len(results)): for face in results[i]: if face['faceId'] in identical_face_id: height = face['faceRectangle']['height'] left = face['faceRectangle']['left'] top = face['faceRectangle']['top'] width = face['faceRectangle']['width'] plt.imshow(cv2.cvtColor(url_to_image(urls[i])[top:top+height, left:left+width], cv2.COLOR_BGR2RGB)) plt.axis('off') plt.show()
[ "noreply@github.com" ]
noreply@github.com
675458e68451063981849d73115b4a2e5e1566b7
c48f3bb73f3ddda53619174fa1f81d42cd7bd0ca
/agent.py
ea6c262202157c3895d46d98c8186177a946266f
[]
no_license
hanhsienhuang/Gomoku
8f04f0b897feb33ff233d370978bf27c1b36f97f
d7f2cb1f042c92675ca877472e7c4376da600992
refs/heads/master
2022-12-31T02:36:01.310759
2020-10-25T05:51:49
2020-10-25T05:51:49
307,036,549
0
0
null
null
null
null
UTF-8
Python
false
false
9,392
py
import networks import torch import torch.nn as nn import torch.optim as optim import numpy as np from utils import is_in_range, list_add, print_board import random def choice2d(p): i = np.random.choice(np.prod(p.shape), p = p.flatten()) return np.unravel_index(i, p.shape) class Agent: def __init__(self, num_mcts, board_size): self.num_mcts = num_mcts self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") self.network = networks.NN(in_channels = 3, feature_size = 50, num_residual = 1, board_size = board_size, value_hidden_size = 256).to(self.device) #self.network = networks.ConvNN(in_channels = 3, # feature_size = 64, # num_layer = 2, # value_hidden_size = 64).to(self.device) self.optim = optim.Adam(self.network.parameters(), 1e-4, weight_decay=1e-4) self.temperature = 1 # TODO self.UCBConstant = 1 self.batchSize = 100 def get_action(self, treeNode): while treeNode.n < self.num_mcts: self._dfs(treeNode) policy = self.get_mcts_policy(treeNode, 0.1) return choice2d(policy) def _dfs(self, treeNode): if treeNode.state.isEnd: return -abs(treeNode.state.endResult) if treeNode.P is None: p, v = self.get_network_policy_and_value(treeNode) treeNode.P = p return v ucb = self.get_mcts_ucb_value(treeNode) move = np.unravel_index(np.argmax(ucb), ucb.shape) v = -self._dfs(treeNode.next(move)) treeNode.update(move, v) return v def get_network_policy_and_value(self, treeNode): inp = self._construct_tensors((treeNode.state, )) policy_logit, value = self.network(inp) policy_logit = policy_logit.cpu().detach().numpy()[0] policy_logit = np.where(treeNode.state.validMoves, policy_logit, float("-inf")) exp_logit = np.exp(policy_logit - policy_logit.max()) policy = exp_logit / exp_logit.sum() value = value.item() return policy, value def get_mcts_ucb_value(self, treeNode): # Q + U # U = c P \sqrt{n} / (1+N) # For invalid move, value = -inf U = np.where(treeNode.state.validMoves, \ self.UCBConstant * np.sqrt(treeNode.n + 1) * treeNode.P / (treeNode.N+1), \ float("-inf")) return treeNode.Q + U def get_mcts_policy(self, treeNode, temperature = None): if temperature is None: temperature = self.temperature poweredN = (treeNode.N / np.max(treeNode.N)) ** (1/temperature if temperature > 0 else float("inf")) return poweredN / poweredN.sum() def update(self, experience): #random.shuffle(experience) states, policies, zs = list(zip(*experience)) inputs = self._construct_tensors(states) valids = torch.stack([torch.as_tensor(s.validMoves, dtype=int, device=self.device) for s in states]) policies = torch.stack([torch.as_tensor(p, dtype=torch.float, device=self.device) for p in policies]) zs = torch.tensor(zs, dtype=torch.float, device=self.device).unsqueeze(-1) neginf = torch.tensor(-1e8, dtype=torch.float, device=self.device) # Rotate and flip inputs = torch.cat([inputs, torch.flip(inputs, [1])]) inputs = torch.cat([torch.rot90(inputs, i, (2,3)) for i in range(4)]) valids = torch.cat([valids, torch.flip(valids, [1])]) valids = torch.cat([torch.rot90(valids, i, (1,2)) for i in range(4)]) policies = torch.cat([policies, torch.flip(policies, [1])]) policies = torch.cat([torch.rot90(policies, i, (1,2)) for i in range(4)]) zs = zs.repeat(8,1) # shuffle index = torch.randperm(valids.shape[0]) inputs = inputs[index] valids = valids.to(dtype=bool)[index] policies = policies[index] zs = zs[index] total_loss = 0 num_it = 0 for i in range(inputs.shape[0] //self.batchSize ): beg, end = i*self.batchSize, (i+1)*self.batchSize inp = inputs[beg:end] val = valids[beg:end] pol = policies[beg:end] z = zs[beg:end] policy_logit, value = self.network(inp) policy_logit = torch.where(val, policy_logit, neginf) loss = - torch.mean(torch.sum(pol * policy_logit, dim=(1,2))) \ + torch.mean(torch.logsumexp(policy_logit, dim=(1,2))) \ + torch.mean((value - z)**2) self.optim.zero_grad() loss.backward() self.optim.step() total_loss += loss.item() num_it += 1 print(f"num iter: {num_it}, mean loss: {total_loss/num_it:.2f}") def copy(self, other): if self is not other: self.network.load_state_dict(other.network.state_dict()) def _construct_tensors(self, states): tensors = [self._construct_tensor(state) for state in states] return torch.stack(tensors) def _construct_tensor(self, state): board = torch.as_tensor(state.board, dtype=torch.float, device=self.device) isBlack = torch.full((1,) + state.shape, int(state.isNextBlack), dtype=torch.float, device=self.device) tensor = torch.cat((board, isBlack)) return tensor.to(self.device) class BaselineAgent0: def __init__(self): pass def get_action(self, treeNode): state = treeNode.state if not np.any(state.board[0]): action = tuple(s//2 for s in state.shape) treeNode.update(action, 1) return action i = int(state.isNextBlack) myBoard = state.board[i] oppoBoard = state.board[(i+1)%2] scores = np.zeros(state.shape, dtype=int) # 1,2,4,100 mapScores = [0, 1, 4, 8, 1000, 0] for i in range(state.shape[0]): for j in range(state.shape[1]): for d in [(1,0), (0,1), (1,1), (1, -1)]: hasFive, n = self._check_five(myBoard, oppoBoard, (i,j), d) if hasFive: score = mapScores[n] for step in range(5): pos = list_add((i,j), d, step) if state.validMoves[pos]: scores[pos] += score hasFive, n = self._check_five(oppoBoard, myBoard, (i,j), d) if hasFive: score = mapScores[n] for step in range(5): pos = list_add((i,j), d, step) if state.validMoves[pos]: scores[pos] += score maxScore = np.max(scores) indices = list(zip(*np.where(np.logical_and(scores == maxScore, state.validMoves)))) action = random.choice(indices) treeNode.update(action, 1) return action def end(self, state): pass def _check_five(self, board, oppoboard, start, direction): num = 0 for step in range(5): pos = list_add(start, direction, step) if not is_in_range(pos, board.shape): return False, None if oppoboard[pos]: return False, None if board[pos]: num += 1 return True, num def get_mcts_policy(self, treeNode): return treeNode.N / np.sum(treeNode.N) class InputAgent: def __init__(self): pass def get_action(self, treeNode): state = treeNode.state print_board(state) while True: inp = input("Input position: ") try: lst = inp.split(",") assert(len(lst)==2) pos = tuple(int(l) for l in lst) break except: print() return pos def get_mcts_policy(self, treeNode): return None def end(self, state): pass import asyncio import json class WebsocketAgent: def __init__(self, ws): self.ws = ws def state_to_json(self, state): shape = state.shape board = [[0]*shape[1] for _ in range(shape[0])] validMoves = [[0]*shape[1] for _ in range(shape[0])] for i in range(shape[0]): for j in range(shape[1]): if state.board[0, i, j]: board[i][j] = 1 elif state.board[1, i, j]: board[i][j] = -1 validMoves[i][j] = 1 if state.validMoves[i, j] else 0 s = dict( shape = shape, board = board, isNextBlack = state.isNextBlack, validMoves = validMoves, isEnd = state.isEnd, endResult = state.endResult, ) return json.dumps(s) async def get_action(self, treeNode): await self.ws.send(self.state_to_json(treeNode.state)) rec = await self.ws.recv() action = tuple(json.loads(rec)) print(action) return action def get_mcts_policy(self, treeNode): return None async def end(self, state): await self.ws.send(self.state_to_json(state)) await self.ws.close()
[ "hu8108@gmail.com" ]
hu8108@gmail.com
a63f0922e59cac5a62214ffbe9d6b901f45c2afc
844ac3a61068c6d60fbf2add52d927f29d3453c9
/main.py
afde28c6164b8aff73edf7f88f59530d4b9e121b
[]
no_license
ilacombe2022/Rock-Paper-Scissors
21cffa80802361b329d94358f528928a82089485
efd0597ec8614070f7738ffaa0a0caf850bcca62
refs/heads/main
2023-03-22T10:42:37.247944
2021-03-11T17:38:50
2021-03-11T17:38:50
346,786,042
0
0
null
null
null
null
UTF-8
Python
false
false
5,867
py
import random def choose(): choice = input("Shall we get started? [yes/no]: ").lower().strip() if choice == "yes": return choice elif choice == "no": print("We understand, thanks anyways.") exit() else: print("That's not the answer we're looking for.") choose() def difficulty(): print("Choose your difficulty:") print("Best of 1") print("Best of 3") print("Best of 5") diff = int(input("\n[1/3/5]: ")) if diff == 1: bestOfOne(1) elif diff == 3: bestOfThree(2) elif diff == 5: bestOfFive(3) else: print("We do not provide that difficulty.\n") return difficulty() def winner(u,c): print("\nYou beat Al!") print("Final Score: %d - %d" % (u, c)) print("Number of Rounds: %d" % (round - 1)) def loser(u, c): print("You lost to Al.") print("Final Score: %d - %d" % (u, c)) print("Number of Rounds: %d" % (round - 1)) def bestOfOne(num): print("Rule: \tOne round of Rock-Paper-Scissors.") print("\t\tFirst person to score 1 point win!") startGame() introCPU() playGame(num) def bestOfThree(num): print("Rule: \tThree rounds of Rock-Paper-Scissors.") print("\t\tFirst person to score 2 points win!") startGame() introCPU() playGame(num) def bestOfFive(num): print("Rule: \tFive rounds of Rock-Paper-Scissors.") print("\t\tFirst person to score 3 points win!") startGame() introCPU() playGame(num) def playGame(match): userPoint = 0 computerPoint = 0 round = 1 while userPoint < match and computerPoint < match: user = input("\nRound #%d, what will you choose? [rock/paper/scissors]: " % round) computer = random.randrange(1, 4, 1) if user == "rock" or user == "paper" or user == "scissors": if user == "rock" and computer == 1: print("You chose rock and Al chose rock! Tie!") print("Score: %d - %d" % (userPoint, computerPoint)) round = round + 1 elif user == "rock" and computer == 2: print("You chose rock and Al chose paper! Al gets a point!") computerPoint = computerPoint + 1 print("Score: %d - %d" % (userPoint, computerPoint)) round = round + 1 elif user == "rock" and computer == 3: print("You chose rock and Al chose scissors! You get a point!") userPoint = userPoint + 1 print("Score: %d - %d" % (userPoint, computerPoint)) round = round + 1 elif user == "paper" and computer == 1: print("You chose paper and Al chose rock! You gets a point!") userPoint = userPoint + 1 print("Score: %d - %d" % (userPoint, computerPoint)) round = round + 1 elif user == "paper" and computer == 2: print("You chose paper and Al chose paper! Tie!") print("Score: %d - %d" % (userPoint, computerPoint)) round = round + 1 elif user == "paper" and computer == 3: print("You chose paper and Al chose scissors! Al gets a point!") computerPoint = computerPoint + 1 print("Score: %d - %d" % (userPoint, computerPoint)) round = round + 1 elif user == "scissors" and computer == 1: print("You chose scissors and Al chose rock! Al gets a point!") computerPoint = computerPoint + 1 print("Score: %d - %d" % (userPoint, computerPoint)) round = round + 1 elif user == "scissors" and computer == 2: print("You chose scissors and Al chose paper! You get a point!") userPoint = userPoint + 1 print("Score: %d - %d" % (userPoint, computerPoint)) round = round + 1 elif user == "scissors" and computer == 3: print("You chose scissors and Al chose scissors! Tie!") print("Score: %d - %d" % (userPoint, computerPoint)) round = round + 1 else: print("Not an option, time to start over.\n") playGame(match) if userPoint == match: print("\nYou beat Al!") print("Final Score: %d - %d" % (userPoint, computerPoint)) print("Number of Rounds: %d" % (round - 1)) playAgain() elif computerPoint == match: print("You lost to Al.") print("Final Score: %d - %d" % (userPoint, computerPoint)) print("Number of Rounds: %d" % (round - 1)) playAgain() def playAgain(): again = input("\nWould you like to play again?[yes/no]: ").lower().strip() if again == "yes": difficulty() elif again == "no": print("Thanks for playing!") exit() else: print("We are trying to ask if you would like to play again?") playAgain() def startGame(): start = input("\nAre you ready to play against the CPU? [yes/no]: ").lower().strip() if start == "yes": return start elif start == "no": print("Oh! You've changed your mind? That's fine.") exit() else: print("That choice isn't available.\n") startGame() def introCPU(): print("Say hello to Al! He will be you opponent!") print("NOTE: Make sure you spell each word correctly, otherwise, rounds and scores will be reset!") print("HAVE FUN!") if __name__ == '__main__': print("Let's play Rock-Paper-Scissors!") print("Created by Isaac Lacombe\n") choose() difficulty()
[ "noreply@github.com" ]
noreply@github.com
c243ec1a490acd1d8b165d7a7ddef83cc8088bf6
2c09e0fa8b9c84af6686962a8d8569af298573d7
/client/GUI.py
8c42ec4ee18b6ba646fd58bec03a55c3b0f80fd8
[]
no_license
eldraco/Adeept_RaspClaws
62e3dd4259e909c7eb5b9809e0815cf616277975
2d7c56016091678803410131ad328c2cae1b8256
refs/heads/master
2022-04-25T21:22:12.775696
2020-04-26T19:25:49
2020-04-26T19:25:49
256,761,979
1
0
null
2020-04-18T13:35:03
2020-04-18T13:35:03
null
UTF-8
Python
false
false
25,732
py
#!/usr/bin/python # -*- coding: UTF-8 -*- # File name : client.py # Description : client # Website : www.adeept.com # E-mail : support@adeept.com # Author : William # Date : 2018/08/22 from socket import * import sys import time import threading as thread import tkinter as tk try:#1 import cv2 import zmq import base64 import numpy as np except: print("Couldn't import OpenCV, you need to install it first.") ip_stu=1 #Shows connection status c_f_stu = 0 c_b_stu = 0 c_l_stu = 0 c_r_stu = 0 c_ls_stu= 0 c_rs_stu= 0 funcMode= 0 tcpClicSock = '' root = '' stat = 0 Switch_3 = 0 Switch_2 = 0 Switch_1 = 0 SmoothMode = 0 ########>>>>>VIDEO<<<<<######## def video_thread(): global footage_socket, font, frame_num, fps context = zmq.Context() footage_socket = context.socket(zmq.SUB) footage_socket.bind('tcp://*:5555') footage_socket.setsockopt_string(zmq.SUBSCRIBE, np.unicode('')) font = cv2.FONT_HERSHEY_SIMPLEX frame_num = 0 fps = 0 def get_FPS(): global frame_num, fps while 1: try: time.sleep(1) fps = frame_num frame_num = 0 except: time.sleep(1) def opencv_r(): global frame_num while True: try: frame = footage_socket.recv_string() img = base64.b64decode(frame) npimg = np.frombuffer(img, dtype=np.uint8) source = cv2.imdecode(npimg, 1) cv2.putText(source,('PC FPS: %s'%fps),(40,20), font, 0.5,(255,255,255),1,cv2.LINE_AA) try: cv2.putText(source,('CPU Temperature: %s'%CPU_TEP),(370,350), font, 0.5,(128,255,128),1,cv2.LINE_AA) cv2.putText(source,('CPU Usage: %s'%CPU_USE),(370,380), font, 0.5,(128,255,128),1,cv2.LINE_AA) cv2.putText(source,('RAM Usage: %s'%RAM_USE),(370,410), font, 0.5,(128,255,128),1,cv2.LINE_AA) #cv2.line(source,(320,240),(260,300),(255,255,255),1) #cv2.line(source,(210,300),(260,300),(255,255,255),1) #cv2.putText(source,('%sm'%ultra_data),(210,290), font, 0.5,(255,255,255),1,cv2.LINE_AA) except: pass #cv2.putText(source,('%sm'%ultra_data),(210,290), font, 0.5,(255,255,255),1,cv2.LINE_AA) cv2.imshow("Stream", source) frame_num += 1 cv2.waitKey(1) except: time.sleep(0.5) break fps_threading=thread.Thread(target=get_FPS) #Define a thread for FPV and OpenCV fps_threading.setDaemon(True) #'True' means it is a front thread,it would close when the mainloop() closes fps_threading.start() #Thread starts video_threading=thread.Thread(target=video_thread) #Define a thread for FPV and OpenCV video_threading.setDaemon(True) #'True' means it is a front thread,it would close when the mainloop() closes video_threading.start() #Thread starts ########>>>>>VIDEO<<<<<######## def replace_num(initial,new_num): #Call this function to replace data in '.txt' file newline="" str_num=str(new_num) with open("ip.txt","r") as f: for line in f.readlines(): if(line.find(initial) == 0): line = initial+"%s" %(str_num) newline += line with open("ip.txt","w") as f: f.writelines(newline) #Call this function to replace data in '.txt' file def num_import(initial): #Call this function to import data from '.txt' file with open("ip.txt") as f: for line in f.readlines(): if(line.find(initial) == 0): r=line begin=len(list(initial)) snum=r[begin:] n=snum return n def call_forward(event): #When this function is called,client commands the car to move forward global c_f_stu if c_f_stu == 0: tcpClicSock.send(('forward').encode()) c_f_stu=1 def call_back(event): #When this function is called,client commands the car to move backward global c_b_stu if c_b_stu == 0: tcpClicSock.send(('backward').encode()) c_b_stu=1 def call_FB_stop(event): #When this function is called,client commands the car to stop moving global c_f_stu,c_b_stu,c_l_stu,c_r_stu,c_ls_stu,c_rs_stu c_f_stu=0 c_b_stu=0 tcpClicSock.send(('DS').encode()) def call_Turn_stop(event): #When this function is called,client commands the car to stop moving global c_f_stu,c_b_stu,c_l_stu,c_r_stu,c_ls_stu,c_rs_stu c_l_stu=0 c_r_stu=0 c_ls_stu=0 c_rs_stu=0 tcpClicSock.send(('TS').encode()) def call_Left(event): #When this function is called,client commands the car to turn left global c_l_stu if c_l_stu == 0: tcpClicSock.send(('left').encode()) c_l_stu=1 def call_Right(event): #When this function is called,client commands the car to turn right global c_r_stu if c_r_stu == 0: tcpClicSock.send(('right').encode()) c_r_stu=1 def call_LeftSide(event): global c_ls_stu if c_ls_stu == 0: tcpClicSock.send(('leftside').encode()) c_ls_stu=1 def call_RightSide(event): global c_rs_stu if c_rs_stu == 0: tcpClicSock.send(('rightside').encode()) c_rs_stu=1 def call_headup(event): tcpClicSock.send(('headup').encode()) def call_headdown(event): tcpClicSock.send(('headdown').encode()) def call_headleft(event): tcpClicSock.send(('headleft').encode()) def call_headright(event): tcpClicSock.send(('headright').encode()) def call_headhome(event): tcpClicSock.send(('headhome').encode()) def call_steady(event): if funcMode == 0: tcpClicSock.send(('steady').encode()) else: tcpClicSock.send(('funEnd').encode()) def call_FindColor(event): if funcMode == 0: tcpClicSock.send(('FindColor').encode()) else: tcpClicSock.send(('funEnd').encode()) def call_WatchDog(event): if funcMode == 0: tcpClicSock.send(('WatchDog').encode()) else: tcpClicSock.send(('funEnd').encode()) def call_Smooth(event): if SmoothMode == 0: tcpClicSock.send(('Smooth_on').encode()) else: tcpClicSock.send(('Smooth_off').encode()) def call_Switch_1(event): if Switch_1 == 0: tcpClicSock.send(('Switch_1_on').encode()) else: tcpClicSock.send(('Switch_1_off').encode()) def call_Switch_2(event): if Switch_2 == 0: tcpClicSock.send(('Switch_2_on').encode()) else: tcpClicSock.send(('Switch_2_off').encode()) def call_Switch_3(event): if Switch_3 == 0: tcpClicSock.send(('Switch_3_on').encode()) else: tcpClicSock.send(('Switch_3_off').encode()) def all_btn_red(): Btn_Steady.config(bg='#FF6D00', fg='#000000') Btn_FindColor.config(bg='#FF6D00', fg='#000000') Btn_WatchDog.config(bg='#FF6D00', fg='#000000') Btn_Fun4.config(bg='#FF6D00', fg='#000000') Btn_Fun5.config(bg='#FF6D00', fg='#000000') Btn_Fun6.config(bg='#FF6D00', fg='#000000') def all_btn_normal(): Btn_Steady.config(bg=color_btn, fg=color_text) Btn_FindColor.config(bg=color_btn, fg=color_text) Btn_WatchDog.config(bg=color_btn, fg=color_text) Btn_Fun4.config(bg=color_btn, fg=color_text) Btn_Fun5.config(bg=color_btn, fg=color_text) Btn_Fun6.config(bg=color_btn, fg=color_text) def connection_thread(): global funcMode, Switch_3, Switch_2, Switch_1, SmoothMode while 1: car_info = (tcpClicSock.recv(BUFSIZ)).decode() if not car_info: continue elif 'FindColor' in car_info: funcMode = 1 all_btn_red() Btn_FindColor.config(bg='#00E676') elif 'steady' in car_info: funcMode = 1 all_btn_red() Btn_Steady.config(bg='#00E676') elif 'WatchDog' in car_info: funcMode = 1 all_btn_red() Btn_WatchDog.config(bg='#00E676') elif 'Smooth_on' in car_info: SmoothMode = 1 Btn_Smooth.config(bg='#4CAF50') elif 'Smooth_off' in car_info: SmoothMode = 0 Btn_Smooth.config(bg=color_btn) elif 'Switch_3_on' in car_info: Switch_3 = 1 Btn_Switch_3.config(bg='#4CAF50') elif 'Switch_2_on' in car_info: Switch_2 = 1 Btn_Switch_2.config(bg='#4CAF50') elif 'Switch_1_on' in car_info: Switch_1 = 1 Btn_Switch_1.config(bg='#4CAF50') elif 'Switch_3_off' in car_info: Switch_3 = 0 Btn_Switch_3.config(bg=color_btn) elif 'Switch_2_off' in car_info: Switch_2 = 0 Btn_Switch_2.config(bg=color_btn) elif 'Switch_1_off' in car_info: Switch_1 = 0 Btn_Switch_1.config(bg=color_btn) elif 'CVFL_on' in car_info: function_stu = 1 Btn_CVFL.config(bg='#4CAF50') elif 'CVFL_off' in car_info: function_stu = 0 Btn_CVFL.config(bg='#212121') elif 'FunEnd' in car_info: funcMode = 0 all_btn_normal() print(car_info) def Info_receive(): global CPU_TEP,CPU_USE,RAM_USE HOST = '' INFO_PORT = 2256 #Define port serial ADDR = (HOST, INFO_PORT) InfoSock = socket(AF_INET, SOCK_STREAM) InfoSock.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) InfoSock.bind(ADDR) InfoSock.listen(5) #Start server,waiting for client InfoSock, addr = InfoSock.accept() print('Info connected') while 1: try: info_data = '' info_data = str(InfoSock.recv(BUFSIZ).decode()) info_get = info_data.split() CPU_TEP,CPU_USE,RAM_USE= info_get #print('cpu_tem:%s\ncpu_use:%s\nram_use:%s'%(CPU_TEP,CPU_USE,RAM_USE)) CPU_TEP_lab.config(text='CPU Temp: %s℃'%CPU_TEP) CPU_USE_lab.config(text='CPU Usage: %s'%CPU_USE) RAM_lab.config(text='RAM Usage: %s'%RAM_USE) except: pass def socket_connect(): #Call this function to connect with the server global ADDR,tcpClicSock,BUFSIZ,ip_stu,ipaddr ip_adr=E1.get() #Get the IP address from Entry if ip_adr == '': #If no input IP address in Entry,import a default IP ip_adr=num_import('IP:') l_ip_4.config(text='Connecting') l_ip_4.config(bg='#FF8F00') l_ip_5.config(text='Default:%s'%ip_adr) pass SERVER_IP = ip_adr SERVER_PORT = 10223 #Define port serial BUFSIZ = 1024 #Define buffer size ADDR = (SERVER_IP, SERVER_PORT) tcpClicSock = socket(AF_INET, SOCK_STREAM) #Set connection value for socket for i in range (1,6): #Try 5 times if disconnected #try: if ip_stu == 1: print("Connecting to server @ %s:%d..." %(SERVER_IP, SERVER_PORT)) print("Connecting") tcpClicSock.connect(ADDR) #Connection with the server print("Connected") l_ip_5.config(text='IP:%s'%ip_adr) l_ip_4.config(text='Connected') l_ip_4.config(bg='#558B2F') replace_num('IP:',ip_adr) E1.config(state='disabled') #Disable the Entry Btn14.config(state='disabled') #Disable the Entry ip_stu=0 #'0' means connected connection_threading=thread.Thread(target=connection_thread) #Define a thread for FPV and OpenCV connection_threading.setDaemon(True) #'True' means it is a front thread,it would close when the mainloop() closes connection_threading.start() #Thread starts info_threading=thread.Thread(target=Info_receive) #Define a thread for FPV and OpenCV info_threading.setDaemon(True) #'True' means it is a front thread,it would close when the mainloop() closes info_threading.start() #Thread starts video_threading=thread.Thread(target=opencv_r) #Define a thread for FPV and OpenCV video_threading.setDaemon(True) #'True' means it is a front thread,it would close when the mainloop() closes video_threading.start() #Thread starts break else: print("Cannot connecting to server,try it latter!") l_ip_4.config(text='Try %d/5 time(s)'%i) l_ip_4.config(bg='#EF6C00') print('Try %d/5 time(s)'%i) ip_stu=1 time.sleep(1) continue if ip_stu == 1: l_ip_4.config(text='Disconnected') l_ip_4.config(bg='#F44336') def connect(event): #Call this function to connect with the server if ip_stu == 1: sc=thread.Thread(target=socket_connect) #Define a thread for connection sc.setDaemon(True) #'True' means it is a front thread,it would close when the mainloop() closes sc.start() #Thread starts def connect_click(): #Call this function to connect with the server if ip_stu == 1: sc=thread.Thread(target=socket_connect) #Define a thread for connection sc.setDaemon(True) #'True' means it is a front thread,it would close when the mainloop() closes sc.start() #Thread starts def set_R(event): time.sleep(0.03) tcpClicSock.send(('wsR %s'%var_R.get()).encode()) def set_G(event): time.sleep(0.03) tcpClicSock.send(('wsG %s'%var_G.get()).encode()) def set_B(event): time.sleep(0.03) tcpClicSock.send(('wsB %s'%var_B.get()).encode()) def EC_send(event):#z tcpClicSock.send(('setEC %s'%var_ec.get()).encode()) time.sleep(0.03) def EC_default(event):#z var_ec.set(0) tcpClicSock.send(('defEC').encode()) def scale_FL(x,y,w):#1 global Btn_CVFL def lip1_send(event): time.sleep(0.03) tcpClicSock.send(('lip1 %s'%var_lip1.get()).encode()) def lip2_send(event): time.sleep(0.03) tcpClicSock.send(('lip2 %s'%var_lip2.get()).encode()) def err_send(event): time.sleep(0.03) tcpClicSock.send(('err %s'%var_err.get()).encode()) def call_Render(event): tcpClicSock.send(('Render').encode()) def call_CVFL(event): tcpClicSock.send(('CVFL').encode()) def call_WB(event): tcpClicSock.send(('WBswitch').encode()) Scale_lip1 = tk.Scale(root,label=None, from_=0,to=480,orient=tk.HORIZONTAL,length=w, showvalue=1,tickinterval=None,resolution=1,variable=var_lip1,troughcolor='#212121',command=lip1_send,fg=color_text,bg=color_bg,highlightthickness=0) Scale_lip1.place(x=x,y=y) #Define a Scale and put it in position Scale_lip2 = tk.Scale(root,label=None, from_=0,to=480,orient=tk.HORIZONTAL,length=w, showvalue=1,tickinterval=None,resolution=1,variable=var_lip2,troughcolor='#212121',command=lip2_send,fg=color_text,bg=color_bg,highlightthickness=0) Scale_lip2.place(x=x,y=y+30) #Define a Scale and put it in position Scale_err = tk.Scale(root,label=None, from_=0,to=200,orient=tk.HORIZONTAL,length=w, showvalue=1,tickinterval=None,resolution=1,variable=var_err,troughcolor='#212121',command=err_send,fg=color_text,bg=color_bg,highlightthickness=0) Scale_err.place(x=x,y=y+60) #Define a Scale and put it in position canvas_cover=tk.Canvas(root,bg=color_bg,height=30,width=510,highlightthickness=0) canvas_cover.place(x=x,y=y+90) Btn_Render = tk.Button(root, width=10, text='Render',fg=color_text,bg='#212121',relief='ridge') Btn_Render.place(x=x+w+111,y=y+20) Btn_Render.bind('<ButtonPress-1>', call_Render) Btn_CVFL = tk.Button(root, width=10, text='CV FL',fg=color_text,bg='#212121',relief='ridge') Btn_CVFL.place(x=x+w+21,y=y+20) Btn_CVFL.bind('<ButtonPress-1>', call_CVFL) Btn_WB = tk.Button(root, width=23, text='LineColorSwitch',fg=color_text,bg='#212121',relief='ridge') Btn_WB.place(x=x+w+21,y=y+60) Btn_WB.bind('<ButtonPress-1>', call_WB) def loop(): #GUI global tcpClicSock,root,E1,connect,l_ip_4,l_ip_5,color_btn,color_text,Btn14,CPU_TEP_lab,CPU_USE_lab,RAM_lab,canvas_ultra,color_text,var_lip1,var_lip2,var_err,var_R,var_B,var_G,var_ec,Btn_Steady,Btn_FindColor,Btn_WatchDog,Btn_Fun4,Btn_Fun5,Btn_Fun6,Btn_Switch_1,Btn_Switch_2,Btn_Switch_3,Btn_Smooth,color_bg #1 The value of tcpClicSock changes in the function loop(),would also changes in global so the other functions could use it. while True: color_bg='#000000' #Set background color color_text='#E1F5FE' #Set text color color_btn='#0277BD' #Set button color color_line='#01579B' #Set line color color_can='#212121' #Set canvas color color_oval='#2196F3' #Set oval color target_color='#FF6D00' root = tk.Tk() #Define a window named root root.title('Adeept RaspClaws') #Main window title root.geometry('565x680') #1 Main window size, middle of the English letter x. root.config(bg=color_bg) #Set the background color of root window try: logo =tk.PhotoImage(file = 'logo.png') #Define the picture of logo,but only supports '.png' and '.gif' l_logo=tk.Label(root,image = logo,bg=color_bg) #Set a label to show the logo picture l_logo.place(x=30,y=13) #Place the Label in a right position except: pass CPU_TEP_lab=tk.Label(root,width=18,text='CPU Temp:',fg=color_text,bg='#212121') CPU_TEP_lab.place(x=400,y=15) #Define a Label and put it in position CPU_USE_lab=tk.Label(root,width=18,text='CPU Usage:',fg=color_text,bg='#212121') CPU_USE_lab.place(x=400,y=45) #Define a Label and put it in position RAM_lab=tk.Label(root,width=18,text='RAM Usage:',fg=color_text,bg='#212121') RAM_lab.place(x=400,y=75) #Define a Label and put it in position l_ip=tk.Label(root,width=18,text='Status',fg=color_text,bg=color_btn) l_ip.place(x=30,y=110) #Define a Label and put it in position l_ip_4=tk.Label(root,width=18,text='Disconnected',fg=color_text,bg='#F44336') l_ip_4.place(x=400,y=110) #Define a Label and put it in position l_ip_5=tk.Label(root,width=18,text='Use default IP',fg=color_text,bg=color_btn) l_ip_5.place(x=400,y=145) #Define a Label and put it in position E1 = tk.Entry(root,show=None,width=16,bg="#37474F",fg='#eceff1') E1.place(x=180,y=40) #Define a Entry and put it in position l_ip_3=tk.Label(root,width=10,text='IP Address:',fg=color_text,bg='#000000') l_ip_3.place(x=175,y=15) #Define a Label and put it in position label_openCV=tk.Label(root,width=28,text='OpenCV Status',fg=color_text,bg=color_btn) label_openCV.place(x=180,y=110) #Define a Label and put it in position ################################ #canvas_rec=canvas_ultra.create_rectangle(0,0,340,30,fill = '#FFFFFF',width=0) #canvas_text=canvas_ultra.create_text((90,11),text='Ultrasonic Output: 0.75m',fill=color_text) ################################ Btn_Smooth = tk.Button(root, width=8, text='Smooth',fg=color_text,bg=color_btn,relief='ridge') Btn_Smooth.place(x=240,y=230) Btn_Smooth.bind('<ButtonPress-1>', call_Smooth) root.bind('<KeyPress-f>', call_Smooth) Btn_Switch_1 = tk.Button(root, width=8, text='Port 1',fg=color_text,bg=color_btn,relief='ridge') Btn_Switch_2 = tk.Button(root, width=8, text='Port 2',fg=color_text,bg=color_btn,relief='ridge') Btn_Switch_3 = tk.Button(root, width=8, text='Port 3',fg=color_text,bg=color_btn,relief='ridge') Btn_Switch_1.place(x=30,y=265) Btn_Switch_2.place(x=100,y=265) Btn_Switch_3.place(x=170,y=265) Btn_Switch_1.bind('<ButtonPress-1>', call_Switch_1) Btn_Switch_2.bind('<ButtonPress-1>', call_Switch_2) Btn_Switch_3.bind('<ButtonPress-1>', call_Switch_3) Btn0 = tk.Button(root, width=8, text='Forward',fg=color_text,bg=color_btn,relief='ridge') Btn1 = tk.Button(root, width=8, text='Backward',fg=color_text,bg=color_btn,relief='ridge') Btn2 = tk.Button(root, width=8, text='Left',fg=color_text,bg=color_btn,relief='ridge') Btn3 = tk.Button(root, width=8, text='Right',fg=color_text,bg=color_btn,relief='ridge') Btn_LeftSide = tk.Button(root, width=8, text='<--',fg=color_text,bg=color_btn,relief='ridge') Btn_LeftSide.place(x=30,y=195) Btn_LeftSide.bind('<ButtonPress-1>', call_LeftSide) Btn_LeftSide.bind('<ButtonRelease-1>', call_Turn_stop) Btn_RightSide = tk.Button(root, width=8, text='-->',fg=color_text,bg=color_btn,relief='ridge') Btn_RightSide.place(x=170,y=195) Btn_RightSide.bind('<ButtonPress-1>', call_RightSide) Btn_RightSide.bind('<ButtonRelease-1>', call_Turn_stop) Btn0.place(x=100,y=195) Btn1.place(x=100,y=230) Btn2.place(x=30,y=230) Btn3.place(x=170,y=230) Btn0.bind('<ButtonPress-1>', call_forward) Btn1.bind('<ButtonPress-1>', call_back) Btn2.bind('<ButtonPress-1>', call_Left) Btn3.bind('<ButtonPress-1>', call_Right) Btn0.bind('<ButtonRelease-1>', call_FB_stop) Btn1.bind('<ButtonRelease-1>', call_FB_stop) Btn2.bind('<ButtonRelease-1>', call_Turn_stop) Btn3.bind('<ButtonRelease-1>', call_Turn_stop) root.bind('<KeyPress-w>', call_forward) root.bind('<KeyPress-a>', call_Left) root.bind('<KeyPress-d>', call_Right) root.bind('<KeyPress-s>', call_back) root.bind('<KeyPress-q>', call_LeftSide) root.bind('<KeyPress-e>', call_RightSide) root.bind('<KeyRelease-q>', call_Turn_stop) root.bind('<KeyRelease-e>', call_Turn_stop) root.bind('<KeyRelease-w>', call_FB_stop) root.bind('<KeyRelease-a>', call_Turn_stop) root.bind('<KeyRelease-d>', call_Turn_stop) root.bind('<KeyRelease-s>', call_FB_stop) Btn_up = tk.Button(root, width=8, text='Up',fg=color_text,bg=color_btn,relief='ridge') Btn_down = tk.Button(root, width=8, text='Down',fg=color_text,bg=color_btn,relief='ridge') Btn_left = tk.Button(root, width=8, text='Left',fg=color_text,bg=color_btn,relief='ridge') Btn_right = tk.Button(root, width=8, text='Right',fg=color_text,bg=color_btn,relief='ridge') Btn_home = tk.Button(root, width=8, text='Home',fg=color_text,bg=color_btn,relief='ridge') Btn_up.place(x=400,y=195) Btn_down.place(x=400,y=265) Btn_left.place(x=330,y=230) Btn_right.place(x=470,y=230) Btn_home.place(x=400,y=230) root.bind('<KeyPress-i>', call_headup) root.bind('<KeyPress-k>', call_headdown) root.bind('<KeyPress-j>', call_headleft) root.bind('<KeyPress-l>', call_headright) root.bind('<KeyPress-h>', call_headhome) Btn_up.bind('<ButtonPress-1>', call_headup) Btn_down.bind('<ButtonPress-1>', call_headdown) Btn_left.bind('<ButtonPress-1>', call_headleft) Btn_right.bind('<ButtonPress-1>', call_headright) Btn_home.bind('<ButtonPress-1>', call_headhome) Btn14= tk.Button(root, width=8,height=2, text='Connect',fg=color_text,bg=color_btn,command=connect_click,relief='ridge') Btn14.place(x=315,y=15) #Define a Button and put it in position root.bind('<Return>', connect) var_lip1 = tk.StringVar()#1 var_lip1.set(440) var_lip2 = tk.StringVar() var_lip2.set(380) var_err = tk.StringVar() var_err.set(20) var_R = tk.StringVar() var_R.set(0) Scale_R = tk.Scale(root,label=None, from_=0,to=255,orient=tk.HORIZONTAL,length=505, showvalue=1,tickinterval=None,resolution=1,variable=var_R,troughcolor='#F44336',command=set_R,fg=color_text,bg=color_bg,highlightthickness=0) Scale_R.place(x=30,y=330) #Define a Scale and put it in position var_G = tk.StringVar() var_G.set(0) Scale_G = tk.Scale(root,label=None, from_=0,to=255,orient=tk.HORIZONTAL,length=505, showvalue=1,tickinterval=None,resolution=1,variable=var_G,troughcolor='#00E676',command=set_G,fg=color_text,bg=color_bg,highlightthickness=0) Scale_G.place(x=30,y=360) #Define a Scale and put it in position var_B = tk.StringVar() var_B.set(0) Scale_B = tk.Scale(root,label=None, from_=0,to=255,orient=tk.HORIZONTAL,length=505, showvalue=1,tickinterval=None,resolution=1,variable=var_B,troughcolor='#448AFF',command=set_B,fg=color_text,bg=color_bg,highlightthickness=0) Scale_B.place(x=30,y=390) #Define a Scale and put it in position var_ec = tk.StringVar() #Z start var_ec.set(0) Scale_ExpCom = tk.Scale(root,label='Exposure Compensation Level', from_=-25,to=25,orient=tk.HORIZONTAL,length=315, showvalue=1,tickinterval=None,resolution=1,variable=var_ec,troughcolor='#212121',command=EC_send,fg=color_text,bg=color_bg,highlightthickness=0) Scale_ExpCom.place(x=30,y=610) #Define a Scale and put it in position canvas_cover_exp=tk.Canvas(root,bg=color_bg,height=30,width=510,highlightthickness=0) canvas_cover_exp.place(x=30,y=610+50) Btn_dEC = tk.Button(root, width=23,height=2, text='Set Default Exposure\nCompensation Level',fg=color_text,bg='#212121',relief='ridge') Btn_dEC.place(x=30+315+21,y=610+3) Btn_dEC.bind('<ButtonPress-1>', EC_default) #Z end canvas_cover=tk.Canvas(root,bg=color_bg,height=30,width=510,highlightthickness=0) canvas_cover.place(x=30,y=420) Btn_Steady = tk.Button(root, width=10, text='Steady',fg=color_text,bg=color_btn,relief='ridge') Btn_Steady.place(x=30,y=445) root.bind('<KeyPress-z>', call_steady) Btn_Steady.bind('<ButtonPress-1>', call_steady) Btn_FindColor = tk.Button(root, width=10, text='FindColor',fg=color_text,bg=color_btn,relief='ridge') Btn_FindColor.place(x=115,y=445) root.bind('<KeyPress-z>', call_FindColor) Btn_FindColor.bind('<ButtonPress-1>', call_FindColor) Btn_WatchDog = tk.Button(root, width=10, text='WatchDog',fg=color_text,bg=color_btn,relief='ridge') Btn_WatchDog.place(x=200,y=445) root.bind('<KeyPress-z>', call_WatchDog) Btn_WatchDog.bind('<ButtonPress-1>', call_WatchDog) Btn_Fun4 = tk.Button(root, width=10, text='Function 4',fg=color_text,bg=color_btn,relief='ridge') Btn_Fun4.place(x=285,y=445) root.bind('<KeyPress-z>', call_WatchDog) Btn_Fun4.bind('<ButtonPress-1>', call_WatchDog) Btn_Fun5 = tk.Button(root, width=10, text='Function 5',fg=color_text,bg=color_btn,relief='ridge') Btn_Fun5.place(x=370,y=445) root.bind('<KeyPress-z>', call_WatchDog) Btn_Fun5.bind('<ButtonPress-1>', call_WatchDog) Btn_Fun6 = tk.Button(root, width=10, text='Function 6',fg=color_text,bg=color_btn,relief='ridge') Btn_Fun6.place(x=455,y=445) root.bind('<KeyPress-z>', call_WatchDog) Btn_Fun6.bind('<ButtonPress-1>', call_WatchDog) scale_FL(30,490,315)#1 global stat if stat==0: # Ensure the mainloop runs only once root.mainloop() # Run the mainloop() stat=1 # Change the value to '1' so the mainloop() would not run again. if __name__ == '__main__': try: loop() # Load GUI except: tcpClicSock.close() # Close socket or it may not connect with the server again footage_socket.close() cv2.destroyAllWindows() pass
[ "noreply@github.com" ]
noreply@github.com
c63effbac0ae9a65a8e037ea99875dcf94ae1746
44e26d6e5ada8bc5fb9d000e86e4694615262bcd
/download_latest_build.py
0a1c243fbbd71a64c4fc2ce7e7a65fd9d9fe1c28
[]
no_license
symlib/clitest
18c9d0475179b035a466d604a60fca52d5c63d84
524bd59f64d4754a760d483c9b7038647f442240
refs/heads/master
2021-06-21T21:20:53.031850
2017-08-22T01:04:19
2017-08-22T01:04:19
81,310,193
0
1
null
null
null
null
UTF-8
Python
false
false
10,847
py
# initial version # March 20, 2017 buildserverurl="http://192.168.208.5/release/hyperion_ds/daily/" fcsserverurl="http://192.168.208.5/release/hyperion_ds/fcs/" tftpserver="root@10.84.2.99:/work/tftpboot/" serv = "MjExLjE1MC42NS44MQ==" u = "amFja3kubGlAY24ucHJvbWlzZS5jb20=" p = "NzcwMjE0WHA=" import requests from bs4 import BeautifulSoup import os import glob import time def getnewbuild(): download=False # get the current build folder files=glob.glob("/work/tftpboot/d5k-multi*.ptif") tftpbuildnumber120=0 tftpbuildnumber121=0 tftpbuildnumber122 = 0 tftpbuildnumber13 = 0 tmp120=tmp121=tmp122=tmp13=0 for file in files: try: if int(file[25:27])==12 and int(file[28])==2: tmp122=int(file[-7:-5]) elif int(file[25:27])==12 and int(file[28])==1: tmp121=int(file[-7:-5]) elif int(file[25:27])==12 and int(file[28])==0: tmp120 = int(file[-7:-5]) elif int(file[25:27]) == 13: tmp13 = int(file[-7:-5]) except: tmp120=0 tmp121 = 0 tmp122 = 0 tmp13=0 if tmp120>tftpbuildnumber120: tftpbuildnumber120=tmp120 if tmp121>tftpbuildnumber121: tftpbuildnumber121=tmp121 if tmp122>tftpbuildnumber122: tftpbuildnumber122=tmp122 if tmp13>tftpbuildnumber13: tftpbuildnumber13=tmp13 # print "current build is %d" %tftpbuildnumber # to get the full directory list soup = BeautifulSoup(requests.get(buildserverurl).text) fcssoup=BeautifulSoup(requests.get(fcsserverurl).text) buildnumber120 = list() buildnumber121 = list() buildnumber122 = list() buildnumber13 = list() for link in soup.find_all('a'): tmp = link.get('href') if "13." in tmp: buildnumber13.append(tmp) if "12.00" in tmp: buildnumber120.append(tmp) if "12.01" in tmp: buildnumber121.append(tmp) if "12.02" in tmp: buildnumber122.append(tmp) for link in fcssoup.find_all('a'): print link tmp = link.get('href') print tmp if "13_" in tmp: buildnumber13.append(tmp) try: webupdatedbuild120=int((buildnumber120[-1].replace("/","").split(".")[-1])) webupdatedbuild121 = int((buildnumber121[-1].replace("/", "").split(".")[-1])) webupdatedbuild122 = int((buildnumber122[-1].replace("/", "").split(".")[-1])) webupdatedbuild13 = int((buildnumber13[-1].replace("/", "").split("_")[-1])) except: webupdatedbuild120=0 webupdatedbuild121=0 webupdatedbuild122 = 0 webupdatedbuild13 = 0 #print "webupdatedbuildnumbers are %d,%d" %(webupdatedbuild12,webupdatedbuild13) # if the webupdated build is newer than the installed one, download the new build # file list contains the filename to be updated on the host filelist=list() print "webupdatebuild120,webupdatedbuild121,tftpbuildnumber120,tftpbuildnumber121,tftpbuildnumber122",webupdatedbuild120,webupdatedbuild121,tftpbuildnumber120,tftpbuildnumber121,webupdatedbuild122 print "webupdatebuild13,tptpbuildnumber13", webupdatedbuild13, tftpbuildnumber13 if webupdatedbuild13 >tftpbuildnumber13: download=True Pfile = open('downloadedfiles', 'w') Pfile.close() #for filetype in ("conf", "multi"): for filetype in ("conf", "multi", "bios", "fw", "lib", "oem", "sw", "usr", "base"): if filetype=="base": filename="d5k-"+filetype+"-"+(buildnumber13[-1].replace("/","")).replace(".","_").replace("13_00","13_0")+".raw.gz" else: filename="d5k-"+filetype+"-"+(buildnumber13[-1].replace("/","")).replace(".","_").replace("13_00","13_0")+".ptif" os.system("wget "+fcsserverurl+buildnumber13[-1]+filename) # os.system("scp "+ filename +" "+tftpserver) # filename="d5k-"+filetype+"-"+webupdatedbuild.replace(".","_").replace("00","0")+".ptif" # #os.system("wget " + buildserverurl + buildnumber[-1] + "/" + filename) timestr=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) os.system("echo " + timestr +" downloaded %s" % filename +" >> downloadedfiles") os.system("mv /root/d5k* /work/tftpboot/") os.system("mv ./d5k* /work/tftpboot/") if webupdatedbuild120 > tftpbuildnumber120: download = True Pfile = open('downloadedfiles', 'w') Pfile.close() # for filetype in ("conf", "multi"): for filetype in ("conf", "multi", "bios", "fw", "lib", "oem", "sw", "usr", "base"): if filetype == "base": filename = "d5k-" + filetype + "-" + (buildnumber120[-1].replace("/", "")).replace(".", "_").replace( "12_00", "12_0") + ".raw.gz" else: filename = "d5k-" + filetype + "-" + (buildnumber120[-1].replace("/", "")).replace(".", "_").replace( "12_00", "12_0") + ".ptif" os.system("wget " + buildserverurl + buildnumber120[-1] + filename) # os.system("scp "+ filename +" "+tftpserver) # filename="d5k-"+filetype+"-"+webupdatedbuild.replace(".","_").replace("00","0")+".ptif" # # os.system("wget " + buildserverurl + buildnumber[-1] + "/" + filename) timestr = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) os.system("echo " + timestr + " downloaded %s" % filename + " >> downloadedfiles") os.system("mv /root/d5k* /work/tftpboot/") os.system("mv ./d5k* /work/tftpboot/") if webupdatedbuild121 > tftpbuildnumber121: download = True Pfile = open('downloadedfiles', 'w') Pfile.close() # for filetype in ("conf", "multi"): for filetype in ("conf", "multi", "bios", "fw", "lib", "oem", "sw", "usr", "base"): if filetype == "base": filename = "d5k-" + filetype + "-" + (buildnumber121[-1].replace("/", "")).replace(".", "_").replace( "12_01", "12_1") + ".raw.gz" else: filename = "d5k-" + filetype + "-" + (buildnumber121[-1].replace("/", "")).replace(".", "_").replace( "12_01", "12_1") + ".ptif" os.system("wget " + buildserverurl + buildnumber121[-1] + filename) # os.system("scp "+ filename +" "+tftpserver) # filename="d5k-"+filetype+"-"+webupdatedbuild.replace(".","_").replace("00","0")+".ptif" # # os.system("wget " + buildserverurl + buildnumber[-1] + "/" + filename) timestr = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) os.system("echo " + timestr + " downloaded %s" % filename + " >> downloadedfiles") os.system("mv /root/d5k* /work/tftpboot/") os.system("mv ./d5k* /work/tftpboot/") if webupdatedbuild122 > tftpbuildnumber122: download = True Pfile = open('downloadedfiles', 'w') Pfile.close() # for filetype in ("conf", "multi"): for filetype in ("conf", "multi", "bios", "fw", "lib", "oem", "sw", "usr", "base"): if filetype == "base": filename = "d5k-" + filetype + "-" + (buildnumber122[-1].replace("/", "")).replace(".", "_").replace( "12_02", "12_2") + ".raw.gz" else: filename = "d5k-" + filetype + "-" + (buildnumber122[-1].replace("/", "")).replace(".", "_").replace( "12_02", "12_2") + ".ptif" os.system("wget " + buildserverurl + buildnumber122[-1] + filename) # os.system("scp "+ filename +" "+tftpserver) # filename="d5k-"+filetype+"-"+webupdatedbuild.replace(".","_").replace("00","0")+".ptif" # # os.system("wget " + buildserverurl + buildnumber[-1] + "/" + filename) timestr = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) os.system("echo " + timestr + " downloaded %s" % filename + " >> downloadedfiles") os.system("mv /root/d5k* /work/tftpboot/") os.system("mv ./d5k* /work/tftpboot/") return download if __name__ == "__main__": timestr=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) os.system("echo %s \" Trying to download files\" >> downloadedfiles" %timestr ) download=getnewbuild() if download==True: import smtplib # Import the email modules we'll need from email.mime.text import MIMEText # Open a plain text file for reading. For this example, assume that # the text file contains only ASCII characters. textfile="downloadedfiles" fp = open(textfile, 'rb') buildversion=fp.readline()[-18:-6] tofile=open("buildnum","w") tofile.write(buildversion.replace("_",".")) tofile.close() os.system("scp /root/buildnum root@192.168.252.106:/opt/testlink-1.9.16-0/apache2/htdocs/srvpool/") # os.system("scp /work/jackyl/buildnum root@192.168.252.106:/opt/testlink-1.9.16-0/apache2/htdocs/srvpool/") time.sleep(1) os.system("scp /root/buildnum root@10.84.2.66:/home/work/jackyl/Scripts/clitest/") # os.system("scp /work/jackyl/buildnum root@10.84.2.66:/home/work/jackyl/Scripts/clitest/") time.sleep(1) # Create a text/plain message msg = MIMEText(fp.read()) fp.close() # me == the sender's email address # you == the recipient's email address msg['Subject'] = 'New build is available at 10.84.2.99:/work/tftpboot/, please see the %s for detail' % textfile msg['From'] = 'jacky.li@cn.promise.com' msg['To'] = 'jacky.li@cn.promise.com' # Send the message via our own SMTP server, but don't include the rec = ['ken.hou@cn.promise.com','tracy.you@cn.promise.com','travis.tang@cn.promise.com','xin.wang@cn.promise.com','lily.zhao@cn.promise.com','lisa.xu@cn.promise.com','jacky.li@cn.promise.com','zach.feng@cn.promise.com','socrates.su@cn.promise.com','paul.diao@cn.promise.com','hulda.zhao@cn.promise.com'] #rec = ['zach.feng@cn.promise.com','jacky.li@cn.promise.com','hulda.zhao@cn.promise.com'] # Send the message via our own SMTP server, but don't include the # Send the message via our own SMTP server, but don't include the # envelope header. u=u.decode('base64') serv=serv.decode('base64') p=p.decode('base64') s = smtplib.SMTP(serv) s.login(u,p) s.sendmail(msg['From'], rec, msg.as_string()) s.quit()
[ "jacky.li@cn.promise.com" ]
jacky.li@cn.promise.com
b6191a17aaf91109773e1e4d016a0f29112fe0f6
d46bae120d44ccec2ac00aa6f7bf2bde744dde73
/venv/bin/python-config
570bc983cb0570a1347c2d2bb79d4ba0f54f6602
[]
no_license
Link-yu/FlaskProject
9f5bbe4596e2a6212cc8764b36348d9326e5b014
e3d560067a5ca6d7e4cccc626ea56b9179b0340d
refs/heads/master
2020-12-02T09:59:53.753105
2017-07-11T12:24:45
2017-07-11T12:24:45
96,673,152
0
0
null
null
null
null
UTF-8
Python
false
false
2,353
#!/home/yupaopao/myPythonProject/venv/bin/python import sys import getopt import sysconfig valid_opts = ['prefix', 'exec-prefix', 'includes', 'libs', 'cflags', 'ldflags', 'help'] if sys.version_info >= (3, 2): valid_opts.insert(-1, 'extension-suffix') valid_opts.append('abiflags') if sys.version_info >= (3, 3): valid_opts.append('configdir') def exit_with_usage(code=1): sys.stderr.write("Usage: {0} [{1}]\n".format( sys.argv[0], '|'.join('--'+opt for opt in valid_opts))) sys.exit(code) try: opts, args = getopt.getopt(sys.argv[1:], '', valid_opts) except getopt.error: exit_with_usage() if not opts: exit_with_usage() pyver = sysconfig.get_config_var('VERSION') getvar = sysconfig.get_config_var opt_flags = [flag for (flag, val) in opts] if '--help' in opt_flags: exit_with_usage(code=0) for opt in opt_flags: if opt == '--prefix': print(sysconfig.get_config_var('prefix')) elif opt == '--exec-prefix': print(sysconfig.get_config_var('exec_prefix')) elif opt in ('--includes', '--cflags'): flags = ['-I' + sysconfig.get_path('include'), '-I' + sysconfig.get_path('platinclude')] if opt == '--cflags': flags.extend(getvar('CFLAGS').split()) print(' '.join(flags)) elif opt in ('--libs', '--ldflags'): abiflags = getattr(sys, 'abiflags', '') libs = ['-lpython' + pyver + abiflags] libs += getvar('LIBS').split() libs += getvar('SYSLIBS').split() # add the prefix/lib/pythonX.Y/config dir, but only if there is no # shared library in prefix/lib/. if opt == '--ldflags': if not getvar('Py_ENABLE_SHARED'): libs.insert(0, '-L' + getvar('LIBPL')) if not getvar('PYTHONFRAMEWORK'): libs.extend(getvar('LINKFORSHARED').split()) print(' '.join(libs)) elif opt == '--extension-suffix': ext_suffix = sysconfig.get_config_var('EXT_SUFFIX') if ext_suffix is None: ext_suffix = sysconfig.get_config_var('SO') print(ext_suffix) elif opt == '--abiflags': if not getattr(sys, 'abiflags', None): exit_with_usage() print(sys.abiflags) elif opt == '--configdir': print(sysconfig.get_config_var('LIBPL'))
[ "kevinyulk@163.com" ]
kevinyulk@163.com
4e72b71582b2240f32ecf38474428072ef1b7413
9e7b9e91b8425061a5ad36e0dd630a799ec79f6f
/opencv_cookbook.py
49d0d5b8c67cdd2753d61353ec3e42ef9014ce83
[]
no_license
OlgaBelitskaya/colab_notebooks
c27fad60f7e4ca35287e2561487b5d9d82efde43
d568149c8bcfb0025f7b09120ca44f639ac40efe
refs/heads/master
2023-07-07T23:02:49.289280
2021-08-14T08:16:38
2021-08-14T08:16:38
158,067,383
1
1
null
null
null
null
UTF-8
Python
false
false
8,397
py
# -*- coding: utf-8 -*- """opencv_cookbook.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1GD7Oi1LtFaEi8VOjiBM5cj5ayWpaejaf # OpenCV Cookbook ## Libraries & Color Tools """ import warnings; warnings.filterwarnings('ignore') import urllib,cv2 from skimage import io,transform import numpy as np,pylab as pl import seaborn as sb,scipy as sp fpath='https://olgabelitskaya.github.io/' pl.style.use('seaborn-whitegrid') pl.rcParams['figure.figsize']=(7,7) ColorFlags=[flag for flag in dir(cv2) if flag.startswith('COLOR')] print (np.array(ColorFlags[:30])) def get_image(original,flag,fpath=fpath): input_file=urllib.request.urlopen(fpath+original) output_file=open(original,'wb'); output_file.write(input_file.read()) output_file.close(); input_file.close() img=cv2.imread(original) return cv2.cvtColor(img,flag) """## Data""" plist=[get_image('pattern0%s.jpeg'%(i+1),flag=cv2.COLOR_BGR2RGB) for i in range(7)] flower_img=get_image('flower.png',flag=cv2.COLOR_BGR2RGB) cat_img=get_image('cat.png',flag=cv2.COLOR_BGR2RGB) img=plist[2] st='Image parameters: size - %s; shape - %s; type - %s' print (st%(img.size,img.shape,img.dtype)) pl.imshow(img); pl.show() """## Simple Manipulations""" img_inv=cv2.bitwise_not(img) pl.imshow(img_inv); pl.show() img_w2b=img.copy() img_w2b[np.where((img_w2b==[255,255,255]).all(axis=2))]=[0,0,0] pl.imshow(img_w2b); pl.show() pl.rcParams['figure.figsize']=(14,7) pl.figure(1); pl.subplot(121) img_gray1=cv2.cvtColor(img,cv2.COLOR_RGB2GRAY) pl.imshow(img_gray1) pl.subplot(122) img_gray2=cv2.cvtColor(img_w2b,cv2.COLOR_RGB2GRAY) pl.imshow(img_gray2); pl.show() pl.rcParams['figure.figsize']=(8,8); N=50 # skimage & opencv - grayscale, resize, invert img_skgray=io.imread('pattern03.jpeg',as_gray=True) img_skgray_resized=transform.resize(img_skgray,(N,N)) img_skgray_resized2=cv2.bitwise_not(img_skgray_resized) img_cvgray_resized=cv2.resize(img_gray1,(N,N), interpolation=cv2.INTER_CUBIC) img_cvgray_resized2=cv2.bitwise_not(img_cvgray_resized) pl.figure(1); pl.subplot(221) pl.imshow(img_skgray_resized,cmap=pl.cm.Greys) pl.subplot(222) pl.imshow(img_skgray_resized2) pl.subplot(223) pl.imshow(img_cvgray_resized,cmap=pl.cm.Greys) pl.subplot(224) pl.imshow(img_cvgray_resized); pl.show() pl.rcParams['figure.figsize']=(8,8) # split color channels img0=plist[0]; b,g,r=cv2.split(img0) # merge channels img_merged=cv2.merge([b,g,r]) # display one of the channels pl.figure(1); pl.subplot(231); pl.imshow(r,cmap=pl.cm.Reds_r) pl.subplot(232); pl.imshow(g,cmap=pl.cm.Greens_r) pl.subplot(233); pl.imshow(b,cmap=pl.cm.Blues_r) # display merged image pl.subplot(234); pl.imshow(img_merged); pl.show() hsv_img=cv2.cvtColor(img0,cv2.COLOR_RGB2HSV_FULL) lab_img=cv2.cvtColor(img0,cv2.COLOR_RGB2LAB) pl.figure(1); pl.subplot(121); pl.imshow(hsv_img) pl.subplot(122); pl.imshow(lab_img); pl.show() pl.rcParams['figure.figsize']=(12,4) # flip images img_vertical_flipped=cv2.flip(img,0) img_horizontal_flipped=cv2.flip(img,1) img_transposed=cv2.transpose(img) pl.figure(1); pl.subplot(131); pl.imshow(img_vertical_flipped) pl.subplot(132); pl.imshow(img_horizontal_flipped) pl.subplot(133); pl.imshow(img_transposed); pl.show() """## Advanced Transformations""" # repeat the fragment img_twice=img.copy() img_fragment=img_twice[15:60,15:60] img_twice[105:105+img_fragment.shape[0],105:105+\ img_fragment.shape[1]]=img_fragment pl.imshow(img_twice); pl.show() pl.rcParams['figure.figsize']=(8,4) # perspective transformation rows,cols,ch=img.shape pts1=np.float32([[10,10],[140,40],[10,140],[140,100]]) pts2=np.float32([[0,0],[150,0],[0,150],[150,150]]) m=cv2.getPerspectiveTransform(pts1,pts2) dst=cv2.warpPerspective(img,m,(150,150)) pl.subplot(121),pl.imshow(img),pl.title('Input') pl.scatter(pts1[:,0],pts1[:,1],c='g') pl.subplot(122),pl.imshow(dst),pl.title('Output') pl.xlim(-5,155); pl.ylim(155,-5) pl.scatter(pts2[:,0],pts2[:,1],c='g'); pl.show() pl.rcParams['figure.figsize']=(16,8) # gradient filters img2=img0.copy() img2_gray=cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY) laplacian=cv2.Laplacian(img2_gray,cv2.CV_64F,ksize=5) sobel=cv2.Sobel(img2_gray,cv2.CV_64F,1,0,ksize=3) scharr=cv2.Scharr(img2_gray,cv2.CV_64F,1,0) pl.subplot(1,4,1),pl.imshow(img2) pl.title('Original'),pl.xticks([]),pl.yticks([]) pl.subplot(1,4,2),pl.imshow(laplacian,cmap=pl.cm.bone) pl.title('Laplacian'),pl.xticks([]),pl.yticks([]) pl.subplot(1,4,3),pl.imshow(sobel,cmap=pl.cm.bone) pl.title('Sobel'),pl.xticks([]),pl.yticks([]) pl.subplot(1,4,4),pl.imshow(scharr,cmap=pl.cm.bone) pl.title('Scharr'),pl.xticks([]),pl.yticks([]); pl.show() pl.rcParams['figure.figsize']=(12,12) # erosion kernel=np.ones((3,3),np.uint8) erosion=cv2.erode(img_gray1,kernel,iterations=1) pl.subplot(2,2,1),pl.imshow(img_gray1) pl.title('Original Gray'),pl.xticks([]),pl.yticks([]) pl.subplot(2,2,2),pl.imshow(erosion,cmap=pl.cm.bone) pl.title('Erosion'),pl.xticks([]),pl.yticks([]) img_gray1_inv=cv2.bitwise_not(img_gray1) erosion_inv=cv2.erode(img_gray1_inv,kernel,iterations=1) pl.subplot(2,2,3),pl.imshow(img_gray1_inv) pl.title('Inverted Gray'),pl.xticks([]),pl.yticks([]) pl.subplot(2,2,4),pl.imshow(erosion_inv,cmap=pl.cm.bone) pl.title('Erosion for Inverted') pl.xticks([]),pl.yticks([]); pl.show() # morphological gradient gradient=cv2.morphologyEx(img,cv2.MORPH_GRADIENT,kernel) pl.subplot(1,2,1),pl.imshow(img) pl.title('Original Gray'),pl.xticks([]),pl.yticks([]) pl.subplot(1,2,2),pl.imshow(gradient,cmap=pl.cm.bone) pl.title('Morphological Gradient') pl.xticks([]),pl.yticks([]); pl.show() """## Edges' Detection""" pl.rcParams['figure.figsize']=(12,6) img_gray0=cv2.cvtColor(img0,cv2.COLOR_RGB2GRAY) edge_img=img.copy(); edge_img0=img0.copy() edge=cv2.Canny(img_gray1,90,240) edge_img[edge!=0]=(0,255,0) edge0=cv2.Canny(img_gray0,90,240) edge_img0[edge0!=0]=(0,255,0) pl.figure(1); pl.subplot(121); pl.imshow(edge_img) pl.subplot(122); pl.imshow(edge_img0); pl.show() """## Key Points""" pl.rcParams['figure.figsize']=(16,6) orb_img=flower_img.copy() orb=cv2.ORB_create() keypoints=orb.detect(orb_img,None) keypoints,descriptors=orb.compute(orb_img,keypoints) cv2.drawKeypoints(orb_img,keypoints,orb_img) match_img=np.zeros(flower_img.shape,np.uint8) center_img=flower_img[60:140,90:180] match_img[60:140,100:180]=[0,0,0] center_img=cv2.flip(center_img,0) match_img[100:100+center_img.shape[0], 150:150+center_img.shape[1]]=center_img pl.figure(1); pl.subplot(121); pl.imshow(orb_img) pl.subplot(122); pl.imshow(match_img); pl.show() pl.rcParams['figure.figsize']=(16,6) match_keypoints=orb.detect(match_img,None) match_keypoints,match_descriptors=\ orb.compute(match_img,match_keypoints) brute_force=cv2.BFMatcher(cv2.NORM_HAMMING,crossCheck=True) matches=brute_force.match(descriptors,match_descriptors) matches=sorted(matches,key=lambda x:x.distance) draw_matches=cv2.drawMatches(orb_img,keypoints, match_img,match_keypoints, matches[:9],orb_img) pl.imshow(draw_matches); pl.show() """## Object Detection""" pl.rcParams['figure.figsize']=(8,8) url='haarcascade_frontalcatface.xml' input_file=urllib.request.urlopen(fpath+url) output_file=open(url,'wb') output_file.write(input_file.read()) output_file.close(); input_file.close() gray_cat_img=cv2.cvtColor(cat_img,cv2.COLOR_RGB2GRAY) catface_img=cat_img.copy() catface_cascade=cv2.CascadeClassifier(url) catfaces=catface_cascade.detectMultiScale(gray_cat_img,1.095,6) for (x,y,w,h) in catfaces: cv2.rectangle(catface_img,(x,y),(x+w,y+h),(0,255,0),3) pl.figure(1); pl.subplot(121); pl.imshow(cat_img) pl.subplot(122); pl.imshow(catface_img); pl.show() pl.rcParams['figure.figsize']=(12,12) sport_img=get_image('sport.jpg',flag=cv2.COLOR_BGR2RGB) gray_sport_img=cv2.cvtColor(sport_img,cv2.COLOR_RGB2GRAY) face_img=sport_img.copy() url='haarcascade_frontalface_default.xml' input_file=urllib.request.urlopen(fpath+url) output_file=open(url,'wb') output_file.write(input_file.read()) output_file.close(); input_file.close() face_cascade=cv2.CascadeClassifier(url) faces=face_cascade.detectMultiScale(gray_sport_img,1.095,4) for (x,y,w,h) in faces: cv2.rectangle(face_img,(x,y),(x+w,y+h),(0,255,0),3) pl.figure(1); pl.subplot(211); pl.imshow(sport_img) pl.subplot(212); pl.imshow(face_img); pl.show()
[ "safuolga@gmail.com" ]
safuolga@gmail.com
f6bb5a74f05f10651cae3ee6b1e226e5f896c8de
65e0c11d690b32c832b943fb43a4206739ddf733
/bsdradius/tags/release20060404_v_0_4_0/bsdradius/Typecast.py
436a5e6ae0899419c20edf50298dd09eb597dcaf
[ "BSD-3-Clause" ]
permissive
Cloudxtreme/bsdradius
b5100062ed75c3201d179e190fd89770d8934aee
69dba67e27215dce49875e94a7eedbbdf77bc784
refs/heads/master
2021-05-28T16:50:14.711056
2015-04-30T11:54:17
2015-04-30T11:54:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,761
py
## BSDRadius is released under BSD license. ## Copyright (c) 2006, DATA TECH LABS ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## * Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above copyright notice, ## this list of conditions and the following disclaimer in the documentation ## and/or other materials provided with the distribution. ## * Neither the name of the DATA TECH LABS nor the names of its contributors ## may be used to endorse or promote products derived from this software without ## specific prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ## ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ## WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ## DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ## (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; ## LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ## ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ## SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ Functions and methods for casting types from string to other types. Contains functions and class for inheritance in other classes. Supported types: 'str', 'string', 'int', 'hex', 'oct', 'dec', 'bool', 'Template' """ # HeadURL $HeadURL: file:///Z:/backup/svn/bsdradius/tags/release20060404_v_0_4_0/bsdradius/Typecast.py $ # Author: $Author: valts $ # File version: $Revision: 201 $ # Last changes: $Date: 2006-04-04 17:22:11 +0300 (Ot, 04 Apr 2006) $ # for typecasting to Template from string import Template ### functions ### def getstr (input): return str(input) def getstring (input): return getstr(input) def getint (input): return int(str(input)) def gethex (input): return int(str(input), 16) def getoct (input): return int(str(input), 8) def getdec (input): return int(str(input), 10) _booleanStates = {'1': True, 'yes': True, 'y': True, 'true': True, 'on': True, '0': False, 'no': False, 'n': False, 'false': False, 'off': False} def getbool (input): inp = str(input) if inp.lower() not in _booleanStates: raise ValueError, 'Not a boolean: %s' % inp return _booleanStates[inp.lower()] def getTemplate (input): return Template(str(input)) class Typecast: """Use this class as base class in your classes to add typecasting functionality. This class defines methods which are wrappers to functions in module namespace. You can override attribute "data" in derived classes. Since self.data is dictionary (with multiple levels) you can pass any number of keys to typecasting methods. They all use method _getItem() which searches recursively in self.data for rightmost key value. """ _booleanStates = _booleanStates def __init__(self): self.data = {} def _getItem(self, keys): """Search recursively for item by given keys Input: (str) keys Example: t._getItem('key1', 'key2', 'key3') Output: (mixed) value """ if not keys: raise KeyError, 'No key specified' tmp = None for key in keys: if tmp is None: tmp = self.data[key] else: tmp = tmp[key] return tmp def getstr (self, *keys): return getstr(self._getItem(keys)) def getstring (self, *keys): return getstring(self._getItem(keys)) def getint (self, *keys): return getint(self._getItem(keys)) def gethex (self, *keys): return gethex(self._getItem(keys)) def getoct (self, *keys): return getoct(self._getItem(keys)) def getdec (self, *keys): return getdec(self._getItem(keys)) def getbool (self, *keys): return getbool(self._getItem(keys)) def getTemplate (self, *keys): return getTemplate(self._getItem(keys)) # holds references to all supported typecast methods typecastMethods = { 'str' : getstr, 'string' : getstring, 'int' : getint, 'hex' : gethex, 'oct' : getoct, 'dec' : getdec, 'bool' : getbool, 'Template' : getTemplate, } # holds references to all supported typecast methods Typecast.typecastMethods = { 'str' : Typecast.getstr, 'string' : Typecast.getstring, 'int' : Typecast.getint, 'hex' : Typecast.gethex, 'oct' : Typecast.getoct, 'dec' : Typecast.getdec, 'bool' : Typecast.getbool, 'Template' : Typecast.getTemplate, }
[ "valdiic@72071c86-a5be-11dd-a5cd-697bfd0a0cef" ]
valdiic@72071c86-a5be-11dd-a5cd-697bfd0a0cef
a81b7b040209bbe9e4e5f1677ea8da5097ef6593
906297c4f691b03e65b454bf9c12ab0331e53589
/cron/tasks.py
b05b58e0b7ff3f2b13ed3fe898d4431d67695957
[]
no_license
unamatasanatarai/django-movie-theater
5798a54044a889c71f937865fe3adfbe477eb6ab
7d0cd27738b330bfe67eef1a35d2827c2137a222
refs/heads/master
2021-01-23T15:07:47.382052
2017-09-07T06:33:13
2017-09-07T06:33:13
102,700,159
1
1
null
null
null
null
UTF-8
Python
false
false
956
py
from celery import task from theater.models import SeatTentative, SeatBooked from datetime import datetime, timedelta from rest.communicate import Communicate @task() def trim_tentative(): elements = SeatTentative.objects.filter(created_at__lte=(datetime.now() - timedelta(minutes=3))) movie_ids = elements.values_list('repertoire_id', flat=True).distinct() elements.delete() for movie_id in movie_ids: Communicate.tentative_push(str(movie_id)) @task() def confirm_payments(): toconfirm = SeatBooked.objects.filter(created_at__lte=(datetime.now() - timedelta(minutes=2)), confirmed=False) movie_ids = toconfirm.values_list('repertoire_id', flat=True).distinct() for seat in toconfirm: seat.confirmed = True seat.save() SeatTentative.objects.filter(repertoire_id=seat.repertoire_id, seat_id=seat.id).delete() for movie_id in movie_ids: Communicate.tentative_push(str(movie_id))
[ "piotr.grabowski@interak.pl" ]
piotr.grabowski@interak.pl
a135ba849e3b4b36122c67ab34cbc6fde8d2f519
702c7b618951339f31b4161f55bbbd8f3ffd7811
/hw1/hw1.py
94d3f51e7f777b1727c9f5569e4fa7bc34d19109
[]
no_license
erhla/machine-learning
839f581676cb003d304a2f6efc0528885fce993c
6e9bb6fa377a91039695a717f932f14e5f2214d9
refs/heads/master
2020-05-04T23:31:05.531591
2019-05-29T20:12:28
2019-05-29T20:12:28
179,546,114
0
0
null
null
null
null
UTF-8
Python
false
false
3,773
py
''' Homework 1 Eric Langowski ''' import pandas as pd from sodapy import Socrata import geopandas import shapely #Problem 1 CRIMES_18 = '3i3m-jwuy' CRIMES_17 = 'd62x-nvdr' CENSUS_TRACTS = '74p9-q2aq' def get_crime_data(cid): ''' gets crime data from City of Chicago API ''' client = Socrata('data.cityofchicago.org', None) current = 0 results = client.get(cid, limit=2000, offset=current) while len(results) > 0: current += 2000 new = client.get(cid, limit=2000, offset=current) if new: results.append(new) else: break print(current) return pd.DataFrame.from_records(results) def download_17_18(): ''' Downloads '17 and '18 Crime data ''' crime_17 = get_crime_data(CRIMES_17) crime_18 = get_crime_data(CRIMES_18) return pd.concat(crime_17, crime_18) CSV_URL = 'https://data.cityofchicago.org/api/views/' CSV_FRAG = '/rows.csv?accessType=DOWNLOAD' URLS = {'17': CSV_URL + CRIMES_17 + CSV_FRAG, '18': CSV_URL + CRIMES_18 + CSV_FRAG} def download_17_18_alt(): ''' Alternate method to download '17 and '18 crime data ''' crime_17 = pd.read_csv(URLS['17']) crime_18 = pd.read_csv(URLS['18']) df = pd.concat([crime_17, crime_18]) df['Date'] = pd.to_datetime(df['Date']) return df CENSUS_VARIABLES = {"S0101_C01_001E": "Population", "S1701_C02_001E": "Population in Poverty", "S1901_C01_012E": "Median income", "S1501_C02_015E": "Percent Population with Bachelors", "S2303_C02_033E": "Percent Population working full-time", "S1601_C02_003E": "Percent speaking not English"} CENSUS_URL = "https://api.census.gov/data/2017/acs/acs5/subject?get=" CENSUS_FRAG = "&for=tract:*&in=state:17&in=county:031" def get_census_data(): ''' gets census data for Census tracts in Chicago. Modify dictionary census_variables to change which variables are retrieved ''' url = CENSUS_URL + ",".join(CENSUS_VARIABLES.keys()) + CENSUS_FRAG df = pd.read_json(url, orient='records') new_cols = list(CENSUS_VARIABLES.values()) + ['state', 'county', 'tract'] df.columns = new_cols df = df.drop(df.index[0]) df = df.drop(['state', 'county'], axis=1) return df def geomerge(crime_data): ''' Note: Some of this code is from my group's 122 project which made a spatial join on Chicago's neighborhoods. This takes the crime data and performs a spatial join on Chicago's census tracts. Returns: (geodf) the crime df ''' client = Socrata('data.cityofchicago.org', None) files = client.get(CENSUS_TRACTS) df = pd.DataFrame(files) df['the_geom'] = df['the_geom'].apply(shapely.geometry.shape) df = geopandas.GeoDataFrame(df, geometry='the_geom') df.crs = {'init': 'espg:4326'} df = df[['the_geom', 'tractce10']] crime_data = crime_data[crime_data['Longitude'].notna()] crime_data['Location'] = crime_data['Location'].str.strip('()').str.split(',') crime_data['Location'] = crime_data['Location'].apply(lambda x: (float(x[1]), float(x[0]))) crime_data.loc[:, 'Location'] = crime_data['Location'].apply(shapely.geometry.Point) geodf = geopandas.GeoDataFrame(crime_data, geometry='Location') geodf.crs = {'init': 'espg:4326'} #Memory performance hack ls = [] step = 4000 num_steps = geodf.shape[0] % step - 2 counter = 0 while num_steps > 0: if (counter + 1) * step > geodf.shape[0]: break ls.append(geopandas.sjoin(geodf[step*counter:(counter+1)*step], df, how='left', op='within')) counter = counter + 1 num_steps = num_steps - 1 return pd.concat(ls)
[ "langowski@cs.uchicago.edu" ]
langowski@cs.uchicago.edu
76eac8484a0e0f4385ec8d7a7a8100f4be7cd089
d6fa7b19190e83447ac7456ccce5e0d8ae7de4f0
/move.py
dd11292061947f3145cb005a2f669d9ce85a0b32
[]
no_license
VariousMilkshakes/GRID-py
ffcabd35bd421ca56d1486f7b75c875d073940bc
d243be07016742ab129cb0e48ae64c0f5e0733fa
refs/heads/master
2016-08-08T04:03:47.105610
2013-07-04T21:32:37
2013-07-04T21:32:37
11,161,532
0
0
null
null
null
null
ISO-8859-4
Python
false
false
3,402
py
# -*- coding: cp1252 -*- from random import randint import sys print "Welcome to the this Test" print "This is test 2: Sam like Woffles!" print gY = input("How tall do you want your grid?") gX = input("How wide do you want your grid?") oY = gY oX = gX - 2 Xinput = input("Where do you want to start? (X)") Yinput = input("Where do you want to start (Y)?") print c = 0 while (c == 0): foodX = randint(0,oX) foodY = randint(0,oY) if Xinput == foodX and foodY == Yinput: c = 0 else: c = 1 fX = foodX fY = foodY item = '#' mX = Xinput mY = Yinput game = 0 ship='A' jump = False while(game == 0): o = 0 x = 0 y = 0 rowXdef = { 0 : [o] } while (y <= oY): while (x <= oX): rowXdef[y].append(o) x = x + 1 x = 0 y = y + 1 rowXdef[y] = [o] mark = rowXdef[mY] mark[mX] = ship spawn = rowXdef[fY] spawn[fX] = item del rowXdef[(oY + 1)] del rowXdef[oY] if mY == fY and mX == fX: print 'WIN' raw_input() sys.exit() for line in rowXdef: x = rowXdef[line] cCell = 0 while (cCell <= oX): for cell in x: print cell, cCell = cCell + 1 print clean = 0 while (clean == 0): move = raw_input() if move == 'w': if jump == True: mY = (gY - 1) jump = False else: mY = mY - 1 if mY == 0: jump = True ship = 'A' clean = 1 elif move == 'a': if jump == True: mX = (gX - 1) jump = False else: mX = mX - 1 if mX == 0: jump = True ship = '<' clean = 1 elif move == 'd': if jump == True: mX = 0 jump = False else: mX = mX + 1 if mX == (gX - 1): jump = True ship = '>' clean = 1 elif move == 's': if jump == True: mY = 0 jump = False else: mY = mY + 1 if mY == (gY - 1): jump = True ship = 'V' clean = 1 else: print "Īnvalid Movement Key"
[ "bn.gladstone@gmail.com" ]
bn.gladstone@gmail.com
e36bbc0c4240de429927358094f5d3cd4c54a838
f7e4ba62191d39b050eab6cbf196c9000751a779
/examples/function_param.py
b285fc9ff46f8f155c969867b438a10ade9d1976
[]
no_license
heimo-tiihonen/hello-world
04bdc59f7806b9c851adf43dfa6312ed219bac79
b1d513242a0511f1866874cec9b410484b186038
refs/heads/master
2021-01-09T06:16:34.729181
2017-02-04T19:41:57
2017-02-04T19:41:57
80,949,066
0
0
null
null
null
null
UTF-8
Python
false
false
278
py
def print_max(a, b): if a > b: print(a, 'is maximum') elif a == b: print(a, 'is equal to', b) else: print(b, 'is maximum') # directly pass literal values print_max(3, 4) x = 5 y = 7 z = 'Testi' # pass variables as arguments print_max(z, y)
[ "heimo@dsl-espbrasgw1-50dfb2-69.dhcp.inet.fi" ]
heimo@dsl-espbrasgw1-50dfb2-69.dhcp.inet.fi
8de1127722d96b24e0ea4a854844cb853d233569
7193be8e52b2095d8b6472f3ef2104843dca339e
/Project5-Capstone/the_dummy_variables/josh/testing/test_relative_path.py
1f24c6af184d5ae1c59feb6189e85136b5bb7ee5
[]
no_license
vuchau/bootcamp007_project
4b0f37f49a1163ea6d8ee4143a5dcfdef0d352dd
ffbd0f961b18510fc72fd49770187ec1b4b013ae
refs/heads/master
2020-03-20T13:19:58.812791
2017-06-08T05:13:24
2017-06-08T05:13:24
null
0
0
null
null
null
null
UTF-8
Python
false
false
140
py
import os file_dir = os.path.dirname(__file__) print file_dir dirname = os.path.dirname print dirname(dirname(os.path.abspath(__file__)))
[ "jlitven@gmail.com" ]
jlitven@gmail.com
88ea9f503fbe4878090275c2480106a7648b48f2
f94e4955f9d16b61b7c9bff130b9d9ee43436bea
/labs/lab06/lab06.py
1c1dac20000f742c21337b538d3d8ac3b9563bc4
[]
no_license
j2chu/dsc80-sp19
bd1dade66c19b920a54b0f8551fd999185449f86
dd48210a7cbadfb6470104b275f34085437e4766
refs/heads/master
2020-06-01T23:22:32.727488
2019-06-07T01:46:11
2019-06-07T01:46:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,275
py
import os import pandas as pd import numpy as np import requests import bs4 import json # --------------------------------------------------------------------- # Question # 1 # --------------------------------------------------------------------- def question1(): """ NOTE: You do NOT need to do anything with this function. The function for this question makes sure you have a correctly named HTML file in the right place. Note: This does NOT check if the supplementary files needed for your page are there! >>> os.path.exists('lab06_1.html') True """ # Don't change this function body! # No python required; create the HTML file. return # --------------------------------------------------------------------- # Question # 2 # --------------------------------------------------------------------- def extract_book_links(text): """ :Example: >>> fp = os.path.join('data', 'products.html') >>> out = extract_book_links(open(fp, encoding='utf-8').read()) >>> url = 'scarlet-the-lunar-chronicles-2_218/index.html' >>> out[0] == url True """ return ... def get_product_info(text): """ :Example: >>> fp = os.path.join('data', 'Frankenstein.html') >>> out = get_product_info(open(fp, encoding='utf-8').read()) >>> isinstance(out, dict) True >>> 'UPC' in out.keys() True >>> out['Rating'] 'Two' """ return ... def scrape_books(k): """ :param k: number of book-listing pages to scrape. :returns: a dataframe of information on (certain) books on the k pages (as described in the question). :Example: >>> out = scrape_books(1) >>> out.shape (1, 10) >>> out['Rating'][0] == 'Five' True >>> out['UPC'][0] == 'ce6396b0f23f6ecc' True """ return ... # --------------------------------------------------------------------- # Question 3 # --------------------------------------------------------------------- def send_requests(apiKey, *args): """ :param apiKey: apiKey from newsapi website :param args: number of languages as strings :return: a list of dictionaries, where keys correspond to languages and values correspond to Response objects >>> responses = send_requests(os.environ['API_KEY'], "ru", "fr") >>> isinstance(responses[0], dict) True >>> isinstance(responses[1], dict) True """ return ... def gather_info(resp): """ Finds some basic information from the obtained responses :param resp: a list of dictionaries :return: a list with the following items: language that has the most number of news most common base url for every language >>> responses = send_requests(os.environ['API_KEY'], "ru", "fr") >>> result = gather_info(responses) >>> isinstance(result[0], str) True >>> len(result) == len(responses) + 1 True """ return ... # --------------------------------------------------------------------- # Question # 4 # --------------------------------------------------------------------- def depth(comments): """ :Example: >>> fp = os.path.join('data', 'comments.csv') >>> comments = pd.read_csv(fp, sep='|') >>> depth(comments).max() == 5 True """ return ... # --------------------------------------------------------------------- # DO NOT TOUCH BELOW THIS LINE # IT'S FOR YOUR OWN BENEFIT! # --------------------------------------------------------------------- # Graded functions names! DO NOT CHANGE! # This dictionary provides your doctests with # a check that all of the questions being graded # exist in your code! GRADED_FUNCTIONS = { 'q01': ['question1'], 'q02': ['extract_book_links', 'get_product_info', 'scrape_books'], 'q03': ['send_requests', 'gather_info'], 'q04': ['depth'] } def check_for_graded_elements(): """ >>> check_for_graded_elements() True """ for q, elts in GRADED_FUNCTIONS.items(): for elt in elts: if elt not in globals(): stmt = "YOU CHANGED A QUESTION THAT SHOULDN'T CHANGE! \ In %s, part %s is missing" % (q, elt) raise Exception(stmt) return True
[ "aaron.fraenkel@gmail.com" ]
aaron.fraenkel@gmail.com
090b3c526b14fc85e5ddfe57bd932deff3860bf7
9d4bf5f90cd0a8eb97e7e48a0545f349c3b17b45
/1-100/Letter_Combinations_of_a_Phone_Number.py
f86071b4c06a57181e25e64c02981526a3a4edc6
[]
no_license
Ys-Zhou/leetcode-medi-p2
8201a6d1ee7e4cb6fe8bc9516530a8b8b3e26e8c
df3495d0bc504237305b11974906f27f8fd124e9
refs/heads/master
2021-10-07T09:07:28.974814
2018-12-04T09:23:21
2018-12-04T09:23:21
111,872,195
0
0
null
null
null
null
UTF-8
Python
false
false
813
py
# 25 / 25 test cases passed. # Runtime: 36 ms class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ if digits == '': return [] letters = {'2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'], '5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'], '7': ['p', 'q', 'r', 's'], '8': ['t', 'u', 'v'], '9': ['w', 'x', 'y', 'z']} length = len(digits) def getletter(index): if index == length: return [''] return [x + y for x in letters[digits[index]] for y in getletter(index + 1)] return getletter(0)
[ "zhouyan1993ys@gmail.com" ]
zhouyan1993ys@gmail.com
bc95461ad6fdc0ef95c4d671c174b643f840fd99
3354e6bdd4aeb2ddec84e6a8036c90cd24b6577a
/(구)자료구조와 알고리즘/(구)Quizes/backjoon/back_1002.py
b90ab7cd42413d530cb002dd703cd4c028e3c9d1
[]
no_license
hchayan/Data-Structure-and-Algorithms
1125d7073b099d8c6aae4b14fbdb5e557dcb9412
be060447e42235e94f93a0b2f94f84d2fd560ffe
refs/heads/master
2023-01-05T10:15:02.862700
2020-11-04T08:16:56
2020-11-04T08:16:56
209,513,516
1
0
null
null
null
null
UTF-8
Python
false
false
466
py
import sys import math n = int(sys.stdin.readline().rstrip()) def getAns(): x1, y1, r1, x2, y2, r2 = map(int, sys.stdin.readline().rstrip().split()) leng = math.sqrt((x2-x1)**2+(y2-y1)**2) if r1 == r2 and x1 == x2 and y1 == y2: return -1 if r1 > r2: r1, r2 = r2, r1 if leng > r1+r2: return 0 elif leng == r1+r2: return 1 else: if leng+r1 == r2: return 1 elif leng+r1 < r2: return 0 return 2 for nn in range(n): print(getAns())
[ "k852012@naver.com" ]
k852012@naver.com
d23876d3a93f905357e7be2a1449341ef64f86a7
f4718efa9d34fabad15f1b4ef856c4639eb6e718
/Test.py
0f3fceb541fd26b23c09661bee50a64c921d957e
[]
no_license
wilee1224/Data_wrangling
98faa7428da2ec28dba5ad524d811bfadaf2db2b
ba4d88a987a38a4c1850f2954073d423300f1652
refs/heads/master
2020-03-12T04:14:49.194795
2018-08-06T12:24:57
2018-08-06T12:24:57
130,441,245
0
0
null
null
null
null
UTF-8
Python
false
false
127
py
import xlrd book = xlrd.open_workbook("SOWC 2014 Stat Tables_Table 9.xlsx") for sheet in book.sheets(): print sheet.name
[ "wilee1224@gmail.com" ]
wilee1224@gmail.com
bfce90df81d846a317456efccf614e1b2558a113
495fbb4b87586186480826273abf55b947d9c366
/Adivinar_el_numero.py
989c64be349a9c164f29fa88863b8a2871297b8a
[]
no_license
GitBis/-FP-_Labo06_-00370819-
d7b777a76096e7936e5114b10516876f11f360b0
074166f4caefc9a3e4cbd214e40df6556f4dfd24
refs/heads/master
2020-08-13T04:06:13.414501
2019-10-16T05:53:26
2019-10-16T05:53:26
214,902,229
0
0
null
null
null
null
UTF-8
Python
false
false
842
py
import random print("ADIVINA EL NUMERO") comprobar = True contador = 1 while comprobar == True: n = int(input("Ingrese un numero del 1 al 10: ")) if n > 0 and n < 11: all = random.randrange(1,10) if n == all: print(all) print(f"numero de intentos: {contador}") else: while n != all: if n > all: n = int(input("¡Te pasastes! vuelve a intentar: ")) contador += 1 elif n < all: n = int(input("¡Prueba un numero mayor! : ")) contador += 1 print(f"El numero aleatorio era: {all}") print(f"numero de intentos: {contador}") comprobar = False else: print("Ese no es un numero del 1 al 10 vuelve a intentar")
[ "00370819@uca.edu.sv" ]
00370819@uca.edu.sv
77fdcf1dbfc3a529545552210737968c88bf404b
ffaeaf54e891c3dcca735347f27f1980f66b7a41
/python/1.POP/1.base/01.helloworld.py
015e87763fe1f07c2320ce7fe71f056ea13d317c
[ "Apache-2.0" ]
permissive
dunitian/BaseCode
9804e3d8ff1cb6d4d8cca96978b20d168072e8bf
4855ef4c6dd7c95d7239d2048832d8acfe26e084
refs/heads/master
2020-04-13T09:51:02.465773
2018-12-24T13:26:32
2018-12-24T13:26:32
137,184,193
0
0
Apache-2.0
2018-06-13T08:13:38
2018-06-13T08:13:38
null
UTF-8
Python
false
false
970
py
'''三个单引号多行注释: print("Hello World!") print("Hello World!") print("Hello World!")''' """三个双引号多行注释: print("Hello World!") print("Hello World!") print("Hello World!")""" # 单行注释 输出 print("Hello World!") # 定义一个变量并输出 name = "小明" print(name) print("x" * 10) print("dnt.dkill.net/now", end='') print("带你走进中医经络") print("dnt.dkill.net/now", end="") print("带你走进中医经络") # 如果字符串内部既包含'又包含"怎么办?可以用转义字符\来标识 print("I\'m \"OK\"!") # 如果字符串里面有很多字符都需要转义,就需要加很多\,为了简化,Python还允许用r''表示''内部的字符串默认不转义 print(r'\\\t\\') # 如果字符串内部有很多换行,用\n写在一行里不好阅读,为了简化,Python允许用'''...'''的格式表示多行内容 print('''我请你吃饭吧~ 晚上吃啥? 去厕所,你说呢?''')
[ "39723758+lotapp@users.noreply.github.com" ]
39723758+lotapp@users.noreply.github.com
4b8450ca316cbf700f09c76a6c374e71ef1ce7c9
62b78ad6d3ec041ad20e4328d1730d815c9e35f1
/Twosteps.py
8c659c092569737b987696cb0d9e96f753e7dd19
[]
no_license
Jamshid93/ForLoops2
7fe5b3240370d88a888f2d4609fb6d7787965a4d
296de0ccc51872001e45e20926b91a4528abd7a5
refs/heads/master
2022-01-26T05:22:18.206075
2019-07-20T04:12:37
2019-07-20T04:12:37
197,874,396
0
0
null
null
null
null
UTF-8
Python
false
false
105
py
for item in range(3, 14, 2): # this is code result 3,5,...13. Because after 14 writin 2 print(item)
[ "hamzayevjf@gmail.com" ]
hamzayevjf@gmail.com
e9eef0ae487bb90ae983c14902b33bc6d26c7a4f
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/429/usersdata/313/105928/submittedfiles/jogoDaVelha.py
6702e638a0b195b5ad2f3fe0c84a675088f19cc5
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
1,102
py
print (" BEM-VINDO AO JOGO DA VELHA ") print("O primeiro jogador será o (X) e o segundo o (O) ") posicao = """ posicoes do jogo 1 | 2 | 3 ----------- 4 | 5 | 6 ----------- 7 | 8 | 9 """ print (posicao) posicoes = [ (5,7), (5,5), (5,3), (9,7), (9,5), (9,3), (7,7), (7,5), (7,3), ] ganhador = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7], ] jogo = [] for vertical in posicao.splitlines(): jogo.append(list(vertical)) jogador = "X" jogando = True jogadas = 0 while True: if jogadas == 9: print (" DEU VELHA!") break jogada = int(input(" digite a posicao de 1 à 9 (jogador %s): " % jogador )) if jogada<1 or jogada>9: print ("posicao fora das posicoes do jogo") continue if jogo[posicoes[jogada][0]][posicoes[jogada][1]] != " ": print ("Essa posicao já foi ocupada") continue
[ "rafael.mota@ufca.edu.br" ]
rafael.mota@ufca.edu.br
67f1386cbcd7aa7765debd357ae2e31c5ecdad81
8ab2c341b570e26c8a06e7c5e9e95e3e2a108aba
/build/tasks/catkin_generated/pkg.installspace.context.pc.py
1a3ac85d66d27b61334ac967aed258bf919d3a93
[]
no_license
Aquavaders/Vader3-Control
c6429d58d208f303d5ed309c488d06f140ab08b5
8523e7ddda78b747106586bacfac14e99201741b
refs/heads/master
2020-07-29T04:01:25.852450
2020-02-27T20:04:36
2020-02-27T20:04:36
209,660,745
0
0
null
null
null
null
UTF-8
Python
false
false
366
py
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else [] PROJECT_CATKIN_DEPENDS = "".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME = "tasks" PROJECT_SPACE_DIR = "/home/alaa/rov19_ws/install" PROJECT_VERSION = "0.0.0"
[ "AlaaAnani" ]
AlaaAnani
79115cc0889d1e2a25aaab0b5bb5644d6b83c037
a4b621ef4230c27ddec5a4c1290f2e0c57e40019
/AK_RPversion.py
29bbcef2ed0e84d3c5f66352b6551262107c1064
[]
no_license
EliReid/4Button-Expert
54479297f168fe534a9e5866ba267968337c0011
f5971182a467fc0ff507d7a4ec4904d03803a56e
refs/heads/master
2020-04-28T12:08:03.942819
2019-02-21T22:15:56
2019-02-21T22:15:56
null
0
0
null
null
null
null
UTF-8
Python
false
false
16,752
py
## uses only RP and AK planning units and unit tasks, so far ## perception of the game is hacked, so far import sys sys.path.append('/Users/robertwest/CCMSuite') #sys.path.append('C:/Users/Robert/Documents/Development/SGOMS/CCMSuite') import ccm from random import randrange, uniform log = ccm.log() # log=ccm.log(html=True) from ccm.lib.actr import * class MyEnvironment(ccm.Model): warning_light = ccm.Model(isa='warning_light', state='off') response = ccm.Model(isa='response', state='none') code = ccm.Model(isa='code', state='SU') # model assumes it starts at AK and doen't look until it has to motor_finst = ccm.Model(isa='motor_finst', state='re_set') class MotorModule(ccm.Model): ## def maybe_change_light(self): ## irand = randrange(0, 30) # adjust warning light probability here ## if irand < 1: ## print ' light on ++++++++++++++++++++++++++++++++++++++++++++++++++++' ## print irand ## self.parent.parent.warning_light.state='on' ## ## def turn_off_light(self): ## self.parent.parent.warning_light.state='off' ## print 'light off ------------------------------------------------------' ## # change_state is a generic action that changes the state slot of any object # disadvantages (1) yield #time is always the same (2) cannot use for parallel actions def change_state_fast(self, env_object, slot_value): yield 3 x = eval('self.parent.parent.' + env_object) x.state = slot_value print env_object print slot_value self.parent.parent.motor_finst.state = 'change_state_fast' def vision_slow(self): yield 5 print 'target identified' self.parent.parent.motor_finst.state = 'vision_slow' self.parent.b_vision.set('YP') def motor_finst_reset(self): self.parent.parent.motor_finst.state = 're_set' class EmotionalModule(ccm.ProductionSystem): production_time = 0.043 ## def warning_light(b_emotion='threat:ok',warning_light='state:on'): ## print "warning light is on!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" ## b_emotion.set('threat:high') class Environment_Manager(ACTR): # this agent triggers the warning light b_focus = Buffer() motor = MotorModule() ## def init(): ## b_focus.set('set_warning') ## def environment(b_focus='set_warning'): ## motor.maybe_change_light() class MyAgent(ACTR): # this is the agent that does the task # module buffers b_DM = Buffer() b_motor = Buffer() b_focus = Buffer() b_vision = Buffer() # goal buffers b_context = Buffer() b_plan_unit = Buffer() b_unit_task = Buffer() b_method = Buffer() b_operator = Buffer() b_emotion = Buffer() DM = Memory(b_DM) motor = MotorModule(b_motor) Emotion = EmotionalModule(b_emotion) def init(): ## DM.add('planning_unit:XY cuelag:none cue:start unit_task:X') ## DM.add('planning_unit:XY cuelag:start cue:X unit_task:Y') ## DM.add('planning_unit:XY cuelag:X cue:Y unit_task:finished') DM.add('planning_unit:AK cuelag:none cue:start unit_task:AK') DM.add('planning_unit:AK cuelag:start cue:AK unit_task:RP') DM.add('planning_unit:AK cuelag:AK cue:RP unit_task:finished') DM.add('planning_unit:RP cuelag:none cue:start unit_task:RP') DM.add('planning_unit:RP cuelag:start cue:RP unit_task:AK') DM.add('planning_unit:RP cuelag:RP cue:AK unit_task:finished') b_context.set('finshed:nothing status:unoccupied warning_light:off') b_emotion.set('threat:ok') b_focus.set('none') b_vision.set('AK') # assume this has happened ########################### begin the planning unit # these productions are the highest level of SGOMS and fire off the context buffer # the decision process can be as complex as needed # the simplest way is to have a production for each planning unit (as in this case) # the first unit task in the planning unit is directly triggered from here def run_PU_AK(b_context='finshed:nothing status:unoccupied', b_vision='AK'): b_unit_task.set('unit_task:AK state:running typee:ordered') b_plan_unit.set('planning_unit:AK cuelag:none cue:start unit_task:AK state:running') b_context.set('finished:nothing status:occupied') print 'PU_AK ordered planning unit is chosen OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' def run_PU_RP(b_context='finshed:AK status:unoccupied'): b_unit_task.set('unit_task:RP state:running typee:ordered') b_plan_unit.set('planning_unit:RP cuelag:none cue:start unit_task:RP state:running') b_context.set('finished:nothing status:occupied') print 'PU_RP ordered planning unit is chosen OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' def end(b_context='finshed:RP status:unoccupied'): b_context.set('end') print 'end program' def false_alarm(b_context='finshed:?finished status:interupted'): motor.turn_off_light() b_emotion.set('threat:ok') b_unit_task.set('unit_task:X state:running typee:ordered') b_plan_unit.set('planning_unit:XY cuelag:none cue:start unit_task:X state:running') b_context.set('finished:nothing status:occupied') print 'ordered planning unit is chosen OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' ######################### planning unit management loop # these are generic productions for managing the execution of planning units ######## get next unit task and save a memory of the completed unit task # the first unit task in a planning unit is triggered when the planning unit is chosen # these porductions fire within planning units to get the next unit task # to trigger the next unit task the unit_task state slot value is switched from 'end' to 'begin' # this is also where the successful completion of the last unit task is saved to memory ## the memory save is often not needed in simple models and is not implemented here ### although, in theory, the memory save always happens so this step should always be included # ordered planning units ## retrieve next unit task def request_next_unit_task(b_plan_unit='planning_unit:?planning_unit cuelag:?cuelag cue:?cue unit_task:?unit_task state:running', b_unit_task='unit_task:?unit_task state:end typee:ordered', b_emotion='threat:ok'): DM.request('planning_unit:?planning_unit cue:?unit_task unit_task:? cuelag:?cue') b_plan_unit.set('planning_unit:?planning_unit cuelag:?cuelag cue:?cue unit_task:?unit_task state:retrieve') # next unit task print 'finished unit task = ', unit_task # save completed unit task here def retrieved_next_unit_task(b_plan_unit='state:retrieve', b_DM='planning_unit:?planning_unit cuelag:?cuelag cue:?cue unit_task:?unit_task!finished'): b_plan_unit.set('planning_unit:?planning_unit cuelag:?cuelag cue:?cue unit_task:?unit_task state:running') b_unit_task.set('unit_task:?unit_task state:running typee:ordered') print 'next unit_task = ', unit_task print 'ordered' # situated planning units ## allow the next unit task to fire def next_situated_unit_task(b_unit_task='unit_task:?unit_task state:end typee:situated', b_emotion='threat:ok'): b_unit_task.modify(state='find_match') print 'next situated unit task' print 'situated' # save unit task here ########### end the planning unit and save a memory of it # a planning unit can be thought of as a loop # these are the exit conditions # in these the planning unit should be saved # although, to keep the code simple, this is not done here ## finished ordered planning unit def retrieved_last_unit_task(b_plan_unit='planning_unit:?planning_unit state:retrieve', b_unit_task='unit_task:?unit_task state:end typee:ordered', b_DM='planning_unit:?planning_unit cuelag:?cuelag cue:?cue unit_task:finished'): # not, the memory retrieval indicates the plan is finished print 'stopped planning unit=',planning_unit print 'finished' b_unit_task.modify(state='stopped') b_context.set('finshed:?planning_unit status:unoccupied') # save completed planning unit here def interupted_planning_unit(b_plan_unit='planning_unit:?planning_unit', b_unit_task='unit_task:?unit_task state:end typee:?typee', b_emotion='threat:high'): print 'stopped planning unit=' print 'interupted IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII' b_unit_task.modify(state='stopped') b_context.set('finshed:?planning_unit status:interupted') # save completed planning unit here ####################################### unit tasks # AK unit task AK-WM-SU-ZB-FJ ## situated matching productions def AK_start_unit_task_situated(b_unit_task='state:find_match typee:situated'): b_unit_task.set('unit_task:AK state:running typee:situated') print 'start unit task AK' ## body of the unit task def AK_known_response_AK(b_unit_task='unit_task:AK state:running', b_focus='none'): b_focus.set('AK') b_method.set('method:known_response target:response content:1234 state:start') print 'AK unit task AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' print 'doing AK' def AK_known_response_WM(b_unit_task='unit_task:AK state:running', b_focus='AK', b_method='state:finished'): b_focus.set('WM') b_method.set('method:known_response target:response content:1432 state:start') print 'doing WM' def AK_known_response_SU(b_unit_task='unit_task:AK state:running', b_focus='WM', b_method='state:finished'): b_focus.set('SU') b_method.set('method:known_response target:response content:4123 state:start') print 'doing SU' def AK_known_response_ZB(b_unit_task='unit_task:AK state:running', b_focus='SU', b_method='state:finished'): b_focus.set('ZB') b_method.set('method:known_response target:response content:2143 state:start') print 'doing ZB' def AK_known_response_FJ(b_unit_task='unit_task:AK state:running', b_focus='ZB', b_method='state:finished'): b_focus.set('FJ') b_method.set('method:known_response target:response content:3214 state:start') print 'doing FJ' def AK_finished(b_unit_task='unit_task:AK state:running', b_focus='FJ', b_method='state:finished'): b_focus.set('none') b_unit_task.modify(state='end') ## this line ends the unit task print ' - finished unit task' # YP-FJ # RP unit task RP-SU< # ZB-WM ## situated matching productions def RP_start_unit_task_situated(b_unit_task='state:find_match typee:situated'): b_unit_task.set('unit_task:Y state:running typee:situated') print 'start unit task Y' ## body of the unit task def RP_known_response_RP(b_unit_task='unit_task:RP state:running', b_focus='none'): b_focus.set('RP') b_method.set('method:known_response target:response content:4321 state:start') print 'doing RP_UT RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR' print 'doing RP' def RP_known_response_SU(b_unit_task='unit_task:RP state:running', b_focus='RP', b_method='state:finished'): b_focus.set('SU') b_method.set('method:known_response target:response content:4123 state:start') print 'doing SU' def RP_unknown_code(b_unit_task='unit_task:RP state:running', b_focus='SU', b_method='state:finished'): b_focus.set('unkown_code') b_method.set('method:get_code target:response content:1432 state:start') print 'getting code' def RP_got_code1(b_unit_task='unit_task:RP state:running', b_focus='unkown_code', b_method='state:finished', b_vision='YP'): b_focus.set('YP') b_method.set('method:known_response target:response content:1432 state:start') print 'doing YP' def RP_known_response_FJ(b_unit_task='unit_task:RP state:running', b_focus='YP', b_method='state:finished'): b_focus.set('FJ') b_method.set('method:known_response target:response content:3214 state:start') print 'doing FJ' def RP_finished1(b_unit_task='unit_task:RP state:running', b_focus='FJ', b_method='state:finished'): b_focus.set('none') b_unit_task.modify(state='end') ## this line ends the unit task print ' - finished unit task' def RP_got_code2(b_unit_task='unit_task:RP state:running', b_focus='unkown_code', b_method='state:finished', b_vision='ZB'): b_focus.set('ZB') b_method.set('method:known_response target:response content:1432 state:start') print 'doing ZB' def RP_known_response_WM(b_unit_task='unit_task:RP state:running', b_focus='ZB', b_method='state:finished'): b_focus.set('WM') b_method.set('method:known_response target:response content:2143 state:start') print 'doing WM' def RP_finished2(b_unit_task='unit_task:Y state:running', b_focus='WM', b_method='state:finished'): b_focus.set('none') b_unit_task.modify(state='end') ## this line ends the unit task b_unit_task.modify(state='stop') ## this line ends the unit task print ' - finished unit task' ###################################################### methods ################################################################### ################################################################################################################################## # known response method ######################### # the response is passed down by the production that called this method def known_response_vision(b_method='method:known_response target:?target content:?content state:start'): # target is the chunk to be altered motor.change_state_fast(target, content) b_method.modify(state='running') print 'entering response' print 'target object = ', target def response_entered(b_method='method:?method target:?target state:running', motor_finst='state:change_state_fast'): b_method.modify(state='finished') motor.motor_finst_reset() print 'I have altered - ', target # get_code method ################################ # in the case where the next response depends on the code the agent must first read the code def get_code(b_method='method:get_code target:?target content:?content state:start'): # target is the chunk to be altered motor.vision_slow() b_method.modify(state='running') print 'getting code' def get_code_finished(motor_finst='state:vision_slow', b_vision='?code'): motor.motor_finst_reset() b_method.modify(state='finished') print 'I have spotted the target, I have the new code' print code ############## run model ############# jim = Environment_Manager() tim = MyAgent() # name the agent subway = MyEnvironment() # name the environment subway.agent = tim # put the agent in the environment subway.agent = jim # put the agent in the environment ccm.log_everything(subway) # print out what happens in the environment subway.run() # run the environment ccm.finished() # stop the environment
[ "noreply@github.com" ]
noreply@github.com
5bec3ae23b68e6c2e0be46181e3e6e1f669fcd98
7518d339026e523ca99e77b7b49edfe71b7da5c5
/main.py
8b72a3d7569f8ca47bb5852ececdb44cac03e96b
[]
no_license
SP185221/FileAgent_Client
475c76ed2ab3a705b8643708f3e24f629661b57b
188d4d509c2d127afed8736d26b74805284e4b70
refs/heads/main
2023-07-25T08:03:22.780456
2021-09-02T16:18:01
2021-09-02T16:18:01
402,486,328
0
0
null
null
null
null
UTF-8
Python
false
false
6,751
py
import socket, tqdm from tkinter import* from threading import Thread from tkinter import filedialog import requests import wget, os from PIL import Image from time import sleep from zipfile import ZipFile #import pm_app_fxn as pm output1 = ['']*1 list_of_sent_files = [] class main_App(Thread): def __init__(self): Thread.__init__(self) def browse_button(self): filename = filedialog.askdirectory() #self.filename1[0]=filename #print(filename) temp = self.entry_path.get() #print(temp) self.entry_path.delete('0', 'end') self.entry_path.insert(0,filename) return filename def output(self, value): #value = sample_text.get(1.0, "end-1c") self.output_data.insert(END, value) def output_screen(self): #value = sample_text.get(1.0, "end-1c") value = output1[0] self.output(value) #self.entry_2.insert(1.0, value+'\n') def connect(self): filename = self.filename1[0] to_be_excute = "jpg_to_pdf" #ch = ConvertHandler( filename, to_be_excute ) #ch.start() def execute_handler(self): path = self.entry_path.get() server_ip = self.server_ip.get() server_port = self.server_port.get() interval = self.entry_interval.get() fh = file_handler(path,server_ip, server_port,interval ) fh.start() def run(self): self.filename1 = ['']*1 self.data1 = ['']*1 self.root = Tk() #self.entry_0 = Text(self.root, height = 10, width = 250) self.entry_path = Entry(self.root, width=55) #self.entry_2 = Text(self.root, height = 10, width = 250) #self.root = Tk() self.root.geometry('900x500') self.root.title("File Agent - Send your files to specified server") # Server IP Label(self.root, text = "Server IP:").place(x = 100, y = 50) self.server_ip = Entry(self.root, width=20) self.server_ip.place(x=170,y=50) self.server_ip.insert(0, "192.168.1.109") # Port Number Label(self.root, text = "Port No: ").place(x = 100, y = 100) self.server_port = Entry(self.root, width=20) self.server_port.place(x=170,y=100) self.server_port.insert(0, "5003") #Connect Button Button(self.root, text='Connect',command = self.connect, height = 4, width=64,bg='Green',fg='white').place(x=350,y=50) # File path selector #Button(self.root, text='Choose path of folder where file available',command = self.browse_button, width=35,bg='brown',fg='white').place(x=90,y=150) self.entry_path = Entry(self.root, width=55) self.entry_path.place(x=350,y=150) #Default self.entry_path.insert(0, "Select Folder path") Label(self.root, text = "Interval: ").place(x=690,y=150) self.entry_interval = Entry(self.root, width=10 ) #Default value self.entry_interval.insert(0, " 5") self.entry_interval.place(x=740,y=150) Button(self.root, text='Choose path of folder where file available',command = self.browse_button, width=35,bg='brown',fg='white').place(x=90,y=150) # Action using button Button(self.root, text='Execute',command = self.execute_handler, height = 3, width=47,bg='blue',fg='white').place(x=90,y=200) #Button(self.root, text='Merge PDF',command = self.merge_pdf, width=20,bg='green',fg='white').place(x=280,y=290) #Button(self.root, text='SPLIT PDF',command = self.split_pdf, width=20,bg='green',fg='white').place(x=470,y=290) Button(self.root, text='EXIT ',command = self.root.quit, height = 3, width=47,bg='red',fg='white').place(x=470,y=200) # Display Logs # Action to download self.output_data = Text(self.root, height = 8, width = 90) self.output_data.place(x=90,y=280) self.root.mainloop() print("\nProgram Exit") class file_handler(Thread): def __init__(self, path, server_ip, server_port, interval ): Thread.__init__(self) self.path = path self.server_ip = server_ip self.server_port = int(server_port) self.interval = int(interval) def run(self): list_of_current_files = os.listdir(self.path) #print(list_of_current_files) #print(self.server_ip) #print(self.server_port) #print(self.interval) remaining_files = list(set(list_of_current_files) - set(list_of_sent_files)) for file in remaining_files: file_path = self.path+'/'+file #print(file_path) list_of_sent_files.append(file) ft = FileTransfer(file_path,self.server_ip, self.server_port ) ft.start() ft.join() sleep(10) #self.run() class FileTransfer(Thread): def __init__(self, path, server_ip, server_port): Thread.__init__(self) self.host = server_ip self.port = server_port self.filename = path def run(self): SEPARATOR = "<SEPARATOR>" BUFFER_SIZE = 4096 # send 4096 bytes each time step host = self.host port = int(self.port) filename = self.filename fl = filename.split('/') sp = '\\' filename = sp.join(fl) #print(filename,'\n') #host = "192.168.1.109" # Server address #port = 5003 # Server port #filename = "Wall-Paper.jpeg" # File to be send filesize = os.path.getsize(filename) s = socket.socket() print(f"[+] Connecting to {host}:{port}") s.connect((host, port)) print("[+] Connected.") # send the filename and filesize s.send(f"{filename}{SEPARATOR}{filesize}".encode()) # start sending the file progress = tqdm.tqdm(range(filesize), f"Sending {filename}", unit="B", unit_scale=True, unit_divisor=1024) output1[0] = f"Sending {filename}" main_App.output(client,f"Sending {filename}") with open(filename, "rb") as f: for _ in progress: # read the bytes from the file bytes_read = f.read(BUFFER_SIZE) if not bytes_read: # file transmitting is done break # we use sendall to assure transimission in # busy networks s.sendall(bytes_read) # update the progress bar progress.update(len(bytes_read)) s.close() sleep(3) #output1[0] = f"Sending {filename}" main_App.output(client," - completed\n") client = main_App() client.start()
[ "noreply@github.com" ]
noreply@github.com
78bdca14128518d133ddf2e80c557c7d2e26fd7f
933493356546a769dda5c67f0a89eed9c970afa8
/ch6/q57.py
e42bbe6997419cc37dcd0703bfc6f51610b9fcca
[]
no_license
irtfrm/NLP100
233aa3b76d14dd89fe1d8f6d2e204ca3566bd5f5
ee0acedf7d2b00fe23f457120313d621fd1f098f
refs/heads/master
2021-08-06T09:47:38.238306
2020-06-05T08:18:08
2020-06-05T08:18:08
184,555,295
0
0
null
null
null
null
UTF-8
Python
false
false
925
py
import xml.etree.ElementTree as ET def gets_dot(tokens, deps): ans = 'digraph {\n' ans += ' token%s [label="%s"];\n' % (0, 'ROOT') for token in tokens: ans += ' token%s [shape=box, label="%s"];\n' % (token['id'], token['word']) for dep in deps: ans += ' token%s -> token%s;\n' % (dep['governor'], dep['dependent']) ans += '}\n' return ans with open('nlp.txt.xml', 'r') as f: lines = ''.join(f.readlines()) root = ET.fromstring(lines) tokens = [] deps = [] for sentence in root.findall('./document/sentences/sentence'): lst = [] for token in sentence[0]: lst.append({ 'id' : int(token.attrib['id']), 'word' : token[0].text }) tokens.append(lst) lst = [] for dep in sentence[2]: lst.append({ 'governor' : int(dep[0].attrib['idx']), 'dependent' : int(dep[1].attrib['idx']), }) deps.append(lst) i = 0 print(gets_dot(tokens[i], deps[i]))
[ "furukawa.tomoya@g.mbox.nagoya-u.ac.jp" ]
furukawa.tomoya@g.mbox.nagoya-u.ac.jp
0c3d4e6d095391de301cf46bf58d774a8b2830a2
3a12b346c87b05dac63951b3bc9cdd882d5ec9ed
/com/huai/learning/customLoss.py
5fe805bc9a0714a658b8ffb5710a0f4cfedfc37e
[]
no_license
namebxl/my_tensorflow
96005d656d33cdb5a8c4a54380adbff5ba697d6f
43e7ccdc94125b125476747b1897795171ad4358
refs/heads/master
2021-06-30T02:51:26.574885
2021-01-20T08:05:51
2021-01-20T08:05:51
213,275,207
0
0
null
2019-10-07T01:52:24
2019-10-07T01:52:24
null
UTF-8
Python
false
false
1,002
py
import tensorflow as tf from numpy.random import RandomState batch_size = 8; x = tf.placeholder(tf.float32, shape=(None, 2), name="x-input") y_ = tf.placeholder(tf.float32, shape=(None, 1), name="y-input") w1 = tf.Variable(tf.random_normal([2, 1], stddev=1, seed=1)); y = tf.matmul(x, w1); loss_less = 10; loss_more = 1; loss = tf.reduce_sum(tf.where(tf.greater(y, y_), (y - y_)*loss_more, (y_-y)*loss_less)); train_step = tf.train.AdamOptimizer(0.001).minimize(loss); rdm = RandomState(1); dataset_size = 128; X = rdm.rand(dataset_size, 2); Y = [[x1 + x2 + rdm.rand()/10.0 - 0.05] for (x1, x2) in X]; with tf.Session() as sess: init_op = tf.initialize_all_variables(); sess.run(init_op); STEPS = 5000; for i in range(STEPS): start = (i * batch_size)%dataset_size; end = min(start + batch_size, dataset_size); sess.run(train_step, feed_dict={x: X[start: end], y_:Y[start: end]}) print(sess.run(w1));
[ "1757153156@qq.com" ]
1757153156@qq.com
4345a2c669d02154dade74de723eb3affdd3c2a8
07252bc9ce0ba693e8c3cd0ad969ab7e9f336083
/apps/posts/forms.py
d2e808cc4daa9f7550ad748f64978972f26c3e4b
[]
no_license
Bakal1990/project
9f038ae2f821e737ae3cd39e3c4d1efcf8db90e1
3673c621383f8366572b083be203f49074eba55e
refs/heads/master
2020-12-25T19:26:10.888707
2015-02-16T19:31:09
2015-02-16T19:31:09
30,318,392
0
0
null
null
null
null
UTF-8
Python
false
false
455
py
from django import forms from .models import Post from profiles.models import User class LikePostForm(forms.Form): post_id = forms.CharField() user_id = forms.CharField() def clean_post_id(self): post_id = self.cleaned_data.get('post_id') return Post.objects.filter(id=post_id).exists() def clean_user_id(self): user_id = self.cleaned_data.get('user_id') return User.objects.filter(id=user_id).exists()
[ "molotovxiii@gmail.com" ]
molotovxiii@gmail.com
4b9670f8ab0b81af5668d3c702c93f533e2797c4
48581671e6fe9f59633aa9527c07d2724783a45c
/backend/Sunshine/api/urls.py
13f6022e5be3c9148cab22057ca78eec281224c2
[]
no_license
suma2001/SeniorSunshine
14fdcf22877c30d3f81d0f159c3b91df91e5bc44
54274d3b2f1a87fcb8926313a32bc4234fe48572
refs/heads/master
2023-02-03T03:24:26.871423
2020-12-11T14:08:02
2020-12-11T14:08:02
320,590,319
0
0
null
null
null
null
UTF-8
Python
false
false
1,661
py
from django.urls import path from .views import * from rest_framework.urlpatterns import format_suffix_patterns from rest_framework.authtoken import views from knox import views as knox_views urlpatterns = [ path('register/', RegisterAPI.as_view(), name='register'), path('login/', LoginAPI.as_view(), name='login'), path('logout/', LogoutAPI.as_view(), name='logout'), path('logoutall/', knox_views.LogoutAllView.as_view(), name='knox_logoutall'), path('elderregister/', RegisterElderAPI.as_view(), name='elderregister'), path('elderlogin/', LoginElderAPI.as_view(), name='elderlogin'), path('currentuser/', current_user, name='current_user'), path('token/', views.obtain_auth_token, name='token'), path('services/', ServicesAPIView.as_view(), name ='get_post_services'), path('service/<int:id>/', ServicesDetailsView.as_view(), name='get_delete_update_service'), # path('profiles/', ProfileAPIView.as_view()), # path('profile/<int:id>/', ProfileDetailsView.as_view()), path('elders/',ElderListView.as_view(),name ='get_post_elder_profiles'), path('elder/<int:id>/',ElderDetailView.as_view(),name ='get_delete_update_elder_profile'), path('requestservice/',RequestServiceAPIView.as_view(),name ='get_post_service'), path('feedback/',FeedbackSubmitAPIView.as_view(),name ='get_post_feedback'), path('test_volunteers/',TestVolunteerView.as_view(), name ='get_post_profiles'), path('test_volunteer/<int:id>/',TestVolunteerDetailView.as_view(),name='get_delete_update_profile'), path('custom_users/',UsersAPIView.as_view()), path('volunteers/<int:id>/',GetVolunteers.as_view()) ]
[ "sumashreya.t18@iiits.in" ]
sumashreya.t18@iiits.in
24966601f3f870f304dc6d67df48fa497d89c512
46d04bd3a1f8d53b147133b4b7a8c0c4fa58d9cd
/app/views.py
2b2d2323ce93f7cddcf6e68625ba576e2bd2e6e0
[]
no_license
RitikaSethiya/TB-strategic-planning-Web-App
f2c63d97413d1c384b591948cf812ac8dcf071c1
be1b9b3f5d510696cd8a76160426977032d27ed1
refs/heads/master
2022-08-13T19:10:01.334557
2020-05-11T11:59:40
2020-05-11T11:59:40
263,017,987
2
0
null
null
null
null
UTF-8
Python
false
false
28,346
py
# -*- encoding: utf-8 -*- """ License: MIT Copyright (c) 2019 - present AppSeed.us """ # Python modules import os, logging import pandas as pd import numpy as np import requests import base64 import pickle import json import tablib # Flask modules from flask import render_template, request, url_for, redirect, send_from_directory from flask_login import login_user, logout_user, current_user, login_required from werkzeug.exceptions import HTTPException, NotFound, abort from flask import jsonify # App modules from app import app, lm, db, bc from app.models import User from app.forms import LoginForm, RegisterForm # dataset = tablib.Dataset() # with open(os.path.join(os.path.dirname(__file__),'rotated_prediction.csv')) as f: # dataset.csv = f.read() @app.route("/table.html") def table(): data = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\rotated_prediction.csv") # data = "/dataset.html" #return dataset.html return render_template('pages/table.html', dataa=data) #provide login manager with load_user callback @lm.user_loader def load_user(user_id): return User.query.get(int(user_id)) # Logout user @app.route('/logout.html') def logout(): logout_user() return redirect(url_for('index')) # Register a new user @app.route('/register.html', methods=['GET', 'POST']) def register(): # declare the Registration Form form = RegisterForm(request.form) msg = None if request.method == 'GET': return render_template( 'pages/register.html', form=form, msg=msg ) # check if both http method is POST and form is valid on submit if form.validate_on_submit(): # assign form data to variables username = request.form.get('username', '', type=str) password = request.form.get('password', '', type=str) email = request.form.get('email' , '', type=str) # filter User out of database through username user = User.query.filter_by(user=username).first() # filter User out of database through username user_by_email = User.query.filter_by(email=email).first() if user or user_by_email: msg = 'Error: User exists!' else: pw_hash = password #bc.generate_password_hash(password) user = User(username, email, pw_hash) user.save() msg = 'User created, please <a href="' + url_for('login') + '">login</a>' else: msg = 'Input error' return render_template( 'pages/register.html', form=form, msg=msg ) # Authenticate user @app.route('/login.html', methods=['GET', 'POST']) def login(): # Declare the login form form = LoginForm(request.form) # Flask message injected into the page, in case of any errors msg = None # check if both http method is POST and form is valid on submit if form.validate_on_submit(): # assign form data to variables username = request.form.get('username', '', type=str) password = request.form.get('password', '', type=str) # filter User out of database through username user = User.query.filter_by(user=username).first() if user: #if bc.check_password_hash(user.password, password): if user.password == password: login_user(user) return redirect(url_for('index')) else: msg = "Wrong password. Please try again." else: msg = "Unknown user" return render_template( 'pages/login.html', form=form, msg=msg ) # App main route + generic routing @app.route('/', defaults={'path': 'index.html'}) @app.route('/<path>') def index(path): if not current_user.is_authenticated: return redirect(url_for('login')) content = None try: # @WIP to fix this # Temporary solution to solve the dependencies if path.endswith(('.png', '.svg' '.ttf', '.xml', '.ico', '.woff', '.woff2')): return send_from_directory(os.path.join(app.root_path, 'static'), path) # try to match the pages defined in -> pages/<input file> return render_template( 'pages/'+path ) except: return render_template('layouts/auth-default.html', content=render_template( 'pages/404.html' ) ) @app.route('/charts', methods=['GET']) def map(): district = request.args.get('name') df = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\tb_full.csv") xold=df[df["Location"]==district] x_axis = xold['Year'] y_axis= xold['total_cases'] name=df['Location'].unique() rate=y_axis.pct_change() rate=round(rate.fillna(value=0),4) rate=rate.replace(np.inf, 0) line_labelsold=round(x_axis,2) line_valuesold=round(y_axis,2) smear=xold["smear"] data_points_0 = zip(line_labelsold,line_valuesold,smear,rate) df1=pd.concat([x_axis,rate],axis=1) df1.columns=['Year','Total Cases Spread rate'] df1.reset_index(drop=True, inplace=True) path=r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\templates\pages\\"+district+".csv" df1.to_csv(path) return render_template('pages/charts.html', title=district,my_list=data_points_0) @app.route('/graphs', methods=['GET','POST']) def value(): district = request.args.get('name') if request.method == 'POST': so = request.form.get('so') no = request.form.get('no') rspmm = request.form.get('rspm') rainfall = request.form.get('rainfall') temperature = request.form.get('temperature') humidity = request.form.get('humidity') loc=district no2=no so2=so rspm=rspmm print(loc,no2,so2,rspm,rainfall,temperature,humidity) data={'loc':loc,'rspm':int(rspm),'no2':int(no2),'so2':int(so2),'rainfall':int(rainfall),'temperature':int(temperature),'humidity':int(humidity)} response = requests.post('https://beprojectdm.pythonanywhere.com/dm',data=json.dumps(data)).json() df1=pickle.loads(base64.b64decode(response['prediction'].encode())) df2=pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\tb_yearly.csv") dff=df2.append(df1) dff.to_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\prediction2.csv") x=dff[dff["Location"]==loc] x_axis = x['Year'] y_axis= x['total_cases'] smearnew=x["smear"] ratenew=y_axis.pct_change() ratenew=round(ratenew.fillna(value=0),4) ratenew=ratenew.replace(np.inf, 0) name=dff['Location'].unique() line_labelsnew=round(x_axis,2) line_valuesnew=round(y_axis,2) data_points_1 = zip(line_labelsnew,line_valuesnew,smearnew,ratenew) df3=pd.concat([x_axis,ratenew],axis=1) df3.columns=['Year','Total Cases Spread rate'] df3.reset_index(drop=True, inplace=True) path=r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\templates\pages\\"+district+"_retrain.csv" df3.to_csv(path) # df1 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\predicted.csv") df = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\tb_full.csv") xold=df[df["Location"]==district] x_axis = xold['Year'] y_axis= xold['total_cases'] rateold=y_axis.pct_change() rateold=round(rateold.fillna(value=0),4) rateold=rateold.replace(np.inf, 0) name=df['Location'].unique() line_labelsold=round(x_axis,2) line_valuesold=round(y_axis,2) smearold=xold["smear"] data_points_0 = zip(line_labelsold,line_valuesold,smearold,rateold) return render_template('pages/graphs.html', title=district,my_list=data_points_0,my_list_1=data_points_1,rainfall=rainfall,temperature=temperature,humidity=humidity) @app.route('/triple', methods=['POST']) def triple(): district = request.args.get('name') if request.method == 'POST': so = request.values.get('so') no = request.values.get('no') rspmm = request.values.get('rspm') rainfall = request.values.get('rainfall') temperature = request.values.get('temperature') humidity = request.values.get('humidity') loc=district no2=no so2=so rspm=rspmm data={'loc':loc,'rspm':int(rspm),'no2':int(no2),'so2':int(so2),'rainfall':int(rainfall),'temperature':int(temperature),'humidity':int(humidity)} response = requests.post('https://beprojectdm.pythonanywhere.com/dm',data=json.dumps(data)).json() df1=pickle.loads(base64.b64decode(response['prediction'].encode())) df2=pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\tb_yearly.csv") dff=df2.append(df1) x=dff[dff["Location"]==loc] x_axis = x['Year'] y_axis= x['total_cases'] smearnew=x["smear"] ratenew=y_axis.pct_change() ratenew=round(ratenew.fillna(value=0),4) ratenew=ratenew.replace(np.inf, 0) name=dff['Location'].unique() line_labelsnew=round(x_axis,2) line_valuesnew=round(y_axis,2) data_points_2 = zip(line_labelsnew,line_valuesnew,smearnew,ratenew) df3=pd.concat([x_axis,ratenew],axis=1) df3.columns=['Year','Total Cases Spread rate'] df3.reset_index(drop=True, inplace=True) path=r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\templates\pages\\"+district+"_retrain.csv" df3.to_csv(path) # df1 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\predicted.csv") df = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\tb_full.csv") xold=df[df["Location"]==district] x_axis = xold['Year'] y_axis= xold['total_cases'] rateold=y_axis.pct_change() rateold=round(rateold.fillna(value=0),4) rateold=rateold.replace(np.inf, 0) name=df['Location'].unique() line_labelsold=round(x_axis,2) line_valuesold=round(y_axis,2) smearold=xold["smear"] data_points_0 = zip(line_labelsold,line_valuesold,smearold,rateold) dff=pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\prediction2.csv") x=dff[dff["Location"]==loc] x_axis = x['Year'] y_axis= x['total_cases'] smearneww=x["smear"] rateneww=y_axis.pct_change() rateneww=round(rateneww.fillna(value=0),4) rateneww=rateneww.replace(np.inf, 0) name=dff['Location'].unique() line_labelsneww=round(x_axis,2) line_valuesneww=round(y_axis,2) data_points_1 = zip(line_labelsneww,line_valuesneww,smearneww,rateneww) return render_template('pages/triple.html', title=district,my_list=data_points_0,my_list_1=data_points_1,my_list_2=data_points_2) @app.route('/bar', methods=['GET']) def bar(): df = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\india_all_sum.csv") x_axis = df['Year'] y_axis= df['total_cases'] z_axis= df['smear'] data_points = zip(x_axis,y_axis) data_points_smear = zip(x_axis,z_axis) #,smear,ratey,ratez return render_template('pages/bar.html', list=list(data_points),lists=list(data_points_smear)) @app.route('/india_line', methods=['GET']) def line(): df = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\india_all_sum.csv") x_axis = df['Year'] y_axis= df['total_cases'] rate=y_axis.pct_change() rate=round(rate.fillna(value=0),4) line_labelsold=round(x_axis,2) line_valuesold=round(y_axis,2) smear=round(df["smear"],2) data_points_0 = zip(line_labelsold,line_valuesold,smear,rate) return render_template('pages/india_linechart.html',my_list=data_points_0) @app.route('/stats.html', methods=['GET']) def stats(): df1 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_test_totalcases.csv") df2 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_test_smearpositivecases.csv") df3 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_train_totalcases.csv") df4 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_train_smearpositivecases.csv") gbr_1=df3['gbr'] gbr_2=df1['gbr'] gbr_3=df4['gbr'] gbr_4=df2['gbr'] #,smear,ratey,ratez return render_template('pages/stats.html',train_total=gbr_1,test_total=gbr_2,train_smear=gbr_3,test_smear=gbr_4 ) @app.route('/model2.html', methods=['GET']) def model2(): df1 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_test_totalcases.csv") df2 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_test_smearpositivecases.csv") df3 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_train_totalcases.csv") df4 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_train_smearpositivecases.csv") rfr_1=df3['rfr'] rfr_2=df1['rfr'] rfr_3=df4['rfr'] rfr_4=df2['rfr'] #,smear,ratey,ratez return render_template('pages/model2.html',train_total=rfr_1,test_total=rfr_2,train_smear=rfr_3,test_smear=rfr_4 ) @app.route('/model3.html', methods=['GET']) def model3(): df1 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_test_totalcases.csv") df2 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_test_smearpositivecases.csv") df3 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_train_totalcases.csv") df4 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_train_smearpositivecases.csv") dtr_1=df3['dtr'] dtr_2=df1['dtr'] dtr_3=df4['dtr'] dtr_4=df2['dtr'] #,smear,ratey,ratez return render_template('pages/model3.html',train_total=dtr_1,test_total=dtr_2,train_smear=dtr_3,test_smear=dtr_4 ) @app.route('/model4.html', methods=['GET']) def model4(): df1 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_test_totalcases.csv") df2 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_test_smearpositivecases.csv") df3 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_train_totalcases.csv") df4 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_train_smearpositivecases.csv") xgbr_1=df3['xgbr'] xgbr_2=df1['xgbr'] xgbr_3=df4['xgbr'] xgbr_4=df2['xgbr'] #,smear,ratey,ratez return render_template('pages/model4.html',train_total=xgbr_1,test_total=xgbr_2,train_smear=xgbr_3,test_smear=xgbr_4 ) @app.route('/model5.html', methods=['GET']) def model5(): df1 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_test_totalcases.csv") df2 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_test_smearpositivecases.csv") df3 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_train_totalcases.csv") df4 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_train_smearpositivecases.csv") nn_1=df3['nn'] nn_2=df1['nn'] nn_3=df4['nn'] nn_4=df2['nn'] #,smear,ratey,ratez return render_template('pages/model5.html',train_total=nn_1,test_total=nn_2,train_smear=nn_3,test_smear=nn_4 ) @app.route('/correlation.html', methods=['POST']) def corr1(): if request.method =='POST': if request.args.get('list')!=None: value=request.args.get('value_change') col_head=request.args.get('id') selected_list=request.args.get('list') print('value',value,'col_head',col_head,'selected_list',selected_list) df=pd.read_csv(r'C:/Users/Ritika/AppData/Local/Programs/Python/Python37/DMWebapp/app/combinations.csv') df=df.iloc[:,[0,1,2,3,4,5,6,7]] if(col_head=='year' or col_head=='quarter'): value=int(value) df1=df[df[col_head]==value] rspmmm=df1['rspm'].unique().tolist() nooo2=df1['no2'].unique().tolist() sooo2=df1['so2'].unique().tolist() rainfallll=df1['rainfall'].unique().tolist() humidityyy=df1['humidity'].unique().tolist() temperaturee=df1['temperature'].unique().tolist() yearrr=df1['year'].unique().tolist() quarterrr=df1['quarter'].unique().tolist() yearrr.sort() quarterrr.sort() print(rspmmm) # return render_template('pages/correlation.html',rspmmm=rspmmm,nooo2=nooo2,sooo2=sooo2,rainfallll=rainfallll,humidityyy=humidityyy,temperaturee=temperaturee,yearrr=yearrr,quarterrr=quarterrr,selected_list=selected_list) final_list={'rspm':rspmmm,'no2':nooo2,'so2':sooo2,'rainfall':rainfallll,'humidity':humidityyy,'temperature':temperaturee,'year':yearrr,'quarter':quarterrr,'selected_list':selected_list} return jsonify(final_list) elif request.values.get('rspm')!=None: print("hello") rspm = request.values.get('rspm') no2 = request.values.get('no2') so2 = request.values.get('so2') year = request.values.get('year') rainfall = request.values.get('rainfall') temperature = request.values.get('temperature') humidity = request.values.get('humidity') quarter = request.values.get('quarter') year=int(year) quarter=int(quarter) print(rspm,so2,no2,year,rainfall,temperature,humidity,quarter) df=pd.read_csv(r'C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\correlation.csv') df.columns=['Location','Year','Quarter','totalcases','smearpositivecases','rainfall','humidity','temperature','so2','no2','rspm'] table=[] table.append(['rainfall_low','x','750']) table.append(['rainfall_moderate','751','2350']) table.append(['rainfall_high','2351','x']) table.append(['temperature_low','x','20']) table.append(['temperature_moderate','21','30']) table.append(['temperature_high','31','x']) table.append(['humidity_low','x','50']) table.append(['humidity_high','51','x']) table.append(['rspm_good','x','50']) table.append(['rspm_satisfactory','51','100']) table.append(['rspm_moderate','101','200']) table.append(['rspm_poor','201','300']) table.append(['rspm_severe','301','x']) table.append(['no2_safe','x','25']) table.append(['no2_potential','26','50']) table.append(['no2_curtailing','51','100']) table.append(['no2_hazardous','101','x']) table.append(['so2_safe','x','25']) table.append(['so2_potential','26','50']) table.append(['so2_curtailing','51','100']) ranges=pd.DataFrame(table,columns=['category','low','high']) try: df1=df[df['Year']==year] df2=df1[df1['Quarter']==quarter] rspm1=ranges[ranges['category']==rspm].iloc[0,:] if(str(rspm1['low'])=='x'): df3=df2[df2['rspm']<=int(rspm1['high'])] elif(str(rspm1['high'])=='x'): df3=df2[df2['rspm']>=int(rspm1['low'])] else: df3=df2[df2['rspm'].between(int(rspm1['low']),int(rspm1['high']),inclusive=True)] # In[71]: so21=ranges[ranges['category']==so2].iloc[0,:] if(str(so21['low'])=='x'): df4=df3[df3['so2']<=int(so21['high'])] elif(str(so21['high'])=='x'): df4=df3[df3['so2']>=int(so21['low'])] else: df4=df3[df3['so2'].between(int(so21['low']),int(so21['high']),inclusive=True)] # In[72]: no21=ranges[ranges['category']==no2].iloc[0,:] if(str(no21['low'])=='x'): df5=df4[df4['no2']<=int(no21['high'])] elif(str(no21['high'])=='x'): df5=df4[df4['no2']>=int(no21['low'])] else: df5=df4[df4['no2'].between(int(no21['low']),int(no21['high']),inclusive=True)] # In[73]: humidity1=ranges[ranges['category']==humidity].iloc[0,:] if(str(humidity1['low'])=='x'): df6=df5[df5['humidity']<=int(humidity1['high'])] elif(str(humidity1['high'])=='x'): df6=df5[df5['humidity']>=int(humidity1['low'])] else: df6=df5[df5['humidity'].between(int(humidity1['low']),int(humidity1['high']),inclusive=True)] # In[74]: rainfall1=ranges[ranges['category']==rainfall].iloc[0,:] if(str(rainfall1['low'])=='x'): df7=df6[df6['rainfall']<=int(rainfall1['high'])] elif(str(rainfall1['high'])=='x'): df7=df6[df6['rainfall']>=int(rainfall1['low'])] else: df7=df6[df6['rainfall'].between(int(rainfall1['low']),int(rainfall1['high']),inclusive=True)] # In[75]: temperature1=ranges[ranges['category']==temperature].iloc[0,:] if(str(temperature1['low'])=='x'): df8=df7[df7['temperature']<=int(temperature1['high'])] elif(str(temperature1['high'])=='x'): df8=df7[df7['temperature']>=int(temperature1['low'])] else: df8=df7[df7['temperature'].between(int(temperature1['low']),int(temperature1['high']),inclusive=True)] df9=df8.iloc[:,[0,3,4]] l=[x for x in df9["Location"]] print(l) if not l: l=['-1'] return render_template('pages/correlation.html',list1=l,year=year,quarter=quarter,rainfall=rainfall,temperature=temperature,humidity=humidity,rspm=rspm,so2=so2,no2=no2) except: return ['-1'] # return Error return render_template('pages/correlation.html') # @app.route('/correlation', methods=['POST']) # def corr2(): # if request.method == 'POST' and # return render_template('pages/correlation.html') @app.route('/pie', methods=['GET']) def pie(): year=request.args.get('year') quarter=request.args.get('quarter') rspm=request.args.get('rspm') so2=request.args.get('so2') no2=request.args.get('no2') rainfall=request.args.get('rainfall') temperature=request.args.get('temperature') humidity=request.args.get('humidity') year=int(year) quarter=int(quarter) print(rspm,so2,no2,year,rainfall,temperature,humidity,quarter) df=pd.read_csv(r'C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\correlation.csv') df.columns=['Location','Year','Quarter','totalcases','smearpositivecases','rainfall','humidity','temperature','so2','no2','rspm'] table=[] table.append(['rainfall_low','x','750']) table.append(['rainfall_moderate','751','2350']) table.append(['rainfall_high','2351','x']) table.append(['temperature_low','x','20']) table.append(['temperature_moderate','21','30']) table.append(['temperature_high','31','x']) table.append(['humidity_low','x','50']) table.append(['humidity_high','51','x']) table.append(['rspm_good','x','50']) table.append(['rspm_satisfactory','51','100']) table.append(['rspm_moderate','101','200']) table.append(['rspm_poor','201','300']) table.append(['rspm_severe','301','x']) table.append(['no2_safe','x','25']) table.append(['no2_potential','26','50']) table.append(['no2_curtailing','51','100']) table.append(['no2_hazardous','101','x']) table.append(['so2_safe','x','25']) table.append(['so2_potential','26','50']) table.append(['so2_curtailing','51','100']) ranges=pd.DataFrame(table,columns=['category','low','high']) df1=df[df['Year']==year] df2=df1[df1['Quarter']==quarter] rspm1=ranges[ranges['category']==rspm].iloc[0,:] if(str(rspm1['low'])=='x'): df3=df2[df2['rspm']<=int(rspm1['high'])] elif(str(rspm1['high'])=='x'): df3=df2[df2['rspm']>=int(rspm1['low'])] else: df3=df2[df2['rspm'].between(int(rspm1['low']),int(rspm1['high']),inclusive=True)] # In[71]: so21=ranges[ranges['category']==so2].iloc[0,:] if(str(so21['low'])=='x'): df4=df3[df3['so2']<=int(so21['high'])] elif(str(so21['high'])=='x'): df4=df3[df3['so2']>=int(so21['low'])] else: df4=df3[df3['so2'].between(int(so21['low']),int(so21['high']),inclusive=True)] # In[72]: no21=ranges[ranges['category']==no2].iloc[0,:] if(str(no21['low'])=='x'): df5=df4[df4['no2']<=int(no21['high'])] elif(str(no21['high'])=='x'): df5=df4[df4['no2']>=int(no21['low'])] else: df5=df4[df4['no2'].between(int(no21['low']),int(no21['high']),inclusive=True)] # In[73]: humidity1=ranges[ranges['category']==humidity].iloc[0,:] if(str(humidity1['low'])=='x'): df6=df5[df5['humidity']<=int(humidity1['high'])] elif(str(humidity1['high'])=='x'): df6=df5[df5['humidity']>=int(humidity1['low'])] else: df6=df5[df5['humidity'].between(int(humidity1['low']),int(humidity1['high']),inclusive=True)] # In[74]: rainfall1=ranges[ranges['category']==rainfall].iloc[0,:] if(str(rainfall1['low'])=='x'): df7=df6[df6['rainfall']<=int(rainfall1['high'])] elif(str(rainfall1['high'])=='x'): df7=df6[df6['rainfall']>=int(rainfall1['low'])] else: df7=df6[df6['rainfall'].between(int(rainfall1['low']),int(rainfall1['high']),inclusive=True)] # In[75]: temperature1=ranges[ranges['category']==temperature].iloc[0,:] if(str(temperature1['low'])=='x'): df8=df7[df7['temperature']<=int(temperature1['high'])] elif(str(temperature1['high'])=='x'): df8=df7[df7['temperature']>=int(temperature1['low'])] else: df8=df7[df7['temperature'].between(int(temperature1['low']),int(temperature1['high']),inclusive=True)] dfff=df8.iloc[:,[0,3,4]] dft=[x for x in dfff["totalcases"]] dfl=[x for x in dfff["Location"]] dfs=[x for x in dfff["smearpositivecases"]] df9=list(zip(dft,dfl,dfs)) print(df9) return render_template('pages/pie.html',df=df9,rspm=rspm,so2=so2,no2=no2,rainfall=rainfall,temperature=temperature,humidity=humidity) @app.route('/pass_val', methods=['POST']) def pass_val(): value=request.args.get('value_change') col_head=request.args.get('id') selected_list=request.args.get('list') print('value',value,'col_head',col_head,'selected_list',selected_list) df=pd.read_csv(r'C:/Users/Ritika/AppData/Local/Programs/Python/Python37/DMWebapp/app/combinations.csv') df=df.iloc[:,[0,1,2,3,4,5,6,7]] if(col_head=='year' or col_head=='quarter'): value=int(value) df1=df[df[col_head]==value] rspmmm=df1['rspm'].unique().tolist() nooo2=df1['no2'].unique().tolist() sooo2=df1['so2'].unique().tolist() rainfallll=df1['rainfall'].unique().tolist() humidityyy=df1['humidity'].unique().tolist() temperaturee=df1['temperature'].unique().tolist() yearrr=df1['year'].unique().tolist() quarterrr=df1['quarter'].unique().tolist() yearrr.sort() quarterrr.sort() return jsonify({'reply':'success'})
[ "ritikasethiya99.rs@gmail.com" ]
ritikasethiya99.rs@gmail.com
b91cd725562befb469c66d4ce9802baecaa2cf54
e999577db526bdc87ab83d30d393e06f921c2326
/multiagent/multiAgents.py
2dab318ae711f77bae0c426c49a25673c4ad1a2c
[]
no_license
anant-k-singh/Pacman-AI
e4a630de420ad942fef8b0c5ab0d6799859c0737
503730f7baa5fac690cedcd6f65cc592bb7758c3
refs/heads/master
2022-01-22T18:23:32.347366
2019-07-31T17:24:26
2019-07-31T17:24:26
115,016,037
2
0
null
null
null
null
UTF-8
Python
false
false
14,272
py
# multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to http://ai.berkeley.edu. # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel (pabbeel@cs.berkeley.edu). from util import manhattanDistance from game import Directions import random, util, sys from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() legalMoves.remove('Stop') # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) # bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] # chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" for i in range(0,len(scores)): if(scores[i] == bestScore): return legalMoves[i] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" # for ghostState in newGhostStates: # print manhattanDistance(newPos, ghostState.getPosition()) # return successorGameState.getScore() foodlist = currentGameState.getFood().asList() distanceToClosestFood = min(map(lambda x: util.manhattanDistance(newPos, x), foodlist)) distanceToClosestGhost = manhattanDistance(newPos, newGhostStates[0].getPosition()) if distanceToClosestGhost == 0: return -50 # print int(-8/distanceToClosestGhost) return -(8/distanceToClosestGhost)-distanceToClosestFood def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gamestate): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" def pacman(gameState, curDepth): if gameState.isWin() or gameState.isLose(): return self.evaluationFunction(gameState) legalMoves = gameState.getLegalActions(0) score = [] for move in legalMoves: nextState = gameState.generateSuccessor(0, move) if nextState.isWin(): return self.evaluationFunction(nextState) score.append( ghost(nextState,curDepth,total_ghosts) ) # print score,"score for pacman @",curDepth return max(score) def ghost(gameState, curDepth, ghost_idx): if curDepth == self.depth or gameState.isWin() or gameState.isLose(): return self.evaluationFunction(gameState) legalMoves = gameState.getLegalActions(ghost_idx) score = [] # Pacman's turn if ghost_idx == 1: for move in legalMoves: nextState = gameState.generateSuccessor(ghost_idx, move) if nextState.isLose(): return self.evaluationFunction(nextState) score.append( pacman(nextState,curDepth+1) ) # next ghost's turn else: for move in legalMoves: nextState = gameState.generateSuccessor(ghost_idx, move) if nextState.isLose(): return self.evaluationFunction(nextState) score.append( ghost(nextState, curDepth, ghost_idx-1) ) # print score,"score for ghost",ghost_idx,"@",curDepth return min(score) bestScore = -9999 bestMove = 'Fail' total_ghosts = gamestate.getNumAgents()-1 legalMoves = gamestate.getLegalActions(0) for move in legalMoves: nextState = gamestate.generateSuccessor(0, move) # if it can win immediately if nextState.isWin(): return move tempScore = ghost(nextState, 1, total_ghosts) if tempScore > bestScore: bestScore = tempScore bestMove = move return bestMove class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gamestate): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" def pacman(gameState, curDepth,A,B): if gameState.isWin() or gameState.isLose(): return self.evaluationFunction(gameState) legalMoves = [action for action in gameState.getLegalActions(0) if action!='Stop'] score = -9999999 for move in legalMoves: nextState = gameState.generateSuccessor(0, move) if nextState.isWin(): return self.evaluationFunction(nextState) score = max(score, ghost(nextState,curDepth,total_ghosts,A,B)) if score > B: return score A = max(A,score) # print score,"score for pacman @",curDepth return score def ghost(gameState, curDepth, ghost_idx,A,B): if curDepth == self.depth or gameState.isWin() or gameState.isLose(): return self.evaluationFunction(gameState) legalMoves = gameState.getLegalActions(ghost_idx) score = 9999999 # Pacman's turn if ghost_idx == 1: for move in legalMoves: nextState = gameState.generateSuccessor(ghost_idx, move) if nextState.isLose(): return self.evaluationFunction(nextState) # score.append( pacman(nextState,curDepth+1) ) score = min(score, pacman(nextState,curDepth+1,A,B)) if score < A: return score B = min(B,score) # next ghost's turn else: for move in legalMoves: nextState = gameState.generateSuccessor(ghost_idx, move) if nextState.isLose(): return self.evaluationFunction(nextState) # score.append( ghost(nextState, curDepth, ghost_idx-1) ) score = min(score, ghost(nextState, curDepth, ghost_idx-1,A,B)) # print score,"score for ghost",ghost_idx,"@",curDepth return score bestScore = -99999999 bestMove = 'Fail' total_ghosts = gamestate.getNumAgents()-1 legalMoves = gamestate.getLegalActions(0) for move in legalMoves: nextState = gamestate.generateSuccessor(0, move) # if it can win immediately if nextState.isWin(): return move tempScore = ghost(nextState, 1, total_ghosts,-9999999,9999999) if tempScore > bestScore: bestScore = tempScore bestMove = move return bestMove class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gamestate): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" def pacman(gameState, curDepth): if gameState.isWin() or gameState.isLose(): return self.evaluationFunction(gameState) legalMoves = [action for action in gameState.getLegalActions(0) if action!='Stop'] score = [] for move in legalMoves: nextState = gameState.generateSuccessor(0, move) if nextState.isWin(): return self.evaluationFunction(nextState) score.append( ghost(nextState,curDepth,total_ghosts) ) # print score,"score for pacman @",curDepth return max(score) def ghost(gameState, curDepth, ghost_idx): if curDepth == self.depth or gameState.isWin() or gameState.isLose(): return self.evaluationFunction(gameState) legalMoves = gameState.getLegalActions(ghost_idx) score = 0 # Pacman's turn if ghost_idx == 1: for move in legalMoves: nextState = gameState.generateSuccessor(ghost_idx, move) if nextState.isLose(): return self.evaluationFunction(nextState) score += pacman(nextState,curDepth+1) # next ghost's turn else: for move in legalMoves: nextState = gameState.generateSuccessor(ghost_idx, move) if nextState.isLose(): return self.evaluationFunction(nextState) score += ghost(nextState, curDepth, ghost_idx-1) # print score,"score for ghost",ghost_idx,"@",curDepth return (score*1.0)/len(legalMoves) bestScore = -999999 bestMove = 'Fail' total_ghosts = gamestate.getNumAgents()-1 legalMoves = gamestate.getLegalActions(0) for move in legalMoves: nextState = gamestate.generateSuccessor(0, move) # if it can win immediately if nextState.isWin(): return move tempScore = ghost(nextState, 1, total_ghosts) if tempScore > bestScore: bestScore = tempScore bestMove = move return bestMove def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: Farther the nearest food higher the score """ "*** YOUR CODE HERE ***" pacmanPos = currentGameState.getPacmanPosition() foodlist = currentGameState.getFood().asList() distanceToClosestFood = min(map(lambda x: util.manhattanDistance(pacmanPos, x), foodlist)) return currentGameState.getScore()+distanceToClosestFood # Abbreviation better = betterEvaluationFunction
[ "anant02sep@gmail.com" ]
anant02sep@gmail.com
1cdb9ccb8eb20c40eb3ca82b06c082532bc3b005
db2e1604cdd45df402b93cd72b36e1995f0ded57
/baidu_baike/baidu_baike/middlewares.py
69c61f1ce3dc83c9f549186ad6a2fc5baa47e026
[]
no_license
JimyFengqi/baidubaike
9bd558bea58d728ef1d256aa9746978b058a138f
6bf6114494db485107f8869ed79ec70200ed26c2
refs/heads/master
2020-04-07T10:46:12.906874
2018-04-26T07:52:49
2018-04-26T07:52:49
124,205,144
2
0
null
null
null
null
UTF-8
Python
false
false
3,605
py
# -*- coding: utf-8 -*- # Define here the models for your spider middleware # # See documentation in: # https://doc.scrapy.org/en/latest/topics/spider-middleware.html from scrapy import signals class BaiduBaikeSpiderMiddleware(object): # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the spider middleware does not modify the # passed objects. @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_spider_input(self, response, spider): # Called for each response that goes through the spider # middleware and into the spider. # Should return None or raise an exception. return None def process_spider_output(self, response, result, spider): # Called with the results returned from the Spider, after # it has processed the response. # Must return an iterable of Request, dict or Item objects. for i in result: yield i def process_spider_exception(self, response, exception, spider): # Called when a spider or process_spider_input() method # (from other spider middleware) raises an exception. # Should return either None or an iterable of Response, dict # or Item objects. pass def process_start_requests(self, start_requests, spider): # Called with the start requests of the spider, and works # similarly to the process_spider_output() method, except # that it doesn’t have a response associated. # Must return only requests (not items). for r in start_requests: yield r def spider_opened(self, spider): spider.logger.info('Spider opened: %s' % spider.name) class BaiduBaikeDownloaderMiddleware(object): # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the downloader middleware does not modify the # passed objects. @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_request(self, request, spider): # Called for each request that goes through the downloader # middleware. # Must either: # - return None: continue processing this request # - or return a Response object # - or return a Request object # - or raise IgnoreRequest: process_exception() methods of # installed downloader middleware will be called return None def process_response(self, request, response, spider): # Called with the response returned from the downloader. # Must either; # - return a Response object # - return a Request object # - or raise IgnoreRequest return response def process_exception(self, request, exception, spider): # Called when a download handler or a process_request() # (from other downloader middleware) raises an exception. # Must either: # - return None: continue processing this exception # - return a Response object: stops process_exception() chain # - return a Request object: stops process_exception() chain pass def spider_opened(self, spider): spider.logger.info('Spider opened: %s' % spider.name)
[ "jmps515@163.com" ]
jmps515@163.com
43ded90cced3f1255adfe6cd098a2966f73fb180
42705b3049418c3dc2815a0262aa814c6a2e3d9e
/feat_eng/funcs.py
dcc248c03ab3520bd17e5e378f3b4fea24b3f0f4
[]
no_license
ppiont/cnn-soc-wagga
617f4a0fecd6ac0b7d6fac2cb7171df9bfbf74a2
5152faf59c38c4b168a1dc9639fa8d13c16a91cd
refs/heads/master
2023-07-11T09:01:08.786970
2021-08-14T12:17:09
2021-08-14T12:17:09
257,276,955
0
0
null
null
null
null
UTF-8
Python
false
false
2,506
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 30 18:32:01 2020. @author: peter """ import numpy as np def min_max(array, axis=(0, 1, 2), rm_no_variance=True): """Min-max scale an array and optionally remove features with no variance. Parameters ---------- array : ndarray Array to be scaled. axis : int or tuple of int, optional The axis or axes along which to scale. The default is (0, 1, 2). Returns ------- ndarray The scaled array. zero_channels_idx : ndarray, depending on `rm_no_variance` The idx of zero variance features/channels that were removed. """ # Compute the mins along the axis x_mins = array.min(axis=axis) # Compute the maxs along hte axis x_maxs = array.max(axis=axis) # Get the difference diff = x_maxs-x_mins if rm_no_variance is True: # Get index of features with no variance (max == min) zero_channels_idx = np.where(diff == 0)[0] # Remove features with no variance array = np.delete(array, zero_channels_idx, -1) diff = np.delete(diff, zero_channels_idx) x_maxs = np.delete(x_maxs, zero_channels_idx) x_mins = np.delete(x_mins, zero_channels_idx) print(f'Removed from axis: {zero_channels_idx}') # Compute and return the array normalized to 0-1 range and # optionally return zero variance indexes return (array-x_mins)/diff, zero_channels_idx else: return (array-x_mins)/diff def crop_center(arr, crop_x, crop_y): """Crop an array, maintaining center.""" if len(arr.shape) == 4 and arr.shape[0] == 1: arr = np.squeeze(arr) y, x, _ = arr.shape start_x = x//2 - crop_x//2 start_y = y//2 - crop_y//2 return arr[start_y:start_y + crop_y, start_x:start_x + crop_x, :] def get_corr_feats(X, min_corr=0.8): """Get indices of correlated features of an array.""" correlated_features = set() correlation_matrix = np.corrcoef(X, rowvar=False) for i in range(correlation_matrix.shape[-1]): for j in range(i): if abs(correlation_matrix[i, j]) > min_corr: correlated_features.add(i) return np.array(list(correlated_features)) def add_min(a): """Add abs(minimum) along whole 1-D array.""" return a + abs(a.min()) if a.min() < 0 else a def safe_log(x): """Apply log transform on all values except x <= 0s.""" x = np.ma.log(x) return x.filled(0)
[ "piontek0@gmail.com" ]
piontek0@gmail.com