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
5cfab9db402b8e67c21d32c6243a3daf5fc7270b
2f1dd60a4b9a4dbe13a8429baa402e49379a9c2f
/math_model/test/test.py
d6687dc173f9ef8c8c555fdd9ddb525d477d7abb
[]
no_license
lyz21/MachineLearning
b3de2e218050b7ec7d571367f9f455c6fdb4f4e9
3624b5bf4edf52125f91666ddf25fbf957c723ed
refs/heads/master
2022-11-11T12:07:06.336485
2020-07-01T15:39:34
2020-07-01T15:39:34
276,404,490
0
0
null
null
null
null
UTF-8
Python
false
false
153
py
# encoding=utf-8 """ @Time : 2020/6/21 20:07 @Author : LiuYanZhe @File : test.py @Software: PyCharm @Description: 一些基本不会复用的方法 """
[ "liuyenzhe@163.com" ]
liuyenzhe@163.com
93343708920188248d56b7182815d65a56fbde02
e77eef0040bf8158ff7734bb49336b32e99fb866
/PythonTrainee/Packages/getrequests.py
9061f6eb597276e36ad6f10e5906dcfbf86a075f
[]
no_license
xistadi/homework
c7bf34b873370c9bede8eb9752b3afcd4cc9a1b5
0a6ebf7c2b05d3f750f165f48dadadb14befcfef
refs/heads/main
2023-03-28T19:16:47.181381
2021-04-03T15:28:49
2021-04-03T15:28:49
294,196,272
0
0
null
null
null
null
UTF-8
Python
false
false
1,106
py
import requests from requests.exceptions import HTTPError class GetRequests: """Class for working with the requests library""" def __init__(self, url): self.url = url def get_response(self): """Get requests by url""" try: headers = {'User-Agent': 'Mozilla/5.0'} # use mozilla as a user agent response_from_requests = requests.get(self.url, headers=headers) # get requests by url response_from_requests.raise_for_status() except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') except Exception as err: print(f'Other error occurred: {err}') else: print('Success!') return response_from_requests def get_main_text(self, response_from_requests): """Get html pages by url""" main_text = response_from_requests.text # decode response return main_text if __name__ == "__main__": response = GetRequests('http://google.com').get_response() print(GetRequests('http://google.com').get_main_text(response))
[ "xistadi@gmail.com" ]
xistadi@gmail.com
7f453ee788ea3c55a8a31bf385c548409caa9c8b
e5c3772f5d70eb4eaba69261c0a6af9e522aad3c
/proj_euler/problems/p138.py
dcccfdca0e78b29913d4c56b43a3f29c5b2dd4a1
[]
no_license
ztalloC/ProjectEuler
60b1600150a2f7256b8eade83175bbbd0d98bf12
39d37ddd257c52f536bb6cfe3703eda4cd365f92
refs/heads/main
2021-05-31T00:03:29.025752
2016-04-01T03:43:39
2016-04-01T03:43:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,206
py
# -*- coding: utf-8 -*- """ Created on Fri Jan 22 21:24:24 2016 @author: mjcosta """ from itertools import islice from proj_euler.utils.timing import timefunc # Returns an infinite generator of solutions for the equation y^2 = 5L^2 - 1 # where solutions are returned in the format (L, y). def diophantine_solutions(): # Initial solution, 5*1^2 -1 = 2^2. x, y = (1, 2) yield (x, y) while True: # We can generate infinite solutions with a recurrence relation. # Coefficients generated from: https://www.alpertron.com.ar/QUAD.HTM x, y = (9*x + 4*y, 20*x + 9*y) yield (x, y) # Returns an infinite generator of special isoceles triangles in the form # (b, h, L). def generate_special_isoceles(): diop_sols = diophantine_solutions() # Skip the solution (0, 1, 1) next(diop_sols) for L, y in diop_sols: # Based on how solutions are generated, y can only be 2 or 3 mod 5, # which determines whether it is h = b + 1 or h = b - 1. sign = 1 if y % 5 == 2 else -1 b = (sign * -4 + 2 * y)/5 yield (b, b + sign, L) # Computes the sum of the first num smallest special isoceles triangles. @timefunc def solve_p138(num): return sum(x[2] for x in islice(generate_special_isoceles(), num)) """ Thoughts: This problem took a while for me to solve since it was mostly math based (the code was very short). The problem was finding special isoceles triangles where the height was within +/- 1 of the base. From this requirement, one can use the Pythagorean formula to have L^2 = b^2 + h^2 and then substitute h = b +/- 1 into the formula and solve. Solving the equation results in b = (-/+ 4 +/- sqrt(5L^2-1)), but since sqrt(5L^2-1) >= 4 (if L > 0), we can just consider b = (-/+ 4 + sqrt(5L^2-1)). Now we need to find values of 5L^2-1 that are equal to a perfect square. If you let y^2 = 5L^2 - 1, then y^2 - 5L^2 = -1, which is the negative Pell's equation. I did not feel like writing a solver, so after much searching online, I found "https://www.alpertron.com.ar/QUAD.HTM", which is a tool for solving quadratic Diophantine solutions (Pell's is a specific case) of the form ax^2 + bxy + cy^2 + dx + ey + f = 0 (where you plug in the constants a-f). The tool gave me some simple recurrences that I could use to generate infinite solutions from an initial solution (also given). I then just had to plug in the solutions to y^2 = 5L^2 - 1, and use some simple math to generate b and h. It was then just a matter of summing up the lengths of the triangles. The code is very short and efficient, taking only a few microseconds to run (my timing method is probably not accurate enough). After solving the problem, I looked at how other people solved it and it seems that the side length of the triangles are half of every 6th Fibonacci number starting from 9 (i.e. 9, 15, 21, ...). This is quite interesting, though it is not something I would have thought of unless I was very familiar with Fibonacci numbers. """ if __name__ == "__main__": # 307 + 15 = 322 print "Example (2 lowest) (expect 322):" print solve_p138(2) print "Problem (12 lowest):" print solve_p138(12)
[ "cosmic@seas.upenn.edu" ]
cosmic@seas.upenn.edu
ffb4543aa41b64b881c293934398b1479120481a
202d2685dabf67ac7a26d32b99cdf3e289691faa
/simpson_faster_rcnn/simpson.py
0f062ca8a49d434f55074c3f9f02dc3750088dc6
[]
no_license
cenkbircanoglu/simpson-recognition
0d2bbdb2283f89136e6fe676765845b5a82e460b
fe48dddb7c2df065e2c2a943c4008e20af093b90
refs/heads/master
2022-12-01T07:02:15.737824
2022-01-02T12:53:57
2022-01-02T12:53:57
187,513,224
1
0
null
2022-11-21T21:23:32
2019-05-19T18:26:36
Jupyter Notebook
UTF-8
Python
false
false
2,705
py
import csv import os import os.path import torch.utils.data as data from PIL import Image def find_classes(dir): fname = os.path.join(dir, 'annotation.txt') # read the content of the file with open(fname) as f: content = f.readlines() # remove whitespace characters like `\n` at the end of each line content = [x.strip() for x in content] # find the list of classes classes = dict() for x in content: classes[x.split(",")[-1]] = 0 # assign a label for each class index = 0 for key in sorted(classes): classes[key] = index index += 1 return classes def make_dataset(dir, classes, set): images = [] fname = os.path.join(dir, '%s_annotation.txt' % set) # read the content of the file with open(fname) as f: content = f.readlines() # remove whitespace characters like `\n` at the end of each line content = [x.strip() for x in content] for x in content: path = x.split(",")[0] label = classes[x.split(",")[-1]] item = (path, label) images.append(item) return images def write_csv_file(dir, images, set): csv_file = os.path.join(dir, set + '.csv') if not os.path.exists(csv_file): # write a csv file print('[dataset] write file %s' % csv_file) with open(csv_file, 'w') as csvfile: fieldnames = ['name', 'label'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for x in images: writer.writerow({'name': x[0], 'label': x[1]}) csvfile.close() class SimpsonDataset(data.Dataset): def __init__(self, root, set, transform=None, target_transform=None): self.root = root self.set = set self.transform = transform self.target_transform = target_transform self.path_images = os.path.join(self.root, 'characters') self.classes = find_classes(self.root) self.images = make_dataset(self.root, self.classes, set) print('[dataset] Simpson set=%s number of classes=%d number of images=%d' % ( set, len(self.classes), len(self.images))) write_csv_file(self.root, self.images, set) def __getitem__(self, index): path, target = self.images[index] img = Image.open(path).convert('RGB') if self.transform is not None: img = self.transform(img) if self.target_transform is not None: target = self.target_transform(target) return img, target def __len__(self): return len(self.images) def get_number_classes(self): return len(self.classes)
[ "cenk@voltlines.com" ]
cenk@voltlines.com
74bb432487665c9dafc8bef8671f7ec5d50da97d
f4efeb9333d92bf4ece483d19916218bd9fcc9da
/clientes/migrations/0001_initial.py
af66494980aed45220d0756f006190fc48d53df7
[]
no_license
veronicaasilva/django-crud-fbv
79473fadc23514ac8d40aa0307eb5ed8e1bb9616
c20857df6249ad7b278d67dbe78ffac66b3e3b62
refs/heads/master
2023-08-16T23:45:42.383977
2020-07-10T21:42:25
2020-07-10T21:42:25
275,207,775
1
0
null
2021-09-22T19:21:18
2020-06-26T17:08:40
HTML
UTF-8
Python
false
false
1,121
py
# Generated by Django 3.0.7 on 2020-06-26 12:14 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Cliente', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nomecompleto', models.CharField(max_length=150, verbose_name='Nome Completo')), ('nascimento', models.DateField(verbose_name='Data de Nascimento')), ('sexo', models.CharField(choices=[('Feminino', 'Feminino'), ('Masculino', 'Masculino'), ('Outros', 'Outros')], max_length=9, verbose_name='Sexo')), ('whatsapp', models.CharField(max_length=15, verbose_name='Whatsapp')), ('endereco', models.CharField(max_length=150, verbose_name='Endereço')), ('cidade', models.CharField(max_length=30, verbose_name='Cidade')), ('email', models.EmailField(max_length=254, verbose_name='Email')), ], ), ]
[ "veh.silva@gmail.com" ]
veh.silva@gmail.com
68d81e16c4ab27cbf8211219e8f06aa614c009f2
3679b977de9b33233fc846e151b994acece71db6
/Phenophase_Classification/evaluate_ensemble.py
78d0c2b027c1c76d757e41ae848fff37fcbf802d
[ "MIT" ]
permissive
n8srumsey/ISEF-2020-Phenology
1242433dc0da550bb4634c0dabd2dfd29a6be0ac
881e0ba096ea5c20ebb1fcc7a066cdc1df5c3843
refs/heads/master
2023-04-03T16:56:46.580206
2021-04-01T17:05:43
2021-04-01T17:05:43
316,903,895
0
0
null
null
null
null
UTF-8
Python
false
false
3,100
py
"""Evaluate the ensemble of models trained with k-fold cross validation.""" import os from statistics import mode import numpy as np from tensorflow.keras.models import load_model from tqdm import tqdm from .generator_dataset import get_generators from .utils import MODELS_DIR, RESULTS_DIR def load_models(path): directories = os.listdir(MODELS_DIR + path) models = [load_model(directory) for directory in directories] return models def eval_ensemble(models, eval_dataset=get_generators(), mthd_mode=True, mthd_mean=False, mthd_weighted=False, model_results=None, mthd_stacked=False, train_dataset=get_generators()): print('\n\n\n ***EVALUATING DATASET ***') def eval_mode(): print('\n Mode Method:') mode_predictions = [] generator = eval_dataset.gen_iter() # loop through batches for _ in tqdm(range(len(eval_dataset))): x, y = next(generator) pred = [] for model in models: output = model.predict(x, batch_size=1) pred.append(output[0]) for i in range(len(pred[0])): item_predicitons = [predictions[i] for predictions in pred] if mode([np.argmax(item) for item in item_predicitons]) == np.argmax(y): mode_predictions.append(1) else: mode_predictions.append(0) mode_binary_accuracy = float(np.sum(np.array(mode_predictions)) / len(mode_predictions)) return mode_binary_accuracy def eval_mean(): print('\n Mean Method:') mean_predictions = [] generator = eval_dataset.gen_iter() # loop through batches for _ in tqdm(range(len(eval_dataset))): x, y = next(generator) pred = [] for model in models: output = model.predict(x, batch_size=1) pred.append(output[0]) for i in range(len(pred[0])): item_predicitons = [predictions[i] for predictions in pred] mean = np.argmax(np.sum(item_predicitons, axis=0) / len(pred)) if mean == np.argmax(y): mean_predictions.append(1) else: mean_predictions.append(0) mean_binary_accuracy = float(np.sum(np.array(mean_predictions)) / len(mean_predictions)) return mean_binary_accuracy def eval_weighted(): print('\n Weighted Method:') pass def eval_stacked(): print('\n Stacked Method:') pass eval_results = {'mode_binary_accuracy': None, 'mean_binary_accuracy': None, 'weighted_binary_accuracy': None, 'stacked_binary_accuracy': None} if mthd_mode: eval_results['mode_binary_accuracy'] = eval_mode() if mthd_mean: eval_results['mean_binary_accuracy'] = eval_mean() if mthd_weighted: eval_results['weighted_binary_accuracy'] = eval_weighted() if mthd_stacked: eval_results['stacked_binary_accuracy'] = eval_stacked() print(eval_results) return eval_results
[ "nathan.s.rumsey@gmail.com" ]
nathan.s.rumsey@gmail.com
7ba77fcadf0c114f543e83167777171881f8ed86
2d812a812eb19ed1687058a88f8806217198a2d1
/account/forms.py
52ced73be99997b18875ad863cb8d8c8eda1a4ba
[]
no_license
Ahmed075/World
553181358279df0c8b265ff32e147f12574e512a
7ab93eb56d1c5db618311dd42a0b09f0e189ef2a
refs/heads/main
2023-02-18T00:26:45.916065
2021-01-11T04:10:55
2021-01-11T04:10:55
328,421,686
0
0
null
null
null
null
UTF-8
Python
false
false
1,493
py
from django import forms from .models import User class RegistrationForm(forms.ModelForm): password = forms.CharField(min_length=8, required=True, widget=forms.PasswordInput) password_confirmation = forms.CharField(min_length=8, required=True, widget=forms.PasswordInput) class Meta: model = User fields = ('username', 'email', 'password', 'password_confirmation', 'first_name', 'last_name', 'image') def clean_username(self): username = self.cleaned_data.get('username') if User.objects.filter(username=username).exists(): raise forms.ValidationError('Пользователь с данным именем пользователя уже существует') return username def clean_email(self): email = self.cleaned_data.get('email') if User.objects.filter(email=email).exists(): raise forms.ValidationError('Пользователь с данным именем email уже существует') return email def clean(self): data = self.cleaned_data password = data.get('password') password_confirm = data.pop('password_confirmation') if password != password_confirm: raise forms.ValidationError('Пароли не совпадают') return data def save(self, commit=True): print(self.cleaned_data) user = User.objects.create_user(**self.cleaned_data) return user
[ "akhmed096@mail.ru" ]
akhmed096@mail.ru
a8330e9e1cec37a1ea43903ccf3e36b9c86c9794
dd9b1b05db4968ee546be944f1e79f42dda143f3
/SOvSO.py
f635fa145be7b4649aec5c953e8f7c31631a22b0
[]
no_license
SOvSO/QLQ
e66b00713c53c6ee873821b929400688425cd0a5
c863e141ff947bac1e2dc57b39c95069c634f9ed
refs/heads/master
2020-06-11T23:30:33.912593
2019-06-28T09:07:03
2019-06-28T09:07:03
194,122,184
1
0
null
null
null
null
UTF-8
Python
false
false
321,488
py
from linepy import * from liff.ttypes import LiffChatContext, LiffContext, LiffSquareChatContext, LiffNoneContext, LiffViewRequest from akad.ttypes import Message from akad.ttypes import ContentType as Type from akad.ttypes import TalkException from datetime import datetime, timedelta from time import sleep from bs4 import BeautifulSoup as bSoup from bs4 import BeautifulSoup from humanfriendly import format_timespan, format_size, format_number, format_length #from gtts import gTTS from threading import Thread from io import StringIO from multiprocessing import Pool from googletrans import Translator from urllib.parse import urlencode from tmp.MySplit import * from random import randint from shutil import copyfile from youtube_dl import YoutubeDL import subprocess, youtube_dl, humanize, traceback import subprocess as cmd import platform import requests, json import time, random, sys, json, null, pafy, codecs, html5lib ,shutil ,threading, glob, re, base64, string, os, requests, six, ast, pytz, wikipedia, urllib, urllib.parse, atexit, asyncio, traceback _session = requests.session() #====================================================================================== botStart = time.time() #====================================================================================== maxgie = LINE('') maxgie.log("Auth Token : " + str(maxgie.authToken)) maxgie.log("Timeline Token : " + str(maxgie.tl.channelAccessToken)) waitOpen = codecs.open("Max2.json","r","utf-8") settingsOpen = codecs.open("max.json","r","utf-8") imagesOpen = codecs.open("image.json","r","utf-8") stickersOpen = codecs.open("sticker.json","r","utf-8") wait = json.load(waitOpen) images = json.load(imagesOpen) settings = json.load(settingsOpen) stickers = json.load(stickersOpen) #==============================================================================# maxgieMID = maxgie.profile.mid maxgieProfile = maxgie.getProfile() maxgieSettings = maxgie.getSettings() #==============================================================================# maxgiePoll = OEPoll(maxgie) maxgieMID = maxgie.getProfile().mid admin = [maxgieMID] loop = asyncio.get_event_loop() listToken = ['desktopmac','desktopwin','iosipad','chromeos','win10'] mc = {"wr":{}} unsendchat = {} msgdikirim = {} msg_image={} msg_video={} msg_sticker={} wbanlist = [] msg_dict = {} temp_flood = {} #==============================================================================# did = {"join": True,} kcn = {"autojoin": False,"Members":5,} sets = { "l":True, "c":True, "cm":"AUTO LIKE FOR : SOvSO", "winvite": False, "wblacklist": False, "tagsticker": False, "Sticker": False, "autoJoin": False, "autoCancel": False, "autoJoinTicket": False, "changePictureProfile": False, "addSticker": { "name": "", "status": False, }, "messageSticker": { "addName": "", "addStatus": False, "listSticker": { "tag": { "STKID": "", "STKPKGID": "", "STKVER": "" }, "lv": { "STKID": "", "STKPKGID": "", "STKVER": "" }, "wc": { "STKID": "", "STKPKGID": "", "STKVER": "" }, "add": { "STKID": "", "STKPKGID": "", "STKVER": "" }, "join2": { "STKID": "", "STKPKGID": "", "STKVER": "" }, } }, } chatbot = { "admin": [], "botMute": [], "botOff": [], } anyun = { "addTikel": { "name": "", "status": False }, } nissa = { "addTikel2": { "name": "", "status": False }, } tagadd = { "tagss": False, "tags": False, "tag": "วิธีตั้งแทค \n- ตั้งแทค ข้อความที่ต้องการ", "add": "ยินดีที่ได้รู้จักนะครับ 😃\nรับแอดละน้า. >_<", "wctext": "หวัดดีๆๆๆๆ", "lv": "จะรีบไปใหน หว่า", "b": "บัญชีนี้ถูกป้องกันด้วย\n AUTO BLOCK ★ʄທയஆടஷະ★ \nระบบได้บล็อคบัญชีคุณอัตโนมัติ >_<", "c":"AUTO LIKE FOR ★ʄທയஆടஷະ★ ", "m": "เจอลิ้งไม่ได้นะ ผมต้องมุด555", } apalo = { "winvite": False, "wblacklist": False, "blacklist":{}, "Talkblacklist": {}, "talkban": True, "Talkwblacklist": False, "Talkdblacklist": False, } temp = {"te": "#000000","t": "#FFC000"} read = { "readPoint": {}, "readMember": {}, "readTime": {}, "setTime":{}, "ROM": {} } rfuSet = { 'setTime':{}, 'ricoinvite':{}, 'winvite':{}, } ProfileMe = { "coverId": "", "statusMessage": "", "PictureMe": "", "NameMe": "", } peler = { "receivercount": 0, "sendcount": 0 } hoho = { "savefile": False, "namefile": "", } user1 = maxgieMID user2 = "" setTime = {} setTime = rfuSet['setTime'] contact = maxgie.getProfile() backup = maxgie.getProfile() backup.dispalyName = contact.displayName backup.statusMessage = contact.statusMessage backup.pictureStatus = contact.pictureStatus mulai = time.time() Start = time.time() tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) settings["myProfile"]["displayName"] = maxgieProfile.displayName settings["myProfile"]["statusMessage"] = maxgieProfile.statusMessage settings["myProfile"]["pictureStatus"] = maxgieProfile.pictureStatus cont = maxgie.getContact(maxgieMID) settings["myProfile"]["videoProfile"] = cont.videoProfile coverId = maxgie.getProfileDetail()["result"]["objectId"] settings["myProfile"]["coverId"] = coverId ProfileMe["statusMessage"] = maxgieProfile.statusMessage ProfileMe["pictureStatus"] = maxgieProfile.pictureStatus coverId = maxgie.getProfileDetail()["result"]["objectId"] ProfileMe["coverId"] = coverId #===================================================================== with open("max.json", "r", encoding="utf_8_sig") as f: anu = json.loads(f.read()) anu.update(settings) settings = anu with open("Max2.json", "r", encoding="utf_8_sig") as f: itu = json.loads(f.read()) itu.update(wait) wait = itu #==============================================================================# def RhyN_(to, mid): try: aa = '{"S":"0","E":"3","M":'+json.dumps(mid)+'}' text_ = '@Ma ' maxgie.sendMessage(to, text_, contentMetadata={'MENTION':'{"MENTIONEES":['+aa+']}'}, contentType=0) except Exception as error: logError(error) def sendMessageCustom(to, text, icon , name): annda = {'MSG_SENDER_ICON': icon, 'MSG_SENDER_NAME': name, } maxgie.sendMessage(to, text, contentMetadata=annda) def sendMessageCustomContact(to, icon, name, mid): annda = { 'mid': mid, 'MSG_SENDER_ICON': icon, 'MSG_SENDER_NAME': name, } maxgie.sendMessage(to, '', annda, 13) def cloneProfile(mid): contact = maxgie.getContact(mid) if contact.videoProfile == None: maxgie.cloneContactProfile(mid) else: profile = maxgie.getProfile() profile.displayName, profile.statusMessage = contact.displayName, contact.statusMessage maxgie.updateProfile(profile) pict = maxgie.downloadFileURL('http://dl.profile.line-cdn.net/' + contact.pictureStatus, saveAs="tmp/pict.bin") vids = maxgie.downloadFileURL( 'http://dl.profile.line-cdn.net/' + contact.pictureStatus + '/vp', saveAs="tmp/video.bin") changeVideoAndPictureProfile(pict, vids) coverId = maxgie.getProfileDetail(mid)['result']['objectId'] maxgie.updateProfileCoverById(coverId) def backupProfile(): profile = maxgie.getContact(maxgieMID) settings['myProfile']['displayName'] = profile.displayName settings['myProfile']['pictureStatus'] = profile.pictureStatus settings['myProfile']['statusMessage'] = profile.statusMessage settings['myProfile']['videoProfile'] = profile.videoProfile coverId = maxgie.getProfileDetail()['result']['objectId'] settings['myProfile']['coverId'] = str(coverId) def restoreProfile(): profile = maxgie.getProfile() profile.displayName = settings['myProfile']['displayName'] profile.statusMessage = settings['myProfile']['statusMessage'] if settings['myProfile']['videoProfile'] == None: profile.pictureStatus = settings['myProfile']['pictureStatus'] maxgie.updateProfileAttribute(8, profile.pictureStatus) maxgie.updateProfile(profile) else: maxgie.updateProfile(profile) pict = maxgie.downloadFileURL('http://dl.profile.line-cdn.net/' + settings['myProfile']['pictureStatus'], saveAs="tmp/pict.bin") vids = maxgie.downloadFileURL( 'http://dl.profile.line-cdn.net/' + settings['myProfile']['pictureStatus'] + '/vp', saveAs="tmp/video.bin") changeVideoAndPictureProfile(pict, vids) coverId = settings['myProfile']['coverId'] maxgie.updateProfileCoverById(coverId) def autoresponuy(to,msg,wait): to = msg.to if msg.to not in wait["GROUP"]['AR']['AP']: return if msg.to in wait["GROUP"]['AR']['S']: maxgie.sendMessage(msg.to,text=None,contentMetadata=wait["GROUP"]['AR']['S'][msg.to]['Sticker'], contentType=7) if(wait["GROUP"]['AR']['P'][msg.to] in [""," ","\n",None]): return if '@!' not in wait["GROUP"]['AR']['P'][msg.to]: wait["GROUP"]['AR']['P'][msg.to] = '@!'+wait["GROUP"]['AR']['P'][msg.to] nama = maxgie.getGroup(msg.to).name sd = maxgie.waktunjir() maxgie.sendMention(msg.to,wait["GROUP"]['AR']['P'][msg.to].replace('greeting',sd).replace(';',nama),'',[msg._from]*wait["GROUP"]['AR']['P'][msg.to].count('@!')) def ClonerV2(to): try: contact = maxgie.getContact(to) profile = maxgie.profile profileName = maxgie.profile profileStatus = maxgie.profile profileName.displayName = contact.displayName profileStatus.statusMessage = contact.statusMessage maxgie.updateProfile(profileName) maxgie.updateProfile(profileStatus) profile.pictureStatus = maxgie.downloadFileURL('http://dl.profile.line-cdn.net/{}'.format(contact.pictureStatus, 'path')) if maxgie.getProfileCoverId(to) is not None: maxgie.updateProfileCoverById(maxgie.getProfileCoverId(to)) maxgie.updateProfilePicture(profile.pictureStatus) print("Success Clone Profile {}".format(contact.displayName)) return maxgie.updateProfile(profile) if contact.videoProfile == None: return "Get Video Profile" path2 = "http://dl.profile.line-cdn.net/" + profile.pictureStatus maxgie.updateProfilePicture(path2, 'vp') except Exception as error: print(error) def sendMentionFooter(to, mid, firstmessage, lastmessage): try: arrData = "" text = "%s " %(str(firstmessage)) arr = [] mention = "@LopeAgri" slen = str(len(text)) elen = str(len(text) + len(mention)) arrData = {'S':slen, 'E':elen, 'M':mid} arr.append(arrData) text += mention + str(lastmessage) nama = "{}".format(maxgie.getContact(maxgieMID).displayName) img = "http://dl.profile.line-cdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus) ticket = "https://line.me/ti/p/~topzalove123" maxgie.sendMessage(to, text, {'AGENT_LINK': ticket, 'AGENT_ICON': img, 'AGENT_NAME': nama, 'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0) except Exception as error: logError(error) maxgie.sendMessage(to, "[ INFO ] Error :\n" + str(error)) def ggggg(secs): mins, secs = divmod(secs,60) hours, mins = divmod(mins,60) days, hours = divmod(hours,24) return '%02d วัน\n───────────\n%02d ชั่วโมง\n───────────\n%02d นาที\n───────────\n' %(days ,hours, mins) def mentions(to, text="", mids=[]): arrData = "" arr = [] mention = "@" if mids == []: raise Exception("Invalid mids") if "@!" in text: if text.count("@!") != len(mids): raise Exception("Invalid mids") texts = text.split("@!") textx = "" for mid in mids: textx += str(texts[mids.index(mid)]) slen = len(textx) elen = len(textx) + 15 arrData = {'S':str(slen), 'E':str(elen - 4), 'M':mid} arr.append(arrData) textx += mention textx += str(texts[len(mids)]) else: textx = "" slen = len(textx) elen = len(textx) + 15 arrData = {'S':str(slen), 'E':str(elen - 4), 'M':mids[0]} arr.append(arrData) textx += mention + str(text) maxgie.sendMessage(to, textx, {'AGENT_NAME':'LINE OFFICIAL', 'AGENT_LINK': 'line://ti/p/~{}'.format(maxgie.getProfile().userid), 'AGENT_ICON': "http://dl.profile.line-cdn.net/" + maxgie.getContact("ua053fcd4c52917706ae60c811e39d3ea").picturePath, 'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0) def changeVideoAndPictureProfile(pict, vids): try: files = {'file': open(vids, 'rb')} obs_params = maxgie.genOBSParams({'oid': maxgieMID, 'ver': '2.0', 'type': 'video', 'cat': 'vp.mp4'}) data = {'params': obs_params} r_vp = maxgie.server.postContent('{}/talk/vp/upload.nhn'.format(str(maxgie.server.LINE_OBS_DOMAIN)), data=data, files=files) if r_vp.status_code != 201: return "Failed update profile" maxgie.updateProfilePicture(pict, 'vp') return "Success update profile" except Exception as e: raise Exception("Error change video and picture profile {}".format(str(e))) os.remove("FadhilvanHalen.mp4") def sendTemplate(to, data): xyz = LiffChatContext(to) xyzz = LiffContext(chat=xyz) view = LiffViewRequest('1602687308-GXq4Vvk9', xyzz) token = maxgie.liff.issueLiffView(view) url = 'https://api.line.me/message/v3/share' headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer %s' % token.accessToken } data = {"messages":[data]} requests.post(url, headers=headers, data=json.dumps(data)) def sendTemplate(group, data): xyz = LiffChatContext(group) xyzz = LiffContext(chat=xyz) view = LiffViewRequest('1602687308-GXq4Vvk9', xyzz) token = maxgie.liff.issueLiffView(view) url = 'https://api.line.me/message/v3/share' headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer %s' % token.accessToken } data = {"messages":[data]} requests.post(url, headers=headers, data=json.dumps(data)) def NOTIFIED_READ_MESSAGE(op): try: if read['readPoint'][op.param1]: if op.param2 in read['readMember'][op.param1]: pass else: read['readMember'][op.param1][op.param2] = True read['ROM'][op.param1] = op.param2 else: pass except: pass def logError(text): maxgie.log("[ แจ้งเตือน ] " + str(text)) time_ = datetime.now() with open("errorLog.txt","a") as error: error.write("\n[%s] %s" % (str(time), text)) def command(text): pesan = text.lower() if settings["setKey"] == True: if pesan.startswith(settings["keyCommand"]): cmd = pesan.replace(settings["keyCommand"],"") else: cmd = "Undefined command" else: cmd = text.lower() return cmd def sendMessage(to, text, contentMetadata={}, contentType=0): mes = Message() mes.to, mes.from_ = to, profile.mid mes.text = text mes.contentType,mes.contentMetadata = contentType, contentMetadata if to not in messageReq: messageReq[to] = -1 messageReq[to] += 1 def sendMention(to, mid, firstmessage, lastmessage): try: arrData = "" text = "%s " %(str(firstmessage)) arr = [] mention = "@x " slen = str(len(text)) elen = str(len(text) + len(mention) - 1) arrData = {'S':slen, 'E':elen, 'M':mid} arr.append(arrData) text += mention + str(lastmessage) maxgie.sendMessage(to, text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0) except Exception as error: logError(error) maxgie.sendMessage(to, "[ INFO ] Error :\n" + str(error)) def mentionMembers(to, mid): try: group = maxgie.getGroup(to) mids = [mem.mid for mem in group.members] jml = len(mids) arrData = "" if mid[0] == mids[0]: textx = "" else: textx = "" arr = [] for i in mid: no = mids.index(i) + 1 textx += "{}.".format(str(no)) mention = "@x\n" slen = str(len(textx)) elen = str(len(textx) + len(mention) - 1) arrData = {'S':slen, 'E':elen, 'M':i} arr.append(arrData) textx += mention if no == jml: textx += "" textx += "" maxgie.sendMessage(to, textx, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0) except Exception as error: logError(error) maxgie.sendMessage(to, "[ INFO ] Error :\n" + str(error)) def timeChange(secs): mins, secs = divmod(secs,60) hours, mins = divmod(mins,60) days, hours = divmod(hours,24) weeks, days = divmod(days,7) months, weeks = divmod(weeks,4) text = "" if months != 0: text += "%02d เดือน" % (months) if weeks != 0: text += " %02d สัปดาห์" % (weeks) if days != 0: text += " %02d วัน" % (days) if hours != 0: text += " %02d ชั่วโมง" % (hours) if mins != 0: text += " %02d นาที" % (mins) if secs != 0: text += " %02d วินาที" % (secs) if text[0] == " ": text = text[1:] return text def restartBot(): print ("RESETBOT..") python = sys.executable os.execl(python, python, *sys.argv) def load(): global images global stickers with open("image.json","r") as fp: images = json.load(fp) with open("sticker.json","r") as fp: stickers = json.load(fp) # with open("stickerz.json","r") as fp: # stickerz = json.load(fp) def sendStickers(to, sver, spkg, sid): contentMetadata = { 'STKVER': sver, 'STKPKGID': spkg, 'STKID': sid } maxgie.sendMessage(to, '', contentMetadata, 7) def sendSticker(to, mid, sver, spkg, sid): contentMetadata = { 'MSG_SENDER_NAME': maxgie.getContact(mid).displayName, 'MSG_SENDER_ICON': 'http://dl.profile.line-cdn.net/' + maxgie.getContact(mid).pictureStatus, 'STKVER': sver, 'STKPKGID': spkg, 'STKID': sid } maxgie.sendMessage(to, '', contentMetadata, 7) def sendImage(to, path, name="image"): try: if settings["server"] == "VPS": maxgie.sendImageWithURL(to, str(path)) except Exception as error: logError(error) def command(text): pesan = text.lower() if settings["setKey"] == True: if pesan.startswith(settings["keyCommand"]): cmd = pesan.replace(settings["keyCommand"],"") else: cmd = "Undefined command" else: cmd = text.lower() return cmd def removeCmd(cmd, text): key = settings["keyCommand"] if settings["setKey"] == False: key = '' rmv = len(key + cmd) + 1 return text[rmv:] def duc1(to, duc1): data={ "type": "flex", "altText": duc1, "contents": { "type": "bubble", "styles": { "footer": {"backgroundColor": "#000000"}, }, "footer": { "type": "box", "layout": "vertical", "spacing": "sm", "contents": [ { "type": "box", "layout": "baseline", "contents": [ { "type": "icon", "url": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus), "size": "md" }, { "type": "text", "text": duc1, "color":"#00FF00", "gravity": "center", "align":"center", "wrap": True, "size": "md" }, { "type": "icon", "url": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus), "size": "md" }, ] } ] } } } sendTemplate(to, data) #===================================================================== #===================================================================== def backupData(): try: backup = settings f = codecs.open('max.json','w','utf-8') json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False) backup = images f = codecs.open('image.json','w','utf-8') json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False) backup = stickers f = codecs.open('sticker.json','w','utf-8') json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False) backup = wait f = codecs.open('Max2.json','w','utf-8') json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False) return True except Exception as error: logError(error) return False #==============================================================================# async def maxgieBot(op): try: if settings["restartPoint"] != None: maxgie.sendMessage(settings["restartPoint"], 'ล็อคอินแล้วเรียบร้อย ><') settings["restartPoint"] = None if op.type == 0: return if op.type == 5: if settings["autoAdd"] == True: # if op.param2 in admin: # return maxgie.findAndAddContactsByMid(op.param1) maxgie.sendMessage(op.param1,"{}".format(tagadd["add"])) msgSticker = sets["messageSticker"]["listSticker"]["add"] if msgSticker != None: sid = msgSticker["STKID"] spkg = msgSticker["STKPKGID"] sver = msgSticker["STKVER"] sendSticker(op.param1, sver, spkg, sid) print ("[ 5 ] AUTO ADD") if op.type == 5: if settings["autoblock"] == True: #if op.param2 in admin: # return maxgie.sendMessage(op.param1,tagadd["b"]) # msgSticker = sets["messageSticker"]["listSticker"]["block"] # if msgSticker != None: # sid = msgSticker["STKID"] # spkg = msgSticker["STKPKGID"] # sver = msgSticker["STKVER"] # sendSticker(op.param1, sver, spkg, sid) #maxgie.sendMessage(op.param1,tagaad["b"]) maxgie.blockContact(op.param1) print ("[ 5 ] AUTO BLOCK") if op.type == 13: if kcn["autojoin"] == True: G = maxgie.getCompactGroup(op.param1) if len(G.members) <= kcn["Members"]: maxgie.acceptGroupInvitation(op.param1) maxgie.leaveGroup(op.param1) else: maxgie.acceptGroupInvitation(op.param1) if op.type == 13: if maxgieMID in op.param3: if did["join"] == True: friend = maxgie.getAllContactIds() kontak = maxgie.getContacts(friend) for ids in kontak: The = ids.mid if op.param2 not in The: try: maxgie.acceptGroupInvitation(op.param1) ginfo = maxgie.getGroup(op.param1) except: maxgie.acceptGroupInvitation(op.param1) ginfo = maxgie.getGroup(op.param1) maxgie.sendMessage(op.param1,"BYE BYE~~") maxgie.leaveGroup(op.param1) if op.type == 13: if maxgieMID in op.param3: G = maxgie.getGroup(op.param1) if settings["autoJoin"] == True: if settings["autoCancel"]["on"] == True: if len(G.members) <= settings["autoCancel"]["members"]: maxgie.acceptGroupInvitation(op.param1) else: maxgie.leaveGroup(op.param1) else: maxgie.acceptGroupInvitation(op.param1) elif settings["autoCancel"]["on"] == True: if len(G.members) <= settings["autoCancel"]["members"]: maxgie.acceptGroupInvitation(op.param1) maxgie.leaveGroup(op.param1) else: Inviter = op.param3.replace("",',') InviterX = Inviter.split(",") matched_list = [] for tag in apalo["blacklist"]: matched_list+=[str for str in InviterX if str == tag] if matched_list == []: pass else: maxgie.acceptGroupInvitation(op.param1, matched_list) maxgie.leaveGroup(op.param1, matched_list) print ("[ 17 ] LEAVE GROUP") if op.type == 15: if settings["Leave"] == True: if op.param2 in admin: return ginfo = maxgie.getGroup(op.param1) contact = maxgie.getContact(op.param2) name = contact.displayName pp = contact.pictureStatus s = name + " " + tagadd["lv"] data = { "type": "flex", "altText": "มีคนออกกลุ่ม", "contents": { "type": "bubble", "styles": { "body": { "backgroundColor": '#EE1289' }, }, "body": { "type": "box", "layout": "vertical", "contents": [ { "type": "text", "text": "{}".format(s), "wrap": True, "color": "#00F5FF", "gravity": "center", "size": "md" }, ] } } } sendTemplate(op.param1, data) data = { "type": "flex", "altText": "มีคนออกกลุ่ม", "contents": { "type": "bubble", "hero": { "type":"image", "url": "https://profile.line-scdn.net/" + str(pp), "size":"full", "action": { "type": "uri", "uri": "line://ti/p/~nonbysignal" # # " } }, } } sendTemplate(op.param1, data) if op.type == 15: if settings["lv"] == True: ginfo = maxgie.getGroup(op.param1) msg = sets["messageSticker"]["listSticker"]["lv"] if msg != None: contact = maxgie.getContact(maxgieMID) a = contact.displayName stk = msg['STKID'] spk = msg['STKPKGID'] data={'type':'template','altText': str(a)+' ส่งสติ๊กเกอร์','template':{'type':'image_carousel','columns':[{'imageUrl':'https://stickershop.line-scdn.net/stickershop/v1/sticker/{}/IOS/sticker_animation@2x.png'.format(stk),'action':{'type':'uri','uri':'https://line.me/S/sticker/{}'.format(spk)}}]}} sendTemplate(op.param1, data) if op.type == 17: if settings["Welcome"] == True: if op.param2 in admin: return g = maxgie.getGroup(op.param1) contact = maxgie.getContact(op.param2) gname = g.name name = contact.displayName pp = contact.pictureStatus s = "〖 Group Welcome 〗\n" s += "\n• ชื่อกลุ่ม : {}".format(gname) s += "\n• ชื่อคนเข้ากลุ่ม : {}\n\n".format(name) s += tagadd["wctext"] data = { "type": "flex", "altText": "มีคนเข้ากลุ่ม", "contents": { "type": "bubble", "styles": { "body": { "backgroundColor": '#EE1289' }, }, "body": { "type": "box", "layout": "vertical", "contents": [ { "type": "text", "text": "{}".format(s), "wrap": True, "color": "#00F5FF", "align": "center", "gravity": "center", "size": "md" }, ] } } } sendTemplate(op.param1, data) data = { "type": "flex", "altText": "ใครออกไปใหนหว่า", "contents": { "type": "bubble", "hero": { "type":"image", "url": "https://profile.line-scdn.net/" + str(pp), "size":"full", "action": { "type": "uri", "uri": "line://ti/p/~nonbysignal" #" } }, } } sendTemplate(op.param1, data) if op.type == 17: if settings["Wc"] == True: if op.param2 in admin: return ginfo = maxgie.getGroup(op.param1) contact = maxgie.getContact(op.param2) cover = maxgie.getProfileCoverURL(op.param2) names = contact.displayName status = contact.statusMessage pp = contact.pictureStatus data = { "type": "flex", "altText": "มีคนเข้ากลุ่มไปแล้วนะ", "contents": { "type": "bubble", 'styles': { "body": { "backgroundColor": '#EE1289' }, }, "hero": { "type":"image", "url": cover, "size":"full", "aspectRatio":"20:13", "aspectMode":"cover" }, "body": { "type": "box", "layout": "vertical", "contents": [ { "type": "image", "url": "https://profile.line-scdn.net/" + str(pp), "size": "lg" }, { "type":"text", "text":" " }, { "type":"text", "text":"{}".format(names), "size":"xl", "weight":"bold", "color":"#00F5FF", "align":"center" }, { "type": "text", "text": status, "wrap": True, "align": "center", "gravity": "center", "color": "#00F5FF", "size": "md" }, ] } } } sendTemplate(op.param1, data) if op.type == 17: if settings["wcsti2"] == True: ginfo = maxgie.getGroup(op.param1) msg = sets["messageSticker"]["listSticker"]["wc"] if msg != None: contact = maxgie.getContact(maxgieMID) a = contact.displayName stk = msg['STKID'] spk = msg['STKPKGID'] data={'type':'template','altText': str(a)+' ส่งสติ๊กเกอร์','template':{'type':'image_carousel','columns':[{'imageUrl':'https://stickershop.line-scdn.net/stickershop/v1/sticker/{}/IOS/sticker_animation@2x.png'.format(stk),'action':{'type':'uri','uri':'https://line.me/S/sticker/{}'.format(spk)}}]}} sendTemplate(op.param1, data) #===================================================================== # if op.type == 26: # print ("[ 26 ] RECEIVE MESSAGE") # msg = op.message # text = str(msg.text) # msg_id = msg.id # receiver = msg.to # sender = msg._from # cmd = command(text) # setKey = settings["keyCommand"].title() # if settings["setKey"] == False: setKey = "" # isValid = True # if isValid != False: # if msg.toType == 0 and sender != maxgieMID: to = sender # else: to = receiver # if msg.toType == 0 and settings["replays"] and sender != maxgieMID: # contact = maxgie.getContact(sender) #if contact.attributes != 32 and "[ auto reply ]" not in text.lower(): # msgSticker = sets["messageSticker"]["listSticker"]["replay"] # if msgSticker != None: # sid = msgSticker["STKID"] # spkg = msgSticker["STKPKGID"] # sver = msgSticker["STKVER"] # sendSticker(to, sver, spkg, sid) # if "@!" in settings["reply"]: # msg_ = settings["reply"].split("@!") # sendMention(to, sender, "「 แทคส่วนตัว 」\n" + msg_[0], msg_[1]) # maxgie.sendMessage(to, "「 แทคส่วนตัว 」\n", settings["reply"]) if op.type == 24: if settings["autoLeave"] == True: maxgie.leaveRoom(op.param1) if op.type == 25: msg = op.message if msg.contentType == 13: if apalo["winvite"] == True: if msg._from in admin: _name = msg.contentMetadata["displayName"] invite = msg.contentMetadata["mid"] groups = maxgie.getGroup(msg.to) pending = groups.invitee targets = [] for s in groups.members: if _name in s.displayName: maxgie.sendMessage(msg.to,"-> " + _name + " ทำการเชิญสำเร็จ") break elif invite in apalo["blacklist"]: maxgie.sendMessage(msg.to,"ขออภัย, " + _name + " บุคคนนี้อยู่ในรายการบัญชีดำ") maxgie.sendMessage(msg.to,"ใช้คำสั่ง!,ล้างดำ,ดึง" ) break else: targets.append(invite) if targets == []: pass else: for target in targets: try: maxgie.findAndAddContactsByMid(target) maxgie.inviteIntoGroup(msg.to,[target]) maxgie.sendMessage(msg.to,"เชิญ :" + _name + "เรียบร้อย") apalo["winvite"] = False break except: try: maxgie.findAndAddContactsByMid(invite) maxgie.inviteIntoGroup(op.param1,[invite]) apalo["winvite"] = False except: maxgie.sendMessage(msg.to,"😧ตรวจพบข้อผิดพลาดที่ไม่ทราบสาเหตุ อาจเป็นได้ว่าบัญชีบัคเชิญ") apalo["winvite"] = False break if op.type == 25: msg = op.message text = str(msg.text) msg_id = msg.id receiver = msg.to sender = msg._from if msg.to not in unsendchat: unsendchat[msg.to] = {} if msg_id not in unsendchat[msg.to]: unsendchat[msg.to][msg_id] = msg_id msgdikirim[msg_id] = {"text":text} to = msg.to isValid = True cmd = command(text) setkey = settings['keyCommand'].title() if settings['setKey'] == False: setkey = '' if isValid != False: if msg.contentType in [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]: try: if msg.to not in wait['Unsend']: wait['Unsend'][msg.to] = {'B':[]} if msg._from not in [maxgieMID]: return wait['Unsend'][msg.to]['B'].append(msg.id) except:pass if op.type in [25, 26]: msg = op.message text = str(msg.text) msg_id = msg.id receiver = msg.to sender = msg._from to = msg.to cmd = command(text) isValid = True setKey = settings["keyCommand"].title() if settings["setKey"] == False: setKey = '' if isValid != False: if msg.toType == 0 and sender != maxgieMID: to = sender else: to = receiver if msg._from not in maxgieMID: if apalo["talkban"] == True: if msg._from in apalo["Talkblacklist"]: maxgie.sendMention(to, "คุณติดดำผมอยู่นะครับ @! :)","",[msg._from]) maxgie.kickoutFromGroup(msg.to, [msg._from]) if msg.contentType == 13: if apalo["Talkwblacklist"] == True: if msg._from in admin: if msg.contentMetadata["mid"] in apalo["Talkblacklist"]: maxgie.sendMessage(msg.to,"Sudah Ada") apalo["Talkwblacklist"] = False else: apalo["Talkblacklist"][msg.contentMetadata["mid"]] = True apalo["Talkwblacklist"] = False maxgie.unsendMessage(msg_id) duc1(to, "🌟เพิ่มบัญชีนี้ในรายการสีดำเรียบร้อยแล้ว🌟") if apalo["Talkdblacklist"] == True: if msg._from in admin: if msg.contentMetadata["mid"] in apalo["Talkblacklist"]: del apalo["Talkblacklist"][msg.contentMetadata["mid"]] maxgie.unsendMessage(msg_id) duc1(to, "🌟เพิ่มบัญชีนี้ในรายการสีขาวเรียบร้อยแล้ว🌟") apalo["Talkdblacklist"] = False else: apalo["Talkdblacklist"] = False maxgie.sendMessage(msg.to,"Tidak Ada Dalam Da ftar Blacklist") if op.type in [25,26]: msg = op.message text = str(msg.text) msg_id = msg.id receiver = msg.to sender = msg._from to = msg.to isValid = True if isValid != False: if msg.toType == 0 and sender != maxgieMID: to = sender else: to = receiver if msg.contentType == 16: if msg.toType in [2,1,0]: try: if sets["l"] == True: purl = msg.contentMetadata["postEndUrl"].split('userMid=')[1].split('&postId=') duc1(to,"🌟ไลค์ให้แล้วนะครับ🌟") if purl[1] not in wait['postId']: maxgie.likePost(purl[0], purl[1], random.choice([1001])) if sets["c"] == True: maxgie.createComment(purl[0], purl[1], sets["cm"]) wait['postId'].append(purl[1]) else: pass except Exception as e: if sets["l"] == True: purl = msg.contentMetadata['postEndUrl'].split('homeId=')[1].split('&postId=') duc1(to,"🌟ไลค์ให้แล้วนะครับ🌟") if purl[1] not in wait['postId']: maxgie.likePost(msg._from, purl[1], random.choice([1001])) if sets["c"] == True: maxgie.createComment(msg._from, purl[1], sets["cm"]) wait['postId'].append(purl[1]) else:pass #===================================================================== #===================================================================== if op.type == 25: print("[ 25 ] SEND MESSAGE") msg = op.message text = msg.text msg_id = msg.id receiver = msg.to sender = msg._from if msg.toType == 0 or msg.toType == 1 or msg.toType == 2: if msg.toType == 0: if sender != maxgie.profile.mid: to = sender else: to = receiver elif msg.toType == 1: to = receiver elif msg.toType == 2: to = receiver if msg.contentType == 0: if text is None: return if text.lower() == "ประกาศ": sa="วิธีใช้ ประกาศกลุ่ม >\\<" sa+="\n- ประกาศ ข้อความ/ไอดีไลน์" sa+="\nตัวอย่าง >\\<" sa+="\n- ประกาศ มอนิ่ง/nonbysignal" data = {"type": "text","text": "{}".format(sa),"sentBy": {"label": " ★ʄທയஆടஷະ★ ", "iconUrl": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus),"linkUrl": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac"}} sendTemplate(to,data) if text.lower() == "ตั้งapi": sa = "วีธีใช้ api >\\<" sa += "\n- ตั้งapi คีย์เวิร์ด;;ตอบกลับ" sa += "\nตัวอย่าง >\\<" sa += "\n- ตั้งapi เทส;;เทสทำไม" data = {"type": "text","text": "{}".format(sa),"sentBy": {"label": "★ʄທയஆടஷະ★ ", "iconUrl": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus),"linkUrl": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac"}} sendTemplate(to,data) if text.lower() == "stag": sa = "วิธีใช้ stag >\\<" sa += "\n- stag [เลขที่ต้องการ] @user" sa += "\nตัวอย่าง >\\<" sa += "\n- stag 1 @user" data = {"type": "text","text": "{}".format(sa),"sentBy": {"label": "★ʄທയஆടஷະ★ ", "iconUrl": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus),"linkUrl": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac"}} sendTemplate(to,data) if text.lower() == "สะกด": sa = "วิธีใช้ สะกด >\\<" sa += "\n- สะกดกิต [ข้อความ] @user" sa += "\nตัวอย่าง >\\<" sa += "\n- สะกด รักทอป @user" data = {"type": "text","text": "{}".format(sa),"sentBy": {"label": "★ʄທയஆടஷະ★ ", "iconUrl": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus),"linkUrl": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac"}} sendTemplate(to,data) if text.lower() == "เชคค่า" or text.lower() == "set": sas = "☆ Settings ☆" if settings["autoAdd"] == True: sa = "\n• ออโต้แอด ( เปิด )" else:sa = "\n• ออโต้แอด ( ปิด )" if settings["autoblock"] == True: sa += "\n• ออโต้บล็อค ( เปิด )" else:sa += "\n• ออโต้บล็อค ( ปิด )" if settings["autoCancel"]["on"] == True: sa +="\n• ยกเชิญที่มีสมาชิกต่ำกว่า: " + str(settings["autoCancel"]["members"]) else:sa += "\n• ปฏิเสธกลุ่มเชิญ ( ปิด )" if tagadd["tags"] == True: sa += "\n• ตอบกลับคนแทค ( เปิด )" else:sa += "\n• ตอบกลับคนแทค ( ปิด )" if tagadd["tagss"] == True: sa += "\n• ตอบกลับคนแทค2 ( เปิด )" else:sa += "\n• ตอบกลับคนแทค2 ( ปิด )" if sets["tagsticker"] == True: sa += "\n• แทคสติ๊กเกอร์ ( เปิด )" else:sa += "\n• แทคสติ๊กเกอร์ ( ปิด )" if settings["autolike"] == True: sa += "\n• ออโต้ไลค์ ( เปิด )" else:sa += "\n• ออโต้ไลค์ ( ปิด )" if settings["com"] == True: sa += "\n• คอมเม้นโพส ( เปิด )" else:sa += "\n• คอมเม้นโพส ( ปิด )" if settings["Welcome"] == True: sa += "\n• ต้อนรับคนเข้ากลุ่ม ( เปิด )" else:sa += "\n• ต้อนรับคนเข้ากลุ่ม ( ปิด )" if settings["Wc"] == True: sa += "\n• ต้อนรับคนเข้ากลุ่ม2 ( เปิด )" else:sa += "\n• ต้อนรับคนเข้ากลุ่ม2 ( ปิด )" if settings["wcsti2"] == True: sa += "\n• ติ๊กคนเข้ากลุ่ม ( เปิด )" else:sa += "\n• ติ๊กคนเข้ากลุ่ม ( ปิด )" if settings["Leave"] == True: sa += "\n• คนออกกลุ่ม ( เปิด )" else:sa += "\n• คนออกกลุ่ม ( ปิด )" if settings["lv"] == True: sa += "\n• ติ๊กคนออกกลุ่ม ( เปิด )" else:sa += "\n• ติ๊กคนออกกลุ่ม ( ปิด )" if settings["unsendMessage"] == True: sa += "\n• ตรวจจับยกเลิก ( เปิด )" else:sa += "\n• ตรวจจับยกเลิก ( ปิด )" if settings["Sticker"] == True: sa += "\n• เชคติ๊กใหญ่ ( เปิด )" else:sa += "\n• เชคติ๊กใหญ่ ( ปิด )" if sets["Sticker"] == True: sa += "\n• เชคโค๊ดสติ๊กเกอร์ ( เปิด )" else:sa += "\n• เชคโค๊ดสติ๊กเกอร์ ( ปิด )" data = { "type": "flex", "altText": "{}".format(sas), "contents": { "type": "bubble", "styles": { "body": { "backgroundColor": '#EE1289' }, }, "hero": { "type": "image", "url": "https://obs.line-scdn.net/{}".format(maxgie.getContact(sender).pictureStatus), "size": "full", "aspectRatio": "1:1", "aspectMode": "fit", }, "body": { "type": "box", "layout": "vertical", "contents": [ { "type": "text", "text": sas, "color": "#00F5FF", "align": "center", "weight": "bold", "size": "xxl" }, { "type": "text", "text": "{}".format(sa), "wrap": True, "color": "#00F5FF", "gravity": "center", "size": "md" }, ] }, } } sendTemplate(to, data) elif text.lower() == 'clearban' or text.lower() == "ล้างดำ": apalo["Talkblacklist"] = [] duc1(to, "🌟สำเร็จ🌟") elif text.lower() == "คนดำ": if msg._from in maxgieMID: if apalo["Talkblacklist"] == []: maxgie.unsendMessage(msg_id) duc1(to, "🌟ไม่มีคน.คนติดดำ🌟") else: for bl in apalo["Talkblacklist"]: maxgie.sendMessage(to, text=None, contentMetadata={'mid': bl}, contentType=13) elif text.lower() == "เตะดำ": if msg.toType == 2: groupMemberMids = [contact.mid for contact in maxgie.getGroup(to).members] matched_list = [] for mid in apalo["Talkblacklist"]: matched_list += [x for x in groupMemberMids if x == mid] if matched_list == []: duc1(to, "ไม่มีคนติดดำในนี้") else: for mids in matched_list: try: maxgie.kickoutFromGroup(to, [mids]) except:pass elif "Kick " in msg.text: Ri0 = text.replace("kick ","") Ri1 = Ri0.rstrip() Ri2 = Ri1.replace("@","") Ri3 = Ri2.rstrip() _name = Ri3 gs = maxgie.getGroup(msg.to) targets = [] for s in gs.members: if _name in s.displayName: targets.append(s.mid) if targets == []: pass else: for target in targets: if target in admin: pass else: try: maxgie.kickoutFromGroup(to,[target]) except: pass elif "ล้อเล่น " in msg.text: Ri0 = text.replace("ล้อเล่น ","") Ri1 = Ri0.rstrip() Ri2 = Ri1.replace("@","") Ri3 = Ri2.rstrip() _name = Ri3 gs = maxgie.getGroup(msg.to) targets = [] for s in gs.members: if _name in s.displayName: targets.append(s.mid) if targets == []: pass else: for target in targets: if target in admin: pass else: try: maxgie.kickoutFromGroup(to,[target]) maxgie.findAndAddContactsByMid(target) maxgie.inviteIntoGroup(to,[target]) except: pass elif "เตะ " in msg.text: vkick0 = msg.text.replace("เตะ ","") vkick1 = vkick0.rstrip() vkick2 = vkick1.replace("@","") vkick3 = vkick2.rstrip() _name = vkick3 gs = maxgie.getGroup(msg.to) targets = [] for s in gs.members: if _name in s.displayName: targets.append(s.mid) if targets == []: pass else: for target in targets: try: maxgie.kickoutFromGroup(msg.to,[target]) maxgie.findAndAddContactsByMid(target) maxgie.inviteIntoGroup(msg.to,[target]) maxgie.cancelGroupInvitation(msg.to,[target]) except: pass elif msg.text.lower().startswith("สีme "): text_ = removeCmd("สีme", text) try: temp["t"] = text_ maxgie.sendMessage(to,"「 โค๊ดสี 」\nคือ : " + text_) except: maxgie.sendMessage(to,"สำเเร็จแล้ว") elif msg.text.lower().startswith("สีอักษร "): text_ = removeCmd("สีอักษร", text) try: temp["te"] = text_ maxgie.sendMessage(to,"「 โค๊ดสี 」\nคือ : " + text_) except: maxgie.sendMessage(to,"สำเเร็จแล้ว") elif msg.text.lower() == "รหัสสี": c="https://i.pinimg.com/originals/d0/9c/8a/d09c8ad110eb44532825df454085a376.jpg" p="https://i.pinimg.com/originals/7c/d3/aa/7cd3aa57150f8f6f18711ff22c9f6d4a.jpg" m="**ตัวอย่างที่1**\nคำสั่งเปลี่ยนสี me\nพิม'ตั้งสีme #333333'\n**ตัวอย่างที่2**\nคำสั่งเปลี่ยนสี tag\nพิม'ตั้งสีแทค #333333'" maxgie.sendImageWithURL(to,c) maxgie.sendImageWithURL(to,p) maxgie.sendMessage(to,m) elif msg.text.lower().startswith("ตั้งบล็อค "): text_ = removeCmd("ตั้งบล็อค", text) try: tagadd["b"] = text_ maxgie.sendMessage(to,"「 ตั้งบล็อคอัตโนมัติ 」\nคือ : " + text_) except: maxgie.unsendMessage(msg_id) duc1(to, "🌟สำเร็จแล้ววว🌟") elif text.lower().startswith("ตั้งค้างเชิญ "): text_ = removeCmd("ตั้งค้างเชิญ", text) try: settings["autoCancel"]["members"] = text_ maxgie.sendMessage(to,"「 ตั้งยกค้างเชิญ 」\nจำนวน : " + text_) except: maxgie.unsendMessage(msg_id) duc1(to, "🌟สำเร็จแล้ววว🌟") if text.lower() == "ดำ": if msg._from in admin: apalo["Talkwblacklist"] = True maxgie.unsendMessage(msg_id) duc1(to, "🌟ส่งคทลงมา...🌟") if text.lower() == "ขาว": if msg._from in admin: apalo["Talkdblacklist"] = True maxgie.unsendMessage(msg_id) duc1(to, "🌟ส่งคทลงมา...🌟") elif msg.text.lower().startswith("ตั้งแทค "): text_ = removeCmd("ตั้งแทค", text) try: tagadd["tag"] = text_ sa = "「 ตั้งคำแทค 」\nคือ : " + text_ data = {"type": "text","text": "{}".format(sa),"sentBy": {"label": "★ʄທയஆടஷະ★ ", "iconUrl": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus),"linkUrl": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac"}} sendTemplate(to,data) except: maxgie.sendMessage(to,"Done. >_<") elif msg.text.lower().startswith("ตั้งแทคแชท "): text_ = removeCmd("ตั้งแทคแชท", text) try: settings["reply"] = text_ sa = "「 ตั้งคำแทค 」\nคือ : " + text_ data = {"type": "text","text": "{}".format(sa),"sentBy": {"label": "★ʄທയஆടஷະ★", "iconUrl": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus),"linkUrl": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac"}} sendTemplate(to,data) except: maxgie.sendMessage(to,"Done. >_<") elif msg.text.lower().startswith("ตั้งต้อนรับ "): text_ = removeCmd("ตั้งต้อนรับ", text) try: tagadd["wctext"] = text_ sa = "「 ตั้งต้อนรับ 」\nคือ : " + text_ data = {"type": "text","text": "{}".format(sa),"sentBy": {"label": " ★ʄທയஆടஷະ★", "iconUrl": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus),"linkUrl": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac"}} sendTemplate(to,data) except: maxgie.sendMessags(to,"Done. >_<") elif msg.text.lower().startswith("ตั้งคนออก "): text_ = removeCmd("ตั้งคนออก", text) try: tagadd["lv"] = text_ maxgie.sendMessage(to,"「 ตั้งคนออก 」\nคือ : " + text_) except: maxgie.sendMessage(to,"สำเเร็จแล้ว") elif msg.text.lower().startswith("ตั้งแอด "): text_ = removeCmd("ตั้งแอด", text) try: tagadd["add"] = text_ sa = "「 ตั้งแอด 」\nคือ : " + text_ data = {"type": "text","text": "{}".format(sa),"sentBy": {"label": "★ʄທയஆടஷະ★ ", "iconUrl": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus),"linkUrl": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac"}} sendTemplate(to,data) except: maxgie.sendMessags(to,"Done. >_<") elif msg.text.lower().startswith("ตั้งคอมเม้น "): text_ = removeCmd("ตั้งคอมเม้น", text) try: settings["commet"] = text_ sa = "「 ตั้งคอมเม้น 」\nคือ : " + text_ data = {"type": "text","text": "{}".format(sa),"sentBy": {"label": "★ʄທയஆടஷະ★ ", "iconUrl": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus),"linkUrl": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac"}} sendTemplate(to,data) except: maxgie.sendMessags(to,"Done. >_<") elif msg.text.lower() == "ทัก": if msg.toType == 0: sendMention(to, to, "────────────────\n", "\n────────────────") elif msg.toType == 2: group = maxgie.getGroup(to) contact = [mem.mid for mem in group.members] mentionMembers(to, contact) if text.lower() == "เชค": add = tagadd["add"] tag = tagadd["tag"] like = settings["commet"] wc = tagadd["wctext"] lv = tagadd["lv"] c = settings["autoCancel"]["members"] b = tagadd["b"] Re = settings["reply"] maxgie.generateReplyMessage(msg.id) maxgie.sendMessags(id, to, "ข้อความแอด :\n"+str(add)+"\n\nข้อความแทค :\n"+str(tag)+"\n\nข้อความเม้น :\n"+str(like)+"\n\nข้อความต้อนรับ :\n"+str(wc)+"\n\nข้อความคนออก :\n"+str(lv)+"\n\nจำนวนค้างเชิญ :\n"+str(c)+" จำนวน\n\nข้อความบล็อค :\n"+str(b)+"\n\nข้อความแทคแชท :\n"+str(Re)) if text.lower() == "/คำสั่ง" or text.lower() == "/help": sas = "😀 Help Message 😀\n" sa = "• คท\n" sa += "• ไอดีเรา\n" sa += "• ชื่อเรา\n" sa += "• ตัสเรา\n" sa += "• รูปเรา\n" sa += "• รูปวีดีโอเรา\n" sa += "• ปกเรา\n" sa += "──────────────\n" sa += "• ข้อมูล\n" sa += "• ออน\n" sa += "• รีบอท\n" sa += "• แทค\n" sa += "• ยกเชิญ\n" sa += "• /ลบรัน\n" sa += "• ก็อป @user\n" sa += "• กลับร่าง\n" sa += "──────────────\n" sa += "• สะกดกิต [พิม'สะกดกิต'เพื่อดูวิธี]\n" sa += "• ตั้งapi [พิมเพื่อดูวิธี]\n" sa += "• ล้างapi [คำที่จะลบ]\n" sa += "• เชคapi\n" sa += "• stag [พิม'stag'เพื่อดูวิธี]\n" sa += "• แปรงคท [MID]\n" sa += "• ยูทูป [ข้อความ]\n" sa += "• image [text(ภาษาอังกฤษ)]\n" sa += "• รูป [ข้อความ(ภาษาไทย)]\n" sa += "• เพลสโต [ชื่อแอพ]\n" sa += "• ตั้งรูปโปรไฟล์ [ลิ้งยูทูป]\n" sa += "• ประกาศ [พิม'ประกาศ'เพื่อดูวิธี]\n" sa += "• ยก [ใส่จำนวนที่จะยกเลิก]\n" sa += "──────────────\n" sa += "• ดำ ส่งคท.\n" sa += "• ขาว ส่งคท.\n" sa += "• ดำ @user\n" sa += "• ล้าง @user\n" sa += "• เชคดำ\n" sa += "• คทดำ\n" sa += "• ล้างดำ\n" sa += "──────────────\n" sa += "• ตั้งต้อนรับ [ข้อความ]\n" sa += "• ตั้งคนออก [ข้อความ]\n" sa += "• ตั้งแอด [ข้อความ]\n" sa += "• ตั้งแทค [ข้อความ]\n" sa += "• ตั้งคอมเม้น [ข้อความ]\n" sa += "──────────────\n" sa += "• เปิดแทค/ปิดแทค\n" sa += "• เปิดแทค2/ปิดแทค2\n" sa += "• เปิดแทค3/ปิดแทค3\n" sa += "• เปิดไลค์/ปิดไลค์\n" sa += "• เปิดคอมเม้น/ปิดคอมเม้น\n" sa += "• เปิดบล็อค/ปิดบล็อค\n" sa += "• เปิดแอด/ปิดแอด\n" sa += "• เปิดกันรัน/ปิดกันรัน\n" sa += "• เปิดต้อนรับ/ปิดต้อนรับ\n" sa += "• เปิดต้อนรับ2/ปิดต้อนรับ2\n" sa += "• เปิดคนออก/ปิดคนออก\n" sa += "• เปิดยกเลิก/ปิดยกเลิก\n" sa += "• เปิดโค๊ดติ๊ก/ปิดโค๊ดติ๊ก\n" sa += "• เปิดติ๊กใหญ่/ปิดติ๊กใหญ่" helps = "{}".format(str(sa)) data = { "type": "flex", "altText": "{}".format(sas), "contents": { "type": "bubble", "styles": { "body": { "backgroundColor": '#EE1289' }, }, "body": { "type": "box", "layout": "vertical", "contents": [ { "type":"text", "text": sas, "size":"xl", "weight":"bold", "color":"#00F5FF", "align":"center" }, { "type":"text", "text": " " }, { "type": "text", "text": "{}".format(sa), "wrap": True, "color": "#000000", "gravity": "center", "size": "md" }, { "type": "text", "text": " " }, { "type":"button", "style":"primary", "color":"#", "action": { "type":"uri", "label":"ผู้สร้าง", "uri":"line://ti/p/~nonbysignal" }, }, ] } } } sendTemplate(to, data) if text.lower() == "!help" or text.lower() == "!คำสั่ง": s = "#FF00FF" sa = "•👊 me\n" sa += "•👊 /me\n" sa += "•👊 คท\n" sa += "•👊 ไอดีเรา\n" sa += "•👊 ชื่อเรา\n" sa += "•👊 ตัสเรา\n" sa += "•👊 รูปเรา\n" sa += "•👊 รูปวีดีโอเรา\n" sa += "•👊 ปกเรา\n" sa += "•👊 ข้อมูล\n" sa += "•👊 รีบอท\n" sa += "•👊 ออน\n" sa += "•👊 /ลบรัน\n" sa += "•👊 เชค\n" ss = "•👊 แทค\n" sa += "•👊 ยกเชิญ" ss += "•👊 ก็อป @user\n" ss += "•👊 กลับร่าง\n" ss += "•👊 ตั้งapi [พิมเพื่อดูวิธี]\n" ss += "•👊 ล้างapi [คำที่จะลบ]\n" ss += "•👊 เชคapi\n" ss += "•👊 stag [พิม'stag'เพื่อดูวิธี]\n" ss += "•👊 แปรงคท [MID]\n" ss += "•👊 ยูทูป [ข้อความ]\n" ss += "•👊 image [text(ภาษาอังกฤษ)]\n" ss += "•👊 รูป [ข้อความ(ภาษาไทย)]\n" ss += "•👊 เพลสโต [ชื่อแอพ]\n" ss += "•👊 ตั้งรูปโปรไฟล์ [ลิ้งยูทูป]\n" ss += "•👊 ประกาศ [พิม'ประกาศ'เพื่อดูวิธี]\n" ss += "•👊 ยก [ใส่จำนวนที่จะยกเลิก]" sd = "•👊 ดำ ส่งคท.\n" sd += "•👊 ขาว ส่งคท.\n" sd += "•👊 ดำ @user\n" sd += "•👊 ล้าง @user\n" sd += "•👊 เชคดำ\n" sd += "•👊 คทดำ\n" sd += "•👊 ล้างดำ\n" sd += "•👊 ตั้งต้อนรับ [ข้อความ]\n" sd += "•👊 ตั้งคนออก [ข้อความ]\n" sd += "•👊 ตั้งแอด [ข้อความ]\n" sd += "•👊 ตั้งแทค [ข้อความ]\n" sd += "•👊 ตั้งคอมเม้น [ข้อความ]\n" sd += "•👊 ตั้งค้างเชิญ [จำนวน]\n" sd += "•👊 ตั้งมุดลิ้ง [ข้อความ]\n" sd += "•👊 ตั้งคนบล็อค [ข้อความ]" se = "•👊 เปิดแทค/ปิดแทค\n" se += "•👊 เปิดแทค2/ปิดแทค2\n" se += "•👊 เปิดแทค3/ปิดแทค3\n" se += "•👊 เปิดไลค์/ปิดไลค์\n" se += "•👊 เปิดคอมเม้น/ปิดคอมเม้น\n" se += "•👊 เปิดบล็อค/ปิดบล็อค\n" se += "•👊 เปิดแอด/ปิดแอด\n" se += "•👊 เปิดกันรัน/ปิดกันรัน\n" se += "•👊 เปิดต้อนรับ/ปิดต้อนรับ\n" se += "•👊 เปิดต้อนรับ2/ปิดต้อนรับ2\n" se += "•👊 เปิดคนออก/ปิดคนออก\n" se += "•👊 เปิดยกเลิก/ปิดยกเลิก\n" se += "•👊 เปิดติ๊กคนเข้า/ปิดติ๊กคนเข้า\n" se += "•👊 เปิดติ๊กคนออก/ปิดติ๊กคนออก\n" se += "•👊 เปิดติ๊กใหญ่/ปิดติ๊กใหญ่" sti = "•👊 เปิดมุดลิ้ง/ปิดมุดลิ้ง\n" sti += "•👊 ตั้งติ๊กคนแอด\n" sti += "•👊 ลบติ๊กคนแอด\n" # sti += "• ตั้งติ๊กแทคแชท\n" # sti += "• ลบติ๊กแทคแชท\n" sti += "•👊 ตั้งติ๊กคนแทค\n" sti += "•👊 ลบติ๊กคนแทค\n" sti += "•👊 ตั้งติ๊กคนเข้า\n" sti += "•👊 ลบติ๊กคนเข้า\n" sti += "•👊 ตั้งติ๊กคนออก\n" sti += "•👊 ลบติ๊กคนออก\n" sti += "•👊 เขียน1 [ข้อความ]\n" sti += "•👊 ไอดีไลน์ [idline]\n" sti += "•👊 ดึง @user\n" sti += "•👊 บล็อค @user\n" sti += "•👊 เพิ่มเพื่อน @user\n" sti += "•👊 ลบเพื่อน @user\n" dataProfile = [ { "type": "bubble", "styles": { "header": {"backgroundColor":"#FFFFFF"}, "hero": {"backgroundColor": "#000000"}, #"separator": True, "separatorColor": "#333333"}, "footer": {"backgroundColor": "#000000"}, #"separator": True, "separatorColor": "#333333"} }, "header": { "type": "box", "layout": "vertical", "spacing": "sm", "contents": [ { "type": "image", "url": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus), "size": "full" }, { "type": "text", "text": "HELP 1", "size": "xxl", "weight": "bold", "align": "center", "color": s }, { "type": "text", "text": " " }, { "type": "text", "text": sa, "color": s, "wrap": True, "gravity": "center", # "size": "md" }, { "type": "text", "text": " " }, { "type":"button", "style":"primary", "color":"#353535", "action":{ "type":"uri", "label":"★ʄທയஆടஷະ★ ", "uri":"line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac" }, }, ] }, }, { "type": "bubble", "styles": { "header": {"backgroundColor": "FFFFFF"}, "hero": {"backgroundColor": "#000000"}, #"separator": True, "separatorColor": "#333333"}, "footer": {"backgroundColor": "#000000"}, #"separator": True, "separatorColor": "#333333"} }, "header": { "type": "box", "layout": "vertical", "spacing": "sm", "contents": [ { "type": "image", "url": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus), "size": "full" }, { "type": "text", "text": "HELP 2", "size": "xxl", "weight": "bold", "align": "center", "color": s }, { "type": "text", "text": " " }, { "type": "text", "text": ss, "color": s, "wrap": True, "gravity": "center", }, { "type": "text", "text": " " }, { "type":"button", "style":"primary", "color":"#353535", "action":{ "type":"uri", "label":"★ʄທയஆടஷະ★", "uri":"line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac" }, }, ] }, }, { "type": "bubble", "styles": { "header": {"backgroundColor": "#FFFFFF"}, "hero": {"backgroundColor": "#000000"}, #"separator": True, "separatorColor": "#333333"}, "footer": {"backgroundColor": "#000000"}, #"separator": True, "separatorColor": "#333333"} }, "header": { "type": "box", "layout": "vertical", "spacing": "sm", "contents": [ { "type": "image", "url": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus), "size": "full" }, { "type": "text", "text": "HELP 3", "size": "xxl", "weight": "bold", "align": "center", "color": s }, { "type": "text", "text": " " }, { "type": "text", "text": sd, "color": s, "wrap": True, "gravity": "center", }, { "type": "text", "text": " " }, { "type":"button", "style":"primary", "color":"#353535", "action":{ "type":"uri", "label":"★ʄທയஆടஷະ★", "uri":"line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac" }, }, ] }, }, { "type": "bubble", "styles": { "header": {"backgroundColor": "#FFFFFF"}, "hero": {"backgroundColor": "#000000"}, #"separator": True, "separatorColor": "#333333"}, "footer": {"backgroundColor": "#000000"}, #"separator": True, "separatorColor": "#333333"} }, "header": { "type": "box", "layout": "vertical", "spacing": "sm", "contents": [ { "type": "image", "url": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus), "size": "full" }, { "type": "text", "text": "HELP 4", "size": "xxl", "weight": "bold", "align": "center", "color": s }, { "type": "text", "text": " " }, # { # "type": "text", # "text": " " # }, # { # "type": "text", # "text": " " # }, { "type": "text", "text": se, "color": s, # "size": "lg", "wrap": True, "gravity": "center", }, #{ # "type": "text", # "text": " " # }, # { # "type": "text", # "text": " " # }, { "type": "text", "text": " " }, # { # "type": "text", # "text": "สนใจบอท ติดต่อได้ที่ปุ่มเลยค้ะ >_<", # "color": "#B5B5B5", # "size": "xs" # }, { "type":"button", "style":"primary", "color":"#353535", "action":{ "type":"uri", "label":"★ʄທയஆടஷະ★ ", "uri":"line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac" }, }, ] }, }, { "type": "bubble", "styles": { "header": {"backgroundColor": "#FFFFFF"}, "hero": {"backgroundColor": "#000000"}, #"separator": True, "separatorColor": "#333333"}, "footer": {"backgroundColor": "#000000"}, #"separator": True, "separatorColor": "#333333"} }, "header": { "type": "box", "layout": "vertical", "spacing": "sm", "contents": [ { "type": "image", "url": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus), "size": "full" }, { "type": "text", "text": "HELP 5", "size": "xxl", "weight": "bold", "align": "center", "color": s }, { "type": "text", "text": " " }, { "type": "text", "text": sti, "color": s, "wrap": True, "gravity": "center", }, { "type": "text", "text": " " }, { "type":"button", "style":"primary", "color":"#353535", "action":{ "type":"uri", "label":"★ʄທയஆടஷະ★ ", "uri":"line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac" }, }, ] }, }, ] data = { "type": "flex", "altText": "Help Message", "contents": { "type": "carousel", "contents": dataProfile } } sendTemplate(to, data) #===================================================================== if text.lower() == "help" or text.lower() == "คำสั่ง": s = "#FFFFFF" sa = "•✨ me\n" sa += "•✨ /me\n" sa += "•✨ คท\n" sa += "•✨ ไอดีเรา\n" sa += "•✨ ชื่อเรา\n" sa += "•✨ ตัสเรา\n" sa += "•✨ รูปเรา\n" sa += "•✨ รูปวีดีโอเรา\n" sa += "•✨ ปกเรา\n" sa += "•✨ ข้อมูล\n" sa += "•✨ รีบอท\n" sa += "•✨ ออน\n" sa += "•✨ /ลบรัน\n" sa += "•✨ เชค\n" ss = "•✨ แทค\n" sa += "•✨ ยกเชิญ" ss += "•✨ ก็อป @user\n" ss += "•✨ กลับร่าง\n" ss += "•✨ ตั้งapi [พิมเพื่อดูวิธี]\n" ss += "•✨ ล้างapi [คำที่จะลบ]\n" ss += "•✨ เชคapi\n" ss += "•✨ stag [พิม'stag'เพื่อดูวิธี]\n" ss += "•✨ แปรงคท [MID]\n" ss += "•✨ยูทูป [ข้อความ]\n" ss += "•✨ image [text(ภาษาอังกฤษ)]\n" ss += "•✨ รูป [ข้อความ(ภาษาไทย)]\n" ss += "•✨ เพลสโต [ชื่อแอพ]\n" ss += "•✨ ตั้งรูปโปรไฟล์ [ลิ้งยูทูป]\n" ss += "•✨ ประกาศ [พิม'ประกาศ'เพื่อดูวิธี]\n" ss += "•✨ ยก [ใส่จำนวนที่จะยกเลิก]" sd = "•✨ ดำ ส่งคท.\n" sd += "•✨ ขาว ส่งคท.\n" sd += "•✨ ดำ @user\n" sd += "•✨ ล้าง @user\n" sd += "•✨ เชคดำ\n" sd += "•✨ คทดำ\n" sd += "•✨ ล้างดำ\n" sd += "•✨ ตั้งต้อนรับ [ข้อความ]\n" sd += "•✨ ตั้งคนออก [ข้อความ]\n" sd += "•✨ ตั้งแอด [ข้อความ]\n" sd += "•✨ ตั้งแทค [ข้อความ]\n" sd += "•✨ ตั้งคอมเม้น [ข้อความ]\n" sd += "•✨ ตั้งค้างเชิญ [จำนวน]\n" sd += "•✨ ตั้งมุดลิ้ง [ข้อความ]\n" sd += "•✨ ตั้งคนบล็อค [ข้อความ]" se = "•✨ เปิดแทค/ปิดแทค\n" se += "•✨ เปิดแทค2/ปิดแทค2\n" se += "•✨ เปิดแทค3/ปิดแทค3\n" se += "•✨ เปิดไลค์/ปิดไลค์\n" se += "•✨ เปิดคอมเม้น/ปิดคอมเม้น\n" se += "•✨ เปิดบล็อค/ปิดบล็อค\n" se += "•✨ เปิดแอด/ปิดแอด\n" se += "•✨ เปิดกันรัน/ปิดกันรัน\n" se += "•✨ เปิดต้อนรับ/ปิดต้อนรับ\n" se += "•✨ เปิดต้อนรับ2/ปิดต้อนรับ2\n" se += "•✨ เปิดคนออก/ปิดคนออก\n" se += "•✨ เปิดยกเลิก/ปิดยกเลิก\n" se += "•✨ เปิดติ๊กคนเข้า/ปิดติ๊กคนเข้า\n" se += "•✨ เปิดติ๊กคนออก/ปิดติ๊กคนออก\n" se += "•✨ เปิดติ๊กใหญ่/ปิดติ๊กใหญ่" sti = "•✨ เปิดมุดลิ้ง/ปิดมุดลิ้ง\n" sti += "•✨ ตั้งติ๊กคนแอด\n" sti += "•✨ ลบติ๊กคนแอด\n" # sti += "• ตั้งติ๊กแทคแชท\n" # sti += "• ลบติ๊กแทคแชท\n" sti += "•✨ ตั้งติ๊กคนแทค\n" sti += "•✨ ลบติ๊กคนแทค\n" sti += "•✨ ตั้งติ๊กคนเข้า\n" sti += "•✨ ลบติ๊กคนเข้า\n" sti += "•✨ ตั้งติ๊กคนออก\n" sti += "•✨ ลบติ๊กคนออก\n" sti += "•✨ เขียน1 [ข้อความ]\n" sti += "•✨ ไอดีไลน์ [idline]\n" sti += "•✨ ดึง @user\n" sti += "•✨ บล็อค @user\n" sti += "•✨ เพิ่มเพื่อน @user\n" sti += "•✨ ลบเพื่อน @user\n" dataProfile = [ { "type": "bubble", "styles": { "header": {"backgroundColor":"#EE1289"}, "hero": {"backgroundColor": "#000000"}, #"separator": True, "separatorColor": "#333333"}, "footer": {"backgroundColor": "#000000"}, #"separator": True, "separatorColor": "#333333"} }, "header": { "type": "box", "layout": "vertical", "spacing": "sm", "contents": [ { "type": "image", "url": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus), "size": "full" }, { "type": "text", "text": "• คำสั่งส่วนตัว •", "size": "xxl", "weight": "bold", "align": "center", "color": s }, { "type": "text", "text": " " }, { "type": "text", "text": sa, "color": s, "wrap": True, "gravity": "center", # "size": "md" }, { "type": "text", "text": " " }, { "type":"button", "style":"primary", "color":"#00F5FF", "action":{ "type":"uri", "label":"★ʄທയஆടஷະ★ ", "uri":"line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac" }, }, ] }, }, { "type": "bubble", "styles": { "header": {"backgroundColor": "#EE1289"}, "hero": {"backgroundColor": "#000000"}, #"separator": True, "separatorColor": "#333333"}, "footer": {"backgroundColor": "#000000"}, #"separator": True, "separatorColor": "#333333"} }, "header": { "type": "box", "layout": "vertical", "spacing": "sm", "contents": [ { "type": "image", "url": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus), "size": "full" }, { "type": "text", "text": "• คำสั่งพิเศษ •", "size": "xxl", "weight": "bold", "align": "center", "color": s }, { "type": "text", "text": " " }, { "type": "text", "text": ss, "color": s, "wrap": True, "gravity": "center", }, { "type": "text", "text": " " }, { "type":"button", "style":"primary", "color":"#00F5FF", "action":{ "type":"uri", "label":"★ʄທയஆടஷະ★", "uri":"line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac" }, }, ] }, }, { "type": "bubble", "styles": { "header": {"backgroundColor": "#EE1289"}, "hero": {"backgroundColor": "#000000"}, #"separator": True, "separatorColor": "#333333"}, "footer": {"backgroundColor": "#000000"}, #"separator": True, "separatorColor": "#333333"} }, "header": { "type": "box", "layout": "vertical", "spacing": "sm", "contents": [ { "type": "image", "url": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus), "size": "full" }, { "type": "text", "text": "• คำสั่งเปิด/ปิด •", "size": "xxl", "weight": "bold", "align": "center", "color": s }, { "type": "text", "text": " " }, { "type": "text", "text": sd, "color": s, "wrap": True, "gravity": "center", }, { "type": "text", "text": " " }, { "type":"button", "style":"primary", "color":"#00F5FF", "action":{ "type":"uri", "label":"★ʄທയஆടஷະ★", "uri":"line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac" }, }, ] }, }, { "type": "bubble", "styles": { "header": {"backgroundColor": "#EE1289"}, "hero": {"backgroundColor": "#000000"}, #"separator": True, "separatorColor": "#333333"}, "footer": {"backgroundColor": "#000000"}, #"separator": True, "separatorColor": "#333333"} }, "header": { "type": "box", "layout": "vertical", "spacing": "sm", "contents": [ { "type": "image", "url": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus), "size": "full" }, { "type": "text", "text": "• คำสั่งตั้งค่า/ติดดำ •", "size": "xxl", "weight": "bold", "align": "center", "color": s }, { "type": "text", "text": " " }, # { # "type": "text", # "text": " " # }, # { # "type": "text", # "text": " " # }, { "type": "text", "text": se, "color": s, # "size": "lg", "wrap": True, "gravity": "center", }, #{ # "type": "text", # "text": " " # }, # { # "type": "text", # "text": " " # }, { "type": "text", "text": " " }, # { # "type": "text", # "text": "สนใจบอท ติดต่อได้ที่ปุ่มเลยค้ะ >_<", # "color": "#B5B5B5", # "size": "xs" # }, { "type":"button", "style":"primary", "color":"#00F5FF", "action":{ "type":"uri", "label":"★ʄທയஆടஷະ★ ", "uri":"line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac" }, }, ] }, }, { "type": "bubble", "styles": { "header": {"backgroundColor": "#EE1289"}, "hero": {"backgroundColor": "#000000"}, #"separator": True, "separatorColor": "#333333"}, "footer": {"backgroundColor": "#000000"}, #"separator": True, "separatorColor": "#333333"} }, "header": { "type": "box", "layout": "vertical", "spacing": "sm", "contents": [ { "type": "image", "url": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus), "size": "full" }, { "type": "text", "text": "• คำสั่งทั่วไป •", "size": "xxl", "weight": "bold", "align": "center", "color": s }, { "type": "text", "text": " " }, { "type": "text", "text": sti, "color": s, "wrap": True, "gravity": "center", }, { "type": "text", "text": " " }, { "type":"button", "style":"primary", "color":"#00F5FF", "action":{ "type":"uri", "label":"★ʄທയஆടஷະ★ ", "uri":"line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac" }, }, ] }, }, ] data = { "type": "flex", "altText": "Help Message", "contents": { "type": "carousel", "contents": dataProfile } } sendTemplate(to, data) #===================================================================== elif msg.text.lower().startswith("ก็อป "): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) clone = ast.literal_eval(msg.contentMetadata['MENTION']) clones = clone['MENTIONEES'] target = [] for clone in clones: if clone["M"] not in target: target.append(clone["M"]) for she in target: BackupProfile = maxgie.getContact(sender) Save1 = "http://dl.profile.line-cdn.net/{}".format(BackupProfile.pictureStatus);Save2 = "{}".format(BackupProfile.displayName);ProfileMe["PictureMe"] = Save1;ProfileMe["NameMe"] = Save2 contact = maxgie.getContact(she);ClonerV2(she) sendMention(to, contact.mid, "=͟͟͞͞➳ คุณกำลังก็อปปี้", "สำเร็จแล้ว >_<");maxgie.sendContact(to, str(BackupProfile.mid));maxgie.sendContact(to, str(contact.mid)) elif text.lower() == "กลับร่าง": try: maxgiestatus = maxgie.getProfile() maxgieName = maxgie.getProfile() maxgieName.statusMessage = ProfileMe["statusMessage"] maxgieName.pictureStatus = str(ProfileMe["pictureStatus"]) maxgie.updateProfile(maxgiestatus) maxgieName.displayName = ProfileMe["NameMe"] maxgie.updateProfile(maxgieName) path = maxgie.downloadFileURL(ProfileMe["PictureMe"]) maxgie.updateProfilePicture(path) coverId = ProfileMe["coverId"] maxgie.updateProfileCoverById(coverId) BackupProfile = maxgie.getContact(sender) sendMention(to, BackupProfile.mid, "=͟͟͞͞➳ กลับบัญชีเดิมเรียบร้อย", ">_<");maxgie.sendContact(to, str(BackupProfile.mid)) except Exception as error: maxgie.unsendMessage(msg_id) duc1(to, "🌟คุณยังไม่ได้ก๊อปปี้🌟") elif msg.text.lower().startswith("."): text = msg.text.lower().replace("."," ") maxgie.unsendMessage(msg_id) duc1(msg.to,text) if text.lower() == "คท": maxgie.generateReplyMessage(msg.id) maxgie.sendReplyMessage(msg.id, to, None, contentMetadata={'mid': maxgieMID}, contentType=13) if text.lower() == "mid" or text.lower() == "ไอดีเรา": maxgie.generateReplyMessage(msg.id) maxgie.sendReplyMessage(msg.id, to,maxgieMID) elif text.lower() == "myname" or text.lower() == "ชื่อเรา": h = maxgie.getContact(maxgieMID) maxgie.generateReplyMessage(msg.id) maxgie.sendReplyMessage(msg.id, to, "「 ชื่อของคุณ 」\n"+str(h.displayName)) elif text.lower() == "mybio" or text.lower() == "ตัสเรา": h = maxgie.getContact(maxgieMID) maxgie.generateReplyMessage(msg.id) maxgie.sendReplyMessage(msg.id, to, "「 ตัสของคุณ 」\n"+str(h.statusMessage)) elif text.lower() == "mypicture" or text.lower() == "รูปเรา": h = maxgie.getContact(maxgieMID) image = "http://dl.profile.line-cdn.net/" + h.pictureStatus maxgie.generateReplyMessage(msg.id) maxgie.sendReplyImageWithURL(msg.id, to, image) elif text.lower() == "myvideo" or text.lower() == "รูปวีดีโอเรา": h = maxgie.getContact(maxgieMID) if h.videoProfile == None: return maxgie.sendMessage(to, "คุณไม่ได้ใส่รูปวีดีโอ >_<") maxgie.generateReplyMessage(msg.id) maxgie.sendReplyVideoWithURL(msg.id, to,"http://dl.profile.line-cdn.net/" + h.pictureStatus + "/vp") elif text.lower() == "mycover" or text.lower() == "ปกเรา": h = maxgie.getContact(maxgieMID) cu = maxgie.getProfileCoverURL(maxgieMID) image = str(cu) maxgie.generateReplyMessage(msg.id) maxgie.sendReplyImageWithURL(msg.id, to, image) elif msg.text in ["ดึง"]: apalo["winvite"] = True maxgie.unsendMessage(msg_id) duc1(to, "🌟ส่งคทที่จะดึงลงมา..🌟") elif "อัพชื่อ " in text.lower(): if msg._from in admin: proses = text.split(" ") string = text.replace(proses[0] + " ","") profile_A = maxgie.getProfile() profile_A.displayName = string maxgie.updateProfile(profile_A) maxgie.sendMessage(msg.to,"Update to :\n" + string) print ("Update Name") elif "อัพตัส " in msg.text.lower(): if msg._from in admin: proses = text.split(" ") string = text.replace(proses[0] + " ","") profile_A = maxgie.getProfile() profile_A.statusMessage = string maxgie.updateProfile(profile_A) maxgie.sendMessage(msg.to,"Succes Update :\n" + string) print ("Update Bio Succes") elif text.lower() == "อัพดิส": sets["changePictureProfile"] = True maxgie.unsendMessage(msg_id) duc1(to, "🌟ส่งรูปที่จะอัพลงมาครับ..🌟") elif text.lower() == 'เปิดออก': did["join"] = True maxgie.unsendMessage(msg_id) duc1(to, "🌟ออกแชทรวมอัตโนมัติ (เปิด) ใช้งาน🌟") elif text.lower() == 'ปิดออก': did["join"] = False maxgie.unsendMessage(msg_id) duc1(to, "🌟ออกแชทรวมอัตโนมัติ (ปิด) ใช้งาน🌟") if text.lower() == "ออน1": cover = maxgie.getProfileCoverURL(maxgie.profile.mid) pp = maxgie.getProfile().pictureStatus profile = "https://profile.line-scdn.net/" + str(pp) name = maxgie.getProfile().displayName status = maxgie.getProfile().statusMessage tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) eltime = time.time() - mulai van = ggggg(eltime) van2 = "\n\nวันที่ :"+ datetime.strftime(timeNow,'%d-%m-%Y')+"\n───────────\nเวลา:"+ datetime.strftime(timeNow,'%H:%M:%S')+"\n\n" data={ "type":"flex", "altText":"Weclome", "contents":{ "type": "carousel", "contents": [ { "type": "bubble", "styles": { "header": {"backgroundColor": "#EE1289", "separator": True, "separatorColor": "#EE1289"}, "body": {"backgroundColor": "#000000", "separator": True, "separatorColor": "#000000"}, "footer": {"backgroundColor": "#000000", "separator": True, "separatorColor": "#000000"} }, "header": { "type": "box", "layout": "horizontal", "contents": [ { "type": "text", "text": "runtime", "align": "center", "size": "lg", "weight": "bold", "color": "#00F5FF", "wrap": True } ] }, "type": "bubble", "body": { "contents": [ { "contents": [ { "url": profile, "type": "image" }, { "type": "separator", "color": "#00F5FF" }, { "url": profile, "type": "image" } ], "type": "box", "spacing": "md", "layout": "horizontal" }, { "type": "separator", "color": "#00F5FF" }, { "contents": [ { "text": "ระยะเวลาของบอท", "size": "md", "align": "center", "color": "#00F5FF", "wrap": True, "weight": "bold", "type": "text" } ], "type": "box", "spacing": "md", "layout": "vertical" }, { "type": "separator", "color": "#00F5FF" }, { "contents": [ { "contents": [ { "type": "text", "text": van, "align": "center", "size": "xs", "weight": "bold", "color": "#00F5FF", "wrap": True } ], "type": "box", "layout": "baseline" }, { "contents": [ { "url": profile, "type": "icon", "size": "md" }, { "text": " is bot line ★ʄທയஆടஷະ★ ", "size": "xs", "margin": "none", "color": "#00F5FF", "wrap": True, "weight": "regular", "type": "text" } ], "type": "box", "layout": "baseline" } ], "type": "box", "layout": "vertical" } ], "type": "box", "spacing": "md", "layout": "vertical" }, "footer": { "type": "box", "layout": "horizontal", "spacing": "sm", "contents": [ { "type": "button", "flex": 2, "style": "primary", "color": "#00F5FF", "height": "sm", "action": { "type": "uri", "label": "ติดต่อเชล", "uri": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac", } }, { "flex": 3, "type": "button", "style": "primary", "color": "#00F5FF", "margin": "sm", "height": "sm", "action": { "type": "uri", "label": "ติดต่อผู้สร้าง", "uri": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac", } } ] } }, { "type": "bubble", "styles": { "header": {"backgroundColor": "#EE1289", "separator": True, "separatorColor": "#EE1289"}, "body": {"backgroundColor": "#000000", "separator": True, "separatorColor": "#000000"}, "footer": {"backgroundColor": "#000000", "separator": True, "separatorColor": "#000000"} }, "header": { "type": "box", "layout": "horizontal", "contents": [ { "type": "text", "text": "ปฏิทิน ", "align": "center", "size": "lg", "weight": "bold", "color": "#00F5FF", "wrap": True } ] }, "type": "bubble", "body": { "contents": [ { "contents": [ { "url": profile, "type": "image" }, { "type": "separator", "color": "#00F5FF" }, { "url": profile, "type": "image" } ], "type": "box", "spacing": "md", "layout": "horizontal" }, { "type": "separator", "color": "#00F5FF" }, { "contents": [ { "text": "วันเดือนปีและเวลา", "size": "md", "align": "center", "color": "#00F5FF", "wrap": True, "weight": "bold", "type": "text" } ], "type": "box", "spacing": "md", "layout": "vertical" }, { "type": "separator", "color": "#00F5FF" }, { "contents": [ { "contents": [ { "type": "text", "text": van2, "align": "center", "size": "xs", "weight": "bold", "color": "#00F5FF", "wrap": True } ], "type": "box", "layout": "baseline" }, { "contents": [ { "url": profile, "type": "icon", "size": "md" }, { "text": " is bot line ★ʄທയஆടஷະ★ ", "size": "xs", "margin": "none", "color": "#00F5FF", "wrap": True, "weight": "regular", "type": "text" } ], "type": "box", "layout": "baseline" } ], "type": "box", "layout": "vertical" } ], "type": "box", "spacing": "md", "layout": "vertical" }, "footer": { "type": "box", "layout": "horizontal", "spacing": "sm", "contents": [ { "type": "button", "flex": 2, "style": "primary", "color": "#00F5FF", "height": "sm", "action": { "type": "uri", "label": "ติดต่อเชล", "uri": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac", } }, { "flex": 3, "type": "button", "style": "primary", "color": "#00F5FF", "margin": "sm", "height": "sm", "action": { "type": "uri", "label": "ติดต่อผู้สร้าง", "uri": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac", } } ] } } ] } } sendTemplate(to, data) if text.lower() == "ออน2" or text.lower() == "runtime": contact = maxgie.getContact(sender) timeNow = time.time() - Start runtime = timeChange(timeNow) tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) a = "วันที่"+ datetime.strftime(timeNow,'%d-%m-%Y')+"🇹🇭เวลา"+ datetime.strftime(timeNow,'%H:%M:%S')+"\n" run = "「 เวลาออน 」\n" run += runtime data = { "type": "flex", "altText": "{}".format(run), "contents": { "styles": { "body": { "backgroundColor": "#EE1289" }, "footer": { "backgroundColor": "#EE1289" } }, "type": "bubble", "body": { "contents": [ { "contents": [ { "url": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus), "type": "image" }, { "type": "separator", "color": "#00F5FF" }, { "url": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus), "type": "image" } ], "type": "box", "spacing": "md", "layout": "horizontal" }, { "type": "separator", "color": "#00F5FF" }, { "contents": [ { "text": "ระยะเวลาทำงาน", "size": "lg", "align": "center", "color": "#00F5FF", "wrap": True, "weight": "bold", "type": "text" } ], "type": "box", "spacing": "md", "layout": "vertical" }, { "type": "separator", "color": "#00F5FF" }, { "contents": [ { "contents": [ { "text": "{}".format(run), "size": "lg", "align": "center", "margin": "none", "color": "#00F5FF", "wrap": True, "weight": "regular", "type": "text" } ], "type": "box", "layout": "baseline" }, ], "type": "box", "layout": "vertical" } ], "type": "box", "spacing": "md", "layout": "vertical" }, "footer": { "contents": [ { "contents": [ { "contents": [ { "text": "★ʄທയஆടஷະ★ ", "size": "xl", "action": { "uri": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac", "type": "uri", "label": "Add Maker" }, "margin": "xl", "align": "center", "color": "#00F5FF", "weight": "bold", "type": "text" } ], "type": "box", "layout": "baseline" } ], "type": "box", "layout": "horizontal" } ], "type": "box", "layout": "vertical" } } } sendTemplate(to, data) if text.lower() == "me": cover = maxgie.getProfileCoverURL(maxgie.profile.mid) pp = maxgie.getProfile().pictureStatus profile = "https://profile.line-scdn.net/" + str(pp) name = maxgie.getProfile().displayName status = maxgie.getProfile().statusMessage s = temp["te"] a = temp["t"] data={"type":"flex","altText":"{} sendFlex".format(name),"contents":{"type":"bubble",'styles': {"body":{"backgroundColor":a}},"hero":{"type":"image","url":cover,"size":"full","aspectRatio":"20:13","aspectMode":"cover"},"body":{"type":"box","layout":"vertical","contents":[{"type":"text","text":" "},{"type":"image","url":profile,"size":"lg"},{"type":"text","text":" "},{"type":"text","text":name,"size":"xl","weight":"bold","color":s,"align":"center"},{"type":"text","text":" "},{"type":"text","text":status,"align":"center","size":"xs","color":s,"wrap":True},{"type":"text","text":" "},{"type":"button","style":"primary","color":"#EE1289","action":{"type":"uri","label":"★ʄທയஆടஷະ★ ","uri":"https://sv1.picz.in.th/images/2019/05/19/wubKKl.gif"}}]}}} sendTemplate(to, data) elif text.lower() == "me2": s = temp["te"] a = temp["t"] contact = maxgie.getContact(maxgieMID) cover = maxgie.getProfileCoverURL(maxgieMID) dataProfile = [ { "type": "bubble", "styles": { "header": {"backgroundColor": a}, "body": {"backgroundColor": a},# "separator": True, "separatorColor": "#333333"}, "footer": {"backgroundColor": a, "separator": True, "separatorColor": s} }, "hero": { "type": "image", "url": "https://obs.line-scdn.net/{}".format(contact.pictureStatus), "size": "full", "aspectRatio": "1:1", "aspectMode": "fit", }, "body": { "type": "box", "layout": "vertical", "spacing": "sm", "contents": [ { "type": "text", "text": "{}".format(contact.displayName), "align": "center", "weight": "bold", "color": s, "size": "lg", 'flex': 1 }, { "type": "text", "text": " รูปโปรไฟล์ ", "weight": "bold", "align": "center", "color": s, "size": "lg", 'flex': 1, }, ] }, "footer": { "type": "box", "layout": "vertical", "spacing": "sm", "contents": [ { "type": "box", "layout": "baseline", "contents": [ { "type": "icon", "url": "https://os.line.naver.jp/os/p/"+maxgieMID, "size": "md" }, { "type": "text", "text": "★ʄທയஆടஷະ★ ", "align": "center", "color": s, "size": "md", "action": { "type": "uri", "uri": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac" } }, { "type": "spacer", "size": "sm", } ] } ] } }, { "type": "bubble", "styles": { "header": {"backgroundColor": a}, "body": {"backgroundColor": a}, "footer": {"backgroundColor": a, "separator": True, "separatorColor": s} }, "hero": { "type": "image", "url": "{}".format(cover), "size": "full", "aspectRatio":"20:13", "aspectMode":"cover" }, "body": { "type": "box", "layout": "vertical", "spacing": "sm", "contents": [ { "type": "text", "text": "{}".format(contact.mid), "align": "center", "color": s, "size": "sm", "flex": 1, }, { "type": "text", "text": "รูปปกพื้นหลัง ", "weight": "bold", "align": "center", "color": s, "size": "lg", 'flex': 1, }, ] }, "footer": { "type": "box", "layout": "vertical", "spacing": "sm", "contents": [ { "type": "box", "layout": "baseline", "contents": [ { "type": "icon", "url": "https://os.line.naver.jp/os/p/"+maxgieMID, "size": "md" }, { "type": "text", "text": "★ʄທയஆടஷະ★ ", "align": "center", "color": s, "size": "md", "action": { "type": "uri", "uri": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac" } }, { "type": "spacer", "size": "sm", } ] } ] } }, { "type": "bubble", "styles": { "header": {"backgroundColor": a}, "body": {"backgroundColor": a},# "separator": True, "separatorColor": "#333333"}, "footer": {"backgroundColor": a, "separator": True, "separatorColor": s} }, "body": { "type": "box", "layout": "vertical", "spacing": "sm", "contents": [ { "type": "text", "text": "ชื่อ. ", "size": "lg", "weight": "bold", "align": "center", "color": s }, { "type": "text", "text": "{}".format(contact.displayName), "align": "center", "color": s, "size": "md" }, { "type": "text", "text": "-", "align": "center", "color": a, "size": "sm", }, { "type": "text", "text": "สเตตัส ", "size": "lg", "weight": "bold", "align": "center", "color": s }, { "type": "text", "text": "{}".format(contact.statusMessage), "align": "center", "color": s, "wrap": True, "size": "md" }, ] }, "footer": { "type": "box", "layout": "vertical", "spacing": "sm", "contents": [ { "type": "box", "layout": "baseline", "contents": [ { "type": "icon", "url": "https://os.line.naver.jp/os/p/"+maxgieMID, "size": "md" }, { "type": "text", "text": "★ʄທയஆടஷະ★ ", "align": "center", "color": s, "size": "md", "action": { "type": "uri", "uri": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac" } }, { "type": "spacer", "size": "sm" } ] } ] } } ] data = { "type": "flex", "altText": "{}".format(contact.displayName), "contents": { "type": "carousel", "contents": dataProfile } } sendTemplate(to, data) if text.lower() == "เรา": contact = maxgie.getContact(sender) sendTemplate(to,{"type":"flex","altText": "★ʄທയஆടஷະ★ ","contents":{"type":"bubble","footer":{"type":"box","layout":"horizontal","contents":[{"color":"#333333","size":"xs","wrap":True,"action":{"type":"uri","uri":"https://sv1.picz.in.th/images/2019/05/19/wubKKl.gif"},"type":"text","text":"★ʄທയஆടஷະ★ ","align":"center","weight":"bold"},{"type":"separator","color":"#FF3333"},{"color":"#FF3333","size":"xs","wrap":True,"action":{"type":"uri","uri":"line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac"},"type":"text","text":"ผู้สร้าง","align":"center","weight":"bold"}]},"styles":{"footer":{"backgroundColor":"#000000"},"body":{"backgroundColor":"#CCFFFF"}},"body":{"type":"box","contents":[{"type":"box","contents":[{"type":"separator","color":"#FF3333"},{"aspectMode":"cover","gravity":"bottom","aspectRatio":"1:1","size":"sm","type":"image","url":"https://sv1.picz.in.th/images/2019/05/19/wubKKl.gif"},{"type":"separator","color":"#FF3333"},{"type":"image","aspectMode":"cover","aspectRatio":"1:1","size":"sm","url":"https://sv1.picz.in.th/images/2019/05/19/wubKKl.gif"},{"type":"separator","color":"#FF3333"},{"type":"image","aspectMode":"cover","aspectRatio":"1:1","size":"sm","url":"https://img.live/images/2019/02/10/1549778907829.jpg"},{"type":"separator","color":"#FF3333"},{"type":"image","aspectMode":"cover","aspectRatio":"1:1","size":"sm","url":"https://sv1.picz.in.th/images/2019/05/19/wubKKl.gif"},{"type":"separator","color":"#FF3333"}],"layout":"vertical","spacing":"none","flex":1},{"type":"separator","color":"#FF3333"},{"type":"box","contents":[{"type":"separator","color":"#FF3333"},{"color":"#FF3333","size":"md","wrap":True,"type":"text","text":" ★ʄທയஆടஷະ★ ","weight":"bold"},{"type":"separator","color":"#FF3333"},{"color":"#FF3333","size":"md","wrap":True,"type":"text","text":"{}".format(contact.displayName),"weight":"bold"},{"type":"separator","color":"#FF3333"},{"color":"#FF3333","size":"xs","wrap":True,"type":"text","text":"Status Profile:","weight":"bold"},{"type":"text","text":"{}".format(contact.statusMessage),"size":"xxs","wrap":True,"color":"#FF3333"}],"layout":"vertical","flex":2}],"layout":"horizontal","spacing":"md"},"hero":{"aspectMode":"cover","margin":"xxl","aspectRatio":"1:1","size":"full","type":"image","url":"https://obs.line-scdn.net/{}".format(contact.pictureStatus)}}}) elif text.lower() == "/runtime" or text.lower() == "/ออน": timeNow = time.time() - Start runtime = timeChange(timeNow) run = "เวลาออน \n" run += runtime helps = "{}".format(str(run)) data = { "type": "text", "text": "{}".format(str(run)), "sentBy": { "label": "{}".format(maxgie.getContact(maxgieMID).displayName), "iconUrl": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus), "linkUrl": "line://nv/profilePopup/mid=uca43cd15fb994f5e04c0984b7c1693ef" } } sendTemplate(to, data) elif text.lower() == "/runtime" or text.lower() == "!ออน": timeNow = time.time() - Start runtime = timeChange(timeNow) run = "⇨ เวลาออน ⇦\n" run += runtime helps = "{}".format(str(run)) data = { "type": "text", "text": "{}".format(str(run)), "sentBy": { "label": "{}".format(maxgie.getContact(maxgieMID).displayName), "iconUrl": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus), "linkUrl": "line://nv/profilePopup/mid=ubd86e8c77559b1493f0ad64b1dba2d6c" } } sendTemplate(to, data) if text.lower() == "ออน" or text.lower() == "runtime": timeNow = time.time() - Start runtime = timeChange(timeNow) run = "⇨ เวลาออน ⇦\n" run += runtime data = { "type": "flex", "altText": "{}".format(run), "contents": { "type": "bubble", "styles": { "body": { "backgroundColor": '#EE1289' }, }, "hero": { "type": "image", "url": "https://obs.line-scdn.net/{}".format(maxgie.getContact(sender).pictureStatus), "size": "full", "aspectRatio": "1:1", "aspectMode": "fit", }, "body": { "type": "box", "layout": "vertical", "contents": [ # { # "type": "image", #"url": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus), # "size": "full" # }, { "type": "text", "text": "{}".format(run), "wrap": True, "color": "#000000", "align": "center", "gravity": "center", "size": "md" }, ] } } } sendTemplate(to, data) elif text.lower() == "รีบอท" or text.lower() == "reset": gifnya = ["https://sv1.picz.in.th/images/2019/05/19/wubKKl.gif"] data = { "type": "template", "altText": "กำลังรีบอท...", "template": { "type": "image_carousel", "columns": [ { "imageUrl": "{}".format(random.choice(gifnya)), "size": "full", "action": { "type": "uri", "uri": "line://ti/p/~nonbysignal" } } ] } } sendTemplate(to, data) restartBot() time.sleep(1) ga = "สำเร็จแล้ว (`・ω・´)" data = { "type": "text", "text": "{}".format(str(ga)), "sentBy": { "label": "รีบอทสำเร็จ...", "iconUrl": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus), "linkUrl": "line://ti/p/~nonbysignal" } } sendTemplate(to, data) elif text.lower() == "Sp" or text.lower() == "สปีด": contact = maxgie.getContact(sender) start = time.time() maxgie.sendMessage(to, "ทดสอบความเร็ว") elapsed_time = time.time() - start took = time.time() - start a = " สปีดบอท \nความเร็วปิง ✔️\n Took : %.3fms ✔️\nความเร็วสปีด: %.10f ✔️" % (took,elapsed_time) LINKFOTO = "https://os.line.naver.jp/os/p/" + sender LINKVIDEO = "https://os.line.naver.jp/os/p/" + sender + "/vp" data = { "type": "flex", "altText": "{}".format(a), "contents": { "type": "bubble", 'styles': { "header": { "backgroundColor": '#13C500' }, "footer": { "backgroundColor": '#000000' }, }, "header": { "type": "box", "layout": "vertical", "contents": [ { "type": "image", "url": "https://obs.line-scdn.net/{}".format(contact.pictureStatus), "size": "full", "aspectRatio": "1:1", "aspectMode": "fit", }, { "type": "box", "layout": "vertical", "margin": "lg", "spacing": "sm", "contents": [ { "type": "box", "layout": "baseline", "spacing": "sm", "contents": [ { "type": "text", "text": "{}".format(a), "color": "#000000", "wrap": True, "size": "sm", "flex": 1 } ] } ] } ] }, "footer": { "type": "box", "layout": "vertical", "spacing": "sm", "contents": [ { "type": "button", "style": "link", "height": "sm", "action": { "type": "uri", "label": "★ʄທയஆടஷະ★ ", "uri": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac" } }, { "type": "spacer", "size": "sm", } ], "flex": 0 } } } sendTemplate(to, data) elif "คอล" in msg.text.lower(): if msg.toType == 2: sep = msg.text.split(" ") resp = msg.text.replace(sep[0] + " ","") num = int(resp) try: maxgie.unsendMessage(msg_id) duc1(to, "เริ่มการเชิญ....") except: pass for var in range(num): group = maxgie.getGroup(msg.to) members = [mem.mid for mem in group.members] maxgie.acquireGroupCallRoute(msg.to) maxgie.inviteIntoGroupCall(msg.to, contactIds=members) maxgie.unsendMessage(msg_id) duc1(to, "เชิญเรียบร้อย") elif msg.text.startswith("โทร"): dan = text.split(" ") num = int(dan[1]) ret_ = "╭──[ เชิญโทรสำเร็จ ]" if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if mention["M"] not in lists: lists.append(mention["M"]) for ls in lists: for var in range(0,num): group = maxgie.getGroup(to) members = [ls] maxgie.acquireGroupCallRoute(to) maxgie.inviteIntoGroupCall(to, contactIds=members) ret_ += "\n├> @!" ret_ += "\n╰─── ★ʄທയஆടஷະ★ " maxgie.sendPhu(to, ret_, lists) elif "Spam " in msg.text: txt = msg.text.split(" ") jmlh = int(txt[2]) teks = msg.text.replace("Spam "+str(txt[1])+" "+str(jmlh)+" ","") tulisan = jmlh * (teks+"\n") if txt[1] == "on": if jmlh <= 100000: for x in range(jmlh): maxgie.sendMessage(msg.to, teks) else: maxgie.sendMessage(msg.to, "Out of Range!") elif txt[1] == "off": if jmlh <= 100000: maxgie.sendMessage(msg.to, tulisan) elif text.lower() == 'ข้อมูล' or text.lower() == "about": try: arr = [] owner = "ubd86e8c77559b1493f0ad64b1dba2d6c" creator = maxgie.getContact(owner) contact = maxgie.getContact(maxgieMID) grouplist = maxgie.getGroupIdsJoined() contactlist = maxgie.getAllContactIds() blockedlist = maxgie.getBlockedContactIds() IdsInvit = maxgie.getGroupIdsInvited() times = time.time() - Start runtime = timeChange(times) ret_ = "╭───「 About Your 」" ret_ += "\n├ ชื่อ : {}".format(contact.displayName) ret_ += "\n├ กลุ่ม : {}".format(str(len(grouplist))) ret_ += "\n├ เพื่อน : {}".format(str(len(contactlist))) ret_ += "\n├ บล็อค : {}".format(str(len(blockedlist))) ret_ += "\n├ ค้างเชิญ : {}".format(str(len(IdsInvit))) ret_ += "\n├────────────" ret_ += "\n├ เวลาออนบอท :" ret_ += "\n├ {}".format(str(runtime)) ret_ += "\n├────────────" ret_ += "\n├ ผู้สร้าง : {}".format(str(creator.displayName)) ret_ += "\n╰───「 ★ʄທയஆടஷະ★ 」" feds = "{}".format(str(ret_)) data = { "type": "text", "text": "{}".format(str(ret_)), "sentBy": { "label": "{}".format(maxgie.getContact(maxgieMID).displayName), "iconUrl": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus), "linkUrl": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac" } } sendTemplate(to, data) maxgie.sendContact(msg.to, creator.mid) except Exception as e: maxgie.sendMessage(msg.to, str(e)) elif text.lower() == "หลุดมือ": gifnya = ['https://i.pinimg.com/originals/87/a8/9b/87a89b5aeaf35ba0c8879db5a136ccbd.gif'] data = { "type": "template", "altText": "Image carouserl", "template": { "type": "image_carousel", "columns": [ { "imageUrl": "{}".format(random.choice(gifnya)), "size": "full", "action": { "type": "uri", "uri": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac" } } ] } } sendTemplate(to, data) elif text.lower() == "รัก" or text.lower() == "รักๆ": gifnya = ['https://thumbs.gfycat.com/KlutzyUglyGelding-small.gif'] data = { "type": "template", "altText": "Image carouserl", "template": { "type": "image_carousel", "columns": [ { "imageUrl": "{}".format(random.choice(gifnya)), "size": "full", "action": { "type": "uri", "uri": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac" } } ] } } sendTemplate(to, data) elif cmd == "เทสๆ": gifnya = ['https://thumbs.gfycat.com/AngelicCloudyJaeger-size_restricted.gif','https://thumbs.gfycat.com/AgedZealousBlackfootedferret-size_restricted.gif','https://thumbs.gfycat.com/FondHastyChinesecrocodilelizard-size_restricted.gif','https://thumbs.gfycat.com/LividCrazyDipper-size_restricted.gif','https://thumbs.gfycat.com/LoathsomeDevotedGossamerwingedbutterfly-size_restricted.gif','https://thumbs.gfycat.com/SamePhysicalHarrierhawk-size_restricted.gif','https://thumbs.gfycat.com/ColorlessPinkLangur-size_restricted.gif','https://thumbs.gfycat.com/ThoseBitesizedBrahmanbull-size_restricted.gif','https://thumbs.gfycat.com/FakeSlowBengaltiger-size_restricted.gif','https://thumbs.gfycat.com/TanSpitefulChupacabra-size_restricted.gif'] data = { "type": "template", "altText": "Image carouserl", "template": { "type": "image_carousel", "columns": [ { "imageUrl": "{}".format(random.choice(gifnya)), "size": "full", "action": { "type": "uri", "uri": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac" } } ] } } sendTemplate(to, data) elif msg.text.lower().startswith("ตั้งรูปโปรไฟล์"): link = removeCmd("ตั้งรูปโปรไฟล์", text) contact = maxgie.getContact(sender) maxgie.sendMessage(to, "Type: Profile\n • Detail: Change video url\n • Status: Download...") print("Sedang Mendownload Data ~") pic = "http://dl.profile.line-cdn.net/{}".format(contact.pictureStatus) subprocess.getoutput('youtube-dl --format mp4 --output TeamAnuBot.mp4 {}'.format(link)) pict = maxgie.downloadFileURL(pic) vids = "TeamAnuBot.mp4" changeVideoAndPictureProfile(pict, vids) maxgie.sendMessage(to, "Type: Profile\n • Detail: Change video url\n • Status: Succes") os.remove("TeamAnuBot.mp4") #===================================================================== #===================================================================== elif msg.text.lower().startswith("/คท "): if 'MENTION' in list(msg.contentMetadata.keys())!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if mention["M"] not in lists: lists.append(mention["M"]) for ls in lists: contact = maxgie.getContact(ls) mi_d = contact.mid maxgie.sendContact(msg.to, mi_d) elif text.lower() == "เทส": duc1(to, "█▒... 10.0%") duc1(to, "███▒... 25.0%") duc1(to, "█████▒... 50.0%") duc1(to, "███████▒... 75.0%") duc1(to, "███████████..100.0%") elif msg.text in ["นับ"]: duc1(to,"เริ่ม..") duc1(to,"??:::⭐ 1 ⭐:::💖") duc1(to,"💚:::⭐ 5 ⭐:::💚") duc1(to,"💖:::⭐ 10 ⭐:::💖") duc1(to,"?????" +datetime.today().strftime('%H:%M:%S')+ "™") #===================================================================== elif msg.text.lower().startswith("ประกาศแชท: "): sep = text.split(" ") txt = text.replace(sep[0] + " ","") friends = maxgie.friends for friend in friends: maxgie.sendMessage(friend, "「ข้อความอัตโนมัติ ประกาศแชท」\n{}".format(str(txt))) duc1(to, "ส่งข้อความถึงเพื่อน {} คน".format(str(len(friends)))) #============================================================================= elif msg.text.lower().startswith("ดำ "): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if mention["M"] not in lists: lists.append(mention["M"]) for ls in lists: try: apalo["Talkblacklist"][ls] = True maxgie.sendMessage(to, 'Add to TalkBan') except: pass elif msg.text.lower().startswith("ล้าง "): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if mention["M"] not in lists: lists.append(mention["M"]) for ls in lists: try: del apalo["Talkblacklist"][ls] maxgie.sendMessage(to, 'Deleted from TalkBan') except: pass elif text.lower() == "เชคดำ": if apalo["Talkblacklist"] == {}: maxgie.unsendMessage(msg_id) duc1(to, "🌟ไม่พบคนที่ยัดดำ🌟") else: ma = "" a = 0 for m_id in apalo["Talkblacklist"]: a = a + 1 end = '\n' ma += str(a) + ". " +maxgie.getContact(m_id).displayName + "\n" duc1(to,"รายชื่อคนติดดำ :\n\n"+ma+"\nจำนวน %s คนติดดำ" %(str(len(apalo["Talkblacklist"])))) #===================================================================== if text.lower() == "เปิดบล็อค": if msg._from in admin: settings["autoblock"] = True sa = "เปิดแล้ว (`・ω・´)" else: sa = "เปิดอยู่แล้ว (`・ω・´)" duc1(to, sa) if text.lower() == "ปิดบล็อค": if msg._from in admin: settings["autoblock"] = False duc1(to,"ปิดแล้ว (`・ω・´)") else: duc1(to,"ปิดอยู่แล้ว (`・ω・´)") if text.lower() == "เปิดแทค": tagadd["tags"] = True sa = "เปิดแล้วว >_<" duc1(to,str(sa)) if text.lower() == "ปิดแทค": tagadd["tags"] = False sa = "ปิดแล้ว >_<" duc1(to,str(sa)) if text.lower() == "เปิดกันรัน": settings["autoCancel"]["on"] = True maxgie.unsendMessage(msg_id) duc1(to, "🌟เปิดกันรันเรียบร้อย🌟") if text.lower() == "ปิดกันรัน": settings["autoCancel"]["on"] = False maxgie.unsendMessage(msg_id) duc1(to, "🌟ปิดกันรันเรียบร้อย🌟") if text.lower() == "กินห้องเปิด": if msg._from in maxgieMID: kcn["autojoin"] = True maxgie.unsendMessage(msg_id) duc1(to, "🌟กินห้อง (เปิด) ใช้งาน🌟") else: maxgie.sendMessage(msg.to,"「 Status Autoleave 」\nเปิดใช้งานกินห้องอัตโนมัติแล้ว") if text.lower() == "กินห้องปิด": if msg._from in maxgieMID: kcn["autojoin"] = False maxgie.unsendMessage(msg_id) duc1(to, "🌟กินห้อง (ปิด) ใช้งาน🌟") else: maxgie.sendMessage(msg.to,"「 Status Autoleave 」\nเปิดใช้งานกินห้องอัตโนมัติแล้ว") if text.lower() == "เปิดแอด": settings["autoAdd"] = True maxgie.unsendMessage(msg_id) duc1(to, "🌟เปิดแอดเรียบร้อย🌟") if text.lower() == "ปิดแอด": settings["autoAdd"] = False maxgie.unsendMessage(msg_id) duc1(to, "🌟ปิดแอดเรียบร้อย🌟") if text.lower() == "ปิดไลค์": sets["l"] = False maxgie.unsendMessage(msg_id) duc1(to, "🌟ปิดไลค์แล้ว🌟") if text.lower() == "เปิดไลค์": sets["l"] = True maxgie.unsendMessage(msg_id) duc1(to, "🌟เปิดไลค์แล้ว🌟") if text.lower() == "เปิดแทค2": tagadd["tagss"] = True maxgie.unsendMessage(msg_id) duc1(to, "🌟เปิดแทค2เรียบร้อย🌟") if text.lower() == "ปิดแทค2": tagadd["tagss"] = False maxgie.unsendMessage(msg_id) duc1(to, "🌟ปิดแทค2เรียบร้อย🌟") if text.lower() == "เปิดคอมเม้น": settings["com"] = True maxgie.unsendMessage(msg_id) duc1(to, "🌟เปิดคอมเม้นเรียบร้อย🌟") if text.lower() == "ปิดคอมเม้น": settings["com"] = False maxgie.unsendMessage(msg_id) duc1(to, "🌟ปิดคอมเม้นเรียบร้อย🌟") if text.lower() == "เปิดต้อนรับ": settings["Welcome"] = True maxgie.unsendMessage(msg_id) duc1(to, "🌟เปิดต้อนรับเรียบร้อย🌟") if text.lower() == "ปิดต้อนรับ": settings["Welcome"] = False maxgie.unsendMessage(msg_id) duc1(to, "🌟ปิดต้อนรับเรียบร้อย🌟") if text.lower() == "เปิดต้อนรับ2": settings["Wc"] = True maxgie.unsendMessage(msg_id) duc1(to, "🌟เปิดต้อนรับ2เรียบร้อย🌟") if text.lower() == "ปิดต้อนรับ2": settings["Wc"] = False maxgie.unsendMessage(msg_id) duc1(to, "🌟ปิดต้อนรับ2เรียบร้อย🌟") if text.lower() == "เปิดคนออก": settings["Leave"] = True maxgie.unsendMessage(msg_id) duc1(to, "🌟เปิดคนออกเรียบร้อย🌟") if text.lower() == "ปิดคนออก": settings["Leave"] = False maxgie.unsendMessage(msg_id) duc1(to, "🌟ปิดคนออกเรียบร้อย🌟") if text.lower() == "เปิดยกเลิก": settings["unsendMessage"] = True maxgie.unsendMessage(msg_id) duc1(to, "🌟เปิดยกเลิกเรียบร้อย🌟") if text.lower() == "ปิดยกเลิก": settings["unsendMessage"] = False maxgie.unsendMessage(msg_id) duc1(to, "🌟ปิดยกเลิกเรียบร้อย🌟") if text.lower() == "เปิดติ๊กใหญ่": settings["Sticker"] = True maxgie.unsendMessage(msg_id) duc1(to, "🌟เปิดติ๊กใหญ่เรียบร้อย🌟") if text.lower() == "ปิดติ๊กใหญ่": settings["Sticker"] = False maxgie.unsendMessage(msg_id) duc1(to, "🌟ปิดติ๊กใหญ่เรียบร้อย🌟") if text.lower() == "เปิดโค๊ดติ๊ก": sets["Sticker"] = True maxgie.unsendMessage(msg_id) duc1(to, "🌟เปิดโค๊ดติ๊กเรียบร้อย🌟") if text.lower() == "ปิดโค๊ดติ๊ก": sets["Sticker"] = False maxgie.unsendMessage(msg_id) duc1(to, "🌟ปิดโค๊ดติ๊กเรียบร้อย🌟") if text.lower() == "เปิดแทค3": sets["tagsticker"] = True maxgie.unsendMessage(msg_id) duc1(to, "🌟เปิดแทค3เรียบร้อย🌟") if text.lower() == "ปิดแทค3": sets["tagsticker"] = False maxgie.unsendMessage(msg_id) duc1(to, "🌟ปิดแทค3เรียบร้อย🌟") if text.lower() == "เปิดติ๊กคนออก": settings["lv"] = True maxgie.unsendMessage(msg_id) duc1(to, "🌟เปิดติ๊กคนออกเรียบร้อย🌟") if text.lower() == "ปิดติ๊กคนออก": settings["lv"] = False maxgie.unsendMessage(msg_id) duc1(to, "🌟ปิดติ๊กคนออกเรียบร้อย🌟") if text.lower() == "เปิดติ๊กคนเข้า": settings["wcsti2"] = True maxgie.unsendMessage(msg_id) duc1(to, "🌟เปิดติ๊กคนเข้าเรียบร้อย🌟") if text.lower() == "ปิดติ๊กคนเข้า": settings["wcsti2"] = False maxgie.unsendMessage(msg_id) duc1(to, "🌟ปิดติ๊กคนเข้าเรียบร้อย🌟") if text.lower() == "เปิดมุดลิ้ง": sets["autoJoinTicket"] = True maxgie.unsendMessage(msg_id) duc1(to, "🌟เปิดมุดลิ้งเรียบร้อย🌟") if text.lower() == "ปิดมุดลิ้ง": sets["autoJoinTicket"] = False maxgie.unsendMessage(msg_id) duc1(to, "🌟ปิดมุดลิ้งเรียบร้อย🌟") elif text.lower() == 'speed':start = time.time();maxgie.sendMessage("ue846139824ec13384cbb921b460323ac", "★ʄທയஆടஷະ★ ");elapsed_time = time.time() - start;duc1(to, "Speed : %s second"%str(round(elapsed_time,4))) elif msg.text.lower().startswith("ประกาศ "): txt = removeCmd("ประกาศ", text) groups = maxgie.getGroupIdsJoined() url = 'https://nekos.life/api/v2/img/ngif' text1 = requests.get(url).text image = json.loads(text1)['url'] for group in groups: sa = " ประกาศ \n\n{}".format(str(txt)) data = { "type":"flex", "altText":"ขอพื้นที่แหกปากหน่อย...", "contents":{ "type": "carousel", "contents": [ { "type": "bubble", "styles": { "header": {"backgroundColor": "#000000", "separator": True, "separatorColor": "#FF0000"}, "body": {"backgroundColor": "#000000", "separator": True, "separatorColor": "#FF0000"}, "footer": {"backgroundColor": "#0033FF", "separator": True, "separatorColor": "#FF0000"} }, "header": { "type": "box", "layout": "horizontal", "contents": [ { "type": "text", "text": "ขอพื้นที่แหกปากหน่อยนะ\n", "align": "center", "size": "lg", "weight": "bold", "color": "#FFD300", "wrap": True } ] }, "type": "bubble", "body": { "contents": [ { "contents": [ { "url": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus), "type": "image" }, { "type": "separator", "color": "#000000" }, { "url": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus), "type": "image" } ], "type": "box", "spacing": "md", "layout": "horizontal" }, { "type": "separator", "color": "#000000" }, { "contents": [ { "text": sa, "size": "md", "align": "center", "color": "#FFD300", "wrap": True, "weight": "bold", "type": "text" } ], "type": "box", "spacing": "md", "layout": "vertical" }, { "type": "separator", "color": "#000000" }, { "contents": [ { "contents": [ { "type": "text", "text": sa, "align": "center", "size": "xs", "weight": "bold", "color": "#000000", "wrap": True } ], "type": "box", "layout": "baseline" }, { "contents": [ { "url": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus), "type": "icon", "size": "md" }, { "text": " ★ʄທയஆടஷະ★ ", "size": "xs", "margin": "none", "color": "#FFD300", "wrap": True, "weight": "regular", "type": "text" } ], "type": "box", "layout": "baseline" } ], "type": "box", "layout": "vertical" } ], "type": "box", "spacing": "md", "layout": "vertical" }, "footer": { "type": "box", "layout": "horizontal", "spacing": "sm", "contents": [ { "type": "button", "flex": 2, "style": "primary", "color": "#FFD300", "height": "sm", "action": { "type": "uri", "label": "★ʄທയஆടஷະ★ ", "uri": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac", } }, { "flex": 3, "type": "button", "style": "primary", "color": "#FFD300", "margin": "sm", "height": "sm", "action": { "type": "uri", "label": "★ʄທയஆടஷະ★ ", "uri": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac", } } ] } } ] } } sendTemplate(group, data) time.sleep(1) maxgie.sendMessage(to, "ส่งคำประกาศจำนวน {} กลุ่ม".format(str(len(groups)))) elif msg.text.lower().startswith("ขายของ"): contact = maxgie.getContact(sender) groups = maxgie.getGroupIdsJoined() for group in groups: dataProfile = [ { "type": "bubble", "styles": { "header": { "backgroundColor": '#000000' }, "body": { "backgroundColor": '#000000' }, "footer": { "backgroundColor": '#FF0033' }, }, "header": { "type": "box", "layout": "horizontal", "contents": [ { "type": "text", "text": "★ʄທയஆടஷະ★ ", "size": "md", "weight": "bold", "align": "center", "color": "#FF0033" } ] }, "hero": { "type": "image", "url": "https://sv1.picz.in.th/images/2019/05/19/wubKKl.gif", "size": "full", "aspectRatio": "20:13", "aspectMode": "cover", "action": { "type": "uri", "uri": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac" } }, "body": { "type": "box", "layout": "horizontal", "spacing": "md", "contents": [ { "type": "box", "layout": "vertical", "flex": 1, "contents": [ { "type": "image", "url": "https://sv1.picz.in.th/images/2019/05/19/wubKKl.gif", "aspectMode": "cover", "aspectRatio": "4:3", "size": "sm", "gravity": "bottom" }, { "type": "image", "url": "https://sv1.picz.in.th/images/2019/05/19/wubKKl.gif", "aspectMode": "cover", "aspectRatio": "4:3", "margin": "md", "size": "sm" } ] }, { "type": "box", "layout": "vertical", "flex": 2, "contents": [ { "type": "text", "text": "self bot python3", "color": "#FF0033", "gravity": "top", "size": "xs", "flex": 1 }, { "type": "separator" }, { "type": "text", "text": "ราคา 100 บาท/เดือน", "color": "#FF0033", "gravity": "center", "size": "xs", "flex": 2 }, { "type": "separator" }, { "type": "text", "text": "ห้องบอท", "color": "#FF0033", "gravity": "center", "size": "xs", "flex": 2 }, { "type": "separator" }, { "type": "text", "text": "ราคา 200 บาท", "color": "#FF0033", "gravity": "bottom", "size": "xs", "flex": 1 }, { "type": "separator" }, { "type": "text", "text": "ดูแลตลอดการใช้งาน", "color": "#FF0033", "gravity": "bottom", "size": "xs", "flex": 1 }, ] } ] }, "footer": { "contents": [ { "contents": [ { "contents": [ { "text": "สนใจติดต่อ", "size": "xl", "action": { "uri": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac", "type": "uri", "label": "Add Maker" }, "margin": "xl", "align": "center", "color": "#000000", "weight": "bold", "type": "text" } ], "type": "box", "layout": "baseline" } ], "type": "box", "layout": "horizontal" } ], "type": "box", "layout": "vertical" } }, { "type": "bubble", "styles": { "header": { "backgroundColor": '#000000' }, "body": { "backgroundColor": '#000000' }, "footer": { "backgroundColor": '#FF0033' }, }, "header": { "type": "box", "layout": "horizontal", "contents": [ { "type": "text", "text": "★ʄທയஆടஷະ★ ", "size": "md", "weight": "bold", "align": "center", "color": "#FF0033" } ] }, "hero": { "type": "image", "url": "https://sv1.picz.in.th/images/2019/05/19/wubKKl.gif", "size": "full", "aspectRatio": "20:13", "aspectMode": "cover", "action": { "type": "uri", "uri": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac" } }, "body": { "type": "box", "layout": "horizontal", "spacing": "md", "contents": [ { "type": "box", "layout": "vertical", "flex": 1, "contents": [ { "type": "image", "url": "https://sv1.picz.in.th/images/2019/05/19/wubKKl.gif", "aspectMode": "cover", "aspectRatio": "4:3", "size": "sm", "gravity": "bottom" }, { "type": "image", "url": "https://sv1.picz.in.th/images/2019/05/19/wubKKl.gif", "aspectMode": "cover", "aspectRatio": "4:3", "margin": "md", "size": "sm" } ] }, { "type": "box", "layout": "vertical", "flex": 2, "contents": [ { "type": "text", "text": "ติ๊กเกอร์ ราคาถูก", "color": "#FF0033", "gravity": "top", "size": "xs", "flex": 1 }, { "type": "separator" }, { "type": "text", "text": "เหรียญเหมาเหรียญแท้ๆ", "color": "#FF0033", "gravity": "center", "size": "xs", "flex": 2 }, { "type": "separator" }, { "type": "text", "text": "ติ๊กโปรทุกวัน", "color": "#FF0033", "gravity": "center", "size": "xs", "flex": 2 }, { "type": "separator" }, { "type": "text", "text": "ราคาถูกสอบถามได้", "color": "#FF0033", "gravity": "bottom", "size": "xs", "flex": 1 }, { "type": "separator" }, { "type": "text", "text": "เราใจดี", "color": "#FF0033", "gravity": "bottom", "size": "xs", "flex": 1 }, ] } ] }, "footer": { "contents": [ { "contents": [ { "contents": [ { "text": "สนใจติดต่อ", "size": "xl", "action": { "uri": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac", "type": "uri", "label": "Add Maker" }, "margin": "xl", "align": "center", "color": "#000000", "weight": "bold", "type": "text" } ], "type": "box", "layout": "baseline" } ], "type": "box", "layout": "horizontal" } ], "type": "box", "layout": "vertical" } }, { "type": "bubble", "styles": { "header": { "backgroundColor": '#000000' }, "body": { "backgroundColor": '#000000' }, "footer": { "backgroundColor": '#FF0033' }, }, "header": { "type": "box", "layout": "horizontal", "contents": [ { "type": "text", "text": "★ʄທയஆടஷະ★ ", "size": "md", "weight": "bold", "align": "center", "color": "#FF0033" } ] }, "hero": { "type": "image", "url": "https://sv1.picz.in.th/images/2019/05/19/wubKKl.gif", "size": "full", "aspectRatio": "20:13", "aspectMode": "cover", "action": { "type": "uri", "uri": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac" } }, "body": { "type": "box", "layout": "horizontal", "spacing": "md", "contents": [ { "type": "box", "layout": "vertical", "flex": 1, "contents": [ { "type": "image", "url": "https://sv1.picz.in.th/images/2019/05/19/wubKKl.gif", "aspectMode": "cover", "aspectRatio": "4:3", "size": "sm", "gravity": "bottom" }, { "type": "image", "url": "https://sv1.picz.in.th/images/2019/05/19/wubKKl.gif", "aspectMode": "cover", "aspectRatio": "4:3", "margin": "md", "size": "sm" } ] }, { "type": "box", "layout": "vertical", "flex": 2, "contents": [ { "type": "text", "text": "ขายสคิป/เฟค/คิก/ธรรมดา", "color": "#FF0033", "gravity": "top", "size": "xs", "flex": 1 }, { "type": "separator" }, { "type": "text", "text": "ไฟลบอทล็อคอิน", "color": "#FF0033", "gravity": "center", "size": "xs", "flex": 2 }, { "type": "separator" }, { "type": "text", "text": "ปล่อยเช่าเชิฟเวอร์", "color": "#FF0033", "gravity": "center", "size": "xs", "flex": 2 }, { "type": "separator" }, { "type": "text", "text": "ราคาสบายๆกระเป๋า", "color": "#FF0033", "gravity": "bottom", "size": "xs", "flex": 1 }, { "type": "separator" }, { "type": "text", "text": "ดูแลตลอดการใช้งาน", "color": "#FF0033", "gravity": "bottom", "size": "xs", "flex": 1 }, ] } ] }, "footer": { "contents": [ { "contents": [ { "contents": [ { "text": "สนใจติดต่อ", "size": "xl", "action": { "uri": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac", "type": "uri", "label": "Add Maker" }, "margin": "xl", "align": "center", "color": "#000000", "weight": "bold", "type": "text" } ], "type": "box", "layout": "baseline" } ], "type": "box", "layout": "horizontal" } ], "type": "box", "layout": "vertical" } }, ] data = { "type": "flex", "altText": "มีของมาขาย", "contents": { "type": "carousel", "contents": dataProfile } } sendTemplate(group, data) time.sleep(1) maxgie.sendMessage(to, "ส่งคำประกาศจำนวน {} กลุ่ม".format(str(len(groups)))) #==============================================================================# elif text.lower() == "แทค": group = maxgie.getGroup(to);nama = [contact.mid for contact in group.members];nama.remove(maxgie.getProfile().mid) maxgie.datamention(to,'★ʄທയஆടஷະ★ ',nama) elif text.lower() == "/แทค" or text.lower() == "tagall": if msg._from in maxgieMID: group = maxgie.getGroup(msg.to) nama = [contact.mid for contact in group.members] nm1, nm2, nm3, nm4, nm5, nm6, nm7, nm8, nm9, jml = [], [], [], [], [], [], [], [], [], len(nama) if jml <= 20: mentionMembers(msg.to, nama) if jml > 20 and jml < 40: for i in range (0, 19): nm1 += [nama[i]] mentionMembers(msg.to, nm1) for j in range (20, len(nama)): nm2 += [nama[j]] mentionMembers(msg.to, nm2) if jml > 40 and jml < 60: for i in range (0, 19): nm1 += [nama[i]] mentionMembers(msg.to, nm1) for j in range (20, 39): nm2 += [nama[j]] mentionMembers(msg.to, nm2) for k in range (40, len(nama)): nm3 += [nama[k]] mentionMembers(msg.to, nm3) if jml > 60 and jml < 80: for i in range (0, 19): nm1 += [nama[i]] mentionMembers(msg.to, nm1) for j in range (20, 39): nm2 += [nama[j]] mentionMembers(msg.to, nm2) for k in range (40, 59): nm3 += [nama[k]] mentionMembers(msg.to, nm3) for l in range (60, len(nama)): nm4 += [nama[l]] mentionMembers(msg.to, nm4) if jml > 80 and jml < 100: for i in range (0, 19): nm1 += [nama[i]] mentionMembers(msg.to, nm1) for j in range (20, 39): nm2 += [nama[j]] mentionMembers(msg.to, nm2) for k in range (40, 59): nm3 += [nama[k]] mentionMembers(msg.to, nm3) for l in range (60, 79): nm4 += [nama[l]] mentionMembers(msg.to, nm4) for m in range (80, len(nama)): nm5 += [nama[m]] mentionMembers(msg.to, nm5) if jml > 100 and jml < 120: for i in range (0, 19): nm1 += [nama[i]] mentionMembers(msg.to, nm1) for j in range (20, 39): nm2 += [nama[j]] mentionMembers(msg.to, nm2) for k in range (40, 59): nm3 += [nama[k]] mentionMembers(msg.to, nm3) for l in range (60, 79): nm4 += [nama[l]] mentionMembers(msg.to, nm4) for n in range (80, 99): nm5 += [nama[n]] mentionMembers(msg.to, nm5) for o in range (100, len(nama)): nm6 += [nama[o]] mentionMembers(msg.to, nm6) if jml > 120 and jml < 140: for i in range (0, 19): nm1 += [nama[i]] mentionMembers(msg.to, nm1) for j in range (20, 39): nm2 += [nama[j]] mentionMembers(msg.to, nm2) for k in range (40, 59): nm3 += [nama[k]] mentionMembers(msg.to, nm3) for l in range (60, 79): nm4 += [nama[l]] mentionMembers(msg.to, nm4) for n in range (80, 99): nm5 += [nama[n]] mentionMembers(msg.to, nm5) for o in range (100, 119): nm6 += [nama[o]] mentionMembers(msg.to, nm6) for v in range (120, len(nama)): nm7 += [nama[v]] mentionMembers(msg.to, nm7) if jml > 140 and jml < 160: for i in range (0, 19): nm1 += [nama[i]] mentionMembers(msg.to, nm1) for j in range (20, 39): nm2 += [nama[j]] mentionMembers(msg.to, nm2) for k in range (40, 59): nm3 += [nama[k]] mentionMembers(msg.to, nm3) for l in range (60, 79): nm4 += [nama[l]] mentionMembers(msg.to, nm4) for n in range (80, 99): nm5 += [nama[n]] mentionMembers(msg.to, nm5) for o in range (100, 119): nm6 += [nama[o]] mentionMembers(msg.to, nm6) for q in range (120, 139): nm7 += [nama[q]] mentionMembers(msg.to, nm7) for r in range (140, len(nama)): nm8 += [nama[r]] mentionMembers(msg.to, nm8) if jml > 160 and jml < 180: for i in range (0, 19): nm1 += [nama[i]] mentionMembers(msg.to, nm1) for j in range (20, 39): nm2 += [nama[j]] mentionMembers(msg.to, nm2) for k in range (40, 59): nm3 += [nama[k]] mentionMembers(msg.to, nm3) for l in range (60, 79): nm4 += [nama[l]] mentionMembers(msg.to, nm4) for n in range (80, 99): nm5 += [nama[n]] mentionMembers(msg.to, nm5) for o in range (100, 119): nm6 += [nama[o]] mentionMembers(msg.to, nm6) for q in range (120, 139): nm7 += [nama[q]] mentionMembers(msg.to, nm7) for z in range (140, 159): nm8 += [nama[z]] mentionMembers(msg.to, nm8) for f in range (160, len(nama)): nm9 += [nama[f]] mentionMembers(msg.to, nm9) #==============================================================================# elif msg.text.lower().startswith("เขียน "): sep = msg.text.split(" ") textnya = msg.text.replace(sep[0] + " ","") urlnya ="http://chart.apis.google.com/chart?chs=480x80&cht=p3&chtt=" + textnya +"&chts=ff3333,70&chf=bg,s,ff3333" maxgie.sendImageWithURL(msg.to, urlnya) elif msg.text.lower().startswith("เขียน1 "): sep = text.split(" ") textnya = text.replace(sep[0] + " ", "") text = "{}".format(textnya) contact = maxgie.getContact(maxgieMID) data = { "type": "flex", "altText": "มาอ่าน", "contents": { "type": "bubble", "styles": { "body": { "backgroundColor": '#00FFFF' }, }, "hero": { "type": "image", "url": "https://obs.line-scdn.net/{}".format(contact.pictureStatus), "size": "full", "aspectRatio":"1:1", "aspectMode":"cover" }, "body": { "type": "box", "layout": "horizontal", "contents": [ { "type": "text", "text": "{}".format(text), "color":"#000000", "wrap": True, "align": "center", "gravity": "center", "size": "xl" }, ] } } } sendTemplate(to, data) elif msg.text.lower().startswith("ดึง "): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if mention["M"] not in lists: lists.append(mention["M"]) for ls in lists: try: maxgie.findAndAddContactsByMid(ls) maxgie.inviteIntoGroup(to, [ls]) except: duc1(to, "Limited !") elif msg.text.lower().startswith("สะกด"): if msg.toType == 2: data = text.replace("สะกด ","") yud = data.split(' ') yud = yud[0].replace(' ','_') if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if mention["M"] not in lists: lists.append(mention["M"]) for ls in lists: maxgie.unsendMessage(msg_id) maxgie.sendMessage(to, yud,contentMetadata={"MSG_SENDER_NAME": str(maxgie.getContact(ls).displayName),"MSG_SENDER_ICON":"http://dl.profile.line-cdn.net/%s" % maxgie.getContact(ls).pictureStatus}) elif text.startswith("ยูทูป "): a = maxgie.adityarequestweb("https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=25&q="+maxgie.adityasplittext(text,'s')+"&type=video&key=AIzaSyAF-_5PLCt8DwhYc7LBskesUnsm1gFHSP8") if a["items"] != []: no = 0 ret_ = [] for music in a["items"]: no += 1 ret_.append({"type": "bubble","styles": {"header": {"backgroundColor": "#0033FF", "separator": True, "separatorColor": "#FFFFFF"},"body": {"backgroundColor": "#0033FF", "separator": True, "separatorColor": "#FFFFFF"},"footer": {"backgroundColor": "#000000", "separator": True, "separatorColor": "#FFFFFF"},},"header": {"type": "box","layout": "horizontal","contents": [{"type": "text","text": "Youtube","weight": "bold","color": "#FFFFFF","size": "sm"}]},"hero": {"type": "image","url": 'https://i.ytimg.com/vi/{}/maxresdefault.jpg'.format(music['id']['videoId']),"size": "full","aspectRatio": "20:13","aspectMode": "fit","action": {"type": "uri","uri": 'https://www.youtube.com/watch?v=' +music['id']['videoId']}},"body": {"type": "box","layout": "vertical","contents": [{"type": "box","layout": "vertical","margin": "lg","spacing": "sm","contents": [{"type": "box","layout": "baseline","spacing": "sm","contents": [{"type": "text","text": "ข้อมูล","color": "#FFFFFF","size": "sm","flex": 1},{"type": "text","text": "{}".format(music['snippet']['title']),"color": "#FFFFFF","wrap": True,"size": "sm","flex": 5}]}]}]},"footer": {"type": "box","layout": "horizontal","spacing": "sm","contents": [{"type": "button","flex": 2,"style": "primary","color": "#EE1289","height": "sm","action": {"type": "uri","label": "VIDIO","uri": "{}วีดีโอ%20https://www.youtube.com/watch?v={}".format(wait['ttt'],music['id']['videoId'])}},{"type": "button","flex": 2,"style": "primary","color": "#EE1289","height": "sm","action": {"type": "uri","label": "AUDIO","uri": "{}เสียง%20https://www.youtube.com/watch?v={}".format(wait['ttt'],music['id']['videoId'])}},],}}) k = len(ret_)//10 for aa in range(k+1): data = {"messages": [{"type": "flex","altText": "ยูทูป","contents": {"type": "carousel","contents": ret_[aa*10 : (aa+1)*10]}}]} maxgie.sendMessage(to,data) else: maxgie.sendMessage(to,"Type: Search Youtube Video\nStatus: "+str(self.adityasplittext(msg.text,'s'))+" not found") elif msg.text.lower().startswith("image "): query = removeCmd("image", text) cond = query.split("|") search = str(cond[0]) r = requests.get("https://cryptic-ridge-9197.herokuapp.com/api/imagesearch/{}".format(str(search))) data=r.text data=json.loads(r.text) if data != []: ret_ = [] for food in data: if 'http://' in food["url"]: pass else: if len(ret_) >= 10: pass else: ret_.append({ "imageUrl": "{}".format(str(food["url"])), "action": { "type": "uri", "label": "Send Image", "uri": "line://app/1602687308-GXq4Vvk9?type=image&img={}".format(str(food["url"])) } } ) k = len(ret_)//10 for aa in range(k+1): data = { "type": "template", "altText": "sendImage", "template": { "type": "image_carousel", "columns": ret_[aa*10 : (aa+1)*10] } } sendTemplate(to, data) elif msg.text.lower().startswith("เพลสโต "): query = removeCmd("เพลสโต", text) cond = query.split("|") search = str(cond[0]) result = requests.get("http://api.farzain.com/playstore.php?id={}&apikey=KJaOT94NCD1bP1veQoJ7uXc9M".format(str(search))) data = result.text data = json.loads(data) if data != []: ret_ = [] for music in data: if 'http://' in music["url"]: pass else: if len(ret_) >= 10: pass else: ret_.append({ "imageUrl": "{}".format(str(music["icon"])), "action": { "type": "uri", "label": "Download", "uri": "{}".format(str(music["url"])) } } ) k = len(ret_)//10 for aa in range(k+1): data = { "type": "template", "altText": "Searching App", "template": { "type": "image_carousel", "columns": ret_[aa*10 : (aa+1)*10] } } sendTemplate(to, data) elif msg.text.lower().startswith("รูป "): query = removeCmd("รูป", text) cond = query.split("|") search = str(cond[0]) result = requests.get("https://api.boteater.co/googleimg?search={}".format(str(search))) data = result.text data = json.loads(data) if data["result"] != []: ret_ = [] for fn in data["result"]: if 'http://' in fn["img"]: pass else: if len(ret_) >= 10: pass else: ret_.append({ "imageUrl": "{}".format(str(fn["img"])), "action": { "type": "uri", "label": "Send Image", "uri": "line://app/1602687308-GXq4Vvk9?type=image&img={}".format(str(fn["img"])) } } ) k = len(ret_)//10 for aa in range(k+1): data = { "type": "template", "altText": "Google_Image", "template": { "type": "image_carousel", "columns": ret_[aa*10 : (aa+1)*10] } } sendTemplate(to, data) #===================================================================== elif msg.text.lower().startswith("ยกเชิญ"): if msg._from in maxgieMID: if msg.toType == 2: group = maxgie.getGroup(receiver) gMembMids = [contact.mid for contact in group.invitee] k = len(gMembMids)//20 maxgie.sendMessage(msg.to,"[ ยกค้างเชิญ จำนวน {} คน] \nรอสักครู่...".format(str(len(gMembMids)))) num=1 for i in range(k+1): for j in gMembMids[i*20 : (i+1)*20]: time.sleep(random.uniform(0.5,0.4)) maxgie.cancelGroupInvitation(msg.to,[j]) print ("[Command] "+str(num)+" => "+str(len(gMembMids))+" cancel members") num = num+1 maxgie.sendMessage(receiver,"รอสักครู่🕛เดียวยกต่อ 20 คน\n 『.★ʄທയஆടஷະ★ 』 ") time.sleep(random.uniform(15,10)) maxgie.sendMessage(receiver,"[ ยกค้างเชิญ จำนวน {} คน เรียบร้อยแล้ว👏]".format(str(len(gMembMids)))) time.sleep(random.uniform(0.95,1)) maxgie.sendMessage(receiver, None, contentMetadata={"STKID": "52002735","STKPKGID": "11537","STKVER": "1" }, contentType=7) gname = line.getGroup(receiver).name maxgie.sendMessage(Notify,"[ ยกค้างเชิญ >> "+gname+" <<] \n จำนวน {} คน เรียบร้อยแล้ว👏\n『★ʄທയஆടஷະ★ 』".format(str(len(gMembMids)))) time.sleep(random.uniform(0.95,1)) maxgie.leaveGroup(receiver) maxgie.sendMessage(receiver,"[ไม่มีค้างเชิญ แล้วนะ😁]") maxgie.sendMessage(receiver, None, contentMetadata={"STKID": "52114123","STKPKGID": "11539","STKVER": "1" }, contentType=7) maxgie.leaveGroup(receiver) #===================================================================== elif msg.text.lower().startswith("ยกเลิก "): args = msg.text.lower().replace("ยกเลิก ","") mes = 0 try: mes = int(args[1]) except: mes = 100 M = maxgie.getRecentMessagesV2(to, 100) MId = [] for ind,i in enumerate(M): if ind == 0: pass else: if i._from == maxgie.profile.mid: MId.append(i.id) if len(MId) == mes: break def unsMes(id): maxgie.unsendMessage(id) for i in MId: thread1 = threading.Thread(target=unsMes, args=(i,)) thread1.start() thread1.join() duc1(to, ' 「 กำลังยกเลิก 」\nยกเลิกทั้งหมด {} ข้อความ'.format(len(MId))) maxgie.unsendMessage(msg_id) #===================================================================== elif msg.text.lower().startswith("เพิ่มเพื่อน "): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if mention["M"] not in lists: lists.append(mention["M"]) for ls in lists: contact = maxgie.getContact(ls) maxgie.findAndAddContactsByMid(ls) maxgie.generateReplyMessage(msg.id) duc1(id, to, "Success add " + str(contact.displayName) + " to Friendlist") elif msg.text.lower().startswith("ลบเพื่อน "): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if mention["M"] not in lists: lists.append(mention["M"]) for ls in lists: contact = maxgie.getContact(ls) n = len(maxgie.getAllContactIds()) try: maxgie.deleteContact(ls) except:pass t = len(maxgie.getAllContactIds()) maxgie.generateReplyMessage(msg.id) duc1(id, to, "Type: Friendlist\n • Detail: Delete friend\n • Status: Succes..\n • Before: %s Friendlist\n • After: %s Friendlist"%(n,t)) elif msg.text.lower().startswith("บล็อค "): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if mention["M"] not in lists: lists.append(mention["M"]) for ls in lists: contact = maxgie.getContact(ls) maxgie.blockContact(ls) maxgie.generateReplyMessage(msg.id) duc1(id, to, "Success add " + str(contact.displayName) + " to Blocklist") elif msg.text.lower().startswith("ไอดีไลน์ "): a = removeCmd("ไอดีไลน์", text) b = maxgie.findContactsByUserid(a) line = b.mid maxgie.unsendMessage(msg_id) duc1(to, "line://ti/p/~" + a) maxgie.sendContact(to, line) maxgie.sendMessage(to,str(hasil)) elif msg.text.lower().startswith("stag "): sep = text.split(" ") text = text.replace(sep[0] + " ","") cond = text.split(" ") jml = int(cond[0]) if msg.toType == 2: group = maxgie.getGroup(to) for x in range(jml): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if mention["M"] not in lists: lists.append(mention["M"]) for receiver in lists: contact = maxgie.getContact(receiver) RhyN_(to, contact.mid) elif "/ลบรัน" in msg.text.lower(): spl = re.split("/ลบรัน",msg.text,flags=re.IGNORECASE) if spl[0] == "": spl[1] = spl[1].strip() ag = maxgie.getGroupIdsInvited() txt = "กำลังยกเลิกค้างเชิญจำนวน "+str(len(ag))+" กลุ่ม" if spl[1] != "": txt = txt + " ด้วยข้อความ \""+spl[1]+"\"" txt = txt + "\nกรุณารอสักครู่.." data = {"type": "text","text": "{}".format(str(txt)),"sentBy": {"label": "{}".format(maxgie.getContact(maxgieMID).displayName),"iconUrl": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus),"linkUrl": "line://nv/profilePopup/mid=ubd86e8c77559b1493f0ad64b1dba2d6c"}} sendTemplate(to, data) procLock = len(ag) for gr in ag: try: maxgie.acceptGroupInvitation(gr) if spl[1] != "": maxgie.sendMessage(gr,spl[1]) maxgie.leaveGroup(gr) except: pass sis = "สำเร็จแล้ว (`・ω・´)" data = {"type": "text","text": "{}".format(str(sis)),"sentBy": {"label": "{}".format(maxgie.getContact(maxgieMID).displayName),"iconUrl": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus),"linkUrl": "line://nv/profilePopup/mid=ubd86e8c77559b1493f0ad64b1dba2d6c"}} sendTemplate(to, data) #===================================================================== #==============================================================================# elif text.lower() == 'คนสร้างกลุ่ม' or text.lower() == "แอด": group = maxgie.getGroup(to) cg = group.creator c = cg.mid name = cg.displayName pp = cg.pictureStatus # profile = "https://profile.line-scdn.net/" + str(pp) data = { "type": "flex", "altText": "แอดกลุ่ม", "contents": { "type": "bubble", "body": { "type": "box", "layout": "vertical", "contents": [ { "type":"text", "text": "★ʄທയஆടஷະ★ ", "size":"md", # "weight":"bold", "color":"#FF3333", "align":"center" }, { "type": "text", "text": " " }, { "type": "image", "url": "https://profile.line-scdn.net/" + str(pp), "size": "xl" }, { "type":"text", "text":" " }, { "type":"text", "text": name, "color":"#FF3333", "align":"center", "size":"xl", }, ] } } } sendTemplate(to, data) maxgie.sendContact(to, c) elif text.lower() == 'ไอดีกลุ่ม': gid = maxgie.getGroup(to) # maxgie.unsendMessage(msg_id) duc1(to, "{ Group ID }\n" + gid.id) maxgie.sendMessage(to, maxgie.getGroup(to).name, contentMetadata = {'previewUrl': 'http://dl.profile.line-cdn.net/'+maxgie.getGroup(to).pictureStatus, 'i-installUrl': 'https://line.me/ti/p/~', 'type': 'mt', 'subText': "★ʄທയஆടஷະ★ ", 'a-installUrl': 'https://line.me/ti/p/~', 'a-installUrl': ' https://line.me/ti/p/~', 'a-packageName': 'com.spotify.music', 'countryCode': 'ID', 'a-linkUri': 'https://line.me/ti/p/~', 'i-linkUri': 'https://line.me/ti/p/~', 'id': 'mt000000000a6b79f9', 'text': '★ʄທയஆടஷະ★ ', 'linkUri': 'https://line.me/ti/p/~'}, contentType=19) elif text.lower() == 'รูปกลุ่ม': group = maxgie.getGroup(to) path = "http://dl.profile.line-cdn.net/" + group.pictureStatus maxgie.sendImageWithURL(to, path) elif text.lower() == 'ชื่อกลุ่ม': gid = maxgie.getGroup(to) maxgie.unsendMessage(msg_id) duc1(to, "ชื่อกลุ่ม -> \n" + gid.name) elif text.lower() == 'ลิ้ง': if msg.toType == 2: group = maxgie.getGroup(to) if group.preventedJoinByTicket == False: ticket = maxgie.reissueGroupTicket(to) maxgie.sendMessage(to, "ลิ้งของกลุ่ม : "+group.name+"\nhttps://line.me/R/ti/g/{}".format(str(ticket))) elif text.lower() == 'เปิดลิ้ง': if msg.toType == 2: group = maxgie.getGroup(to) if group.preventedJoinByTicket == False: maxgie.unsendMessage(msg_id) duc1(to, "เปิดลิ้งเรียบร้อย") else: group.preventedJoinByTicket = False maxgie.updateGroup(group) maxgie.sendMessage(to, "เปิดลิ้งเรียบร้อย") elif text.lower() == 'ปิดลิ้ง': if msg.toType == 2: group = maxgie.getGroup(to) if group.preventedJoinByTicket == True: maxgie.unsendMessage(msg_id) duc1(to, "ปิดลิ้งเรียบร้อย") else: group.preventedJoinByTicket = True maxgie.updateGroup(group) maxgie.sendMessage(to, "ปิดลิ้งเรียบร้อย") elif text.lower() == 'ข้อมูลกลุ่ม': group = maxgie.getGroup(to) try: gCreator = group.creator.displayName except: gCreator = "ผู้สร้างกลุ่มนี้ลบชี" if group.invitee is None: gPending = "0" else: gPending = str(len(group.invitee)) if group.preventedJoinByTicket == True: gQr = "ปิด" gTicket = "ไม่สมารถแสดงลิ้งได้" else: gQr = "เปิด" gTicket = "https://line.me/R/ti/g/{}".format(str(maxgie.reissueGroupTicket(group.id))) path = "http://dl.profile.line-cdn.net/" + group.pictureStatus ret_ = "╔══[ ข้อมูลของกลุ่มนี้ ]" ret_ += "\n╠ ชื่อของกลุ่ม : {}".format(str(group.name)) ret_ += "\n╠ ไอดีของกลุ่ม : {}".format(group.id) ret_ += "\n╠ ผู้สร้างกลุ่ม : {}".format(str(gCreator)) ret_ += "\n╠ จำนวนสมาชิก : {}".format(str(len(group.members))) ret_ += "\n╠ จำนวนค้างเชิญ : {}".format(gPending) ret_ += "\n╠ ลิ้งของกลุ่ม : {}".format(gQr) ret_ += "\n╠ ลิ้งกลุ่ม👉 : {}".format(gTicket) ret_ += "\n╚══『★ʄທയஆടஷະ★ 』" data = { "type": "flex", "altText": "กลุ่ม", "contents": { "type": "bubble", "styles": { "body": { "backgroundColor": '#EE1289' }, }, "body": { "type": "box", "layout": "vertical", "contents": [ # { # "type": "image", # "url": path, # "size": "xl" # }, { "type": "text", "text": ret_, "color": "#000000", "wrap": True, "size": "md", }, ] }, } } sendTemplate(to, data) maxgie.sendImageWithURL(to, path) elif text.lower() == 'คนในห้อง': if msg.toType == 2: group = maxgie.getGroup(to) ret_ = "รายชื่อสามชิกในกลุ่มนี้\n" no = 0 + 1 for mem in group.members: ret_ += "\n{}. {}".format(str(no), str(mem.displayName)) no += 1 ret_ += "\n\nจำนวน {} คน".format(str(len(group.members))) data = { "type": "flex", "altText": "กลุ่ม", "contents": { "type": "bubble", "styles": { "body": { "backgroundColor": '#EE1289' }, }, "hero": { "type": "image", "url": "https://obs.line-scdn.net/{}".format(maxgie.getContact(sender).pictureStatus), "size": "full", "aspectRatio": "1:1", "aspectMode": "fit", }, "body": { "type": "box", "layout": "vertical", "contents": [ { "type": "text", "text": ret_, "color": "#000000", "wrap": True, "size": "md" }, ] } } } sendTemplate(to, data) elif text.lower() == 'กลุ่มทั้งหมด': groups = maxgie.groups ret_ = "รายชื่อกลุ่มทั้งหมด :\n" no = 0 + 1 for gid in groups: group = maxgie.getGroup(gid) ret_ += "\n{}. {} | {}".format(str(no), str(group.name), str(len(group.members))) no += 1 ret_ += "\n\nจำนวน {} กลุ่ม".format(str(len(groups))) data = { "type": "flex", "altText": "Group list", "contents": { "type": "bubble", "styles": { "body": { "backgroundColor": '#EE1289' }, }, "body": { "type": "box", "layout": "vertical", "contents": [ { "type":"text", "text": ret_, "color": "#000000", "wrap": True, "size": "md" }, ] } } } sendTemplate(to, data) elif "อัพชื่อ " in text.lower(): if msg._from in admin: proses = text.split(" ") string = text.replace(proses[0] + " ","") profile_A = maxgie.getProfile() profile_A.displayName = string maxgie.updateProfile(profile_A) maxgie.sendMessage(msg.to,"Update to :\n" + string) print ("Update Name") elif "อัพตัส " in msg.text.lower(): if msg._from in admin: proses = text.split(" ") string = text.replace(proses[0] + " ","") profile_A = maxgie.getProfile() profile_A.statusMessage = string maxgie.updateProfile(profile_A) maxgie.sendMessage(msg.to,"Succes Update :\n" + string) print ("Update Bio Succes") elif text.lower() == "อัพรูปโปร": sets["changePictureProfile"] = True maxgie.unsendMessage(msg_id) duc1(to, "🌟ส่งรูปภาพที่จะอัพมาเลยครับ🌟") elif text.lower() == "อัพรูปกลุ่ม": if msg.toType == 2: if to not in sets["changeGroupPicture"]: sets["changeGroupPicture"].append(to) maxgie.unsendMessage(msg_id) duc1(to, "🌟ส่งรูปภาพที่จะอัพมาเลยครับ🌟") elif text.lower() == 'เพื่อน': contactlist = maxgie.getAllContactIds() kontak = maxgie.getContacts(contactlist) num=1 msgs="☢️รายชื่อเพื่อนทั้งหมด☢️" for ids in kontak: msgs+="\n[%i] %s" % (num, ids.displayName) num=(num+1) msgs+="\n☢️รายชื่อเพื่อนทั้งหมด☢️\n\nมีดังต่อไปนี้ : %i" % len(kontak) maxgie.sendMessage(msg.to, msgs) # if msg.toType == 2: # # ginfo = line.getGroup(receiver) # try: # gcmid = ginfo.creator.mid # except: # gcmid = "Error" # if settings["lang"] == "JP": # line.inviteIntoGroup(receiver,[gcmid]) # line.sendMessage(receiver, "พิมพ์คำเชิญกลุ่ม") # else: # line.inviteIntoGroup(receiver,[gcmid]) # line.sendMessage(receiver, "ผู้สร้างกลุ่มอยู่ในแล้ว") #==================================================================== elif msg.text.lower()== "ตั้งติ๊กคนแทค": sets["messageSticker"]["addStatus"] = True sets["messageSticker"]["addName"] = "tag" maxgie.unsendMessage(msg_id) duc1(to, "🌟ส่งติ๊กที่จะใช้ลงมา🌟") elif msg.text.lower() == "ลบติ๊กคนแทค": sets["messageSticker"]["listSticker"]["tag"] = None maxgie.unsendMessage(msg_id) duc1(to, "🌟ลบติ๊กคนแทคแล้วครับ🌟") elif msg.text.lower()== "ตั้งติ๊กคนเข้า": sets["messageSticker"]["addStatus"] = True sets["messageSticker"]["addName"] = "wc" maxgie.unsendMessage(msg_id) duc1(to, "🌟ส่งติ๊กที่จะใช้ลงมา🌟") elif msg.text.lower() == "ลบติ๊กคนเข้า": sets["messageSticker"]["listSticker"]["wc"] = None maxgie.unsendMessage(msg_id) duc1(to, "🌟ลบติ๊กคนเข้าแล้วครับ🌟") elif msg.text.lower()== "ตั้งติ๊กคนออก": sets["messageSticker"]["addStatus"] = True sets["messageSticker"]["addName"] = "lv" maxgie.unsendMessage(msg_id) duc1(to, "🌟ส่งติ๊กที่จะใช้ลงมา🌟") elif msg.text.lower() == "ลบติ๊กคนออก": sets["messageSticker"]["listSticker"]["lv"] = None maxgie.unsendMessage(msg_id) duc1(to, "🌟ลบติ๊กคนออกแล้วครับ🌟") elif msg.text.lower()== "ตั้งติ๊กคนแอด": sets["messageSticker"]["addStatus"] = True sets["messageSticker"]["addName"] = "add" maxgie.unsendMessage(msg_id) duc1(to, "🌟ส่งติ๊กที่จะใช้ลงมา🌟") elif msg.text.lower() == "ลบติ๊กคนแอด": sets["messageSticker"]["listSticker"]["add"] = None maxgie.unsendMessage(msg_id) duc1(to, "🌟ลบติ๊กคนแอดแล้วครับ🌟") elif msg.text.lower() == "ตั้งติ๊กมุดลิ้ง": sets["messageSticker"]["addStatus"] = True sets["messageSticker"]["addName"] = "join2" maxgie.unsendMessage(msg_id) duc1(to, "🌟ส่งติ๊กที่จะใช้ลงมาครับ🌟") elif msg.text.lower() == "ลบติ๊กมุดลิ้ง": sets["messageSticker"]["listSticker"]["join2"] = None maxgie.unsendMessage(msg_id) duc1(to, "🌟ลบติ๊กมุดลิ้งแล้ว🌟") #===================================================================== elif msg.contentType == 1: if sets["changePictureProfile"] == True: path = maxgie.downloadObjectMsg(msg_id) sets["changePictureProfile"] = False maxgie.updateProfilePicture(path) maxgie.unsendMessage(msg_id) duc1(to, "🌟ทำการเปลี่ยนแล้วครับ🌟") if op.type == 26: msg = op.message text = msg.text msg_id = msg.id receiver = msg.to sender = msg._from if msg.toType == 0 or msg.toType == 1 or msg.toType == 2: if msg.toType == 0: if sender != maxgie.profile.mid: to = sender else: to = receiver elif msg.toType == 1: to = receiver elif msg.toType == 2: to = receiver elif msg.contentType == 7: if sets["Sticker"] == True: try: stk_id = msg.contentMetadata['STKID'] stk_ver = msg.contentMetadata['STKVER'] pkg_id = msg.contentMetadata['STKPKGID'] ret_ = "「 Check Sticker 」\n" ret_ += "\nSTKID : {}".format(stk_id) ret_ += "\nSTKPKGID : {}".format(pkg_id) ret_ += "\nSTKVER : {}".format(stk_ver) ret_ += "\nLINK : line://shop/detail/{}".format(pkg_id) print(msg) maxgie.sendImageWithURL(to, "http://dl.stickershop.line.naver.jp/products/0/0/"+msg.contentMetadata["STKVER"]+"/"+msg.contentMetadata["STKPKGID"]+"/WindowsPhone/stickers/"+msg.contentMetadata["STKID"]+".png") maxgie.sendMessage(to, str(ret_)) except Exception as error: maxgie.sendMessage(to, str(error)) if msg.text: if msg.text.lower().lstrip().rstrip() in wbanlist: if msg.text not in maxgieMID: try: maxgie.kickoutFromGroup(msg.to,[sender]) maxgie.unsendMessage(msg_id) duc1(to, "🌟บอกแล้วอย่าพิมจุกไปดิครับ🌟") except Exception as e: print(e) if "/ti/g/" in msg.text.lower(): if sets["autoJoinTicket"] == True: link_re = re.compile('(?:line\:\/|line\.me\/R)\/ti\/g\/([a-zA-Z0-9_-]+)?') links = link_re.findall(text) n_links = [] for l in links: if l not in n_links: n_links.append(l) for ticket_id in n_links: group = maxgie.findGroupByTicket(ticket_id) maxgie.acceptGroupInvitationByTicket(group.id,ticket_id) maxgie.sendMessage(group.id,str(tagadd["m"])) # msgSticker = sets["messageSticker"]["listSticker"]["join2"] # if msgSticker != None: # sid = msgSticker["STKID"] # spkg = msgSticker["STKPKGID"] # sver = msgSticker["STKVER"] # sendSticker(group.id, str(sver), str(spkg), str(sid)) maxgie.unsendMessage(msg_id) duc1(to, "🌟มุดเข้าลิ้งกลุ่ม %s เรียบร้อย 555🌟" % str(group.name)) if msg.contentType == 7: if sets["messageSticker"]["addStatus"] == True: name = sets["messageSticker"]["addName"] if name != None and name in sets["messageSticker"]["listSticker"]: sets["messageSticker"]["listSticker"][name] = { "STKID": msg.contentMetadata["STKID"], "STKVER": msg.contentMetadata["STKVER"], "STKPKGID": msg.contentMetadata["STKPKGID"] } maxgie.sendMessage(to, "Success Sticker " + name + " Done...") sets["messageSticker"]["addStatus"] = False sets["messageSticker"]["addName"] = None if sets["addSticker"]["status"] == True: stickers[sets["addSticker"]["name"]]["STKVER"] = msg.contentMetadata["STKVER"] stickers[sets["addSticker"]["name"]]["STKID"] = msg.contentMetadata["STKID"] stickers[sets["addSticker"]["name"]]["STKPKGID"] = msg.contentMetadata["STKPKGID"] f = codecs.open('sticker.json','w','utf-8') json.dump(stickers, f, sort_keys=True, indent=4, ensure_ascii=False) maxgie.sendMessage(to, "Success Added sticker {}".format(str(sets["addSticker"]["name"]))) sets["addSticker"]["status"] = False sets["addSticker"]["name"] = "" elif msg.contentType == 7: if sets["Sticker"] == True: stk_id = msg.contentMetadata['STKID'] stk_ver = msg.contentMetadata['STKVER'] pkg_id = msg.contentMetadata['STKPKGID'] ret_ = "╔══[ Sticker Info ]" ret_ += "\n╠ STICKER ID : {}".format(stk_id) ret_ += "\n╠ STICKER PACKAGES ID : {}".format(pkg_id) ret_ += "\n╠ STICKER VERSION : {}".format(stk_ver) ret_ += "\n╠ STICKER URL : line://shop/detail/{}".format(pkg_id) ret_ += "\n╚══[ Finish ]" maxgie.sendMessage(to, str(ret_)) #===================================================================== if op.type == 22: if did["join"] == True: maxgie.leaveRoom(op.param1) if op.type == 24: if did["join"] == True: maxgie.leaveRoom(op.param1) #======================================================================== if op.type == 25 or op.type == 26: msg = op.message text = msg.text msg_id = msg.id receiver = msg.to sender = msg._from if msg.toType == 0 or msg.toType == 1 or msg.toType == 2: if msg.toType == 0: if sender != maxgie.profile.mid: to = sender else: to = receiver elif msg.toType == 1: to = receiver elif msg.toType == 2: to = receiver if msg.contentType == 0: if text is None: return if text.lower() == ".": duc1(to, "★ʄທയஆടஷະ★ ") #======================================================================== elif msg.contentType == 7: # Content type is sticker if settings['Sticker']: if 'STKOPT' in msg.contentMetadata: contact = maxgie.getContact(sender) A = contact.displayName stk = msg.contentMetadata['STKID'] spk = msg.contentMetadata['STKPKGID'] data={'type':'template','altText': str(A)+' ส่งสติ๊กเกอร์','template':{'type':'image_carousel','columns':[{'imageUrl':'https://stickershop.line-scdn.net/stickershop/v1/sticker/{}/IOS/sticker_animation@2x.png'.format(stk),'action':{'type':'uri','uri':'https://line.me/S/sticker/{}'.format(spk)}}]}} sendTemplate(to, data) else: contact = maxgie.getContact(sender) A = contact.displayName stk = msg.contentMetadata['STKID'] spk = msg.contentMetadata['STKPKGID'] data={'type':'template','altText': str(A)+' ส่งสติ๊กเกอร์','template':{'type':'image_carousel','columns':[{'imageUrl':'https://stickershop.line-scdn.net/stickershop/v1/sticker/{}/IOS/sticker@2x.png'.format(stk),'action':{'type':'uri','uri':'https://line.me/S/sticker/{}'.format(spk)}}]}} sendTemplate(to, data) if op.type == 26: print ("[ 26 ] RECEIVE MESSAGE") msg = op.message text = str(msg.text) msg_id = msg.id receiver = msg.to sender = msg._from to = msg.to cmd = command(text) isValid = True setKey = settings["keyCommand"].title() if settings["setKey"] == False: setKey = '' if isValid != False: # elif msg.contentType == 7: if msg.toType == 0 and sender != maxgieMID: to = sender else: to = receiver # elif msg.contentType == 7: # if "/ti/g/" in msg.text.lower(): # if sets["autoJoinTicket"] == True: # link_re = re.compile('(?:line\:\/|line\.me\/R)\/ti\/g\/([a-zA-Z0-9_-]+)?') # links = link_re.findall(text) # n_links = [] # for l in links: # if l not in n_links: # n_links.append(l) # for ticket_id in n_links: # group = maxgie.findGroupByTicket(ticket_id) # maxgie.acceptGroupInvitationByTicket(group.id,ticket_id) # # maxgie.sendMessage(to, "เข้าไปสิงในห้องชื่อ %s 👈 เรียบร้อยแล้ว" % str(group.name)) if msg.contentType == 0 and sender not in maxgieMID and msg.toType == 2: if "MENTION" in list(msg.contentMetadata.keys()) != None: if tagadd["tags"] == True: me = maxgie.getContact(sender) name = re.findall(r'@(\w+)', msg.text) mention = ast.literal_eval(msg.contentMetadata["MENTION"]) mentionees = mention['MENTIONEES'] for mention in mentionees: if mention['M'] in maxgieMID: cover = maxgie.getProfileCoverURL(sender) pp = me.pictureStatus profile = "https://profile.line-scdn.net/" + str(pp) name = me.displayName status = "\nสเตตัส\n" + me.statusMessage pk = str(tagadd["tag"]) tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) van2 = "เวลา:"+ datetime.strftime(timeNow,'%H:%M:%S') data = { "type":"flex", "altText": pk, "contents":{ "type": "carousel", "contents": [ { "type": "bubble", "styles": { "header": {"backgroundColor": "#000000", "separator": True, "separatorColor": "#EE1289"}, "body": {"backgroundColor": "#000000", "separator": True, "separatorColor": "#000000"}, "footer": {"backgroundColor": "#000000", "separator": True, "separatorColor": "#EE1289"} }, "type": "bubble", "body": { "contents": [ { "contents": [ { "url": profile, "type": "image" }, { "type": "separator", "color": "#33FF33" }, { "url": profile, "type": "image" } ], "type": "box", "spacing": "md", "layout": "horizontal" }, { "type": "separator", "color": "#33FF33" }, { "contents": [ { "text": name, "size": "sm", "align": "center", "color": "#33FF33", "wrap": True, "weight": "bold", "type": "text" } ], "type": "box", "spacing": "md", "layout": "vertical" }, { "contents": [ { "contents": [ { "type": "text", "text": pk, "align": "center", "size": "sm", "weight": "bold", "color": "#33FF33", "wrap": True } ], "type": "box", "layout": "baseline" } ], "type": "box", "layout": "vertical" } ], "type": "box", "spacing": "md", "layout": "vertical" }, "footer": { "type": "box", "layout": "horizontal", "spacing": "sm", "contents": [ { "text": " เวลา :"+van2 +" \n ★ʄທയஆടஷະ★ ", "size": "xs", "margin": "none", "color": "#33FF33", "wrap": True, "weight": "regular", "type": "text" } ] } } ] } } sendTemplate(to, data) if op.type == 26: print ("[ SELF BOT ★ʄທയஆടஷະ★ ] ") msg = op.message text = str(msg.text) msg_id = msg.id receiver = msg.to sender = msg._from to = msg.to cmd = command(text) isValid = True setKey = settings["keyCommand"].title() if settings["setKey"] == False: setKey = '' if isValid != False: if msg.contentType == 0 and sender not in maxgieMID and msg.toType == 2: if 'MENTION' in msg.contentMetadata.keys() != None: if sets["tagsticker"] == True: name = re.findall(r'@(\w+)', msg.text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] for mention in mentionees: if maxgieMID in mention["M"]: # contact = maxgie.getContact(maxgieMID) # a = contact.displayName msg = sets["messageSticker"]["listSticker"]["tag"] if msg != None: contact = maxgie.getContact(maxgieMID) a = contact.displayName stk = msg['STKID'] spk = msg['STKPKGID'] data={'type':'template','altText': str(a)+' ส่งสติ๊กเกอร์','template':{'type':'image_carousel','columns':[{'imageUrl':'https://stickershop.line-scdn.net/stickershop/v1/sticker/{}/IOS/sticker_animation@2x.png'.format(stk),'action':{'type':'uri','uri':'https://line.me/S/sticker/{}'.format(spk)}}]}} sendTemplate(to, data) else: contact = maxgie.getContact(maxgieMID) a = contact.displayName stk = msg['STKID'] spk = msg['STKPKGID'] data={'type':'template','altText': str(a)+'ส่งสติ๊กเกอร์','template':{'type':'image_carousel','columns':[{'imageUrl':'https://stickershop.line-scdn.net/stickershop/v1/sticker/{}/IOS/sticker@2x.png'.format(stk),'action':{'type':'uri','uri':'https://line.me/S/sticker/{}'.format(spk)}}]}} sendTemplate(to, data) #==============================================================================# if op.type == 19: if maxgieMID in op.param3: apalo["Talkblacklist"][op.param2] = True if op.type == 26 or op.type == 25: msg = op.message sender = msg._from try: if mc["wr"][str(msg.text)]: maxgie.sendMessage(msg.to,mc["wr"][str(msg.text)]) except: pass if op.type == 25: msg = op.message text = msg.text msg_id = msg.id receiver = msg.to sender = msg._from if msg.toType == 0 or msg.toType == 1 or msg.toType == 2: if msg.toType == 0: if sender != maxgie.profile.mid: to = sender else: to = receiver elif msg.toType == 1: to = receiver elif msg.toType == 2: to = receiver if msg.contentType == 0: if text is None: return if msg.text.lower().startswith("แปรงคท "): delcmd = msg.text.split(" ") getx = msg.text.replace(delcmd[0] + " ","") maxgie.sendContact(msg.to,str(getx)) if msg.text.startswith("ตั้งapi "): try: delcmd = msg.text.split(" ") get = msg.text.replace(delcmd[0]+" ","").split(";;") kw = get[0] ans = get[1] mc["wr"][kw] = ans f=codecs.open('sb.json','w','utf-8') json.dump(mc, f, sort_keys=True, indent=4, ensure_ascii=False) maxgie.sendMessage(msg.to,"คีย์เวิร์ด: " + str(kw) + "\nตอบกลับ: "+ str(ans)) except Exception as Error: print(Error) if msg.text.startswith("ล้างapi "): try: delcmd = msg.text.split(" ") getx = msg.text.replace(delcmd[0] + " ","") del mc["wr"][getx] maxgie.sendMessage(msg.to, "คำ " + str(getx) + " ล้างแล้ว") f=codecs.open('sb.json','w','utf-8') json.dump(mc, f, sort_keys=True, indent=4, ensure_ascii=False) except Exception as Error: print(Error) if msg.text.lower() == "เชคapi": lisk = "[ คำตอบโต้ทั้งหมด ]\n" for i in mc["wr"]: lisk+="\nคีย์เวิร์ด: "+str(i)+"\nตอบโต้: "+str(mc["wr"][i])+"\n" lisk+="\nวิธีล้างapi >\\<\nล้างapi ตามด้วยคำที่จะล้าง" data = {"type": "text","text": "{}".format(lisk),"sentBy": {"label": "list API", "iconUrl": "https://obs.line-scdn.net/{}".format(maxgie.getContact(maxgieMID).pictureStatus),"linkUrl": "line://nv/profilePopup/mid=ue846139824ec13384cbb921b460323ac"}} sendTemplate(to,data) #==============================================================================# #==============================================================================# if op.type == 25: msg = op.message text = msg.text msg_id = msg.id receiver = msg.to sender = msg._from if msg.toType == 0: if sender != maxgie.profile.mid: to = sender else: to = receiver else: to = receiver #======================================================================== if msg.contentType == 7: if sets["messageSticker"]["addStatus"] == True: name = sets["messageSticker"]["addName"] if name != None and name in sets["messageSticker"]["listSticker"]: sets["messageSticker"]["listSticker"][name] = { "STKID": msg.contentMetadata["STKID"], "STKVER": msg.contentMetadata["STKVER"], "STKPKGID": msg.contentMetadata["STKPKGID"] } maxgie.sendMessage(to, "Success Added " + name) sets["messageSticker"]["addStatus"] = False sets["messageSticker"]["addName"] = None if sets["addSticker"]["status"] == True: stickers[sets["addSticker"]["name"]]["STKVER"] = msg.contentMetadata["STKVER"] stickers[sets["addSticker"]["name"]]["STKID"] = msg.contentMetadata["STKID"] stickers[sets["addSticker"]["name"]]["STKPKGID"] = msg.contentMetadata["STKPKGID"] f = codecs.open('sticker.json','w','utf-8') json.dump(stickers, f, sort_keys=True, indent=4, ensure_ascii=False) line.sendMessage(to, "Success Added sticker {}".format(str(sets["addSticker"]["name"]))) sets["addSticker"]["status"] = False sets["addSticker"]["name"] = "" if op.type == 26: print ("[ 26 ] RECEIVE MESSAGE") msg = op.message text = str(msg.text) msg_id = msg.id receiver = msg.to sender = msg._from to = msg.to cmd = command(text) isValid = True setKey = settings["keyCommand"].title() if settings["setKey"] == False: setKey = '' if isValid != False: if msg.toType == 0 and sender != maxgieMID: to = sender else: to = receiver if msg.contentType == 0 and to not in chatbot["botMute"]: if settings["unsendMessage"] == True: try: if msg.location != None: unsendmsg = time.time() msg_dict[msg.id] = {"location":msg.location,"from":msg._from,"waktu":unsendmsg} else: unsendmsg = time.time() msg_dict[msg.id] = {"text":msg.text,"from":msg._from,"waktu":unsendmsg} except Exception as e: print (e) if msg.contentType == 1 and to not in chatbot["botMute"]: if settings["unsendMessage"] == True: try: unsendmsg1 = time.time() path = maxgie.downloadObjectMsg(msg_id) msg_dict[msg.id] = {"from":msg._from,"image":path,"waktu":unsendmsg1} except Exception as e: print (e) if msg.contentType == 2 and to not in chatbot["botMute"]: if settings["unsendMessage"] == True: try: unsendmsg2 = time.time() path = maxgie.downloadObjectMsg(msg_id) msg_dict[msg.id] = {"from":msg._from,"video":path,"waktu":unsendmsg2} except Exception as e: print (e) if msg.contentType == 3 and to not in chatbot["botMute"]: if settings["unsendMessage"] == True: try: unsendmsg3 = time.time() path = maxgie.downloadObjectMsg(msg_id) msg_dict[msg.id] = {"from":msg._from,"audio":path,"waktu":unsendmsg3} except Exception as e: print (e) if msg.contentType == 7 and to not in chatbot["botMute"]: if settings["unsendMessage"] == True: try: unsendmsg7 = time.time() sticker = msg.contentMetadata["STKID"] link = "http://dl.stickershop.line.naver.jp/stickershop/v1/sticker/{}/android/sticker.png".format(sticker) msg_dict[msg.id] = {"from":msg._from,"sticker":link,"waktu":unsendmsg7} except Exception as e: print (e) if msg.contentType == 13 and to not in chatbot["botMute"]: if settings["unsendMessage"] == True: try: unsendmsg13 = time.time() mid = msg.contentMetadata["mid"] msg_dict[msg.id] = {"from":msg._from,"mid":mid,"waktu":unsendmsg13} except Exception as e: print (e) if msg.contentType == 14 and to not in chatbot["botMute"]: if settings["unsendMessage"] == True: try: unsendmsg14 = time.time() path = maxgie.downloadObjectMsg(msg_id) msg_dict[msg.id] = {"from":msg._from,"file":path,"waktu":unsendmsg14} except Exception as e: print (e) if op.type == 65: if op.param1 not in chatbot["botMute"]: if settings["unsendMessage"] == True: at = op.param1 msg_id = op.param2 if msg_id in msg_dict: ah = time.time() ikkeh = maxgie.getContact(msg_dict[msg_id]["from"]) if "text" in msg_dict[msg_id]: waktumsg = ah - msg_dict[msg_id]["waktu"] waktumsg = format_timespan(waktumsg) rat_ = "\nSend At :\n{} ago".format(waktumsg) rat_ += "\nText :\n{}".format(msg_dict[msg_id]["text"]) sendMentionFooter(at, ikkeh.mid, "# Resend Message\n\nMaker :\n", str(rat_)) del msg_dict[msg_id] else: if "image" in msg_dict[msg_id]: waktumsg = ah - msg_dict[msg_id]["waktu"] waktumsg = format_timespan(waktumsg) rat_ = "\nSend At :\n{} ago".format(waktumsg) rat_ += "\nImage :\nBelow" sendMentionFooter(at, ikkeh.mid, "# Resend Message\n\nMaker :\n", str(rat_)) maxgie.sendImage(at, msg_dict[msg_id]["image"]) del msg_dict[msg_id] else: if "video" in msg_dict[msg_id]: waktumsg = ah - msg_dict[msg_id]["waktu"] waktumsg = format_timespan(waktumsg) rat_ = "\nSend At :\n{} ago".format(waktumsg) rat_ += "\nVideo :\nBelow" sendMentionFooter(at, ikkeh.mid, "# Resend Message\n\nMaker :\n", str(rat_)) maxgie.sendVideo(at, msg_dict[msg_id]["video"]) del msg_dict[msg_id] else: if "audio" in msg_dict[msg_id]: waktumsg = ah - msg_dict[msg_id]["waktu"] waktumsg = format_timespan(waktumsg) rat_ = "\nSend At :\n{} ago".format(waktumsg) rat_ += "\nAudio :\nBelow" sendMentionFooter(at, ikkeh.mid, "# Resend Message\n\nMaker :\n", str(rat_)) maxgie.sendAudio(at, msg_dict[msg_id]["audio"]) del msg_dict[msg_id] else: if "sticker" in msg_dict[msg_id]: waktumsg = ah - msg_dict[msg_id]["waktu"] waktumsg = format_timespan(waktumsg) rat_ = "\nSend At :\n{} ago".format(waktumsg) rat_ += "\nSticker :\nBelow" sendMentionFooter(at, ikkeh.mid, "# Resend Message\n\nMaker :\n", str(rat_)) maxgie.sendImageWithURL(at, msg_dict[msg_id]["sticker"]) del msg_dict[msg_id] else: if "mid" in msg_dict[msg_id]: waktumsg = ah - msg_dict[msg_id]["waktu"] waktumsg = format_timespan(waktumsg) rat_ = "\nSend At :\n{} ago".format(waktumsg) rat_ += "\nContact :\nBelow" sendMentionFooter(at, ikkeh.mid, "# Resend Message\n\nMaker :\n", str(rat_)) maxgie.sendContact(at, msg_dict[msg_id]["mid"]) del msg_dict[msg_id] else: if "location" in msg_dict[msg_id]: waktumsg = ah - msg_dict[msg_id]["waktu"] waktumsg = format_timespan(waktumsg) rat_ = "\nSend At :\n{} ago".format(waktumsg) rat_ += "\nLocation :\nBelow" sendMentionFooter(at, ikkeh.mid, "# Resend Message\n\nMaker :\n", str(rat_)) maxgie.sendLocation(at, msg_dict[msg_id]["location"]) del msg_dict[msg_id] else: if "file" in msg_dict[msg_id]: waktumsg = ah - msg_dict[msg_id]["waktu"] waktumsg = format_timespan(waktumsg) rat_ = "\nSend At :\n{} ago".format(waktumsg) rat_ += "\nFile :\nBelow" sendMentionFooter(at, ikkeh.mid, "# Resend Message\n\nMaker :\n", str(rat_)) maxgie.sendFile(at, msg_dict[msg_id]["file"]) del msg_dict[msg_id] else: print ("[ ERROR ] Terjadi Error Karena Tidak Ada Data Chat Tersebut~") #----------------------------------------------------------------------------------------------------------------------------------------------------------------------- if op.type in [26]: msg = op.message text = msg.text msg_id = msg.id receiver = msg.to sender = msg._from if msg.toType == 0 or msg.toType == 2: if msg.toType == 0: to = receiver elif msg.toType == 2: to = receiver if msg.contentType == 0: if text is None: return else: if receiver in temp_flood: if temp_flood[receiver]["expire"] == True: if msg.text == "/open": temp_flood[receiver]["expire"] = False temp_flood[receiver]["time"] = time.time() maxgie.sendMessage(to,"Bot Actived") return elif time.time() - temp_flood[receiver]["time"] <= 5: temp_flood[receiver]["flood"] += 1 if temp_flood[receiver]["flood"] >= 200: temp_flood[receiver]["flood"] = 0 temp_flood[receiver]["expire"] = True maxgie.unsendMessage(msg_id) duc1(to, "🌟มีคนส่งข้อความเกิน200ระบบขอออกอัติโนมัติ🌟") maxgie.leaveGroup(to) else: temp_flood[receiver]["flood"] = 0 temp_flood[receiver]["time"] = time.time() else: temp_flood[receiver] = { "time": time.time(), "flood": 0, "expire": False } #----------------------------------------------------------------------------------------------------------------------------------------------------------------------- if op.type == 55: print ("[ 55 ] NOTIFIED READ MESSAGE") NOTIFIED_READ_MESSAGE(op) except Exception as error: logError(error) #==============================================================================# backupData() except Exception as error: logError(error) traceback.print_tb(error.__traceback__) def run(): while True: try: ops = maxgiePoll.singleTrace(count=50) if ops != None: for op in ops: loop.run_until_complete(maxgieBot(op)) maxgiePoll.setRevision(op.revision) except Exception as e: logError(e) if __name__ == "__main__": run()
[ "noreply@github.com" ]
noreply@github.com
d825976a680205df6ff714cd107c46aa4117496c
7738a8dfdc16ba4cd99c85bd07499af5f3916115
/02_strings.py
d4d3142fa0388329d19284c7d1662175d2c0cc75
[ "MIT" ]
permissive
BijuAle/PythonBasics
b7575e6173005178cdc3887968ea94453a3e423a
b7c4522114d8bc5bd2b7ddf7ea0179d9078dee35
refs/heads/master
2021-07-25T06:57:45.105139
2020-05-12T10:15:27
2020-05-12T10:15:27
171,409,391
0
0
null
null
null
null
UTF-8
Python
false
false
1,959
py
# Copyright (c) 2019 BIJU ALE # Author: BIJU ALE (github.com/BijuAle) # License: MIT License # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # Print as raw strin#G print(r'C:/net') # Escaping chars print("This is the double quote symbol - \"\"") name = "Roger Penrose" # Print value of variable firstprint(name 5 times. print((name + '\n') * 3) # Print 1st letter from a string print(name[0]) # Print 1st letter from a string from right print(name[-1]) # Print letters from of a string from 2nd to 3rd pos print(name[2:4]) # Print letters of a string from begining to 4th pos print(name[:4]) # Print letters of a string from 4th pos to last pos print(name[4:]) # Print length of a string print(len(name)) # Reverse string name = "George" name = name[::-1] print(name) # Strip unwanted chars name = " George " name2 = "George///" name = name.strip() # prints "George" name2 = name2.strip("/") # prints "George" print(name) print(name2)
[ "bijuale@hotmail.com" ]
bijuale@hotmail.com
c6da96e57e9679a40dedeb0a219a652c55337d16
c224275ff2ff634abcd072c3aa94b68bb5801944
/abcli/commands/test/__init__.py
d6e8574dda0ba95f58cd090bd9e929d370a2461e
[ "MIT" ]
permissive
john5f35/abcli
5dc6d07db5a898151848ac3defc2dbe3eb049203
fa696cf6bcc2f26fbd754e01952553ce09e5e006
refs/heads/master
2021-06-28T05:04:20.806246
2020-02-03T07:00:23
2020-02-03T07:00:23
216,186,047
3
1
MIT
2021-04-20T18:47:12
2019-10-19T10:08:29
Python
UTF-8
Python
false
false
775
py
from pathlib import Path import json from typing import * from click.testing import Result, CliRunner from pony.orm import Database from abcli.main import cli from abcli.model import init_orm def setup_db(tmp_path: Path): tmpfile = tmp_path / 'tmp.db' db = Database(provider='sqlite', filename=str(tmpfile), create_db=True) init_orm(db) return db, tmpfile def invoke_cmd(db_file: Path, args: List[str]) -> Result: config_file = db_file.parent / 'config.json' with config_file.open('w', encoding='utf-8') as fp: json.dump({ 'db': { 'provider': 'sqlite', 'filename': str(db_file) } }, fp, indent=2) return CliRunner().invoke(cli, ['--config', str(config_file)] + args)
[ "john.u5f35@gmail.com" ]
john.u5f35@gmail.com
387f51e0f8907ab9ea32d68006e9dec8eae78b6c
7d9bf6444ef321d3b8264f814fc52036c9373805
/ba_data_paths/__init__.py
19a5403cda72cfbf2efcef05a4c4be3112cc29da
[ "Apache-2.0" ]
permissive
knu2xs/ba_data_paths
ef5f34d1f054bed2beddd2eb0461c981ade7a4db
c161feec529882a2edfb2ed88b8a89cf07ec3243
refs/heads/master
2020-07-09T21:12:17.956351
2019-10-14T19:59:42
2019-10-14T19:59:42
204,085,377
0
0
null
null
null
null
UTF-8
Python
false
false
42
py
from ba_data_paths.ba_data import ba_data
[ "knu2xs@gmail.com" ]
knu2xs@gmail.com
56efb9441995eb2fda459e9d9f9ae46429b1659e
ba560dfeb43f02020057cc2f7656728c99243df5
/Cursos/Services/ListarCurso.py
aaddf05386ce21a5beb25fa6298e9555c059d5e7
[]
no_license
fabiana-carneiro/agencia-emprego
5d5746546809b479edb1d33e29d2f0ce7e657b91
9cdb1e7879f30df37e79a0011a6450cbd4d69555
refs/heads/master
2021-07-16T09:18:08.116486
2020-05-19T04:57:48
2020-05-19T04:57:48
157,045,455
0
0
null
null
null
null
UTF-8
Python
false
false
216
py
################################################# # Web API Cursos # Listagem de Cursos ################################################# from Cursos.Models.Cursos import Cursos def ListarCurso(): return Cursos
[ "fabiana.lima149@gmail.com" ]
fabiana.lima149@gmail.com
877d8cc7e9fae6f765ffa10ecee924287a1c6710
de9a7bece474db741dab82a1fe1ff2b11e934767
/POMBU/V_estimators/__init__.py
dc2e99d14456be5107c9724fff1f591601c35131
[]
no_license
GoingMyWay/RL-POMBU
9c54532ac7809b5fa31464f94f1873464c64b8c6
dbd8a9eee8cb0ece6b394921dc5fc6eaf14ac948
refs/heads/master
2022-03-20T15:31:53.168345
2019-12-19T03:00:36
2019-12-19T03:00:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
525
py
import tensorflow as tf import warnings class VEstimator: def __init__(self, env): self.env = env self.state_space = self.env.observation_space def tf_value(self, state_input): warnings.warn("Please rewrite the tf_value funciton") return None, tf.placeholder(dtype=tf.float32, shape=(None,)) def tf_uncertainty(self, state_input, Vs, V): warnings.warn("Please rewrite the tf_uncertainty funciton") return None, tf.placeholder(dtype=tf.float32, shape=(None,))
[ "qizhou@miralab.ai" ]
qizhou@miralab.ai
76688249427204abd0d2879d1ba29284a2768925
1a8a7000bc8bb3abcd51d33dfbfe952e89444313
/arodnap/wsgi.py
0d1921f88fc89c2ed08b93b7c4019216708f804c
[]
no_license
RashimNarayanTiku/arodnap
5bf996f92aea28dc32eaef2bf2d208c2ee59a477
6726760058ef9d842b867a07078ab467172d6f5a
refs/heads/main
2023-02-28T19:04:54.172659
2021-02-10T17:07:36
2021-02-10T17:07:36
336,744,352
2
0
null
null
null
null
UTF-8
Python
false
false
391
py
""" WSGI config for arodnap 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', 'arodnap.settings') application = get_wsgi_application()
[ "rnt11223344@tutanota.com" ]
rnt11223344@tutanota.com
b87d3c6c3e1f49c4c0cfbc2f7d0ecab4016fc060
fb2cc597f319380d228fc15c4008760a82203687
/var/spack/repos/builtin/packages/py-linear-operator/package.py
8133edf5144a33322dd069c679c2a2a0f9be91e9
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "LGPL-2.1-only" ]
permissive
JayjeetAtGithub/spack
c41b5debcbe139abb2eab626210505b7f930d637
6c2df00443a2cd092446c7d84431ae37e64e4296
refs/heads/develop
2023-03-21T02:35:58.391230
2022-10-08T22:57:45
2022-10-08T22:57:45
205,764,532
0
0
MIT
2019-09-02T02:44:48
2019-09-02T02:44:47
null
UTF-8
Python
false
false
888
py
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack.package import * class PyLinearOperator(PythonPackage): """A linear operator implementation, primarily designed for finite-dimensional positive definite operators (i.e. kernel matrices).""" homepage = "https://github.com/cornellius-gp/linear_operator/" pypi = "linear_operator/linear_operator-0.1.1.tar.gz" version("0.1.1", sha256="81adc1aea9e98f3c4f07f5608eb77b689bc61793e9beebfea82155e9237bf1be") depends_on("python@3.8:", type=("build", "run")) depends_on("py-setuptools", type="build") depends_on("py-setuptools-scm", type="build") depends_on("py-torch@1.11:", type=("build", "run")) depends_on("py-scipy", type=("build", "run"))
[ "noreply@github.com" ]
noreply@github.com
ffcc1b9e6e1ec606918e23f06f4ec02ac7316151
a8a661a433e8539468d1763b2971120c5c72e708
/mysite/blog/views.py
32f6b5fc67a8723e281fb3d354b07150552d74ba
[]
no_license
dynaanywhere/workingapp
0db9855b1c80a93b06e04813c2b794c4d17a9c0d
dd3ee42e0df2870362baf7ceacfc24d050f8004d
refs/heads/master
2022-07-14T16:26:35.128584
2020-05-19T16:11:44
2020-05-19T16:11:44
257,063,805
0
0
null
null
null
null
UTF-8
Python
false
false
314
py
from django.views import generic from .models import Post class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' paginate_by = 5 class PostDetail(generic.DetailView): model = Post template_name = 'post_detail.html'
[ "seunogidan@gmail.com" ]
seunogidan@gmail.com
1d8790c8a85b8e0720062a80ef94772cd8f97820
27c1356be8b459f19e3daebc049a5753d627a58f
/imageout_f.py
5cc2b3ea8e039d15d8545f5642fea7c4c84022aa
[]
no_license
kwandongSong/flower
ba187e5c01ff677378ef27f3a5e07d4cfaeaca7d
0af2b41187d864dbf42210dbaa51c23148741dba
refs/heads/master
2020-04-05T14:52:19.443738
2018-11-11T00:17:52
2018-11-11T00:17:52
156,944,392
0
0
null
null
null
null
UTF-8
Python
false
false
1,445
py
import serial import pygame import threading import time import datetime WHITE = (255,255,255) # white RGB pad_width = 600 pad_height = 400 def gainsensorval(): ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1) sumoutput = ser.readline() output= str(sumoutput) output= output.replace("b'","") output= output.replace("\\r\\n'","") finaldata= output.split("*") temsenval =float(finaldata[0]) soilsenval =int(finaldata[1]) print(temsenval) print(soilsenval) def runGame(): global gamepad, clock x=pad_width*0.05 y=pad_height*0.8 x_change=5 y_change=0 crashed = False while not crashed: now=datetime.datetime.now() nowhour= now.strftime('%M') nowsec= now.strftime('%S') nowhour=int(nowhour) nowsec=int(nowsec) # if nowhour%3 ==0 and nowsec == 0: gainsensorval() for event in pygame.event.get(): if event.type == pygame.QUIT: crashed = True if x>360: x_change=-5 elif x<10: x_change=5 x += x_change gamepad.fill(WHITE) flower(x,y) pygame.display.update() clock.tick(60) pygame.quit() def initGame(): global gamepad, clock, flowere # use global var pygame.init() # lib init gamepad = pygame.display.set_mode((pad_width,pad_height)) # display use pygame.display.set_caption('Smart flower') # name flowere = pygame.image.load('pika.png') clock = pygame.time.Clock() # set frame runGame() def flower(x,y): global gamepad, flowere gamepad.blit(flowere,(x,y)) initGame()
[ "kdh4714@naver.com" ]
kdh4714@naver.com
140475678049842dcc7a9513455b15a220182ac9
fe8d49331e73fe89be9195bf748159830d2c3622
/zerver/views/drafts.py
47b5c6fa242f0d66e718fb84c1ffb31a7fce178b
[ "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
lizzzp1/zulip
13e1a4428b5ed6d9cdc06cb291b126ee127a03e8
4e8067aadc7d5a4b2644e383898c5c731740ffd5
refs/heads/master
2022-12-13T23:44:52.351757
2020-09-12T19:04:24
2020-09-12T19:04:24
295,025,435
1
0
Apache-2.0
2020-09-12T21:00:35
2020-09-12T21:00:34
null
UTF-8
Python
false
false
5,766
py
import time from typing import Any, Dict, List, Set from django.core.exceptions import ValidationError from django.http import HttpRequest, HttpResponse from django.utils.translation import ugettext as _ from zerver.lib.actions import recipient_for_user_profiles from zerver.lib.addressee import get_user_profiles_by_ids from zerver.lib.exceptions import JsonableError from zerver.lib.message import truncate_body, truncate_topic from zerver.lib.request import REQ, has_request_variables from zerver.lib.response import json_error, json_success from zerver.lib.streams import access_stream_by_id from zerver.lib.timestamp import timestamp_to_datetime from zerver.lib.validator import ( check_dict_only, check_float, check_int, check_list, check_required_string, check_string, check_string_in, check_union, ) from zerver.models import Draft, UserProfile VALID_DRAFT_TYPES: Set[str] = {"", "private", "stream"} # A validator to verify if the structure (syntax) of a dictionary # meets the requirements to be a draft dictionary: draft_dict_validator = check_dict_only( required_keys=[ ("type", check_string_in(VALID_DRAFT_TYPES)), ("to", check_list(check_int)), # The ID of the stream to send to, or a list of user IDs. ("topic", check_string), # This string can simply be empty for private type messages. ("content", check_required_string), ], optional_keys=[ ("timestamp", check_union([check_int, check_float])), # A Unix timestamp. ] ) def further_validated_draft_dict(draft_dict: Dict[str, Any], user_profile: UserProfile) -> Dict[str, Any]: """ Take a draft_dict that was already validated by draft_dict_validator then further sanitize, validate, and transform it. Ultimately return this "further validated" draft dict. It will have a slightly different set of keys the values for which can be used to directly create a Draft object. """ content = truncate_body(draft_dict["content"]) if "\x00" in content: raise JsonableError(_("Content must not contain null bytes")) timestamp = draft_dict.get("timestamp", time.time()) timestamp = round(timestamp, 6) if timestamp < 0: # While it's not exactly an invalid timestamp, it's not something # we want to allow either. raise JsonableError(_("Timestamp must not be negative.")) last_edit_time = timestamp_to_datetime(timestamp) topic = "" recipient = None to = draft_dict["to"] if draft_dict["type"] == "stream": topic = truncate_topic(draft_dict["topic"]) if "\x00" in topic: raise JsonableError(_("Topic must not contain null bytes")) if len(to) != 1: raise JsonableError(_("Must specify exactly 1 stream ID for stream messages")) stream, recipient, sub = access_stream_by_id(user_profile, to[0]) elif draft_dict["type"] == "private" and len(to) != 0: to_users = get_user_profiles_by_ids(set(to), user_profile.realm) try: recipient = recipient_for_user_profiles(to_users, False, None, user_profile) except ValidationError as e: # nocoverage raise JsonableError(e.messages[0]) return { "recipient": recipient, "topic": topic, "content": content, "last_edit_time": last_edit_time, } def fetch_drafts(request: HttpRequest, user_profile: UserProfile) -> HttpResponse: user_drafts = Draft.objects.filter(user_profile=user_profile).order_by("last_edit_time") draft_dicts = {str(draft.id): draft.to_dict() for draft in user_drafts} return json_success({"count": user_drafts.count(), "drafts": draft_dicts}) @has_request_variables def create_drafts(request: HttpRequest, user_profile: UserProfile, draft_dicts: List[Dict[str, Any]]=REQ("drafts", validator=check_list(draft_dict_validator)), ) -> HttpResponse: draft_objects = [] for draft_dict in draft_dicts: valid_draft_dict = further_validated_draft_dict(draft_dict, user_profile) draft_objects.append(Draft( user_profile=user_profile, recipient=valid_draft_dict["recipient"], topic=valid_draft_dict["topic"], content=valid_draft_dict["content"], last_edit_time=valid_draft_dict["last_edit_time"], )) created_draft_objects = Draft.objects.bulk_create(draft_objects) draft_ids = [draft_object.id for draft_object in created_draft_objects] return json_success({"ids": draft_ids}) @has_request_variables def edit_draft(request: HttpRequest, user_profile: UserProfile, draft_id: int, draft_dict: Dict[str, Any]=REQ("draft", validator=draft_dict_validator), ) -> HttpResponse: try: draft_object = Draft.objects.get(id=draft_id, user_profile=user_profile) except Draft.DoesNotExist: return json_error(_("Draft does not exist"), status=404) valid_draft_dict = further_validated_draft_dict(draft_dict, user_profile) draft_object.content = valid_draft_dict["content"] draft_object.topic = valid_draft_dict["topic"] draft_object.recipient = valid_draft_dict["recipient"] draft_object.last_edit_time = valid_draft_dict["last_edit_time"] draft_object.save() return json_success() def delete_draft(request: HttpRequest, user_profile: UserProfile, draft_id: int) -> HttpResponse: try: draft_object = Draft.objects.get(id=draft_id, user_profile=user_profile) except Draft.DoesNotExist: return json_error(_("Draft does not exist"), status=404) draft_object.delete() return json_success()
[ "tabbott@zulip.com" ]
tabbott@zulip.com
b1c806080769dbbd96a828a4f775b7cd730fbd53
8eeef7742573a8b671648d94e448d5614272c5d6
/core2web/week2/day7/printNumber.py
33b2619d33b2dfbf88f662253e9577e0f68a5cc6
[]
no_license
damodardikonda/Python-Basics
582d18bc9d003d90b1a1930c68b9b39a85778ea7
fd239722fc6e2a7a02dae3e5798a5f1172f40378
refs/heads/master
2023-01-28T16:22:19.153514
2020-12-11T06:36:49
2020-12-11T06:36:49
270,733,918
0
0
null
null
null
null
UTF-8
Python
false
false
159
py
""" Program 1: Write a program that accepts an integer from user and print it. Input: 11 Output: 11 """ v=(int)(input("enter the number")) print("output",v)
[ "damodar2dikonda@gmail.com" ]
damodar2dikonda@gmail.com
d60ba409026c0f28c8df428740be38b2c140b052
c3b75410ee83053ac53e7229708bc6c72ad47d67
/프로그래밍기초/트리재귀코드들.py
d5862ca369f002acef1f496ab20e9acc4ce52c5c
[]
no_license
sooyeon9/python
a60a0b3f3ec9327db22f5a14136c5cf6e3d8b6f7
bf5f00ed9cd8499c83ad9dbf114a7041e3943dfd
refs/heads/master
2021-04-09T10:47:50.062357
2018-03-16T08:00:25
2018-03-16T08:00:25
125,483,269
0
0
null
null
null
null
UTF-8
Python
false
false
3,659
py
# 트리재귀 모범코드들 # Tree Recursion # Fibonacci Sequence def fib(n): if n > 1: return fib(n-1) + fib(n-2) else: return n def fibtail(n): def loop(k,old,new): if counter < n: return loop(k+1,new,old+new) else: # k == n return new return loop(1,1,0) def fibwhile(n): k = 1 old, new = 0, 1 while k < n: k += 1 old, new = new, old+new # �룞�떆 吏��젙 # temp = new # new = old + new # old = temp return new def fibfor(n): old, new = 0, 1 for _ in range(2,n+1): old, new = new, old+new return new def fibseq(n): fibs = [0,1] for k in range(2,n+1): fib = fibs[k-1]+fibs[k-2] fibs.append(fib) return fibs def fib2(n): return fibseq(n).pop() # Combination def comb(n,r): if not (r == 0 or r == n): return comb(n-1,r-1) + comb(n-1,r) else: return 1 def pascal(n,r): table = [[]]*(n-r+1) table[0] = [1]*(r+1) for i in range(1,n-r+1): table[i] = [1] for i in range(1,n-r+1): for j in range(1,r+1): newvalue = table[i][j-1] + table[i-1][j] table[i].append(newvalue) return table[n-r][r] # Tower of Hanoi # assume n >= 0 def tower(n,src,dst,tmp) : if n > 0 : tower(n-1,src,tmp,dst) print("move from", src, "to", dst) tower(n-1,tmp,dst,src) else : pass # Calulation table def gugudan1(): for i in range(2,10): for j in range(1,10): if j % 3 == 0: print(i,"x",j,"=",str(i*j).rjust(2)) else: print(i,"x",j,"=",str(i*j).rjust(2),end=" ") if i != 9: print() def gugudan2(): for k in [2,6]: for i in range(1,10): for j in range(k,k+4): print(j,"x",i,"=",str(j*i).rjust(2),end=" ") print() if k == 2: print() # Sliding Puzzle def get_number(): num = input("Type the number you want to move (Type 0 to quit): ") while not (num.isdigit() and 0 <= int(num) <= 15): num = input("Type the number you want to move (Type 0 to quit): ") return int(num) def create_init_board(): return [[15, 14, 13, 12], [11, 10, 9, 8], [7, 6, 5, 4], [3, 2, 1, 0]] def set_goal_board(): return [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 0]] def print_board(board): for row in board: for item in row: if item == 0: print(" ", end=" ") elif 10 <= item <= 15: print(item,end=" ") else: print(str(item).rjust(2),end=" ") print() def find_position(num,board): for i in range(len(board)): for j in range(len(board)): if num == board[i][j]: return (i,j) def move(pos,opened,board): (x,y) = pos if opened == (x-1,y) or opened == (x+1,y) or \ opened == (x,y-1) or opened == (x,y+1): board[opened[0]][opened[1]] = board[x][y] board[x][y] = 0 return (pos,board) else: print("Can't move! Try again.") return (opened,board) def sliding_puzzle(): board = create_init_board() goal = set_goal_board() opened = (3,3) while True: print_board(board) if board == goal: print("Congratulations!") break num = get_number() # get number between 0 and 15 if num == 0: break pos = find_position(num,board) (opened,board) = move(pos,opened,board) print("Please come again.")
[ "sooyean9@naver.com" ]
sooyean9@naver.com
4226a33df187e6cbc3842c4c6d0f777e82bd2e15
3ab618da41c4ad11cbfba8de1ce0961dc0affcaa
/cnavg/preprocess/segmentCNVs.py
b7dcfaea4c2427e19446d4220a7c382788461324
[ "BSD-3-Clause" ]
permissive
dzerbino/cn-avg
35ca23c225b548258ab07de64971cf7800247ae8
884e02aa8ba8ca643485d9969999be975a71b1df
refs/heads/master
2021-01-21T21:48:53.438206
2015-09-11T08:09:45
2015-09-11T08:09:45
6,695,890
3
3
null
null
null
null
UTF-8
Python
false
false
5,878
py
# Copyright (c) 2012, Daniel Zerbino # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # (1) Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # (2) 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. # # (3)The name of the author may not be used to # endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. #!/usr/bin/env python """Smooth out brute CNV calls""" import sys import cbs.cbs as cbs from cnv import CNV def _mergeCNVs_Forward(A, B): for i in range(A.ploidy()): A.val[i] = (A.val[i] * A.length() + B.val[i] * B.length() / 2) / (A.length() + B.length() / 2) assert A.val > 0 if B.softStart is not None: A.finish = (B.softStart + B.finish) / 2 else: A.finish = B.finish if B.softFinish is not None: A.softFinish = (B.start + B.softFinish) / 2 else: A.softFinish = B.start A.numMarks += B.numMarks / 2 def _mergeCNVs_Backward(A, B): for i in range(A.ploidy()): B.val[i] = (A.val[i] * A.length() / 2 + B.val[i] * B.length()) / (A.length() / 2 + B.length()) assert B.val > 0 if A.softFinish is not None: B.start = (A.start + A.softFinish) / 2 else: B.start = A.start if A.softStart is not None: B.softFinish = (A.softStart + A.finish) / 2 else: B.softFinish = A.finish B.numMarks += A.numMarks / 2 def _filterCNVs(cnvs): filtered = [] for index in range(len(cnvs)): cnv = cnvs[index] if cnv.numMarks < 5: if len(filtered) > 0: valsA = sum(filtered[-1].val) else: valsA = 0 valsB = sum(cnv.val) #if len(filtered) > 0 and filtered[-1].chr == cnv.chr and filtered[-1].ploidy() == cnv.ploidy() and valsB > 0 and valsA / float(valsB) > 0.5 and valsA / float(valsB) < 2: if len(filtered) > 0 and filtered[-1].chr == cnv.chr: _mergeCNVs_Forward(filtered[-1], cnv) else: filtered += [cnv] if index + 1 < len(cnvs) and cnvs[index+1].chr == cnv.chr and cnv.ploidy() == cnvs[index+1].ploidy(): _mergeCNVs_Backward(cnv, cnvs[index+1]) else: filtered += [cnv] return filtered def _glueCNV(cnvs, index): prev = cnvs[index-1] cnv = cnvs[index] if prev.chr == cnv.chr and prev.finish < cnv.start and prev.finish > cnv.start - 50: prev.finish = cnv.start def _glueCNVs(cnvs): map(lambda X: _glueCNV(cnvs, X), range(1, len(cnvs))) def _computeBorderMargins(segments, sortedCNVs): print "Computing CNV border margins" cnvindex = 0 for segment in segments: while len(sortedCNVs) > 0 and sortedCNVs[cnvindex] < segment: cnvindex += 1 assert cnvindex < len(sortedCNVs) if cnvindex > 0 and sortedCNVs[cnvindex - 1].chr == segment.chr: segment.start = sortedCNVs[cnvindex - 1].start else: segment.start = sortedCNVs[cnvindex].start segment.softStart = sortedCNVs[cnvindex].finish while cnvindex < len(sortedCNVs) and sortedCNVs[cnvindex] == segment: cnvindex += 1 # Backing up to last valid index assert cnvindex > 0 cnvindex -= 1 segment.softFinish = sortedCNVs[cnvindex].start if segment.softFinish == segment.start: segment.softStart = sortedCNVs[cnvindex].start + 1 segment.softFinish = sortedCNVs[cnvindex].finish - 1 if segment.softFinish <= segment.softStart: segment.softFinish = segment.softStart + 1 if cnvindex < len(sortedCNVs) - 1 and sortedCNVs[cnvindex + 1].chr == segment.chr: segment.finish = sortedCNVs[cnvindex + 1].finish else: segment.finish = sortedCNVs[cnvindex].finish assert segment.finish > segment.start if segment.softFinish >= segment.finish: print cnvindex print len(sortedCNVs) - 1 print sortedCNVs[cnvindex + 1].chr print segment.chr print sortedCNVs[cnvindex].start print segment.softStart print segment.softFinish if cnvindex < len(sortedCNVs) - 1: print sortedCNVs[cnvindex + 1].finish print sortedCNVs[cnvindex].finish segment.validate() return segments ########################################### ## Master function ########################################### def _median(X): return (X.start + X.finish)/2 def segmentCNVs(cnvs): print "Segmentation of CNV data" sortedCNVs = sorted(cnvs) _glueCNVs(sortedCNVs) chrom = [X.chr for X in sortedCNVs] pos = map(_median, sortedCNVs) vals = [X.val[0] for X in sortedCNVs] cbsCNVS = cbs.run(chrom, pos, vals) sortedCBSCNVs = sorted(cbsCNVS) filtered = _filterCNVs(sortedCBSCNVs) return _computeBorderMargins(filtered, sortedCNVs) ########################################### ## Unit test ########################################### def main(): region1 = CNV("chr1", 1000, 2000, [1.0], "A") region2 = CNV("chr1", 2000, 3000, [1.0], "B") region3 = CNV("chr1", 3000, 4000, [5.0], "C") region4 = CNV("chr1", 4000, 5000, [5.0], "D") print "\n".join(map(str, segmentCNVs([region1, region2, region3, region4]))) if __name__ == "__main__": main()
[ "dzerbino@soe.ucsc.edu" ]
dzerbino@soe.ucsc.edu
e4e5e481233d10aa848528ddd6839ce75ca7e3ec
d485838edf2a80d583f8cb35926367deb51a7f80
/py/net_proto/proto.py
770d9de7bcceb78eb1a1d1ce6b797b5a4cdabf43
[]
no_license
xuy1202/projects
fc0a8870b51ebd54109ac479198dc13fca3241a7
627fd87a050d4e1798f3b5a9fec1dbb4b38f3a21
refs/heads/master
2021-01-23T13:38:10.581358
2017-07-26T11:39:07
2017-07-26T11:39:07
42,382,953
0
0
null
null
null
null
UTF-8
Python
false
false
47
py
#coding: utf-8 ParseError = '_parse_error'
[ "xuyang-pd@dev1.netlab.corp.qihoo.net" ]
xuyang-pd@dev1.netlab.corp.qihoo.net
3580c0c25dc1cefc1b8530f46a50b057a46d0467
a0690baf8400629d27baeb0b72bdad1aaaa1074a
/basis_readme/6.DNN-IRM/dataset.py
d1b6da953314c4d93eebe642c6eee638bb634f23
[]
no_license
HuaChung/speech_enhancement_awesome
09313e8240823812cad7236ebd44d13f20d06e65
f53d8279550de2d49e11e601f4f2c89efe25e3d1
refs/heads/master
2023-08-22T18:47:19.313004
2021-10-27T02:04:17
2021-10-27T02:04:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,315
py
import os import torch import numpy as np from torch.utils.data import Dataset,DataLoader from hparams import hparams import librosa import random import soundfile as sf def feature_stft(wav,para): spec = librosa.stft(wav, n_fft=para["N_fft"], win_length = para["win_length"], hop_length = para["hop_length"], window =para["window"]) mag = np.abs(spec) phase = np.angle(spec) return mag.T, phase.T # T x D # feature T x D # out T x D*(2*expand+1) def feature_contex(feature,expend): feature = feature.unfold(0,2*expend+1,1) # T x D x 2*expand+1 feature = feature.transpose(1,2) # T x 2*n_expand+1 x D feature = feature.view([-1,(2*expend+1)*feature.shape[-1]]) # T x D * 2*n_expand+1 return feature def get_mask(clean,noisy,para): noise = noisy-clean clean_mag,_ = feature_stft(clean,para) noisy_mag,_ = feature_stft(noisy,para) noise_mag,_ = feature_stft(noise,para) mask = (clean_mag ** 2 / (clean_mag ** 2 + noise_mag ** 2))**(0.5) return clean_mag,noisy_mag,mask class TIMIT_Dataset(Dataset): def __init__(self,para): self.file_scp = para.file_scp self.para_stft = para.para_stft self.n_expand = para.n_expand files = np.loadtxt(self.file_scp,dtype = 'str') self.clean_files = files[:,1].tolist() self.noisy_files = files[:,0].tolist() print(len(self.clean_files)) def __len__(self): return len(self.clean_files) def __getitem__(self,idx): # 读取干净语音 clean_wav,fs = sf.read(self.clean_files[idx],dtype = 'float32') clean_wav = clean_wav.astype('float32') # 读取含噪语音 noisy_wav,fs = sf.read(self.noisy_files[idx],dtype = 'float32') noisy_wav = noisy_wav.astype('float32') # 进行 特征提取 clean_mag,noisy_mag,mask = get_mask(clean_wav,noisy_wav,self.para_stft) # 转为torch格式 X_train = torch.from_numpy(np.log(noisy_mag**2)) Y_train = torch.from_numpy(mask) # 拼帧 X_train = feature_contex(X_train,self.n_expand) Y_train = Y_train[self.n_expand:-self.n_expand,:] return X_train, Y_train def my_collect(batch): batch_X = [item[0] for item in batch] batch_Y = [item[1] for item in batch] batch_X = torch.cat(batch_X,0) batch_Y = torch.cat(batch_Y,0) return[batch_X.float(),batch_Y.float()] if __name__ == '__main__': # 数据加载测试 para = hparams() m_Dataset= TIMIT_Dataset(para) m_DataLoader = DataLoader(m_Dataset,batch_size = 2,shuffle = True, num_workers = 4, collate_fn = my_collect) for i_batch, sample_batch in enumerate(m_DataLoader): train_X = sample_batch[0] train_Y = sample_batch[1] print(train_X.shape) print(train_Y.shape)
[ "tower.ysable@gmail.com" ]
tower.ysable@gmail.com
ef503885f150b97c1b8d4603130113bbdeee0874
bb65865a35137450140faba9622a0caa5d74ae21
/phasing/plot-N50-coverages.py
6f5cc4cec04ac26497134feda91764da9a514a32
[]
no_license
PacificBiosciences/hg002-ccs
3b98630b799a528226954addd9d033b8a37934f0
dded2678b0bd758f5cc6faf4557df712714c624c
refs/heads/master
2021-08-07T14:58:15.821694
2021-08-01T02:50:22
2021-08-01T02:50:22
169,060,449
17
9
null
2021-08-01T02:30:53
2019-02-04T10:17:27
Python
UTF-8
Python
false
false
1,127
py
import matplotlib.pyplot as plt; plt.rcdefaults() import numpy as np import matplotlib.pyplot as plt import argparse parser = argparse.ArgumentParser(prog='plot-N50-coverages.py', description=__doc__) parser.add_argument('tsv', metavar='FILE', nargs='+', help='tsv files containing N50s') parser.add_argument('output', metavar='OUTPUT', help='name of output file') args = parser.parse_args() def extract_rate(filename): splitted = filename.split('.') for element in splitted: if element[0:4] == 'rate': return int(element[4:]) assert(False) data = [] for filename in args.tsv: value = -1 rate = extract_rate(filename) for line in open(filename, 'r'): splitted = line.split() if splitted[1] == 'ALL': value = int(splitted[21]) continue assert(value is not -1) data.append( (rate, value) ) # sort values low coverage -> high coverage data = sorted(data, key=lambda x: x[0]) print(data) coverages = [0.01*i[0] for i in data] n50s = [i[1] for i in data] print('coverages:', coverages) print('n50s:', n50s) plt.plot(coverages, n50s, 'bo-') plt.xlabel('rate') plt.ylabel('N50') plt.savefig(args.output)
[ "awenger@pacificbiosciences.com" ]
awenger@pacificbiosciences.com
0eb66d998b161fbbd062f926526bb83adaeeba70
1d0a223b743b005cd2ecd904337178e322e63534
/chapter10/file.reader.py
15088ab8515910c4dc81f9a8f361f65a07a60000
[]
no_license
Stefanroets180/all-my-Python-work
285607ce1ef50aac4897e0721ead4daca01fa6e0
d7937b51a309ebd051bef90e78154447b6e9a8ea
refs/heads/main
2023-03-27T10:15:54.793489
2021-03-18T12:26:20
2021-03-18T12:26:20
349,063,278
0
0
null
null
null
null
UTF-8
Python
false
false
113
py
filename = 'pi_digital.txt' with open(filename) as file_object: for line in file_object: print(line)
[ "61413955+Stefanroets180@users.noreply.github.com" ]
61413955+Stefanroets180@users.noreply.github.com
2d185bbe654caec61b928db73a33eeb507cd8e72
ffac7f80e02a0a6ddb125b30086f022d4114a4c2
/Scan-Small-ROI-Della/scan_interface.py
2a55a8aa66d892f0cdc55e184acc837676401b4c
[]
no_license
jeansom/DM-Catalog-Scan
ca20400f1a4133ca0aa49a23932e6d6bbe2a871a
6c22043fdc837de606733a4ef2e7c30462bdaab8
refs/heads/master
2021-04-25T06:46:43.883494
2017-10-11T13:58:59
2017-10-11T13:58:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,439
py
import argparse from scan import Scan from local_dirs import * parser = argparse.ArgumentParser() parser.add_argument("--perform_scan", action="store", dest="perform_scan", default=1,type=int) parser.add_argument("--perform_postprocessing", action="store", dest="perform_postprocessing", default=1,type=int) parser.add_argument("--imc", action="store", dest="imc", default=0,type=int) parser.add_argument("--iobj", action="store", dest="iobj", default=0,type=int) parser.add_argument("--Asimov", action="store", dest="Asimov", default=0,type=int) parser.add_argument("--save_dir", action="store", dest="save_dir", default="",type=str) parser.add_argument("--load_dir", action="store", dest="load_dir", default="",type=str) parser.add_argument("--float_ps_together", action="store", dest="float_ps_together", default=1,type=int) parser.add_argument("--noJprof", action="store", dest="noJprof", default=0,type=int) parser.add_argument("--start_idx", action="store", dest="start_idx", default=0,type=int) parser.add_argument("--floatDM", action="store", dest="floatDM", default=0,type=int) parser.add_argument("--mc_dm", action="store", dest="mc_dm", default=-1,type=int) parser.add_argument("--catalog_file", action="store", dest="catalog_file", default="DarkSky_ALL_200,200,200_v3.csv",type=str) parser.add_argument("--diff", action="store", dest="diff", default="p7",type=str) parser.add_argument("--randlocs", action="store", dest="randlocs", default=0,type=int) parser.add_argument("--channel", action="store", dest="channel", default="b",type=str) parser.add_argument("--eventtype", action="store", dest="eventtype", default=0,type=int) parser.add_argument("--Burkert", action="store", dest="Burkert", default=0,type=int) parser.add_argument("--use_boost", action="store", dest="use_boost", default=0,type=int) parser.add_argument("--boost", action="store", dest="boost", default=1,type=int) results = parser.parse_args() iobj=results.iobj imc=results.imc Asimov=results.Asimov save_dir=results.save_dir load_dir=results.load_dir float_ps_together=results.float_ps_together noJprof=results.noJprof start_idx=results.start_idx floatDM=results.floatDM perform_scan=results.perform_scan perform_postprocessing=results.perform_postprocessing mc_dm=results.mc_dm catalog_file=results.catalog_file diff=results.diff randlocs=results.randlocs channel=results.channel eventtype=results.eventtype Burkert=results.Burkert use_boost=results.use_boost boost=results.boost if load_dir != "": load_dir = work_dir + '/Scan-Small-ROI/data/' + str(load_dir) + "/" else: load_dir = None Scan(perform_scan=perform_scan, perform_postprocessing=perform_postprocessing, imc=imc, iobj=start_idx+iobj, Asimov=Asimov, float_ps_together=float_ps_together, noJprof=noJprof, floatDM=floatDM, diff=diff, mc_dm=mc_dm, load_dir=load_dir, verbose=True, catalog_file=catalog_file, randlocs=randlocs, channel=channel, eventtype=eventtype, Burkert=Burkert, use_boost=use_boost, boost=boost, save_dir=work_dir + '/Scan-Small-ROI/data/' + str(save_dir) + "/")
[ "smsharma@princeton.edu" ]
smsharma@princeton.edu
b4358aa6af74467e6805dc7e3b11ff77c479f70a
09744f85b0aa4c1e8525260cfdb894c76bf2d58e
/Resources/Examples/PycharmProjects/Image Processing/Image4.py
4135bc25ca44edf82ffd06dd20340548e6a994d0
[ "CC0-1.0" ]
permissive
ehfo0/eYSIP_2015_Depth_Mapping_Kinect
5ad2ca7dbd6a5a8d721fc7d033648b53a643416c
f8e9e0297ed3ef9f9ab6e35252a1329f6e5a1623
refs/heads/master
2021-01-25T08:23:01.711296
2015-07-15T15:04:42
2015-07-15T15:04:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,087
py
__author__ = 'aniket' import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('paka.jpg',0) ret1,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY) ret2,th2 = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) blur = cv2.GaussianBlur(img,(5,5),0) ret3,th3 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) images = [img, 0, th1, img, 0, th2, blur, 0, th3] titles = ['Original Noisy Image','Histogram','Global Thresholding (v = 127)','Original Noisy Image','Histogram', "Otsu's Thresholding",'Gaussian filtered Image','Histogram',"Otsu's Thresholding"] for i in xrange(3): plt.subplot(3,3,i*3+1),plt.imshow(images[i*3],'gray') plt.title(titles[i*3]), plt.xticks([]), plt.yticks([]) plt.subplot(3,3,i*3+2), plt.hist(images[i*3].ravel(),256) plt.title(titles[i*3+1]), plt.xticks([]), plt.yticks([]) plt.subplot(3,3,i*3+3), plt.imshow(images[i*3+2],'gray') plt.title(titles[i*3+2]), plt.xticks([]), plt.yticks([]) plt.show() """This code gives the comparison of otsu thresholding and binary thresh"""
[ "aniket10051994@gmail.com" ]
aniket10051994@gmail.com
a83a11d7de133095f348d5920113cb836562415e
8e95e79840005f6c34dfb978e8fe6e0ec4f7f643
/7_Image Processing in Python_/29_Edges.py
f4953bd068a7dbf38dcc7620a093d0b9b0858f0d
[]
no_license
Naysla/Machine_Learning
a0593cac41ef1561f14bec55780570b82fc37720
e75d5cd2894ccb005228ab3da87dde9025385a08
refs/heads/master
2023-02-01T17:19:32.413609
2020-12-22T20:36:45
2020-12-22T20:36:45
323,708,628
0
0
null
null
null
null
UTF-8
Python
false
false
577
py
#Edges #In this exercise you will identify the shapes in a grapefruit image by detecting the edges, using the Canny algorithm. #Image preloaded as grapefruit. #The color module has already been preloaded for you. # Import the canny edge detector from skimage.feature import canny # Convert image to grayscale grapefruit = color.rgb2gray(grapefruit) # Apply canny edge detector canny_edges = canny(grapefruit) # Show resulting image show_image(canny_edges, "Edges with Canny") #You can see the shapes and details of the grapefruits of the original image being highlighted.
[ "60472499+Naysla@users.noreply.github.com" ]
60472499+Naysla@users.noreply.github.com
e41804e5078006e13023aee28491f1f6eb99284b
736cd2f00631fed8a2f545ac9da0b0164862407e
/Face_Recognition(using KNN)/face_recog.py
c9b9d2ac303d3b8ced767c1d9c1b1da2bd778f95
[]
no_license
mihirsood/kNN-Face-Detection-Recognition
9428eeca996185a3e5bccbfc161d49e5631490f0
86c42d4c7167a376d2ac27811babcc94425601bc
refs/heads/master
2022-11-30T12:20:42.967465
2020-08-05T21:57:55
2020-08-05T21:57:55
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,783
py
# Recognise Faces using some classification algorithms like KNN #1. Load the training data(numpy arrays of all the persons) # x- values are stores in the numpy arrays # y- values we need to assign for each Person # 2. Read a video stream using opencv # 3. Extract faces out of it # 4. Use knn to find the prediction of face (int ) # 5. Map the Predicted id to name of the User # 6. display the predictions on the screen - bounding box and name import os import numpy as np import cv2 dataset_path = "./data/" face_data=[] labels=[] for fx in os.listdir(dataset_path): if fx.endswith(".npy"): l = fx.split(".")[0] face_item=np.load(dataset_path+fx) print(face_item.shape) print(l) face_data.append(face_item) # appending labels : times => faces for i in range(len(face_item)): labels.append(l) # face_data[0].shape # # face_data X=np.concatenate(face_data,axis=0) Y = np.array(labels) print(X.shape) print(Y.shape) #KNN def distance(pA,pB): return np.sum((pB-pA)**2)**0.5 def kNN(X, y, x_query, k = 5): """ X -> (m,30000) np array y -> (m,) np array x_query -> (1,2) np array k -> scalar int do knn for classification """ m = X.shape[0] distances = [] for i in range(m): dis = distance(x_query, X[i]) distances.append((dis,y[i])) distances = sorted(distances) distances = distances[:k] distances = np.array(distances) labels = distances[:,1] uniq_label,counts = np.unique(labels,return_counts=True) pred = uniq_label[counts.argmax()] return pred # Test Face Recog cam = cv2.VideoCapture(0) face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml") while True: ret, frame = cam.read() if ret == False: continue gray_frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) #bgr-> grayscale conversion b/c haarcascade works on gray scale 24x24 window faces = face_cascade.detectMultiScale(gray_frame,1.3,5) for face in faces: face_section = None x,y,w,h = face cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2) offset = 10 #increasing 10 pixels on all the sides and cropping the new file face_section = frame[y-offset:y+h+offset,x-offset:x+w+offset] face_section = cv2.resize(face_section,(100,100)) name = kNN(X,Y,face_section.reshape(1,-1)) cv2.putText(frame,name,(x,y-10),cv2.FONT_HERSHEY_PLAIN,5,(255,255,255),2,cv2.LINE_AA) cv2.imshow("window",frame) key=cv2.waitKey(1) #1ms # 0 means wait for indefinite time if key==ord("q"): # ord returns ascii vale break cam.release() cv2.destroyAllWindows()
[ "noreply@github.com" ]
noreply@github.com
6f336c38ab7c777f19b1fdd414f93f0af5423883
c8ef98a2fb6d2592b53bf3338e639d0707224944
/scott/leaf/nn_multi_leaf.py
414f140d96dd7f05510083761582267d9dc8b675
[]
no_license
yysy2/CAS-projects
0bc374c318c04a1c5aa1fe41c1779bd42d4f1e13
d1e353e8b189748f401fef09c58f03240a52e465
refs/heads/master
2020-07-27T01:19:19.678379
2016-12-09T12:39:47
2016-12-09T12:39:47
73,706,887
1
0
null
2016-11-30T18:20:23
2016-11-14T13:25:09
Python
UTF-8
Python
false
false
19,778
py
#-----------------BEGIN HEADERS----------------- import numpy as np #import matplotlib.pyplot as plt from scipy import stats import csv import scipy np.set_printoptions(threshold=np.nan) import contextlib import pdb from random import shuffle import myfunctions_leaf as mf @contextlib.contextmanager def printoptions(*args, **kwargs): original = np.get_printoptions() np.set_printoptions(*args, **kwargs) yield np.set_printoptions(**original) #-----------------END HEADERS----------------- #-----------------BEGIN BODY----------------- print("Started running") ## Setup the parameters you will use for this exercise -- YOU WILL NEED TO SET THESE FLAGS BEFORE STARTING!!! ############################################################################################################# ##Basic flags #input_layer_size = 784 # 28x28 Input Images of Digits hidden_layer_size1 = 120 # hidden units, unless allow_optimisation = True hidden_layer_size2 = 1600 # hidden units, unless allow_optimisation = True, ignored if number_of_layers = 3 hidden_layer_size3 = 1600 # hidden units, unless allow_optimisation = True, ignored if number_of_layers = 3 or 4 #num_labels = 8 # 10 labels, from 0 to 9 number_of_layers = 3 # Gives the number of layers in nn. 3, 4, 5 are available. lambda_reg = 0.0006 # Regularisation parameter, allow_optimisation = True ratio_training_to_cv = 0.7 # Sets the ratio of training to cv data use_all_training_data = False # If True, will use all training data instead of spliting into train and CV ##Initialisation use_random_initialisation = True # If true, it will use random initialisation, if false, will use preset random values (FOR DEBUGGING ONLY) -- ONLY WORKS IF ALLOW_OPTIMISER = FALSE AND HIDDEN LAYER = 25 AND LAYERS = 3 ##Gradient checking use_gradient_checking = False # If true, will turn on gradient checking (FOR DEBUGGING/FIRST RUN ONLY) only_gradient_checking = False # If true, will exit after gradient checking ##Minimiser options iteration_number = 4000 # Number of iterations minimisation_method = "L-BFGS-B" # Sets minimiser method, recommended L-BFGS-B or TNC use_minimisation_display = True # Sets whether we display iterations ##Optimisation options allow_optimisation = False # If True, will try to find best hidden layers and lambda. It will ignore inputted numbers. Only work if use_all_training_data = False and use_random_initialisation = True only_optimisation = False # If True, will exit after optimisation, only works if allow_optimisation = True use_logloss = True # If True, will use logloss instead of accuracy to optimise optimisation_iteration = 300 # Sets how many iterations when doing optimisation optimisation_jump = 2.0 # Sets how multiplier lambda_reg_lower_threshold = 0.002 #1.0 #5.0 # Sets the min lambda threshold for optimisation lambda_reg_upper_threshold = 0.130 #300.0 #350.0 # Sets the max lambda threshold for optimisation d1_reg_lower_threshold = 25 # Sets the min d1 threshold for optimisation d1_reg_upper_threshold = 3500 # Sets the max d1 threshold for optimisation d2_reg_lower_threshold = 25 # Sets the min d1 threshold for optimisation d2_reg_upper_threshold = 3500 # Sets the max d1 threshold for optimisation d3_reg_lower_threshold = 25 # Sets the min d1 threshold for optimisation d3_reg_upper_threshold = 3500 # Sets the max d1 threshold for optimisation ##Output CSV file options output_test_submission = True # If True, will print out test data for submission ##Reading in data ############################################################################################################# m, n, x, y, m_train, m_cv, x_train, x_cv, y_train, y_cv, leafid, leafid_train, leafid_cv, num_labels = mf.readincsv(ratio_training_to_cv); input_layer_size = n #Gradient checking ############################################################################################################# if use_gradient_checking == True: print('Doing gradient checking') if number_of_layers == 3: mf.smallNN3(lambda_reg); elif number_of_layers == 4: mf.smallNN4(lambda_reg); elif number_of_layers == 5: mf.smallNN5(lambda_reg); if only_gradient_checking == True: exit() #Optimising d and lambda ############################################################################################################# if allow_optimisation == True: if use_all_training_data == True: print("Must set use_all_training_data = False for this to work") exit() elif use_random_initialisation == False: print("Must set use_random_initialisation = True for this to work") else: print('Doing optimisation') if number_of_layers == 3: del(hidden_layer_size1) del(lambda_reg) hidden_layer_size1, lambda_reg = mf.myoptimiser3(use_logloss, optimisation_jump, optimisation_iteration, input_layer_size, num_labels, x_train, y_train, x_cv, y_cv, minimisation_method, lambda_reg_lower_threshold, lambda_reg_upper_threshold, d1_reg_lower_threshold, d1_reg_upper_threshold); elif number_of_layers == 4: del(hidden_layer_size1) del(hidden_layer_size2) del(lambda_reg) hidden_layer_size1, hidden_layer_size2, lambda_reg = mf.myoptimiser4(use_logloss, optimisation_jump, optimisation_iteration, input_layer_size, num_labels, x_train, y_train, x_cv, y_cv, minimisation_method, lambda_reg_lower_threshold, lambda_reg_upper_threshold, d1_reg_lower_threshold, d1_reg_upper_threshold, d2_reg_lower_threshold, d2_reg_upper_threshold); elif number_of_layers == 5: del(hidden_layer_size1) del(hidden_layer_size2) del(lambda_reg) hidden_layer_size1, hidden_layer_size2, hidden_layer_size2, lambda_reg = mf.myoptimiser5(use_logloss, optimisation_jump, optimisation_iteration, input_layer_size, num_labels, x_train, y_train, x_cv, y_cv, minimisation_method, lambda_reg_lower_threshold, lambda_reg_upper_threshold, d1_reg_lower_threshold, d1_reg_upper_threshold, d2_reg_lower_threshold, d2_reg_upper_threshold, d3_reg_lower_threshold, d3_reg_upper_threshold); else: print("Number of layers must be 3, 4 or 5!!! :(") if number_of_layers == 3: print("Using Hidden_layer_size: " + str(hidden_layer_size1) + ", lambda: " + str(lambda_reg)) elif number_of_layers == 4: print("Using Hidden_layer_size: " + str(hidden_layer_size1) + ", " + str(hidden_layer_size2) + ", lambda: " + str(lambda_reg)) elif number_of_layers == 5: print("Using Hidden_layer_size: " + str(hidden_layer_size1) + ", " + str(hidden_layer_size2) + ", " + str(hidden_layer_size3) + ", lambda: " + str(lambda_reg)) else: print("Number of layers must be 3, 4 or 5") exit() if only_optimisation == True: exit() #Randomly initalize weights for Theta_initial ############################################################################################################# print('Initialising weights') if use_random_initialisation == True: if number_of_layers == 3: theta1_initial = mf.randinitialize(input_layer_size, hidden_layer_size1); theta2_initial = mf.randinitialize(hidden_layer_size1, num_labels); theta_initial_ravel = np.concatenate((np.ravel(theta1_initial), np.ravel(theta2_initial))) elif number_of_layers == 4: theta1_initial = mf.randinitialize(input_layer_size, hidden_layer_size1); theta2_initial = mf.randinitialize(hidden_layer_size1, hidden_layer_size2); theta3_initial = mf.randinitialize(hidden_layer_size2, num_labels); theta_initial_ravel = np.concatenate((np.ravel(theta1_initial), np.ravel(theta2_initial), np.ravel(theta3_initial))) elif number_of_layers == 5: theta1_initial = mf.randinitialize(input_layer_size, hidden_layer_size1); theta2_initial = mf.randinitialize(hidden_layer_size1, hidden_layer_size2); theta3_initial = mf.randinitialize(hidden_layer_size2, hidden_layer_size3); theta4_initial = mf.randinitialize(hidden_layer_size3, num_labels); theta_initial_ravel = np.concatenate((np.ravel(theta1_initial), np.ravel(theta2_initial), np.ravel(theta3_initial), np.ravel(theta4_initial))) else: print("Number of layers must be 3, 4 or 5") exit() else: theta1_initial = np.genfromtxt('tt1.csv', delimiter=',') theta2_initial = np.genfromtxt('tt2.csv', delimiter=',') theta_initial_ravel = np.concatenate((np.ravel(theta1_initial), np.ravel(theta2_initial))) #Minimize nncostfunction ############################################################################################################# print('Doing minimisation') if use_all_training_data == True and number_of_layers == 3: fmin = scipy.optimize.minimize(fun=mf.nncostfunction3, x0=theta_initial_ravel, args=(input_layer_size, hidden_layer_size1, num_labels, x, y, lambda_reg), method=minimisation_method, jac=True, options={'maxiter': iteration_number, 'disp': use_minimisation_display}) answer = fmin.x theta1 = np.array(np.reshape(answer[0:hidden_layer_size1*(input_layer_size+1)], ((hidden_layer_size1, input_layer_size + 1)))) theta2 = np.array(np.reshape(answer[hidden_layer_size1*(input_layer_size+1):], ((num_labels, hidden_layer_size1 + 1)))) elif use_all_training_data == True and number_of_layers == 4: fmin = scipy.optimize.minimize(fun=mf.nncostfunction4, x0=theta_initial_ravel, args=(input_layer_size, hidden_layer_size1, hidden_layer_size2, num_labels, x, y, lambda_reg), method=minimisation_method, jac=True, options={'maxiter': iteration_number, 'disp': use_minimisation_display}) answer = fmin.x theta1 = np.array(np.reshape(answer[0:hidden_layer_size1*(input_layer_size+1)], ((hidden_layer_size1, input_layer_size + 1)))) theta2 = np.array(np.reshape(answer[hidden_layer_size1*(input_layer_size+1):hidden_layer_size1*(input_layer_size+1)+hidden_layer_size2*(hidden_layer_size1+1)], ((hidden_layer_size2, hidden_layer_size1 + 1)))) theta3 = np.array(np.reshape(answer[hidden_layer_size1*(input_layer_size+1)+hidden_layer_size2*(hidden_layer_size1+1):], ((num_labels, hidden_layer_size2 + 1)))) elif use_all_training_data == True and number_of_layers == 5: fmin = scipy.optimize.minimize(fun=mf.nncostfunction5, x0=theta_initial_ravel, args=(input_layer_size, hidden_layer_size1, hidden_layer_size2, hidden_layer_size3, num_labels, x, y, lambda_reg), method=minimisation_method, jac=True, options={'maxiter': iteration_number, 'disp': use_minimisation_display}) answer = fmin.x theta1 = np.array(np.reshape(answer[0:hidden_layer_size1*(input_layer_size+1)], ((hidden_layer_size1, input_layer_size + 1)))) theta2 = np.array(np.reshape(answer[hidden_layer_size1*(input_layer_size+1):hidden_layer_size1*(input_layer_size+1)+hidden_layer_size2*(hidden_layer_size1+1)], ((hidden_layer_size2, hidden_layer_size1 + 1)))) theta3 = np.array(np.reshape(answer[hidden_layer_size1*(input_layer_size+1)+hidden_layer_size2*(hidden_layer_size1+1):hidden_layer_size1*(input_layer_size+1)+hidden_layer_size2*(hidden_layer_size1+1)+hidden_layer_size3*(hidden_layer_size2+1)], ((hidden_layer_size3, hidden_layer_size2 + 1)))) theta4 = np.array(np.reshape(answer[hidden_layer_size1*(input_layer_size+1)+hidden_layer_size2*(hidden_layer_size1+1)+hidden_layer_size3*(hidden_layer_size2+1):], ((num_labels, hidden_layer_size3 + 1)))) elif use_all_training_data == False and number_of_layers == 3: fmin = scipy.optimize.minimize(fun=mf.nncostfunction3, x0=theta_initial_ravel, args=(input_layer_size, hidden_layer_size1, num_labels, x_train, y_train, lambda_reg), method=minimisation_method, jac=True, options={'maxiter': iteration_number, 'disp': use_minimisation_display}) answer = fmin.x theta1 = np.array(np.reshape(answer[0:hidden_layer_size1*(input_layer_size+1)], ((hidden_layer_size1, input_layer_size + 1)))) theta2 = np.array(np.reshape(answer[hidden_layer_size1*(input_layer_size+1):], ((num_labels, hidden_layer_size1 + 1)))) elif use_all_training_data == False and number_of_layers == 4: fmin = scipy.optimize.minimize(fun=mf.nncostfunction4, x0=theta_initial_ravel, args=(input_layer_size, hidden_layer_size1, hidden_layer_size2, num_labels, x_train, y_train, lambda_reg), method=minimisation_method, jac=True, options={'maxiter': iteration_number, 'disp': use_minimisation_display}) answer = fmin.x theta1 = np.array(np.reshape(answer[0:hidden_layer_size1*(input_layer_size+1)], ((hidden_layer_size1, input_layer_size + 1)))) theta2 = np.array(np.reshape(answer[hidden_layer_size1*(input_layer_size+1):hidden_layer_size1*(input_layer_size+1)+hidden_layer_size2*(hidden_layer_size1+1)], ((hidden_layer_size2, hidden_layer_size1 + 1)))) theta3 = np.array(np.reshape(answer[hidden_layer_size1*(input_layer_size+1)+hidden_layer_size2*(hidden_layer_size1+1):], ((num_labels, hidden_layer_size2 + 1)))) elif use_all_training_data == False and number_of_layers == 5: fmin = scipy.optimize.minimize(fun=mf.nncostfunction5, x0=theta_initial_ravel, args=(input_layer_size, hidden_layer_size1, hidden_layer_size2, hidden_layer_size3, num_labels, x_train, y_train, lambda_reg), method=minimisation_method, jac=True, options={'maxiter': iteration_number, 'disp': use_minimisation_display}) answer = fmin.x theta1 = np.array(np.reshape(answer[0:hidden_layer_size1*(input_layer_size+1)], ((hidden_layer_size1, input_layer_size + 1)))) theta2 = np.array(np.reshape(answer[hidden_layer_size1*(input_layer_size+1):hidden_layer_size1*(input_layer_size+1)+hidden_layer_size2*(hidden_layer_size1+1)], ((hidden_layer_size2, hidden_layer_size1 + 1)))) theta3 = np.array(np.reshape(answer[hidden_layer_size1*(input_layer_size+1)+hidden_layer_size2*(hidden_layer_size1+1):hidden_layer_size1*(input_layer_size+1)+hidden_layer_size2*(hidden_layer_size1+1)+hidden_layer_size3*(hidden_layer_size2+1)], ((hidden_layer_size3, hidden_layer_size2 + 1)))) theta4 = np.array(np.reshape(answer[hidden_layer_size1*(input_layer_size+1)+hidden_layer_size2*(hidden_layer_size1+1)+hidden_layer_size3*(hidden_layer_size2+1):], ((num_labels, hidden_layer_size3 + 1)))) else: print("Error") exit() #Doing predictions ############################################################################################################# print('Doing predictions') if use_all_training_data == True: p, h = mf.predict(theta1, theta2, x); correct = [1 if a == b else 0 for (a, b) in zip(p,y)] accuracy = (sum(map(int, correct)) / float(len(correct))) print 'training set accuracy = {0}%'.format(accuracy * 100) else: if number_of_layers == 3: p, h = mf.predict3(theta1, theta2, x_train); print(p[0:10]) print(y_train[0:10]) correct = [1 if a == b else 0 for (a, b) in zip(p,y_train)] accuracy = (sum(map(int, correct)) / float(len(correct))) print 'training set accuracy = {0}%'.format(accuracy * 100) mylogloss = mf.mylogloss(h, y_train, num_labels); print("mylogloss_train is: " + str(mylogloss)) p_cv, h_cv = mf.predict3(theta1, theta2, x_cv); correct_cv = [1 if a == b else 0 for (a, b) in zip(p_cv,y_cv)] accuracy_cv = (sum(map(int, correct_cv)) / float(len(correct_cv))) print 'CV set accuracy = {0}%'.format(accuracy_cv * 100) mylogloss_cv = mf.mylogloss(h_cv, y_cv, num_labels); print("mylogloss_CV is: " + str(mylogloss_cv)) ''' print(len(fp_cv)) print(len(y_cv)) print(len(p_cv)) #exit() ourcheck = np.vstack((fp_cv.astype('str'),y_cv.astype('str'),h_cv[:,0].astype('str'),h_cv[:,1].astype('str'),h_cv[:,2].astype('str'),h_cv[:,3].astype('str'),h_cv[:,4].astype('str'),h_cv[:,5].astype('str'),h_cv[:,6].astype('str'),h_cv[:,7].astype('str'))) np.set_printoptions(suppress=True) np.savetxt("logcheck.csv", ourcheck.T, delimiter=",", fmt="%s")#fmt='%.17f') exit() ''' elif number_of_layers == 4: p, h = mf.predict4(theta1, theta2, theta3, x_train); print(p[0:10]) print(y_train[0:10]) correct = [1 if a == b else 0 for (a, b) in zip(p,y_train)] accuracy = (sum(map(int, correct)) / float(len(correct))) print 'training set accuracy = {0}%'.format(accuracy * 100) mylogloss = mf.mylogloss(h, y_train, num_labels); print("mylogloss_train is: " + str(mylogloss)) p_cv, h_cv = mf.predict4(theta1, theta2, theta3, x_cv); correct_cv = [1 if a == b else 0 for (a, b) in zip(p_cv,y_cv)] accuracy_cv = (sum(map(int, correct_cv)) / float(len(correct_cv))) print 'CV set accuracy = {0}%'.format(accuracy_cv * 100) mylogloss_cv = mf.mylogloss(h_cv, y_cv, num_labels); print("mylogloss_CV is: " + str(mylogloss_cv)) elif number_of_layers == 5: p, h = mf.predict5(theta1, theta2, theta3, theta4, x_train); print(p[0:10]) print(y_train[0:10]) correct = [1 if a == b else 0 for (a, b) in zip(p,y_train)] accuracy = (sum(map(int, correct)) / float(len(correct))) print 'training set accuracy = {0}%'.format(accuracy * 100) mylogloss = mf.mylogloss(h, y_train, num_labels); print("mylogloss_train is: " + str(mylogloss)) p_cv, h_cv = mf.predict5(theta1, theta2, theta3, theta4, x_cv); correct_cv = [1 if a == b else 0 for (a, b) in zip(p_cv,y_cv)] accuracy_cv = (sum(map(int, correct_cv)) / float(len(correct_cv))) print 'CV set accuracy = {0}%'.format(accuracy_cv * 100) mylogloss_cv = mf.mylogloss(h_cv, y_cv, num_labels); print("mylogloss_cv is: " + str(mylogloss_cv)) #Processing test data ############################################################################################################# if output_test_submission == True: print("Processing test data") if number_of_layers == 3: x_test, m_test, n_test, leafid_test = mf.readintestcsv(); p_test, h_test = mf.predict3(theta1, theta2, x_test); #ourcheck = np.vstack((leafid_test.astype('str'),h_test[:,0].astype('str'),h_test[:,1].astype('str'),h_test[:,2].astype('str'),h_test[:,3].astype('str'),h_test[:,4].astype('str'),h_test[:,5].astype('str'),h_test[:,6].astype('str'),h_test[:,7].astype('str'))) np.set_printoptions(suppress=True) np.savetxt("4000mytest_3layers.csv", h_test, delimiter=",",fmt="%s")# fmt='%.17f') print("Using Hidden_layer_size: " + str(hidden_layer_size1) + ", lambda: " + str(lambda_reg)) elif number_of_layers == 4: x_test, m_test, n_test, leafid_test = mf.readintestcsv(); p_test, h_test = mf.predict4(theta1, theta2, theta3, x_test); #ourcheck = np.vstack((leafid_test.astype('str'),h_test[:,0].astype('str'),h_test[:,1].astype('str'),h_test[:,2].astype('str'),h_test[:,3].astype('str'),h_test[:,4].astype('str'),h_test[:,5].astype('str'),h_test[:,6].astype('str'),h_test[:,7].astype('str'))) np.set_printoptions(suppress=True) np.savetxt("mytest_4layers.csv", h_test, delimiter=",", fmt='%.17f') print("Using Hidden_layer_size: " + str(hidden_layer_size1) + ", " + str(hidden_layer_size2) + ", lambda: " + str(lambda_reg)) elif number_of_layers == 5: x_test, m_test, n_test = mf.readintestcsv(); p_test, h_test = mf.predict5(theta1, theta2, theta3, theta4, x_test); #ourcheck = np.vstack((leafid_test.astype('str'),h_test[:,0].astype('str'),h_test[:,1].astype('str'),h_test[:,2].astype('str'),h_test[:,3].astype('str'),h_test[:,4].astype('str'),h_test[:,5].astype('str'),h_test[:,6].astype('str'),h_test[:,7].astype('str'))) np.set_printoptions(suppress=True) np.savetxt("l3mytest_5layers.csv", h_test, delimiter=",", fmt='%.8f') print("Using Hidden_layer_size: " + str(hidden_layer_size1) + ", " + str(hidden_layer_size2) + ", " + str(hidden_layer_size3) + ", lambda: " + str(lambda_reg)) else: print("Number of layers must be 3, 4 or 5") #-----------------END BODY-----------------
[ "yysy2@cam.ac.uk" ]
yysy2@cam.ac.uk
3ecd780fadd66086a58de5752e5b3af54de3c7b4
49f7929ef547197b91aa0e40a49afcc27c64c069
/PAC-MAN.py
cef0267d248167ffd585d2fae4ea5f3115ea49e3
[]
no_license
lin233/PACMAN
bd4c74f99ec48c8588a693c43033e2faa0950c1e
bd967ecec7721245ce21fc8bfaa4358c1c967891
refs/heads/master
2023-01-05T23:33:26.524554
2017-10-08T12:59:24
2017-10-08T12:59:24
106,176,179
0
0
null
null
null
null
UTF-8
Python
false
false
66,148
py
# -*- coding:utf-8 -*- #'eater.gif'是吃豆人的图像 #'demon.gif'是怪物的图像 # map1,map2,map3,map4,map5的txt文件中储存了要用的地图的墙的分割为小矩形的坐标 from Tkinter import * from string import * from random import random from time import * def rebackLevel1(): #第一关失败后重来的窗口按钮调用的函数,关闭该窗口并重新开始这一关 askFail.destroy() #关闭 paintCanvas1() #重开 def rebackLevel2(): #第二关失败后重来的窗口按钮调用的函数 askFail2.destroy() paintCanvas2() def rebackLevel3(): #第三关失败后重来的窗口按钮调用的函数 askFail3.destroy() paintCanvas3() def rebackLevel4(): #第四关失败后重来的窗口按钮调用的函数 askFail4.destroy() paintCanvas4() def rebackLevel5(): #第五关失败后重来的窗口按钮调用的函数 askFail5.destroy() paintCanvas5() def continueLevel2(): #第一关成功后继续的窗口按钮调用的函数,关闭该窗口并进行下一关 ask.destroy() #关闭 paintCanvas2() #重开 def continueLevel3(): #第二关成功后继续的窗口按钮调用的函数 ask2.destroy() paintCanvas3() def continueLevel4(): #第三关成功后继续的窗口按钮调用的函数 ask3.destroy() paintCanvas4() def continueLevel5(): #第四关成功后继续的窗口按钮调用的函数 ask4.destroy() paintCanvas5() def destroyI(): #无敌版胜利窗口的关闭 askI.destroy() def rebackI(): #无敌版失败窗口的关闭和重开 askFailI.destroy() #关闭 Invincible() #重开 def Right(i,L,cv): #检验右边是否通路 , 通路返回True ,不通返回 False。 #(i 是怪物的标签,L是关卡数,cv是画布,同下。) #在第L关中检验怪物的右方是否为墙,为墙不通,没有墙则通 (Right,Left,Up,Down函数内部原理相同,就不多加赘述) walls=[9,16,16,13,26,9] #每关中墙的最大图形项加一 xyb=list(cv.coords(i)) #返回怪物i的坐标 xyb_=list(cv.find_overlapping(xyb[0]-14+1,xyb[1]-14,xyb[0]+14+1,xyb[1]+14)) # 返回怪物右方一个像素的矩形范围内的图形项 if xyb_[0]<walls[L-1]: #因为墙的图形项是最小的那几个,所以只要第一项不是墙,就没有墙了 return False #撞墙了 返回False return True #没撞墙 返回True def Left(i,L,cv): #检验左边是否通路 , 通路返回True ,不通返回 False #(i 是怪物的标签,L是关卡数,cv是画布,同下。) walls=[9,16,16,13,26,9] xyb=list(cv.coords(i)) xyb_=list(cv.find_overlapping(xyb[0]-14-1,xyb[1]-14,xyb[0]+14-1,xyb[1]+14)) if xyb_[0]<walls[L-1]: return False return True def Up(i,L,cv): #检验上边是否通路,通路返回True ,不通返回 False #(i 是怪物的标签,L是关卡数,cv是画布,同下。) walls=[9,16,16,13,26,9] xyb=list(cv.coords(i)) xyb_=list(cv.find_overlapping(xyb[0]-14,xyb[1]-14-1,xyb[0]+14,xyb[1]+14-1)) if xyb_[0]<walls[L-1]: return False return True def Down(i,L,cv): #检验下边是否通路,通路返回True,不通返回False #(i 是怪物的标签,L是关卡数,cv是画布,同下。) walls=[9,16,16,13,26,9] xyb=list(cv.coords(i)) xyb_=list(cv.find_overlapping(xyb[0]-14,xyb[1]-14+1,xyb[0]+14,xyb[1]+14+1)) if xyb_[0]<walls[L-1]: return False return True def zhq(i,x,y,L,cv): #在第L关中检验怪物是否撞墙并移动 # i是怪物的标签 , x,y是要前进的方向。x为正是向右,y为正向下。 walls=[9,16,16,13,26,9] #墙壁的最大图形项+1 xyb = list(cv.coords(i)) #返回怪物i的中心坐标 xyb_ = list(cv.find_overlapping(xyb[0] - 14 + x, xyb[1] - 14 + y, xyb[0] + 14 + x, xyb[1] + 14 + y)) #返回怪物前方一个像素的图形项并储存在列表中,以判断是否会撞墙 if xyb_[0] < walls[L-1]: #如果前方是墙 cv.move(i, 0, 0) #不移动 else: #前方没有墙 cv.move(i, x, y) #移动 def zhqEater(x,y,i,L,cv): #在第L关中检验吃豆人是否撞墙并移动,x,y是吃豆人要前进的方向,x是水平方向,向右为正,y是竖直方向,向下为正。i是吃豆人的标签,L是关卡数,cv是画布。 walls=[9,16,16,13,26,9] #墙壁的最大图形项+1 xyc__=list(cv.coords(i)) #返回吃豆人的中心坐标 xyc___=list(cv.find_overlapping(xyc__[0]-8+x,xyc__[1]-8+y,xyc__[0]+8+x,xyc__[1]+8+y)) #返回吃豆人的矩形范围前进的方向上的图形项,以判断是否会撞墙 if xyc___[0]<walls[L-1]: #撞墙了 cv.move(i, 0, 0) #不移动 else: #没有撞墙 cv.move(i, x, y) #移动 #吃豆人和怪物的移动函数相似,但是没有合并,因为参考范围的问题,怪物需要用的矩形范围是28*28,这样可以使怪物不会卡在道路中,否则Up Down函数的判定会出问题 #而吃豆人的参考范围只用了16*16,可以使吃豆人在转弯的时候的容错性更好,更容易转弯。 def budongle(i,x,y,L,cv): #当怪物走进死路的时候需要掉头 ,i是怪物的标签,x,y是怪物前进的方向,x水平,向右为正,y竖直,向下为正 back=0 # back是怪物四个方向是否为通路,每一个方向不通,则加一 #接下来判断每个方向是否通路,不通则 back 加 1 if Down(i,L,cv)==False: back +=1 if Up(i,L,cv)==False: back +=1 if Right(i,L,cv)==False: back += 1 if Left(i,L,cv)==False: back += 1 if back == 3: #如果back=3,就说明有三个方向都不通,说明走进了死路,需要掉头 return True #需要掉头返回True def zhuan(i,a,b,L,cv): #使怪物转向:1.走进死路掉头,2:走到路口,随机转向(继续前进或掉头或转向) # i是怪物的标签,a,b是现在的前进方向的参数,a为水平方向,向右为正,b是竖直方向,向下为正。 # 通过改变a,b的值并返回来改变前进方向 if budongle(i,a,b,L,cv): # 判读是否走进死路,如果是budongle会返回True 然后将前进方向掉头 return -a,-b # 将a,b变为相反数,即掉头 else: if b == 0 : #目前处于水平运动状态 x=random() #生成一个随机数 if Up(i,L,cv) and Down(i,L,cv): #上下都通,则走到十字路口,接下来向四个方向的前进各占四分之一 if x > 0.75: #1/4 a,b = 0,-1 #向上走 elif x > 0.5: #1/4 a,b = 0,1 #向下走 elif x > 0.25: #1/4 a,b = -a,-b #掉头 #剩下的1/4,继续向前 elif Up(i,L,cv): #水平运动时,走到向上通路的路口 if x > 0.66: #1/3 a,b = 0,-1 #向上走 elif x > 0.33: #1/3 a,b = -a,-b #掉头 #剩下的1/3,继续向前 elif Down(i,L,cv): #水平运动时,走到向下通路的路口 if x > 0.66: a,b = 0,1 #向下走 elif x > 0.33: a,b = -a,-b #向反方向走 else: #目前处于上下运动状态 y=random() #生成一个随机数 if Right(i,L,cv) and Left(i,L,cv): #上下运动时走到了十字路口,四个方向各四分之一的机率 if y > 0.75: #1/4 a,b = -1,0 #向左走 elif y > 0.5: #1/4 a,b = 1,0 #向右走 elif y > 0.25: #1/4 a,b = -a,-b #向反方向走 #剩下的1/4,不变 elif Right(i,L,cv): #上下运动时,走到了能够右转的路口 if y > 0.66: a,b = 1,0 #向右走 elif y > 0.33: a,b = -a,-b #向反方向走 elif Left(i,L,cv): #上下运动时,走到了能够左转的路口 if y > 0.66: a,b = -1,0 #向左走 elif y > 0.33: a,b = -a,-b #向反方向走 return a,b def movetriangle(event): #移动吃豆人 绑定键盘事件 global c #c,d是吃豆人的移动时候的参数,c是水平方向的,向右为正 global d #d是竖直方向的,向下为正 if event.keysym == 'Up': #如果按 ↑ 键,改变吃豆人的前进方向为向上 , c,d=0,-1 elif event.keysym == 'Down': #如果按 ↓ 键, 改变吃豆人的前进方向为向下 c,d=0,1 elif event.keysym == 'Left': #如果按 ← 键, 改变吃豆人的前进方向为向左 c,d = -1,0 elif event.keysym == 'Right': #如果按 → 键, 改变吃豆人的前进方向为向右 c,d = 1,0 def deleteBeans(maps,cv,L): #在第L关中的地图上除去与墙重叠的豆子。 #maps是储存了地图中的墙壁的矩形范围的坐标的txt文件 #txt文件中以每一个点的坐标为一行,两个点确定一个矩形 itemsBesidesBeans=[13,20,20,17,30,13] #每关中墙块、吃豆人和怪物的总数 f = open(maps, "r") #读入地图中的矩形的大致坐标 r = f.readlines() #全部读取 list1 = [] #创建用来存储坐标的list1 for i in r: a = i.split() #将r拆分为坐标数值的列表,以逗号的换行符为分隔 for t in a: #遍历列表 t = int(t) #将列表中的元素类别转化为数值 s = (t + 5) / 10 * 10 #四舍五入精确坐标 list1.append(s) #添加到list1中 # 坐标分类 # 因为此时list1中的坐标数值是以' x1,x2,y1,y2 ,x1,x2,y1,y2 …… '的形式存在的, listx1 = [] # 所以在这里将其分类到专门存储x1,x2,y1,y2的四个列表中 listy1 = [] listx2 = [] listy2 = [] for i in range(0, len(list1), 4): #每四个为一组 因为两个点确定一个矩形,所以四个一组确定一个矩形 listx1.append(list1[i]) #将所有的x1,y1,x2,y2坐标分别放在listx1,listy1,listx2,listy2中 listy1.append(list1[i + 1]) listx2.append(list1[i + 2]) listy2.append(list1[i + 3]) for i in range(len(listx1)): #遍历坐标列表,四个一组为一个地图的矩形坐标 x1 = listx1[i] y1 = listy1[i] x2 = listx2[i] y2 = listy2[i] list3 = list(cv.find_overlapping(x1, y1, x2, y2)) # 找出与地图重叠的豆豆,储存在list3中 for t in list3: #遍历list3, if t > itemsBesidesBeans[L-1]:#如果t的图形项大于吃豆人怪物墙壁,那么t就是豆豆的图形项 cv.delete(t) # 删掉豆豆 def eat(cv,i,L,beans,windows): global life,score positionOfEater=[97,97,97,68,97,97] #吃豆人在每关中的初始位置和复活位置 xPositionOfDemons=[355,415,355,275,215,355] #怪物在每关中的复活位置 itemsOfWallsAndEater=[9,16,16,13,26,9] #每关中墙块和吃豆人的总数 itemsBesidesBeans=[13,20,20,17,30,13] #每关中墙块、吃豆人和怪物的总数 xya1 = list(cv.coords(i)) # 报告吃豆人的中心坐标,存储形式:xya1=[x1,y1,x2,y2] xya = list(cv.find_overlapping(xya1[0] - 10, xya1[1] - 10, xya1[0] + 10, xya1[ 1] + 10)) # 用find_overlapping找出与吃豆人矩形范围内重叠的其他图形(豆豆)的标识号,存到列表中 for n in xya: # 对于xya中的图形项 if n > itemsBesidesBeans[L-1]: #如果是豆豆 cv.delete(n) #吃掉豆豆 score+=10 #分数+10 if n == beans[-1] or n == beans[-2]: #吃掉大豆豆 score += 50 #分数+50 life += 1 #生命值+1 Label(windows, text="Your scores: %d"%(score), fg='black', font="Times -15 bold", bg='LightSkyBlue').place(x=300, y=0, anchor=N) #写有分数的标签 每次在吃掉一个豆豆后更新 Label(windows, text="Your lives: %d" % (life), fg='black', font="Times -15 bold", bg='LightSkyBlue').place(x=300, y=600, anchor=S) #更新写有生命值的标签 elif n > itemsOfWallsAndEater[L-1]: #碰到了怪物 sleep(0.5) #给玩家一个反应的时间 cv.move(i,positionOfEater[L-1]-xya1[0],positionOfEater[L-1]-xya1[1]) #吃豆人回到初始位置 xyn = list(cv.coords(n)) cv.move(n,xPositionOfDemons[L-1]-xyn[0],300-xyn[1]) #怪物回到复活位置 life=life-1 #生命值-1 Label(windows, text="Your lives: %d" % (life), fg='black', font="Times -15 bold", bg='LightSkyBlue').place(x=300, y=600, anchor=S) #更新写有生命值的标签 def paintCanvas1(): #LEVEL1 第一关 global askFail global score,life life = 3 #吃豆人的初始生命值 score = 0 #初试分数 win1 = Toplevel() win1.resizable(0,0) #固定窗口界面,使不能最大化窗口 bg1 = Canvas(win1, width=600, height=600, bg="white") # 画布创建 bg1.pack() #画布展开 global a1 p1 = (20, 20, 580, 20, 580, 580, 20, 580, 20, 20) # 地图墙壁多边形的坐标 pw1 = (20, 20, 580, 20, 580, 580, 20, 580, 20, 80, 80, 80, 80, 490, 490, 490, 490, 80, 20, 80) pw2 = (110, 110, 200, 110, 200, 230, 110, 230) pw3 = (230, 110, 340, 110, 340, 230, 230, 230) pw4 = (370, 110, 460, 110, 460, 230, 370, 230) pw5 = (110, 260, 340, 260, 340, 340, 110, 340) pw6 = (370, 260, 460, 260, 460, 340, 370, 340) pw7 = (110, 370, 340, 370, 340, 460, 110, 460) pw8 = (370, 370, 460, 370, 460, 460, 370, 460) w1_1 = bg1.create_polygon(pw1, outline="", fill="LightSkyBlue") # 地图多边形的创建 w1_2 = bg1.create_polygon(pw2, outline="", fill="LightSkyBlue") w1_3 = bg1.create_polygon(pw3, outline="", fill="LightSkyBlue") w1_4 = bg1.create_polygon(pw4, outline="", fill="LightSkyBlue") w1_5 = bg1.create_polygon(pw5, outline="", fill="LightSkyBlue") w1_6 = bg1.create_polygon(pw6, outline="", fill="LightSkyBlue") w1_7 = bg1.create_polygon(pw7, outline="", fill="LightSkyBlue") w1_8 = bg1.create_polygon(pw8, outline="", fill="LightSkyBlue") pic = PhotoImage(file="eater.gif") # 吃豆人,eater.gif是吃豆人的图片 a1 = bg1.create_image(97, 97, image=pic, anchor=CENTER) # 初始放置吃豆人 dem = PhotoImage(file="demon.gif") # 怪物,demon.gif是怪物的图片 a10 = bg1.create_image(355,324, image=dem,anchor=CENTER) #初始放置怪物 a11 = bg1.create_image(475,474, image=dem,anchor=CENTER) a12 = bg1.create_image(475,95, image=dem,anchor=CENTER) a13 = bg1.create_image(95,474, image=dem,anchor=CENTER) Label(win1, text="LEVEL 1", fg='black', font="Times -30 bold", bg='LightSkyBlue').place(x=500, y=50, anchor=CENTER) #放置表示关卡数的标签 for i in range(14): # 将地图铺满豆豆 for j in range(14): bij = (90 + i * 29, 90 + j * 29, 100 + i * 29, 100 + j * 29) #豆豆的坐标(每隔29个像素,铺一个豆豆,铺满地图) bi_j = bg1.create_oval(bij, outline="pink", fill="pink")#豆豆的形状:圆形 以及 颜色:粉色 bigbean1=bg1.create_oval(346,232,366,252,outline='GreenYellow',fill='GreenYellow') # 放置两个大豆子 bigbean2=bg1.create_oval(230,467,250,487,outline='GreenYellow',fill='GreenYellow') bean=list(bg1.find_overlapping(0, 0, 600, 600)) #地图上所有的图形项,存储在列表bean bean1=bean[0:len(bean)] #深拷贝bean deleteBeans("map1.txt",bg1,1) #删除与墙重叠的豆豆 global c global d global a global b c,d = 1,0 #c,d 是吃豆人的初始移动方向 x0,y0 = -1,0 #x,y 是怪物的初始移动方向 x1,y1 = -1,0 x2,y2 = -1,0 x3,y3 = -1,0 while True: bg1.bind_all('<KeyPress-Up>', movetriangle) #绑定键盘事件与更改吃豆人移动参数的函数 bg1.bind_all('<KeyPress-Down>', movetriangle) bg1.bind_all('<KeyPress-Left>', movetriangle) bg1.bind_all('<KeyPress-Right>', movetriangle) zhqEater(c,d,a1,1,bg1) #在第L关中检验吃豆人是否撞墙并移动 eat(bg1,a1,1,bean1,win1) #游戏进行,吃豆子&碰怪物 zhq(a10,x0,y0,1,bg1) #四个怪物的移动 x0,y0=zhuan(a10,x0,y0,1,bg1) zhq(a11,x1,y1,1,bg1) x1,y1=zhuan(a11,x1,y1,1,bg1) zhq(a12,x2,y2,1,bg1) x2,y2=zhuan(a12,x2,y2,1,bg1) zhq(a13,x3,y3,1,bg1) x3,y3=zhuan(a13,x3,y3,1,bg1) bg1.update() sleep(0.001) if life == 0 : #life为0,Game Over askFail = Toplevel(height=200, width=400) askFail.resizable(0,0) askCanvas = Canvas(askFail, width=198, height=171, bg="white") askCanvas.grid(row=9) fail = PhotoImage(file="hahaha.gif") failing = askCanvas.create_image(99, 85, image=fail, anchor=CENTER) Label(askFail, text=" 失败!", font="Times -24 bold", bg="white", fg="black").grid(row=1, rowspan=2, sticky=W + E) Label(askFail, text="重头开始?", font="Times -20 bold", bg="white", fg="black").grid(row=10, rowspan=2, sticky=W + E) backButton = Button(askFail, text="ok", font="Times -20 bold", bg="black", fg="white", command=rebackLevel1).grid(row=12) win1.destroy() global ask itemsBesidesBeans=[13,20,20,17,30] #墙块、吃豆人和怪物的总数(即不包括豆豆的最大图形项) final=list(bg1.find_overlapping(0,0,600,600)) #返回现在地图上所存在的所有图形项 if final[-1] == itemsBesidesBeans[0] : #如果最后一项是怪物的图形项,说明豆豆已经被吃完了 #因为豆豆的图形项是比怪物墙壁吃豆人的大的,所以如果还有豆豆肯定在最后 #所以如果最后一项不是豆豆,就说明豆豆吃完了 ask = Toplevel(height=200, width=400) ask.resizable(0,0) askCanvas2 = Canvas(ask, width=178, height=179, bg="white") askCanvas2.grid(row=9) winwin = PhotoImage(file="winwinwin.gif") winPicture = askCanvas2.create_image(89, 89, image=winwin, anchor=CENTER) Label(ask, text=" 通关!", font="Times -24 bold", bg="white", fg="black").grid(row=1, rowspan=2, sticky=W + E) Label(ask, text="继续下一关?", font="Times -20 bold", bg="white", fg="black").grid(row=10, rowspan=2, sticky=W + E) continueButton = Button(ask, text="ok", font="Times -20 bold", bg="black", fg="white", command=continueLevel2).grid(row=12) win1.destroy() def paintCanvas2():#LEVEL2 #注释同第一关 global askFail2 global score,life life = 3 score = 0 win2 = Toplevel() win2.resizable(0,0) #固定窗口界面,使不能最大化窗口 bg2 = Canvas(win2, width=600, height=600, bg="white") # 画布 bg2.pack() global a2 p2 = (20, 0, 20, 20, 580, 20, 580, 0) pw1 = (20, 20, 50, 20, 50, 550, 550, 550, 550, 20, 580, 20, 580, 580, 20, 580) #地图墙壁的多边形的坐标 pw2 = (80, 50, 430, 50, 430, 80, 80, 80) pw3 = (460, 50, 520, 50, 520, 310, 490, 310, 490, 80, 460, 80) pw4 = (490, 340, 520, 340, 520, 520, 430, 520, 430, 490, 490, 490) pw5 = (80, 490, 400, 490, 400, 520, 80, 520) pw6 = (80, 230, 110, 230, 110, 460, 80, 460) pw7 = (80, 110, 310, 110, 310, 140, 110, 140, 110, 200, 80, 200) pw8 = (340, 110, 460, 110, 460, 230, 430, 230, 430, 140, 340, 140) pw9 = (430, 260, 460, 260, 460, 460, 340, 460, 340, 430, 430, 430) pw10 = (140, 290, 170, 290, 170, 430, 310, 430, 310, 460, 140, 460) pw11 = (140, 170, 400, 170, 400, 400, 370, 400, 370, 200, 170, 200, 170, 260, 140, 260) pw12 = (200, 230, 340, 230, 340, 260, 200, 260) pw13 = (260, 290, 340, 290, 340, 340, 260, 340) pw14 = (200, 290, 230, 290, 230, 370, 340, 370, 340, 400, 200, 400) ol2 = bg2.create_polygon(p2, outline='', fill="LightSkyBlue") #地图墙壁的多边形的创建 w2_1 = bg2.create_polygon(pw1, outline="", fill="LightSkyBlue") w2_2 = bg2.create_polygon(pw2, outline="", fill="LightSkyBlue") w2_3 = bg2.create_polygon(pw3, outline="", fill="LightSkyBlue") w2_4 = bg2.create_polygon(pw4, outline="", fill="LightSkyBlue") w2_5 = bg2.create_polygon(pw5, outline="", fill="LightSkyBlue") w2_6 = bg2.create_polygon(pw6, outline="", fill="LightSkyBlue") w2_7 = bg2.create_polygon(pw7, outline="", fill="LightSkyBlue") w2_8 = bg2.create_polygon(pw8, outline="", fill="LightSkyBlue") w2_9 = bg2.create_polygon(pw9, outline="", fill="LightSkyBlue") w2_10 = bg2.create_polygon(pw10, outline="", fill="LightSkyBlue") w2_11 = bg2.create_polygon(pw11, outline="", fill="LightSkyBlue") w2_12 = bg2.create_polygon(pw12, outline="", fill="LightSkyBlue") w2_13 = bg2.create_polygon(pw13, outline="", fill="LightSkyBlue") w2_14 = bg2.create_polygon(pw14, outline="", fill="LightSkyBlue") pic = PhotoImage(file="eater.gif") # 吃豆人 a2 = bg2.create_image(97, 97, image=pic, anchor=CENTER) dem = PhotoImage(file="demon.gif") # 怪物 a20 = bg2.create_image(415,300, image=dem,anchor=CENTER) a21 = bg2.create_image(95,535 ,image=dem,anchor=CENTER) a22 = bg2.create_image(535,534, image=dem,anchor=CENTER) a23 = bg2.create_image(535,95, image=dem,anchor=CENTER) Label(win2, text="LEVEL 2", fg='black', font="Times -20 bold", bg='LightSkyBlue').place(x=130, y=65, anchor=CENTER) for i in range(18): #将地图铺满豆豆 for j in range(18): bij = (32 + i * 29, 32 + j * 29, 42 + i * 29, 42 + j * 29) bi_j = bg2.create_oval(bij, outline="pink", fill="pink") bigbean1=bg2.create_oval(346,232,366,252,outline='GreenYellow',fill='GreenYellow') # 放置两个大豆子 bigbean2=bg2.create_oval(230,467,250,487,outline='GreenYellow',fill='GreenYellow') bean=list(bg2.find_overlapping(0, 0, 600, 600)) bean2=bean[0:len(bean)] deleteBeans("map2.txt",bg2,2) global c global d x0_,y0_=-1,0 c,d=1,0 x1_,y1_ = -1,0 x2_,y2_ = -1,0 x3_,y3_ = -1,0 while True: bg2.bind_all('<KeyPress-Up>',movetriangle) bg2.bind_all('<KeyPress-Down>',movetriangle) bg2.bind_all('<KeyPress-Left>',movetriangle) bg2.bind_all('<KeyPress-Right>',movetriangle) zhqEater(c,d,a2,2,bg2) eat(bg2,a2,2,bean2,win2) zhq(a20,x0_,y0_,2,bg2) x0_,y0_=zhuan(a20,x0_,y0_,2,bg2) zhq(a21,x1_,y1_,2,bg2) x1_,y1_=zhuan(a21,x1_,y1_,2,bg2) zhq(a22,x2_,y2_,2,bg2) x2_,y2_=zhuan(a22,x2_,y2_,2,bg2) zhq(a23,x3_,y3_,2,bg2) x3_,y3_=zhuan(a23,x3_,y3_,2,bg2) bg2.update() sleep(0.001) if life == 0 : #Game Over askFail2 = Toplevel(height=200, width=400) askFail2.resizable(0,0) askCanvas = Canvas(askFail2, width=198, height=171, bg="white") askCanvas.grid(row=9) fail = PhotoImage(file="hahaha.gif") failing = askCanvas.create_image(99, 85, image=fail, anchor=CENTER) Label(askFail2, text=" 失败!", font="Times -24 bold", bg="white", fg="black").grid(row=1, rowspan=2, sticky=W + E) Label(askFail2, text="重头开始?", font="Times -20 bold", bg="white", fg="black").grid(row=10, rowspan=2, sticky=W + E) backButton = Button(askFail2, text="ok", font="Times -20 bold", bg="black", fg="white", command=rebackLevel2).grid(row=12) win2.destroy() global ask2 itemsBesidesBeans=[13,20,20,17,30] final=list(bg2.find_overlapping(0,0,600,600)) if final[-1] == itemsBesidesBeans[1] : ask2 = Toplevel(height=200, width=400) ask2.resizable(0,0) askCanvas2 = Canvas(ask2, width=178, height=179, bg="white") askCanvas2.grid(row=9) winwin = PhotoImage(file="winwinwin.gif") winPicture = askCanvas2.create_image(89, 89, image=winwin, anchor=CENTER) Label(ask2, text=" 通关!", font="Times -24 bold", bg="white", fg="black").grid(row=1, rowspan=2, sticky=W + E) Label(ask2, text="继续下一关?", font="Times -20 bold", bg="white", fg="black").grid(row=10, rowspan=2, sticky=W + E) continueButton = Button(ask2, text="ok", font="Times -20 bold", bg="black", fg="white", command=continueLevel3).grid(row=12) win2.destroy() def paintCanvas3():#LEVEL3 #注释同第一关 global askFail3 global win3 global bg3 global score,life life = 3 score = 0 win3 = Toplevel() win3.resizable(0,0) #固定窗口界面,使不能最大化窗口 bg3 = Canvas(win3, width=600, height=600, bg="white") # 画布 bg3.pack() global a3 p31 = (0, 0, 0, 600, 600, 600, 600, 0, 580, 0, 580, 580, 20, 580, 20, 0) p32 = (20, 0, 20, 20, 580, 20, 580, 0) pw1 = (50, 50, 370, 50, 370, 80, 310, 80, 310, 140, 230, 140, 230, 80, 50, 80) pw2 = (400, 50, 550, 50, 550, 80, 430, 80, 430, 140, 340, 140, 340, 110, 400, 110) pw3 = (20, 110, 200, 110, 200, 140, 20, 140) pw4 = (460, 110, 550, 110, 550, 200, 290, 200, 290, 170, 460, 170) pw5 = (50, 170, 260, 170, 260, 260, 50, 260) pw6 = (290, 230, 490, 230, 490, 310, 400, 310, 400, 370, 370, 370, 370, 260, 290, 260) pw7 = (520, 230, 580, 230, 580, 490, 520, 490, 520, 430, 490, 430, 490, 400, 520, 400) pw8 = (20, 290, 340, 290, 340, 370, 260, 370, 260, 430, 170, 430, 170, 400, 230, 400, 230, 310, 20, 310) pw9 = (50, 340, 200, 340, 200, 370, 140, 370, 140, 430, 50, 430) pw10 = (430, 340, 490, 340, 490, 370, 460, 370, 460, 460, 490, 460, 490, 520, 550, 520, 550, 550, 400, 550, 400, 490, 370, 490, 370, 400, 430, 400) pw11 = (290, 400, 340, 400, 340, 490, 310, 490, 310, 550, 230, 550, 230, 460, 290, 460) pw12 = (50, 460, 200, 460, 200, 550, 50, 550) pw13 = (340, 520, 370, 520, 370, 580, 340, 580) w3_14 = bg3.create_polygon(p31, fill="LightSkyBlue") w3_15 = bg3.create_polygon(p32, fill="LightSkyBlue") w3_1 = bg3.create_polygon(pw1, outline="", fill="LightSkyBlue") w3_2 = bg3.create_polygon(pw2, outline="", fill="LightSkyBlue") w3_3 = bg3.create_polygon(pw3, outline="", fill="LightSkyBlue") w3_4 = bg3.create_polygon(pw4, outline="", fill="LightSkyBlue") w3_5 = bg3.create_polygon(pw5, outline="", fill="LightSkyBlue") w3_6 = bg3.create_polygon(pw6, outline="", fill="LightSkyBlue") w3_7 = bg3.create_polygon(pw7, outline="", fill="LightSkyBlue") w3_8 = bg3.create_polygon(pw8, outline="", fill="LightSkyBlue") w3_9 = bg3.create_polygon(pw9, outline="", fill="LightSkyBlue") w3_10 = bg3.create_polygon(pw10, outline="", fill="LightSkyBlue") w3_11 = bg3.create_polygon(pw11, outline="", fill="LightSkyBlue") w3_12 = bg3.create_polygon(pw12, outline="", fill="LightSkyBlue") w3_13 = bg3.create_polygon(pw13, outline="", fill="LightSkyBlue") pic = PhotoImage(file="eater.gif") # 吃豆人 a3 = bg3.create_image(97, 97, image=pic, anchor=CENTER) dem = PhotoImage(file="demon.gif") # 怪物 a30 = bg3.create_image(355,300, image=dem,anchor=CENTER) a31 = bg3.create_image(95,565, image=dem,anchor=CENTER) a32 = bg3.create_image(565,565, image=dem,anchor=CENTER) a33 = bg3.create_image(565,95, image=dem,anchor=CENTER) Label(win3, text="LEVEL 3", fg='black', font="Times -30 bold", bg='LightSkyBlue').place(x=152, y=212, anchor=CENTER) for i in range(19): for j in range(19): bij = (32 + i * 29, 32 + j * 29, 42 + i * 29, 42 + j * 29) bi_j = bg3.create_oval(bij, outline="pink", fill="pink") bigbean1=bg3.create_oval(205,435,225,455,outline='GreenYellow',fill='GreenYellow') # 放置两个大豆子 bigbean2=bg3.create_oval(490,205,510,225,outline='GreenYellow',fill='GreenYellow') bean=list(bg3.find_overlapping(0, 0, 600, 600)) bean3=bean[0:len(bean)] deleteBeans("map3.txt",bg3,3) global c global d x0__,y0__=-1,0 c,d=1,0 x1__,y1__= -1,0 x2__,y2__= -1,0 x3__,y3__ = -1,0 while True: bg3.bind_all('<KeyPress-Up>', movetriangle) bg3.bind_all('<KeyPress-Down>', movetriangle) bg3.bind_all('<KeyPress-Left>', movetriangle) bg3.bind_all('<KeyPress-Right>', movetriangle) zhqEater(c,d,a3,3,bg3) eat(bg3,a3,3,bean3,win3) zhq(a30,x0__,y0__,3,bg3) x0__,y0__=zhuan(a30,x0__,y0__,3,bg3) zhq(a31,x1__,y1__,3,bg3) x1__,y1__=zhuan(a31,x1__,y1__,3,bg3) zhq(a32,x2__,y2__,3,bg3) x2__,y2__=zhuan(a32,x2__,y2__,3,bg3) zhq(a33,x3__,y3__,3,bg3) x3__,y3__=zhuan(a33,x3__,y3__,3,bg3) bg3.update() sleep(0.001) if life == 0 : #Game Over askFail3 = Toplevel(height=200, width=400) askFail3.resizable(0,0) askCanvas = Canvas(askFail3, width=198, height=171, bg="white") askCanvas.grid(row=9) fail = PhotoImage(file="hahaha.gif") failing = askCanvas.create_image(99, 85, image=fail, anchor=CENTER) Label(askFail3, text=" 失败!", font="Times -24 bold", bg="white", fg="black").grid(row=1, rowspan=2, sticky=W + E) Label(askFail3, text="重头开始?", font="Times -20 bold", bg="white", fg="black").grid(row=10, rowspan=2, sticky=W + E) backButton = Button(askFail3, text="ok", font="Times -20 bold", bg="black", fg="white", command=rebackLevel3).grid(row=12) win3.destroy() global ask3 itemsBesidesBeans=[13,20,20,17,30] final=list(bg3.find_overlapping(0,0,600,600)) if final[-1] == itemsBesidesBeans[2] : ask3 = Toplevel(height=200, width=400) ask3.resizable(0,0) askCanvas2 = Canvas(ask3, width=178, height=179, bg="white") askCanvas2.grid(row=9) winwin = PhotoImage(file="winwinwin.gif") winPicture = askCanvas2.create_image(89, 89, image=winwin, anchor=CENTER) Label(ask3, text=" 通关!", font="Times -24 bold", bg="white", fg="black").grid(row=1, rowspan=2, sticky=W + E) Label(ask3, text="继续下一关?", font="Times -20 bold", bg="white", fg="black").grid(row=10, rowspan=2, sticky=W + E) continueButton = Button(ask3, text="ok", font="Times -20 bold", bg="black", fg="white", command=continueLevel4).grid(row=12) win3.destroy() def paintCanvas4(): #LEVEL4 #注释同第一关 global askFail4 global win4 global bg4 global score,life life = 3 score = 0 win4 = Toplevel() win4.resizable(0,0) #固定窗口界面,使不能最大化窗口 bg4 = Canvas(win4, width=600, height=600, bg="white") # 画布 bg4.pack() global a4 p41 = (0, 0, 0, 600, 600, 600, 600, 0, 580, 0, 580, 580, 20, 580, 20, 0) p42 = (20, 0, 20, 20, 580, 20, 580, 0) pw1 = (20, 20, 580, 20, 580, 310, 550, 310, 550, 430, 520, 430, 520, 230, 430, 230, 430, 310, 370, 310, 370, 200, 340, 200, 340, 170, 310, 170, 310, 230, 340, 230, 340, 310, 290, 310, 290, 140, 400, 140, 400, 200, 520, 200, 520, 50, 50, 50, 50, 460, 110, 460, 110, 550, 370, 550, 370, 580, 20, 580) pw2 = (80, 80, 170, 80, 170, 110, 110, 110, 110, 140, 200, 140, 200, 80, 260, 80, 260, 310, 200, 310, 200, 170, 80, 170) pw3 = (290, 80, 490, 80, 490, 170, 430, 170, 430, 110, 290, 110) pw4 = (80, 200, 170, 200, 170, 310, 80, 310) pw5 = (460, 260, 490, 260, 490, 430, 290, 430, 290, 340, 460, 340) pw6 = (80, 340, 170, 340, 170, 460, 370, 460, 370, 520, 140, 520, 140, 430, 80, 430) pw7 = (200, 340, 260, 340, 260, 430, 200, 430) pw8 = (400, 460, 460, 460, 460, 490, 430, 490, 430, 520, 460, 520, 460, 550, 400, 550) pw9 = (490, 460, 550, 460, 550, 520, 490, 520) pw10 = (490, 550, 580, 550, 580, 580, 490, 580) o41 = bg4.create_polygon(p41, fill="LightSkyBlue") o42 = bg4.create_polygon(p42, fill="LightSkyBlue") w4_1 = bg4.create_polygon(pw1, outline="", fill="LightSkyBlue") w4_2 = bg4.create_polygon(pw2, outline="", fill="LightSkyBlue") w4_3 = bg4.create_polygon(pw3, outline="", fill="LightSkyBlue") w4_4 = bg4.create_polygon(pw4, outline="", fill="LightSkyBlue") w4_5 = bg4.create_polygon(pw5, outline="", fill="LightSkyBlue") w4_6 = bg4.create_polygon(pw6, outline="", fill="LightSkyBlue") w4_7 = bg4.create_polygon(pw7, outline="", fill="LightSkyBlue") w4_8 = bg4.create_polygon(pw8, outline="", fill="LightSkyBlue") w4_9 = bg4.create_polygon(pw9, outline="", fill="LightSkyBlue") w4_10 = bg4.create_polygon(pw10, outline="", fill="LightSkyBlue") pic = PhotoImage(file="eater.gif") # 吃豆人 a4 = bg4.create_image(68, 68, image=pic, anchor=CENTER) dem = PhotoImage(file="demon.gif") # 怪物 a40 = bg4.create_image(275,300,image=dem,anchor=CENTER) a41 = bg4.create_image(565,534, image=dem,anchor=CENTER) a42 = bg4.create_image(505,100, image=dem,anchor=CENTER) a43 = bg4.create_image(130,535, image=dem,anchor=CENTER) Label(win4, text="LEVEL 4", fg='black', font="Times -30 bold", bg='LightSkyBlue').place(x=120, y=27, anchor=CENTER) for i in range(19): for j in range(19): bij = (32 + i * 29, 32 + j * 29, 42 + i * 29, 42 + j * 29) bi_j = bg4.create_oval(bij, outline="pink", fill="pink") bigbean1=bg4.create_oval(465,520,485,540,outline='GreenYellow',fill='GreenYellow') # 放置两个大豆子 bigbean2=bg4.create_oval(345,205,365,225,outline='GreenYellow',fill='GreenYellow') bean=list(bg4.find_overlapping(0, 0, 600, 600)) bean4=bean[0:len(bean)] deleteBeans("map4.txt",bg4,4) global c global d x0___,y0___=-1,0 c,d=1,0 x1___,y1___= -1,0 x2___,y2___= -1,0 x3___,y3___= -1,0 while True: bg4.bind_all('<KeyPress-Up>', movetriangle) bg4.bind_all('<KeyPress-Down>', movetriangle) bg4.bind_all('<KeyPress-Left>', movetriangle) bg4.bind_all('<KeyPress-Right>', movetriangle) zhqEater(c, d,a4,4,bg4) eat(bg4,a4,4,bean4,win4) zhq(a40,x0___,y0___,4,bg4) x0___,y0___=zhuan(a40,x0___,y0___,4,bg4) zhq(a41,x1___,y1___,4,bg4) x1___,y1___=zhuan(a41,x1___,y1___,4,bg4) zhq(a42,x2___,y2___,4,bg4) x2___,y2___=zhuan(a42,x2___,y2___,4,bg4) zhq(a43,x3___,y3___,4,bg4) x3___,y3___=zhuan(a43,x3___,y3___,4,bg4) bg4.update() sleep(0.001) if life == 0 : #Game Over askFail4 = Toplevel(height=200, width=400) askFail4.resizable(0,0) askCanvas = Canvas(askFail4, width=198, height=171, bg="white") askCanvas.grid(row=9) fail = PhotoImage(file="hahaha.gif") failing = askCanvas.create_image(99, 85, image=fail, anchor=CENTER) Label(askFail4, text=" 失败!", font="Times -24 bold", bg="white", fg="black").grid(row=1, rowspan=2, sticky=W + E) Label(askFail4, text="重头开始?", font="Times -20 bold", bg="white", fg="black").grid(row=10, rowspan=2, sticky=W + E) backButton = Button(askFail4, text="ok", font="Times -20 bold", bg="black", fg="white", command=rebackLevel4).grid(row=12) win4.destroy() global ask4 itemsBesidesBeans=[13,20,20,17,30] final=list(bg4.find_overlapping(0,0,600,600)) if final[-1] == itemsBesidesBeans[3] : ask4 = Toplevel(height=200, width=400) ask4.resizable(0,0) askCanvas2 = Canvas(ask4, width=178, height=179, bg="white") askCanvas2.grid(row=9) winwin = PhotoImage(file="winwinwin.gif") winPicture = askCanvas2.create_image(89, 89, image=winwin, anchor=CENTER) Label(ask4, text=" 通关!", font="Times -24 bold", bg="white", fg="black").grid(row=1, rowspan=2, sticky=W + E) Label(ask4, text="继续下一关?", font="Times -20 bold", bg="white", fg="black").grid(row=10, rowspan=2, sticky=W + E) continueButton = Button(ask4, text="ok", font="Times -20 bold", bg="black", fg="white", command=continueLevel5).grid(row=12) win4.destroy() def paintCanvas5(): #LEVEL5 #注释同第一关 global askFail5 global win5 global bg5 global score,life life = 3 score = 0 win5 = Toplevel() win5.resizable(0,0) #固定窗口界面,使不能最大化窗口 bg5 = Canvas(win5, width=600, height=600, bg="white") # 画布 bg5.pack() global a5 p51 = (0, 0, 0, 600, 600, 600, 600, 0, 580, 0, 580, 580, 20, 580, 20, 0) p52 = (20, 0, 20, 20, 580, 20, 580, 0) pw1 = (230, 20, 260, 20, 260, 80, 200, 80, 200, 110, 260, 110, 260, 170, 230, 170, 230, 140, 170, 140, 170, 50, 230, 50) pw2 = (400, 20, 460, 20, 460, 50, 430, 50, 430, 140, 340, 140, 340, 110, 400, 110) pw3 = (490, 20, 580, 20, 580, 50, 490, 50) pw4 = (50, 50, 140, 50, 140, 140, 110, 140, 110, 80, 50, 80) pw5 = (290, 50, 370, 50, 370, 80, 310, 80, 310, 260, 290, 260, 290, 230, 260, 230, 260, 260, 230, 260, 230, 200, 290, 200) pw6 = (460, 80, 490, 80, 490, 140, 460, 140) pw7 = (520, 80, 550, 80, 550, 200, 340, 200, 340, 170, 520, 170) pw8 = (20, 110, 80, 110, 80, 140, 20, 140) pw9 = (50, 170, 80, 170, 80, 230, 200, 230, 200, 340, 260, 340, 260, 370, 170, 370, 170, 260, 140, 260, 140, 370, 50, 370, 50, 340, 110, 340, 110, 260, 50, 260) pw10 = (110, 170, 200, 170, 200, 200, 110, 200) pw11 = (520, 230, 580, 230, 580, 260, 520, 260) pw12 = (340, 230, 490, 230, 490, 260, 400, 260, 400, 370, 310, 370, 310, 430, 140, 430, 140, 550, 110, 550, 110, 400, 290, 400, 290, 340, 370, 340, 370, 260, 340, 260) pw13 = (20, 290, 80, 290, 80, 310, 20, 310) pw14 = (230, 290, 340, 290, 340, 310, 230, 310) pw15 = (430, 290, 550, 290, 550, 370, 520, 370, 520, 310, 430, 310) pw16 = (430, 340, 490, 340, 490, 370, 460, 370, 460, 430, 370, 430, 370, 460, 430, 460, 430, 550, 400, 550, 400, 490, 310, 490, 310, 550, 290, 550, 290, 460, 340, 460, 340, 400, 430, 400) pw17 = (20, 400, 80, 400, 80, 430, 20, 430) pw18 = (490, 400, 550, 400, 550, 490, 520, 490, 520, 430, 490, 430) pw19 = (50, 460, 80, 460, 80, 550, 50, 550) pw20 = (170, 460, 200, 460, 200, 580, 170, 580) pw21 = (230, 460, 260, 460, 260, 550, 230, 550) pw22 = (460, 460, 490, 460, 490, 520, 550, 520, 550, 550, 460, 550) pw23 = (340, 520, 370, 520, 370, 580, 340, 580) w5_24 = bg5.create_polygon(p51, fill="LightSkyBlue") w5_25 = bg5.create_polygon(p52, fill="LightSkyBlue") w5_1 = bg5.create_polygon(pw1, outline="", fill="LightSkyBlue") w5_2 = bg5.create_polygon(pw2, outline="", fill="LightSkyBlue") w5_3 = bg5.create_polygon(pw3, outline="", fill="LightSkyBlue") w5_4 = bg5.create_polygon(pw4, outline="", fill="LightSkyBlue") w5_5 = bg5.create_polygon(pw5, outline="", fill="LightSkyBlue") w5_6 = bg5.create_polygon(pw6, outline="", fill="LightSkyBlue") w5_7 = bg5.create_polygon(pw7, outline="", fill="LightSkyBlue") w5_8 = bg5.create_polygon(pw8, outline="", fill="LightSkyBlue") w5_9 = bg5.create_polygon(pw9, outline="", fill="LightSkyBlue") w5_10 = bg5.create_polygon(pw10, outline="", fill="LightSkyBlue") w5_11 = bg5.create_polygon(pw11, outline="", fill="LightSkyBlue") w5_12 = bg5.create_polygon(pw12, outline="", fill="LightSkyBlue") w5_13 = bg5.create_polygon(pw13, outline="", fill="LightSkyBlue") w5_14 = bg5.create_polygon(pw14, outline="", fill="LightSkyBlue") w5_15 = bg5.create_polygon(pw15, outline="", fill="LightSkyBlue") w5_16 = bg5.create_polygon(pw16, outline="", fill="LightSkyBlue") w5_17 = bg5.create_polygon(pw17, outline="", fill="LightSkyBlue") w5_18 = bg5.create_polygon(pw18, outline="", fill="LightSkyBlue") w5_19 = bg5.create_polygon(pw19, outline="", fill="LightSkyBlue") w5_20 = bg5.create_polygon(pw20, outline="", fill="LightSkyBlue") w5_21 = bg5.create_polygon(pw21, outline="", fill="LightSkyBlue") w5_22 = bg5.create_polygon(pw22, outline="", fill="LightSkyBlue") w5_23 = bg5.create_polygon(pw23, outline="", fill="LightSkyBlue") pic = PhotoImage(file="eater.gif") # 吃豆人 a5 = bg5.create_image(97, 97, image=pic, anchor=CENTER) dem = PhotoImage(file="demon.gif") # 怪物 a50 = bg5.create_image(215,300, image=dem,anchor=CENTER) a51 = bg5.create_image(95,565, image=dem,anchor=CENTER) a52 = bg5.create_image(565,565, image=dem,anchor=CENTER) a53 = bg5.create_image(565,100, image=dem,anchor=CENTER) Label(win5, text="LEVEL 5", fg='black', font="Times -20 bold", bg='LightSkyBlue').place(x=95, y=65, anchor=CENTER) for i in range(19): # 铺豆豆 for j in range(19): bij = (32 + i * 29, 32 + j * 29, 42 + i * 29, 42 + j * 29) bi_j = bg5.create_oval(bij, outline="pink", fill="pink") bigbean1=bg5.create_oval(145,290,165,310,outline='GreenYellow',fill='GreenYellow') # 放置两个大豆子 bigbean2=bg5.create_oval(405,290,425,310,outline='GreenYellow',fill='GreenYellow') bean=list(bg5.find_overlapping(0, 0, 600, 600)) bean5=bean[0:len(bean)] deleteBeans("map5.txt",bg5,5) global c global d x0____,y0____=-1,0 c,d=1,0 x1____,y1____ = -1,0 x2____,y2____ = -1,0 x3____,y3____ = -1,0 while True: bg5.bind_all('<KeyPress-Up>', movetriangle) bg5.bind_all('<KeyPress-Down>', movetriangle) bg5.bind_all('<KeyPress-Left>', movetriangle) bg5.bind_all('<KeyPress-Right>', movetriangle) zhqEater(c, d,a5,5,bg5) eat(bg5,a5,5,bean5,win5) zhq(a50,x0____,y0____,5,bg5) x0____,y0____=zhuan(a50,x0____,y0____,5,bg5) zhq(a51,x1____,y1____,5,bg5) x1____,y1____=zhuan(a51,x1____,y1____,5,bg5) zhq(a52,x2____,y2____,5,bg5) x2____,y2____=zhuan(a52,x2____,y2____,5,bg5) zhq(a53,x3____,y3____,5,bg5) x3____,y3____=zhuan(a53,x3____,y3____,5,bg5) bg5.update() sleep(0.001) if life == 0 : #Game Over askFail5 = Toplevel(height=200, width=400) askFail5.resizable(0,0) askCanvas = Canvas(askFail5, width=198, height=171, bg="white") askCanvas.grid(row=9) fail = PhotoImage(file="hahaha.gif") failing = askCanvas.create_image(99, 85, image=fail, anchor=CENTER) Label(askFail5, text=" 失败!", font="Times -24 bold", bg="white", fg="black").grid(row=1, rowspan=2, sticky=W + E) Label(askFail5, text="重头开始?", font="Times -20 bold", bg="white", fg="black").grid(row=10, rowspan=2, sticky=W + E) backButton = Button(askFail5, text="ok", font="Times -20 bold", bg="black", fg="white", command=rebackLevel5).grid(row=12) win5.destroy() global ask5 itemsBesidesBeans=[13,20,20,17,30] final=list(bg5.find_overlapping(0,0,600,600)) if final[-1] == itemsBesidesBeans[4] : ask5 = Toplevel(height=200, width=400) ask5.resizable(0,0) askCanvas2 = Canvas(ask5, width=178, height=179, bg="white") askCanvas2.grid(row=9) winwin = PhotoImage(file="winwinwin.gif") winPicture = askCanvas2.create_image(89, 89, image=winwin, anchor=CENTER) Label(ask5, text="恭喜通关了本游戏!", font="Times -24 bold", bg="white", fg="black").grid(row=1, rowspan=2, sticky=W+E) Label(ask5, text="豆豆吃的好饱啊……", font="Times -20 bold", bg="white", fg="black").grid(row=10, rowspan=2, sticky=W+E) quitButton5 = Button(ask5, text="byebye", font="Times -20 bold", bg="black", fg="white", command=rootwin.quit).grid(row=12) win5.destroy() def Level_1(): #这是选择关卡窗口对应关卡的按钮所调用的函数,开始第一关 select.destroy() #关闭选择关卡窗口 paintCanvas1() #开始这一关 def Level_2(): #第二关 select.destroy() paintCanvas2() def Level_3(): #第三关 select.destroy() paintCanvas3() def Level_4(): #第四关 select.destroy() paintCanvas4() def Level_5(): #第五关 select.destroy() paintCanvas5() def start(): #这是主窗口的开始游戏按钮调用的函数,由此函数进入第一关 paintCanvas1() def Invincible(): # 第一关无敌版 #内部注释同第一关 winI = Toplevel() winI.resizable(0,0) #固定窗口界面,使不能最大化窗口 global cvI cvI = Canvas(winI, width=600, height=600, bg="white") # 创建画布 cvI.pack() global aI global askI global askFailI p1 = (20, 20, 580, 20, 580, 580, 20, 580, 20, 20) # 地图坐标 pw1 = (20, 20, 580, 20, 580, 580, 20, 580, 20, 80, 80, 80, 80, 490, 490, 490, 490, 80, 20, 80) pw2 = (110, 110, 200, 110, 200, 230, 110, 230) pw3 = (230, 110, 340, 110, 340, 230, 230, 230) pw4 = (370, 110, 460, 110, 460, 230, 370, 230) pw5 = (110, 260, 340, 260, 340, 340, 110, 340) pw6 = (370, 260, 460, 260, 460, 340, 370, 340) pw7 = (110, 370, 340, 370, 340, 460, 110, 460) pw8 = (370, 370, 460, 370, 460, 460, 370, 460) w1_1 = cvI.create_polygon(pw1, outline="", fill="LightSkyBlue") # 画地图,墙 w1_2 = cvI.create_polygon(pw2, outline="", fill="LightSkyBlue") w1_3 = cvI.create_polygon(pw3, outline="", fill="LightSkyBlue") w1_4 = cvI.create_polygon(pw4, outline="", fill="LightSkyBlue") w1_5 = cvI.create_polygon(pw5, outline="", fill="LightSkyBlue") w1_6 = cvI.create_polygon(pw6, outline="", fill="LightSkyBlue") w1_7 = cvI.create_polygon(pw7, outline="", fill="LightSkyBlue") w1_8 = cvI.create_polygon(pw8, outline="", fill="LightSkyBlue") pic = PhotoImage(file="eater.gif") # 吃豆人 aI = cvI.create_image(97, 97, image=pic, anchor=CENTER) # 引入吃豆人的初始坐标 dem1 = PhotoImage(file="demon.gif") # 引入怪物的图片 a20 = cvI.create_image(355, 324, image=dem1, anchor=CENTER) # 放置怪物的初始位置 a21 = cvI.create_image(475, 474, image=dem1, anchor=CENTER) # 放置怪物的初始位置 a22 = cvI.create_image(475, 95, image=dem1, anchor=CENTER) # 放置怪物的初始位置 a23 = cvI.create_image(95, 474, image=dem1, anchor=CENTER) # 放置怪物的初始位置 Label(winI, text="无敌挑战版!!", fg='black', font="Times -30 bold", bg='LightSkyBlue').place(x=450, y=50, anchor=CENTER) for i in range(14): # 将地图铺满豆豆 for j in range(14): bij = (90 + i * 29, 90 + j * 29, 100 + i * 29, 100 + j * 29) # 豆豆的坐标(每隔29个像素,铺一个豆豆,铺满地图) bi_j = cvI.create_oval(bij, outline="pink", fill="pink") # 豆豆的形状:圆形 以及 颜色 deleteBeans("map1.txt",cvI,6) global c global d global aII global bI x0, y0 = -1, 0 c, d = 1, 0 x1, y1 = -1, 0 x2, y2 = -1, 0 x3, y3 = -1, 0 score = 1500000 #这是无敌版不同于正常关卡的地方,用于进行倒计时的变量score Label(winI, text="Your lives: +∞", fg='black', font="Times -15 bold", bg='LightSkyBlue').place(x=300, y=600, anchor=S) while True: cvI.bind_all('<KeyPress-Up>', movetriangle) # 绑定键盘的上下左右键 cvI.bind_all('<KeyPress-Down>', movetriangle) cvI.bind_all('<KeyPress-Left>', movetriangle) cvI.bind_all('<KeyPress-Right>', movetriangle) zhqEater(c,d,aI,6,cvI) cvI.update() xya1 = list(cvI.coords(aI)) # 报告吃豆人的中心坐标,存储形式:xya1=[x1,y1,x2,y2] xya = list(cvI.find_overlapping(xya1[0] - 10, xya1[1] - 10, xya1[0] + 10, xya1[ 1] + 10)) # 吃豆人的大小是20*20,所以(xya1[0]-10,xya1[1]-10,xya1[0]+10,xya1[1]+10)得到的是吃豆人矩形 #用find_overlapping找出与吃豆人矩形范围内重叠的其他图形(豆豆)的标识号,存到列表中 for n in xya: # 删掉xya中的图形项(豆豆),表示被吃掉了 if n > 13: cvI.delete(n) elif n > 9: sleep(0.5) cvI.move(aI, 97 - xya1[0], 97 - xya1[1]) xyn = list(cvI.coords(n)) cvI.move(n, 475 - xyn[0], 474 - xyn[1]) score -= 20000 #被怪物吃掉后,score减少20000 sleep(0.0002) score -= 1 #表示每0.0002秒score会减少1(如果不被怪物吃掉,一般大约5分钟左右score变为0) zhq(a20, x0, y0,6,cvI) x0, y0 = zhuan(a20, x0, y0,6,cvI) zhq(a21, x1, y1,6,cvI) x1, y1 = zhuan(a21, x1, y1,6,cvI) zhq(a22, x2, y2,6,cvI) x2, y2 = zhuan(a22, x2, y2,6,cvI) zhq(a23, x3, y3,6,cvI) x3, y3 = zhuan(a23, x3, y3,6,cvI) cvI.update() final = list(cvI.find_overlapping(0, 0, 600, 600)) if final[-1] == 13: #这个胜利窗口可以告诉玩家无敌版的秘密 askI = Toplevel(height=200, width=400) askI.resizable(0,0) askCanvas2 = Canvas(askI, width=178, height=179, bg="white") askCanvas2.grid(row=12) winwin = PhotoImage(file="winwinwin.gif") winPicture = askCanvas2.create_image(89, 89, image=winwin, anchor=CENTER) Label(askI, text="Your HP: %d" % (score), fg="black", font="Times -20 bold", bg="white").grid(row=3, rowspan=2, sticky=W + E) Label(askI, text="恭喜通关了无敌(鬼畜)版!", font="Times -24 bold", bg="white", fg="black").grid(row=1, rowspan=2, sticky=W + E) secret = "嗯……\n通关了无敌版的你应该发现了:\n这个无敌版是有限制的!\n" \ "在最开始你有1,500,000HP的,\n但是随着时间增加,它是慢慢减少的;\n" \ "并且如果怪物吃了你,\n你的HP会减少20,000!\n\n" \ "……所以如果你输过了的话,\n你应该知道你是怎么输的了吧\n" Label(askI, text=secret, font="Times -20 bold", bg="white", fg="black").grid(row=13, sticky=W + E) Label(askI, text="hhh,游戏愉快!", font="Times -20 bold", bg="white", fg="black").grid(row=21, rowspan=2, sticky=W + E) quitButtonI = Button(askI, text="byebye", font="Times -20 bold", bg="black", fg="white", command=destroyI).grid(row=23) winI.destroy() if score <= 0: #倒计时结束,玩家失败 askFailI = Toplevel(height=200, width=400) askFailI.resizable(0,0) askCanvas = Canvas(askFailI, width=198, height=171, bg="white") askCanvas.grid(row=12) fail = PhotoImage(file="hahaha.gif") failing = askCanvas.create_image(99, 85, image=fail, anchor=CENTER) Label(askFailI, text="Your HP: %d" % (score), fg="black", font="Times -20 bold", bg="white").grid(row=3, rowspan=2, sticky=W + E) #此处提示玩家是有HP的(就是score的值) Label(askFailI, text=" 失败!", font="Times -24 bold", bg="white", fg="black").grid(row=1, rowspan=2, sticky=W + E) Label(askFailI, text="重头开始?", font="Times -20 bold", bg="white", fg="black").grid(row=13, rowspan=2, sticky=W + E) backButton = Button(askFailI, text="ok", font="Times -20 bold", bg="black", fg="white", command=rebackI).grid(row=15) winI.destroy() def Destroy3():#用于退出关卡选择界面的命令函数 select.destroy() def SelectLevel(): #选择关卡,有对应关卡的按钮 global select select = Toplevel() select.resizable(0,0) #固定窗口界面,使不能最大化窗口 # 以下是界面装饰部分 bgr3 = Canvas(select, width=600, height=800, bg="white") bgr3.pack() pe1 = (40, 36, 114, 110) pee1 = (75, 57, 79, 61) eater1 = bgr3.create_arc(pe1, start=45, extent=270, fill="black") eatereye1 = bgr3.create_oval(pee1, fill="white") pe2 = (600 - 114, 800 - 110, 600 - 40, 800 - 36) pee2 = (600 - 79, 800 - 61, 600 - 75, 800 - 57) eater2 = bgr3.create_arc(pe2, start=225, extent=270, fill="black") eatereye2 = bgr3.create_oval(pee2, fill="white") adornment1 = bgr3.create_rectangle(40, 110, 50, 720, outline="", fill="black") adornment2 = bgr3.create_rectangle(80, 754, 464, 764, outline="", fill="black") adornment3 = bgr3.create_rectangle(600 - 50, 800 - 720, 600 - 40, 800 - 110, outline="", fill="black") adornment4 = bgr3.create_rectangle(600 - 464, 800 - 764, 600 - 80, 800 - 754, outline="", fill="black") adornment5 = bgr3.create_oval(600 - 51, 800 - 764, 600 - 40, 800 - 753, outline="", fill="black") adornment6 = bgr3.create_oval(40, 753, 51, 764, outline="", fill="black") #以下是关卡选择窗口中的标签和按钮,每个按钮对应每个关卡,以及退出该选择关卡窗口的按钮 selecttitle = Label(select, text="关卡选择", font="Times -25 bold", bg="black", fg="white").place(x=170, y=110, anchor=CENTER) Button_1 = Button(select, text="关卡1", font="Times -20 bold", bg="black", fg="white", command=Level_1).place(x=170, y=240, anchor=CENTER) Button_2 = Button(select, text="关卡2", font="Times -20 bold", bg="black", fg="white", command=Level_2).place(x=170, y=340, anchor=CENTER) Button_3 = Button(select, text="关卡3", font="Times -20 bold", bg="black", fg="white", command=Level_3).place(x=170, y=440, anchor=CENTER) Button_4 = Button(select, text="关卡4", font="Times -20 bold", bg="black", fg="white", command=Level_4).place(x=170, y=540, anchor=CENTER) Button_5 = Button(select, text="关卡5", font="Times -20 bold", bg="black", fg="white", command=Level_5).place(x=170, y=640, anchor=CENTER) Button_I = Button(select, text="无敌版", font="Times -20 bold", bg="black", fg="white", command=Invincible).place(x=430, y=240, anchor=CENTER) ExitButton3 = Button(select, text="exit", font="Times -20 bold", bg="black", fg="white", command=Destroy3).place(x=437, y=700, anchor=CENTER) def Destroy1():#用于退出帮助界面的命令函数 rootwin1.destroy() def Help(): #帮助界面 global rootwin1 rootwin1 = Toplevel() rootwin1.resizable(0,0) #固定窗口界面,使不能最大化窗口 #以下是装饰部分 bgr1 = Canvas(rootwin1, width=600, height=800, bg="white") bgr1.pack() pe1 = (40, 36, 114, 110) pee1 = (75, 57, 79, 61) eater1 = bgr1.create_arc(pe1, start=45, extent=270, fill="black") eatereye1 = bgr1.create_oval(pee1, fill="white") pe2 = (600 - 114, 800 - 110, 600 - 40, 800 - 36) pee2 = (600 - 79, 800 - 61, 600 - 75, 800 - 57) eater2 = bgr1.create_arc(pe2, start=225, extent=270, fill="black") eatereye2 = bgr1.create_oval(pee2, fill="white") adornment1 = bgr1.create_rectangle(40, 110, 50, 720, outline="", fill="black") adornment2 = bgr1.create_rectangle(80, 754, 464, 764, outline="", fill="black") adornment3 = bgr1.create_rectangle(600 - 50, 800 - 720, 600 - 40, 800 - 110, outline="", fill="black") adornment4 = bgr1.create_rectangle(600 - 464, 800 - 764, 600 - 80, 800 - 754, outline="", fill="black") adornment5 = bgr1.create_oval(600 - 51, 800 - 764, 600 - 40, 800 - 753, outline="", fill="black") adornment6 = bgr1.create_oval(40, 753, 51, 764, outline="", fill="black") #以下是帮助窗口的标签、文本和退出按钮 title_H = "游戏帮助" helpstitle = Label(rootwin1, text=title_H, font="Times -25 bold", bg="black", fg="white").place(x=170, y=110, anchor=CENTER) helptext = "利用键盘方向键控制吃豆人的移动方向,避开怪物,把地图上的所有豆豆吃掉过关!\n\n" \ "普通豆豆(小豆子):吃掉一颗分数增加10点\n奖励豆豆(大豆子):吃掉一颗分数增加50点," \ "并且增加一条生命\n怪物:怪物会随机运动,一旦碰到怪物会失去一条生命" \ "\n\n游戏共有5关,在每一关你有初始的三条生命," \ "生命全部失去后会GAME OVER\n\n\n\n" \ "Ps: 其实有一个无敌版,操作方法是没有变化的,但是……" \ "具体是什么情况呢请慢慢探索(◍ ´꒳` ◍)" helps = Message(rootwin1,text=helptext,font="Times -20 bold", bg="white",fg="black",width=460).place(x=300,y=400,anchor=CENTER) ExitButton1 = Button(rootwin1, text="exit", font="Times -20 bold", bg="black", fg="white", command=Destroy1).place(x=437, y=700, anchor=CENTER) def Destroy2():#用于退出制作人员界面的命令函数 global rootwin2 rootwin2.destroy() def Staff(): #制作人员界面 global rootwin2 rootwin2 = Toplevel() rootwin2.resizable(0,0) #固定窗口界面,使不能最大化窗口 bgr2 = Canvas(rootwin2, width=600, height=800, bg="white") bgr2.pack() pe1 = (40, 36, 114, 110) pee1 = (75, 57, 79, 61) eater1 = bgr2.create_arc(pe1, start=45, extent=270, fill="black") eatereye1 = bgr2.create_oval(pee1, fill="white") pe2 = (600 - 114, 800 - 110, 600 - 40, 800 - 36) pee2 = (600 - 79, 800 - 61, 600 - 75, 800 - 57) eater2 = bgr2.create_arc(pe2, start=225, extent=270, fill="black") eatereye2 = bgr2.create_oval(pee2, fill="white") adornment1 = bgr2.create_rectangle(40, 110, 50, 720, outline="", fill="black") adornment2 = bgr2.create_rectangle(80, 754, 464, 764, outline="", fill="black") adornment3 = bgr2.create_rectangle(600 - 50, 800 - 720, 600 - 40, 800 - 110, outline="", fill="black") adornment4 = bgr2.create_rectangle(600 - 464, 800 - 764, 600 - 80, 800 - 754, outline="", fill="black") adornment5 = bgr2.create_oval(600 - 51, 800 - 764, 600 - 40, 800 - 753, outline="", fill="black") adornment6 = bgr2.create_oval(40, 753, 51, 764, outline="", fill="black") #以下制作人员窗口的标签及文本,和退出该窗口的按钮 title_S = "制作人员" StaffTitle = Label(rootwin2, text=title_S, font="Times -25 bold", bg="black", fg="white").place(x=170, y=110, anchor=CENTER) stafflist = "组长:\n\n方焯\n\n\n组员:\n\n乔蕴昭\n\n王梦瑶\n\n李 珊" Stafflist = Message(rootwin2, text=stafflist, font="Times -20 bold", bg="white", fg="black",width=460).place(x=170,y=300,anchor=CENTER) ExitButton2 = Button(rootwin2, text="exit", font="Times -20 bold", bg="black", fg="white", command=Destroy2).place(x=437, y=700, anchor=CENTER) #以下为主界面及对应按钮 rootwin = Tk() rootwin.resizable(0,0) #固定窗口界面,使不能最大化窗口 rootwin.title("PAC-MAN") rootwin.geometry("600x800") #下述部分是界面装饰部分 bg = Canvas(rootwin,width=600,height=800,bg="white") bg.pack() pe1 = (40, 36, 114, 110) pee1 = (75, 57, 79, 61) eater1 = bg.create_arc(pe1, start=45, extent=270, fill="black") eatereye1 = bg.create_oval(pee1, fill="white") pe2 = (600 - 114, 800 - 110, 600 - 40, 800 - 36) pee2 = (600 - 79, 800 - 61, 600 - 75, 800 - 57) eater2 = bg.create_arc(pe2, start=225, extent=270, fill="black") eatereye2 = bg.create_oval(pee2, fill="white") adornment1 = bg.create_rectangle(40, 110, 50, 720, outline="", fill="black") adornment2 = bg.create_rectangle(80, 754, 464, 764, outline="", fill="black") adornment3 = bg.create_rectangle(600-50, 800-720, 600-40, 800-110, outline="", fill="black") adornment4 = bg.create_rectangle(600-464, 800-764, 600-80, 800-754, outline="", fill="black") adornment5 = bg.create_rectangle(365, 240, 479, 245, outline="", fill="black") adornment6 = bg.create_rectangle(365, 240+17, 479, 245+17, outline="", fill="black") adornment7 = bg.create_oval(600-51, 800-764, 600-40, 800-753, outline="", fill="black") adornment8 = bg.create_oval(40, 753, 51, 764, outline="", fill="black") #下面三行是主标题 TitleFrame = Frame(rootwin,width=320,height=80) TitleFrame.place(x=300,y=175,anchor=CENTER) Title = Label(TitleFrame,text="Pac - Man", font="Times -80 bold", bg="black", fg="white").grid(sticky=E+W+N+S) #接下来是按钮 ButtonFrame = Frame(rootwin,width=320,height=410) ButtonFrame.place(x=300,y=510,anchor=CENTER) #开始按钮,对应函数start() StartButton = Button(ButtonFrame,text="Start New Game",font="Times -30 bold",bg="black", fg="white",command=start).grid(row=0,rowspan=2,sticky=W+E) #跳关按钮,对应函数SelectLevel() SelectButton = Button(ButtonFrame,text="Select Level",font="Times -30 bold",bg="black", fg="white",command=SelectLevel).grid(row=4,rowspan=2,sticky=W+E) #帮助按钮,对应函数Help() HelpButton = Button(ButtonFrame,text="Game Help",font="Times -30 bold",bg="black", fg="white",command=Help).grid(row=8,rowspan=2,sticky=W+E) #制作组按钮,对应函数Staff() StaffButton = Button(ButtonFrame,text="Staff List",font="Times -30 bold",bg="black", fg="white",command=Staff).grid(row=12,rowspan=2,sticky=W+E) #退出按钮,根窗口主循环退出 ExitButton = Button(rootwin,text="exit",font="Times -20 bold",bg="black", fg="white",command=rootwin.quit).place(x=437,y=700,anchor=CENTER) rootwin.mainloop() #进入主循环
[ "noreply@github.com" ]
noreply@github.com
d3f738a922c2ea7fe1926992b5765c878b180712
6899f55b07bd6d49da2d331dfce217f92673ed34
/Accounts/views.py
8bbba8102db9276f6aa4bd89a08304dd6d7071ad
[ "MIT" ]
permissive
Khushiraikar1/sudhaksha_maxo
e72945f2d2e6ec985b27a67f2db4465cf3a72ce2
ccaba5426b8fcac0d6772bdb78916cb0cd0c09e7
refs/heads/main
2023-02-11T12:09:35.046523
2021-01-15T16:37:55
2021-01-15T16:37:55
317,636,328
2
6
MIT
2021-01-15T15:40:49
2020-12-01T18:46:39
HTML
UTF-8
Python
false
false
1,536
py
from django.shortcuts import render,redirect,get_object_or_404 from django.contrib.auth import authenticate,login,logout from django.contrib.auth.models import User from .forms import Registrationform,Profileform,Register from django.contrib import messages from .models import profile from django.contrib.auth.decorators import login_required from .randgenrator import rand from .decarators import unauthenticated_user # Create your views here. @unauthenticated_user def register(request): if request.POST: form=Registrationform(request.POST) if(form.is_valid()): username=form.cleaned_data.get('username') messages.success(request,f'Account created for {username}') b=form.save() u_id=rand(8) a=profile(user=b,Uid=u_id) a.save() return redirect('/accounts/registeration',{'messages':messages}) else: form=Registrationform() return render(request, 'adhyayana.html',{'form':form}) @login_required def registration(request): client=profile.objects.get(user=request.user).Uid if request.POST: form1=Register(request.POST,instance=request.user) form2=Profileform(request.POST,instance=request.user.profile) if form2.is_valid(): form1.save() form2.save() messages.success(request,f'Registration Complete!!' ) return redirect('home') else: form1=Register(instance=request.user) form2=Profileform(instance=request.user.profile) return render(request,'registration.html',{'form1':form1,'form2':form2,'uid':client}) def userlogout(request): logout(request) return redirect('home')
[ "anandajith911@gmail.com" ]
anandajith911@gmail.com
e504b3eab9169f7b66094ab0d02abc8b8d857565
3f854f15ed22c0dc5a14f6d9d62f4e69657fa13c
/updated/catkin_ws/build/catkin_generated/installspace/_setup_util.py
97ac002b9ced133a8aa05a680da2a0d4b7b0f25a
[ "BSD-2-Clause" ]
permissive
JisuHann/Point-Cloud-Grasp
3bbbcaa30c83cd07a4b73e45064d72d440e78c7a
083244632412709dbc29ac7841b6a837e4ed3cb6
refs/heads/main
2023-06-22T01:18:59.809150
2021-07-23T10:23:15
2021-07-23T10:23:15
353,249,941
2
1
BSD-2-Clause
2021-05-26T02:35:31
2021-03-31T06:26:38
Makefile
UTF-8
Python
false
false
13,338
py
#!/usr/bin/python2 # -*- coding: utf-8 -*- # Software License Agreement (BSD License) # # Copyright (c) 2012, Willow Garage, Inc. # 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 Willow Garage, Inc. 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. """This file generates shell code for the setup.SHELL scripts to set environment variables.""" from __future__ import print_function import argparse import copy import errno import os import platform import sys CATKIN_MARKER_FILE = '.catkin' system = platform.system() IS_DARWIN = (system == 'Darwin') IS_WINDOWS = (system == 'Windows') PATH_TO_ADD_SUFFIX = ['bin'] if IS_WINDOWS: # while catkin recommends putting dll's into bin, 3rd party packages often put dll's into lib # since Windows finds dll's via the PATH variable, prepend it with path to lib PATH_TO_ADD_SUFFIX.extend([['lib', os.path.join('lib', 'x86_64-linux-gnu')]]) # subfolder of workspace prepended to CMAKE_PREFIX_PATH ENV_VAR_SUBFOLDERS = { 'CMAKE_PREFIX_PATH': '', 'LD_LIBRARY_PATH' if not IS_DARWIN else 'DYLD_LIBRARY_PATH': ['lib', os.path.join('lib', 'x86_64-linux-gnu')], 'PATH': PATH_TO_ADD_SUFFIX, 'PKG_CONFIG_PATH': [os.path.join('lib', 'pkgconfig'), os.path.join('lib', 'x86_64-linux-gnu', 'pkgconfig')], 'PYTHONPATH': 'lib/python2.7/dist-packages', } def rollback_env_variables(environ, env_var_subfolders): """ Generate shell code to reset environment variables. by unrolling modifications based on all workspaces in CMAKE_PREFIX_PATH. This does not cover modifications performed by environment hooks. """ lines = [] unmodified_environ = copy.copy(environ) for key in sorted(env_var_subfolders.keys()): subfolders = env_var_subfolders[key] if not isinstance(subfolders, list): subfolders = [subfolders] value = _rollback_env_variable(unmodified_environ, key, subfolders) if value is not None: environ[key] = value lines.append(assignment(key, value)) if lines: lines.insert(0, comment('reset environment variables by unrolling modifications based on all workspaces in CMAKE_PREFIX_PATH')) return lines def _rollback_env_variable(environ, name, subfolders): """ For each catkin workspace in CMAKE_PREFIX_PATH remove the first entry from env[NAME] matching workspace + subfolder. :param subfolders: list of str '' or subfoldername that may start with '/' :returns: the updated value of the environment variable. """ value = environ[name] if name in environ else '' env_paths = [path for path in value.split(os.pathsep) if path] value_modified = False for subfolder in subfolders: if subfolder: if subfolder.startswith(os.path.sep) or (os.path.altsep and subfolder.startswith(os.path.altsep)): subfolder = subfolder[1:] if subfolder.endswith(os.path.sep) or (os.path.altsep and subfolder.endswith(os.path.altsep)): subfolder = subfolder[:-1] for ws_path in _get_workspaces(environ, include_fuerte=True, include_non_existing=True): path_to_find = os.path.join(ws_path, subfolder) if subfolder else ws_path path_to_remove = None for env_path in env_paths: env_path_clean = env_path[:-1] if env_path and env_path[-1] in [os.path.sep, os.path.altsep] else env_path if env_path_clean == path_to_find: path_to_remove = env_path break if path_to_remove: env_paths.remove(path_to_remove) value_modified = True new_value = os.pathsep.join(env_paths) return new_value if value_modified else None def _get_workspaces(environ, include_fuerte=False, include_non_existing=False): """ Based on CMAKE_PREFIX_PATH return all catkin workspaces. :param include_fuerte: The flag if paths starting with '/opt/ros/fuerte' should be considered workspaces, ``bool`` """ # get all cmake prefix paths env_name = 'CMAKE_PREFIX_PATH' value = environ[env_name] if env_name in environ else '' paths = [path for path in value.split(os.pathsep) if path] # remove non-workspace paths workspaces = [path for path in paths if os.path.isfile(os.path.join(path, CATKIN_MARKER_FILE)) or (include_fuerte and path.startswith('/opt/ros/fuerte')) or (include_non_existing and not os.path.exists(path))] return workspaces def prepend_env_variables(environ, env_var_subfolders, workspaces): """Generate shell code to prepend environment variables for the all workspaces.""" lines = [] lines.append(comment('prepend folders of workspaces to environment variables')) paths = [path for path in workspaces.split(os.pathsep) if path] prefix = _prefix_env_variable(environ, 'CMAKE_PREFIX_PATH', paths, '') lines.append(prepend(environ, 'CMAKE_PREFIX_PATH', prefix)) for key in sorted(key for key in env_var_subfolders.keys() if key != 'CMAKE_PREFIX_PATH'): subfolder = env_var_subfolders[key] prefix = _prefix_env_variable(environ, key, paths, subfolder) lines.append(prepend(environ, key, prefix)) return lines def _prefix_env_variable(environ, name, paths, subfolders): """ Return the prefix to prepend to the environment variable NAME. Adding any path in NEW_PATHS_STR without creating duplicate or empty items. """ value = environ[name] if name in environ else '' environ_paths = [path for path in value.split(os.pathsep) if path] checked_paths = [] for path in paths: if not isinstance(subfolders, list): subfolders = [subfolders] for subfolder in subfolders: path_tmp = path if subfolder: path_tmp = os.path.join(path_tmp, subfolder) # skip nonexistent paths if not os.path.exists(path_tmp): continue # exclude any path already in env and any path we already added if path_tmp not in environ_paths and path_tmp not in checked_paths: checked_paths.append(path_tmp) prefix_str = os.pathsep.join(checked_paths) if prefix_str != '' and environ_paths: prefix_str += os.pathsep return prefix_str def assignment(key, value): if not IS_WINDOWS: return 'export %s="%s"' % (key, value) else: return 'set %s=%s' % (key, value) def comment(msg): if not IS_WINDOWS: return '# %s' % msg else: return 'REM %s' % msg def prepend(environ, key, prefix): if key not in environ or not environ[key]: return assignment(key, prefix) if not IS_WINDOWS: return 'export %s="%s$%s"' % (key, prefix, key) else: return 'set %s=%s%%%s%%' % (key, prefix, key) def find_env_hooks(environ, cmake_prefix_path): """Generate shell code with found environment hooks for the all workspaces.""" lines = [] lines.append(comment('found environment hooks in workspaces')) generic_env_hooks = [] generic_env_hooks_workspace = [] specific_env_hooks = [] specific_env_hooks_workspace = [] generic_env_hooks_by_filename = {} specific_env_hooks_by_filename = {} generic_env_hook_ext = 'bat' if IS_WINDOWS else 'sh' specific_env_hook_ext = environ['CATKIN_SHELL'] if not IS_WINDOWS and 'CATKIN_SHELL' in environ and environ['CATKIN_SHELL'] else None # remove non-workspace paths workspaces = [path for path in cmake_prefix_path.split(os.pathsep) if path and os.path.isfile(os.path.join(path, CATKIN_MARKER_FILE))] for workspace in reversed(workspaces): env_hook_dir = os.path.join(workspace, 'etc', 'catkin', 'profile.d') if os.path.isdir(env_hook_dir): for filename in sorted(os.listdir(env_hook_dir)): if filename.endswith('.%s' % generic_env_hook_ext): # remove previous env hook with same name if present if filename in generic_env_hooks_by_filename: i = generic_env_hooks.index(generic_env_hooks_by_filename[filename]) generic_env_hooks.pop(i) generic_env_hooks_workspace.pop(i) # append env hook generic_env_hooks.append(os.path.join(env_hook_dir, filename)) generic_env_hooks_workspace.append(workspace) generic_env_hooks_by_filename[filename] = generic_env_hooks[-1] elif specific_env_hook_ext is not None and filename.endswith('.%s' % specific_env_hook_ext): # remove previous env hook with same name if present if filename in specific_env_hooks_by_filename: i = specific_env_hooks.index(specific_env_hooks_by_filename[filename]) specific_env_hooks.pop(i) specific_env_hooks_workspace.pop(i) # append env hook specific_env_hooks.append(os.path.join(env_hook_dir, filename)) specific_env_hooks_workspace.append(workspace) specific_env_hooks_by_filename[filename] = specific_env_hooks[-1] env_hooks = generic_env_hooks + specific_env_hooks env_hooks_workspace = generic_env_hooks_workspace + specific_env_hooks_workspace count = len(env_hooks) lines.append(assignment('_CATKIN_ENVIRONMENT_HOOKS_COUNT', count)) for i in range(count): lines.append(assignment('_CATKIN_ENVIRONMENT_HOOKS_%d' % i, env_hooks[i])) lines.append(assignment('_CATKIN_ENVIRONMENT_HOOKS_%d_WORKSPACE' % i, env_hooks_workspace[i])) return lines def _parse_arguments(args=None): parser = argparse.ArgumentParser(description='Generates code blocks for the setup.SHELL script.') parser.add_argument('--extend', action='store_true', help='Skip unsetting previous environment variables to extend context') parser.add_argument('--local', action='store_true', help='Only consider this prefix path and ignore other prefix path in the environment') return parser.parse_known_args(args=args)[0] if __name__ == '__main__': try: try: args = _parse_arguments() except Exception as e: print(e, file=sys.stderr) sys.exit(1) if not args.local: # environment at generation time CMAKE_PREFIX_PATH = r'/home/min/catkin_ws/devel;/opt/ros/melodic'.split(';') else: # don't consider any other prefix path than this one CMAKE_PREFIX_PATH = [] # prepend current workspace if not already part of CPP base_path = os.path.dirname(__file__) # CMAKE_PREFIX_PATH uses forward slash on all platforms, but __file__ is platform dependent # base_path on Windows contains backward slashes, need to be converted to forward slashes before comparison if os.path.sep != '/': base_path = base_path.replace(os.path.sep, '/') if base_path not in CMAKE_PREFIX_PATH: CMAKE_PREFIX_PATH.insert(0, base_path) CMAKE_PREFIX_PATH = os.pathsep.join(CMAKE_PREFIX_PATH) environ = dict(os.environ) lines = [] if not args.extend: lines += rollback_env_variables(environ, ENV_VAR_SUBFOLDERS) lines += prepend_env_variables(environ, ENV_VAR_SUBFOLDERS, CMAKE_PREFIX_PATH) lines += find_env_hooks(environ, CMAKE_PREFIX_PATH) print('\n'.join(lines)) # need to explicitly flush the output sys.stdout.flush() except IOError as e: # and catch potential "broken pipe" if stdout is not writable # which can happen when piping the output to a file but the disk is full if e.errno == errno.EPIPE: print(e, file=sys.stderr) sys.exit(2) raise sys.exit(0)
[ "sammin9614@gmail.com" ]
sammin9614@gmail.com
4681f93f39d6f4d7e12d2abc33f56032b610f0e0
d50dec961435073f35bd89be322341862cf7ae6c
/enaml/qt/docking/q_dock_container.py
7c95686787621238b95078e2b6c0b4259b34ad77
[ "BSD-3-Clause" ]
permissive
johnelund/enaml
19971d298b46c5c08f662110cb1c3b6bab976936
1e957da694e84d016a19c4866a1801ca04651fa5
refs/heads/master
2021-01-18T08:51:44.403979
2013-07-03T20:37:36
2013-07-03T20:37:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
19,875
py
#------------------------------------------------------------------------------ # Copyright (c) 2013, Nucleic Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #------------------------------------------------------------------------------ from atom.api import Typed, Bool from enaml.qt.QtCore import Qt, QMargins, QPoint, QRect, QEvent, Signal from enaml.qt.QtGui import QApplication, QLayout, QIcon from .q_dock_area import QDockArea from .q_dock_frame import QDockFrame from .q_dock_frame_layout import QDockFrameLayout from .q_dock_tab_widget import QDockTabWidget from .utils import repolish class QDockContainerLayout(QDockFrameLayout): """ A QDockFrameLayout subclass which works with a QDockContainer. """ def invalidate(self): """ Invalidate the cached layout data. """ super(QDockContainerLayout, self).invalidate() widget = self.getWidget() if widget is not None: self.parentWidget().setSizePolicy(widget.sizePolicy()) def _computePressPos(container, coeff): """ Compute the press position for a title bar. Parameters ---------- container : QDockContainer The dock container which owns the title bar of interest. coeff : float A floating point value between 0.0 and 1.0 which is the proportional x-offset of the mouse press in the title bar. """ margins = container.layout().contentsMargins() button_width = 50 # general approximation max_x = container.width() - margins.right() - button_width test_x = int(coeff * container.width()) new_x = max(margins.left() + 5, min(test_x, max_x)) title_bar = container.dockItem().titleBarWidget() title_height = title_bar.height() / 2 mid_title = title_bar.mapTo(container, QPoint(0, title_height)) return QPoint(new_x, mid_title.y()) class QDockContainer(QDockFrame): """ A QDockFrame which holds a QDockItem instance. A QDockContainer has a dynamic boolean property 'floating' which can be used to apply custom stylesheet styling when the container is a floating top level window versus docked in a dock area. """ #: A signal emitted when the container changes its toplevel state. topLevelChanged = Signal(bool) class FrameState(QDockFrame.FrameState): """ A private class for managing container drag state. """ #: The original title bar press position. press_pos = Typed(QPoint) #: Whether or not the dock item is being dragged. dragging = Bool(False) #: Whether the dock item is maximized in the dock area. item_is_maximized = Bool(False) def __init__(self, manager, parent=None): """ Initialize a QDockContainer. Parameters ---------- manager : DockManager The manager which owns the container. parent : QWidget or None The parent of the QDockContainer. """ super(QDockContainer, self).__init__(manager, parent) layout = QDockContainerLayout() layout.setSizeConstraint(QLayout.SetMinAndMaxSize) self.setLayout(layout) self.setProperty('floating', False) self._dock_item = None #-------------------------------------------------------------------------- # Reimplementations #-------------------------------------------------------------------------- def titleBarGeometry(self): """ Get the geometry rect for the title bar. Returns ------- result : QRect The geometry rect for the title bar, expressed in frame coordinates. An invalid rect is returned if title bar should not be active. """ title_bar = self.dockItem().titleBarWidget() if title_bar.isHidden(): return QRect() pt = title_bar.mapTo(self, QPoint(0, 0)) return QRect(pt, title_bar.size()) def resizeMargins(self): """ Get the margins to use for resizing the container. Returns ------- result : QMargins The margins to use for container resizing when the container is a top-level window. """ if self.isMaximized(): return QMargins() return self.layout().contentsMargins() def showMaximized(self): """ Handle the show maximized request for the dock container. """ def update_buttons(bar, link=False): buttons = bar.buttons() buttons |= bar.RestoreButton buttons &= ~bar.MaximizeButton if link: buttons &= ~bar.LinkButton bar.setButtons(buttons) if self.isWindow(): super(QDockContainer, self).showMaximized() self.setLinked(False) update_buttons(self.dockItem().titleBarWidget(), link=True) else: area = self.parentDockArea() if area is not None: item = self.dockItem() update_buttons(item.titleBarWidget()) area.setMaximizedWidget(item) self.frame_state.item_is_maximized = True item.installEventFilter(self) def showNormal(self): """ Handle the show normal request for the dock container. """ def update_buttons(bar, link=False): buttons = bar.buttons() buttons |= bar.MaximizeButton buttons &= ~bar.RestoreButton if link: buttons |= bar.LinkButton bar.setButtons(buttons) if self.isWindow(): super(QDockContainer, self).showNormal() self.setLinked(False) update_buttons(self.dockItem().titleBarWidget(), link=True) elif self.frame_state.item_is_maximized: item = self.dockItem() update_buttons(item.titleBarWidget()) self.layout().setWidget(item) self.frame_state.item_is_maximized = False item.removeEventFilter(self) #-------------------------------------------------------------------------- # Framework API #-------------------------------------------------------------------------- def dockItem(self): """ Get the dock item installed on the container. Returns ------- result : QDockItem or None The dock item installed in the container, or None. """ return self._dock_item def setDockItem(self, dock_item): """ Set the dock item for the container. Parameters ---------- dock_item : QDockItem The dock item to use in the container. """ layout = self.layout() old = layout.getWidget() if old is not None: old.maximizeButtonClicked.disconnect(self.showMaximized) old.restoreButtonClicked.disconnect(self.showNormal) old.closeButtonClicked.disconnect(self.close) old.linkButtonToggled.disconnect(self.linkButtonToggled) old.titleBarLeftDoubleClicked.disconnect(self.toggleMaximized) if dock_item is not None: dock_item.maximizeButtonClicked.connect(self.showMaximized) dock_item.restoreButtonClicked.connect(self.showNormal) dock_item.closeButtonClicked.connect(self.close) dock_item.linkButtonToggled.connect(self.linkButtonToggled) dock_item.titleBarLeftDoubleClicked.connect(self.toggleMaximized) layout.setWidget(dock_item) self._dock_item = dock_item def title(self): """ Get the title for the container. This proxies the call to the underlying dock item. """ item = self.dockItem() if item is not None: return item.title() return u'' def icon(self): """ Get the icon for the container. This proxies the call to the underlying dock item. """ item = self.dockItem() if item is not None: return item.icon() return QIcon() def closable(self): """ Get whether or not the container is closable. This proxies the call to the underlying dock item. """ item = self.dockItem() if item is not None: return item.closable() return True def isLinked(self): """ Get whether or not the container is linked. This proxies the call to the underlying dock item. """ item = self.dockItem() if item is not None: return item.isLinked() return False def setLinked(self, linked): """ Set whether or not the container should be linked. This proxies the call to the underlying dock item. """ item = self.dockItem() if item is not None: item.setLinked(linked) def showTitleBar(self): """ Show the title bar for the container. This proxies the call to the underlying dock item. """ item = self.dockItem() if item is not None: item.titleBarWidget().show() def hideTitleBar(self): """ Hide the title bar for the container. This proxies the call to the underlying dock item. """ item = self.dockItem() if item is not None: item.titleBarWidget().hide() def showLinkButton(self): """ Show the link button on the title bar. """ item = self.dockItem() if item is not None: bar = item.titleBarWidget() bar.setButtons(bar.buttons() | bar.LinkButton) def hideLinkButton(self): """ Show the link button on the title bar. """ item = self.dockItem() if item is not None: bar = item.titleBarWidget() bar.setButtons(bar.buttons() & ~bar.LinkButton) def toggleMaximized(self): """ Toggle the maximized state of the container. """ is_win = self.isWindow() is_maxed = self.isMaximized() item_maxed = self.frame_state.item_is_maximized if is_win and is_maxed or item_maxed: self.showNormal() else: self.showMaximized() def reset(self): """ Reset the container to the initial pre-docked state. """ state = self.frame_state state.dragging = False state.press_pos = None self.showNormal() self.unfloat() self.hideLinkButton() self.setLinked(False) self.showTitleBar() self.setAttribute(Qt.WA_WState_ExplicitShowHide, False) self.setAttribute(Qt.WA_WState_Hidden, False) def float(self): """ Set the window state to be a toplevel floating window. """ self.hide() self.setAttribute(Qt.WA_Hover, True) flags = Qt.Tool | Qt.FramelessWindowHint self.setParent(self.manager().dock_area(), flags) self.layout().setContentsMargins(QMargins(5, 5, 5, 5)) self.setProperty('floating', True) self.setLinked(False) self.showLinkButton() repolish(self) self.topLevelChanged.emit(True) def unfloat(self): """ Set the window state to be non-floating window. """ self.hide() self.setAttribute(Qt.WA_Hover, False) self.setParent(self.manager().dock_area(), Qt.Widget) self.layout().setContentsMargins(QMargins(0, 0, 0, 0)) self.unsetCursor() self.setProperty('floating', False) self.setLinked(False) self.hideLinkButton() repolish(self) self.topLevelChanged.emit(False) def parentDockArea(self): """ Get the parent dock area of the container. Returns ------- result : QDockArea or None The nearest ancestor which is an instance of QDockArea, or None if no such ancestor exists. """ parent = self.parent() while parent is not None: if isinstance(parent, QDockArea): return parent parent = parent.parent() def parentDockTabWidget(self): """ Get the parent dock area of the container. Returns ------- result : QDockTabWidget or None The nearest ancestor which is an instance of QDockTabWidget, or None if no such ancestor exists. """ parent = self.parent() while parent is not None: if isinstance(parent, QDockTabWidget): return parent parent = parent.parent() def unplug(self): """ Unplug the container from its containing dock area. This method is invoked by the framework when appropriate. It should not need to be called by user code. Returns ------- result : bool True if the container was unplugged, False otherwise. """ dock_area = self.parentDockArea() if dock_area is None: return False # avoid a circular import from .layout_handling import unplug_container return unplug_container(dock_area, self) def untab(self, pos): """ Unplug the container from a tab control. This method is invoked by the QDockTabBar when the container should be torn out. It synthesizes the appropriate internal state so that the item can continue to be dock dragged. This method should not be called by user code. Parameters ---------- pos : QPoint The global mouse position. Returns ------- result : bool True on success, False otherwise. """ if not self.unplug(): return state = self.frame_state state.mouse_title = True state.dragging = True self.float() self.raiseFrame() title_bar = self.dockItem().titleBarWidget() title_pos = QPoint(title_bar.width() / 2, title_bar.height() / 2) margins = self.layout().contentsMargins() offset = QPoint(margins.left(), margins.top()) state.press_pos = title_bar.mapTo(self, title_pos) + offset self.move(pos - state.press_pos) self.show() self.grabMouse() self.activateWindow() self.raise_() #-------------------------------------------------------------------------- # Event Handlers #-------------------------------------------------------------------------- def eventFilter(self, obj, event): """ Filter the events for the dock item. This filter will proxy out the mouse events for the dock item. This event filter will only be activated when the dock item is set to maximzed mode. """ if obj is not self._dock_item: return False if event.type() == QEvent.MouseButtonPress: return self.filteredMousePressEvent(event) elif event.type() == QEvent.MouseMove: return self.filteredMouseMoveEvent(event) elif event.type() == QEvent.MouseButtonRelease: return self.filteredMouseReleaseEvent(event) return False def filteredMousePressEvent(self, event): """ Handle the filtered mouse press event for the dock item. """ bar = self.dockItem().titleBarWidget() if bar.isVisible() and bar.geometry().contains(event.pos()): self.frame_state.mouse_title = True return self.titleBarMousePressEvent(event) return False def filteredMouseMoveEvent(self, event): """ Handle the filtered mouse move event for the dock item. """ if self.frame_state.mouse_title: return self.titleBarMouseMoveEvent(event) return False def filteredMouseReleaseEvent(self, event): """ Handle the filtered mouse release event for the dock item. """ if self.frame_state.mouse_title: self.frame_state.mouse_title = False return self.titleBarMouseReleaseEvent(event) return False def closeEvent(self, event): """ Handle the close event for the dock container. """ self.manager().close_container(self, event) def titleBarMousePressEvent(self, event): """ Handle a mouse press event on the title bar. Returns ------- result : bool True if the event is handled, False otherwise. """ if event.button() == Qt.LeftButton: state = self.frame_state if state.press_pos is None: state.press_pos = event.pos() return True return False def titleBarMouseMoveEvent(self, event): """ Handle a mouse move event on the title bar. Returns ------- result : bool True if the event is handled, False otherwise. """ state = self.frame_state if state.press_pos is None: return False # If dragging and floating, move the container's position and # notify the manager of that the container was mouse moved. If # the container is maximized, it is first restored before. global_pos = event.globalPos() if state.dragging: if self.isWindow(): target_pos = global_pos - state.press_pos self.manager().drag_move_frame(self, target_pos, global_pos) return True # Ensure the drag has crossed the app drag threshold. dist = (event.pos() - state.press_pos).manhattanLength() if dist <= QApplication.startDragDistance(): return True # If the container is already floating, ensure that it is shown # normal size. The next move event will move the window. state.dragging = True if self.isWindow(): if self.isMaximized(): coeff = state.press_pos.x() / float(self.width()) self.showNormal() state.press_pos = _computePressPos(self, coeff) return True # Restore a maximized dock item before unplugging. if state.item_is_maximized: bar = self.dockItem().titleBarWidget() coeff = state.press_pos.x() / float(bar.width()) self.showNormal() state.press_pos = _computePressPos(self, coeff) # Unplug the container from the layout before floating so # that layout widgets can clean themselves up when empty. if not self.unplug(): return False # Make the container a toplevel frame, update it's Z-order, # and grab the mouse to continue processing drag events. self.float() self.raiseFrame() margins = self.layout().contentsMargins() state.press_pos += QPoint(0, margins.top()) self.move(global_pos - state.press_pos) self.show() self.grabMouse() self.activateWindow() self.raise_() return True def titleBarMouseReleaseEvent(self, event): """ Handle a mouse release event on the title bar. Returns ------- result : bool True if the event is handled, False otherwise. """ if event.button() == Qt.LeftButton: state = self.frame_state if state.press_pos is not None: self.releaseMouse() if self.isWindow(): self.manager().drag_release_frame(self, event.globalPos()) state.dragging = False state.press_pos = None return True return False
[ "sccolbert@gmail.com" ]
sccolbert@gmail.com
4d5cf3b281253a0ff8110f76cc5142cb3cf4c837
4c6c2a8257c12c0b1d4aff84089c9ee33823acc8
/ex041.py
6f93e0ea1ee9e222119b058cdd05faaa6129b03f
[]
no_license
AilanPaula/Curso_em_video_Python3
ab69295424b327e42690196a5d710e25d7846086
8fbe2964b232969c493438997d18762d7f89ebc0
refs/heads/master
2020-06-26T05:20:30.001036
2019-08-05T13:25:42
2019-08-05T13:25:42
199,545,008
0
0
null
null
null
null
UTF-8
Python
false
false
482
py
''' Crie um programa que leia duas notas de um aluno e calcule sua média, mostrando uma mensagem no final, de acordo com a média atingida: -> Média abaixo de 5.0: REPROVADO -> Média entre 5.0 e 6.9: RECUPERAÇÃO -> Média 7.0 ou superior: APROVADO ''' nota1 = float(input('Nota 1: ')) nota2 = float(input('Nota 2: ')) media = (nota1 + nota2) / 2 if media >= 7.0: print('Aprovado') elif media >= 5.0 and media < 7.0: print('Recuperação') else: print('Reprovado')
[ "ailanpaula@hotmail.com" ]
ailanpaula@hotmail.com
2b0925270cc4865750383848e14aa68b739cf6fb
d252c3496a4dc715df1f5f1d0db4e4228811d29a
/caching/CacheInstance.py
1c7f2ad0b277da8a22d9e70b83f402ab7709ba20
[]
no_license
aredev/quic-scapy
df0ca35d937ea877ddbf2894c03d9c4b635da1e7
3df8e8b9d2db7ba9ebf75f7fdf2029c855bb432f
refs/heads/master
2021-04-06T09:35:03.685639
2018-06-26T17:40:41
2018-06-26T17:40:41
125,071,319
11
0
null
null
null
null
UTF-8
Python
false
false
934
py
import peewee from caching.SessionModel import SessionModel class CacheInstance: """ """ __instance = None __db = None @staticmethod def get_instance(): if CacheInstance.__instance is None: return CacheInstance() else: return CacheInstance.__instance def __init__(self): if CacheInstance.__instance is not None: raise Exception("Singleton bla") else: self.__db = peewee.SqliteDatabase('quic_scapy.db') self.__db.connect() self.__db.drop_tables([SessionModel]) self.__db.create_tables([SessionModel]) def add_session_model(self, model: SessionModel): model.save() def remove_session_model(self): self.__db.drop_tables([SessionModel]) self.__db.create_tables([SessionModel]) def retrieve_current_session(self): return SessionModel.select()
[ "appierasool@gmail.com" ]
appierasool@gmail.com
dfcb7dfeeb3c6b1f35413b7208110d79c55af59a
a05fbee56f08f09a839ae9e9c4d909dfac0f58e2
/crossdomain/read_ud.py
6cb6bccd91977f66c1a9b7ce74125649afd4ba85
[ "MIT" ]
permissive
INK-USC/ConNet
b67d7c1d9d0379e8a3205273ee428cb0aa4c9179
adb299f160556004561df302c19578200bd3835b
refs/heads/master
2020-08-04T15:09:09.969997
2020-04-14T05:00:33
2020-04-14T05:00:33
212,179,312
12
2
null
null
null
null
UTF-8
Python
false
false
5,791
py
from pathlib import Path import pickle import sys, os import argparse from collections import defaultdict, Counter, OrderedDict import logging as log import numpy as np import random import math, re import time import copy import torch import torch.nn as nn torch.manual_seed(123) np.random.seed(123) random.seed(123) # read glove embeddings def read_emb(emb_file, word_vocab): with open(emb_file, 'r', encoding="utf-8") as f: emb_list = [] for x in f: xx = x.strip().split(' ') if xx[0] in word_vocab: emb_list.append((xx[0], [float(r) for r in xx[1:]])) word_emb = np.array([r[1] for r in emb_list]) # add special tokens word_emb = np.vstack((np.zeros((1, word_emb.shape[1])), word_emb)) word_emb = np.vstack((np.mean(word_emb, 0), word_emb)) curr_word_vocab = ['<unk>', '<pad>'] + [r[0] for r in emb_list] word2idx = OrderedDict((curr_word_vocab[i], i) for i in range(len(curr_word_vocab))) return (word_emb, word2idx) def read_gum(data_file): data, curr_data = [], [] curr_doc_id, curr_genre, curr_sent_id = None, None, None with open(data_file, 'r') as f: i = 0 for line in f: if line.startswith('# newdoc id = '): curr_doc_id = line.strip().split('# newdoc id = ')[1] _, curr_genre, detail = curr_doc_id.split('_') elif line.startswith('# sent_id = '): curr_sent_id = line.strip().split('# sent_id = ')[1] elif line == '\n': data.append({'data_id': i, 'doc_id': curr_doc_id, 'sent_id': curr_sent_id, 'genre': curr_genre, \ 'words': [r[0] for r in curr_data], 'pos_tags': [r[1] for r in curr_data]}) curr_data = [] i += 1 elif line[0] != '#': id, form, lemma, upostag, xpostag, feats, head, deprel, deps, misc = line.strip().split('\t') curr_data.append([form, upostag]) return data def char_feats(words, char2idx): char_idx, char_boundaries, curr_char_boundary = [], [], [] posit = 0 for i in range(len(words)): if i != 0: char_idx.append(char2idx['<dlm>']) posit += 1 curr_char_boundary.append(posit) for c in words[i]: char_idx.append(char2idx[c.lower()] if c.lower() in char2idx else char2idx['<unk>']) posit += 1 curr_char_boundary.append(posit-1) char_boundaries.append(curr_char_boundary) curr_char_boundary = [] return char_idx, char_boundaries def create_feats(data, char2idx, word2idx, task2idx, label2idx): for i in range(len(data)): d = data[i] data_id = d['data_id'] task = task2idx[d['genre']] words = d['words'] char_idx, char_boundaries = char_feats(words, char2idx) label = [label2idx[r] for r in d['pos_tags']] feats = {'data_id': data_id, 'task': task, 'chars': char_idx, \ 'char_boundaries': char_boundaries, 'words': words, 'label': label} data[i] = {'ref': d, 'feats': feats} if __name__ == '__main__': p = argparse.ArgumentParser() p.add_argument('-data_dir', help='path to data directory') p.add_argument('-word_emb_dir', help='path to word embedding files') p.add_argument('-save_data', help='path to save processed data') args = p.parse_args() print(args) # For debugging # pickle.dump(args, open('pickle_breakpoints/read_ud.p', 'wb')) # assert False # args = pickle.load(open('pickle_breakpoints/read_ud.p', 'rb')) train_data = read_gum(args.data_dir + '/en_gum-ud-train.conllu') dev_data = read_gum(args.data_dir + '/en_gum-ud-dev.conllu') test_data = read_gum(args.data_dir + '/en_gum-ud-test.conllu') all_words = [r.lower() for rr in train_data+dev_data+test_data for r in rr['words']] word_vocab = list(set(all_words)) for word_emb_file in ['glove.6B.50d.txt', 'glove.6B.100d.txt', 'glove.6B.200d.txt', 'glove.6B.300d.txt']: word_emb, word2idx = read_emb(args.word_emb_dir+'/' + word_emb_file, word_vocab) pickle.dump({'word_emb': word_emb, 'word2idx': word2idx}, open(args.save_data + '/' + word_emb_file + '.p', 'wb')) # leave 10% chars as OOV train_chars = [r for r in ''.join([r.lower() for rr in train_data for r in rr['words']])] train_chars = [r[0] for r in sorted(Counter(train_chars).items(), key=lambda x:x[1], reverse=True)] train_chars = ['<unk>', '<pad>', '<dlm>'] + train_chars[:int(len(train_chars)*0.9)] # dlm is word delimiter char2idx = {y:x for x,y in enumerate(train_chars)} for char_emb_dim in [30,50,100,200]: char_emb = nn.Embedding(len(char2idx), char_emb_dim, padding_idx=char2idx['<pad>']) char_emb = char_emb.weight.detach().numpy() pickle.dump({'char_emb': char_emb, 'char2idx': char2idx}, open(args.save_data + '/random_char_emb_' + str(char_emb_dim) + '.p', 'wb')) all_labels = ['<start>', '<pad>'] + list(set([r for rr in test_data for r in rr['pos_tags']])) label2idx = {k:v for v,k in enumerate(all_labels)} all_tasks = list(set([r['genre'] for r in test_data])) # here "task" means genre task2idx = {k:v for v,k in enumerate(all_tasks)} pickle.dump({'label2idx': label2idx, 'task2idx': task2idx}, open(args.save_data+'/common.p', 'wb')) create_feats(train_data, char2idx, word2idx, task2idx, label2idx) create_feats(dev_data, char2idx, word2idx, task2idx, label2idx) create_feats(test_data, char2idx, word2idx, task2idx, label2idx) pickle.dump({'train_data': train_data, 'dev_data': dev_data, 'test_data': test_data}, open(args.save_data+'/data.p', 'wb'))
[ "huan183@usc.edu" ]
huan183@usc.edu
bd44b5d8494ad55030d5d025e1f24e94f5c0e5ca
20125d3579eff08bd4e28f4c4ba914a185d3f9ea
/collision_map.py
75999d7a3ee739632c2f681265c057f71474b2a9
[ "MIT" ]
permissive
incherre/slam-bot
9e3b519a1197fd288f12a7b92864133eaa248bfa
b9835ba42ba1c06e5f68d73bdc9791e98ccfa632
refs/heads/master
2022-06-16T15:04:05.082016
2022-06-05T18:40:06
2022-06-05T18:40:06
137,243,316
0
0
null
null
null
null
UTF-8
Python
false
false
13,524
py
'''A map to record possible obstacles.''' from math import sin, cos, inf, sqrt REPR_VERSION_STRING = "v1" class MapLocation: '''A location of the map that stores various counts.''' def __init__(self): # The number of times an agent has stepped in this location, strong evidence it is clear. self.stepped_count = 0 # The number of times a scan beam has passed through this location, weak evidence it is clear. self.missed_count = 0 # The number of times a scan beam has terminated in this location, evidence of an obstacle. self.hit_count = 0 def __eq__(self, other): return isinstance(other, MapLocation) and \ self.stepped_count == other.stepped_count and \ self.missed_count == other.missed_count and \ self.hit_count == other.hit_count def get_discrete_coord(scale, coord): shifted = coord + (scale / 2) return int(shifted - shifted % scale) def v_dot(v1, v2): return v1[0] * v2[0] + v1[1] * v2[1] def v_diff(v1, v2): return (v1[0] - v2[0], v1[1] - v2[1]) class CollisionMap: '''A map which records possible obstacles given a sensor reading.''' def __init__(self, collision_map_scale=5, collision_map_max_dist=100, **kwargs): assert(isinstance(collision_map_scale, int)) assert(collision_map_scale > 0) self.scale = collision_map_scale assert(isinstance(collision_map_max_dist, int)) assert(collision_map_max_dist > 0) self.max_dist = collision_map_max_dist self.rectangle_tolerance = collision_map_scale / 1000 self.map = {} @classmethod def from_string(cls, serialized_map): '''Creates a new map from a string generated by __repr__.''' new_map = None for line_number, line in enumerate(serialized_map.split("\n")): if line_number == 0: assert(line == REPR_VERSION_STRING) elif line_number == 1: assert(line == "scale,max_dist") elif line_number == 2: [scale, max_dist] = line.split(",") new_map = cls(collision_map_scale=int(scale), collision_map_max_dist=int(max_dist)) elif line_number == 3: assert(line == "x,y,stepped_count,missed_count,hit_count") elif line_number > 3: assert(new_map is not None) [x, y, stepped_count, missed_count, hit_count] = line.split(",") line_location = new_map.get_location(int(x), int(y), create = True) line_location.stepped_count = int(stepped_count) line_location.missed_count = int(missed_count) line_location.hit_count = int(hit_count) return new_map def get_key(self, x, y): '''Returns the key into the internal map corresponding to the provided point.''' shifted_x = x + (self.scale / 2) shifted_y = y + (self.scale / 2) return (int(shifted_x - shifted_x % self.scale), int(shifted_y - shifted_y % self.scale)) def get_location(self, x, y, create = False): '''Retrieves the obstacle information for the given location.''' key = self.get_key(x, y) if not key in self.map and not create: return MapLocation() if not key in self.map and create: self.map[key] = MapLocation() return self.map[key] def get_neighbor_keys(self, x, y): '''Get the keys for all 8 adjacent neighbor cells.''' key_x, key_y = self.get_key(x, y) neighbors = [] for dx in [-self.scale, 0, self.scale]: for dy in [-self.scale, 0, self.scale]: if dx == 0 and dy == 0: continue neighbors.append((key_x + dx, key_y + dy)) return neighbors def record_observations(self, x, y, theta, observations): '''Record the appropriate counts for each of the given (delta_theta, distance) pairs based out of the provided current location.''' current_location_key = self.get_key(x, y) self.__get_or_insert_location(current_location_key).stepped_count += 1 for delta_theta, distance in observations: self.__add_line(x, y, theta + delta_theta, distance, current_location_key) def get_locations_within_rectangle(self, p1, p2, p3, p4): '''Returns the set of all observed locations partially or fully inside the given rectangle.''' assert abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]) > self.rectangle_tolerance, "Provided rectangle points are equal (or close enough)." assert abs(p1[0] - p3[0]) + abs(p1[1] - p3[1]) > self.rectangle_tolerance, "Provided rectangle points are equal (or close enough)." assert abs(p1[0] - p4[0]) + abs(p1[1] - p4[1]) > self.rectangle_tolerance, "Provided rectangle points are equal (or close enough)." assert abs(p2[0] - p3[0]) + abs(p2[1] - p3[1]) > self.rectangle_tolerance, "Provided rectangle points are equal (or close enough)." assert abs(p2[0] - p4[0]) + abs(p2[1] - p4[1]) > self.rectangle_tolerance, "Provided rectangle points are equal (or close enough)." assert abs(p3[0] - p4[0]) + abs(p3[1] - p4[1]) > self.rectangle_tolerance, "Provided rectangle points are equal (or close enough)." center_x = (p1[0] + p2[0] + p3[0] + p4[0]) / 4 center_y = (p1[1] + p2[1] + p3[1] + p4[1]) / 4 center_dist = (center_x - p1[0]) ** 2 + (center_y - p1[1]) ** 2 for px, py in [p2, p3, p4]: p_dist = (center_x - px) ** 2 + (center_y - py) ** 2 assert abs(p_dist - center_dist) < self.rectangle_tolerance, "Provided points do not make a rectangle." edge12_dist = v_dot(v_diff(p1, p2), v_diff(p1, p2)) diag13_dist = v_dot(v_diff(p1, p3), v_diff(p1, p3)) assert edge12_dist < diag13_dist, "Provided rectangle points are incorrectly ordered." # Precompute some the rectangle's axes and dimensions. rectangle_axis_1 = v_diff(p1, p2) rectangle_axis_1_norm = sqrt(v_dot(rectangle_axis_1, rectangle_axis_1)) rectangle_axis_1_unit = (rectangle_axis_1[0] / rectangle_axis_1_norm, rectangle_axis_1[1] / rectangle_axis_1_norm) min_rectangle_axis_1 = min(v_dot(p1, rectangle_axis_1_unit), v_dot(p2, rectangle_axis_1_unit)) max_rectangle_axis_1 = max(v_dot(p1, rectangle_axis_1_unit), v_dot(p2, rectangle_axis_1_unit)) rectangle_axis_2 = v_diff(p1, p4) rectangle_axis_2_norm = sqrt(v_dot(rectangle_axis_2, rectangle_axis_2)) rectangle_axis_2_unit = (rectangle_axis_2[0] / rectangle_axis_2_norm, rectangle_axis_2[1] / rectangle_axis_2_norm) min_rectangle_axis_2 = min(v_dot(p1, rectangle_axis_2_unit), v_dot(p4, rectangle_axis_2_unit)) max_rectangle_axis_2 = max(v_dot(p1, rectangle_axis_2_unit), v_dot(p4, rectangle_axis_2_unit)) # Get the grid-aligned bounding box to check. min_x, min_y = self.get_key(min(p1[0], p2[0], p3[0], p4[0]), min(p1[1], p2[1], p3[1], p4[1])) max_x, max_y = self.get_key(max(p1[0], p2[0], p3[0], p4[0]), max(p1[1], p2[1], p3[1], p4[1])) results = {} location_count = 0 current_x = min_x current_y = min_y while current_y <= max_y: location_p1 = (current_x - (self.scale / 2), current_y - (self.scale / 2)) location_p2 = (current_x + (self.scale / 2), current_y - (self.scale / 2)) location_p3 = (current_x - (self.scale / 2), current_y + (self.scale / 2)) location_p4 = (current_x + (self.scale / 2), current_y + (self.scale / 2)) # Using the Separating Axis Theorem to check for overlap between the # rectangle and the location domain. Though I skip projecting the # rectangle onto the location's axes, since those checks are covered # by the loop invariants. min_location_axis_1 = min(v_dot(location_p1, rectangle_axis_1_unit), v_dot(location_p2, rectangle_axis_1_unit), v_dot(location_p3, rectangle_axis_1_unit), v_dot(location_p4, rectangle_axis_1_unit)) max_location_axis_1 = max(v_dot(location_p1, rectangle_axis_1_unit), v_dot(location_p2, rectangle_axis_1_unit), v_dot(location_p3, rectangle_axis_1_unit), v_dot(location_p4, rectangle_axis_1_unit)) if min_location_axis_1 > max_rectangle_axis_1 or min_rectangle_axis_1 > max_location_axis_1: # This location is not inside the rectangle. current_x += self.scale if current_x > max_x: current_x = min_x current_y += self.scale continue min_location_axis_2 = min(v_dot(location_p1, rectangle_axis_2_unit), v_dot(location_p2, rectangle_axis_2_unit), v_dot(location_p3, rectangle_axis_2_unit), v_dot(location_p4, rectangle_axis_2_unit)) max_location_axis_2 = max(v_dot(location_p1, rectangle_axis_2_unit), v_dot(location_p2, rectangle_axis_2_unit), v_dot(location_p3, rectangle_axis_2_unit), v_dot(location_p4, rectangle_axis_2_unit)) if min_location_axis_2 > max_rectangle_axis_2 or min_rectangle_axis_2 > max_location_axis_2: # This location is not inside the rectangle. current_x += self.scale if current_x > max_x: current_x = min_x current_y += self.scale continue location_count += 1 if not (current_x, current_y) in self.map: # This location has not been observed. current_x += self.scale if current_x > max_x: current_x = min_x current_y += self.scale continue results[(current_x, current_y)] = self.get_location(current_x, current_y) current_x += self.scale if current_x > max_x: current_x = min_x current_y += self.scale return results, location_count def __add_line(self, start_x, start_y, theta, distance, current_location_key): '''Record all spots along the given line as passed through, and records the final spot as hit.''' start_point_key = self.get_key(start_x, start_y) end_x = start_x + min(distance, self.max_dist) * cos(theta) end_y = start_y + min(distance, self.max_dist) * sin(theta) end_point_key = self.get_key(end_x, end_y) if distance <= self.max_dist: self.__get_or_insert_location(end_point_key).hit_count += 1 x, y = start_point_key current_distance = sqrt((end_x - x) ** 2 + (end_y - y) ** 2) a = -sin(theta) b = cos(theta) c = (start_x * sin(theta)) - (start_y * cos(theta)) while current_distance <= self.max_dist: if self.get_key(x, y) != start_point_key: # Don't record the starting point as passed through, # since it will be recorded as stepped in. self.get_location(x, y, create = True).missed_count += 1 if (x, y) in self.get_neighbor_keys(end_point_key[0], end_point_key[1]): break next_x = None next_y = None next_error = inf for option_x, option_y in self.get_neighbor_keys(x, y): option_dist = sqrt((end_x - option_x) ** 2 + (end_y - option_y) ** 2) if option_dist >= current_distance: # Don't move away from the target! continue option_error = abs((a * option_x) + (b * option_y) + c) / sqrt(a ** 2 + b ** 2) if option_error < next_error: next_x = option_x next_y = option_y next_error = option_error if next_x is None or next_y is None: break x = next_x y = next_y current_distance = sqrt((end_x - x) ** 2 + (end_y - y) ** 2) def __get_or_insert_location(self, key): '''Retrieves the obstacle information for the given location, but will insert a new location into the map if it is missing.''' if not key in self.map: self.map[key] = MapLocation() return self.map[key] def __repr__(self): repr_str = REPR_VERSION_STRING + "\n" repr_str += "\n".join(["scale,max_dist", ",".join([str(self.scale), str(self.max_dist)]), "x,y,stepped_count,missed_count,hit_count"] + [",".join( [str(x), str(y), str(value.stepped_count), str(value.missed_count), str(value.hit_count)] ) for [x, y], value in self.map.items()]) return repr_str
[ "incherre2526@gmail.com" ]
incherre2526@gmail.com
77a35dc40a9073587aaadf01130767449aed2a7e
6f6b5f86080d8e5b9895c13f60be6c30f1fa516d
/accounts/urls.py
0a8bfbcc9f1daf931f70f3fdd2f2707de9e256bc
[]
no_license
SurajT22/carzone-project
4565c0be6295f89259670006b43549f87c42a0cc
08186f41d84b952321a230a2966fa8616991e440
refs/heads/main
2023-05-12T08:58:23.707969
2023-05-08T15:11:37
2023-05-08T15:11:37
362,905,594
0
0
null
2023-05-06T13:00:53
2021-04-29T18:06:15
Python
UTF-8
Python
false
false
275
py
from django.urls import path from .import views urlpatterns = [ path('login', views.login,name='login'), path('register', views.register, name='register'), path('logout', views.logout, name='logout'), path('dashboard', views.dashboard, name='dashboard'), ]
[ "rapid.suraj@gmail.com" ]
rapid.suraj@gmail.com
bd112b6b91db0e8519d273c4522bb251c13e67ed
b6b0196d11e1c7a4dd36d41c255285e751ec1a6f
/Python/Delete occurrences of an element if it occurs more than n times/solution.py
98eb9d44699dad244bbc5001e6a4253772644100
[]
no_license
tejanke/Codewars
967abb17babe7540bafb3880c647516d7f3c6a34
79ae819321e2f10a7d4c8d2b3aa1d2dad1422f30
refs/heads/main
2023-03-12T23:02:04.983427
2021-03-01T23:21:43
2021-03-01T23:21:43
313,048,975
0
0
null
null
null
null
UTF-8
Python
false
false
227
py
def delete_nth(order,max_e): result = [] for o in order: if o not in result: result.append(o) else: if result.count(o) < max_e: result.append(o) return result
[ "noreply@github.com" ]
noreply@github.com
dbe0a5a91d774e8c317b43293a42fde45b272cee
e5b8a5d93989dd53933c5cd417afa8b2a39ad307
/ultracart/models/oauth_token_response.py
3c0fa3d282238a67a49514ccec2bfe343dd0916b
[ "Apache-2.0" ]
permissive
gstingy/uc_python_api
f3586bfce9c962af2e8c1bc266ff25e0f1971278
9a0bd3f6e63f616586681518e44fe37c6bae2bba
refs/heads/master
2020-03-28T11:13:22.537641
2018-09-10T17:07:59
2018-09-10T17:07:59
148,190,066
0
0
null
null
null
null
UTF-8
Python
false
false
8,949
py
# coding: utf-8 """ UltraCart Rest API V2 UltraCart REST API Version 2 OpenAPI spec version: 2.0.0 Contact: support@ultracart.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class OauthTokenResponse(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'access_token': 'str', 'error': 'str', 'error_description': 'str', 'error_uri': 'str', 'expires_in': 'str', 'refresh_token': 'str', 'scope': 'str', 'token_type': 'str' } attribute_map = { 'access_token': 'access_token', 'error': 'error', 'error_description': 'error_description', 'error_uri': 'error_uri', 'expires_in': 'expires_in', 'refresh_token': 'refresh_token', 'scope': 'scope', 'token_type': 'token_type' } def __init__(self, access_token=None, error=None, error_description=None, error_uri=None, expires_in=None, refresh_token=None, scope=None, token_type=None): """ OauthTokenResponse - a model defined in Swagger """ self._access_token = None self._error = None self._error_description = None self._error_uri = None self._expires_in = None self._refresh_token = None self._scope = None self._token_type = None self.discriminator = None if access_token is not None: self.access_token = access_token if error is not None: self.error = error if error_description is not None: self.error_description = error_description if error_uri is not None: self.error_uri = error_uri if expires_in is not None: self.expires_in = expires_in if refresh_token is not None: self.refresh_token = refresh_token if scope is not None: self.scope = scope if token_type is not None: self.token_type = token_type @property def access_token(self): """ Gets the access_token of this OauthTokenResponse. Access token to use in OAuth authenticated API call :return: The access_token of this OauthTokenResponse. :rtype: str """ return self._access_token @access_token.setter def access_token(self, access_token): """ Sets the access_token of this OauthTokenResponse. Access token to use in OAuth authenticated API call :param access_token: The access_token of this OauthTokenResponse. :type: str """ self._access_token = access_token @property def error(self): """ Gets the error of this OauthTokenResponse. :return: The error of this OauthTokenResponse. :rtype: str """ return self._error @error.setter def error(self, error): """ Sets the error of this OauthTokenResponse. :param error: The error of this OauthTokenResponse. :type: str """ self._error = error @property def error_description(self): """ Gets the error_description of this OauthTokenResponse. :return: The error_description of this OauthTokenResponse. :rtype: str """ return self._error_description @error_description.setter def error_description(self, error_description): """ Sets the error_description of this OauthTokenResponse. :param error_description: The error_description of this OauthTokenResponse. :type: str """ self._error_description = error_description @property def error_uri(self): """ Gets the error_uri of this OauthTokenResponse. :return: The error_uri of this OauthTokenResponse. :rtype: str """ return self._error_uri @error_uri.setter def error_uri(self, error_uri): """ Sets the error_uri of this OauthTokenResponse. :param error_uri: The error_uri of this OauthTokenResponse. :type: str """ self._error_uri = error_uri @property def expires_in(self): """ Gets the expires_in of this OauthTokenResponse. The number of seconds since issuance when the access token will expire and need to be refreshed using the refresh token :return: The expires_in of this OauthTokenResponse. :rtype: str """ return self._expires_in @expires_in.setter def expires_in(self, expires_in): """ Sets the expires_in of this OauthTokenResponse. The number of seconds since issuance when the access token will expire and need to be refreshed using the refresh token :param expires_in: The expires_in of this OauthTokenResponse. :type: str """ self._expires_in = expires_in @property def refresh_token(self): """ Gets the refresh_token of this OauthTokenResponse. The refresh token that should be used to fetch a new access token when the expiration occurs :return: The refresh_token of this OauthTokenResponse. :rtype: str """ return self._refresh_token @refresh_token.setter def refresh_token(self, refresh_token): """ Sets the refresh_token of this OauthTokenResponse. The refresh token that should be used to fetch a new access token when the expiration occurs :param refresh_token: The refresh_token of this OauthTokenResponse. :type: str """ self._refresh_token = refresh_token @property def scope(self): """ Gets the scope of this OauthTokenResponse. The scope of permissions associated with teh access token :return: The scope of this OauthTokenResponse. :rtype: str """ return self._scope @scope.setter def scope(self, scope): """ Sets the scope of this OauthTokenResponse. The scope of permissions associated with teh access token :param scope: The scope of this OauthTokenResponse. :type: str """ self._scope = scope @property def token_type(self): """ Gets the token_type of this OauthTokenResponse. Type of token :return: The token_type of this OauthTokenResponse. :rtype: str """ return self._token_type @token_type.setter def token_type(self, token_type): """ Sets the token_type of this OauthTokenResponse. Type of token :param token_type: The token_type of this OauthTokenResponse. :type: str """ allowed_values = ["bearer"] if token_type not in allowed_values: raise ValueError( "Invalid value for `token_type` ({0}), must be one of {1}" .format(token_type, allowed_values) ) self._token_type = token_type def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ if not isinstance(other, OauthTokenResponse): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
[ "perry@ultracart.com" ]
perry@ultracart.com
3a8e593b81b23b2f274a801b086735a0e264183a
109fdd9d849376c31a0f0bd8c658c5fe5ae32fdb
/FunctionalTests/test_AddItemToCart.py
9cbf0771f9e3d5775c79a7053026e31ee4598d17
[]
no_license
jaggureddy/PythonSelenium
370e6a3e87a2559d77218992c092d3b2dcdf80bf
a44df0e446a591128e86a755e4bcc9a97aa8fe23
refs/heads/master
2022-12-03T06:58:28.365415
2020-08-22T02:17:57
2020-08-22T02:17:57
287,144,539
0
0
null
null
null
null
UTF-8
Python
false
false
2,028
py
from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait from time import sleep from Pages.CheckOutPage import CheckOutPage from Pages.Confirmpage import ConfirmPage from Pages.HomePage import HomePage from Utilities.BaseClass import BaseClass class TestAddItemToCart(BaseClass): def test_AddItemToCart(self): homePage = HomePage(self.driver) checkOutPage = CheckOutPage(self.driver) confirmPage = ConfirmPage(self.driver) # self.driver.find_element_by_xpath("//a[text()='Shop']").click() homePage.shopItems().click() # products = self.driver.find_elements_by_xpath("//div[@class='card h-100']") products = checkOutPage.getProducts() # for product in products: # name = product.find_element_by_xpath("div/h4/a").text # if name == "Blackberry": # product.find_element_by_xpath("div/button").click() products.click() self.driver.execute_script("window.scrollBy(0,-1500);") # self.driver.find_element_by_xpath("//a[contains(text(),'Checkout')]").click() checkOutPage.selectCheckout().click() sleep(10) # checkout = self.driver.find_element_by_xpath("//button[@class='btn btn-success']") checkout = confirmPage.selectCheckout() self.driver.execute_script("arguments[0].click();", checkout) sleep(10) # wait = WebDriverWait(self.driver, 10) # self.driver.get_screenshot_as_file('screen.png') # wait.until(expected_conditions.presence_of_element_located(By.ID, 'country')) self.verifyLinkPresence('ID', 'country') self.driver.find_element_by_id("country").send_keys("Ind") # wait.until(expected_conditions.presence_of_element_located(By.LINK_TEXT, "India")) self.verifyLinkPresence('LINKTEXT', 'India') self.driver.find_element_by_link_text('India').click() sleep(5)
[ "Jagadeesh6010@gmail.com" ]
Jagadeesh6010@gmail.com
ad41e857d0ed042e01c4bab91e33751edd6153d1
552ddf9821a195762985f032f507b0cd9172fcfb
/Using_Databases_with_Python_(py4e_Coursera)/Week_3/Tracks.py
6abc28b7dea993623653433ac1adbace59c54bb5
[]
no_license
rmahmadkhan/PythonForEverybody-py4e-Coursera
00d68e0d1ef017cf0badbb271944d097b5675a26
513dd2eb6608caa789bb4512231e525263f1ab1d
refs/heads/master
2022-04-19T22:37:48.999191
2020-04-21T17:59:24
2020-04-21T17:59:24
201,275,150
1
0
null
null
null
null
UTF-8
Python
false
false
3,776
py
# In this assignment you will parse an XML list of albums, artists, and # Genres and produce a properly normalized database using a Python program. # You can use this code as a starting point for your application: http://www.py4e.com/code3/tracks.zip. # The ZIP file contains the Library.xml file to be used for this assignment. # To grade this assignment, the program will run a query like this on your uploaded database and look for the data it expects to see: #SELECT Track.title, Artist.name, Album.title, Genre.name # FROM Track JOIN Genre JOIN Album JOIN Artist # ON Track.genre_id = Genre.ID and Track.album_id = Album.id # AND Album.artist_id = Artist.id # ORDER BY Artist.name LIMIT 3 # _________________________________________________________________ import xml.etree.ElementTree as ET import sqlite3 conn = sqlite3.connect('trackdb.sqlite') cur = conn.cursor() # Make some fresh tables using executescript() cur.executescript(''' DROP TABLE IF EXISTS Artist; DROP TABLE IF EXISTS Album; DROP TABLE IF EXISTS Track; CREATE TABLE Artist ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, name TEXT UNIQUE ); CREATE TABLE Genre ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, name TEXT UNIQUE ); CREATE TABLE Album ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, artist_id INTEGER, title TEXT UNIQUE ); CREATE TABLE Track ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, title TEXT UNIQUE, album_id INTEGER, genre_id INTEGER, len INTEGER, rating INTEGER, count INTEGER ); ''') fname = input('Enter file name: ') if ( len(fname) < 1 ) : fname = 'Library.xml' # <key>Track ID</key><integer>369</integer> # <key>Name</key><string>Another One Bites The Dust</string> # <key>Artist</key><string>Queen</string> def lookup(d, key): found = False for child in d: if found : return child.text if child.tag == 'key' and child.text == key : found = True return None stuff = ET.parse(fname) all = stuff.findall('dict/dict/dict') print('Dict count:', len(all)) for entry in all: if ( lookup(entry, 'Track ID') is None ) : continue name = lookup(entry, 'Name') artist = lookup(entry, 'Artist') album = lookup(entry, 'Album') #Added this genre = lookup(entry, 'Genre') count = lookup(entry, 'Play Count') rating = lookup(entry, 'Rating') length = lookup(entry, 'Total Time') # added genre here if name is None or artist is None or album is None or genre is None : continue print(name, artist, album, genre, count, rating, length) cur.execute('''INSERT OR IGNORE INTO Artist (name) VALUES ( ? )''', ( artist, ) ) cur.execute('SELECT id FROM Artist WHERE name = ? ', (artist, )) artist_id = cur.fetchone()[0] cur.execute('''INSERT OR IGNORE INTO Album (title, artist_id) VALUES ( ?, ? )''', ( album, artist_id ) ) cur.execute('SELECT id FROM Album WHERE title = ? ', (album, )) album_id = cur.fetchone()[0] #added genre table cur.execute('''INSERT OR IGNORE INTO Genre (name) VALUES ( ? )''', (genre, )) cur.execute('SELECT id FROM Genre WHERE name = ?', (genre, )) genre_id = cur.fetchone()[0] cur.execute('''INSERT OR REPLACE INTO Track (title, album_id, genre_id, len, rating, count) VALUES ( ?, ?, ?, ?, ?, ? )''', ( name, album_id, genre_id, length, rating, count ) ) cur.execute('''SELECT Track.title, Artist.name, Album.title, Genre.name FROM Track JOIN Genre JOIN Album JOIN Artist ON Track.genre_id = Genre.ID and Track.album_id = Album.id AND Album.artist_id = Artist.id ORDER BY Artist.name LIMIT 3''') conn.commit()
[ "noreply@github.com" ]
noreply@github.com
4c0ebc99422d109803628e1c5b84a2f0dac3ea31
7907b042b5c0dc96c387a3a9827e64f5ad2ec190
/booking/sync/payments.py
81b041623b75f886c70d49b6decdd6f3d7441a3d
[]
no_license
Stranger6667/testing-network
6dbfd6429bcd730f72aa857c4bc41e1150e59134
d8441ab29c125697f176be9fb4f40de739ab332e
refs/heads/master
2022-12-21T21:12:11.279830
2021-04-20T20:00:04
2021-04-20T20:09:08
160,372,537
0
0
null
2022-12-08T01:27:40
2018-12-04T14:45:04
Python
UTF-8
Python
false
false
450
py
from decimal import Decimal from . import exchange from ..models import db, Transaction def save_transaction(booking_id: int, amount: Decimal, currency: str): """We need to store EUR amount as well.""" amount_eur = exchange.to_eur(amount, currency) transaction = Transaction(booking_id=booking_id, amount=amount, currency=currency, amount_eur=amount_eur) db.session.add(transaction) db.session.commit() return transaction
[ "dmitry.dygalo@kiwi.com" ]
dmitry.dygalo@kiwi.com
a609eee87d2413308232d12e0b2a2feeb8ca9541
5b24e15d3c477c723f22e460cff345c8079c2559
/Main.py
6ca06d96284e4383cd03a27fd6c0928ea7206064
[]
no_license
mguthrie45/Sudoku-Solver
080bed6ed424d2e8d295ec8df9ea539a65258b93
00a19e9f4044a3d847246914158e01fbfe0e8fd9
refs/heads/master
2022-12-22T03:29:39.979530
2020-09-27T03:24:32
2020-09-27T03:24:32
288,836,765
0
0
null
null
null
null
UTF-8
Python
false
false
2,875
py
import pprint import time from Generator import generate_board pp = pprint.PrettyPrinter(depth=6) def missing_numbers(num_list): numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] for i in range(len(num_list)): for j in numbers: if num_list[i] == j: numbers.remove(j) return numbers class Grid(): board = generate_board() def __init__(self, rows, cols): self.rows = rows self.cols = cols self.model = None def column(self, j): array = [] for i in range(len(self.board)): array.append(self.board[i][j]) return array def cube(self, i, j): #returns a list of the indices the cube you are in. num_list = [] cube_coord = (i//3, j//3) #1, 1 would be a range i(3, 5) and j(3, 5) i_range = (cube_coord[0]*3, cube_coord[0]*3+2) j_range = (cube_coord[1]*3, cube_coord[1]*3+2) for i in range(i_range[0], i_range[1]+1): for j in range(j_range[0], j_range[1]+1): num_list.append(self.board[i][j]) return num_list def update(self, i, j, val): self.board[i][j] = val def solve(self, board): empty_coord = find_empty(self.board) if empty_coord is None: return True i, j = empty_coord for num in range(1, 10): if valid(i, j, num, self): self.update(i, j, num) if self.solve(self.board): return True self.update(i, j, 0) return False def __repr__(self): st = "--------------------------\n" for i in self.board: for j in i: st += str(j) st += " " st += "\n" return st + "--------------------------" __str__ = __repr__ def find_empty(board): for i in range(len(board)): for j in range(len(board[i])): if board[i][j] == 0: return (i, j) return None def missing_cube_numbers(i, j, grid): num_list = grid.cube(i, j) miss_n = missing_numbers(num_list) return miss_n def missing_col_numbers(j, grid): num_list = grid.column(j) miss_n = missing_numbers(num_list) return miss_n def missing_row_numbers(i, grid): num_list = grid.board[i] miss_n = missing_numbers(num_list) return miss_n def intersecting_missing(i, j, grid): row = missing_row_numbers(i, grid) col = missing_col_numbers(j, grid) box = missing_cube_numbers(i, j, grid) common = set(row).intersection(set(col), set(box)) return list(common) def valid(i, j, num, grid): if num in intersecting_missing(i, j, grid): return True return False ''' def main(): grid = Grid(9, 9) print(grid) grid.solve(grid.board) print(grid) main()'''
[ "mguthrie451@gmail.com" ]
mguthrie451@gmail.com
3091920acde66028b88c52eb008ed4d4557a0162
1806d42a4b34d4af586c04293bf993d849be6627
/2015/Day18/test_solution.py
3ad0aacd809221023f7505d854605c2357e40ead
[]
no_license
AlexHorch/AoC_Python
590ea0cee5fd814d48d7e0f378f6799e7c452522
ce519d059afbacfcb53052f06472ff4078b42c9e
refs/heads/master
2022-12-07T00:52:41.928077
2020-08-26T07:43:46
2020-08-26T07:43:46
282,877,690
0
0
null
null
null
null
UTF-8
Python
false
false
1,635
py
import unittest import solution examples = [""".#.#.# ...##. #....# ..#... #.#..# ####..""", """..##.. ..##.# ...##. ...... #..... #.##..""", """..###. ...... ..###. ...... .#.... .#....""", """...#.. ...... ...#.. ..##.. ...... ......""", """...... ...... ..##.. ..##.. ...... ......"""] class TestSolution(unittest.TestCase): def test_parse(self): self.assertListEqual([[0, 1, 0, 1, 0, 1], [0, 0, 0, 1, 1, 0], [1, 0, 0, 0, 0, 1], [ 0, 0, 1, 0, 0, 0], [1, 0, 1, 0, 0, 1], [1, 1, 1, 1, 0, 0]], solution.parse_input(examples[0])) def test_state(self): f = solution.parse_input(examples[0]) self.assertEqual(0, solution.state(f, 0, 0)) self.assertEqual(0, solution.state(f, -1, 0)) self.assertEqual(0, solution.state(f, 0, -1)) self.assertEqual(0, solution.state(f, 6, 0)) self.assertEqual(0, solution.state(f, 0, 6)) self.assertEqual(1, solution.state(f, 0, 1)) def test_step_1(self): self.assertListEqual(solution.parse_input( examples[1]), solution.step(solution.parse_input(examples[0]))) def test_step_2(self): self.assertListEqual(solution.parse_input( examples[2]), solution.step(solution.parse_input(examples[1]))) def test_step_3(self): self.assertListEqual(solution.parse_input( examples[3]), solution.step(solution.parse_input(examples[2]))) def test_step_4(self): self.assertListEqual(solution.parse_input( examples[4]), solution.step(solution.parse_input(examples[3]))) if __name__ == '__main__': unittest.main()
[ "alexander@Alexanders-MacBook-Air.local" ]
alexander@Alexanders-MacBook-Air.local
f78c5a609bc06e6f4e623960f93838db21432089
eccfdf2975c0b97f744f208701c2019d38e2235a
/0x05-python-exceptions/0-safe_print_list.py
cdc1d239f1700edd1cb8bcf68b444d20529d047f
[]
no_license
valerienierenberg/holbertonschool-higher_level_programming
cefde34fcc678eabbcb84777cd56c1dcdc927a3f
d309df4ebf2b0aa611f9e65208b54719abae1ade
refs/heads/main
2023-04-20T06:33:55.658256
2021-05-13T13:35:29
2021-05-13T13:35:29
319,346,543
0
0
null
null
null
null
UTF-8
Python
false
false
744
py
#!/usr/bin/python3 def safe_print_list(my_list=[], x=0): a = 0 for y in range(x): try: print("{}".format(my_list[y]), end="") a += 1 except IndexError: break print("") return(a) # --gives correct output-- # def safe_print_list(my_list=[], x=0): # try: # for x in my_list[:x]: # print("{}".format(my_list[x - 1]), end="") # print() # except IndexError: # print() # finally: # return x # # Function that prints x elements of a list # a = counter variable to keep count correct, will be returned # for loop iterates through list to index x # print value of each element # add to count only if index doesn't exceed length of list
[ "valerie.nierenberg@gmail.com" ]
valerie.nierenberg@gmail.com
cfb7d656e58c4a233384f41bdd7246af27c42da1
ec476ad50f70ea9c1fd796faf92e634efb877af0
/venv/Lib/site-packages/dash_html_components/Data.py
572fcdf800596cfa007669e138f837270b87f131
[]
no_license
Mubeen31/Arduino-Sensor-data-Real-time-temperature-and-humidity-data-in-python-by-plotly-dash
e915cc9cfae5fdba324c57dd7bf6ad2440926ba7
2a80d1512198ea4e8e074ed437f35ac61920bb5c
refs/heads/main
2023-07-13T12:20:13.802937
2021-08-20T21:09:15
2021-08-20T21:09:15
398,258,681
2
0
null
null
null
null
UTF-8
Python
false
false
5,027
py
# AUTO GENERATED FILE - DO NOT EDIT from dash.development.base_component import Component, _explicitize_args class Data(Component): """A Data component. Data is a wrapper for the <data> HTML5 element. For detailed attribute info see: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/data Keyword arguments: - children (a list of or a singular dash component, string or number; optional): The children of this component. - id (string; optional): The ID of this component, used to identify dash components in callbacks. The ID needs to be unique across all of the components in an app. - accessKey (string; optional): Keyboard shortcut to activate or add focus to the element. - aria-* (string; optional): A wildcard aria attribute. - className (string; optional): Often used with CSS to style elements with common properties. - contentEditable (string; optional): Indicates whether the element's content is editable. - contextMenu (string; optional): Defines the ID of a <menu> element which will serve as the element's context menu. - data-* (string; optional): A wildcard data attribute. - dir (string; optional): Defines the text direction. Allowed values are ltr (Left-To-Right) or rtl (Right-To-Left). - draggable (string; optional): Defines whether the element can be dragged. - hidden (a value equal to: 'hidden', 'HIDDEN' | boolean; optional): Prevents rendering of given element, while keeping child elements, e.g. script elements, active. - key (string; optional): A unique identifier for the component, used to improve performance by React.js while rendering components See https://reactjs.org/docs/lists-and-keys.html for more info. - lang (string; optional): Defines the language used in the element. - loading_state (dict; optional): Object that holds the loading state object coming from dash-renderer. `loading_state` is a dict with keys: - component_name (string; optional): Holds the name of the component that is loading. - is_loading (boolean; optional): Determines if the component is loading or not. - prop_name (string; optional): Holds which property is loading. - n_clicks (number; default 0): An integer that represents the number of times that this element has been clicked on. - n_clicks_timestamp (number; default -1): An integer that represents the time (in ms since 1970) at which n_clicks changed. This can be used to tell which button was changed most recently. - role (string; optional): The ARIA role attribute. - spellCheck (string; optional): Indicates whether spell checking is allowed for the element. - style (dict; optional): Defines CSS styles which will override styles previously set. - tabIndex (string; optional): Overrides the browser's default tab order and follows the one specified instead. - title (string; optional): Text to be displayed in a tooltip when hovering over the element. - value (string; optional): Defines a default value which will be displayed in the element on page load.""" @_explicitize_args def __init__(self, children=None, id=Component.UNDEFINED, n_clicks=Component.UNDEFINED, n_clicks_timestamp=Component.UNDEFINED, key=Component.UNDEFINED, role=Component.UNDEFINED, value=Component.UNDEFINED, accessKey=Component.UNDEFINED, className=Component.UNDEFINED, contentEditable=Component.UNDEFINED, contextMenu=Component.UNDEFINED, dir=Component.UNDEFINED, draggable=Component.UNDEFINED, hidden=Component.UNDEFINED, lang=Component.UNDEFINED, spellCheck=Component.UNDEFINED, style=Component.UNDEFINED, tabIndex=Component.UNDEFINED, title=Component.UNDEFINED, loading_state=Component.UNDEFINED, **kwargs): self._prop_names = ['children', 'id', 'accessKey', 'aria-*', 'className', 'contentEditable', 'contextMenu', 'data-*', 'dir', 'draggable', 'hidden', 'key', 'lang', 'loading_state', 'n_clicks', 'n_clicks_timestamp', 'role', 'spellCheck', 'style', 'tabIndex', 'title', 'value'] self._type = 'Data' self._namespace = 'dash_html_components' self._valid_wildcard_attributes = ['data-', 'aria-'] self.available_properties = ['children', 'id', 'accessKey', 'aria-*', 'className', 'contentEditable', 'contextMenu', 'data-*', 'dir', 'draggable', 'hidden', 'key', 'lang', 'loading_state', 'n_clicks', 'n_clicks_timestamp', 'role', 'spellCheck', 'style', 'tabIndex', 'title', 'value'] self.available_wildcard_properties = ['data-', 'aria-'] _explicit_args = kwargs.pop('_explicit_args') _locals = locals() _locals.update(kwargs) # For wildcard attrs args = {k: _locals[k] for k in _explicit_args if k != 'children'} for k in []: if k not in args: raise TypeError( 'Required argument `' + k + '` was not specified.') super(Data, self).__init__(children=children, **args)
[ "qs6272527@gmail.com" ]
qs6272527@gmail.com
1e09a1afad05e40415362ebcf4ab5e7d018788f5
1388c8381e7b179887a53db15b2882a4e51b820e
/paypal/migrations/0006_auto_20150721_1921.py
d597177d5c80f23541162dd9e476c3af94c9f2b6
[]
no_license
laurentenhoor/samsamsam
d0d2d688ecc682bb885cdc398bfda0ddab97cbd4
923647186ee2a074ec186b4ff46fb5ca7ff53d32
refs/heads/master
2023-01-13T10:33:28.666076
2015-08-28T08:57:51
2015-08-28T08:57:51
154,669,877
0
0
null
2022-12-26T20:15:27
2018-10-25T12:48:39
Python
UTF-8
Python
false
false
373
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('paypal', '0005_contact_last_used'), ] operations = [ migrations.AlterModelOptions( name='contact', options={'ordering': ['last_used']}, ), ]
[ "laurentenhoor@gmail.com" ]
laurentenhoor@gmail.com
6b89749fe8823ae962abbaa45373e75891ef3212
15e6385746ccf4b8eb6c6e302aca236021bb8781
/LintcodePartII/li405_submatrixSum.py
443777a2c60f7562a7b839a401d41945fa35145d
[]
no_license
akb46mayu/Data-Structures-and-Algorithms
11c4bbddc9b4d286e1aeaa9481eb6a620cd54746
de98494e14fff3e2a468da681c48d60b4d1445a1
refs/heads/master
2021-01-12T09:51:32.618362
2018-05-16T16:37:18
2018-05-16T16:37:18
76,279,268
3
0
null
null
null
null
UTF-8
Python
false
false
1,307
py
""" Given an integer matrix, find a submatrix where the sum of numbers is zero. Your code should return the coordinate of the left-up and right-down number. Have you met this question in a real interview? Yes Example Given matrix [ [1 ,5 ,7], [3 ,7 ,-8], [4 ,-8 ,9], ] return [(1,1), (2,2)] """ class Solution: # @param {int[][]} matrix an integer matrix # @return {int[][]} the coordinate of the left-up and right-down number def submatrixSum(self, matrix): # Write your code here if not matrix: return [[0,0], [0,0]] m, n = len(matrix), len(matrix[0]) psum = [[0]*n for _ in range(m)] for i in range(m): for j in range(n): if i == 0: psum[i][j] = matrix[i][j] else: psum[i][j] = psum[i-1][j] + matrix[i][j] for lx in range(m): for rx in range(lx, m): dict = {0:-1} sum0 = 0 for j in range(n): sumcur = psum[rx][j] - psum[lx-1][j] if lx >= 1 else psum[rx][j] sum0 += sumcur if sum0 in dict: return [[lx,dict[sum0]+1],[rx,j]] dict[sum0] = j return [[0,0], [0,0]]
[ "noreply@github.com" ]
noreply@github.com
144ee5c0f1f859e617b1d48c45f30ee8867c70bf
b5cca4f03ee8ea511235adfbe3e15e0c9d0cfcf0
/solarroof/settings.py
183d6963bed4ef7e3d70055fcbb6d4e19d32a8bb
[ "MIT" ]
permissive
saksham1991999/Solar-Roof-Potential
29977aa6e7a37bd3f011cd5301a90cba5a1ad63b
cc0b9b6af5abbe005aaeaef5ffdd7307a971fbbc
refs/heads/main
2023-04-07T00:16:04.313551
2021-04-05T20:46:27
2021-04-05T20:46:27
352,153,718
0
0
null
null
null
null
UTF-8
Python
false
false
3,316
py
""" Django settings for solarroof project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os import django_heroku # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'p-woi+rx$mwa&$g13u!jlekrmqbp&*zf4kqf9fe8w-=h0@xtkp' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'drf_yasg', 'core', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'solarroof.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'solarroof.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') django_heroku.settings(locals())
[ "181210045@nitdelhi.ac.in" ]
181210045@nitdelhi.ac.in
36b814ddadae57354bfa080d2e733b36281f8b2d
34d3c58afa95fcb4cee7f0da1b01466fc291e1bb
/src/Account.py
2820ebb0d9125b1ae74e8583c67f91d7c235aa9e
[]
no_license
leolo0626/portfolio_bactest
aa769a82ff7639c0dd1a2099304f52b4ae96dbb1
5a27f3b535f45cedb66d2ba6600372b5fd3d7295
refs/heads/main
2023-07-25T22:27:12.843882
2021-09-11T14:50:26
2021-09-11T14:50:26
392,228,758
0
0
null
null
null
null
UTF-8
Python
false
false
533
py
class Account : def __init__(self): self.initial_capital = 0 self.cash = 0 self.net_asset_value = 0 def add_capital(self, cash_amount): self.initial_capital = self.initial_capital + cash_amount self.cash = self.cash + cash_amount self.net_asset_value = self.net_asset_value + cash_amount def increase_account_value(self, amount): self.cash = self.cash + amount def decrease_account_value(self, amount): self.cash = self.cash - amount
[ "leolo0626@gmail.com" ]
leolo0626@gmail.com
692a9e6559e097c15108dc25e36eb37ad7a4e73f
5b7e7457c0214280d28065d14aee004d8b0a403e
/src/libxslt/python/tests/extfunc.py
6fd908ea5ebaba6be062400aa48b3e1c1849ca90
[ "LicenseRef-scancode-x11-xconsortium-veillard", "X11", "MIT" ]
permissive
webkitdotnet/WinCairoRequirements
0e567e98d45415e389a80e5477d9083e43409036
45cd0bdac280e58792428bc41f0c08ad93f4cf92
refs/heads/master
2021-01-16T22:46:15.321638
2013-02-17T21:27:12
2013-02-17T21:27:12
8,255,164
3
2
null
null
null
null
UTF-8
Python
false
false
1,677
py
#!/usr/bin/python -u import sys import string import libxml2 # Memory debug specific libxml2.debugMemory(1) import libxslt nodeName = None def f(ctx, str): global nodeName # # Small check to verify the context is correcly accessed # try: pctxt = libxslt.xpathParserContext(_obj=ctx) ctxt = pctxt.context() tctxt = ctxt.transformContext() nodeName = tctxt.insertNode().name except: pass return string.upper(str) libxslt.registerExtModuleFunction("foo", "http://example.com/foo", f) styledoc = libxml2.parseDoc(""" <xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:foo='http://example.com/foo' exclude-result-prefixes='foo'> <xsl:param name='bar'>failure</xsl:param> <xsl:template match='/'> <article><xsl:value-of select='foo:foo($bar)'/></article> </xsl:template> </xsl:stylesheet> """) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseDoc("<doc/>") result = style.applyStylesheet(doc, { "bar": "'success'" }) style.freeStylesheet() doc.freeDoc() root = result.children if root.name != "article": print "Unexpected root node name" sys.exit(1) if root.content != "SUCCESS": print "Unexpected root node content, extension function failed" sys.exit(1) if nodeName != 'article': print "The function callback failed to access its context" sys.exit(1) result.freeDoc() # Memory debug specific libxslt.cleanup() if libxml2.debugMemory(1) == 0: print "OK" else: print "Memory leak %d bytes" % (libxml2.debugMemory(1)) libxml2.dumpMemory()
[ "bfulgham@gmail.com" ]
bfulgham@gmail.com
dd749bd41c4159bf4470b8fa036cb104ddad6be2
18f3c47b55635128a8db45dda340df2c7393468d
/map/models.py
2972b9e4d880c50ee0080cb42e9a3e9449536476
[]
no_license
rheehot/Zigbang
c62ec77f7f8352f09622f54a377a4fb69f2a4417
b120559767a0aa286dc3a632a193bf25a0b90aee
refs/heads/master
2022-11-27T14:26:33.413310
2020-08-06T07:45:59
2020-08-06T07:45:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
9,031
py
from django.db import models class City(models.Model): name = models.CharField(max_length = 50) class Meta: db_table = 'cities' class District(models.Model): name = models.CharField(max_length = 50) city = models.ForeignKey('City', on_delete = models.SET_NULL, null = True) class Meta: db_table = 'districts' class Province(models.Model): name = models.CharField(max_length = 50) district = models.ForeignKey('District', on_delete = models.SET_NULL, null = True) class Meta: db_table = 'provinces' class Subway(models.Model): subway_code = models.IntegerField() name = models.CharField(max_length = 50) longitude = models.DecimalField(max_digits = 18, decimal_places = 15) latitude = models.DecimalField(max_digits = 18, decimal_places = 15) local = models.CharField(max_length = 50, null = True, blank = True) line = models.ManyToManyField('Line', through = 'SubwayLine') class Meta: db_table = 'subways' class Line(models.Model): name = models.CharField(max_length = 50) color = models.CharField(max_length = 50) class Meta: db_table = 'line' class SubwayLine(models.Model): subway = models.ForeignKey('Subway', on_delete = models.SET_NULL, null = True) line = models.ForeignKey('Line', on_delete = models.SET_NULL, null = True) class Meta: db_table = 'subways_line' class RoomSubway(models.Model): room = models.ForeignKey('Room', on_delete = models.SET_NULL, null = True) subway = models.ForeignKey('Subway', on_delete = models.SET_NULL, null = True) class Meta: db_table = 'rooms_subways' class School(models.Model): school_gender = models.ForeignKey('SchoolGender', on_delete = models.SET_NULL, null = True) school_type = models.ForeignKey('SchoolType', on_delete = models.SET_NULL, null = True) school_category = models.ForeignKey('SchoolCategory', on_delete = models.SET_NULL, null = True) address = models.CharField(max_length = 500) district = models.ForeignKey('District', on_delete = models.SET_NULL, null = True) road_address = models.CharField(max_length = 500) longitude = models.DecimalField(max_digits = 18, decimal_places = 15) latitude = models.DecimalField(max_digits = 18, decimal_places = 15) foundation_date = models.CharField(max_length = 50) name = models.CharField(max_length = 50) school_establishment_type = models.ForeignKey( 'SchoolEstablishmentType', on_delete = models.SET_NULL, null = True) school_phone_number = models.CharField(max_length = 50) class Meta: db_table = 'schools' class SchoolEstablishmentType(models.Model): name = models.CharField(max_length = 20) class Meta: db_table = 'school_establishment_types' class SchoolGender(models.Model): name = models.CharField(max_length = 50) class Meta: db_table = 'school_genders' class SchoolType(models.Model): name = models.CharField(max_length = 50) class Meta: db_table = 'school_types' class SchoolCategory(models.Model): name = models.CharField(max_length = 50) class Meta: db_table = 'school_categories' class ComplexType(models.Model): name = models.CharField(max_length = 50) class Meta: db_table = 'complex_types' class Complex(models.Model): complex_type = models.ForeignKey('ComplexType', on_delete = models.SET_NULL, null = True) name = models.CharField(max_length = 50) complex_number = models.IntegerField() longitude = models.DecimalField(max_digits = 18, decimal_places = 15) latitude = models.DecimalField(max_digits = 18, decimal_places = 15) province = models.ForeignKey('Province', on_delete = models.SET_NULL, null = True) household = models.IntegerField(default = 1) builddate = models.CharField(max_length = 50) complex_image_thumbnail = models.URLField(max_length = 2000, null = True, blank = True) class Meta: db_table = 'complexes' class Room(models.Model): building_number = models.CharField(max_length = 50, null = True, blank = True) description = models.CharField(max_length = 100, null = True, blank = True) detail_description = models.CharField(max_length = 3000, null = True, blank = True) post_date = models.CharField(max_length = 50, null = True, blank = True) is_recommended = models.BooleanField(default = 0) room_type = models.ForeignKey('RoomType', on_delete = models.SET_NULL, null = True) sub_room_type = models.ForeignKey('SubRoomType', on_delete = models.SET_NULL, null = True) sale_registration_number = models.IntegerField() supply_area_square_meter = models.DecimalField(max_digits = 10, decimal_places = 2) exclusive_area_square_meter = models.DecimalField(max_digits = 10, decimal_places = 2) maintenance_fee = models.DecimalField(max_digits = 5, decimal_places = 2, null = True, blank = True) is_parking_lot = models.BooleanField(default = 0) is_elevator = models.BooleanField(default = 0) floor = models.CharField(max_length = 50) entire_floor = models.CharField(max_length = 50) moving_in_date_type = models.CharField(max_length = 100, null = True, blank = True) agent_comment = models.CharField(max_length = 3000, null = True, blank = True) agency = models.ForeignKey('Agency', on_delete = models.SET_NULL, null = True) complex = models.ForeignKey('Complex', on_delete = models.CASCADE) subway = models.ManyToManyField('Subway', through = 'RoomSubway') trade_type = models.ManyToManyField('TradeType', through = 'RoomTradeType') maintenance_option = models.ManyToManyField('MaintenanceOption', through = 'RoomMaintenanceOption') room_option = models.ManyToManyField('RoomOption', through = 'RoomRoomOption') room_image_thumbnail = models.URLField(max_length = 2000, null = True, blank = True) class Meta: db_table = 'rooms' class TradeType(models.Model): name = models.CharField(max_length = 20) class Meta: db_table = 'trade_types' class RoomTradeType(models.Model): room = models.ForeignKey('Room', on_delete = models.SET_NULL, null = True) trade_type = models.ForeignKey('TradeType', on_delete = models.SET_NULL, null = True) deposit = models.DecimalField(max_digits = 20, decimal_places = 2) monthly_rent = models.DecimalField(max_digits = 20, decimal_places = 2, null = True, blank = True) class Meta: db_table = 'rooms_trade_types' class MaintenanceOption(models.Model): name = models.CharField(max_length = 50) image_url = models.URLField(max_length = 2000) class Meta: db_table = 'maintenance_options' class RoomMaintenanceOption(models.Model): room = models.ForeignKey('Room', on_delete = models.SET_NULL, null = True) maintenance_option = models.ForeignKey('MaintenanceOption', on_delete = models.SET_NULL, null = True) class Meta: db_table = 'rooms_maintenance_options' class RoomImage(models.Model): room = models.ForeignKey('Room', on_delete = models.SET_NULL, null = True) image_url = models.URLField(max_length = 2000) class Meta: db_table = 'room_images' class RoomType(models.Model): name = models.CharField(max_length = 50) class Meta: db_table = 'room_types' class SubRoomType(models.Model): name = models.CharField(max_length = 50) class Meta: db_table = 'sub_room_types' class RoomOption(models.Model): name = models.CharField(max_length = 50) image_url = models.URLField(max_length = 2000) class Meta: db_table = 'room_options' class RoomRoomOption(models.Model): room_option = models.ForeignKey('RoomOption', on_delete = models.SET_NULL, null = True) room = models.ForeignKey('Room', on_delete = models.SET_NULL, null = True) class Meta: db_table = 'rooms_room_options' class Agency(models.Model): agency_number = models.IntegerField() name = models.CharField(max_length = 50) representative = models.CharField(max_length = 50) image_url = models.URLField(max_length = 2000, null = True, blank = True) phone_number = models.CharField(max_length = 50) address = models.CharField(max_length = 500) class Meta: db_table = 'agencies'
[ "nogwang-o@nogwang-oui-MacBookPro.local" ]
nogwang-o@nogwang-oui-MacBookPro.local
9f62583507c99cb0c1fdc4fbddd3bd3f193c5132
0a2190bdd257d8b4a9f879fbc1474337c02da32d
/devel/lib/python2.7/dist-packages/rococo_navigation/msg/_TurnActionGoal.py
53a4e04cdc144fdf63ddbb8ece1ebf8b0887154a
[]
no_license
bitCluod/AkiraRobotService
af4ed667590f33fea11488445787d793e6aaf389
accc6acf0480818306462dc74e6b7adf11cfa220
refs/heads/master
2023-04-18T08:28:54.632006
2021-05-01T02:35:18
2021-05-01T02:35:18
363,306,688
0
0
null
null
null
null
UTF-8
Python
false
false
10,957
py
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from rococo_navigation/TurnActionGoal.msg. Do not edit.""" import codecs import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct import actionlib_msgs.msg import genpy import rococo_navigation.msg import std_msgs.msg class TurnActionGoal(genpy.Message): _md5sum = "f1325916007ff88ca14243f2c70c7ccd" _type = "rococo_navigation/TurnActionGoal" _has_header = True # flag to mark the presence of a Header object _full_text = """# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ====== Header header actionlib_msgs/GoalID goal_id TurnGoal goal ================================================================================ MSG: std_msgs/Header # Standard metadata for higher-level stamped data types. # This is generally used to communicate timestamped data # in a particular coordinate frame. # # sequence ID: consecutively increasing ID uint32 seq #Two-integer timestamp that is expressed as: # * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs') # * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs') # time-handling sugar is provided by the client library time stamp #Frame this data is associated with # 0: no frame # 1: global frame string frame_id ================================================================================ MSG: actionlib_msgs/GoalID # The stamp should store the time at which this goal was requested. # It is used by an action server when it tries to preempt all # goals that were requested before a certain time time stamp # The id provides a way to associate feedback and # result message with specific goal requests. The id # specified must be unique. string id ================================================================================ MSG: rococo_navigation/TurnGoal # ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ====== # Goal # target_angle [DEG] float32 target_angle # flag ABS/REL string absolute_relative_flag # max angular velocity [DEG/s] float32 max_ang_vel """ __slots__ = ['header','goal_id','goal'] _slot_types = ['std_msgs/Header','actionlib_msgs/GoalID','rococo_navigation/TurnGoal'] def __init__(self, *args, **kwds): """ Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: header,goal_id,goal :param args: complete set of field values, in .msg order :param kwds: use keyword arguments corresponding to message field names to set specific fields. """ if args or kwds: super(TurnActionGoal, self).__init__(*args, **kwds) # message fields cannot be None, assign default values for those that are if self.header is None: self.header = std_msgs.msg.Header() if self.goal_id is None: self.goal_id = actionlib_msgs.msg.GoalID() if self.goal is None: self.goal = rococo_navigation.msg.TurnGoal() else: self.header = std_msgs.msg.Header() self.goal_id = actionlib_msgs.msg.GoalID() self.goal = rococo_navigation.msg.TurnGoal() def _get_types(self): """ internal API method """ return self._slot_types def serialize(self, buff): """ serialize message into buffer :param buff: buffer, ``StringIO`` """ try: _x = self buff.write(_get_struct_3I().pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs)) _x = self.header.frame_id length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.Struct('<I%ss'%length).pack(length, _x)) _x = self buff.write(_get_struct_2I().pack(_x.goal_id.stamp.secs, _x.goal_id.stamp.nsecs)) _x = self.goal_id.id length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.Struct('<I%ss'%length).pack(length, _x)) _x = self.goal.target_angle buff.write(_get_struct_f().pack(_x)) _x = self.goal.absolute_relative_flag length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.Struct('<I%ss'%length).pack(length, _x)) _x = self.goal.max_ang_vel buff.write(_get_struct_f().pack(_x)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize(self, str): """ unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str`` """ codecs.lookup_error("rosmsg").msg_type = self._type try: if self.header is None: self.header = std_msgs.msg.Header() if self.goal_id is None: self.goal_id = actionlib_msgs.msg.GoalID() if self.goal is None: self.goal = rococo_navigation.msg.TurnGoal() end = 0 _x = self start = end end += 12 (_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs,) = _get_struct_3I().unpack(str[start:end]) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.header.frame_id = str[start:end].decode('utf-8', 'rosmsg') else: self.header.frame_id = str[start:end] _x = self start = end end += 8 (_x.goal_id.stamp.secs, _x.goal_id.stamp.nsecs,) = _get_struct_2I().unpack(str[start:end]) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.goal_id.id = str[start:end].decode('utf-8', 'rosmsg') else: self.goal_id.id = str[start:end] start = end end += 4 (self.goal.target_angle,) = _get_struct_f().unpack(str[start:end]) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.goal.absolute_relative_flag = str[start:end].decode('utf-8', 'rosmsg') else: self.goal.absolute_relative_flag = str[start:end] start = end end += 4 (self.goal.max_ang_vel,) = _get_struct_f().unpack(str[start:end]) return self except struct.error as e: raise genpy.DeserializationError(e) # most likely buffer underfill def serialize_numpy(self, buff, numpy): """ serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module """ try: _x = self buff.write(_get_struct_3I().pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs)) _x = self.header.frame_id length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.Struct('<I%ss'%length).pack(length, _x)) _x = self buff.write(_get_struct_2I().pack(_x.goal_id.stamp.secs, _x.goal_id.stamp.nsecs)) _x = self.goal_id.id length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.Struct('<I%ss'%length).pack(length, _x)) _x = self.goal.target_angle buff.write(_get_struct_f().pack(_x)) _x = self.goal.absolute_relative_flag length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.Struct('<I%ss'%length).pack(length, _x)) _x = self.goal.max_ang_vel buff.write(_get_struct_f().pack(_x)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize_numpy(self, str, numpy): """ unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module """ codecs.lookup_error("rosmsg").msg_type = self._type try: if self.header is None: self.header = std_msgs.msg.Header() if self.goal_id is None: self.goal_id = actionlib_msgs.msg.GoalID() if self.goal is None: self.goal = rococo_navigation.msg.TurnGoal() end = 0 _x = self start = end end += 12 (_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs,) = _get_struct_3I().unpack(str[start:end]) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.header.frame_id = str[start:end].decode('utf-8', 'rosmsg') else: self.header.frame_id = str[start:end] _x = self start = end end += 8 (_x.goal_id.stamp.secs, _x.goal_id.stamp.nsecs,) = _get_struct_2I().unpack(str[start:end]) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.goal_id.id = str[start:end].decode('utf-8', 'rosmsg') else: self.goal_id.id = str[start:end] start = end end += 4 (self.goal.target_angle,) = _get_struct_f().unpack(str[start:end]) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.goal.absolute_relative_flag = str[start:end].decode('utf-8', 'rosmsg') else: self.goal.absolute_relative_flag = str[start:end] start = end end += 4 (self.goal.max_ang_vel,) = _get_struct_f().unpack(str[start:end]) return self except struct.error as e: raise genpy.DeserializationError(e) # most likely buffer underfill _struct_I = genpy.struct_I def _get_struct_I(): global _struct_I return _struct_I _struct_2I = None def _get_struct_2I(): global _struct_2I if _struct_2I is None: _struct_2I = struct.Struct("<2I") return _struct_2I _struct_3I = None def _get_struct_3I(): global _struct_3I if _struct_3I is None: _struct_3I = struct.Struct("<3I") return _struct_3I _struct_f = None def _get_struct_f(): global _struct_f if _struct_f is None: _struct_f = struct.Struct("<f") return _struct_f
[ "scheneider12.12@gmail.com" ]
scheneider12.12@gmail.com
1a573cda6c2a4d96f172917b8c70da2ab8f0288e
c2d5a7bf3d5f6bcf07b8293b1bf7eff838a5dcbe
/app/migrations/0002_central_ciudad_cluster_ce_estado.py
36f568fee9bbf653e047ec4ce65db547b929f3b8
[]
no_license
leocordero/cuenta
e0a881a6cb01af905c6fd2395dff7b941cf0f9c5
907776df30408f00a413b0a7ed1f9ef45b71e008
refs/heads/master
2023-06-30T08:43:42.626282
2021-07-30T21:21:31
2021-07-30T21:21:31
390,870,143
0
0
null
null
null
null
UTF-8
Python
false
false
1,878
py
# Generated by Django 3.2.5 on 2021-07-13 03:36 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('app', '0001_initial'), ] operations = [ migrations.CreateModel( name='cluster_ce', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombre', models.CharField(max_length=30)), ], ), migrations.CreateModel( name='estado', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombre', models.CharField(max_length=30)), ('divisional', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.divisional')), ], ), migrations.CreateModel( name='ciudad', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombre', models.CharField(max_length=30)), ('estado', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.estado')), ], ), migrations.CreateModel( name='central', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombre', models.CharField(max_length=30)), ('direccion', models.TextField(blank=True, null=True)), ('localizacion', models.TextField(blank=True, null=True)), ('ciudad', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.ciudad')), ], ), ]
[ "lchaconz@cisco.com" ]
lchaconz@cisco.com
963bd6d3840d499bef787d38ba22b3d8a5291ba5
5207b5bc504bd4253da6e78a4e361db61c5b1e70
/game/services/game/event/draw.py
132c8665400fd62d291a91a130a97b8131ad1db5
[]
no_license
luiz290788/ajani
442853cc7c6865ae13cbbf7aee25dae9f798c3de
fdfa112893c4808508376ea308bfc7337169240a
refs/heads/master
2021-01-01T20:34:47.968248
2015-06-14T20:54:49
2015-06-14T20:54:49
34,073,394
1
0
null
null
null
null
UTF-8
Python
false
false
953
py
from google.appengine.ext import ndb from services.game import library, response_util from services.model import Hand, Library def load(incoming_event, player_id, game_key): hand_key = ndb.Key(Hand, player_id, parent=game_key) library_key = ndb.Key(Library, player_id, parent=game_key) return [hand_key, library_key] def process(incoming_event, player_id, game, hand_obj, library_obj): count = incoming_event['count'] if incoming_event['count'] is not None else 0 hand_obj = library.draw(library_obj, hand_obj, count) to_put = [hand_obj, library_obj] hand_response = {'cards': [card.to_dict() for card in hand_obj.cards]} library_response = response_util.library_response(library_obj) response = {'hand': hand_response, 'library': library_response} notification = {'opponent_hand': {'cards': len(hand_obj.cards)}, 'opponent_library': library_response} return (response, notification, to_put)
[ "luiz290788@gmail.com" ]
luiz290788@gmail.com
185c7b7f95c8487e2f85422f38c93095e8bd3438
3f36a8e71ea13a135467ea64367d6e3358333f74
/movie_details.py
b88daf458d68088e861cd4d0c53e98e1ee709f51
[ "MIT" ]
permissive
gorpo/Exemplos-Python
4257873af5a23b79d51cc60e8ea84185b7e299c4
2cc11e0604d83c4f0a46645ceef0b209e467e6e6
refs/heads/master
2023-03-09T00:24:27.404626
2020-08-24T04:49:59
2020-08-24T04:49:59
264,974,378
4
4
MIT
2021-02-26T02:53:36
2020-05-18T15:02:56
Python
UTF-8
Python
false
false
1,600
py
import urllib.request import mechanize from bs4 import BeautifulSoup # Create a Browser browser = mechanize.Browser() # Disable loading robots.txt browser.set_handle_robots(False) browser.addheaders = [('User-agent', 'Mozilla/4.0 (compatible; MSIE 5.0; Windows 98;)')] movie_title = input("Enter movie title: ") movie_types = ('feature', 'tv_movie', 'tv_series', 'tv_episode', 'tv_special', 'tv_miniseries', 'documentary', 'video_game', 'short', 'video', 'tv_short') # Navigate browser.open('http://www.imdb.com/search/title') # Choose a form browser.select_form(nr=1) browser['title'] = movie_title # Check all the boxes of movie types for m_type in movie_types: browser.find_control(type='checkbox', nr=0).get(m_type).selected = True # Submit fd = browser.submit() soup = BeautifulSoup(fd.read(), 'html5lib') # Updated from td tag to h3 tag for div in soup.findAll('h3', {'class': 'lister-item-header'}, limit=1): a = div.findAll('a')[0] hht = 'http://www.imdb.com' + a.attrs['href'] print(hht) page = urllib.request.urlopen(hht) soup2 = BeautifulSoup(page.read(), 'html.parser') find = soup2.find print("Title: " + find(itemprop='name').get_text().strip()) print("Duration: " + find(itemprop='duration').get_text().strip()) print("Director: " + find(itemprop='director').get_text().strip()) print("Genre: " + find(itemprop='genre').get_text().strip()) print("IMDB rating: " + find(itemprop='ratingValue').get_text().strip()) print("Summary: " + find(itemprop='description').get_text().strip())
[ "noreply@github.com" ]
noreply@github.com
bc6ba20afd61f6bf37f412a650eae3cd5cd072c4
6596e7eaa8abdc7cd715aecf1b6a9c4b532d042c
/ciftlik.yem.problemi.py
6d1fb1ae14e21f63ae28f1f0df91cc9480827831
[]
no_license
hasanHIDIROGLU/pythonexamples
5fef51032f2b1f3ca4dd53becd39bf8b937e2078
12e23ade5f8186a84be9eda8afafb6cf89bd679f
refs/heads/master
2021-07-11T14:02:37.662536
2021-07-06T07:16:08
2021-07-06T07:16:08
166,395,043
0
0
null
null
null
null
UTF-8
Python
false
false
1,387
py
# S.3. Bir çiftlikte bulunan koyunların beslenmesi şu şekilde yapılmaktadır. Öncelikle besleme makinesine belirlenen bir miktarda # yem doldurulmaktadır. Daha sonra görevli personel koyunlara verilecek günlük üst limit yem miktarını uygulamaya girmektedir. # Uygulama 1,3,5 gibi tek günlerde üst limitin yarısı, çift günlerde ise üst limitin dörtte biri kadar yem vermektedir. Sizden istenen # belirlenen yem miktarına ve üst limit değerlerine göre günlük yem miktarlarını ve yemin kaç gün yeteceğini hesaplayan # uygulama geliştirmenizdir. Aşağıda uygulamaya ilişkin örnek çıktılar verilmiştir. Not: Son gün kalan miktar üst limitin # yarısından veya dörtte birinden az ise bu durumda kalan yemin tamamı verilmelidir. yem_miktari = int(input("yem miktarını giriniz:")) ust_limit = int(input("üst limit miktarını giriniz:")) tek_gun_yem_miktari = ust_limit // 2 cift_gun_yem_miktari = ust_limit // 4 gun_sayisi = 1 while yem_miktari > 0: if yem_miktari > tek_gun_yem_miktari: print("{0}. gün verilen yem : {1}".format(gun_sayisi,tek_gun_yem_miktari)) gun_sayisi += 1 yem_miktari -= tek_gun_yem_miktari tek_gun_yem_miktari,cift_gun_yem_miktari=cift_gun_yem_miktari,tek_gun_yem_miktari else: print("{0}. gün verilen miktar : {1}".format(gun_sayisi,yem_miktari)) yem_miktari=0
[ "noreply@github.com" ]
noreply@github.com
d3c5e8c30ac270fd164e79ae288a7f1a7b2aeb2d
49e145c536964b1dc72946a19560741c492482d7
/TTA06p2.py
ef4402c2f5c9b9af9a54875e0b34a4b648a921f7
[]
no_license
mueller14003/CS241
502a1cb8f7706ff22741896ea4d612df96515f13
37e539b59e47f4b522c624e5e14e6675eb5be2f3
refs/heads/master
2021-09-20T01:14:58.650239
2018-08-02T06:26:34
2018-08-02T06:26:34
113,709,350
0
0
null
null
null
null
UTF-8
Python
false
false
1,132
py
""" I think that this approach is better because a circle is not a type of point, but rather, it has a location, or point. Thus, it should not inherit from Point, but rather, it should create a class variable that is a point type. This makes much more sense, as a circle will have a point attribute, but is not a type of point. """ class Point: def __init__(self): self.x = 0 self.y = 0 def prompt_for_point(self): self.x = int(input("Enter x: ")) self.y = int(input("Enter y: ")) def display(self): print("Center:\n({}, {})".format(self.x, self.y)) class Circle: def __init__(self): self.point = Point() self.radius = 0 def prompt_for_circle(self): self.point.prompt_for_point() self.radius = int(input("Enter radius: ")) def display(self): self.point.display() print("Radius: {}".format(self.radius)) def main(): point = Point() point.prompt_for_point() point.display() print() circle = Circle() circle.prompt_for_circle() circle.display() if __name__ == "__main__": main()
[ "34406644+mueller14003@users.noreply.github.com" ]
34406644+mueller14003@users.noreply.github.com
58bcf3d3d7a9e42fa01ca8b29a710f6e81cfde90
b086a1caa4e3457c1faa0889d7a7291e653a0248
/tests/test_decontaminate.py
ed588a42754b1f20fbaafdd1f11bfdc4e4ef65af
[ "MIT" ]
permissive
hover2pi/specialsoss
a29381bbfcf7cc15a82e0aba8e607b99192dc48f
6afde9fbd83bb33afa9e606e681c330b64e64aa2
refs/heads/master
2023-01-12T19:22:03.636104
2022-11-30T18:51:16
2022-11-30T18:51:16
152,112,781
1
1
MIT
2022-12-26T20:46:35
2018-10-08T16:36:32
Jupyter Notebook
UTF-8
Python
false
false
500
py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `decontaminate` module.""" import unittest from pkg_resources import resource_filename from specialsoss import decontaminate class TestDecontaminate(unittest.TestCase): """Test functions in decontaminate.py""" def setUp(self): """Test instance setup""" # Get files for testing self.frame = np.ones((256, 2048)) self.tso3d = np.ones((4, 256, 2048)) self.tso4d = np.ones((2, 2, 256, 2048))
[ "jfilippazzo@stsci.edu" ]
jfilippazzo@stsci.edu
a95634a6ae723a37422e4449df51ccd9fdcd283a
1fa3016c1b67178910b477fd5885cc0fff17e923
/Learning Python/Bank Account.py
19e95929801694bca67dd4cd2e1d8495f5cf85f4
[]
no_license
Charnub/python-code
9f1c952075ed725b8561a2115acb30872ba0b797
3e35510756e8635e26fc3b71396a0c8856385b69
refs/heads/master
2021-04-15T09:26:34.691921
2018-03-22T18:09:51
2018-03-22T18:09:51
null
0
0
null
null
null
null
UTF-8
Python
false
false
994
py
class Account: def __init__(self): self.savings = 100 def __init__(self): self.withdraw = 0 account1 = Account() account1.savings = 400 account2 = Account() account2.savings = 50 account3 = Account() account3.savings = 1000 def withdraw(self, withdraw): withdraw = input("How much would you like to withdraw?") self.savings -= withdraw if self.savings < 0: print("Cannot withdraw that amount!") def deposit(self, deposit): deposit = input selectAccount = input("What account would you like to access?") if selectAccount == "account1": print("Account 1 Selected") print("£" + (str(account1.savings)) + " Available to withdraw") elif selectAccount == "account2": print("Account 2 Selected") print("£" + (str(account2.savings)) + " Available to withdraw") elif selectAccount == "account3": print("Account 3 Selected") print("£" + (str(account3.savings)) + " Available to withdraw")
[ "noreply@github.com" ]
noreply@github.com
08bb23fdc4d27bf24fc8acba539dc31a6c16a40d
0412893529999de784ab9cb914f385ba788a3684
/logicmonitor_sdk/models/service_alert.py
f140a8c85cf85576b2c428c2b3678d325ef7a839
[ "Apache-2.0" ]
permissive
JeremyTangCD/lm-sdk-python
0326bf034c16b022b760600dc18fe7aaad42fa26
2a15e055e5a3f72d2f2e4fb43bdbed203c5a9983
refs/heads/master
2020-04-15T15:39:59.276224
2019-01-09T09:55:36
2019-01-09T09:55:36
164,803,314
0
0
Apache-2.0
2019-01-09T09:58:55
2019-01-09T06:33:40
Python
UTF-8
Python
false
false
14,296
py
# coding: utf-8 """ LogicMonitor REST API LogicMonitor is a SaaS-based performance monitoring platform that provides full visibility into complex, hybrid infrastructures, offering granular performance monitoring and actionable data and insights. logicmonitor_sdk enables you to manage your LogicMonitor account programmatically. # noqa: E501 OpenAPI spec version: 1.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six from logicmonitor_sdk.models.widget import Widget # noqa: F401,E501 class ServiceAlert(Widget): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'last_updated_by': 'str', 'user_permission': 'str', 'dashboard_id': 'int', 'name': 'str', 'description': 'str', 'last_updated_on': 'int', 'theme': 'str', 'interval': 'int', 'id': 'int', 'type': 'str', 'timescale': 'str', 'device_id': 'int', 'device_display_name': 'str' } attribute_map = { 'last_updated_by': 'lastUpdatedBy', 'user_permission': 'userPermission', 'dashboard_id': 'dashboardId', 'name': 'name', 'description': 'description', 'last_updated_on': 'lastUpdatedOn', 'theme': 'theme', 'interval': 'interval', 'id': 'id', 'type': 'type', 'timescale': 'timescale', 'device_id': 'deviceId', 'device_display_name': 'deviceDisplayName' } def __init__(self, last_updated_by=None, user_permission=None, dashboard_id=None, name=None, description=None, last_updated_on=None, theme=None, interval=None, id=None, type=None, timescale=None, device_id=None, device_display_name=None): # noqa: E501 """ServiceAlert - a model defined in Swagger""" # noqa: E501 self._last_updated_by = None self._user_permission = None self._dashboard_id = None self._name = None self._description = None self._last_updated_on = None self._theme = None self._interval = None self._id = None self._type = None self._timescale = None self._device_id = None self._device_display_name = None self.discriminator = None if last_updated_by is not None: self.last_updated_by = last_updated_by if user_permission is not None: self.user_permission = user_permission self.dashboard_id = dashboard_id self.name = name if description is not None: self.description = description if last_updated_on is not None: self.last_updated_on = last_updated_on if theme is not None: self.theme = theme if interval is not None: self.interval = interval if id is not None: self.id = id self.type = type if timescale is not None: self.timescale = timescale self.device_id = device_id if device_display_name is not None: self.device_display_name = device_display_name @property def last_updated_by(self): """Gets the last_updated_by of this ServiceAlert. # noqa: E501 The user that last updated the widget # noqa: E501 :return: The last_updated_by of this ServiceAlert. # noqa: E501 :rtype: str """ return self._last_updated_by @last_updated_by.setter def last_updated_by(self, last_updated_by): """Sets the last_updated_by of this ServiceAlert. The user that last updated the widget # noqa: E501 :param last_updated_by: The last_updated_by of this ServiceAlert. # noqa: E501 :type: str """ self._last_updated_by = last_updated_by @property def user_permission(self): """Gets the user_permission of this ServiceAlert. # noqa: E501 The permission level of the user who last modified the widget # noqa: E501 :return: The user_permission of this ServiceAlert. # noqa: E501 :rtype: str """ return self._user_permission @user_permission.setter def user_permission(self, user_permission): """Sets the user_permission of this ServiceAlert. The permission level of the user who last modified the widget # noqa: E501 :param user_permission: The user_permission of this ServiceAlert. # noqa: E501 :type: str """ self._user_permission = user_permission @property def dashboard_id(self): """Gets the dashboard_id of this ServiceAlert. # noqa: E501 The id of the dashboard the widget belongs to # noqa: E501 :return: The dashboard_id of this ServiceAlert. # noqa: E501 :rtype: int """ return self._dashboard_id @dashboard_id.setter def dashboard_id(self, dashboard_id): """Sets the dashboard_id of this ServiceAlert. The id of the dashboard the widget belongs to # noqa: E501 :param dashboard_id: The dashboard_id of this ServiceAlert. # noqa: E501 :type: int """ if dashboard_id is None: raise ValueError("Invalid value for `dashboard_id`, must not be `None`") # noqa: E501 self._dashboard_id = dashboard_id @property def name(self): """Gets the name of this ServiceAlert. # noqa: E501 The name of the widget # noqa: E501 :return: The name of this ServiceAlert. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): """Sets the name of this ServiceAlert. The name of the widget # noqa: E501 :param name: The name of this ServiceAlert. # noqa: E501 :type: str """ if name is None: raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 self._name = name @property def description(self): """Gets the description of this ServiceAlert. # noqa: E501 The description of the widget # noqa: E501 :return: The description of this ServiceAlert. # noqa: E501 :rtype: str """ return self._description @description.setter def description(self, description): """Sets the description of this ServiceAlert. The description of the widget # noqa: E501 :param description: The description of this ServiceAlert. # noqa: E501 :type: str """ self._description = description @property def last_updated_on(self): """Gets the last_updated_on of this ServiceAlert. # noqa: E501 The time that corresponds to when the widget was last updated, in epoch format # noqa: E501 :return: The last_updated_on of this ServiceAlert. # noqa: E501 :rtype: int """ return self._last_updated_on @last_updated_on.setter def last_updated_on(self, last_updated_on): """Sets the last_updated_on of this ServiceAlert. The time that corresponds to when the widget was last updated, in epoch format # noqa: E501 :param last_updated_on: The last_updated_on of this ServiceAlert. # noqa: E501 :type: int """ self._last_updated_on = last_updated_on @property def theme(self): """Gets the theme of this ServiceAlert. # noqa: E501 The color scheme of the widget. Options are: borderPurple | borderGray | borderBlue | solidPurple | solidGray | solidBlue | simplePurple | simpleBlue | simpleGray | newBorderGray | newBorderBlue | newBorderDarkBlue | newSolidGray | newSolidBlue | newSolidDarkBlue | newSimpleGray | newSimpleBlue |newSimpleDarkBlue # noqa: E501 :return: The theme of this ServiceAlert. # noqa: E501 :rtype: str """ return self._theme @theme.setter def theme(self, theme): """Sets the theme of this ServiceAlert. The color scheme of the widget. Options are: borderPurple | borderGray | borderBlue | solidPurple | solidGray | solidBlue | simplePurple | simpleBlue | simpleGray | newBorderGray | newBorderBlue | newBorderDarkBlue | newSolidGray | newSolidBlue | newSolidDarkBlue | newSimpleGray | newSimpleBlue |newSimpleDarkBlue # noqa: E501 :param theme: The theme of this ServiceAlert. # noqa: E501 :type: str """ self._theme = theme @property def interval(self): """Gets the interval of this ServiceAlert. # noqa: E501 The refresh interval of the widget, in minutes # noqa: E501 :return: The interval of this ServiceAlert. # noqa: E501 :rtype: int """ return self._interval @interval.setter def interval(self, interval): """Sets the interval of this ServiceAlert. The refresh interval of the widget, in minutes # noqa: E501 :param interval: The interval of this ServiceAlert. # noqa: E501 :type: int """ self._interval = interval @property def id(self): """Gets the id of this ServiceAlert. # noqa: E501 The Id of the widget # noqa: E501 :return: The id of this ServiceAlert. # noqa: E501 :rtype: int """ return self._id @id.setter def id(self, id): """Sets the id of this ServiceAlert. The Id of the widget # noqa: E501 :param id: The id of this ServiceAlert. # noqa: E501 :type: int """ self._id = id @property def type(self): """Gets the type of this ServiceAlert. # noqa: E501 alert | deviceNOC | html | serviceOverallStatus | sgraph | ngraph | serviceNOC | serviceSLA | bigNumber | gmap | serviceIndividualStatus | gauge | pieChart | ngraph | batchjob # noqa: E501 :return: The type of this ServiceAlert. # noqa: E501 :rtype: str """ return self._type @type.setter def type(self, type): """Sets the type of this ServiceAlert. alert | deviceNOC | html | serviceOverallStatus | sgraph | ngraph | serviceNOC | serviceSLA | bigNumber | gmap | serviceIndividualStatus | gauge | pieChart | ngraph | batchjob # noqa: E501 :param type: The type of this ServiceAlert. # noqa: E501 :type: str """ if type is None: raise ValueError("Invalid value for `type`, must not be `None`") # noqa: E501 self._type = type @property def timescale(self): """Gets the timescale of this ServiceAlert. # noqa: E501 The default timescale of the widget # noqa: E501 :return: The timescale of this ServiceAlert. # noqa: E501 :rtype: str """ return self._timescale @timescale.setter def timescale(self, timescale): """Sets the timescale of this ServiceAlert. The default timescale of the widget # noqa: E501 :param timescale: The timescale of this ServiceAlert. # noqa: E501 :type: str """ self._timescale = timescale @property def device_id(self): """Gets the device_id of this ServiceAlert. # noqa: E501 :return: The device_id of this ServiceAlert. # noqa: E501 :rtype: int """ return self._device_id @device_id.setter def device_id(self, device_id): """Sets the device_id of this ServiceAlert. :param device_id: The device_id of this ServiceAlert. # noqa: E501 :type: int """ if device_id is None: raise ValueError("Invalid value for `device_id`, must not be `None`") # noqa: E501 self._device_id = device_id @property def device_display_name(self): """Gets the device_display_name of this ServiceAlert. # noqa: E501 :return: The device_display_name of this ServiceAlert. # noqa: E501 :rtype: str """ return self._device_display_name @device_display_name.setter def device_display_name(self, device_display_name): """Sets the device_display_name of this ServiceAlert. :param device_display_name: The device_display_name of this ServiceAlert. # noqa: E501 :type: str """ self._device_display_name = device_display_name def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(ServiceAlert, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ServiceAlert): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
[ "jeremy.tang@logicmonitor.com" ]
jeremy.tang@logicmonitor.com
47f279fb0f8e4364b04cdc930d764cfe6abe6001
7d257e13bb2ebe6621e58483f7412fc91b6e641e
/assesmentmanagementsystem/Flask/web_app/git_API_functions.py
580fe4293dca944abe8601093a835054b7be7ab6
[]
no_license
19059019/HonoursProject
da625435a79e8efd85222d511f0e07b25068953f
12fbc29b08fe642b3115e1c423c501ae41550cd2
refs/heads/master
2022-12-26T03:09:39.138365
2020-03-20T12:56:54
2020-03-20T12:56:54
248,755,004
0
0
null
2022-12-08T07:26:10
2020-03-20T12:54:03
Python
UTF-8
Python
false
false
152
py
from config import * import gitlab GIT_SERVER = config["git_server"] TOKEN = config["git_token"] gl = gitlab.Gitlab(GIT_SERVER, private_token=TOKEN)
[ "mikesheep24@gmail.com" ]
mikesheep24@gmail.com
2ae16a9e9e78108fc155c5ad03fae33bc317ad74
d63222abe326a3c8debd59bb8d24cb7eab3de09e
/leetcode/mock-interviews/reorganize_string/solve2.py
457e7f2208383c86f7b71461edd8321eeb4e2c1e
[]
no_license
tariqrahiman/pyComPro
91f47e93eb0a077d489659fcf0a75d5c1a65fc17
86ec13f47506a2495ab6b6bbb58d4e8b2a21538b
refs/heads/master
2022-02-10T04:15:40.194828
2019-06-16T10:22:38
2019-06-16T10:22:38
null
0
0
null
null
null
null
UTF-8
Python
false
false
948
py
class Solution(object): def reorganizeString(self, S): count_letter = [[0, i] for i in xrange(25)] for char in S: count_letter[ord(char) - 97][0] += 1 count_letter.sort(reverse=True) count_letter = [k for k in count_letter if k[0] > 0] res = [""] def decrease(index): res[0] += chr(count_letter[index][1] + 97) count_letter[index][0] -= 1 if count_letter[index][0] == 0: del count_letter[index] print count_letter while len(count_letter) > 1: i = len(count_letter) - 1 while i > 0: for _ in xrange(count_letter[i][0]): decrease(i); decrease(i - 1) i -= 2 print res[0] print count_letter if len(count_letter) == 1: if count_letter[0][0] != 1: return " " return chr(count_letter[0][1] + 97) + res[0] return res[0]
[ "alexsolbiati@hotmail.it" ]
alexsolbiati@hotmail.it
8b4b8b5b6d763fd2a7db57022a79bde58116674a
9692a20a1e7a224a72785e4495f31421639b9f3b
/frex/stores/sparql_queryable.py
ca7711df4642f8043fbcf8e36450204ce9c9d5df
[]
no_license
solashirai/FREx
6b0cb040930761a0e269f4591d7dde36e3f636d1
36ad09a0cb0020661ee990c7800bafd110e2ec04
refs/heads/master
2023-08-14T08:49:49.270281
2021-09-29T14:58:23
2021-09-29T14:58:23
291,760,109
0
0
null
2021-09-24T22:41:19
2020-08-31T15:57:47
Python
UTF-8
Python
false
false
526
py
from abc import ABC, abstractmethod from rdflib.query import Result class SparqlQueryable(ABC): """ SparqlQueryable is the base class for stores that can be queried in some way using SPARQL queries. """ @abstractmethod def query(self, *, sparql: str) -> Result: """ Query the sparql queryable and retrieve a result. :param sparql: A string containing valid SPARQL to query. :return: A Result containing the result from calling the SPARQL query. """ pass
[ "solashakashirai@gmail.com" ]
solashakashirai@gmail.com
5b215f0420808f7de11704061dc9500c57c7f5fa
d57b817ea296970727616dbd6dcdde51479abeef
/Rajesh/Calculator.py
d60bcd8e7357ccdabe20b0541c1f52f1a2a7f9bb
[]
no_license
sharedrepo2021/AWS_Python
fefa0e6564621302c07006222856dde2204af06e
a1f8a6848ce62b6411e9a54fc63f6a41d8bfc875
refs/heads/main
2023-03-07T12:45:47.755159
2021-02-16T22:03:50
2021-02-16T22:03:50
330,518,230
0
0
null
null
null
null
UTF-8
Python
false
false
3,319
py
class Calculator: def __init__(self, number1, number2, result, chc, div0): self.a = number1 self.b = number2 self.result = result self.choice = chc self.d = div0 def add(self): self.result = self.a + self.b return self.result def sub(self): self.result = self.a - self.b return self.result def mul(self): self.result = self.a * self.b return self.result def div(self): self.d = "Cannot Divide By 0" if self.b == 0: self.result = self.d else: self.result = self.a / self.b self.d = 0 return self.result def getinput(self): self.a = int(input("Enter 1st Number : ")) self.b = int(input("Enter 2nd Number : ")) def optiondisplay(self): print("\n") print("Select Options : 1 . Addition") print(" : 2 . Subtraction") print(" : 3 . Multiplication") print(" : 4 . Division") print(" : 5 . Exit") print(" : 6 . Change Input") self.choice = int(input("Choice : ")) print("\n\n") if __name__ == "__main__": a = 0 b = 0 r = 0 choice = 0 d = 0 calc1 = Calculator(a, b, r, choice, d) prev1 = Calculator(a, b, r, choice, d) calc1.optiondisplay() while calc1.choice > 6: print("Invalid choice") calc1.optiondisplay() if calc1.choice != 6: calc1.getinput() else: prev1.choice = calc1.choice while calc1.choice != 5: if calc1.choice == 1: print("\n") print(" " + str(calc1.a) + " +") print(" " + str(calc1.b)) print("---------") print(" " + str(calc1.add())) prev1.choice = calc1.choice calc1.optiondisplay() elif calc1.choice == 2: print("\n") print(" " + str(calc1.a) + " -") print(" " + str(calc1.b)) print("---------") print(" " + str(calc1.sub())) prev1.choice = calc1.choice calc1.optiondisplay() elif calc1.choice == 3: print("\n") print(" " + str(calc1.a) + " *") print(" " + str(calc1.b)) print("---------") print(" " + str(calc1.mul())) prev1.choice = calc1.choice calc1.optiondisplay() elif calc1.choice == 4: print("\n") print(" " + str(calc1.a) + " /") print(" " + str(calc1.b)) print("---------") print(" " + str(calc1.div())) prev1.choice = calc1.choice if calc1.d == 0: calc1.optiondisplay() else: print("\n") calc1.getinput() elif calc1.choice == 5: exit() elif calc1.choice == 6: calc1.getinput() if prev1.choice >= 6: calc1.optiondisplay() else: calc1.choice = prev1.choice else: print("Invalid choice") prev1.choice = calc1.choice calc1.optiondisplay()
[ "rajeshvarghese@gmail.com" ]
rajeshvarghese@gmail.com
24b225f065ed151eb22a92e8b8d904ab8f8a5b5d
ad01faab6dd663dc5193eb8383fdc2d24c2df23d
/_flask/_flask/src/models.py
65bcffc85e3d1501298f09252d2b8c292996163d
[]
no_license
jurgeon018/snippets
585db91b8120076b37deaa37393b34f7c61fec66
e0ab24a99791c3b25422a3208f02919cf98ca084
refs/heads/master
2023-05-14T12:31:48.139452
2023-01-23T03:33:41
2023-01-23T03:33:41
222,001,233
0
0
null
2023-05-01T22:16:48
2019-11-15T20:51:27
Python
UTF-8
Python
false
false
2,368
py
from flask_security import UserMixin, RoleMixin from datetime import datetime import re from app import db def slugify(s): pattern = r'[^\w+]' return re.sub(pattern, '-', str(s)) post_tags = db.Table( 'post_tags', db.Column('post_id', db.Integer, db.ForeignKey('post.id')), db.Column('tag_id', db.Integer, db.ForeignKey('tag.id')) ) roles_users = db.Table( 'roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('user.id')), db.Column('role_id', db.Integer(), db.ForeignKey('role.id')) ) class SaveMixin: def save(self, *args, **kwargs): db.session.add(self) db.session.commit() class User(db.Model, SaveMixin, UserMixin): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(100), unique=True) password = db.Column(db.String(100)) active = db.Column(db.Boolean()) roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic')) class Role(db.Model, SaveMixin, RoleMixin): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), unique=True) description = db.Column(db.String(255)) class Post(db.Model, SaveMixin): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(140)) slug = db.Column(db.String(140), unique=True) body = db.Column(db.Text()) created = db.Column(db.DateTime, default=datetime.now) tags = db.relationship('Tag', secondary=post_tags, backref=db.backref('posts'), lazy='dynamic') def __init__(self, *args, **kwargs): super(Post, self).__init__(*args, **kwargs) self.generate_slug() def generate_slug(self): if self.title: self.slug = slugify(self.title) def __repr__(self): return '<Post id: {}, title: {}'.format(self.id, self.title) class Tag(db.Model, SaveMixin): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100)) slug = db.Column(db.String(100)) def __init__(self, *args, **kwargs): super(Tag, self).__init__(*args, **kwargs) self.slug = slugify(self.name) def __repr__(self): return '<Tag id: {}, name: {}>'.format(self.id, self.name)
[ "jurgeon018@gmail.com" ]
jurgeon018@gmail.com
e17959a66a7bad08e04d87207e82ac8682bbc421
2fe9381ea17e68572521370de6d3519ed1f8a669
/mysite/game/views.py
ebba74a15b4cfd45bf30f1b1106a314f7e508544
[]
no_license
vittesharora/sarcasm-sample
5909fd333e30e8cd430d98b0a69313be6030f682
aa332f9a74fe6179c61bc8f29867d69996509b3e
refs/heads/master
2020-05-27T15:02:27.258571
2019-05-26T11:04:28
2019-05-26T11:04:28
188,670,761
0
0
null
null
null
null
UTF-8
Python
false
false
789
py
from django.shortcuts import render, get_object_or_404, redirect from .models import Question from .forms import SignUpForm from django.contrib.auth.forms import UserCreationForm # Create your views here. def gaming(request): questions=Question.objects.all() return render(request, 'game/home.html', {'questions':questions}) def detail(request, pk): question=get_object_or_404(Question, pk=pk) return render(request, 'game/detail.html',{'pk':pk,'question':question}) def register(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() return redirect('/game') else: form= SignUpForm() return render(request, 'game/register.html', {'form':form}) def opening(request): return render(request, 'game/opening.html',{})
[ "avittesh@gmaill.com" ]
avittesh@gmaill.com
7ce5a5a7e987b5117fe0c6627da59256dd274079
09f0505f3ac1dccaf301c1e363423f38768cc3cc
/r_DailyProgrammer/Hard/C261/__init__.py
7fb10a7e3f3dd524eca4b11a7704983484b081b8
[]
no_license
Awesome-Austin/PythonPractice
02212292b92814016d062f0fec1c990ebde21fe7
9a717f91d41122be6393f9fcd1a648c5e62314b3
refs/heads/master
2023-06-21T11:43:59.366064
2021-07-29T23:33:00
2021-07-29T23:33:00
270,854,302
0
0
null
2020-08-11T20:47:10
2020-06-08T23:24:09
Python
UTF-8
Python
false
false
63
py
#! python3 from r_DailyProgrammer.Hard.C261.main import main
[ "{ID}+{username}@users.noreply.github.com" ]
{ID}+{username}@users.noreply.github.com
f86e34acdf5f4cfe3017b4eb336412a36a9ee039
4df51c5b80555f04c93bc7af29ddf99621198b8f
/codechef_TheLeadGame.py
b2e9c98e7058a9a3d1202d727e97bab2829472dc
[]
no_license
Rup-Royofficial/Codechef_solutions
4752fdf2040a0bd4efaed075f34f65fdfcbc2872
62edb5e0cf3dfc7db68c98f23033b7d2e2007566
refs/heads/main
2023-06-24T07:40:30.848869
2021-07-22T15:47:44
2021-07-22T15:47:44
388,516,041
1
0
null
null
null
null
UTF-8
Python
false
false
873
py
n = int(input()) d = [] f = [] x = 0 y = 0 c_1 = [] c_2 = [] for i in range(n): a,b = map(int,input().split()) if a>b: c = a-b d.append(c) c_1.append(a) c_2.append(b) if b>a: e = b-a f.append(e) c_1.append(a) c_2.append(b) if sum(c_1)> sum(c_2): print(f"1 {max(d)}") if sum(c_2)>sum(c_1): print(f"2 {max(f)}") """ p1=[0] p2=[0] q1=0 q2=0 for i in range(int(input())): a,b=map(int,input().split()) q1+=a q2+=b s=q1-q2 if s>=0: p1.append(s) else: p2.append(-s) # print(p1,p2) p1=max(p1) p2=max(p2) if p1>=p2: print(1,p1) else: print(2,p2) """ """ this above code is the correct answer as per them""" """although the question is broken , i think """
[ "noreply@github.com" ]
noreply@github.com
9fa85e205aedaa36233270fd54d0d9466f74e4e1
bfc58d03880345345459d49d8c57d63cfc941554
/Z1.2.py
db7ede5e7af07896bfb434cd7678aaca70746544
[]
no_license
Gordey007/MADE
cf1684174cfd4b391beff624ee1dc1d2bc4e0ddd
db4d2a1e1f26970c7267f2ee368e22cafae9e178
refs/heads/main
2023-01-30T11:50:54.170479
2020-12-14T13:54:55
2020-12-14T13:54:55
321,359,343
1
0
null
null
null
null
UTF-8
Python
false
false
1,887
py
# многослойная модель персептрона для задачи двух окружностей from sklearn.datasets import make_circles from keras.models import Sequential from keras.layers import Dense from matplotlib import pyplot # # генерировать набор данных X, y = make_circles(n_samples=1000, noise=0.1, random_state=1) # разделить на поезд и проверить n_test = 500 trainX, testX = X[:n_test, :], X[n_test:, :] trainy, testy = y[:n_test], y[n_test:] # print("trainX") # for n in trainX: # print(n) # # print("trainy") # for n in trainy: # print(n) # # print("testX") # for n in testX: # print(n) # # print("testy") # for n in testy: # print(n) # определить модель model = Sequential() model.add(Dense(100, input_dim=2, activation='relu')) model.add(Dense(1, activation='sigmoid')) # составить модель model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # подходящая модель history = model.fit(trainX, trainy, validation_data=(testX, testy), epochs=300, verbose=0) # оценить модель _, train_acc = model.evaluate(trainX, trainy, verbose=0) _, test_acc = model.evaluate(testX, testy, verbose=0) print('Train: %.3f, Test: %.3f' % (train_acc, test_acc)) # потеря сюжета во время тренировки pyplot.subplot(211) pyplot.title('Loss') pyplot.plot(history.history['loss'], label='train') pyplot.plot(history.history['val_loss'], label='test') pyplot.legend() # точность сюжета во время тренировки pyplot.subplot(212) pyplot.title('Accuracy') pyplot.plot(history.history['accuracy'], label='train') pyplot.plot(history.history['val_accuracy'], label='test') pyplot.legend() pyplot.show()
[ "noreply@github.com" ]
noreply@github.com
5e533e4548295d223cc6fd1155ddcb18b11144ec
103e04fe44bf613bbc4c93e7a2d4d044bdca947f
/mysite/urls.py
5e05c26c34cd5c0972403ad74ece322765135b17
[]
no_license
fij0/my-first-blog
3bb00b5567fb8eaa3020948703705fd73923befa
91aff421e69ffb58c7c4142fc0b4cee9bc52826d
refs/heads/master
2016-09-12T16:28:01.698961
2016-04-23T19:22:01
2016-04-23T19:22:01
56,926,273
0
0
null
null
null
null
UTF-8
Python
false
false
181
py
from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'', include ('blog.urls')), ]
[ "fortigala@gmail.com" ]
fortigala@gmail.com
a39a4020e3c0bd37e28ab0cc5f23365d3101cb61
fbc6af0a6bd232f8501822ad75a75e397b4ee05e
/Convert CamelCase to Sname_case.py
922f56b6c3c133136a8a604e94a1277610cabebf
[]
no_license
DushyantVermaCS/Python-Tuts
2d0438974ed0425cd32f15351c758af14fa5fdc6
356a43be77f21cebff64be3c06130a09d932028e
refs/heads/main
2023-05-08T02:50:50.336586
2021-05-25T17:10:07
2021-05-25T17:10:07
370,689,589
0
0
null
null
null
null
UTF-8
Python
false
false
575
py
# Convert Lettrs from CamelCase to snake_case :>--------------------------------- ph = input() #input any phase fis = ph[0].lower() #first letter of phase letter = "" for word in ph[1: ]: if word.isupper(): word ="_"+word.lower() #print(word) letter += word print(fis+letter) ''' -----------------BY USING Replace Method--------------------------------------- text = input() for letter in text: if letter.isupper(): text = text.replace(letter, "_" + letter.lower(), 1) print(text) '''
[ "noreply@github.com" ]
noreply@github.com
c959f7846d359b08fddf15504810577c09e79d06
afa8d16eefad352022461d9752cc3fec7cddb0c0
/venv/Scripts/pip-script.py
c252ecb351b1c5da5afaf73ae6da2332c1fe2ae8
[]
no_license
vermamuskan/Sudoku_Solver
3252bbb0b0b39aa35fcef6fe3a8ab6883aff4c6e
0fff3b77c4eb3eaa0706806635f81c17d7dae131
refs/heads/master
2023-07-18T03:42:15.773716
2021-08-30T17:43:05
2021-08-30T17:43:05
276,735,689
0
0
null
null
null
null
UTF-8
Python
false
false
384
py
#!H:\untitled\venv\Scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip' __requires__ = 'pip==19.0.3' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_point('pip==19.0.3', 'console_scripts', 'pip')() )
[ "themuskanverma@gmail.com" ]
themuskanverma@gmail.com
552ab2bbd2ef44a5026c219a56b2ffd8ce677ca4
c73fc798764f40ea6fa466a573fb01223e367ce3
/recursion/dequeue.py
0cb394faf20083a3b1185caeaf1124bf8907044b
[]
no_license
mohitsh/python_work
b1385f62104aa6b932f5452ca5c2421526345455
223a802dea5cdb73f44a159856c7432983655668
refs/heads/master
2020-04-24T00:34:15.427060
2018-08-21T19:12:07
2018-08-21T19:12:07
37,491,449
0
0
null
null
null
null
UTF-8
Python
false
false
1,060
py
''' in this deque example I have considered position 0 to be FRONT in other deque exmaples like Palindrome checker last element has been considered as front. Usually first element is considered rear and last one is considered front. I have to manipulate 0 twice to make this code compatible with 0 as rear and last as Front so no worries! ''' class Deque: def __init__(self): self.items = [] def size(self): return len(self.items) def isEmpty(self): return self.items == [] def addFront(self,item): self.items.insert(0,item) def addRear(self,item): self.items.append(item) def removeFront(self): return self.items.pop(0) def removeRear(self): return self.items.pop() def show(self): print self.items d = Deque() print d.isEmpty() print d.size() d.addFront(1) d.addFront(2) d.addFront(3) print d.isEmpty() print d.size() d.show() d.addRear(10) d.addRear(11) d.addRear(12) d.show() print d.removeFront() print d.removeFront() print d.removeFront() d.show() print d.removeRear() print d.removeRear() print d.removeRear() d.show()
[ "mohitsh114@gmail.com" ]
mohitsh114@gmail.com
b13067dd270bc42aaa0289e9252634ac5e07ecc2
3f2ebe9b8c3a249de9b81e76fefcec82e1ab61c7
/Breaking4thwall/BreakFourthWall.py
d3f2a27d6e48d1722cec8a8527071390b1d82a45
[]
no_license
AlekseyPanas/BreakingFourthWall
b0b376fabddb899070c3f6b3fd587db8aa613e61
ee9fe4cfdcdbc0c6d6c0f1ec2086ccc750bf9426
refs/heads/main
2023-04-22T20:54:45.540394
2021-05-07T01:24:37
2021-05-07T01:24:37
364,835,823
0
0
null
null
null
null
UTF-8
Python
false
false
35,365
py
import pygame import copy import math import random import time pygame.init() class Game: FRICTION = 0.99 def __init__(self, fourth_wall=False, player_hp=None): self.RESET_GAME = False self.PAUSED = False self.WIN = False self.LOSS = False self.UNPAUSABLE = False self.IS_CUTSCENE = False self.CUTSCENE_STRING = "" # Will the boss pause the game when dying self.WILL_PAUSE = False if fourth_wall else random.choice([True, False, False, False]) self.BOSS = Boss(-1, 1) self.PLY = Player(-1, 1) # Current list, add queue list, and delete queue list for each item self.BULLETS = [] self.bullet_q = [] self.bullet_dq = [] self.SLASHES = [] self.slash_q = [] self.slash_dq = [] self.OTHER = [] self.other_q = [] self.other_dq = [] self.RESTART = Button((SIZE[0] / 2, SIZE[1] / 3), (0, 0), (80, 35), pygame.image.load("reset.png")) self.BACK = Button((SIZE[0] / 2, SIZE[1] / 4), (0, 0), (80, 35), pygame.image.load("back.png")) self.PAUSE = Button((SIZE[0] * .9, SIZE[1] * .1), (0, 0), (80, 35), pygame.image.load("pause.png")) self.PAUSED_TEXT = get_arial_font_bold(50).render("Game Paused", True, (0, 0, 0)).convert_alpha() self.WIN_TEXT = get_arial_font_bold(50).render("You Win!", True, (0, 100, 0)).convert_alpha() self.LOSS_TEXT = get_arial_font_bold(50).render("You Lost!", True, (100, 0, 0)).convert_alpha() if not fourth_wall: self.BOSS.add_dialogue("I WILL DESTROY YOU!!", 5, 10) else: self.IS_CUTSCENE = True self.CUTSCENE_STRING = "restart" self.BOSS.add_dialogue("And you really thought you had me there huh...", 5, 20) # Calculates how fast the player is doing damage to the boss. If bad enough, mouse will be bound self.damage_accum = 0 self.damage_dialogue = ["No more mousing around", "Now stay there!", "Stay!", "Don't move", "No more moving", "Try aiming now!"] self.bind_counter = 0 if player_hp is not None: hp = player_hp if hp < 500: hp = 500 self.PLY.update_health(hp) def cutscene_i1(self): # Boss moves towards point target = SIZE[0] / 2, SIZE[1] * .7 if not distance(target, self.BOSS.pos) < 30: y = target[1] - self.BOSS.pos[1] x = target[0] - self.BOSS.pos[0] h = math.sqrt(y ** 2 + x ** 2) y = (y / h) x = (x / h) self.BOSS.vel = (x, y) self.BOSS.update_physics(screen, self) if distance(target, self.BOSS.pos) < 30: self.BOSS.vel = (0, 0) return True return False def run_game(self, screen): print(self.damage_accum) # Manages damage accumulation if self.damage_accum > 0: self.damage_accum -= .3 if not self.PLY.is_mouse_bound else 1 if self.damage_accum < 0: self.damage_accum = 0 if self.damage_accum > 550: self.PLY.bind_mouse([random.randint(50, 550) for _ in range(2)]) self.bind_counter = 800 self.damage_accum = 0 self.BOSS.clear_dialogue() self.BOSS.add_dialogue(random.choice(self.damage_dialogue), 5, 25) if self.bind_counter > 0: self.bind_counter -= 1 if self.bind_counter == 0: self.PLY.unbind_mouse() # Manages all cutscenes using state machine with CUTSCENE_STRING if self.IS_CUTSCENE: if self.CUTSCENE_STRING == "restart": if not len(self.BOSS.dialogue_queue): self.IS_CUTSCENE = False elif self.CUTSCENE_STRING == "i_0": self.CUTSCENE_2nd_DIALOGUE_FLAG = True self.CUTSCENE_LASER = Laser(copy.copy(self.BOSS.pos), copy.copy(self.PAUSE.pos)) self.CUTSCENE_STRING = "i_-1" elif self.CUTSCENE_STRING == "i_-1": self.CUTSCENE_LASER.update(screen, self) self.CUTSCENE_LASER.render(screen, self) if self.cutscene_i1() and self.CUTSCENE_LASER.opacity <= 0: self.CUTSCENE_STRING = "i_-2" elif self.CUTSCENE_STRING == "i_-2": self.BOSS.add_dialogue("Whew, almost had me there!", 4, 25) self.BOSS.add_dialogue("What? You thought you're the only one who can pause?", 4, 25) self.BOSS.add_dialogue("Now Now, lets see what I can do here", 7, 25) self.BOSS.add_dialogue("Oh! I got an idea", 6, 17) self.CUTSCENE_STRING = "i_3" elif self.CUTSCENE_STRING == "i_1": self.CUTSCENE_2nd_DIALOGUE_FLAG = False if self.cutscene_i1(): self.CUTSCENE_STRING = "i_2" elif self.CUTSCENE_STRING == "i_2": self.BOSS.add_dialogue("Really? You're just gonna pause to give yourself a break?", 4, 15) self.BOSS.add_dialogue("I don't think so...", 10, 10) self.CUTSCENE_STRING = "i_3" elif self.CUTSCENE_STRING == "i_3": if not len(self.BOSS.dialogue_queue): self.CUTSCENE_STRING = "i_4" elif self.CUTSCENE_STRING == "i_4": self.CUTSCENE_LASER = Laser(copy.copy(self.BOSS.pos), copy.copy(self.RESTART.pos)) self.RESTART.height_vel = 5 self.RESTART.vel = ((random.randint(20, 40) / 10) * random.choice([-1, 1]), 1) self.CUTSCENE_STRING = "i_5" elif self.CUTSCENE_STRING == "i_5": self.CUTSCENE_LASER.update(screen, self) self.CUTSCENE_LASER.render(screen, self) if self.RESTART.height <= 0: self.RESTART.vel = (0, 0) self.CUTSCENE_COUNT = 20 self.CUTSCENE_STRING = "i_6" elif self.CUTSCENE_STRING == "i_6": if self.CUTSCENE_COUNT > 0: self.CUTSCENE_COUNT -= 1 else: self.CUTSCENE_STRING = "i_7" elif self.CUTSCENE_STRING == "i_7": if not self.CUTSCENE_2nd_DIALOGUE_FLAG: self.BOSS.add_dialogue("Careful not to restart! Mwahaha!!!", 8, 15) self.BOSS.add_dialogue("Oh.. And no more pausing!", 7, 10) else: self.BOSS.add_dialogue("The restart button might make things a little more balanced", 5, 17) self.BOSS.add_dialogue("Alright, no more pausing for both of us.!", 6, 13) self.CUTSCENE_STRING = "i_8" elif self.CUTSCENE_STRING == "i_8": if not len(self.BOSS.dialogue_queue): self.CUTSCENE_STRING = "i_9" elif self.CUTSCENE_STRING == "i_9": self.add_other(Laser(copy.copy(self.BOSS.pos), copy.copy(self.PAUSE.pos))) CUTSCENE_FRAGMENTS = fragmentate(self.PAUSE.image, self.PAUSE.pos) for frag in CUTSCENE_FRAGMENTS: frag.vel = random.randint(-40, 10) / 10, random.randint(-10, 40) / 10 self.add_other(CUTSCENE_FRAGMENTS[0]) self.add_other(CUTSCENE_FRAGMENTS[1]) self.PAUSED = False self.UNPAUSABLE = True self.IS_CUTSCENE = False print(self.WILL_PAUSE) # Checks for Cutscene conditions if not self.IS_CUTSCENE and (not self.UNPAUSABLE): if self.BOSS.health / self.BOSS.full_health <= 0.3 and self.WILL_PAUSE: self.IS_CUTSCENE = True self.PAUSED = True self.CUTSCENE_STRING = "i_0" elif self.PAUSED and self.BOSS.health / self.BOSS.full_health <= 0.6 and (not (self.WIN or self.LOSS)): print("OMG") self.IS_CUTSCENE = True self.CUTSCENE_STRING = "i_1" # Events if not self.IS_CUTSCENE: rem = [] for event in events: if event.type == pygame.MOUSEBUTTONDOWN and event.button == pygame.BUTTON_LEFT: # Pause Button Pauses Game if (not self.UNPAUSABLE) and self.PAUSE.is_clicked(event.pos): self.PAUSED = True rem.append(event) # Back button returns to game elif self.PAUSED and not (self.WIN or self.LOSS) and self.BACK.is_clicked(event.pos): self.PAUSED = False # Restart button restarts game elif (self.PAUSED or self.UNPAUSABLE) and self.RESTART.is_clicked(event.pos): self.RESET_GAME = True if self.UNPAUSABLE and (not (self.WIN or self.LOSS)): set_4th_wall_toggle(True, self.PLY.health) for event in rem: if event in events: events.remove(event) # Runs logic for boss and player self.BOSS.run_sprite(screen, self) self.PLY.run_sprite(screen, self) # Runs logic for bullets, slashes, and other objects for o in self.SLASHES + self.BULLETS + self.OTHER: o.run_sprite(screen, self) # Runs logic for buttons if self.PAUSED or self.UNPAUSABLE: self.RESTART.run_sprite(screen, self) # If the game is in the unpausable state, restart button chases mouse if self.UNPAUSABLE: y = pygame.mouse.get_pos()[1] - self.RESTART.pos[1] x = pygame.mouse.get_pos()[0] - self.RESTART.pos[0] h = math.sqrt(y ** 2 + x ** 2) y = (y / h) * 1.5 x = (x / h) * 1.5 self.RESTART.vel = (x, y) if self.PAUSED: if not (self.WIN or self.LOSS): self.BACK.run_sprite(screen, self) if self.WIN: screen.blit(self.WIN_TEXT, self.WIN_TEXT.get_rect(center=(SIZE[0] / 2, SIZE[1] / 5))) elif self.LOSS: screen.blit(self.LOSS_TEXT, self.LOSS_TEXT.get_rect(center=(SIZE[0] / 2, SIZE[1] / 5))) else: screen.blit(self.PAUSED_TEXT, self.PAUSED_TEXT.get_rect(center=(SIZE[0] / 2, SIZE[1] / 7))) if not self.UNPAUSABLE: self.PAUSE.run_sprite(screen, self) # Win conditions if self.PLY.health <= 0: self.LOSS = True self.PAUSED = True elif self.BOSS.health <= 0: self.WIN = True self.PAUSED = True # Runs object updater if not self.PAUSED and not self.IS_CUTSCENE: self.update_objects() def update_objects(self): # Decreases lifetime for all objects for obj in self.BULLETS + self.SLASHES + self.OTHER: obj.lifetime -= 1 # Removes dead objects by kill flag or by lifetime count self.BULLETS = [b for b in self.BULLETS if not b.kill and b.lifetime > 0] self.SLASHES = [s for s in self.SLASHES if not s.kill and s.lifetime > 0] self.OTHER = [o for o in self.OTHER if not o.kill and o.lifetime > 0] # Removes objects in delete queues for b in self.bullet_dq: self.BULLETS.remove(b) for s in self.slash_dq: self.SLASHES.remove(s) for o in self.other_dq: self.OTHER.remove(o) # Adds new objects for b in self.bullet_q: self.BULLETS.append(b) for s in self.slash_q: self.SLASHES.append(s) for o in self.other_q: self.OTHER.append(o) # Clears queues self.bullet_q = [] self.bullet_dq = [] self.slash_q = [] self.slash_dq = [] self.other_q = [] self.other_dq = [] # Add and delete methods for all object types def add_bullet(self, bullet): self.bullet_q.append(bullet) def add_slash(self, slash): self.slash_q.append(slash) def add_other(self, other): self.other_q.append(other) def delete_bullet(self, bullet): self.bullet_dq.append(bullet) def delete_slash(self, slash): self.slash_dq.append(slash) def delete_other(self, other): self.other_dq.append(other) class Object: def __init__(self, lifetime, z_order, tags): self.lifetime = lifetime self.kill = False # Draw order self.z_order = z_order # Set of string tags that can identify an object self.tags = set(tags) @staticmethod def rotate(image, rect, angle): """Rotate the image while keeping its center.""" # Rotate the original image without modifying it. new_image = pygame.transform.rotate(image, angle) # Get a new rect with the center of the old rect. rect = new_image.get_rect(center=rect.center) return new_image, rect def run_sprite(self, screen, game): self.render(screen, game) if not game.PAUSED and not game.IS_CUTSCENE: self.update(screen, game) def render(self, screen, game): pass def update(self, screen, game): pass class Button(Object): BUTTON_GRAVITY = 0.2 def __init__(self, pos, vel, size, image): super().__init__(0, 0, {}) # Position of center of button. self.pos = list(pos) self.vel = list(vel) # For popping effect when knocked out of pause menu self.height = 0 self.height_vel = 0 # Width/height of image and the loaded image. self.size = size self.image = pygame.transform.scale(image, (size[0], size[1])) self.button_rect = self.image.get_rect(center=self.pos) self.button_state = "static" def run_sprite(self, screen, game): self.render(screen, game) self.update(screen, game) def render(self, screen, game): screen.blit(self.image, self.button_rect) def update(self, screen, game): self.pos[0] += self.vel[0] self.pos[1] += self.vel[1] self.height += self.height_vel self.height_vel -= Button.BUTTON_GRAVITY if self.height < 0: self.height = 0 self.height_vel = 0 self.button_rect.center = (self.pos[0], self.pos[1] - self.height) def jump(self, height_vel): self.height_vel = height_vel def is_clicked(self, pos): return self.button_rect.collidepoint(pos) class Boss(Object): SPEED = 2 def __init__(self, lifetime, z_order): super().__init__(lifetime, z_order, {}) self.pos = [SIZE[1] / 4, SIZE[1] / 2] self.radius = 20 self.color = (255, 0, 0) self.vel = [0, 0] self.dialogue_queue = [] # {"text": "hello", "delay": 5, "total_lifetime": 40} self.current_text_idx = [0] self.rendered_texts = [] self.current_text = [] self.full_health = 5000 self.health = 0 self.health_text = None self.update_health(self.full_health) # Always counts down if above 0. Only shows hp above zero. Increase when taken damage to show hp self.show_hp = 100 self.textbox_surf = pygame.Surface((self.radius * 7, self.radius * 5), pygame.SRCALPHA, 32) pygame.draw.rect(self.textbox_surf, (200, 200, 200), pygame.Rect(0, 0, self.radius * 7, self.radius * 4.5)) pygame.draw.polygon(self.textbox_surf, (200, 200, 200), ((self.radius*3, self.radius * 4.5), (self.radius*4, self.radius * 4.5), (self.radius*3.5, self.radius*5))) self.textbox_surf = self.textbox_surf.convert_alpha() self.dialogue_size = self.radius * .7 self.dialogue_font = get_arial_font(int(self.dialogue_size)) self.dialogue_gap = self.radius * .05 self.dialogue_max_line_width = self.textbox_surf.get_rect().width * 0.8 def add_dialogue(self, text, delay, extra_lifetime): self.dialogue_queue.append({"text": text, "delay": delay, "total_lifetime": len(text) + extra_lifetime}) def clear_dialogue(self): self.dialogue_queue = [] def run_sprite(self, screen, game): self.render(screen, game) if not game.PAUSED and not game.IS_CUTSCENE: self.update(screen, game) self.run_dialogue(screen, game) def run_dialogue(self, screen, game): # Resets text if not len(self.dialogue_queue): self.current_text_idx = [0] self.rendered_texts = [] self.current_text = [] else: cur_dial = self.dialogue_queue[0] text = cur_dial["text"] # Calculates text if not len(self.current_text): split_words = text.split() split_words = [i if idx == len(split_words) - 1 else (i + " ") for idx, i in enumerate(split_words)] while True: # Is the inner loop done finish_inner = False # The word at which to end slicing word_cutoff = 1 if not len(split_words): break while not finish_inner: # Gets all words up to word_cutoff and strips the last word removing the trailing space current_line = split_words[:word_cutoff] current_line[-1] = current_line[-1].strip() # Checks how long this modified line is line_length = self.dialogue_font.size("".join(current_line))[0] # If the modified line is too long or the end of the list has been reached: if line_length > self.dialogue_max_line_width or word_cutoff > len(split_words): # Go back a step to the word cut_off where it wasnt too long word_cutoff -= 1 # Recreate that old line current_line = split_words[:word_cutoff] current_line[-1] = current_line[-1].strip() # Add the new line to the dialogue list self.current_text.append("".join(current_line)) # Remove the added line by slicing up to the word count split_words = split_words[word_cutoff:] # End the inner loop finish_inner = True else: # If all is good, move to next word word_cutoff += 1 # Shifts letter if ticks % cur_dial["delay"] == 0: # Deals with indexing of the current letter in each sentence self.current_text_idx[-1] += 1 if not len(self.current_text_idx) > len(self.current_text): if self.current_text_idx[-1] >= len(self.current_text[len(self.current_text_idx) - 1]): self.current_text_idx[-1] -= 1 self.current_text_idx.append(0) if not len(self.current_text_idx) > len(self.current_text): # Renders new text self.rendered_texts = [] for idx, i in enumerate(self.current_text_idx): self.rendered_texts.append(self.dialogue_font.render(self.current_text[idx][:i+1], True, (20, 0, 0))) # Deletes if sum(self.current_text_idx) >= cur_dial["total_lifetime"]: self.dialogue_queue.pop(0) self.current_text_idx = [0] self.rendered_texts = [] self.current_text = [] def render(self, screen, game): pygame.draw.circle(screen, self.color, self.pos, self.radius) if self.show_hp > 0: screen.blit(self.health_text, self.health_text.get_rect(center=(self.pos[0], self.pos[1] + self.radius*1.5))) if len(self.dialogue_queue): # Render text box screen.blit(self.textbox_surf, self.textbox_surf.get_rect(center=(self.pos[0], self.pos[1] - self.radius*3.5))) # Render text if len(self.rendered_texts): dialogue_box_center_height = self.pos[1] - self.radius * 3.5 total_height = len(self.rendered_texts) * (self.dialogue_size + self.dialogue_gap) shift_back_constant = self.dialogue_size / 2 + self.dialogue_gap start_height = dialogue_box_center_height - (total_height / 2) for i in range(len(self.rendered_texts)): screen.blit(self.rendered_texts[i], self.rendered_texts[i].get_rect(center=(self.pos[0], start_height + (self.dialogue_size + self.dialogue_gap) * (i + 1) - shift_back_constant))) def update_health(self, health): self.health = health self.health_text = get_arial_font(13).render(str(self.health), True, (225, 0, 0)) def take_damage(self, game, damage): self.update_health(self.health - damage) game.add_other(InflateSurface(200, 0, {}, get_damage_surface(damage), .5, 1.5, 50, copy.copy(self.pos), True, vel=(random.randint(-10, 10) / 10, -2))) self.show_hp = 100 game.damage_accum += 20 def update(self, screen, game): self.run_AI(screen, game) self.update_physics(screen, game) def update_physics(self, screen, game): self.pos[0] += self.vel[0] * self.SPEED self.pos[1] += self.vel[1] * self.SPEED if self.show_hp > 0: self.show_hp -= 1 def run_AI(self, screen, game): x = game.PLY.pos[0] + game.PLY.vel[0] * 50 - self.pos[0] y = game.PLY.pos[1] + game.PLY.vel[1] * 50 - self.pos[1] h = math.sqrt(y ** 2 + x ** 2) try: x = (x / h) * 5 y = (y / h) * 5 except: x = 0 y = 0 x += random.uniform(-1, 1) y += random.uniform(-1, 1) if ticks % 5 == 0: if distance(self.pos, game.PLY.pos) < (self.radius + game.PLY.radius) * 4: game.add_slash(Slash(False, (100, 0, 100), [self.pos[0] + x*10, self.pos[1] + y*10])) else: game.add_bullet(Bullet(copy.copy(self.pos), (x, y), False)) self.vel = [0, 0] vel = [game.PLY.pos[0] - self.pos[0], game.PLY.pos[1] - self.pos[1]] try: vel = [vel[0] / math.sqrt(vel[0] ** 2 + vel[1] ** 2), vel[1] / math.sqrt(vel[0] ** 2 + vel[1] ** 2)] except: vel = [0, 0] self.vel[0] += vel[0] self.vel[1] += vel[1] count = 0 for bullet in game.BULLETS: if bullet.isPlayer: a = +bullet.vel[1] b = -bullet.vel[0] c = +bullet.vel[0] * bullet.pos[1] - bullet.vel[1] * bullet.pos[0] x = (b * (+b * self.pos[0] - a * self.pos[1]) - a * c) / (a ** 2 + b ** 2) y = (a * (-b * self.pos[0] + a * self.pos[1]) - b * c) / (a ** 2 + b ** 2) dist = distance(self.pos, [x, y]) if dist < (self.radius + bullet.radius) * 1.5: count += 1 vel = [x - self.pos[0], y - self.pos[1]] try: vel = [vel[0] / math.sqrt(vel[0] ** 2 + vel[1] ** 2), vel[1] / math.sqrt(vel[0] ** 2 + vel[1] ** 2)] except: vel = [0, 0] self.vel[0] += -vel[0] / count self.vel[1] += -vel[1] / count class Player(Object): SPEED = 4 def __init__(self, lifetime, z_order): super().__init__(lifetime, z_order, {}) self.pos = [SIZE[1] * 0.75, SIZE[1] / 2] self.radius = 10 self.color = (0, 0, 0) self.vel = [0, 0] self.health = 0 self.health_text = None self.update_health(2000) # Always counts down if above 0. Only shows hp above zero. Increase when taken damage to show hp self.show_hp = 100 # Mouse can be locked to a certain position self.is_mouse_bound = False self.mouse_bind_pos = (300, 300) def render(self, screen, game): pygame.draw.circle(screen, self.color, self.pos, self.radius) if self.show_hp > 0: screen.blit(self.health_text, self.health_text.get_rect(center=(self.pos[0], self.pos[1] + self.radius*1.5))) def update_health(self, health): self.health = health self.health_text = get_arial_font(10).render(str(self.health), True, (200, 0, 0)) def bind_mouse(self, pos): self.is_mouse_bound = True self.mouse_bind_pos = tuple(pos) def unbind_mouse(self): self.is_mouse_bound = False def take_damage(self, game, damage): self.update_health(self.health - damage) game.add_other(InflateSurface(200, 0, {}, get_damage_surface(damage), .5, 1.5, 50, copy.copy(self.pos), True, vel=(random.randint(-10, 10) / 10, -2))) self.show_hp = 100 def update(self, screen, game): self.pos[0] += self.vel[0] self.pos[1] += self.vel[1] if self.show_hp > 0: self.show_hp -= 1 self.event_handle(screen, game) # Bind the mouse to a certain location if self.is_mouse_bound: pygame.mouse.set_pos(self.mouse_bind_pos) # Draws binding circles every 5 ticks (visual effect) if ticks % 15 == 0: game.add_other(BindCircle(self.mouse_bind_pos)) def event_handle(self, screen, game): for event in events: if event.type == pygame.MOUSEBUTTONDOWN: # Shooty shoot if event.button == pygame.BUTTON_LEFT: y = event.pos[1] - self.pos[1] x = event.pos[0] - self.pos[0] h = math.sqrt(y ** 2 + x ** 2) y = (y / h) * 5 x = (x / h) * 5 game.add_bullet(Bullet(copy.copy(self.pos), (x + self.vel[0]*.1, y + self.vel[1]*.1), True)) # Slashy Slash elif event.button == pygame.BUTTON_RIGHT: mouse_pos = pygame.mouse.get_pos() y = mouse_pos[1] - self.pos[1] x = mouse_pos[0] - self.pos[0] h = math.sqrt(y ** 2 + x ** 2) y = (y / h) * 20 x = (x / h) * 20 game.add_slash(Slash(True, (100, 100, 0), [self.pos[0] + x, self.pos[1] + y])) # ASWD Movement self.vel = [(-self.SPEED if pygame.key.get_pressed()[pygame.K_a] else 0) + (self.SPEED if pygame.key.get_pressed()[pygame.K_d] else 0), (self.SPEED if pygame.key.get_pressed()[pygame.K_s] else 0) + (-self.SPEED if pygame.key.get_pressed()[pygame.K_w] else 0)] class Bullet(Object): def __init__(self, pos, vel, isPlayerBullet): super().__init__(150, 0, {}) self.isPlayer = isPlayerBullet self.pos = list(pos) self.radius = 3 self.color_bs = (150, 0, 0) self.color_pl = (200, 200, 0) self.vel = list(vel) def update(self, screen, game): self.pos[0] += self.vel[0] self.pos[1] += self.vel[1] # Collision Logic if self.isPlayer: if distance(self.pos, game.BOSS.pos) <= game.BOSS.radius + self.radius: game.BOSS.take_damage(game, random.randint(20, 55)) game.delete_bullet(self) else: if distance(self.pos, game.PLY.pos) <= game.PLY.radius + self.radius: game.PLY.take_damage(game, random.randint(5, 35)) game.delete_bullet(self) def render(self, screen, game): pygame.draw.circle(screen, self.color_pl if self.isPlayer else self.color_bs, self.pos, self.radius) class InflateSurface(Object): def __init__(self, lifetime, z_order, tags, surface, start_scale, stop_scale, scale_time, pos, fade=False, initial_opacity=255, delay_inflation=0, vel=(0, 0), angle_vel=0.0): super().__init__(lifetime, z_order, tags) self.surface_rect = surface.get_rect() self.pos = list(pos) self.vel = vel self.angle = 0 self.angle_vel = angle_vel self.start_scale = (self.surface_rect.w * start_scale, self.surface_rect.h * start_scale) self.stop_scale = (self.surface_rect.w * stop_scale, self.surface_rect.h * stop_scale) self.scale_time = scale_time self.current_scale = list(copy.copy(self.start_scale)) self.scale_increment = ((self.stop_scale[0] - self.start_scale[0]) / self.scale_time, (self.stop_scale[1] - self.start_scale[1]) / self.scale_time) self.surface = pygame.Surface(self.surface_rect.size, pygame.SRCALPHA, 32).convert_alpha() self.surface.blit(surface, (0, 0)) self.opacity = initial_opacity self.fade_increment = (self.opacity + 1) / self.scale_time self.fade = fade # Delays inflation for a given amount of time self.delay_inflation = delay_inflation def update(self, screen, game): if self.delay_inflation == 0: if self.current_scale[0] < self.stop_scale[0]: self.current_scale[0] += self.scale_increment[0] self.current_scale[1] += self.scale_increment[1] if self.fade: self.opacity -= self.fade_increment if self.angle_vel: self.angle += self.angle_vel self.pos[0] += self.vel[0] self.pos[1] += self.vel[1] self.more_logic(screen, game) else: self.delay_inflation -= 1 def more_logic(self, screen, game): pass def render(self, screen, game): if self.opacity > 0: new_surf = pygame.transform.scale(self.surface, [int(x) for x in self.current_scale]).convert_alpha() if self.angle_vel: new_surf = pygame.transform.rotate(new_surf, self.angle).convert_alpha() rect = new_surf.get_rect() rect.center = self.pos if self.fade: new_surf.fill((255, 255, 255, self.opacity if self.opacity >= 0 else 0), None, pygame.BLEND_RGBA_MULT) screen.blit(new_surf, rect) class Slash(InflateSurface): def __init__(self, isPlayerSlash, color, pos): surf = pygame.Surface((160, 160), pygame.SRCALPHA, 32).convert_alpha() pygame.draw.circle(surf, color, (80, 80), 80) super().__init__(200, 5, {}, surf, .01, 1, 30, pos, True) self.isPlayer = isPlayerSlash self.has_hit = False def more_logic(self, screen, game): # Collision logic if not self.has_hit: if self.isPlayer: if distance(self.pos, game.BOSS.pos) <= game.BOSS.radius + self.surface_rect.width / 3: game.BOSS.take_damage(game, random.randint(25, 80)) self.has_hit = True else: if distance(self.pos, game.PLY.pos) <= game.PLY.radius + self.surface_rect.width / 3: game.PLY.take_damage(game, random.randint(5, 80)) self.has_hit = True class BindCircle(InflateSurface): def __init__(self, pos): surf = pygame.Surface((50, 50), pygame.SRCALPHA, 32).convert_alpha() pygame.draw.circle(surf, (0, 0, 255), (25, 25), 25, 2) super().__init__(100, 5, {}, surf, .6, 1.2, 28, pos, True, initial_opacity=150) class Laser(InflateSurface): def __init__(self, start, end): size = abs(end[0] - start[0]), abs(end[1] - start[1]) surf = pygame.Surface(size, pygame.SRCALPHA, 32) new_start = [0, 0] new_end = [0, 0] if end[1] > start[1]: new_end[1] = size[1] new_start[1] = 0 else: new_end[1] = 0 new_start[1] = size[1] if end[0] > start[0]: new_end[0] = size[0] new_start[0] = 0 else: new_end[0] = 0 new_start[0] = size[0] pygame.draw.line(surf, (255, 0, 0), new_start, new_end, 5) surf = surf.convert_alpha() super().__init__(100, -1, {}, surf, 1, 1, 50, (start[0] + (end[0] - start[0]) / 2, start[1] + (end[1] - start[1]) / 2), fade=True) # Cuts the given surface in half and returns 2 flying inflating surfaces for the halves def fragmentate(surf, center): height = surf.get_height() width = surf.get_width() / 2 pos1 = center[0] - width / 2, center[1] pos2 = center[0] + width / 2, center[1] surface1 = pygame.Surface((width, height), pygame.SRCALPHA, 32) surface1.blit(surf, (0, 0)) surface1 = surface1.convert_alpha() surface2 = pygame.Surface((width, height), pygame.SRCALPHA, 32) surface2.blit(surf, (-width, 0)) surface2 = surface2.convert_alpha() return (InflateSurface(150, -1, {}, surface1, 1, 1.2, 100, pos1, fade=True, angle_vel=(random.randint(-30, 30) / 10)), InflateSurface(150, -1, {}, surface2, 1, 1.2, 100, pos2, fade=True, angle_vel=(random.randint(-30, 30) / 10))) def distance(p, q): return math.sqrt((q[0] - p[0]) ** 2 + (q[1] - p[1]) ** 2) def get_arial_font(size): return pygame.font.SysFont("Arial", size, False) def get_arial_font_bold(size): return pygame.font.SysFont("Arial", size, True) def get_damage_surface(damage): return get_arial_font_bold(int(20 + damage / 30)).render(str(damage), True, (255, 0, 0)) fps = 0 last_fps_show = 0 clock = pygame.time.Clock() SIZE = (600, 600) screen = pygame.display.set_mode(SIZE) GAME = Game() running = True events = [] ticks = 0 set_4th_wall = False player_hp_store = 0 def set_4th_wall_toggle(bool, player_hp): global set_4th_wall, player_hp_store set_4th_wall = bool player_hp_store = player_hp while running: screen.fill((255, 255, 255)) events = pygame.event.get() for event in events: if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): running = False GAME.run_game(screen) pygame.display.update() ticks += 1 if GAME.RESET_GAME: if set_4th_wall: GAME = Game(set_4th_wall, player_hp_store) set_4th_wall = False else: GAME = Game() # sets fps to a variable. can be set to caption any time for testing. last_fps_show += 1 if last_fps_show == 30: # every 30th frame: fps = clock.get_fps() pygame.display.set_caption("FPS: " + str(fps)) last_fps_show = 0 # fps max 60 clock.tick(60)
[ "panasaleksey3@gmail.com" ]
panasaleksey3@gmail.com
a27d7d0745d6d09b855f6a9cb674255fdb6a1ffa
d1b14f6a72c8a716594117143080fab004e937b0
/leetcode/LC1290.py
55f3df89e08487ad673f83b2fb2f88fafc65fcd4
[ "MIT" ]
permissive
vgb-codes/leetcode-cp-solutions
738a84a7e83ea323710c81477115ea540be4cf3e
f1953b10bf2854bc01a6fc18b300e4e2671291c7
refs/heads/master
2023-05-12T15:48:15.800467
2021-05-26T07:41:42
2021-05-26T07:41:42
260,933,699
1
0
null
null
null
null
UTF-8
Python
false
false
329
py
class Node: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def getDecimalValue(self, head: Node) -> int: num = head.val while head.next: num = num << 1 num = num | head.next.val head = head.next return num
[ "vijaya.gajanan@outlook.com" ]
vijaya.gajanan@outlook.com
28695cb41961f9b7f6d93c97584d9999c98e5d78
cb4c67ff2ad27834bed67f7e920a12fb1c545fcd
/tensorflow/python/keras/callbacks.py
f2feeb85a1e0db976a1c29e47257558ba40cc856
[ "Apache-2.0" ]
permissive
ahoneybun/tensorflow
b67668cc0d9375eaab3bee4ed0791626f6eac02d
5134e65300d1ac384eeb1f4ca72a011ad7225bc8
refs/heads/master
2020-03-26T00:53:51.554467
2018-08-13T13:36:55
2018-08-13T13:36:55
144,342,477
0
0
Apache-2.0
2018-08-13T13:36:56
2018-08-11T00:07:43
C++
UTF-8
Python
false
false
51,653
py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # pylint: disable=g-import-not-at-top """Callbacks: utilities called at certain points during model training. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from collections import deque from collections import Iterable from collections import OrderedDict import copy import csv import json import math import os import time import numpy as np import six from tensorflow.python.data.ops import iterator_ops from tensorflow.python.eager import context from tensorflow.python.framework import dtypes from tensorflow.python.keras import backend as K from tensorflow.python.keras.engine.training_utils import standardize_input_data from tensorflow.python.keras.utils.data_utils import Sequence from tensorflow.python.keras.utils.generic_utils import Progbar from tensorflow.python.ops import array_ops from tensorflow.python.ops import state_ops from tensorflow.python.ops import summary_ops_v2 from tensorflow.python.ops import variables from tensorflow.python.platform import tf_logging as logging from tensorflow.python.summary import summary as tf_summary from tensorflow.python.training import saver from tensorflow.python.util.tf_export import tf_export try: import requests except ImportError: requests = None def configure_callbacks(callbacks, model, do_validation=False, val_inputs=None, val_targets=None, val_sample_weights=None, batch_size=None, epochs=None, steps_per_epoch=None, samples=None, validation_steps=None, verbose=1, count_mode='steps'): """Configures callbacks for use in various training loops. Arguments: callbacks: List of Callbacks. model: Model being trained. do_validation: Whether or not validation loop will be run. val_inputs: Inputs to Model for validation loop. Can be any data format Keras accepts. val_targets: Targets for Model for validation loop. Can be any data format Keras accepts. val_sample_weights: Sample weights for Model for validation loop. Can be any data format Keras accepts. batch_size: Number of samples per batch. epochs: Number of epoch to train. steps_per_epoch: Number of batches to run per training epoch. samples: Number of training samples. validation_steps: Number of batches to run per validation epoch. verbose: int, 0 or 1. Keras logging verbosity to pass to ProgbarLogger. count_mode: One of 'steps' or 'samples'. Per-batch or per-sample count. Returns: Instance of CallbackList used to control all Callbacks. """ # Add additional callbacks model.history = History() stateful_metric_names = None if hasattr(model, 'stateful_metric_names'): stateful_metric_names = model.stateful_metric_names callbacks = [BaseLogger(stateful_metrics=stateful_metric_names) ] + (callbacks or []) + [model.history] if verbose: callbacks.append( ProgbarLogger(count_mode, stateful_metrics=stateful_metric_names)) callback_list = CallbackList(callbacks) # Set callback model callback_model = model._get_callback_model() # pylint: disable=protected-access if do_validation and val_inputs and not context.executing_eagerly(): # Need to create the test_function before start of the first epoch # because TensorBoard callback on_epoch_begin adds summary to the # list of fetches of the test_function callback_model._make_test_function() # pylint: disable=protected-access callback_list.set_model(callback_model) # Set callback parameters callback_metrics = [] # When we have deferred build scenario with iterator input, we will compile # when we standardize first batch of data. if model._is_compiled: # pylint: disable=protected-access callback_metrics = copy.copy(model.metrics_names) if do_validation: callback_metrics += ['val_' + n for n in model.metrics_names] if validation_steps is None and isinstance(val_inputs, Sequence): validation_steps = len(val_inputs) callback_params = { 'batch_size': batch_size, 'epochs': epochs, 'steps': steps_per_epoch, 'samples': samples, 'verbose': verbose, 'do_validation': do_validation, 'metrics': callback_metrics, 'validation_steps': validation_steps } callback_list.set_params(callback_params) # Pass validation data to callbacks if not val_inputs: val_data = [] elif _is_generator_like(val_inputs): val_data = val_inputs else: val_data = val_inputs + val_targets if val_sample_weights: val_data += val_sample_weights if model.uses_learning_phase and not isinstance(K.learning_phase(), int): val_data += [0.] for cbk in callbacks: cbk.validation_data = val_data callback_list.model.stop_training = False return callback_list def _is_generator_like(data): """Checks if data is a generator, Sequence, or Iterator.""" return (hasattr(data, 'next') or hasattr(data, '__next__') or isinstance( data, (Sequence, iterator_ops.Iterator, iterator_ops.EagerIterator))) class CallbackList(object): """Container abstracting a list of callbacks. Arguments: callbacks: List of `Callback` instances. queue_length: Queue length for keeping running statistics over callback execution time. """ def __init__(self, callbacks=None, queue_length=10): callbacks = callbacks or [] self.callbacks = [c for c in callbacks] self.queue_length = queue_length self.params = {} self.model = None def append(self, callback): self.callbacks.append(callback) def set_params(self, params): self.params = params for callback in self.callbacks: callback.set_params(params) def set_model(self, model): self.model = model for callback in self.callbacks: callback.set_model(model) def on_epoch_begin(self, epoch, logs=None): """Called at the start of an epoch. Arguments: epoch: integer, index of epoch. logs: dictionary of logs. """ logs = logs or {} for callback in self.callbacks: callback.on_epoch_begin(epoch, logs) self._delta_t_batch = 0. self._delta_ts_batch_begin = deque([], maxlen=self.queue_length) self._delta_ts_batch_end = deque([], maxlen=self.queue_length) def on_epoch_end(self, epoch, logs=None): """Called at the end of an epoch. Arguments: epoch: integer, index of epoch. logs: dictionary of logs. """ logs = logs or {} for callback in self.callbacks: callback.on_epoch_end(epoch, logs) def on_batch_begin(self, batch, logs=None): """Called right before processing a batch. Arguments: batch: integer, index of batch within the current epoch. logs: dictionary of logs. """ logs = logs or {} t_before_callbacks = time.time() for callback in self.callbacks: callback.on_batch_begin(batch, logs) self._delta_ts_batch_begin.append(time.time() - t_before_callbacks) delta_t_median = np.median(self._delta_ts_batch_begin) if (self._delta_t_batch > 0. and delta_t_median > 0.95 * self._delta_t_batch and delta_t_median > 0.1): logging.warning('Method on_batch_begin() is slow compared ' 'to the batch update (%f). Check your callbacks.', delta_t_median) self._t_enter_batch = time.time() def on_batch_end(self, batch, logs=None): """Called at the end of a batch. Arguments: batch: integer, index of batch within the current epoch. logs: dictionary of logs. """ logs = logs or {} if not hasattr(self, '_t_enter_batch'): self._t_enter_batch = time.time() self._delta_t_batch = time.time() - self._t_enter_batch t_before_callbacks = time.time() for callback in self.callbacks: callback.on_batch_end(batch, logs) self._delta_ts_batch_end.append(time.time() - t_before_callbacks) delta_t_median = np.median(self._delta_ts_batch_end) if (self._delta_t_batch > 0. and (delta_t_median > 0.95 * self._delta_t_batch and delta_t_median > 0.1)): logging.warning('Method on_batch_end() is slow compared ' 'to the batch update (%f). Check your callbacks.', delta_t_median) def on_train_begin(self, logs=None): """Called at the beginning of training. Arguments: logs: dictionary of logs. """ logs = logs or {} for callback in self.callbacks: callback.on_train_begin(logs) def on_train_end(self, logs=None): """Called at the end of training. Arguments: logs: dictionary of logs. """ logs = logs or {} for callback in self.callbacks: callback.on_train_end(logs) def __iter__(self): return iter(self.callbacks) @tf_export('keras.callbacks.Callback') class Callback(object): """Abstract base class used to build new callbacks. Attributes: params: dict. Training parameters (eg. verbosity, batch size, number of epochs...). model: instance of `keras.models.Model`. Reference of the model being trained. The `logs` dictionary that callback methods take as argument will contain keys for quantities relevant to the current batch or epoch. Currently, the `.fit()` method of the `Sequential` model class will include the following quantities in the `logs` that it passes to its callbacks: on_epoch_end: logs include `acc` and `loss`, and optionally include `val_loss` (if validation is enabled in `fit`), and `val_acc` (if validation and accuracy monitoring are enabled). on_batch_begin: logs include `size`, the number of samples in the current batch. on_batch_end: logs include `loss`, and optionally `acc` (if accuracy monitoring is enabled). """ def __init__(self): self.validation_data = None self.model = None def set_params(self, params): self.params = params def set_model(self, model): self.model = model def on_epoch_begin(self, epoch, logs=None): pass def on_epoch_end(self, epoch, logs=None): pass def on_batch_begin(self, batch, logs=None): pass def on_batch_end(self, batch, logs=None): pass def on_train_begin(self, logs=None): pass def on_train_end(self, logs=None): pass @tf_export('keras.callbacks.BaseLogger') class BaseLogger(Callback): """Callback that accumulates epoch averages of metrics. This callback is automatically applied to every Keras model. Arguments: stateful_metrics: Iterable of string names of metrics that should *not* be averaged over an epoch. Metrics in this list will be logged as-is in `on_epoch_end`. All others will be averaged in `on_epoch_end`. """ def __init__(self, stateful_metrics=None): super(BaseLogger, self).__init__() self.stateful_metrics = set(stateful_metrics or []) def on_epoch_begin(self, epoch, logs=None): self.seen = 0 self.totals = {} def on_batch_end(self, batch, logs=None): logs = logs or {} batch_size = logs.get('size', 0) self.seen += batch_size for k, v in logs.items(): if k in self.stateful_metrics: self.totals[k] = v else: if k in self.totals: self.totals[k] += v * batch_size else: self.totals[k] = v * batch_size def on_epoch_end(self, epoch, logs=None): if logs is not None: for k in self.params['metrics']: if k in self.totals: # Make value available to next callbacks. if k in self.stateful_metrics: logs[k] = self.totals[k] else: logs[k] = self.totals[k] / self.seen @tf_export('keras.callbacks.TerminateOnNaN') class TerminateOnNaN(Callback): """Callback that terminates training when a NaN loss is encountered. """ def on_batch_end(self, batch, logs=None): logs = logs or {} loss = logs.get('loss') if loss is not None: if np.isnan(loss) or np.isinf(loss): print('Batch %d: Invalid loss, terminating training' % (batch)) self.model.stop_training = True @tf_export('keras.callbacks.ProgbarLogger') class ProgbarLogger(Callback): """Callback that prints metrics to stdout. Arguments: count_mode: One of "steps" or "samples". Whether the progress bar should count samples seen or steps (batches) seen. stateful_metrics: Iterable of string names of metrics that should *not* be averaged over an epoch. Metrics in this list will be logged as-is. All others will be averaged over time (e.g. loss, etc). Raises: ValueError: In case of invalid `count_mode`. """ def __init__(self, count_mode='samples', stateful_metrics=None): super(ProgbarLogger, self).__init__() if count_mode == 'samples': self.use_steps = False elif count_mode == 'steps': self.use_steps = True else: raise ValueError('Unknown `count_mode`: ' + str(count_mode)) self.stateful_metrics = set(stateful_metrics or []) def on_train_begin(self, logs=None): self.verbose = self.params['verbose'] self.epochs = self.params['epochs'] def on_epoch_begin(self, epoch, logs=None): if self.verbose: print('Epoch %d/%d' % (epoch + 1, self.epochs)) if self.use_steps: target = self.params['steps'] else: target = self.params['samples'] self.target = target self.progbar = Progbar( target=self.target, verbose=self.verbose, stateful_metrics=self.stateful_metrics) self.seen = 0 def on_batch_begin(self, batch, logs=None): if self.seen < self.target: self.log_values = [] def on_batch_end(self, batch, logs=None): logs = logs or {} batch_size = logs.get('size', 0) if self.use_steps: self.seen += 1 else: self.seen += batch_size for k in self.params['metrics']: if k in logs: self.log_values.append((k, logs[k])) # Skip progbar update for the last batch; # will be handled by on_epoch_end. if self.verbose and self.seen < self.target: self.progbar.update(self.seen, self.log_values) def on_epoch_end(self, epoch, logs=None): logs = logs or {} for k in self.params['metrics']: if k in logs: self.log_values.append((k, logs[k])) if self.verbose: self.progbar.update(self.seen, self.log_values) @tf_export('keras.callbacks.History') class History(Callback): """Callback that records events into a `History` object. This callback is automatically applied to every Keras model. The `History` object gets returned by the `fit` method of models. """ def on_train_begin(self, logs=None): self.epoch = [] self.history = {} def on_epoch_end(self, epoch, logs=None): logs = logs or {} self.epoch.append(epoch) for k, v in logs.items(): self.history.setdefault(k, []).append(v) @tf_export('keras.callbacks.ModelCheckpoint') class ModelCheckpoint(Callback): """Save the model after every epoch. `filepath` can contain named formatting options, which will be filled the value of `epoch` and keys in `logs` (passed in `on_epoch_end`). For example: if `filepath` is `weights.{epoch:02d}-{val_loss:.2f}.hdf5`, then the model checkpoints will be saved with the epoch number and the validation loss in the filename. Arguments: filepath: string, path to save the model file. monitor: quantity to monitor. verbose: verbosity mode, 0 or 1. save_best_only: if `save_best_only=True`, the latest best model according to the quantity monitored will not be overwritten. mode: one of {auto, min, max}. If `save_best_only=True`, the decision to overwrite the current save file is made based on either the maximization or the minimization of the monitored quantity. For `val_acc`, this should be `max`, for `val_loss` this should be `min`, etc. In `auto` mode, the direction is automatically inferred from the name of the monitored quantity. save_weights_only: if True, then only the model's weights will be saved (`model.save_weights(filepath)`), else the full model is saved (`model.save(filepath)`). period: Interval (number of epochs) between checkpoints. """ def __init__(self, filepath, monitor='val_loss', verbose=0, save_best_only=False, save_weights_only=False, mode='auto', period=1): super(ModelCheckpoint, self).__init__() self.monitor = monitor self.verbose = verbose self.filepath = filepath self.save_best_only = save_best_only self.save_weights_only = save_weights_only self.period = period self.epochs_since_last_save = 0 if mode not in ['auto', 'min', 'max']: logging.warning('ModelCheckpoint mode %s is unknown, ' 'fallback to auto mode.', mode) mode = 'auto' if mode == 'min': self.monitor_op = np.less self.best = np.Inf elif mode == 'max': self.monitor_op = np.greater self.best = -np.Inf else: if 'acc' in self.monitor or self.monitor.startswith('fmeasure'): self.monitor_op = np.greater self.best = -np.Inf else: self.monitor_op = np.less self.best = np.Inf def on_epoch_end(self, epoch, logs=None): logs = logs or {} self.epochs_since_last_save += 1 if self.epochs_since_last_save >= self.period: self.epochs_since_last_save = 0 filepath = self.filepath.format(epoch=epoch + 1, **logs) if self.save_best_only: current = logs.get(self.monitor) if current is None: logging.warning('Can save best model only with %s available, ' 'skipping.', self.monitor) else: if self.monitor_op(current, self.best): if self.verbose > 0: print('\nEpoch %05d: %s improved from %0.5f to %0.5f,' ' saving model to %s' % (epoch + 1, self.monitor, self.best, current, filepath)) self.best = current if self.save_weights_only: self.model.save_weights(filepath, overwrite=True) else: self.model.save(filepath, overwrite=True) else: if self.verbose > 0: print('\nEpoch %05d: %s did not improve from %0.5f' % (epoch + 1, self.monitor, self.best)) else: if self.verbose > 0: print('\nEpoch %05d: saving model to %s' % (epoch + 1, filepath)) if self.save_weights_only: self.model.save_weights(filepath, overwrite=True) else: self.model.save(filepath, overwrite=True) @tf_export('keras.callbacks.EarlyStopping') class EarlyStopping(Callback): """Stop training when a monitored quantity has stopped improving. Arguments: monitor: quantity to be monitored. min_delta: minimum change in the monitored quantity to qualify as an improvement, i.e. an absolute change of less than min_delta, will count as no improvement. patience: number of epochs with no improvement after which training will be stopped. verbose: verbosity mode. mode: one of {auto, min, max}. In `min` mode, training will stop when the quantity monitored has stopped decreasing; in `max` mode it will stop when the quantity monitored has stopped increasing; in `auto` mode, the direction is automatically inferred from the name of the monitored quantity. baseline: baseline value for the monitored quantity. Training will stop if the model doesn't show improvement over the baseline. """ def __init__(self, monitor='val_loss', min_delta=0, patience=0, verbose=0, mode='auto', baseline=None): super(EarlyStopping, self).__init__() self.monitor = monitor self.patience = patience self.verbose = verbose self.baseline = baseline self.min_delta = abs(min_delta) self.wait = 0 self.stopped_epoch = 0 if mode not in ['auto', 'min', 'max']: logging.warning('EarlyStopping mode %s is unknown, ' 'fallback to auto mode.', mode) mode = 'auto' if mode == 'min': self.monitor_op = np.less elif mode == 'max': self.monitor_op = np.greater else: if 'acc' in self.monitor: self.monitor_op = np.greater else: self.monitor_op = np.less if self.monitor_op == np.greater: self.min_delta *= 1 else: self.min_delta *= -1 def on_train_begin(self, logs=None): # Allow instances to be re-used self.wait = 0 self.stopped_epoch = 0 if self.baseline is not None: self.best = self.baseline else: self.best = np.Inf if self.monitor_op == np.less else -np.Inf def on_epoch_end(self, epoch, logs=None): current = logs.get(self.monitor) if current is None: logging.warning('Early stopping conditioned on metric `%s` ' 'which is not available. Available metrics are: %s', self.monitor, ','.join(list(logs.keys()))) return if self.monitor_op(current - self.min_delta, self.best): self.best = current self.wait = 0 else: self.wait += 1 if self.wait >= self.patience: self.stopped_epoch = epoch self.model.stop_training = True def on_train_end(self, logs=None): if self.stopped_epoch > 0 and self.verbose > 0: print('Epoch %05d: early stopping' % (self.stopped_epoch + 1)) @tf_export('keras.callbacks.RemoteMonitor') class RemoteMonitor(Callback): """Callback used to stream events to a server. Requires the `requests` library. Events are sent to `root + '/publish/epoch/end/'` by default. Calls are HTTP POST, with a `data` argument which is a JSON-encoded dictionary of event data. If send_as_json is set to True, the content type of the request will be application/json. Otherwise the serialized JSON will be sent within a form. Arguments: root: String; root url of the target server. path: String; path relative to `root` to which the events will be sent. field: String; JSON field under which the data will be stored. The field is used only if the payload is sent within a form (i.e. send_as_json is set to False). headers: Dictionary; optional custom HTTP headers. send_as_json: Boolean; whether the request should be sent as application/json. """ def __init__(self, root='http://localhost:9000', path='/publish/epoch/end/', field='data', headers=None, send_as_json=False): super(RemoteMonitor, self).__init__() self.root = root self.path = path self.field = field self.headers = headers self.send_as_json = send_as_json def on_epoch_end(self, epoch, logs=None): if requests is None: raise ImportError('RemoteMonitor requires the `requests` library.') logs = logs or {} send = {} send['epoch'] = epoch for k, v in logs.items(): send[k] = v try: if self.send_as_json: requests.post(self.root + self.path, json=send, headers=self.headers) else: requests.post( self.root + self.path, {self.field: json.dumps(send)}, headers=self.headers) except requests.exceptions.RequestException: logging.warning('Warning: could not reach RemoteMonitor ' 'root server at ' + str(self.root)) @tf_export('keras.callbacks.LearningRateScheduler') class LearningRateScheduler(Callback): """Learning rate scheduler. Arguments: schedule: a function that takes an epoch index as input (integer, indexed from 0) and returns a new learning rate as output (float). verbose: int. 0: quiet, 1: update messages. """ def __init__(self, schedule, verbose=0): super(LearningRateScheduler, self).__init__() self.schedule = schedule self.verbose = verbose def on_epoch_begin(self, epoch, logs=None): if not hasattr(self.model.optimizer, 'lr'): raise ValueError('Optimizer must have a "lr" attribute.') try: # new API lr = float(K.get_value(self.model.optimizer.lr)) lr = self.schedule(epoch, lr) except TypeError: # Support for old API for backward compatibility lr = self.schedule(epoch) if not isinstance(lr, (float, np.float32, np.float64)): raise ValueError('The output of the "schedule" function ' 'should be float.') K.set_value(self.model.optimizer.lr, lr) if self.verbose > 0: print('\nEpoch %05d: LearningRateScheduler reducing learning ' 'rate to %s.' % (epoch + 1, lr)) @tf_export('keras.callbacks.TensorBoard') class TensorBoard(Callback): # pylint: disable=line-too-long """Tensorboard basic visualizations. This callback writes a log for TensorBoard, which allows you to visualize dynamic graphs of your training and test metrics, as well as activation histograms for the different layers in your model. TensorBoard is a visualization tool provided with TensorFlow. If you have installed TensorFlow with pip, you should be able to launch TensorBoard from the command line: ```sh tensorboard --logdir=/full_path_to_your_logs ``` You can find more information about TensorBoard [here](https://www.tensorflow.org/get_started/summaries_and_tensorboard). Arguments: log_dir: the path of the directory where to save the log files to be parsed by TensorBoard. histogram_freq: frequency (in epochs) at which to compute activation and weight histograms for the layers of the model. If set to 0, histograms won't be computed. Validation data (or split) must be specified for histogram visualizations. write_graph: whether to visualize the graph in TensorBoard. The log file can become quite large when write_graph is set to True. write_grads: whether to visualize gradient histograms in TensorBoard. `histogram_freq` must be greater than 0. batch_size: size of batch of inputs to feed to the network for histograms computation. write_images: whether to write model weights to visualize as image in TensorBoard. embeddings_freq: frequency (in epochs) at which selected embedding layers will be saved. If set to 0, embeddings won't be computed. Data to be visualized in TensorBoard's Embedding tab must be passed as `embeddings_data`. embeddings_layer_names: a list of names of layers to keep eye on. If None or empty list all the embedding layer will be watched. embeddings_metadata: a dictionary which maps layer name to a file name in which metadata for this embedding layer is saved. See the [details](https://www.tensorflow.org/how_tos/embedding_viz/#metadata_optional) about metadata files format. In case if the same metadata file is used for all embedding layers, string can be passed. embeddings_data: data to be embedded at layers specified in `embeddings_layer_names`. Numpy array (if the model has a single input) or list of Numpy arrays (if the model has multiple inputs). Learn [more about embeddings](https://www.tensorflow.org/programmers_guide/embedding) Raises: ValueError: If histogram_freq is set and no validation data is provided. @compatbility(eager) Using `Tensorboard` callback will work while eager execution is enabled, however outputting histogram summaries of weights and gradients is not supported, and thus `histogram_freq` will be ignored. @end_compatibility """ # pylint: enable=line-too-long def __init__(self, log_dir='./logs', histogram_freq=0, batch_size=32, write_graph=True, write_grads=False, write_images=False, embeddings_freq=0, embeddings_layer_names=None, embeddings_metadata=None, embeddings_data=None): super(TensorBoard, self).__init__() self.log_dir = log_dir self.histogram_freq = histogram_freq if self.histogram_freq and context.executing_eagerly(): logging.warning( UserWarning('Weight and gradient histograms not supported for eager' 'execution, setting `histogram_freq` to `0`.')) self.histogram_freq = 0 self.merged = None self.write_graph = write_graph self.write_grads = write_grads self.write_images = write_images self.batch_size = batch_size self._current_batch = 0 self._total_batches_seen = 0 self.embeddings_freq = embeddings_freq self.embeddings_layer_names = embeddings_layer_names self.embeddings_metadata = embeddings_metadata self.embeddings_data = embeddings_data def _init_writer(self): """Sets file writer.""" if context.executing_eagerly(): self.writer = summary_ops_v2.create_file_writer(self.log_dir) elif self.write_graph: self.writer = tf_summary.FileWriter(self.log_dir, K.get_session().graph) else: self.writer = tf_summary.FileWriter(self.log_dir) def _make_histogram_ops(self, model): """Defines histogram ops when histogram_freq > 0.""" # only make histogram summary op if it hasn't already been made if self.histogram_freq and self.merged is None: for layer in self.model.layers: for weight in layer.weights: mapped_weight_name = weight.name.replace(':', '_') tf_summary.histogram(mapped_weight_name, weight) if self.write_images: w_img = array_ops.squeeze(weight) shape = K.int_shape(w_img) if len(shape) == 2: # dense layer kernel case if shape[0] > shape[1]: w_img = array_ops.transpose(w_img) shape = K.int_shape(w_img) w_img = array_ops.reshape(w_img, [1, shape[0], shape[1], 1]) elif len(shape) == 3: # convnet case if K.image_data_format() == 'channels_last': # switch to channels_first to display # every kernel as a separate image w_img = array_ops.transpose(w_img, perm=[2, 0, 1]) shape = K.int_shape(w_img) w_img = array_ops.reshape(w_img, [shape[0], shape[1], shape[2], 1]) elif len(shape) == 1: # bias case w_img = array_ops.reshape(w_img, [1, shape[0], 1, 1]) else: # not possible to handle 3D convnets etc. continue shape = K.int_shape(w_img) assert len(shape) == 4 and shape[-1] in [1, 3, 4] tf_summary.image(mapped_weight_name, w_img) if self.write_grads: for weight in layer.trainable_weights: mapped_weight_name = weight.name.replace(':', '_') grads = model.optimizer.get_gradients(model.total_loss, weight) def is_indexed_slices(grad): return type(grad).__name__ == 'IndexedSlices' grads = [ grad.values if is_indexed_slices(grad) else grad for grad in grads ] tf_summary.histogram('{}_grad'.format(mapped_weight_name), grads) if hasattr(layer, 'output'): if isinstance(layer.output, list): for i, output in enumerate(layer.output): tf_summary.histogram('{}_out_{}'.format(layer.name, i), output) else: tf_summary.histogram('{}_out'.format(layer.name), layer.output) def set_model(self, model): """Sets Keras model and creates summary ops.""" self.model = model self._init_writer() # histogram summaries only enabled in graph mode if not context.executing_eagerly(): self._make_histogram_ops(model) self.merged = tf_summary.merge_all() # If both embedding_freq and embeddings_data are available, we will # visualize embeddings. if self.embeddings_freq and self.embeddings_data is not None: self.embeddings_data = standardize_input_data(self.embeddings_data, model.input_names) # If embedding_layer_names are not provided, get all of the embedding # layers from the model. embeddings_layer_names = self.embeddings_layer_names if not embeddings_layer_names: embeddings_layer_names = [ layer.name for layer in self.model.layers if type(layer).__name__ == 'Embedding' ] self.assign_embeddings = [] embeddings_vars = {} self.batch_id = batch_id = array_ops.placeholder(dtypes.int32) self.step = step = array_ops.placeholder(dtypes.int32) for layer in self.model.layers: if layer.name in embeddings_layer_names: embedding_input = self.model.get_layer(layer.name).output embedding_size = np.prod(embedding_input.shape[1:]) embedding_input = array_ops.reshape(embedding_input, (step, int(embedding_size))) shape = (self.embeddings_data[0].shape[0], int(embedding_size)) embedding = variables.Variable( array_ops.zeros(shape), name=layer.name + '_embedding') embeddings_vars[layer.name] = embedding batch = state_ops.assign(embedding[batch_id:batch_id + step], embedding_input) self.assign_embeddings.append(batch) self.saver = saver.Saver(list(embeddings_vars.values())) # Create embeddings_metadata dictionary if isinstance(self.embeddings_metadata, str): embeddings_metadata = { layer_name: self.embeddings_metadata for layer_name in embeddings_vars.keys() } else: # If embedding_metadata is already a dictionary embeddings_metadata = self.embeddings_metadata try: from tensorboard.plugins import projector except ImportError: raise ImportError('Failed to import TensorBoard. Please make sure that ' 'TensorBoard integration is complete."') # TODO(psv): Add integration tests to test embedding visualization # with TensorBoard callback. We are unable to write a unit test for this # because TensorBoard dependency assumes TensorFlow package is installed. config = projector.ProjectorConfig() for layer_name, tensor in embeddings_vars.items(): embedding = config.embeddings.add() embedding.tensor_name = tensor.name if (embeddings_metadata is not None and layer_name in embeddings_metadata): embedding.metadata_path = embeddings_metadata[layer_name] projector.visualize_embeddings(self.writer, config) def _fetch_callback(self, summary): self.writer.add_summary( summary, self._epoch + self._current_val_batch / self._validation_batches) self._current_val_batch += 1 def _write_custom_summaries(self, step, logs=None): """Writes metrics out as custom scalar summaries. Arguments: step: the global step to use for Tensorboard. logs: dict. Keys are scalar summary names, values are NumPy scalars. """ logs = logs or {} if context.executing_eagerly(): # use v2 summary ops with self.writer.as_default(), summary_ops_v2.always_record_summaries(): for name, value in logs.items(): summary_ops_v2.scalar(name, value.item(), step=step) else: # use FileWriter from v1 summary for name, value in logs.items(): summary = tf_summary.Summary() summary_value = summary.value.add() summary_value.simple_value = value.item() summary_value.tag = name self.writer.add_summary(summary, step) self.writer.flush() def on_train_begin(self, logs=None): """Checks if histogram summaries can be run.""" # will never be set when in eager if self.histogram_freq: if self.params.get('validation_steps', None) is not None: self._validation_batches = self.params['validation_steps'] elif self.validation_data: self._validation_batches = math.ceil( self.validation_data[0].shape[0] / self.batch_size) else: raise ValueError('If printing histograms, validation data must be ' 'provided.') if self._validation_batches == 0: raise ValueError( 'If printing histograms, validation data must have length > 0.') def on_batch_end(self, batch, logs=None): """Writes scalar summaries for metrics on every training batch.""" # Don't output batch_size and batch number as Tensorboard summaries logs = logs or {} batch_logs = {('batch_' + k): v for k, v in logs.items() if k not in ['batch', 'size']} self._write_custom_summaries(self._total_batches_seen, batch_logs) self._total_batches_seen += 1 def on_epoch_begin(self, epoch, logs=None): """Add histogram op to Model test_function callbacks, reset batch count.""" # check if histogram summary should be run for this epoch if self.histogram_freq and epoch % self.histogram_freq == 0: self._epoch = epoch self._current_val_batch = 0 # add the histogram summary op if it should run this epoch if self.merged not in self.model.test_function.fetches: self.model.test_function.fetches.append(self.merged) self.model.test_function.fetch_callbacks[ self.merged] = self._fetch_callback def on_epoch_end(self, epoch, logs=None): """Checks if summary ops should run next epoch, logs scalar summaries.""" # don't output batch_size and # batch number as Tensorboard summaries logs = {('epoch_' + k): v for k, v in logs.items() if k not in ['batch', 'size']} self._write_custom_summaries(epoch, logs) # pop the histogram summary op after each epoch if self.histogram_freq: if self.merged in self.model.test_function.fetches: self.model.test_function.fetches.remove(self.merged) if self.merged in self.model.test_function.fetch_callbacks: self.model.test_function.fetch_callbacks.pop(self.merged) if self.embeddings_data is None and self.embeddings_freq: raise ValueError('To visualize embeddings, embeddings_data must ' 'be provided.') if self.embeddings_freq and self.embeddings_data is not None: if epoch % self.embeddings_freq == 0: # We need a second forward-pass here because we're passing # the `embeddings_data` explicitly. This design allows to pass # arbitrary data as `embeddings_data` and results from the fact # that we need to know the size of the `tf.Variable`s which # hold the embeddings in `set_model`. At this point, however, # the `validation_data` is not yet set. embeddings_data = self.embeddings_data n_samples = embeddings_data[0].shape[0] i = 0 while i < n_samples: step = min(self.batch_size, n_samples - i) batch = slice(i, i + step) if isinstance(self.model.input, list): feed_dict = { model_input: embeddings_data[idx][batch] for idx, model_input in enumerate(self.model.input) } else: feed_dict = {self.model.input: embeddings_data[0][batch]} feed_dict.update({self.batch_id: i, self.step: step}) if self.model.uses_learning_phase: feed_dict[K.learning_phase()] = False self.sess.run(self.assign_embeddings, feed_dict=feed_dict) self.saver.save(self.sess, os.path.join(self.log_dir, 'keras_embedding.ckpt'), epoch) i += self.batch_size def on_train_end(self, logs=None): self.writer.close() @tf_export('keras.callbacks.ReduceLROnPlateau') class ReduceLROnPlateau(Callback): """Reduce learning rate when a metric has stopped improving. Models often benefit from reducing the learning rate by a factor of 2-10 once learning stagnates. This callback monitors a quantity and if no improvement is seen for a 'patience' number of epochs, the learning rate is reduced. Example: ```python reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=5, min_lr=0.001) model.fit(X_train, Y_train, callbacks=[reduce_lr]) ``` Arguments: monitor: quantity to be monitored. factor: factor by which the learning rate will be reduced. new_lr = lr * factor patience: number of epochs with no improvement after which learning rate will be reduced. verbose: int. 0: quiet, 1: update messages. mode: one of {auto, min, max}. In `min` mode, lr will be reduced when the quantity monitored has stopped decreasing; in `max` mode it will be reduced when the quantity monitored has stopped increasing; in `auto` mode, the direction is automatically inferred from the name of the monitored quantity. min_delta: threshold for measuring the new optimum, to only focus on significant changes. cooldown: number of epochs to wait before resuming normal operation after lr has been reduced. min_lr: lower bound on the learning rate. """ def __init__(self, monitor='val_loss', factor=0.1, patience=10, verbose=0, mode='auto', min_delta=1e-4, cooldown=0, min_lr=0, **kwargs): super(ReduceLROnPlateau, self).__init__() self.monitor = monitor if factor >= 1.0: raise ValueError('ReduceLROnPlateau ' 'does not support a factor >= 1.0.') if 'epsilon' in kwargs: min_delta = kwargs.pop('epsilon') logging.warning('`epsilon` argument is deprecated and ' 'will be removed, use `min_delta` instead.') self.factor = factor self.min_lr = min_lr self.min_delta = min_delta self.patience = patience self.verbose = verbose self.cooldown = cooldown self.cooldown_counter = 0 # Cooldown counter. self.wait = 0 self.best = 0 self.mode = mode self.monitor_op = None self._reset() def _reset(self): """Resets wait counter and cooldown counter. """ if self.mode not in ['auto', 'min', 'max']: logging.warning('Learning Rate Plateau Reducing mode %s is unknown, ' 'fallback to auto mode.', self.mode) self.mode = 'auto' if (self.mode == 'min' or (self.mode == 'auto' and 'acc' not in self.monitor)): self.monitor_op = lambda a, b: np.less(a, b - self.min_delta) self.best = np.Inf else: self.monitor_op = lambda a, b: np.greater(a, b + self.min_delta) self.best = -np.Inf self.cooldown_counter = 0 self.wait = 0 def on_train_begin(self, logs=None): self._reset() def on_epoch_end(self, epoch, logs=None): logs = logs or {} logs['lr'] = K.get_value(self.model.optimizer.lr) current = logs.get(self.monitor) if current is None: logging.warning('Reduce LR on plateau conditioned on metric `%s` ' 'which is not available. Available metrics are: %s', self.monitor, ','.join(list(logs.keys()))) else: if self.in_cooldown(): self.cooldown_counter -= 1 self.wait = 0 if self.monitor_op(current, self.best): self.best = current self.wait = 0 elif not self.in_cooldown(): self.wait += 1 if self.wait >= self.patience: old_lr = float(K.get_value(self.model.optimizer.lr)) if old_lr > self.min_lr: new_lr = old_lr * self.factor new_lr = max(new_lr, self.min_lr) K.set_value(self.model.optimizer.lr, new_lr) if self.verbose > 0: print('\nEpoch %05d: ReduceLROnPlateau reducing learning ' 'rate to %s.' % (epoch + 1, new_lr)) self.cooldown_counter = self.cooldown self.wait = 0 def in_cooldown(self): return self.cooldown_counter > 0 @tf_export('keras.callbacks.CSVLogger') class CSVLogger(Callback): """Callback that streams epoch results to a csv file. Supports all values that can be represented as a string, including 1D iterables such as np.ndarray. Example: ```python csv_logger = CSVLogger('training.log') model.fit(X_train, Y_train, callbacks=[csv_logger]) ``` Arguments: filename: filename of the csv file, e.g. 'run/log.csv'. separator: string used to separate elements in the csv file. append: True: append if file exists (useful for continuing training). False: overwrite existing file, """ def __init__(self, filename, separator=',', append=False): self.sep = separator self.filename = filename self.append = append self.writer = None self.keys = None self.append_header = True self.file_flags = 'b' if six.PY2 and os.name == 'nt' else '' super(CSVLogger, self).__init__() def on_train_begin(self, logs=None): if self.append: if os.path.exists(self.filename): with open(self.filename, 'r' + self.file_flags) as f: self.append_header = not bool(len(f.readline())) self.csv_file = open(self.filename, 'a' + self.file_flags) else: self.csv_file = open(self.filename, 'w' + self.file_flags) def on_epoch_end(self, epoch, logs=None): logs = logs or {} def handle_value(k): is_zero_dim_ndarray = isinstance(k, np.ndarray) and k.ndim == 0 if isinstance(k, six.string_types): return k elif isinstance(k, Iterable) and not is_zero_dim_ndarray: return '"[%s]"' % (', '.join(map(str, k))) else: return k if self.keys is None: self.keys = sorted(logs.keys()) if self.model.stop_training: # We set NA so that csv parsers do not fail for this last epoch. logs = dict([(k, logs[k]) if k in logs else (k, 'NA') for k in self.keys]) if not self.writer: class CustomDialect(csv.excel): delimiter = self.sep self.writer = csv.DictWriter( self.csv_file, fieldnames=['epoch'] + self.keys, dialect=CustomDialect) if self.append_header: self.writer.writeheader() row_dict = OrderedDict({'epoch': epoch}) row_dict.update((key, handle_value(logs[key])) for key in self.keys) self.writer.writerow(row_dict) self.csv_file.flush() def on_train_end(self, logs=None): self.csv_file.close() self.writer = None @tf_export('keras.callbacks.LambdaCallback') class LambdaCallback(Callback): r"""Callback for creating simple, custom callbacks on-the-fly. This callback is constructed with anonymous functions that will be called at the appropriate time. Note that the callbacks expects positional arguments, as: - `on_epoch_begin` and `on_epoch_end` expect two positional arguments: `epoch`, `logs` - `on_batch_begin` and `on_batch_end` expect two positional arguments: `batch`, `logs` - `on_train_begin` and `on_train_end` expect one positional argument: `logs` Arguments: on_epoch_begin: called at the beginning of every epoch. on_epoch_end: called at the end of every epoch. on_batch_begin: called at the beginning of every batch. on_batch_end: called at the end of every batch. on_train_begin: called at the beginning of model training. on_train_end: called at the end of model training. Example: ```python # Print the batch number at the beginning of every batch. batch_print_callback = LambdaCallback( on_batch_begin=lambda batch,logs: print(batch)) # Stream the epoch loss to a file in JSON format. The file content # is not well-formed JSON but rather has a JSON object per line. import json json_log = open('loss_log.json', mode='wt', buffering=1) json_logging_callback = LambdaCallback( on_epoch_end=lambda epoch, logs: json_log.write( json.dumps({'epoch': epoch, 'loss': logs['loss']}) + '\n'), on_train_end=lambda logs: json_log.close() ) # Terminate some processes after having finished model training. processes = ... cleanup_callback = LambdaCallback( on_train_end=lambda logs: [ p.terminate() for p in processes if p.is_alive()]) model.fit(..., callbacks=[batch_print_callback, json_logging_callback, cleanup_callback]) ``` """ def __init__(self, on_epoch_begin=None, on_epoch_end=None, on_batch_begin=None, on_batch_end=None, on_train_begin=None, on_train_end=None, **kwargs): super(LambdaCallback, self).__init__() self.__dict__.update(kwargs) if on_epoch_begin is not None: self.on_epoch_begin = on_epoch_begin else: self.on_epoch_begin = lambda epoch, logs: None if on_epoch_end is not None: self.on_epoch_end = on_epoch_end else: self.on_epoch_end = lambda epoch, logs: None if on_batch_begin is not None: self.on_batch_begin = on_batch_begin else: self.on_batch_begin = lambda batch, logs: None if on_batch_end is not None: self.on_batch_end = on_batch_end else: self.on_batch_end = lambda batch, logs: None if on_train_begin is not None: self.on_train_begin = on_train_begin else: self.on_train_begin = lambda logs: None if on_train_end is not None: self.on_train_end = on_train_end else: self.on_train_end = lambda logs: None
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
e4d331190d0951613bfb2dd2e5c596a4220fc079
c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c
/cases/synthetic/sieve-big-4642.py
e44d50bd03724d6fd15dac3b8b839dc0d38c9563
[]
no_license
Virtlink/ccbench-chocopy
c3f7f6af6349aff6503196f727ef89f210a1eac8
c7efae43bf32696ee2b2ee781bdfe4f7730dec3f
refs/heads/main
2023-04-07T15:07:12.464038
2022-02-03T15:42:39
2022-02-03T15:42:39
451,969,776
0
0
null
null
null
null
UTF-8
Python
false
false
31,755
py
# A resizable list of integers class Vector(object): items: [int] = None size: int = 0 def __init__(self:"Vector"): self.items = [0] # Returns current capacity def capacity(self:"Vector") -> int: return len(self.items) # Increases capacity of vector by one element def increase_capacity(self:"Vector") -> int: self.items = self.items + [0] return self.capacity() # Appends one item to end of vector def append(self:"Vector", item: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends many items to end of vector def append_all(self:"Vector", new_items: [int]) -> object: item:int = 0 for item in new_items: self.append(item) # Removes an item from the middle of vector def remove_at(self:"Vector", idx: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Retrieves an item at a given index def get(self:"Vector", idx: int) -> int: return self.items[idx] # Retrieves the current size of the vector def length(self:"Vector") -> int: return self.size # A resizable list of integers class Vector2(object): items: [int] = None items2: [int] = None size: int = 0 size2: int = 0 def __init__(self:"Vector2"): self.items = [0] # Returns current capacity def capacity(self:"Vector2") -> int: return len(self.items) # Returns current capacity def capacity2(self:"Vector2") -> int: return len(self.items) # Increases capacity of vector by one element def increase_capacity(self:"Vector2") -> int: self.items = self.items + [0] return self.capacity() # Increases capacity of vector by one element def increase_capacity2(self:"Vector2") -> int: self.items = self.items + [0] return self.capacity() # Appends one item to end of vector def append(self:"Vector2", item: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends one item to end of vector def append2(self:"Vector2", item: int, item2: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends many items to end of vector def append_all(self:"Vector2", new_items: [int]) -> object: item:int = 0 for item in new_items: self.append(item) # Appends many items to end of vector def append_all2(self:"Vector2", new_items: [int], new_items2: [int]) -> object: item:int = 0 item2:int = 0 for item in new_items: self.append(item) # Removes an item from the middle of vector def remove_at(self:"Vector2", idx: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Removes an item from the middle of vector def remove_at2(self:"Vector2", idx: int, idx2: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Retrieves an item at a given index def get(self:"Vector2", idx: int) -> int: return self.items[idx] # Retrieves an item at a given index def get2(self:"Vector2", idx: int, idx2: int) -> int: return self.items[idx] # Retrieves the current size of the vector def length(self:"Vector2") -> int: return self.size # Retrieves the current size of the vector def length2(self:"Vector2") -> int: return self.size # A resizable list of integers class Vector3(object): items: [int] = None items2: [int] = None items3: [int] = None size: int = 0 size2: int = 0 size3: int = 0 def __init__(self:"Vector3"): self.items = [0] # Returns current capacity def capacity(self:"Vector3") -> int: return len(self.items) # Returns current capacity def capacity2(self:"Vector3") -> int: return len(self.items) # Returns current capacity def capacity3(self:"Vector3") -> int: return len(self.items) # Increases capacity of vector by one element def increase_capacity(self:"Vector3") -> int: self.items = self.items + [0] return self.capacity() # Increases capacity of vector by one element def increase_capacity2(self:"Vector3") -> int: self.items = self.items + [0] return self.capacity() # Increases capacity of vector by one element def increase_capacity3(self:"Vector3") -> int: self.items = self.items + [0] return self.capacity() # Appends one item to end of vector def append(self:"Vector3", item: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends one item to end of vector def append2(self:"Vector3", item: int, item2: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends one item to end of vector def append3(self:"Vector3", item: int, item2: int, item3: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends many items to end of vector def append_all(self:"Vector3", new_items: [int]) -> object: item:int = 0 for item in new_items: self.append(item) # Appends many items to end of vector def append_all2(self:"Vector3", new_items: [int], new_items2: [int]) -> object: item:int = 0 item2:int = 0 for item in new_items: self.append(item) # Appends many items to end of vector def append_all3(self:"Vector3", new_items: [int], new_items2: [int], new_items3: [int]) -> object: item:int = 0 item2:int = 0 item3:int = 0 for item in new_items: self.append(item) # Removes an item from the middle of vector def remove_at(self:"Vector3", idx: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Removes an item from the middle of vector def remove_at2(self:"Vector3", idx: int, idx2: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Removes an item from the middle of vector def remove_at3(self:"Vector3", idx: int, idx2: int, idx3: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Retrieves an item at a given index def get(self:"Vector3", idx: int) -> int: return self.items[idx] # Retrieves an item at a given index def get2(self:"Vector3", idx: int, idx2: int) -> int: return self.items[idx] # Retrieves an item at a given index def get3(self:"Vector3", idx: int, idx2: int, idx3: int) -> int: return self.items[idx] # Retrieves the current size of the vector def length(self:"Vector3") -> int: return self.size # Retrieves the current size of the vector def length2(self:"Vector3") -> int: return self.size # Retrieves the current size of the vector def length3(self:"Vector3") -> int: return self.size # A resizable list of integers class Vector4(object): items: [int] = None items2: [int] = None items3: [int] = None items4: [int] = None size: int = 0 size2: int = 0 size3: int = 0 size4: int = 0 def __init__(self:"Vector4"): self.items = [0] # Returns current capacity def capacity(self:"Vector4") -> int: return len(self.items) # Returns current capacity def capacity2(self:"Vector4") -> int: return len(self.items) # Returns current capacity def capacity3(self:"Vector4") -> int: return len(self.items) # Returns current capacity def capacity4(self:"Vector4") -> int: return len(self.items) # Increases capacity of vector by one element def increase_capacity(self:"Vector4") -> int: self.items = self.items + [0] return self.capacity() # Increases capacity of vector by one element def increase_capacity2(self:"Vector4") -> int: self.items = self.items + [0] return self.capacity() # Increases capacity of vector by one element def increase_capacity3(self:"Vector4") -> int: self.items = self.items + [0] return self.capacity() # Increases capacity of vector by one element def increase_capacity4(self:"Vector4") -> int: self.items = self.items + [0] return self.capacity() # Appends one item to end of vector def append(self:"Vector4", item: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends one item to end of vector def append2(self:"Vector4", item: int, item2: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends one item to end of vector def append3(self:"Vector4", item: int, item2: int, item3: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends one item to end of vector def append4(self:"Vector4", item: int, item2: int, item3: int, item4: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends many items to end of vector def append_all(self:"Vector4", new_items: [int]) -> object: item:int = 0 for item in new_items: self.append(item) # Appends many items to end of vector def append_all2(self:"Vector4", new_items: [int], new_items2: [int]) -> object: item:int = 0 item2:int = 0 for item in new_items: self.append(item) # Appends many items to end of vector def append_all3(self:"Vector4", new_items: [int], new_items2: [int], new_items3: [int]) -> object: item:int = 0 item2:int = 0 item3:int = 0 for item in new_items: self.append(item) # Appends many items to end of vector def append_all4(self:"Vector4", new_items: [int], new_items2: [int], new_items3: [int], new_items4: [int]) -> object: item:int = 0 item2:int = 0 item3:int = 0 item4:int = 0 for item in new_items: self.append(item) # Removes an item from the middle of vector def remove_at(self:"Vector4", idx: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Removes an item from the middle of vector def remove_at2(self:"Vector4", idx: int, idx2: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Removes an item from the middle of vector def remove_at3(self:"Vector4", idx: int, idx2: int, idx3: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Removes an item from the middle of vector def remove_at4(self:"Vector4", idx: int, idx2: int, idx3: int, idx4: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Retrieves an item at a given index def get(self:"Vector4", idx: int) -> int: return self.items[idx] # Retrieves an item at a given index def get2(self:"Vector4", idx: int, idx2: int) -> int: return self.items[idx] # Retrieves an item at a given index def get3(self:"Vector4", idx: int, idx2: int, idx3: int) -> int: return self.items[idx] # Retrieves an item at a given index def get4(self:"Vector4", idx: int, idx2: int, idx3: int, idx4: int) -> int: return self.items[idx] # Retrieves the current size of the vector def length(self:"Vector4") -> int: return self.size # Retrieves the current size of the vector def length2(self:"Vector4") -> int: return self.size # Retrieves the current size of the vector def length3(self:"Vector4") -> int: return self.size # Retrieves the current size of the vector def length4(self:"Vector4") -> int: return self.size # A resizable list of integers class Vector5(object): items: [int] = None items2: [int] = None items3: [int] = None items4: [int] = None items5: [int] = None size: int = 0 size2: int = 0 size3: int = 0 size4: int = 0 size5: int = 0 def __init__(self:"Vector5"): self.items = [0] # Returns current capacity def capacity(self:"Vector5") -> int: return len(self.items) # Returns current capacity def capacity2(self:"Vector5") -> int: return len(self.items) # Returns current capacity def capacity3(self:"Vector5") -> int: return len(self.items) # Returns current capacity def capacity4(self:"Vector5") -> int: return len(self.items) # Returns current capacity def capacity5(self:"Vector5") -> int: return len(self.items) # Increases capacity of vector by one element def increase_capacity(self:"Vector5") -> int: self.items = self.items + [0] return self.capacity() # Increases capacity of vector by one element def increase_capacity2(self:"Vector5") -> int: self.items = self.items + [0] return self.capacity() # Increases capacity of vector by one element def increase_capacity3(self:"Vector5") -> int: self.items = self.items + [0] return self.capacity() # Increases capacity of vector by one element def increase_capacity4(self:$IDSTRING) -> int: self.items = self.items + [0] return self.capacity() # Increases capacity of vector by one element def increase_capacity5(self:"Vector5") -> int: self.items = self.items + [0] return self.capacity() # Appends one item to end of vector def append(self:"Vector5", item: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends one item to end of vector def append2(self:"Vector5", item: int, item2: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends one item to end of vector def append3(self:"Vector5", item: int, item2: int, item3: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends one item to end of vector def append4(self:"Vector5", item: int, item2: int, item3: int, item4: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends one item to end of vector def append5(self:"Vector5", item: int, item2: int, item3: int, item4: int, item5: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends many items to end of vector def append_all(self:"Vector5", new_items: [int]) -> object: item:int = 0 for item in new_items: self.append(item) # Appends many items to end of vector def append_all2(self:"Vector5", new_items: [int], new_items2: [int]) -> object: item:int = 0 item2:int = 0 for item in new_items: self.append(item) # Appends many items to end of vector def append_all3(self:"Vector5", new_items: [int], new_items2: [int], new_items3: [int]) -> object: item:int = 0 item2:int = 0 item3:int = 0 for item in new_items: self.append(item) # Appends many items to end of vector def append_all4(self:"Vector5", new_items: [int], new_items2: [int], new_items3: [int], new_items4: [int]) -> object: item:int = 0 item2:int = 0 item3:int = 0 item4:int = 0 for item in new_items: self.append(item) # Appends many items to end of vector def append_all5(self:"Vector5", new_items: [int], new_items2: [int], new_items3: [int], new_items4: [int], new_items5: [int]) -> object: item:int = 0 item2:int = 0 item3:int = 0 item4:int = 0 item5:int = 0 for item in new_items: self.append(item) # Removes an item from the middle of vector def remove_at(self:"Vector5", idx: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Removes an item from the middle of vector def remove_at2(self:"Vector5", idx: int, idx2: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Removes an item from the middle of vector def remove_at3(self:"Vector5", idx: int, idx2: int, idx3: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Removes an item from the middle of vector def remove_at4(self:"Vector5", idx: int, idx2: int, idx3: int, idx4: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Removes an item from the middle of vector def remove_at5(self:"Vector5", idx: int, idx2: int, idx3: int, idx4: int, idx5: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Retrieves an item at a given index def get(self:"Vector5", idx: int) -> int: return self.items[idx] # Retrieves an item at a given index def get2(self:"Vector5", idx: int, idx2: int) -> int: return self.items[idx] # Retrieves an item at a given index def get3(self:"Vector5", idx: int, idx2: int, idx3: int) -> int: return self.items[idx] # Retrieves an item at a given index def get4(self:"Vector5", idx: int, idx2: int, idx3: int, idx4: int) -> int: return self.items[idx] # Retrieves an item at a given index def get5(self:"Vector5", idx: int, idx2: int, idx3: int, idx4: int, idx5: int) -> int: return self.items[idx] # Retrieves the current size of the vector def length(self:"Vector5") -> int: return self.size # Retrieves the current size of the vector def length2(self:"Vector5") -> int: return self.size # Retrieves the current size of the vector def length3(self:"Vector5") -> int: return self.size # Retrieves the current size of the vector def length4(self:"Vector5") -> int: return self.size # Retrieves the current size of the vector def length5(self:"Vector5") -> int: return self.size # A faster (but more memory-consuming) implementation of vector class DoublingVector(Vector): doubling_limit:int = 1000 # Overriding to do fewer resizes def increase_capacity(self:"DoublingVector") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # A faster (but more memory-consuming) implementation of vector class DoublingVector2(Vector): doubling_limit:int = 1000 doubling_limit2:int = 1000 # Overriding to do fewer resizes def increase_capacity(self:"DoublingVector2") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # Overriding to do fewer resizes def increase_capacity2(self:"DoublingVector2") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # A faster (but more memory-consuming) implementation of vector class DoublingVector3(Vector): doubling_limit:int = 1000 doubling_limit2:int = 1000 doubling_limit3:int = 1000 # Overriding to do fewer resizes def increase_capacity(self:"DoublingVector3") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # Overriding to do fewer resizes def increase_capacity2(self:"DoublingVector3") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # Overriding to do fewer resizes def increase_capacity3(self:"DoublingVector3") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # A faster (but more memory-consuming) implementation of vector class DoublingVector4(Vector): doubling_limit:int = 1000 doubling_limit2:int = 1000 doubling_limit3:int = 1000 doubling_limit4:int = 1000 # Overriding to do fewer resizes def increase_capacity(self:"DoublingVector4") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # Overriding to do fewer resizes def increase_capacity2(self:"DoublingVector4") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # Overriding to do fewer resizes def increase_capacity3(self:"DoublingVector4") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # Overriding to do fewer resizes def increase_capacity4(self:"DoublingVector4") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # A faster (but more memory-consuming) implementation of vector class DoublingVector5(Vector): doubling_limit:int = 1000 doubling_limit2:int = 1000 doubling_limit3:int = 1000 doubling_limit4:int = 1000 doubling_limit5:int = 1000 # Overriding to do fewer resizes def increase_capacity(self:"DoublingVector5") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # Overriding to do fewer resizes def increase_capacity2(self:"DoublingVector5") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # Overriding to do fewer resizes def increase_capacity3(self:"DoublingVector5") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # Overriding to do fewer resizes def increase_capacity4(self:"DoublingVector5") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # Overriding to do fewer resizes def increase_capacity5(self:"DoublingVector5") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # Makes a vector in the range [i, j) def vrange(i:int, j:int) -> Vector: v:Vector = None v = DoublingVector() while i < j: v.append(i) i = i + 1 return v def vrange2(i:int, j:int, i2:int, j2:int) -> Vector: v:Vector = None v2:Vector = None v = DoublingVector() while i < j: v.append(i) i = i + 1 return v def vrange3(i:int, j:int, i2:int, j2:int, i3:int, j3:int) -> Vector: v:Vector = None v2:Vector = None v3:Vector = None v = DoublingVector() while i < j: v.append(i) i = i + 1 return v def vrange4(i:int, j:int, i2:int, j2:int, i3:int, j3:int, i4:int, j4:int) -> Vector: v:Vector = None v2:Vector = None v3:Vector = None v4:Vector = None v = DoublingVector() while i < j: v.append(i) i = i + 1 return v def vrange5(i:int, j:int, i2:int, j2:int, i3:int, j3:int, i4:int, j4:int, i5:int, j5:int) -> Vector: v:Vector = None v2:Vector = None v3:Vector = None v4:Vector = None v5:Vector = None v = DoublingVector() while i < j: v.append(i) i = i + 1 return v # Sieve of Eratosthenes (not really) def sieve(v:Vector) -> object: i:int = 0 j:int = 0 k:int = 0 while i < v.length(): k = v.get(i) j = i + 1 while j < v.length(): if v.get(j) % k == 0: v.remove_at(j) else: j = j + 1 i = i + 1 def sieve2(v:Vector, v2:Vector) -> object: i:int = 0 i2:int = 0 j:int = 0 j2:int = 0 k:int = 0 k2:int = 0 while i < v.length(): k = v.get(i) j = i + 1 while j < v.length(): if v.get(j) % k == 0: v.remove_at(j) else: j = j + 1 i = i + 1 def sieve3(v:Vector, v2:Vector, v3:Vector) -> object: i:int = 0 i2:int = 0 i3:int = 0 j:int = 0 j2:int = 0 j3:int = 0 k:int = 0 k2:int = 0 k3:int = 0 while i < v.length(): k = v.get(i) j = i + 1 while j < v.length(): if v.get(j) % k == 0: v.remove_at(j) else: j = j + 1 i = i + 1 def sieve4(v:Vector, v2:Vector, v3:Vector, v4:Vector) -> object: i:int = 0 i2:int = 0 i3:int = 0 i4:int = 0 j:int = 0 j2:int = 0 j3:int = 0 j4:int = 0 k:int = 0 k2:int = 0 k3:int = 0 k4:int = 0 while i < v.length(): k = v.get(i) j = i + 1 while j < v.length(): if v.get(j) % k == 0: v.remove_at(j) else: j = j + 1 i = i + 1 def sieve5(v:Vector, v2:Vector, v3:Vector, v4:Vector, v5:Vector) -> object: i:int = 0 i2:int = 0 i3:int = 0 i4:int = 0 i5:int = 0 j:int = 0 j2:int = 0 j3:int = 0 j4:int = 0 j5:int = 0 k:int = 0 k2:int = 0 k3:int = 0 k4:int = 0 k5:int = 0 while i < v.length(): k = v.get(i) j = i + 1 while j < v.length(): if v.get(j) % k == 0: v.remove_at(j) else: j = j + 1 i = i + 1 # Input parameter n:int = 50 n2:int = 50 n3:int = 50 n4:int = 50 n5:int = 50 # Data v:Vector = None v2:Vector = None v3:Vector = None v4:Vector = None v5:Vector = None i:int = 0 i2:int = 0 i3:int = 0 i4:int = 0 i5:int = 0 # Crunch v = vrange(2, n) v2 = vrange(2, n) v3 = vrange(2, n) v4 = vrange(2, n) v5 = vrange(2, n) sieve(v) # Print while i < v.length(): print(v.get(i)) i = i + 1
[ "647530+Virtlink@users.noreply.github.com" ]
647530+Virtlink@users.noreply.github.com
1bf4ffff53b8443cb6cfe76a345fc9e1f3d53794
ce2573d39de26cc3dda2a87c1e8746d1d3ff7e4c
/xml_to_csv.py
8f62e960c4fcbef47d7c7dad0a1845c5c42adda6
[]
no_license
krestovolt/cat-dog-breed-detection
2779e30528d4dd63e795439cfa9a9c3b7b3da82d
5fe3566266e087b251c84054f565561adccafa84
refs/heads/master
2021-05-05T12:09:29.605083
2018-01-20T07:44:45
2018-01-20T07:44:45
118,212,311
0
2
null
null
null
null
UTF-8
Python
false
false
2,330
py
import os import glob import pandas as pd import xml.etree.ElementTree as ET from tqdm import tqdm def xml_to_csv(path): xml_list = [] _files = glob.glob(path + '/*.xml') for xml_file in tqdm(_files, total = len(_files)): image_name = os.path.basename(xml_file) image_name = image_name.split('.')[0] + '.jpg' class_name = image_name.split('_')[:-1] class_name = '_'.join(class_name) tree = ET.parse(xml_file) root = tree.getroot() for member in root.findall('object'): value = (image_name, int(root.find('size')[0].text), int(root.find('size')[1].text), class_name, int(member[4][0].text), int(member[4][1].text), int(member[4][2].text), int(member[4][3].text) ) xml_list.append(value) # print('', # image_name,'\n', # class_name,'\n', # root.find('size')[0].text,'\n', # root.find('size')[1].text,'\n', # member[0],'\n', # member[4][0],'\n', # member[4][1],'\n', # member[4][2],'\n', # member[4][3],'\n') column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax'] xml_df = pd.DataFrame(xml_list, columns=column_name) return xml_df # def main(): # image_path = os.path.join(os.getcwd(), 'annotations') # xml_df = xml_to_csv(image_path) # xml_df.to_csv('raccoon_labels.csv', index=None) # print('Successfully converted xml to csv.') def main(): for directory in ['train','test']: data_path = os.path.join(os.getcwd(), 'data/{}'.format(directory)) xml_df = xml_to_csv(data_path) xml_df.to_csv('data/{}_labels.csv'.format(directory), index=None) print('Successfully converted xml to csv.') # def main(): # image_path = os.path.join(os.getcwd(), 'annotations/xmls') # print(image_path) # xml_df = xml_to_csv(image_path) # # xml_df.to_csv('data/{}_labels.csv'.format(directory), index=None) # print('Successfully converted xml to csv.') if __name__ == '__main__': main()
[ "kautsar.ab@gmail.com" ]
kautsar.ab@gmail.com
8939cb11b44574e3ae4666bb7ed1698550d192c4
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5756407898963968_0/Python/eding/A-small-code.py
e5ebfa779d5c7ca729204629dbea0f829a594e03
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
Python
false
false
939
py
import codecs import sys N_ROWS = 4 def main(): file = codecs.open(sys.argv[1], "r", "utf-8-sig") lines = [line.strip() for line in file] T = int(lines[0]) cards1 = [] cards2 = [] index = 1 for trial in xrange(0,T): ans1 = int(lines[index]) cards1 = map(int, lines[index+ans1].split()) index += 5 ans2 = int(lines[index]) cards2 = map(int, lines[index+ans2].split()) index += 5 intersect = [card for card in cards1 if card in cards2] sys.stdout.write("Case #%d: " % (trial+1)) if len(intersect) < 1: sys.stdout.write("Volunteer cheated!\n") elif len(intersect) == 1: sys.stdout.write("%d\n" % intersect[0]) elif len(intersect) > 1: sys.stdout.write("Bad magician!\n") if __name__ == '__main__': main()
[ "eewestman@gmail.com" ]
eewestman@gmail.com
939366fbf9f7400868db1cfbd33d24ecd10c9608
51a0077af1cd234e081b8d0c4f9fb9cccf983fa6
/examples/drawDistribution.py
c67a7464c97fae610fbe523684262b328014ee51
[ "MIT" ]
permissive
wangyuan249/Mymmt767
9a2e127f086a3feaa4538d6c5dce87f89bd04bd0
6b9bb566d290bd3157350f6496fcb5df8c2b515c
refs/heads/main
2023-04-20T01:03:20.407482
2021-05-16T16:44:28
2021-05-16T16:44:28
367,935,789
0
0
null
null
null
null
UTF-8
Python
false
false
1,479
py
import matplotlib.pyplot as plt import numpy as np import math import pdb def dotProduct(v1, v2): v1 = np.mat(v1) v2 = np.mat(v2) z = v1 * v2.T return z if __name__ == '__main__': feature = np.load("similarity_list_3.npy") print(feature.__class__) print(feature.shape) similarity_list = [] feature = feature.reshape(32, 2048, 128) # pdb.set_trace() # print(feature.shape(2).__class__) for k in range(0, feature.shape[0]): for i in range(0, feature.shape[2]): for j in range(0, feature.shape[2]): vector1 = feature[k, :, i] vector2 = feature[k, :, j] cosine = dotProduct(vector1, vector2) / \ math.sqrt(dotProduct(vector1, vector1) * dotProduct(vector2, vector2)) # print("cosine: ", cosine) similarity_list.append(cosine) print("k", k) similarity_list = np.array(similarity_list).reshape(524288) T = np.linspace(0.0, 1.0, num=1000) sim_dis = np.zeros(1000) for item in similarity_list: if(int(item*1000) == 1000): continue sim_dis[int(item*1000)-1] += 1 # power = np.array([1.53E+03, 5.92E+02, 2.04E+02, 7.24E+01, 2.72E+01, 1.10E+01, 4.70E+00]) plt.plot(T,sim_dis) # 绘图 # plt.bar(x=T, height=sim_dis, label='Similarity distribution', color='steelblue', alpha=0.8) plt.show()
[ "249401644@qq.com" ]
249401644@qq.com
31568c8831b174a67e23d04ae523c6729bc766c7
ed9b2c3d96e4251acaa93412b0982cfea51d9dba
/Batch Lesson/operadores_asignacion.py
2d6f826473724556dd5cfeabcdd0b5c9ef79f082
[]
no_license
Dagorik/Batch17Roja
f98c49dc2a24bc74df725e1ecd937fc9b78757fe
266948741d0c2900a9885e3dedc7e894d8573e3b
refs/heads/master
2021-08-23T22:02:40.672409
2017-12-06T19:14:25
2017-12-06T19:14:25
108,353,295
1
4
null
null
null
null
UTF-8
Python
false
false
59
py
x = 5 print(x) x+=10 print(x) x-=10 print(x) x*=10 print(x)
[ "dagorik@gmail.com" ]
dagorik@gmail.com
57dba22400c00b7b658ab8feeab0d24681e26898
a1a8b087a2fe9bf3f6ac27cf37c23484039e9b4f
/env/bin/flask
c9828d13240e322a069af19dbb315a6e42e5cf72
[]
no_license
16014958/week_03
4b0ffe496d10d50ec57a7f6b56532193d019b4cf
76d95cea83a656b29809322b618344492a28a78d
refs/heads/master
2020-03-25T12:33:52.312395
2018-08-06T20:56:01
2018-08-06T20:56:01
143,782,409
0
0
null
null
null
null
UTF-8
Python
false
false
248
#!/Users/callumradford/Desktop/week_03/env/bin/python3 # -*- coding: utf-8 -*- import re import sys from flask.cli import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(main())
[ "callumradford26@gmail.com" ]
callumradford26@gmail.com
e2f530e510936ac5f726ee45cd632a5f4b2067bc
eb0681df9f79394b6d6b6ef51cdb09e96b351567
/faculty/views.py
19a99d5e3c88b45a05add839c531540e7a77d8b5
[]
no_license
sinaesmaili216/univercity
4ff4e06f212f57667b987bc09a3879e077c353c5
5bc90db373c702aca60082129a6294da436e9726
refs/heads/master
2023-07-21T22:46:56.309763
2021-09-02T19:58:39
2021-09-02T19:58:39
400,893,312
0
0
null
null
null
null
UTF-8
Python
false
false
5,774
py
from django.db.models import Q from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, redirect from faculty.models import Class, Student, Lesson, Master, User from .forms import CreateStudent, SelectLesson, LoginForm, EditLessonsByMaster, RegisterMaster from django.contrib.auth import authenticate, login, logout def index(request): return render(request, 'faculty/index.html') def login_user(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = authenticate(email=email, password=password) if user: login(request, user) return render(request, 'faculty/index.html') else: return HttpResponse('email or password is incorrect') else: form = LoginForm() return render(request, 'faculty/login.html', context={'form': form}) def logout_user(request): logout(request) return redirect('faculty:login') def show_class_list(request): classes = Class.objects.all() context = { 'classes': classes } return render(request, 'faculty/class_lists.html', context) def search_in_class_list(request): search_word = request.POST['search'] class_name = Class.objects.filter((Q(name__contains=search_word) | Q(lessons__name__contains=search_word))) if class_name: students = class_name.get().students.all lessons = class_name.get().lessons.all context = { 'lessons': lessons, 'students': students } else: return HttpResponseRedirect('faculty:class_list') return render(request, 'faculty/class_info.html', context) def class_info(request, name): class_name = Class.objects.get(name=name) lessons = class_name.lessons.all students = class_name.students.all context = { 'lessons': lessons, 'students': students } return render(request, 'faculty/class_info.html', context) def create_student(request): if request.method == 'POST': form = CreateStudent(request.POST) if form.is_valid(): nation_code = form['nation_code'].value() student = Student.objects.filter(nation_code=nation_code) if student: return HttpResponse('this student is exist') else: email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') create_new_user = User.objects.create_user(email=email, password=password) create_new_user.is_student = True create_new_user.save() first_name = form.cleaned_data.get('first_name') last_name = form.cleaned_data.get('last_name') nation_code = form.cleaned_data.get('nation_code') age = form.cleaned_data.get('age') faculty = form.cleaned_data.get('faculty') phone = form.cleaned_data.get('phone') print(phone) new_student = Student.objects.create(first_name=first_name, last_name=last_name, nation_code=nation_code, age=age, user=create_new_user, faculty=faculty, phone=phone) new_student.save() login(request, create_new_user) return redirect('faculty:index') else: form = CreateStudent() return render(request, 'faculty/create_student.html', context={'form': form}) def select_lesson(request): if request.method == 'POST': form = SelectLesson(request.POST) if form.is_valid(): lessons = form.cleaned_data.get('lessons') student = Student.objects.get(user=request.user) [student.lessons.add(Lesson.objects.get(name=lesson)) for lesson in lessons] return HttpResponse('lesson added') else: form = SelectLesson() return render(request, 'faculty/select_lesson.html', context={'form': form}) def students_list(request): all_students = Student.objects.all() return render(request, 'faculty/students_list.html', context={'students': all_students}) def edit_student_lessons_by_master(request, student_name): student = Student.objects.get(first_name=student_name) if request.method == 'POST': form = EditLessonsByMaster(request.POST) if form.is_valid(): lessons = form.cleaned_data.get('lessons') for lesson in lessons: lesson = Lesson.objects.get(name=lesson) student.lessons.add(lesson) return HttpResponse('changes saved') else: form = EditLessonsByMaster() return render(request, 'faculty/edit_lesson_by_master.html', context={'student': student, 'form': form}) def register_master(request): if request.method == 'POST': form = RegisterMaster(request.POST) if form.is_valid(): first_name = form.cleaned_data.get('first_name') last_name = form.cleaned_data.get('last_name') email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') new_user = User.objects.create_user(email=email, password=password) new_user.is_teacher = True new_user.save() create_new_master = Master.objects.create(user=new_user, first_name=first_name, last_name=last_name) create_new_master.save() login(request, new_user) return redirect('faculty:index') else: form = RegisterMaster() return render(request, 'faculty/register_master.html', context={'form': form})
[ "sinaesmaili216@gmail.com" ]
sinaesmaili216@gmail.com
2a71d4e4609f4cb41aed46f48f4dc1917e9612b9
9c570e147dab670a91505eef1ca56c3aab64e5a5
/Crypto/urls.py
9dc922ae67e15d61112f52a75a10afd138edcdc6
[]
no_license
Alireza-Helali/crypto-price-tracker
b0a71cf61b59b8723d407532c3c638ae32f44c4e
e7ac3fcb8a103ae5199a12d2e1ad715d86d8c3cb
refs/heads/master
2023-04-12T01:06:21.614706
2021-05-14T17:51:44
2021-05-14T17:51:44
349,701,824
0
0
null
null
null
null
UTF-8
Python
false
false
798
py
"""Crypto 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, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('positions.urls')), ]
[ "a.helali1995@example.com" ]
a.helali1995@example.com
ae8d67d7deda38b735bb7e18ddb5f030a8c4027e
be699e538fc03a2087c430e4771cf9f26e19b16c
/cifar10/resnet_keras_feature_fusion_v2.py
8cec36117d0816e366c91db4996cf0b4c489241b
[]
no_license
fanW96/Fusion_Diversity
ed671ebf266c6cb0740ff8a7853d1ba0be42c21e
a66b0b49f24b81b72a9483244e28649cecfa2d9d
refs/heads/main
2023-02-04T21:38:08.590034
2020-12-28T11:21:52
2020-12-28T11:21:52
324,986,899
0
0
null
null
null
null
UTF-8
Python
false
false
12,282
py
import keras import numpy as np import tensorflow as tf from keras.datasets import cifar10 from keras.preprocessing.image import ImageDataGenerator from keras.layers import Conv2D, Dense, Input, Add, Activation, GlobalAveragePooling2D, BatchNormalization, UpSampling2D, Concatenate, Reshape, Flatten, Average from keras.callbacks import LearningRateScheduler, TensorBoard, ModelCheckpoint from keras.models import Model, load_model from keras import optimizers, regularizers import keras.backend as K # from livelossplot.keras import PlotLossesCallback from train_plot import PlotLearning from functools import partial class ResNet_v2: def __init__(self, epochs=250, batch_size=128, load_weights=True,level="32",transfer=False,x_train=None,y_train=None,x_val=None,y_val=None,loss_fn=None,istransfer=False): self.name = 'resnet_'+level+'_fusion_diversity_avg' #'resnet_cifar10' if dataset=='cifar10' else 'resnet_mnist' self.model_filename = 'models/'+self.name+'.h5' self.stack_n = 5 self.num_classes = 10 self.img_rows = x_train.shape[1] self.img_cols = x_train.shape[2] self.img_channels = x_train.shape[3] self.batch_size = batch_size self.epochs = epochs self.iterations = x_train.shape[0] // self.batch_size # MNIST数据集应该是60000 self.weight_decay = 0.0001 self.log_filepath = r'logs/v2/' self._model = None # 防止后续出现未定义的情况 self.param_count = None self.x_train,self.y_train = x_train,y_train self.x_val,self.y_val = x_val,y_val self.loss_fn = None # loss_fn if loss_fn is not None else 'categorical_crossentropy' self.transfer = istransfer if load_weights: try: self._model = load_model(self.model_filename) # _model表示私有变量,保存了.h5加载过来的参数,load_model库函数详见models.py self.param_count = self._model.count_params() print('Successfully loaded', self.name) except (ImportError, ValueError, OSError): print('Failed to load', self.name) def Entropy(self, input): #input shape is batch_size X num_class return tf.reduce_sum(-tf.multiply(input, tf.log(input + 1e-20)), axis=-1) def Ensemble_Entropy(self, p3, p2, p1): y_p_all = 0 y_p_all += p3 y_p_all += p2 y_p_all += p1 Ensemble = self.Entropy(y_p_all / 3) return Ensemble def log_det(self, p3, p2, p1, y_true_one): zero = tf.constant(0, dtype=tf.float32) det_offset = 1e-6 num_model = 3 y_true = [] y_true.append(y_true_one) y_true.append(y_true_one) y_true.append(y_true_one) y_true = K.concatenate(y_true) y_true = K.reshape(y_true, (-1, 10, 3)) y_pred = [] y_pred.append(p3) y_pred.append(p2) y_pred.append(p1) y_pred = K.concatenate(y_pred) y_pred = K.reshape(y_pred, (-1, 10, 3)) bool_R_y_true = tf.not_equal(tf.ones_like(y_true) - y_true, zero) # batch_size X (num_class X num_models), 2-D mask_non_y_pred = tf.boolean_mask(y_pred, bool_R_y_true) # batch_size X (num_class-1) X num_models, 1-D mask_non_y_pred = tf.reshape(mask_non_y_pred, [-1, num_model, self.num_classes-1]) # batch_size X num_model X (num_class-1), 3-D mask_non_y_pred = mask_non_y_pred / tf.norm(mask_non_y_pred, axis=2, keepdims=True) # batch_size X num_model X (num_class-1), 3-D matrix = tf.matmul(mask_non_y_pred, tf.transpose(mask_non_y_pred, perm=[0, 2, 1])) # batch_size X num_model X num_model, 3-D all_log_det = tf.linalg.logdet(matrix+det_offset*tf.expand_dims(tf.eye(num_model),0)) # batch_size X 1, 1-D return all_log_det def custome_loss(self, y_true, y_pred, p3, p2, p1): lamda = 1 log_det_lamda = 0.5 ce_final = K.categorical_crossentropy(y_true, y_pred) ce_fusion = 0 ce_fusion += K.categorical_crossentropy(y_true, p3) ce_fusion += K.categorical_crossentropy(y_true, p2) ce_fusion += K.categorical_crossentropy(y_true, p1) ee = self.Ensemble_Entropy(p3, p2, p1) log_dets = self.log_det(p3, p2, p1, y_true) return ce_final + ce_fusion - lamda * ee - log_det_lamda * log_dets def construct(self): # build network img_input = Input(shape=(self.img_rows,self.img_cols,self.img_channels)) output, p3, p2, p1 = self.residual_network(img_input,self.num_classes,self.stack_n) self._model = Model(img_input, output) self.loss_fn = partial(self.custome_loss, p3=p3, p2=p2, p1=p1) self.loss_fn.__name__ = "EE_ADP" # self._model.summary() def scheduler(self, epoch): lr = 1e-3 if epoch > 220: lr *= 1e-3 elif epoch > 150: lr *= 1e-2 elif epoch > 80: lr *= 1e-1 print('Learning rate: ', lr) return lr def residual_network(self, img_input,classes_num=10,stack_n=5): # ResNet参数,但不包括weights # 一个残差块!!! 从模型图片来看就是从一个Add到另一个Add之间的部分 def residual_block(intput, out_channel,increase=False, stage=0, block=0): if increase: stride = (2,2) else: stride = (1,1) pre_bn = BatchNormalization()(intput) # (input)为这一层的输入 pre_relu = Activation('relu')(pre_bn) conv_1 = Conv2D(out_channel,kernel_size=(3,3),strides=stride,padding='same', kernel_initializer="he_normal", # he_normal——he正态分布初始化 kernel_regularizer=regularizers.l2(self.weight_decay))(pre_relu) # 记得改回去 —— 修改残差块 bn_1 = BatchNormalization()(conv_1) relu1 = Activation('relu')(bn_1) conv_2 = Conv2D(out_channel,kernel_size=(3,3),strides=(1,1),padding='same', kernel_initializer="he_normal", kernel_regularizer=regularizers.l2(self.weight_decay))(relu1) if increase: # 印证了结构图中有的会在右侧线路中多一个卷积层 projection = Conv2D(out_channel, kernel_size=(1,1), strides=(2,2), padding='same', kernel_initializer="he_normal", kernel_regularizer=regularizers.l2(self.weight_decay))(intput) block = Add(name='block_'+str(stage)+'_'+str(block))([conv_2, projection]) else: block = Add(name='block_'+str(stage)+'_'+str(block))([intput,conv_2]) # 残差的概念:块中的最后一个输出和块中的第一个输入要相加 return block # build model # total layers = stack_n * 3 * 2 + 2 # stack_n = 5 by default, total layers = 32 # input: 32x32x3 output: 32x32x16 x = Conv2D(filters=16,kernel_size=(3,3),strides=(1,1),padding='same', kernel_initializer="he_normal", kernel_regularizer=regularizers.l2(self.weight_decay))(img_input) # input: 32x32x16 output: 32x32x16 for i in range(stack_n): x = residual_block(x,16,False, stage=1, block=i) # 16就是channel!与输入维度无关,最终结果直接由输出维度决定 exit1 = BatchNormalization()(x) exit1 = Activation('relu')(exit1) x = residual_block(x,32,True, stage=2, block=0) for i in range(1,stack_n): x = residual_block(x,32,False, stage=2, block=i) exit2 = BatchNormalization()(x) exit2 = Activation('relu')(exit2) # input: 16x16x32 output: 8x8x64 x = residual_block(x,64,True, stage=3, block=0) for i in range(1,stack_n): x = residual_block(x,64,False, stage=3, block=i) exit3 = BatchNormalization()(x) exit3 = Activation('relu')(exit3) p3 = Conv2D(64, kernel_size=(1,1))(exit3) p2 = Add()([ UpSampling2D(size=(2,2))(p3), Conv2D(64, kernel_size=(1,1))(exit2) ]) p1 = Add()([ UpSampling2D(size=(2,2))(p2), Conv2D(64, kernel_size=(1,1))(exit1) ]) # 16*16*128 p1 = Conv2D(128, kernel_size=(3, 3), strides=(2, 2), padding='same')(p1) # 8*8*128 p1 = Conv2D(128, kernel_size=(1, 1), strides=(2, 2), padding='same')(p1) p1 = GlobalAveragePooling2D()(p1) p1 = Dense(classes_num, kernel_initializer="he_normal", kernel_regularizer=regularizers.l2(self.weight_decay))(p1) # 8*8*128 p2 = Conv2D(128, kernel_size=(3, 3), strides=(2, 2), padding='same')(p2) p2 = GlobalAveragePooling2D()(p2) p2 = Dense(classes_num, kernel_initializer="he_normal", kernel_regularizer=regularizers.l2(self.weight_decay))(p2) # 8*8*128 p3 = Conv2D(128, kernel_size=(1, 1), strides=(1, 1), padding='same')(p3) p3 = GlobalAveragePooling2D()(p3) p3 = Dense(classes_num, kernel_initializer="he_normal", kernel_regularizer=regularizers.l2(self.weight_decay))(p3) p1 = Activation('softmax')(p1) p2 = Activation('softmax')(p2) p3 = Activation('softmax')(p3) out_inner = [] out_inner.append(p3) out_inner.append(p2) out_inner.append(p1) out = Average()(out_inner) return out, p3, p2, p1 def train(self): if not self.transfer: self.construct() if self.x_val is not None and self.y_val is not None: validation_data=(self.x_val, self.y_val) else: validation_data=None # set optimizer # sgd = optimizers.SGD(lr=.1, momentum=0.9, nesterov=True) # momentum-动量法,nesterov-NAG adam = optimizers.Adam() self._model.compile(loss=self.loss_fn, optimizer=adam, metrics=['accuracy']) self._model.summary() # set callback tb_cb = TensorBoard(log_dir=self.log_filepath, histogram_freq=0) change_lr = LearningRateScheduler(self.scheduler) checkpoint = ModelCheckpoint('models/'+self.name+'_weight_best'+'.h5', # 这里保存了model monitor='val_acc', verbose=0, save_best_only= True, mode='auto', save_weights_only=True) plot_callback = PlotLearning() cbks = [ tb_cb, checkpoint, plot_callback, change_lr] # set data augmentation print('Using real-time data augmentation.') datagen = ImageDataGenerator(horizontal_flip=True, width_shift_range=0.125, height_shift_range=0.125, fill_mode='constant',cval=0.) datagen.fit(self.x_train) # def generate_3out(generator, x, y, batch_size): # gen = generator.flow(x, y, batch_size=batch_size) # while True: # (x1, y1) = gen.next() # # y2 = y1.copy() # # y3 = y1.copy() # yield (x1, [y1, y1 ,y1]) # start training self._model.fit_generator(datagen.flow(self.x_train, self.y_train, batch_size=self.batch_size), steps_per_epoch=self.iterations, epochs=self.epochs, callbacks=cbks, validation_data=validation_data) # self._model.save('models/'+self.name+'_3out'+'.h5') self.param_count = self._model.count_params() def accuracy(self): return self._model.evaluate(self.x_val, self.y_val, verbose=0)
[ "fanw9611@163.com" ]
fanw9611@163.com
2128f2350f92bfc597eb04b261dba5bd11281714
65402c579b40377184baa65a806044a8cc760540
/myproducts/myproducts/www/stock.py
f7cc1db1fa11f2a3a2624f123bec400f39d89c75
[ "MIT" ]
permissive
mado2461990/ERPNext-E-Commerce-
040862653eb7472766a01aa9f824edfd567bb23d
b20d171faaa75eea2a21e1a40602799bd4aebd67
refs/heads/master
2021-01-12T08:00:15.348165
2016-12-21T16:46:21
2016-12-21T16:46:21
77,080,800
1
0
null
2016-12-21T19:37:18
2016-12-21T19:37:18
null
UTF-8
Python
false
false
969
py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import sys reload(sys) sys.setdefaultencoding('utf-8') base_template_path = "stock.html" import os, re import frappe from frappe import _ def get_context(context): # context.items = frappe.get_list('Item' ,'item_name,item_group,item_code,quantity') # context.items_price = frappe.get_list('Item Price', 'price_list_rate') raw = frappe.db.sql("""SELECT tabItem.item_name, tabItem.item_group, tabItem.thumbnail, tabItem.quantity, `tabItem Price`.price_list_rate, tabItem.item_code, tabItem.name from tabItem INNER JOIN `tabItem Price` ON tabItem.item_code = `tabItem Price`.item_code""") context.items = list(raw) #context.items_price = frappe.get_list('Item Price','item_code') # return { "doc": frappe.get_doc('Item') } #context.items = frappe.get_list('Item','item_name,item_group' )
[ "noreply@github.com" ]
noreply@github.com
a2a4196517debb6b29438efaef7424708c6a4b21
8ab0d1c0f60805d5bcf17fff95da262a6361437b
/pages/migrations/0001_initial.py
a266b0418b490a8af96b48658f20ae47febe7c24
[]
no_license
singadkamlesh/new_carzone
b556bbb16f6f7336abe83f11cf300a54700c630a
a45f818949a9d6435a537e974c172bdd890405df
refs/heads/main
2023-08-21T23:06:41.769820
2021-10-17T18:12:54
2021-10-17T18:12:54
410,552,697
0
0
null
null
null
null
UTF-8
Python
false
false
848
py
# Generated by Django 3.2.7 on 2021-10-05 19:13 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Trainers', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(max_length=255)), ('last_name', models.CharField(max_length=255)), ('designation', models.CharField(max_length=255)), ('photo', models.ImageField(upload_to='photos/%y/%m/%d/')), ('about_member', models.CharField(max_length=160)), ('created_date', models.DateTimeField(auto_now_add=True)), ], ), ]
[ "singadkamlesh1112@gmail.com" ]
singadkamlesh1112@gmail.com
8fa22e266e0395f7382bd4b576c237e3c295500c
97d4111cdd3b0657c05313eba0f555d4c5b9591a
/python/Find_Cuts.py
123924453c8190aaac165044998a81a15fd8d9cd
[]
no_license
ViniciusMikuni/ttbb-analysis
9d2b6fcf5adb4f26f813a0ca479657c5e62201e5
5d48e5e03bdd0ca162d3dd058f4ee02ef33a8460
refs/heads/master
2021-04-06T02:27:26.282579
2020-01-31T11:34:50
2020-01-31T11:34:50
125,236,195
0
1
null
2020-01-31T11:34:52
2018-03-14T15:44:17
C
UTF-8
Python
false
false
1,442
py
import os import sys import ROOT as rt import tdrstyle import CMS_lumi import array from Plotting_cfg import * import numpy as np from math import * from itertools import product rt.gROOT.SetBatch(True) rt.gROOT.LoadMacro("triggerWeightRound.h+") watch = rt.TStopwatch() npoints = 2 ntrials = 2 processlist = ['data','ttbar'] interestVar = { 'BDT_CWoLa':np.arange(-1,1,2.0/npoints), 'BDT_Comb':np.arange(-1,1,2/npoints), #'prob_chi2':np.arange(0,0.006,0.006/npoints) } def MakeCuts(rangelist): cutlist = [] allcuts = [] for var in interestVar: cut = [] for val in rangelist[var]: cut.append(var+'[0]>='+str(val)) cutlist.append(cut) for c in list(product(*cutlist)): allcuts.append("&&".join(c)) return allcuts else: files = [] tree = [] asi = 0 bestcut = 0 rt.ROOT.EnableImplicitMT() TDF = rt.ROOT.Experimental.TDataFrame dbkg = TDF('tree',processfiles['data']) dsig = TDF('tree',processfiles['ttbar']) allcuts = MakeCuts(interestVar) for i in range(ntrials): for l, c in enumerate(allcuts): sig = dsig.Filter(c).Count().GetValue()*dscale['ttbar'] bkg = dbkg.Filter(c).Count().GetValue() - sig if sig/sqrt(sig+bkg)>asi: asi = sig/sqrt(sig+bkg) bestcut = l print allcuts[bestcut], 'with significance: ',asi watch.Print()
[ "vinicius.mikuni@gmail.com" ]
vinicius.mikuni@gmail.com
82988061d49923ba2608f9ad81a26352284fa476
cffd34002a945a7b7df40faea9b61c88c7a6cdb2
/content/migrations/0002_alter_customuser_options.py
a0acd30726342c49f8f8ec3177fd56aa91f83afd
[]
no_license
binel01/binel_blog_api
c6f21e8c939e912c65f5ab8e49f9960fc9fb24e9
e939dadcd84cec7a41367d702303ef2c543ca328
refs/heads/main
2023-06-15T16:48:21.774169
2021-07-18T21:17:12
2021-07-18T21:17:12
387,239,410
1
0
null
null
null
null
UTF-8
Python
false
false
382
py
# Generated by Django 3.2 on 2021-07-18 20:36 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('content', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='customuser', options={'verbose_name': 'customuser', 'verbose_name_plural': 'customusers'}, ), ]
[ "binelimanga@gmail.com" ]
binelimanga@gmail.com
9273d11433c99cd486d59b7efcdbdf73ababd159
83ed75056a4fa0a26e363ecf80fdb5390b9abe76
/web/decisions/subscriptions/__init__.py
ec796c778fac00714e1a872800e4d04f22d29a5c
[ "BSD-3-Clause" ]
permissive
okffi/decisions
a67ef9150dfa8585b82bb95da323e5b354be4532
e45d8c56cf244ef277ffeba6808e942564028b7f
refs/heads/master
2021-01-21T13:34:03.416056
2016-05-25T09:58:51
2016-05-25T09:58:51
53,145,413
3
2
null
2016-05-02T11:31:34
2016-03-04T15:36:21
JavaScript
UTF-8
Python
false
false
72
py
default_app_config = 'decisions.subscriptions.apps.SubscriptionsConfig'
[ "leo.o.honkanen@gmail.com" ]
leo.o.honkanen@gmail.com
90bd6692ba1c920aebf545909f10a2d5fe660622
c8036cb365243439b4a3593124eafdfba933a034
/src/loss/normal_6_class.py
445ac4273311e941f342bfc5794d5eeaf8cc2e37
[]
no_license
koike-ya/rsna
3a1150dc878bde6320ae4c1d965675460dd7de0d
c88c45cfa280b47f0fb48cc9df88954f83a551b4
refs/heads/master
2022-03-16T00:36:55.846905
2019-11-02T00:49:15
2019-11-02T00:49:15
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,715
py
dir_csv = '../../input/' dir_train_img = '../../input/stage_1_train_pngs/' dir_test_img = '../../input/stage_1_test_pngs/' # Parameters n_classes = 6 n_epochs = 5 batch_size = 32 import glob import os from pathlib import Path import cv2 import numpy as np import pandas as pd import pydicom import torch import torch.optim as optim from albumentations import Compose, ShiftScaleRotate, CenterCrop, HorizontalFlip, RandomBrightnessContrast from albumentations.pytorch import ToTensor from skimage.transform import resize from torch.utils.data import Dataset from tqdm import tqdm as tqdm from apex import amp CT_LEVEL = 40 CT_WIDTH = 150 def rescale_pixelarray(dataset): image = dataset.pixel_array rescaled_image = image * dataset.RescaleSlope + dataset.RescaleIntercept rescaled_image[rescaled_image < -1024] = -1024 return rescaled_image def set_manual_window(hu_image, custom_center, custom_width): min_value = custom_center - (custom_width / 2) max_value = custom_center + (custom_width / 2) hu_image[hu_image < min_value] = min_value hu_image[hu_image > max_value] = max_value return hu_image class IntracranialDataset(Dataset): def __init__(self, csv_file, data_dir, labels, ct_level=0, ct_width=0, transform=None): self.data_dir = data_dir self.data = pd.read_csv(csv_file) self.transform = transform self.labels = labels self.level = ct_level self.width = ct_width self.nn_input_shape = (224, 224) def __len__(self): return len(self.data) def resize(self, image): image = resize(image, self.nn_input_shape) return image def fill_channels(self, image): filled_image = np.stack((image,)*3, axis=-1) return filled_image def _get_hounsfield_window(self, dicom): hu_image = rescale_pixelarray(dicom) windowed_image = set_manual_window(hu_image, self.level, self.width) return windowed_image def _load_dicom_to_image(self, file_path): dicom = pydicom.dcmread(file_path) windowed_image = self._get_hounsfield_window(dicom) image = self.fill_channels(self.resize(windowed_image)) return image def __getitem__(self, idx): file_path = os.path.join(self.data_dir, self.data.loc[idx, 'Image'] + '.png') from pathlib import Path if not Path(file_path).is_file(): return self.__getitem__(idx + 1) # img = self._load_dicom_to_image(file_path) img = cv2.imread(file_path) if self.transform: augmented = self.transform(image=img) img = augmented['image'] if self.labels: labels = torch.tensor( self.data.loc[idx, ['epidural', 'intraparenchymal', 'intraventricular', 'subarachnoid', 'subdural', 'any']]) return {'image': img, 'labels': labels} else: return {'image': img} # # CSV # In[7]: # CSVs if __name__ == '__main__': if not Path('../../src/train.csv').is_file(): train = pd.read_csv(os.path.join(dir_csv, 'stage_1_train.csv')) test = pd.read_csv(os.path.join(dir_csv, 'stage_1_sample_submission.csv')) # Split train out into row per image and save a sample train[['ID', 'Image', 'Diagnosis']] = train['ID'].str.split('_', expand=True) train = train[['Image', 'Diagnosis', 'Label']] train.drop_duplicates(inplace=True) train = train.pivot(index='Image', columns='Diagnosis', values='Label').reset_index() train['Image'] = 'ID_' + train['Image'] train.head() # Some files didn't contain legitimate images, so we need to remove them png = glob.glob(os.path.join(dir_train_img, '*.png')) png = [os.path.basename(png)[:-4] for png in png] png = np.array(png) train = train[train['Image'].isin(png)] train.to_csv('train.csv', index=False) # Also prepare the test data test[['ID','Image','Diagnosis']] = test['ID'].str.split('_', expand=True) test['Image'] = 'ID_' + test['Image'] test = test[['Image', 'Label']] test.drop_duplicates(inplace=True) test.to_csv('test.csv', index=False) # Data loaders transform_train = Compose([CenterCrop(200, 200), #Resize(224, 224), HorizontalFlip(), RandomBrightnessContrast(), ShiftScaleRotate(), ToTensor() ]) transform_test= Compose([CenterCrop(200, 200), #Resize(224, 224), ToTensor() ]) train_dataset = IntracranialDataset( csv_file='train.csv', data_dir=dir_train_img, transform=transform_train, labels=True) test_dataset = IntracranialDataset( csv_file='test.csv', data_dir=dir_test_img, transform=transform_test, labels=False) data_loader_train = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=False, num_workers=8) data_loader_test = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=8) device = torch.device("cuda:0") # device = torch.device("cpu") # model = torch.hub.load('facebookresearch/WSL-Images', 'resnext101_32x8d_wsl') model = torch.hub.load('pytorch/vision', 'shufflenet_v2_x1_0', pretrained=True) model.fc = torch.nn.Linear(1024, n_classes) model.to(device) criterion = torch.nn.BCEWithLogitsLoss() plist = [{'params': model.parameters(), 'lr': 2e-5}] optimizer = optim.Adam(plist, lr=2e-5) model, optimizer = amp.initialize(model, optimizer, opt_level="O1") for epoch in range(n_epochs): print('Epoch {}/{}'.format(epoch, n_epochs - 1)) print('-' * 10) model.train() tr_loss = 0 tk0 = tqdm(data_loader_train, desc="Iteration") for step, batch in enumerate(tk0): inputs = batch["image"] labels = batch["labels"] inputs = inputs.to(device, dtype=torch.float) labels = labels.to(device, dtype=torch.float) outputs = model(inputs) loss = criterion(outputs, labels) with amp.scale_loss(loss, optimizer) as scaled_loss: scaled_loss.backward() # loss.backward() tr_loss += loss.item() optimizer.step() optimizer.zero_grad() if epoch == 1 and step > 6000: epoch_loss = tr_loss / 6000 print('Training Loss: {:.4f}'.format(epoch_loss)) break epoch_loss = tr_loss / len(data_loader_train) print('Training Loss: {:.4f}'.format(epoch_loss)) for param in model.parameters(): param.requires_grad = False model.eval() test_pred = np.zeros((len(test_dataset) * n_classes, 1)) for i, x_batch in enumerate(tqdm(data_loader_test)): x_batch = x_batch["image"] x_batch = x_batch.to(device, dtype=torch.float) with torch.no_grad(): pred = model(x_batch) test_pred[(i * batch_size * n_classes):((i + 1) * batch_size * n_classes)] = torch.sigmoid( pred).detach().cpu().reshape((len(x_batch) * n_classes, 1)) # Submission submission = pd.read_csv(os.path.join(dir_csv, 'stage_1_sample_submission.csv')) submission = pd.concat([submission.drop(columns=['Label']), pd.DataFrame(test_pred)], axis=1) submission.columns = ['ID', 'Label'] submission.to_csv(f'../../output/{Path(__file__).name}_sub.csv', index=False) submission.head()
[ "makeffort134@gmail.com" ]
makeffort134@gmail.com
a9842b561d434c08f0edcb70fe2249ef742611fe
f759794cb30b8ad958544d64859f77700a83e7ab
/turdshovel/commands/dump.py
99dd5310c1503ab8892a1b11b489f90c73e1ea21
[ "MIT" ]
permissive
security-kma/turdshovel
6c209ca9bddf3a054007c76d7bcdaa80430cf66e
6f9d9b08734028fa819c590e8573ae49481dc769
refs/heads/main
2023-09-02T19:12:17.130267
2021-11-07T03:50:30
2021-11-07T03:50:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,870
py
import time from collections import Counter from typing import List import orjson import numpy as np import System from nubia import argument, command, context from rich import inspect from rich.console import Console from rich.table import Table from ..context import TurdshovelContext from ..core.parsing import parse_obj @command class Dump: """Dump commands""" def __init__(self) -> None: self.ctx: TurdshovelContext = context.get_context() self.runtime = self.ctx.runtime self.console: Console = self.ctx.console @command @argument( "filter_", type=List[str], name="filter", description="Filter objects by string" ) def heap(self, filter_: List[str] = ["."]) -> None: """Dumps the objects on the heap""" if not self.ctx.runtime: self.console.print("[bold red] No runtime loaded! Load a dump first!") return object_table = Table(border_style="#8B4513") object_table.add_column("Address", style="cyan") object_table.add_column("Size", style="green") object_table.add_column("Object", style="yellow", overflow="fold") for segment in self.runtime.Heap.Segments: for obj in segment.EnumerateObjects(): if obj.IsValid and not obj.IsFree: if any(f.lower() in obj.ToString().lower() for f in filter_): object_table.add_row( hex(obj.Address), str(obj.Size), obj.ToString().rsplit(maxsplit=1)[0], ) self.console.print(object_table, highlight=True) @command @argument( "sort", type=str, choices=["count", "object", "none"], description="Sort output by count or object", ) @argument( "reverse", type=bool, description="Reverse sorting output. Only used with sort argument.", ) @argument( "filter_", type=List[str], name="filter", description="Filter objects by string" ) def stat( self, filter_: List[str] = ["."], sort: str = "none", reverse: bool = False ) -> None: """Dumps the count of each object on the heap""" counter = Counter() if not self.ctx.runtime: self.console.print("[bold red] No runtime loaded! Load a dump first!") return for segment in self.runtime.Heap.Segments: for obj in segment.EnumerateObjects(): if obj.IsValid and not obj.IsFree: if any(f.lower() in obj.ToString().lower() for f in filter_): counter.update([str(obj.Type)]) if sort == "object": counter = ( dict(sorted(counter.items(), reverse=True)) if reverse else dict(sorted(counter.items())) ) elif sort == "count": counter = ( dict(reversed(counter.most_common())) if reverse else dict(counter.most_common()) ) object_table = Table(border_style="#8B4513") object_table.add_column("Count", style="cyan") object_table.add_column("Object", style="yellow", overflow="fold") for k, v in counter.items(): object_table.add_row(str(v), k) self.console.print(object_table, highlight=True) @command @argument( "address", type=str, positional=True, description="Address of object to dump. Hex format (0x12345678)", ) @argument("save", type=bool, description="Save output to disk") def obj(self, address: str, save: bool = False) -> None: """Dumps an object on the heap by address""" # TODO: Turn this into a decorator for reuse if not self.ctx.runtime: self.console.print("[bold red] No runtime loaded! Load a dump first!") return address = int(address, 16) obj = self.runtime.Heap.GetObject(address) # We only care about valid objects and non-Free objects if obj.IsValid and not obj.IsFree: if obj.IsArray: output = [] obj_list = obj.AsArray() for idx in range(0, obj_list.Length): item = obj_list.GetObjectValue(idx) if not item.IsNull: output.append(parse_obj(self.runtime, item, self.console)) else: output = parse_obj(self.runtime, obj, self.console) output = orjson.dumps(output, default=lambda x: repr(x)) if save: filename = f"{self.ctx.target_friendly_name}_{hex(address)}_{time.strftime('%Y%m%d-%H%M%S')}.json" with open(filename, "wb") as save_file: save_file.write(output) self.console.print(f"[green bold]Output saved to {filename}") else: try: self.console.print_json(output.decode()) except: self.console.print(output) @command @argument( "address", type=str, positional=True, description="Address in memory to dump. Hex format (0x12345678)", ) @argument( "length", type=int, positional=True, description="Length of bytes to dump" ) def mem(self, address: str, length: int) -> None: """Dumps the memory in bytes at location and for length specified""" output_span = System.Span[System.Byte](bytes(length)) self.runtime.DataTarget.DataReader.Read( np.uint64(int(address, 16)), output_span ) output_str = "".join([f"{i:02x}" for i in output_span.ToArray()]) self.console.print(f"Hex: ", output_str) self.console.print(f"Bytes: ", bytes.fromhex(output_str)) try: self.console.print( f"ASCII: ", bytes.fromhex(output_str).decode(), highlight=False ) except: pass @command @argument( "types", type=List[str], description="Dump objects by type", choices=context.get_context().available_obj_types, ) @argument("save", type=bool, description="Save output to disk") def type_(self, types: List[str], save: bool = False) -> None: """Dumps the objects on the heap by type""" if not self.ctx.runtime: self.console.print("[bold red] No runtime loaded! Load a dump first!") return for segment in self.runtime.Heap.Segments: for obj in segment.EnumerateObjects(): if obj.IsValid and not obj.IsFree: if any(_ == str(obj.Type) for _ in types): self.obj(hex(obj.Address), save)
[ "daddycocoaman@gmail.com" ]
daddycocoaman@gmail.com
b60b249ea8589a40ae6b771023665223f5155759
f4a903ab7c1cf4794eb68e6dd4585beb6a6fb67f
/capture_email/settings.py
ccd45961818e4d223070bb10c235b0c5a5c20492
[]
no_license
victorsls/capture_email
2c659519e1cd0f0bdf056287e7a02adc5acca97a
3d50c3dc25feb1a9ff66cd3970861d19dd416254
refs/heads/master
2020-04-18T13:29:02.510963
2019-01-25T15:09:23
2019-01-25T15:09:23
167,562,771
0
0
null
null
null
null
UTF-8
Python
false
false
3,313
py
""" Django settings for capture_email project. Generated by 'django-admin startproject' using Django 2.1.5. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') DEBUG = config('DEBUG', default=False, cast=bool) ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=lambda v: [s.strip() for s in v.split(',')]) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'capture_email.core', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'capture_email.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'capture_email.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'pt-br' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # MAILCHIMP MAILCHIMP_KEY = config('MAILCHIMP_KEY') MAILCHIMP_USER = config('MAILCHIMP_USER')
[ "victorrafael@vago.online" ]
victorrafael@vago.online
f45f67405c41b10219c6e8c520535e03f857f815
2c338c524996844569a0ae36bb252af2b02e116b
/day_1.py
af5efd1d0f1fd50c37f2e5152d22afb76731f24d
[]
no_license
Thomas-G-Steinberg/advent-of-code-2020
dbc3cbeb7ef29c9ca1a2031cbfa3d2b63e3e6718
c3b04cc19cff598e51913618bbe8c1e691458d8e
refs/heads/master
2023-07-10T15:55:19.777471
2021-08-21T18:08:32
2021-08-21T18:08:32
398,625,139
0
0
null
null
null
null
UTF-8
Python
false
false
1,086
py
from time import perf_counter def process_args(args): arglist = [] with open(args[1]) as fil: for line in fil: line = line.strip() if line: arglist.append(int(line)) return arglist def part_1(arglist): for x in arglist: for y in arglist: if x+y==2020: print(x*y) return def part_2(arglist): prod = 1 for x in arglist: for y in arglist: for z in arglist: if x+y+z==2020: print(x*y*z) return def main(args): arglist = process_args(args) print("Part 1") p1time = perf_counter() part_1(arglist) p1time = perf_counter() - p1time print("({} ms)".format(int(p1time*100000)/100)) print("Part 2") p2time = perf_counter() part_2(arglist) p2time = perf_counter() - p2time print("({} ms)".format(int(p2time*100000)/100)) return 0 if __name__ == '__main__': import sys sys.exit(main(sys.argv))
[ "67569229+Thomas-G-Steinberg@users.noreply.github.com" ]
67569229+Thomas-G-Steinberg@users.noreply.github.com
4d0508e30885cf44a76ce69e38cfca87985c97eb
0be02fc1ba339cfc895e79ac4f51b9e5c685ac79
/objects.py
89ca8b38f1c6c33398f6ece546cca0fd4e2f4ec9
[]
no_license
ezzatisawesome/python-practice
53afc04d7871d6f11e721b41d0bce72d64c9497b
1255ac842998f3aac21a8273d2a71ab6d0fd2671
refs/heads/master
2023-04-09T21:01:53.932381
2016-06-18T19:04:46
2016-06-18T19:04:46
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,157
py
class Parent: """A class representing a parent""" def __init__(self, fName="",lName=""): self.fName = fName self.lName = lName fName = "" lName = "" def printName(self): print("Full Name: " + self.fName + " " + self.lName) class Mom(Parent): """A class representing a mom""" def __init__(self, fName="", lName="", dressSize=0): self.dressSize = dressSize self.fName = fName self.lName = lName dressSize = -1 def printInfo(self): self.printName() print("Dress Size: " + str(self.dressSize)) class Dad(Parent): """A class representing a dad""" def __init__(self, fName="", lName="", numScrewdrivers=0): self.numScrewdrivers = numScrewdrivers self.fName = fName self.lName = lName numScrewdrivers = -1 def printInfo(self): self.printName() print("Number of screwdrivers: " + str(self.numScrewdrivers)) class Pet(): """A class representing a pet""" def __init__(self, name=""): self.name = name name = "" def printName(self): print('Name: ' + self.name) class Cat(Pet): """A class representing a cat""" def __init__(self, name="", color="unknown"): self.name = name self.color = color color = "" def printInfo(self): self.printName() print('Color: ' + self.color) class Dog(Pet): """A class representing a dog""" def __init__(self, name="Dog", pantingRate=-1): self.name = name self.pantingRate = pantingRate pantingRate = -1 def printInfo(self): self.printName() print('Panting rate: ' + str(self.pantingRate)) # Declare test objects testParent = Parent('Pewdie', 'Pie') testMom = Mom('Cruella', 'Deville', 12) testDad = Dad('Arnold', 'Schwarzeneggar', 15) testCat = Cat('Fluffly', 'yellow and pink') testDog = Dog('Max', 100) # Print info about test objects print('***Printing info about test objects***\n') testParent.printName() testMom.printInfo() testDad.printInfo() testCat.printInfo() testDog.printInfo() input()
[ "weirdo weirdness" ]
weirdo weirdness
3034e22db3590a3232dd046d24f8618aed25a471
396c4a3b5bd37d0e11c436209fa84906ab3edc69
/LogisticServer/transaction/constants.py
75f115bea4b64daa89955803870d8ae7138da09f
[]
no_license
Sonal305/Major-Project
85a2357eeb6048aedc780688edb6d3d8c81efb61
d86d4063d4dddf4a5b35da878f37068df6e929e7
refs/heads/master
2023-04-01T11:47:37.531344
2021-04-07T09:55:10
2021-04-07T09:55:10
355,492,689
0
0
null
null
null
null
UTF-8
Python
false
false
13,308
py
contractAddress= '0x3c8092C319F87264f20933aD9EeBda977854fcC5' abi = '[{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"}],"name":"getBOL_No","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"}],"name":"getCarrier","outputs":[{"components":[{"internalType":"string","name":"CarrierName","type":"string"},{"internalType":"uint256","name":"TrailerNumber","type":"uint256"},{"internalType":"uint256","name":"SealNumber","type":"uint256"},{"internalType":"uint256","name":"SCAD","type":"uint256"},{"internalType":"uint256","name":"ProNumber","type":"uint256"}],"internalType":"struct Carrier","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"}],"name":"getCarrierInformation","outputs":[{"components":[{"internalType":"uint256","name":"HandlingUnitQuantity","type":"uint256"},{"internalType":"bool","name":"HandlingUnitTyoe","type":"bool"},{"internalType":"uint256","name":"PackageQuantity","type":"uint256"},{"internalType":"bool","name":"PackageType","type":"bool"},{"internalType":"uint256","name":"Weight","type":"uint256"},{"internalType":"bool","name":"HM","type":"bool"},{"internalType":"string","name":"Description","type":"string"},{"internalType":"string","name":"NMFC","type":"string"},{"internalType":"string","name":"Class","type":"string"}],"internalType":"struct CarrierInformation[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"}],"name":"getCharges","outputs":[{"components":[{"internalType":"string","name":"FreightChargeTerms","type":"string"},{"internalType":"uint256","name":"Perpaid","type":"uint256"},{"internalType":"uint256","name":"Collect","type":"uint256"},{"internalType":"uint256","name":"_3rdPartyCharges","type":"uint256"},{"internalType":"uint256","name":"MasterBOL","type":"uint256"}],"internalType":"struct Charges","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"}],"name":"getDate","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"}],"name":"getGrandTotal","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"}],"name":"getOrderInformation","outputs":[{"components":[{"internalType":"uint256","name":"OrderNumber","type":"uint256"},{"internalType":"uint256","name":"NumberOfPackage","type":"uint256"},{"internalType":"uint256","name":"Weight","type":"uint256"},{"internalType":"uint256","name":"Pallet","type":"uint256"},{"internalType":"uint256","name":"Cost","type":"uint256"},{"internalType":"string","name":"AdditionalInformation","type":"string"}],"internalType":"struct OrderInformation[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"}],"name":"getOrderSnapshot","outputs":[{"internalType":"string","name":"","type":"string"},{"internalType":"string","name":"","type":"string"},{"internalType":"bool","name":"","type":"bool"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"}],"name":"getScanDetails","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"string","name":"","type":"string"},{"internalType":"string","name":"","type":"string"},{"internalType":"string","name":"","type":"string"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"}],"name":"getShipFrom","outputs":[{"components":[{"internalType":"string","name":"Name","type":"string"},{"internalType":"string","name":"Address","type":"string"},{"internalType":"string","name":"City","type":"string"},{"internalType":"string","name":"State","type":"string"},{"internalType":"uint256","name":"Zip","type":"uint256"},{"internalType":"uint256","name":"SID","type":"uint256"},{"internalType":"bool","name":"FOB","type":"bool"},{"internalType":"uint256","name":"userId","type":"uint256"},{"internalType":"address","name":"userAddress","type":"address"}],"internalType":"struct ShipFrom","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"}],"name":"getShipTo","outputs":[{"components":[{"internalType":"string","name":"Name","type":"string"},{"internalType":"string","name":"Address","type":"string"},{"internalType":"string","name":"City","type":"string"},{"internalType":"string","name":"State","type":"string"},{"internalType":"uint256","name":"Zip","type":"uint256"},{"internalType":"uint256","name":"Location","type":"uint256"},{"internalType":"bool","name":"FOB","type":"bool"},{"internalType":"uint256","name":"userId","type":"uint256"},{"internalType":"address","name":"userAddress","type":"address"}],"internalType":"struct ShipTo","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"}],"name":"getShipmentAgency","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"}],"name":"getThirdPartyDetails","outputs":[{"components":[{"internalType":"string","name":"Name","type":"string"},{"internalType":"string","name":"Address","type":"string"},{"internalType":"string","name":"City","type":"string"},{"internalType":"string","name":"State","type":"string"},{"internalType":"uint256","name":"Zip","type":"uint256"},{"internalType":"uint256","name":"AppointmentNo","type":"uint256"},{"internalType":"string","name":"Date","type":"string"},{"internalType":"string","name":"DeliveryInstruction","type":"string"}],"internalType":"struct ThirdPartyDetails","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"}],"name":"getTrackingData","outputs":[{"components":[{"internalType":"string","name":"date","type":"string"},{"internalType":"string","name":"time","type":"string"},{"internalType":"string","name":"longitude","type":"string"},{"internalType":"string","name":"latitude","type":"string"},{"internalType":"string","name":"reporterCompanyName","type":"string"},{"internalType":"bool","name":"approved","type":"bool"},{"internalType":"string","name":"remarks","type":"string"}],"internalType":"struct TrackingData[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"}],"name":"payEther","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"recievePayment","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"},{"internalType":"uint256","name":"_BOL_No","type":"uint256"}],"name":"setBOL_No","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"},{"internalType":"string","name":"_CarrierName","type":"string"},{"internalType":"uint256","name":"_TrailerNumber","type":"uint256"},{"internalType":"uint256","name":"_SealNumber","type":"uint256"},{"internalType":"uint256","name":"_SCAD","type":"uint256"},{"internalType":"uint256","name":"_ProNumber","type":"uint256"}],"name":"setCarrier","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"},{"internalType":"uint256","name":"_HandlingUnitQuantity","type":"uint256"},{"internalType":"bool","name":"_HandlingUnitTyoe","type":"bool"},{"internalType":"uint256","name":"_PackageQuantity","type":"uint256"},{"internalType":"bool","name":"_PackageType","type":"bool"},{"internalType":"uint256","name":"_Weight","type":"uint256"},{"internalType":"bool","name":"_HM","type":"bool"},{"internalType":"string","name":"_Description","type":"string"},{"internalType":"string","name":"_NMFC","type":"string"},{"internalType":"string","name":"_Class","type":"string"}],"name":"setCarrierInformation","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"},{"internalType":"string","name":"_FreightChargeTerms","type":"string"},{"internalType":"uint256","name":"_Perpaid","type":"uint256"},{"internalType":"uint256","name":"_Collect","type":"uint256"},{"internalType":"uint256","name":"__3rdPartyCharges","type":"uint256"},{"internalType":"uint256","name":"_MasterBOL","type":"uint256"}],"name":"setCharges","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"},{"internalType":"string","name":"_date","type":"string"}],"name":"setDate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"},{"internalType":"uint256","name":"_OrderNumber","type":"uint256"},{"internalType":"uint256","name":"_NumberOfPackage","type":"uint256"},{"internalType":"uint256","name":"_Weight","type":"uint256"},{"internalType":"uint256","name":"_Pallet","type":"uint256"},{"internalType":"string","name":"_AdditionalInformation","type":"string"},{"internalType":"uint256","name":"_Cost","type":"uint256"}],"name":"setOrderInformation","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"},{"internalType":"string","name":"_Name","type":"string"},{"internalType":"string","name":"_Address","type":"string"},{"internalType":"string","name":"_City","type":"string"},{"internalType":"string","name":"_State","type":"string"},{"internalType":"uint256","name":"_Zip","type":"uint256"},{"internalType":"uint256","name":"_SID","type":"uint256"},{"internalType":"bool","name":"_FOB","type":"bool"},{"internalType":"uint256","name":"_userId","type":"uint256"},{"internalType":"address","name":"_userAddress","type":"address"}],"name":"setShipFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"},{"internalType":"string","name":"_Name","type":"string"},{"internalType":"string","name":"_Address","type":"string"},{"internalType":"string","name":"_City","type":"string"},{"internalType":"string","name":"_State","type":"string"},{"internalType":"uint256","name":"_Zip","type":"uint256"},{"internalType":"uint256","name":"_Location","type":"uint256"},{"internalType":"bool","name":"_FOB","type":"bool"},{"internalType":"uint256","name":"_userId","type":"uint256"},{"internalType":"address","name":"_userAddress","type":"address"}],"name":"setShipTo","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"},{"internalType":"uint256","name":"_shipmentAgencyId","type":"uint256"},{"internalType":"address","name":"_shipmentAgencyAddress","type":"address"}],"name":"setShipmentAgency","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"},{"internalType":"string","name":"_Name","type":"string"},{"internalType":"string","name":"_Address","type":"string"},{"internalType":"string","name":"_City","type":"string"},{"internalType":"string","name":"_State","type":"string"},{"internalType":"uint256","name":"_Zip","type":"uint256"},{"internalType":"uint256","name":"_AppointmentNo","type":"uint256"},{"internalType":"string","name":"_Date","type":"string"},{"internalType":"string","name":"_DeliveryInstruction","type":"string"}],"name":"setThirdPartyDetails","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"shipmentID","type":"string"},{"internalType":"string","name":"_date","type":"string"},{"internalType":"string","name":"_time","type":"string"},{"internalType":"string","name":"_longitude","type":"string"},{"internalType":"string","name":"_latitude","type":"string"},{"internalType":"string","name":"_reporterCompanyName","type":"string"},{"internalType":"bool","name":"_approved","type":"bool"},{"internalType":"string","name":"_remarks","type":"string"}],"name":"setTrackingData","outputs":[],"stateMutability":"nonpayable","type":"function"}]'
[ "sonalagrawal1515@gmail.com" ]
sonalagrawal1515@gmail.com
586a5cbeea1d2983ce82e60cd7eb36d91fed2790
aabff8fe30664a77853f0452d9ffa8cf81245710
/main.py
fd4e8158306db52237db1069974fb71be78c183d
[]
no_license
devansh-srivastav/licence_plate_detection
c90dfc48152be993a68c9c948b24ca3c23976bdc
4dc8ed1ff00e5ef5b16eda3bf5ce43267b5986e7
refs/heads/master
2022-08-01T00:29:33.117314
2020-05-27T16:49:34
2020-05-27T16:49:34
267,373,533
0
0
null
null
null
null
UTF-8
Python
false
false
2,097
py
import cv2 as cv import os from process_images import ProcessVehicleImage from process_images import ProcessNumberPlateImage from process_images import write_on_image from segment_characters import segmentation from predict_characters import predict image_number = 1 image_extension = '.jpg' image_path = "car_images/" + str(image_number) + image_extension root_path = os.getcwd() results_path = os.path.join(root_path, "results") target_path = os.path.join(results_path, str(image_number)) character_path = os.path.join(target_path, 'number_plate_characters') threshold_character_path = os.path.join(target_path, 'number_plate_characters_threshold') def create_dirs(): if not os.path.exists(results_path): os.mkdir(results_path) if not os.path.exists(target_path): os.mkdir(target_path) if not os.path.exists(character_path): os.mkdir(character_path) if not os.path.exists(threshold_character_path): os.mkdir(threshold_character_path) def main(): vehicle_image = cv.imread(image_path) create_dirs() vi = ProcessVehicleImage(vehicle_image) vi.preprocess() vi.get_contours() vi.detect_plate() vi.plot_and_save(target_path) number_plate_image = vi.get_number_plate() npi = ProcessNumberPlateImage(number_plate_image) npi.preprocess() npi.plot_and_save(target_path) threshold_number_plate_image = npi.get_number_plate_threshold() segmentation(number_plate_image.copy(), threshold_number_plate_image.copy(), target_path, character_path, threshold_character_path) registration_number = predict(threshold_character_path) write_on_image(vehicle_image.copy(), registration_number, target_path) create_file(registration_number) def create_file(registration_number): file_path = os.path.join(target_path, 'registration_number.txt') file = open(file_path, 'w') file.write(registration_number) file.close() if __name__ == "__main__": main()
[ "noreply@github.com" ]
noreply@github.com