repo_name
stringlengths
7
111
__id__
int64
16.6k
19,705B
blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
151
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_url
stringlengths
26
130
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
42
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
14.6k
687M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
12 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
10.2M
gha_stargazers_count
int32
0
178k
gha_forks_count
int32
0
88.9k
gha_open_issues_count
int32
0
2.72k
gha_language
stringlengths
1
16
gha_archived
bool
1 class
gha_disabled
bool
1 class
content
stringlengths
10
2.95M
src_encoding
stringclasses
5 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
10
2.95M
extension
stringclasses
19 values
num_repo_files
int64
1
202k
filename
stringlengths
4
112
num_lang_files
int64
1
202k
alphanum_fraction
float64
0.26
0.89
alpha_fraction
float64
0.2
0.89
hex_fraction
float64
0
0.09
num_lines
int32
1
93.6k
avg_line_length
float64
4.57
103
max_line_length
int64
7
931
beexu/testlearngit
3,410,204,070,854
38a0d58103204ad1c0e3447449e0422044e245a7
9637558a4e4a94198342dd4ab7b1706d6bc682d9
/requests git/learnpython/testall.py
9b7d807bf1e24bb1f83e2a13350c26b4e9b091c6
[]
no_license
https://github.com/beexu/testlearngit
28e30efffa8280178b299a11e568f107e50a1f63
3b99237aaf78d09c5b2c473229702bd06aa7ad52
refs/heads/master
2022-04-22T05:39:48.398650
2020-04-25T06:54:35
2020-04-25T06:54:35
258,698,945
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: UTF-8 -*- import requests import sys import unittest # sys.path.insert(0, '..') # 这个可以 sys.path.append('..') # 这个不行 # print(sys.path) from learnexcel import * from learnfixexcel import * from learnjson import * from mytest.testinter import * class testurl(unittest.TestCase): def __init__(self): self.learnexcel1 = ExcelMethod() self.learnfixexcel1 = fixtest() self.learnjson1 = Getpython() self.testinter1 = interface1() def run(self, methon, path): self.url = "http://lovebee.crazylaw.cn/single/sign.php" if methon == "get": res, code = self.testinter1.send_get(self.url, path) return res, code elif methon == "post": res, code = self.testinter1.send_post(self.url, path) return res, code def test(self): row = self.learnexcel1.GettestRow() truepath = '' a = [] for i in range(1, row): print(i) url = self.learnfixexcel1.getexcelurl(i) methon = self.learnfixexcel1.getexcelmethon(i) path = self.learnfixexcel1.getexcelpath(i) try: truepath = {'url': ''} truepath['url'] = url # print(truepath) littletruepath = self.learnjson1.getjsonid(path) for key, value in littletruepath.items(): truepath[key] = littletruepath[key] # print('aaa') # print(truepath) except Exception as e: # traceback = __import__('traceback') # print(traceback.print_exc())print_exc print(e) result, code = self.run(methon, truepath) # 存入excel self.learnexcel1.WriteEXcel(i, result) self.learnexcel1.WriteCode(i, code) returndata = self.learnexcel1.Getreturn(i) self.assertIn(returndata, result) print("test") print(code) print(returndata) # result = self.testinter1.send_get('http://lovebee.crazylaw.cn/single/sign.php', truepath) # result = self.testinter1.send_post('http://lovebee.crazylaw.cn/single/sign.php', truepath) # print(result) one1 = type(result) a.append(result) return a if __name__ == '__main__': testa = testurl().test() print(testa)
UTF-8
Python
false
false
2,458
py
41
testall.py
38
0.550041
0.541427
0
79
29.860759
104
Hwlcoder/CNN_conflict_types
17,875,653,910,712
f0b72e5f9d9a2b5e6c1ff28c711cb67173e87b3c
4e7a7570381a344c7b156da9705e996ef1dccdbd
/CNN/SVM+OurInput.py
e01fcb0cf188001ca6c89b1668c2c9c574ff1109
[]
no_license
https://github.com/Hwlcoder/CNN_conflict_types
7dadea6093a55abeae1938c6113c506d84d23568
b049615de539fb3582f34cdda6d0fbf50722a30e
refs/heads/master
2020-06-17T05:27:54.540574
2019-07-08T13:06:11
2019-07-08T13:06:11
195,811,301
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- import tensorflow as tf from textProcess3 import * from sklearn.model_selection import StratifiedKFold import os from sklearn.decomposition import PCA from sklearn import svm from sklearn.externals import joblib import time os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' os.environ["CUDA_VISIBLE_DEVICES"] = "0" gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.5) sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) #得到整个文本的矩阵(包括标签) all_dir_1 = 'data/cate300_cut/' all_dir_2 = 'data/parser/' categories, cat_to_id = read_category() all_xdata, all_ydata = process_file(all_dir_1,all_dir_2, cat_to_id) #N折交叉验证,先将all_xdata和all_ydata分成N组 stratified_folder = StratifiedKFold(n_splits=10, random_state=0, shuffle=False) train_acc = [] test_acc = [] train_xdata = np.zeros((270,3,3)) train_labels = np.zeros(270) test_xdata = np.zeros((30,3,3)) test_labels = np.zeros(30) fp = open('result/'+'AccurancyResultSVM.txt','w') for train_index, test_index in stratified_folder.split(all_xdata, all_ydata): for i in range(len(train_index)): train_xdata[i] = all_xdata[train_index[i]] train_labels[i] = all_ydata[train_index[i]] for i in range(len(test_index)): test_xdata[i] = all_xdata[test_index[i]] test_labels[i] = all_ydata[test_index[i]] t = time.time() # svm方法 nsamples, nx, ny = train_xdata.shape d2_train_dataset = train_xdata.reshape((nsamples, nx * ny)) nsamples1, nx1, ny1 = test_xdata.shape d2_test_dataset = test_xdata.reshape((nsamples1, nx1 * ny1)) pca = PCA(n_components=0.8, whiten=True) train_x = pca.fit_transform(d2_train_dataset) test_x = pca.transform(d2_test_dataset) svc = svm.SVC(kernel='rbf', C=10) svc.fit(train_x, train_labels) pre = svc.predict(test_x) acc = float((pre == test_labels).sum()) / len(test_x) test_acc.append(acc) print (u'准确率:%f,花费时间:%.2fs' % (acc, time.time() - t)) joblib.dump(svc, "train_svm_model.m") print ("Done\n") sum_acc = 0 for i in test_acc: sum_acc = sum_acc+i print (sum_acc/10) modeluse = joblib.load("train_svm_model.m") my_data_path1 = "data/test/liu/test_3/" my_data_path2 = "data/test/my/test_parser3/" categories, cat_to_id = read_category() test_1, test_2 = process_file(my_data_path1,my_data_path2,cat_to_id) nsamples, nx, ny = test_1.shape d2_test_data = test_1.reshape((nsamples, nx * ny)) d2_test_data_2 = pca.transform(d2_test_data) print(test_2) print(modeluse.predict(d2_test_data_2))
UTF-8
Python
false
false
2,594
py
41
SVM+OurInput.py
10
0.684022
0.658188
0
71
34.43662
79
Muzer/smartbot
10,823,317,626,496
facaa937cca505a07ebae77e5243694936eec16a
5ebe97e9597c1bd7b2162d7c092897f557472b51
/smartbot/backend.py
e0ff94bec31844d59a0edc379278d0b9f00a5ad0
[ "MIT" ]
permissive
https://github.com/Muzer/smartbot
048791e2731c850ffb66fa2178ee7c2f6d271b12
c18daac6b066a7d368ef3dd0848a21c16a076604
refs/heads/master
2021-01-24T21:47:23.583529
2015-05-05T15:09:22
2015-05-05T15:09:22
16,807,677
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from .events import Event class Backend: def __init__(self): self.storage = None self.event_listeners = [] self.on_connect = Event() self.on_disconnect = Event() self.on_ready = Event() self.on_join = Event() self.on_message = Event()
UTF-8
Python
false
false
298
py
25
backend.py
23
0.553691
0.553691
0
13
21.923077
36
Patchkat/Advent-Of-Code-2020
16,054,587,778,825
58814575ed7b4e1ad76e655afd36f0bcd48704a8
e71fd1e081af09cf3a5f8ccc3071bfbdb57ad5d1
/Day 9/AoC9A.py
542ca30dcb2ef0d9edebecb4f6d6fe0fe4fa61be
[]
no_license
https://github.com/Patchkat/Advent-Of-Code-2020
339b76ce2bd61cc1c91d225a2959a0acebbc43d9
7d3abee87c1c3df434cc907594b329b638839e0d
refs/heads/main
2023-04-28T01:54:38.975577
2021-05-04T16:27:09
2021-05-04T16:27:09
318,089,752
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
f = [int(x.rstrip('\n')) for x in open('xmas.txt').readlines()] preamble_length = 25 for x in range(preamble_length, len(f)): current_nums = f[x-preamble_length:x] summed = False for y in current_nums: if (f[x] - y) in current_nums: summed = True if summed == False: print(f[x]) break
UTF-8
Python
false
false
337
py
39
AoC9A.py
39
0.569733
0.563798
0
11
29.636364
63
jakobpederson/tweetbot
8,074,538,543,671
a12f58a3d4d45e11d3cfdbd60fcf20304a15a99a
404a25c21c978ed0025be797c5639f5df8f0652a
/helloworld.py
e3aa6544a92f6a14a705eec171392beee1e88b2b
[]
no_license
https://github.com/jakobpederson/tweetbot
670b34dff5322b9a066c9a2d0cebc804ea21018a
8b1fb4b6e249e85a97dd5660ff8f4c0b671fe8f3
refs/heads/master
2021-01-20T00:14:45.139541
2017-04-23T23:42:07
2017-04-23T23:42:07
89,100,049
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- from datetime import datetime import tweepy from tweepy.error import TweepError import time import random import string import sys import KEYS_AND_TOKENS # argfile = str(sys.argv[1]) CONSUMER_KEY = KEYS_AND_TOKENS.CONSUMER_KEY CONSUMER_SECRET = KEYS_AND_TOKENS.CONSUMER_SECRET ACCESS_KEY = KEYS_AND_TOKENS.ACCESS_KEY ACCESS_SECRET = KEYS_AND_TOKENS.ACCESS_SECRET auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) api = tweepy.API(auth) # filename = open(argfile, 'r') # f = filename.readlines() # filename.close() format = '%Y-%m-%d %H:%M' def deck(): cards = [ 'The Fool', 'The Magician', 'The High Priestess', 'The Empress', 'The Emperor', 'The Hierophant', 'The Lovers', 'The Chariot', 'Strength', 'The Hermit', 'Wheel of Fortune', 'Justice', 'The Hanged Man', 'Death', 'Temperance', 'The Devil', 'The Tower', 'The Star', 'The Moon', 'The Sun', 'Judgement', 'The World', ] houses = ["Cups", "Wands", "Swords", "Pentacles"] royals = ["Ace", "Page", "Knight", "Queen", "King"] number_deck = [] for house in houses: number_deck.extend(['{} of {}'.format(x, house) for x in list(range(2, 11))]) for house in houses: number_deck.extend(['{} of {}'.format(x, house) for x in royals]) cards.extend(number_deck) return cards while(True): try: hand = random.sample(deck(), 3) final_hand = [] for card in hand: orientation = random.sample(["", "Inverted"], 1) if orientation[0] == "Inverted": final_hand.append('{} ({})'.format(card, "Inverted")) else: final_hand.append('{}'.format(card)) final_hand.append(datetime.now().strftime(format)) message = '1.) {0}\n2.) {1}\n3.) {2}\n\n{3}'.format(*final_hand) api.update_status(message) print(message) except TweepError: print('pass') pass time.sleep(900)
UTF-8
Python
false
false
2,192
py
2
helloworld.py
1
0.565237
0.557026
0
84
25.095238
85
AZ015/design_patterns
19,095,424,625,678
7a83c60cd3f7dbb9998bf2964661b91cfccc581d
2e223fb4771146ad0f80085b60aee6110cfdeff7
/Behavioral/observer/push_observer/main.py
e83cb5624a82a5d627ba78cd1942aa29eebf202c
[]
no_license
https://github.com/AZ015/design_patterns
c6b2612ff5ce169f0c8e343c1f9e670b2b593e96
704c4b29d6fab2dfaf7c4e8923909276eaabbfa7
refs/heads/master
2020-12-21T00:59:08.009764
2020-02-05T12:02:29
2020-02-05T12:02:29
236,259,486
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from Behavioral.observer.push_observer import DataSource, SpreadSheet, Chart if __name__ == '__main__': data_source = DataSource() sheet_1 = SpreadSheet() sheet_2 = SpreadSheet() chart = Chart() data_source.add_observer(sheet_1) data_source.add_observer(sheet_2) data_source.add_observer(chart) data_source.value = 1
UTF-8
Python
false
false
351
py
74
main.py
73
0.672365
0.65812
0
12
28.25
76
Tamar20/Google-project
309,237,654,816
936ff441913f5a2238dbb77694875b432d2e06da
0f8a171012617f64df5a7c98845239a583225d53
/init.py
f3b9328fc4ca166f6edb05e764369a8d5a637e07
[]
no_license
https://github.com/Tamar20/Google-project
8608af4b242f052ae1341ad300561fe03ad16e3d
ffac4d8df66375c3077cbb98dee47a28200c2db6
refs/heads/master
2023-02-21T04:30:24.072228
2021-01-21T14:19:15
2021-01-21T14:19:15
331,651,072
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os import string from trie import * def edit_sentence(prefix: str) -> str: prefix = prefix.translate(str.maketrans('', '', string.punctuation)) return ' '.join(prefix.lower().split()) def init_data(): trie = Trie() init_trie(trie) return trie def init_trie(trie): for line, path, line_num in uploading_files(): line = edit_sentence(line) offset = 1 while line != '': trie.insert(line, path, line_num, offset) line = line[1:] offset += 1 def uploading_files(): for root, dirs, files in os.walk(f"./data"): for file in files: curr_path = f"./{root}/{file}" with open(curr_path) as file: for line_num, line in enumerate(file, 1): yield line, curr_path, line_num
UTF-8
Python
false
false
837
py
4
init.py
4
0.553166
0.548387
0
37
21.540541
72
pengliu380/Feature-Detectors
12,429,635,354,752
fcfc26575f85ae113b706f4cc041f20da95fc164
6089d4b659071747aa623041c6b221096f8d07e7
/test.py
69e68f1dae1c3838cb28acd50df6e13d90b31ecc
[]
no_license
https://github.com/pengliu380/Feature-Detectors
47e5c92c35b7d85029f26abc4d5f40ccca2f3872
807ab6cf8d6ed527967ae53626ad247c8ffea47b
refs/heads/master
2020-04-02T16:55:51.586041
2018-10-25T08:43:24
2018-10-25T08:43:24
154,635,415
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import cv2 as cv import numpy as np # Merge pictures classname = ['bikes_blur', 'graffiti_viewpoints', 'bark_zoom_rotation', 'cars_light'] method = ['hcd', 'dog', 'fast', 'mser'] for i in range(4): for j in range(4): filename = 'result/' + classname[i] +'/' + method[j] img = cv.imread(filename + '_1.jpg') for m in range(2): temp = cv.imread( filename + '_' + str(2*m+3) +'.jpg') img = np.hstack((img, temp)) cv.imwrite(filename + '.jpg', img)
UTF-8
Python
false
false
507
py
2
test.py
2
0.556213
0.542406
0
14
35.214286
85
johnnyguogrit/Python--
2,894,807,968,924
b1d3af5c2bfa366f27722315771886643f2e2d47
094dc24a91346ab9c7e12b1b7ed85d2d596804d1
/food.py
5ebcc304d2ac2e9bcd8222308470db1300caffaf
[]
no_license
https://github.com/johnnyguogrit/Python--
23123220e8f7f5ed848b8e3593e47df000195f36
340c00f97449a8691ee3b2025729bdf97ff3a2a8
refs/heads/master
2020-08-14T21:03:16.767061
2019-10-18T11:07:04
2019-10-18T11:07:04
215,232,213
4
0
null
false
2019-10-15T08:13:40
2019-10-15T07:15:16
2019-10-15T07:15:19
2019-10-15T08:13:40
0
0
0
0
null
false
false
my_foods = ['pizza', 'falafel', 'carrot cake'] friend_foods = my_foods[:] print("My favorite foods are:") my_foods.append('cannoli') print(my_foods) print("\nMy friends' favorite foods are:") friend_foods.append('ice cream') print(friend_foods) print("\nThe first three items in the list are:") print(friend_foods[:3]) print("\nThree items from the middle of the list are:") print(my_foods[int(len(my_foods)/2):int(len(my_foods)/2)+3]) print("\nLast three items in the list are") print(my_foods[-3:]) for my_food in my_foods: print(my_food) for friend_food in friend_foods: print(friend_food)
UTF-8
Python
false
false
606
py
50
food.py
48
0.69967
0.691419
0
26
22.192308
60
movie5/deeplearning_from_scratch
10,033,043,616,744
d850002e2f8cd0a65e5373e10426b80038de955c
91b34a72cecfaf6b11333b598cffa60b87afade8
/ch1.헬로 파이썬/1.6.matplotlib.py
0b54559916c03fa025b5340ba311c4362c8b84de
[ "MIT" ]
permissive
https://github.com/movie5/deeplearning_from_scratch
635a1c1cfc96028a7a28c75d74460fdf4d911b02
eedc8718c7995f4f82d3b71475987d6e0c1ff578
refs/heads/master
2023-05-29T23:19:28.262873
2023-05-02T04:52:34
2023-05-02T04:52:34
283,549,037
0
0
MIT
true
2020-07-29T16:29:28
2020-07-29T16:29:27
2020-07-29T16:27:47
2019-03-15T04:34:44
60,444
0
0
0
null
false
false
import numpy as np import matplotlib.pyplot as plt from matplotlib.image import imread # 1.6.1 단순한 그래프 그리기 # 데이터 준비 x = np.arange(0, 6, 0.1) y = np.sin(x) # 그래프 그리기 # plt.plot(x, y) # plt.show() # 1.6.2 pyplot의 기능 # 데이터 준비 x = np.arange(0, 6, 0.1) y1 = np.sin(x) y2 = np.cos(x) # 그래프 그리기 plt.plot(x, y1, label="sin") plt.plot(x, y2, linestyle="--", label="cos") plt.xlabel("x") # 축이름 plt.ylabel("y") plt.title('sin & cos') plt.legend() plt.show() # 1.6.3 이미지 표시하기 img = imread('../dataset/lena.png') plt.imshow(img) plt.show()
UTF-8
Python
false
false
623
py
31
1.6.matplotlib.py
27
0.624299
0.585047
0
34
14.735294
44
shubhamverma1997/Sentiment-Dictionary
15,006,615,736,581
d433c7af2e70c4a8236a2661bc9b5b4030c5c242
8b4e33b960a7b89d4a82eb61546dd1fc53e943eb
/countForeign.py
7ebf770539917de9f0e402e209a6d3d06d68c358
[]
no_license
https://github.com/shubhamverma1997/Sentiment-Dictionary
e3143a3b02581659b5f95d3c86c78f561ae8c20a
a98ebed01507846eae02927201adc7fe55cdda63
refs/heads/master
2020-03-23T16:19:07.790928
2018-05-15T14:26:28
2018-05-15T14:26:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import pandas as pd from langdetect import detect Dict = pd.read_csv('Dict.csv', delimiter = ",") wlist = [] for word in Dict['Word']: wlist.append(word) forCnt = 0 TotWord = len(wlist) print TotWord wordLang = {} for word in wlist: wordLang[word] = detect(word) df = pd.DataFrame(wordLang.items(), columns =['word', 'lang']) df.to_csv(path_or_buf = 'cntForeign.csv', sep = ',', index = False)
UTF-8
Python
false
false
405
py
25
countForeign.py
12
0.664198
0.661728
0
17
22.823529
67
Tilana/Classification
17,523,466,572,760
ee8d130938ccdf235e514f3594cc055a3810c602
fa9d9985a5c1f8e02ea0983097574dcbb51bc699
/lda/Collection.py
c5941d04c289023320878b1efff904fc747dc5dc
[]
no_license
https://github.com/Tilana/Classification
76e111a52a1ceda6a2c090e65a03cd6c087c0fed
636e7660ecbd7d0615a40d210fb3b7afce919166
refs/heads/develop
2020-05-23T07:53:12.885056
2018-05-08T07:29:29
2018-05-08T07:29:29
80,451,934
3
1
null
false
2018-04-12T08:11:26
2017-01-30T18:49:53
2018-04-09T23:49:41
2018-04-12T08:11:25
128,642
3
0
47
Python
false
null
# encoding=utf8 from docLoader import loadData from Preprocessor import Preprocessor #import preprocessor as tweetPreprocessor from FeatureExtractor import FeatureExtractor import cPickle as pickle import listUtils as utils import pandas as pd import numpy as np import os import pdb class Collection: def __init__(self, path=None): self.data = pd.DataFrame() if path: self.path = path self.data = loadData(path) self.nrDocs = len(self.data) def cleanDataframe(self, textField='text'): dataWithText = self.data[self.data[textField].notnull()] cleanDataframe = dataWithText.dropna(axis=1, how='all') self.data = cleanDataframe.reset_index() self.nrDocs = len(self.data) def vectorize(self, vecType='tfidf', vocabulary=None, field='text', ngrams=(1,2), maxFeatures=8000): self.buildVectorizer(vecType=vecType, ngram_range=ngrams, min_df=5, max_df=0.50, max_features=maxFeatures, binary=False, vocabulary=vocabulary) self.trainVectorizer(vecType, field) def buildVectorizer(self, vecType='tfIdf', min_df=10, max_df=0.5, stop_words='english', ngram_range = (1,2), max_features=8000, vocabulary=None, binary=False): self.preprocessor = Preprocessor(processor=vecType, min_df=min_df, max_df=max_df, stop_words=stop_words, ngram_range=ngram_range, max_features=max_features, vocabulary=vocabulary, binary=binary) def trainVectorizer(self, vecType='tfIdf', field='text'): trainDocs = self.data[field].tolist() self.data[vecType] = self.preprocessor.trainVectorizer(trainDocs) self.vocabulary = self.preprocessor.vocabulary def save(self, path): self.savePreprocessor(path) with open(path +'.pkl', 'wb') as f: pickle.dump(self, f, -1) def load(self, path): model = pickle.load(open(path+'.pkl', 'rb')) self.data = model.data self.loadPreprocessor(path) return self def savePreprocessor(self, path): if hasattr(self, 'preprocessor'): self.preprocessor.save(path) del self.preprocessor def loadPreprocessor(self, path): preprocessor = Preprocessor() if os.path.exists(path+'.pkl'): self.preprocessor = preprocessor.load(path) self.vocabulary = self.preprocessor.vocabulary def existsProcessedData(self, path): return os.path.exists(path + '.pkl') def cleanTexts(self): preprocessor = Preprocessor() self.applyToRows('text', preprocessor.removeHTMLtags, 'cleanText') self.applyToRows('cleanText', preprocessor.cleanText, 'cleanText') self.applyToRows('cleanText', preprocessor.numbersInTextToDigits, 'cleanText') def removeStopwords(self): preprocessor = Preprocessor() self.applyToRows('cleanText', preprocessor.removeStopwords, 'cleanTokens') def cleanTweets(self): self.applyToRows('decodeTweet', tweetPreprocessor.clean, 'cleanTweets') def extractDate(self): self.applyToRows('tweet_time', separateDateAndTime, 'date') def extractDate(self): self.data['date'] = self.data.apply(lambda doc: doc['tweet_time'].split('T')[0], axis=1) def extractEntities(self, path=None): featureExtractor = FeatureExtractor(path) self.applyToRows('text', featureExtractor.entities, 'entities') def setRelevantWords(self): self.applyToRows('tfidf', self.relevantWords, 'relevantWords') def relevantWords(self, wordWeights): sortedWeights = sorted(enumerate(wordWeights), key=lambda x: x[1], reverse=True) sortedWeights = [wordWeight for wordWeight in sortedWeights if wordWeight[1]>0] return [(self.vocabulary[wordIndex], weight) for (wordIndex, weight) in sortedWeights] def applyToRows(self, field, fun, name, args=None): if args: self.data[name] = self.data.apply(lambda doc: fun(doc[field], args), axis=1) else: self.data[name] = self.data.apply(lambda doc: fun(doc[field]), axis=1)
UTF-8
Python
false
false
4,100
py
54
Collection.py
43
0.674146
0.666829
0
116
34.344828
202
Ayush1959/Python-prgs
77,309,426,607
8e37d14597356190a9873e924739b500b0d8f870
eee3b82c2596fd71738aa550225675d733b1d0f2
/bigandsmall.py
0d51ae5877c10777411a725a6b0905332e3881c7
[]
no_license
https://github.com/Ayush1959/Python-prgs
d0329233b14b120ce6096ac8e87ba596033be5a4
3f3e26d3351d6b346bb915c135a58b3812977912
refs/heads/master
2021-01-23T09:39:39.948557
2017-09-28T08:42:05
2017-09-28T08:42:05
102,587,880
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
def big (x): tmp = max (x) return tmp def small (x): tmp = min (x) return tmp
UTF-8
Python
false
false
94
py
19
bigandsmall.py
19
0.510638
0.510638
0
6
14.666667
17
bpiche/sent2vec
4,045,859,196,042
e333fd70c6cec930ab8ba2bb2db7ceab30845284
dd6588c995f01ce9fcd9a0ab90dfe8fcd8fd9812
/sentence2vec.py
471accfbd2bf63ec0dc3632ee54b6290439f03a4
[ "Apache-2.0" ]
permissive
https://github.com/bpiche/sent2vec
4b46f0c14719296030548798f15d59734d234f86
42fb05114f03377f4e3b15144ff7444610853d65
refs/heads/master
2020-04-07T14:45:12.243891
2018-11-20T22:38:28
2018-11-20T22:38:28
158,459,717
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Slightly modified from https://github.com/peter3125/sentence2vec with some new methods for preprocessing sentences, calculating cosine similarity with sklearn, and a pipeline for comparing an input sentence against a corpus for some braindead question answering purposes """ from __future__ import print_function import time import gensim from gensim.corpora.wikicorpus import WikiCorpus from gensim.models.doc2vec import Doc2Vec import spacy import math import numpy as np import pandas as pd from sklearn.decomposition import PCA from sklearn.metrics.pairwise import cosine_similarity from typing import List nlp = spacy.load('en') gnews_model = gensim.models.KeyedVectors.load_word2vec_format('~/Downloads/GoogleNews-vectors-negative300.bin', binary=True) class Word: def __init__(self, text, vector): self.text = text self.vector = vector class Sentence: def __init__(self, word_list): self.word_list = word_list # return the length of a sentence def len(self): return(len(self.word_list)) def __str__(self): word_str_list = [word.text for word in self.word_list] return ' '.join(word_str_list) def __repr__(self): return self.__str__() def get_word_frequency(word_text, vec_model): wf = vec_model.vocab[word_text].count return(wf) def preloading_sentences(sentence_list, model): """ Converts a list of sentences into a list of Sentence (and Word) objects Pretty similar to what peter3125/sentence2vec.git does input: a list of sentences, embedding_size output: a list of Sentence objects, containing Word objects, which contain 'text' and word vector attributes """ embedding_size = 300 all_sent_info = [] for sentence in sentence_list: sent_info = [] spacy_sentence = nlp(sentence) for word in spacy_sentence: if word.text in model.vocab: sent_info.append(Word(word.text, model[word.text])) # todo: if sent_info > 0, append, else don't all_sent_info.append(Sentence(sent_info)) return(all_sent_info) def sentence_to_vec(sentence_list, embedding_size, a=1e-3): """ A SIMPLE BUT TOUGH TO BEAT BASELINE FOR SENTENCE EMBEDDINGS Sanjeev Arora, Yingyu Liang, Tengyu Ma Princeton University """ sentence_set = [] # intermediary list of sentence vectors before PCA sent_list = [] # return list of input sentences in the output for sentence in sentence_list: this_sent = [] vs = np.zeros(embedding_size) # add all w2v values into one vector for the sentence sentence_length = sentence.len() for word in sentence.word_list: this_sent.append(word.text) word_freq = get_word_frequency(word.text, gnews_model) a_value = a / (a + word_freq) # smooth inverse frequency, SIF vs = np.add(vs, np.multiply(a_value, word.vector)) # vs += sif * word_vector vs = np.divide(vs, sentence_length) # weighted average, normalized by sentence length sentence_set.append(vs) # add to our existing re-caculated set of sentences sent_list.append(' '.join(this_sent)) # calculate PCA of this sentence set pca = PCA(n_components=embedding_size) pca.fit(np.array(sentence_set)) u = pca.components_[0] # the PCA vector u = np.multiply(u, np.transpose(u)) # u x uT # pad the vector? (occurs if we have less sentences than embeddings_size) if len(u) < embedding_size: for i in range(embedding_size - len(u)): u = np.append(u, 0) # resulting sentence vectors, vs = vs -u * uT * vs sentence_vecs = [] for vs in sentence_set: sub = np.multiply(u, vs) sentence_vecs.append(np.subtract(vs, sub)) return(sentence_vecs, sent_list) def get_sen_embeddings(sentence_list): """ Create Sentence and Word objects from a list and pass them to sentence_to_vec() Return a list of _sentence embeddings_ for all sentences in the list """ embedding_size = 300 all_sent_info = preloading_sentences(sentence_list, gnews_model) sentence_vectors, sent_list = sentence_to_vec(all_sent_info, embedding_size) return(sentence_vectors, sent_list) def get_cos_distance(sentence_list): """ Create Sentence and Word objects from a list and pass them to sentence_to_vec() Return a matrix of the _cosine distance_ of elements in the matrix This is used for sentence similarity functions input: A list of plaintext sentences output: A list of sentence distances """ sentence_vectors, sent_list = get_sen_embeddings(sentence_list) cos_list = cosine_similarity(sentence_vectors, Y=None, dense_output=True) return(cos_list, sent_list) def get_most_similar(utterance, sentence_list): """ Takes an input utterance and a corpus sentence_list to compare it to, and returns a dict of the utterance, closest question, and relevant answer """ sentence_list.append(utterance) cos_list, sent_text = get_cos_distance(sentence_list) tmp_list = list(cos_list[len(cos_list)-1]) tmp_indx = tmp_list.index(max(tmp_list[0:len(tmp_list)-1])) return(tmp_indx) if __name__ == "__main__": # load questions to compare simliarity to input/test utterances faq_csv = pd.read_csv("./utterances_test.csv") sentence_list = list(faq_csv['utterance']) answer_list = list(faq_csv['answer']) max_idx = get_most_similar(utterance, sentence_list) # print the relevant question and answer pair sentence_list[max_idx] answer_list[max_idx]
UTF-8
Python
false
false
5,620
py
2
sentence2vec.py
1
0.67847
0.672954
0
157
34.802548
124
GitHubSecurity/insightconnect-plugins
14,851,996,910,489
8c8916e8a332298dffb9a0e17fede9a9bee101df
160c4eab3c0a7d6b2477a8b857001ddb83199dd1
/recorded_future/setup.py
f40de65f2399f177239ce4549d01227dcd049690
[ "MIT" ]
permissive
https://github.com/GitHubSecurity/insightconnect-plugins
6bc03448b93f2180cc05029adbd5669bca5f3256
b1ecc1ba345e3bd6db22688e5476d9e0edd4e6ac
refs/heads/master
2020-06-17T19:37:38.276131
2019-07-24T09:34:11
2019-07-24T09:34:11
196,028,200
1
0
null
true
2019-07-09T14:47:02
2019-07-09T14:47:01
2019-06-21T16:47:16
2019-06-29T02:35:47
31,084
0
0
0
null
false
false
# GENERATED BY KOMAND SDK - DO NOT EDIT from setuptools import setup, find_packages setup(name='recorded_future-rapid7-plugin', version='1.0.2', description='Recorded Future arms threat analysts, security operators, and incident responders to rapidly connect the dots and reveal unknown threats', author='rapid7', author_email='', url='', packages=find_packages(), install_requires=['komand'], # Add third-party dependencies to requirements.txt, not here! scripts=['bin/komand_recorded_future'] )
UTF-8
Python
false
false
554
py
374
setup.py
107
0.693141
0.684116
0
14
38.571429
157
clbm/SESSDSA-2048-F19-X-ray-
15,899,968,973,765
e314c0d556d110ee893c577e0a8eb738a08a2514
25a5398a5e7cc9f3fb172f206a4d411b73c58a87
/α-β剪枝代码及调试/green light_2.py
0e8893b0c770a546f6fdb355a22ac2dba47f256f
[]
no_license
https://github.com/clbm/SESSDSA-2048-F19-X-ray-
fee89ca3cabc0cd313072a9981bb3011989117ee
7eecd7e1f9c4aaa3aea55d608547a56313b79b62
refs/heads/master
2022-09-26T06:27:14.057050
2020-06-07T13:01:49
2020-06-07T13:01:49
269,928,075
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
Inf = float('inf') import numpy as np Weight_L = np.array((1.0,1.05,1.1,1.15,1.2,1.2,1.2,1.2)) Weight_R = np.array((1.2,1.2,1.2,1.2,1.15,1.1,1.05,1.0)) def getmark(board, isFirst:bool): "评估函数" Value, Belong = np.array(board.getRaw()).transpose((2,0,1)) return np.sum(((Belong<<Value)*Weight_L-((1-Belong)<<Value)*Weight_R)*(1+0.02*Value))*(1 if isFirst else -1) def simulation(depth:int, Round:int, Gamemode:int, is_max:bool, board, alpha, beta): #模拟对战 global Inf mode,isFirst = Gamemode>>1,not Gamemode&1 if depth >= 6 or Round == 500: #大于最大深度时 alpha = getmark(board,isFirst) return (alpha,alpha) #以下为一般情况 if mode == 0: #落子阶段 #第一步,找出全部可行落子 Self_part = board.getNext(isFirst,Round) #自己棋盘落子的位置 #available为全部可行位置 available = [Self_part] if Self_part else [] if Round > 30:available += board.getNone(not isFirst) #对手棋盘可落子的位置 #第二步,迭代模拟 if len(available) == 0: #无合法移动的特殊情况 if not depth&1:return -Inf, -Inf return simulation(depth+1,Round,Gamemode+1,not is_max,board,alpha,beta) #一般情况 result = available[0] for position in available: #子树对决 new_board = board.copy() new_board.add(isFirst,position) alpha_beta = simulation(depth+1,Round,Gamemode+1,not is_max,new_board,alpha,beta) #更新alpha-beta if is_max: if not depth:old_alpha = alpha #对于树根,需要比较alpha值的变化 alpha = max(alpha, *alpha_beta) if not depth and alpha > old_alpha: result = position #当alpha值变大时,落子位置更新 else: beta = min(beta, *alpha_beta) if alpha >= beta: break#alpha-beta剪枝 #返回结果 if depth:return alpha, beta return result else: #合并阶段 No_available = True for move in range(4): #跳过非法合并 new_board = board.copy() if not new_board.move(isFirst, move):continue elif No_available: No_available = False if not depth: result = move #子树对决 alpha_beta = simulation(depth+1,Round+1-isFirst,(Gamemode+1)&3,not is_max,new_board,alpha,beta = beta) #更新alpha-beta if is_max: if not depth:old_alpha = alpha#对于树根,需要比较alpha值的变化 alpha = max(alpha, *alpha_beta) if not depth and alpha > old_alpha:result = move#当alpha值变大时,落子位置更新 else:beta = min(beta, *alpha_beta) if alpha >= beta:break#alpha-beta剪枝 #无合法移动的特殊情况 if No_available: if not depth&1: return -Inf, -Inf return simulation(depth+1,Round + 1-isFirst,(Gamemode+1)&3,not is_max,board,alpha,beta) else: if depth: return alpha, beta return result class Player: def __init__(self, isFirst:bool, array:list): self.isFirst = isFirst def output(self, currentRound:int, board, mode:str): if mode == 'position':Gamemode = 1^self.isFirst # 给出己方下棋的位置 elif mode == 'direction':Gamemode = 2+(1^self.isFirst) # 给出己方合并的方向 else:return return simulation(0, currentRound,Gamemode,True,board,-Inf,Inf)
UTF-8
Python
false
false
3,711
py
31
green light_2.py
31
0.565453
0.542582
0
75
42.306667
114
lishulongVI/rest-web
5,540,507,851,445
60dec3cd3f0e80df65a49f5fc9f93e9fb077bcfe
91fe99a22aa3f6fb0842a79b138eff6190d9676a
/rest/web_admin/base_views.py
664ce9cf0ecfa202bcfb77a9765d4c40e481a923
[]
no_license
https://github.com/lishulongVI/rest-web
f55f2aba79eefb08bc750f3d0595b4cbc65a5bd6
7835c0f393deaac86ada644aa4c9f219811e037b
refs/heads/release
2020-06-25T03:15:17.383452
2019-12-27T08:05:02
2019-12-27T08:05:02
199,183,013
0
0
null
false
2019-12-16T08:30:12
2019-07-27T15:35:32
2019-12-16T08:28:23
2019-12-16T08:28:21
40
0
0
0
Python
false
false
from django_filters.rest_framework import DjangoFilterBackend from rest_framework import mixins, viewsets, serializers class BaseFilter(DjangoFilterBackend): def filter_queryset(self, request, queryset, view): old = request.GET._mutable request.GET._mutable = True if 'deleted' not in request.query_params: request.query_params['deleted'] = 0 request.GET._mutable = old return super().filter_queryset(request, queryset, view) class BaseViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): filter_backends = (BaseFilter,) filterset_fields = ('deleted',) class BaseModelSerialize(serializers.ModelSerializer): update_datetime = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
UTF-8
Python
false
false
939
py
7
base_views.py
6
0.677316
0.676251
0
25
36.56
107
DCC-CC4401/2018-1-Soft-Where-T4
11,192,684,798,070
8637f85cc13d2cbf9265ead5f534794ed60b4d01
d3fc1675c69f6523b79089e9a58510dea91f554d
/cc4401Inventory/loansApp/models.py
99decd5142c22dcc0c44fb369c169233a422badc
[]
no_license
https://github.com/DCC-CC4401/2018-1-Soft-Where-T4
e6ae0740e96eb9726d94e15917aa278515fe8ffe
5171289a72e807e97a5389151d843e3d85588b78
refs/heads/master
2020-03-23T13:44:23.658215
2018-08-21T16:22:05
2018-08-21T16:22:05
141,634,468
0
0
null
false
2018-08-15T00:33:42
2018-07-19T21:53:37
2018-08-02T22:23:42
2018-08-14T20:27:28
996
0
0
1
HTML
false
null
from mainApp.models import Action, User from articlesApp.models import Article from django.db import models class Loan(Action): article = models.ForeignKey(Article, on_delete=models.CASCADE) admin = models.ForeignKey(User, related_name="admin_art_prestador", on_delete=models.CASCADE, default=None, null=True)
UTF-8
Python
false
false
349
py
12
models.py
5
0.716332
0.716332
0
9
37.888889
111
kiruthihan10/Music-Classifier
7,224,135,028,688
c8c0ab3de630a9a85fcbeaa3f49819884d48ebe3
275112ddf479e40316866a08161713c9a84e6a02
/classifier.py
4af712fe015017b897a72c70d9565c4c8409270e
[ "MIT" ]
permissive
https://github.com/kiruthihan10/Music-Classifier
70fb9157d332663ba4382d43597eb9b85f9a5096
e782d230194cd1acdee72c85f3b14a5fd802131c
refs/heads/master
2020-05-03T10:36:16.601275
2019-03-30T16:37:01
2019-03-30T16:37:01
178,583,501
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
################################################## #Import Libs import scipy import sklearn as sk import matplotlib.pyplot as plt from PIL import Image import numpy import numpy as np from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.svm import LinearSVC from sklearn.model_selection import cross_val_score from sklearn.ensemble import RandomForestRegressor from sklearn.linear_model import SGDClassifier from sklearn.base import BaseEstimator from sklearn.model_selection import cross_val_predict from sklearn.metrics import confusion_matrix ##################################################### #Get datas new = [] old = [] new_file = open("new_song_array.txt",'r') import time star = time.time() y=[] for line in new_file: data = line.strip().split(',') temp = [] for i in data: if i.isdigit(): temp.append(float(i)) data = temp new.append(data) y.append(1) #print(data) print(len(y)) print("done") new_file.close() old_file = open("old_song_array.txt",'r') for line in old_file: data = line.strip().split(',') temp = [] for i in data: if i.isdigit(): temp.append(float(i)) data = temp new.append(data) y.append(0) print(len(new)) print("done") print(time.time()-star) #################################################### #Shuffle chaos = np.random.permutation(len(new)) X=[] Y=[] for i in chaos: X.append(new[i]) Y.append(y[i]) train_X = X[:90] train_Y = Y[:90] test_X = X[90:] test_Y = Y[90:] print(np.array(train_X).shape) print(np.array(train_Y).shape) #################################################### #Create Classifications svm_clf = Pipeline((("Scaler",StandardScaler()),("linear_svc",LinearSVC(C=1, loss="hinge")),)) svm_clf.fit(train_X,train_Y) test = svm_clf.predict(test_X) n = 0 correct = 0 for i in test: if i == test_Y[n]: correct+=1 n+=1 print (float(correct)*100/len(test)) svm_score = cross_val_score(svm_clf,train_X,train_Y,cv=3,scoring="accuracy") print (svm_score) y_train_pred = cross_val_predict(svm_clf,train_X,train_Y,cv=3) print (confusion_matrix(train_Y,y_train_pred)) if True: sgd_clf = SGDClassifier(random_state=42) sgd_clf.fit(train_X,train_Y) test = sgd_clf.predict(test_X) # print len(test) # print len(test_Y) n = 0 correct = 0 for i in test: if i == test_Y[n]: correct+=1 n+=1 print (float(correct)*100/len(test)) #print test_Y sgd_score = cross_val_score(sgd_clf,train_X,train_Y,cv=3,scoring="accuracy") print (sgd_score) y_train_pred = cross_val_predict(sgd_clf,train_X,train_Y,cv=3) print (confusion_matrix(train_Y,y_train_pred))
UTF-8
Python
false
false
2,878
py
4
classifier.py
3
0.579222
0.56845
0
111
23.927928
94
Henry-Yan/BusTickets
6,253,472,411,241
d8ee72f9c287bb3f5b0bb0a1248a4da8c0d2cf9b
d1c526efe6c7daa0fd4b52f2585a16fbb4b8bde5
/src/tickets/ticket.py
799ebe9957cab8ef47ddebfb1dd9201573583771
[]
no_license
https://github.com/Henry-Yan/BusTickets
4266a8c3e1c3418622ede695b2e833e5741c7e4f
2ff79dcda8bb086dcfe8f89727fd4917f7ffb8b7
refs/heads/master
2015-08-09T17:54:25.862241
2014-01-13T04:30:15
2014-01-13T04:30:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Created on Dec 11, 2013 @author: Jilin Yan ''' import datetime class Ticket(object): ''' Basic class for ticket ''' cities = { 'Boston' : 94, 'New York' : 123, 'Philadelphia' : 127, 'Washington' : 142, 'Toronto' : 145 } companies = { 'MegaBus' : 1, 'BoltBus' : 2 } def __init__(self, origin, destination, depart_date, depart_time, arrive_time, price, company): ''' Initializes the ticket's data ''' self.origin = origin self.destination = destination self.depart_date = depart_date.strftime("%Y-%m-%d") self.depart_time = self.get_depart_time(depart_time) self.arrive_time = self.get_arrive_time(depart_time, arrive_time) self.price = price self.company = company def get_origin_index(self): ''' Returns the origin city's index ''' return self.cities[self.origin] def get_destination_index(self): ''' Returns the destination city's index ''' return self.cities[self.destination] def get_depart_time(self, depart_time): ''' Returns the depart time ''' d_time = datetime.datetime.strptime(self.depart_date + " " + depart_time, '%Y-%m-%d %I:%M%p') return d_time.strftime("%Y-%m-%d %H:%M:%S") def get_arrive_time(self, depart_time, arrive_time): ''' Returns the arrive time ''' d_time = datetime.datetime.strptime(self.depart_date + " " + depart_time, '%Y-%m-%d %I:%M%p') a_time = datetime.datetime.strptime(self.depart_date + " " + arrive_time, '%Y-%m-%d %I:%M%p') if a_time < d_time: a_time += datetime.timedelta(days = 1) return a_time.strftime("%Y-%m-%d %H:%M:%S") def get_company_index(self): ''' Returns the company's index ''' return self.companies[self.company] def get_ticket(self): ''' Print the ticket information ''' print "origin: %s" % self.origin, print " | destination: %s" % self.destination, print " | depart_date: %s" % self.depart_date, print " | depart_time: %s" % self.depart_time, print " | arrive_time: %s" % self.arrive_time, print " | price: %.2f" % self.price, print " | company: %s" % self.company
UTF-8
Python
false
false
2,568
py
7
ticket.py
6
0.508956
0.499611
0
87
28.425287
101
FabSchilling/WarframePrimeManager
1,176,821,039,661
6d5351e6af69c7c78e1531e40b0a109a900a3d50
11cdf3279144b6aaab299ec2878a5c6aad88b97a
/database_functions.py
537f491e595b47c538ad0003acb70809e753f05b
[]
no_license
https://github.com/FabSchilling/WarframePrimeManager
5cdfd530feec53327ebe63c6008e5ec4d80a5d72
ec42729ed1aab5c90270c9caff8e883e82f31fe8
refs/heads/master
2021-10-24T18:03:24.214454
2018-05-05T17:30:24
2018-05-05T17:30:24
125,201,237
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import json import re from six.moves import urllib from tinydb import TinyDB, Query db = TinyDB('db.json') qr = Query() def updateDatabase(): download_Path_allinone = "https://destiny.trade/JSON/allinone.json" urllib.request.urlretrieve(download_Path_allinone, "./allinone.json") resetDatabase() def resetDatabase(): db.purge() saveRelicDataToDatabase(loadDataFromJSON('./allinone.json')) def loadDataFromJSON(path): json_data=open(path).read() data = json.loads(json_data) return data def saveRelicDataToDatabase(data): relic_Data = data["relicRewards"] tier_list = ["Lith", "Meso", "Neo", "Axi"] for relics in relic_Data: for item in relic_Data[relics]['rewards']: db.insert({'tier': relic_Data[relics]['tier'], 'type': relic_Data[relics]['type'], 'name': item['name'], 'rarity': item['intact']['name'], 'vaulted': False}) vaulted_Relics = getVaultedRelicsFromData(data) for tier in tier_list: for relic_type in vaulted_Relics[tier_list.index(tier)]: db.update({'vaulted': True}, ((qr.tier == tier) & (qr.type == relic_type))) def getListOfPartsFromItem(item): parts = [] db_list = db.search((qr.name.matches(item))) for i in db_list: parts.append(i["name"]) return parts def getVaultedRelicsFromData(data): relic_data = getAllRelics() not_vaulted_relics = [[], [], [], []] vaulted_relics = relic_data pattern = '\w*\s\w*\sRelic' text = str(data) for match in re.findall(pattern, text): if match[:4] == 'Lith': if match[5:7] in relic_data[0]: not_vaulted_relics[0].append(match[5:7]) elif match[:4] == 'Meso': if match[5:7] in relic_data[1]: not_vaulted_relics[1].append(match[5:7]) elif match[:3] == 'Neo': if match[4:6] in relic_data[2]: not_vaulted_relics[2].append(match[4:6]) elif match[:3] == 'Axi': if match[4:6] in relic_data[3]: not_vaulted_relics[3].append(match[4:6]) not_vaulted_relics = [list(set(not_vaulted_relics[0])), list(set(not_vaulted_relics[1])), list(set(not_vaulted_relics[2])), list(set(not_vaulted_relics[3]))] count = 0 for tier in not_vaulted_relics: for type in tier: vaulted_relics[count].remove(type) count += 1 return vaulted_relics def getAllRelics(): relic_list =[] query_result = db.all() for tier in ['Lith', 'Meso', 'Neo', 'Axi']: sub_list = [] for relic in query_result: if relic["tier"] == tier: sub_list.append(relic["type"]) sub_list = list(set(sub_list)) sub_list = sorted(sub_list) relic_list.append(sub_list) return relic_list def isRelicVaulted(tier, type): relic = db.get((qr.tier == tier) & (qr.type == type)) return relic["vaulted"]
UTF-8
Python
false
false
2,924
py
8
database_functions.py
5
0.596443
0.584815
0
95
29.778947
169
hienha/python
2,697,239,493,916
de2e912c30d8b939d51fa2bf3dd65d1986c19e47
826b521587f1384b4d6de83819d6f75d59c2d71d
/apepy/codes/1-Python基础篇/1-2_Python基础进阶/1.8_递归列出目录里的文件.py
de6efe323789712d0302d6bf5fc738246d0ee49e
[]
no_license
https://github.com/hienha/python
b69be98bba5939b89fadd7feacb358b9b59de9d2
a7c1d44be3f7c3ee569dcbca0c7b5c202d40041e
refs/heads/master
2018-05-31T16:48:44.295948
2018-05-30T10:04:47
2018-05-30T10:04:47
59,118,477
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import os import sys def print_files(path): lsdir = os.listdir( path ) files = [ i for i in lsdir if os.path.isfile( os.path.join(path, i) ) ] dirs = [ i for i in lsdir if os.path.isdir( os.path.join(path,i) ) ] if files: for f in files: print os.path.join(path, f) if dirs: for d in dirs: print_files( os.path.join(path, d) ) print_files( sys.argv[1] )
UTF-8
Python
false
false
397
py
948
1.8_递归列出目录里的文件.py
558
0.639798
0.63728
0
19
19.894737
72
Texas-Waitlisters/BlinkLink
13,984,413,544,580
e700d7b079e4546c945d8c9e230881d0aad4591f
813b2275838f234190d7a325cf22cee4b589944a
/Redtooth/RedtoothWindows/Windows.py
e35d2c092dc81790198abd4557017a1a78726a65
[]
no_license
https://github.com/Texas-Waitlisters/BlinkLink
ef57c7750d6718124e0014026643bb55d9fb288d
7554cb227ab28767e9508f3d0c59d9f13ad3db20
refs/heads/master
2021-09-09T09:04:32.509724
2018-03-14T14:33:53
2018-03-14T14:33:53
117,875,405
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import time import os from urllib.request import urlopen import subprocess from uuid import getnode as get_mac ipAddress = "10.209.6.212" mac = str(hex(get_mac())) print(mac) #audio state def getVolumeStatus(): audiovalue = subprocess.Popen("ConsoleApplication1.exe", shell=False, stdout=subprocess.PIPE) val = audiovalue.communicate()[0].strip() == b'True' print(val) time.sleep(.15) audiovalue.kill() return val #Creates custom URL string def getURL(device, isPlaying): boolean = "false" if isPlaying: boolean = "true" url = "http://" + ipAddress + ":8080/redtooth/report/" + device + "/" + boolean print(url) return url #Ping database def pingDatabase(isPlaying): url = getURL(mac, isPlaying) response = urlopen(url).read() desiredMAC = response print(desiredMAC) return desiredMAC def Redtooth(): print("Running Core") while True: isPlaying = getVolumeStatus() deviceToPlay = pingDatabase(isPlaying) if (str(mac) in str(deviceToPlay)) and isPlaying: #bt on and pair print("Redtooth Activated") elif not(str(mac) in str(deviceToPlay)): #windows bt cmds off print("Redtooth De-activated") time.sleep(1) Redtooth()
UTF-8
Python
false
false
1,301
py
13
Windows.py
10
0.644889
0.631053
0
60
20.666667
97
opensciencegrid/osg-display-data
9,612,136,827,039
079daec333d98bf95b86a2f2a2c6ec216c1b01e5
52b5fd2bdc4906e1f944f9d03c9b98a3d1ec3fa6
/src/osg_display/transfer_datasource.py
5d3dbf6ecb4aeff7e0254bb8d25b7744ba7191dd
[]
no_license
https://github.com/opensciencegrid/osg-display-data
bba930f630d4eec8bd621e32d97129c18bd1df5d
93df8bc98f703a4c83fdd979357dd764148dc165
refs/heads/master
2021-07-18T02:10:31.200337
2021-06-28T16:55:00
2021-06-28T16:55:00
55,262,958
0
3
null
false
2021-06-28T16:55:01
2016-04-01T21:18:23
2020-10-27T22:02:11
2021-06-28T16:55:00
105
0
2
0
Python
false
false
import sys import time import pickle import datetime from .common import log, get_files, commit_files, euid import elasticsearch from elasticsearch_dsl import Search, A, Q import logging logging.basicConfig(level=logging.WARN) tracer = logging.getLogger('elasticsearch.trace') tracer.setLevel(logging.WARN) tracer.addHandler(logging.StreamHandler(sys.stderr)) transfers_raw_index = 'gracc.osg-transfer.raw-*' transfers_summary_index = 'gracc.osg-transfer.summary' def gracc_query_transfers(es, index, starttime, endtime, interval): s = Search(using=es, index=index) s = s.query('bool', filter=[ Q('range', StartTime={'gte': starttime, 'lt': endtime }) & ~Q('terms', SiteName=['NONE', 'Generic', 'Obsolete']) ] ) curBucket = s.aggs.bucket('StartTime', 'date_histogram', field='StartTime', interval=interval) curBucket = curBucket.metric('Network', 'sum', field='Network') curBucket = curBucket.metric('Records', 'sum', field='Njobs') response = s.execute() return response class TransferData(object): """ Information about a single hour's worth of tranfers from the DB. Meant to be saved in the cache, keeps track of the creationtime of the object itself so the cache knows when to expire it. """ def __init__(self): self.starttime = None self.endtime = None self.count = None self.volume_mb = None self.createtime = time.time() class DataSourceTransfers(object): """ A data source which queries (and caches!) hourly transfer information from GRACC """ def __init__(self, cp): self.cp = cp self.data = {} self.missing = set() def run(self): self.connect() self.load_cached() self.determine_missing() self.query_missing() def disconnect(self): pass def connect(self): gracc_url = self.cp.get("GRACC Transfer", "Url") #gracc_url = 'https://gracc.opensciencegrid.org/q' try: self.es = elasticsearch.Elasticsearch( [gracc_url], timeout=300, use_ssl=True, verify_certs=True) except Exception as e: log.exception(e) log.error("Unable to connect to GRACC database") raise def load_cached(self): try: data = pickle.load(open(self.cp.get("Filenames", "transfer_data") \ % {'uid': euid}, "rb")) # Verify we didn't get useless data for time, tdata in list(data.items()): assert isinstance(time, datetime.datetime) assert isinstance(tdata, TransferData) assert isinstance(tdata.starttime, datetime.datetime) assert isinstance(tdata.endtime, datetime.datetime) assert tdata.count != None assert tdata.volume_mb != None assert tdata.starttime != None self.data = data log.info("Successfully loaded transfer data from cache; %i" \ " cache entries." % len(data)) remove_data = [] now = globals()['time'].time() now_dt = datetime.datetime.now() for time, tdata in list(data.items()): if not hasattr(tdata, 'createtime') or not tdata.createtime: log.debug("Ignoring cached data from %s as it has no " \ "create time info." % time) remove_data.append(time) continue if now - tdata.createtime > 3600: log.debug("Ignoring cached data from %s as it is over " \ "an hour old." % time) remove_data.append(time) age_starttime = now_dt - tdata.starttime age_starttime = age_starttime.days*86400 + age_starttime.seconds if (now - tdata.createtime > 1800) and (age_starttime <= 12*3600): log.debug("Ignoring cached data from %s as it is over " \ "30 minutes old and is for a recent interval." % \ time) remove_data.append(time) for time in remove_data: del self.data[time] except Exception as e: log.warning("Unable to load cache; it may not exist. Error: %s" % \ str(e)) def save_cache(self): now = datetime.datetime.now() old_keys = [] for key in self.data.keys(): if (now - key).days >= 7: old_keys.append(key) for key in old_keys: del self.data[key] try: name, tmpname = get_files(self.cp, "transfer_data") fp = open(tmpname, 'wb') pickle.dump(self.data, fp) fp.close() commit_files(name, tmpname) log.debug("Saved data to cache.") except Exception as e: log.warning("Unable to write cache; message: %s" % str(e)) def _timestamp_to_datetime(self, ts): return datetime.datetime(*time.gmtime(ts)[:6]) def determine_missing(self): now = time.time() hour_now = now - (now % 3600) if (now-hour_now) < 15*60: hour_now -= 3600 self.missing.add(self._timestamp_to_datetime(hour_now)) self.missing.add(self._timestamp_to_datetime(hour_now-3600)) self.missing.add(self._timestamp_to_datetime(hour_now-2*3600)) self.missing.add(self._timestamp_to_datetime(hour_now-3*3600)) cur = hour_now hours = int(self.cp.get("GRACC Transfer", "hours")) while cur >= now - hours*3600: cur -= 3600 cur_dt = self._timestamp_to_datetime(cur) if cur_dt not in self.data: self.missing.add(cur_dt) def query_missing(self): now = time.time() log.info("Querying %i missing data entries." % len(self.missing)) for mtime in self.missing: starttime = mtime endtime = mtime + datetime.timedelta(0, 3600) results = self.query_transfers(starttime, endtime) if not results: log.warning("No transfer results found for %s." % starttime) for result in results: res_time, count, volume_mb = result res_time = float(res_time) starttime = self._timestamp_to_datetime(res_time) if now-res_time >= 3600: endtime = self._timestamp_to_datetime(res_time+3600) else: endtime = self._timestamp_to_datetime(now) if res_time > now: continue td = TransferData() td.starttime = starttime td.endtime = endtime td.count = count td.volume_mb = volume_mb self.data[starttime] = td log.debug("Successfully parsed results for %s." % starttime) self.save_cache() def query_transfers(self, starttime, endtime): log.info("Querying GRACC Transfer index for transfers from %s to %s." \ % (starttime.strftime("%Y-%m-%d %H:%M:%S"), endtime.strftime("%Y-%m-%d %H:%M:%S"))) params = {'interval': 'hour'} params['starttime'] = starttime params['endtime'] = endtime response = gracc_query_transfers(self.es, transfers_raw_index, **params) try: results = response.aggregations.StartTime.buckets except AttributeError: results = [] all_results = [ (x.key / 1000, x.Records.value, x.Network.value / 1024**2) for x in results ] return all_results def get_json(self): assert self.transfer_results != None assert self.transfer_volume_results != None total_transfers = sum(self.transfer_results) total_transfer_volume = sum(self.transfer_volume_results) return {'transfers_hourly': int(total_transfers), 'transfer_volume_mb_hourly': int(total_transfer_volume)} def get_data(self): all_times = list(self.data.keys()) all_times.sort() all_times = all_times[-26:-1] results = [] for time in all_times: results.append((int(self.data[time].count), self.data[time].volume_mb)) if results: self.transfer_results, self.transfer_volume_results = list(zip(*results)) else: self.transfer_results, self.transfer_volume_results = [[],[]] return results def get_volume_rates(self): all_times = list(self.data.keys()) all_times.sort() all_times = all_times[-26:-1] results = [] for time in all_times: td = self.data[time] interval = td.endtime - td.starttime interval_s = interval.days*86400 + interval.seconds results.append(td.volume_mb/interval_s) return results def get_rates(self): all_times = list(self.data.keys()) all_times.sort() all_times = all_times[-26:-1] results = [] for time in all_times: td = self.data[time] interval = td.endtime - td.starttime interval_s = interval.days*86400 + interval.seconds results.append(td.count/float(interval_s)) return results
UTF-8
Python
false
false
9,565
py
14
transfer_datasource.py
10
0.555463
0.544903
0
259
35.926641
85
karthigkk/chicago_taxi_ss
15,693,810,531,077
a2fb8027ad655d8377ffb1124d8aa8915a37b1dd
c4e3edae8a27ff6f65a21fe9f41d6fb3cfd56fe3
/packages/regression_model/regression_model/pipeline.py
5998a7ecd1ed038ffdcc6f53e30b06e04763035a
[]
no_license
https://github.com/karthigkk/chicago_taxi_ss
648ef04626a10bef0380df14f9c56d1b3a3af6f7
942cd98ef2e3f381e09344713221f37f6e51cceb
refs/heads/master
2023-01-11T18:05:32.487938
2020-11-11T10:34:49
2020-11-11T10:34:49
288,145,261
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from regression_model.preprocessing.preprocessors import Preprocessdataframe from mmlspark.featurize import AssembleFeatures from mmlspark.lightgbm import LightGBMRegressor from mmlspark.stages import UDFTransformer, DropColumns from pyspark.sql.types import IntegerType from pyspark.sql.functions import udf # from pyspark.ml.feature import OneHotEncoderEstimator, StringIndexer, VectorAssembler # from pyspark.ml.regression import LinearRegression from regression_model.config import config class Buildpipeline: def __init__(self): pass @staticmethod def build_stages() -> list: get_week_day = udf(lambda z: z.weekday(), IntegerType()) get_year = udf(lambda z: z.year, IntegerType()) get_month = udf(lambda z: z.month, IntegerType()) get_hour = udf(lambda z: z.hour, IntegerType()) #preprocess = Preprocessdataframe() # build Pipeline # stringIndexer = StringIndexer(inputCol=config.CATEGORICAL_VAR, outputCol='Comp_Index') # encoder = OneHotEncoderEstimator(inputCols=[stringIndexer.getOutputCol()], outputCols=['Comp_classVec']) # inputfeatures = config.NUMERICAL_VARS + config.DERIVED_VARS + ['Comp_classVec'] # assembler = VectorAssembler(inputCols=inputfeatures, outputCol='features') # lr = LinearRegression(featuresCol='features', labelCol=config.TARGET, maxIter=2, regParam=0.3, elasticNetParam=0.8) # STAGES = [preprocess, stringIndexer, encoder, assembler, lr] assembler = AssembleFeatures( columnsToFeaturize=config.NUMERICAL_VARS + config.DERIVED_VARS + config.CATEGORICAL_VAR, numberOfFeatures=1) lgbm = LightGBMRegressor(learningRate=0.001, numIterations=50, featuresCol='features', labelCol=config.TARGET) STAGES = [UDFTransformer(inputCol='trip_start_timestamp', outputCol='Trip_Day_Of_Week', udf=get_week_day), UDFTransformer(inputCol='trip_start_timestamp', outputCol='Trip_Year', udf=get_year), UDFTransformer(inputCol='trip_start_timestamp', outputCol='Trip_Month', udf=get_month), UDFTransformer(inputCol='trip_start_timestamp', outputCol='Trip_Hour', udf=get_hour), DropColumns(cols=['trip_start_timestamp']), assembler, lgbm] return STAGES
UTF-8
Python
false
false
2,313
py
36
pipeline.py
19
0.711198
0.70601
0
40
56.825
125
deutranium/speed-ideating
11,424,613,033,155
c488ae41aae24984de02185ec7ba010a9c409764
c70ef424f4f15fcce67af55ed93248e21f0c2791
/bot.py
aeaab62c67272c1233e4091e7ea21a5f5721178c
[]
no_license
https://github.com/deutranium/speed-ideating
cfbb32ef8b1281ec379ed56b729dcd5115d1242c
9f955636d83ddb8a90ee7ca218c4619ba3c4297b
refs/heads/master
2023-01-05T10:06:23.802102
2020-10-27T17:28:30
2020-10-27T17:28:30
305,782,759
0
0
null
false
2020-10-22T08:39:06
2020-10-20T17:23:04
2020-10-21T14:59:04
2020-10-22T08:39:05
16
0
0
0
Python
false
false
import os import sys from time import sleep import discord from tabulate import tabulate from dotenv import load_dotenv from sql import SQL load_dotenv() client = discord.Client() TOKEN = os.getenv("DISCORD_TOKEN") GUILD = os.getenv("DISCORD_GUILD") db = None history_channel = None # TODO: Add all the teams here # Make sure they are in order team_names = [ 'The Boys', 'MCDT', "Fluffy's 3 Heads", 'Mario & the other guy', 'www.', 'The Intrepids', 'Detty pigs', 'The Invincibles', 'Goal Diggers ', 'HoynaHoyna', 'El', 'Theen Bacche', 'Tesseract', 'XD', 'Ombani', 'Impostors', 'God particle', 'kryptomaniax ', 'Oreo Sheikhs', 'Sons of pitches', 'Strawberry Beans', ] # admin role ID ADMIN_ID = 767717031318782003 HISTORY_CHANNEL_ID = 768235871223676948 def help(): """ Shows help message """ help_msg = """ ``` Commands (prepend `!si` to all the commands): update <teamA> <teamB> <score>: Transfer `score` points FROM teamA TO teamB scoreboard: Display the scoreboard ``` """ return help_msg def print_scoreboard(): """ Returns the scoreboard as a string """ data = db.get_scoreboard() headers = ["Team #", "Name", "Score"] content = tabulate(data, headers) return "```\n" + content + "\n```" def update_score(from_team_id, to_team_id, score_delta): """ Updates the score If successful, returns the new scoreboard otherwise nothing """ if db.update_score(from_team_id, to_team_id, score_delta): return print_scoreboard() return None # TODO: ADD ALL THE UPDATES TO READ-ONLY HISTORY CHANNEL async def add_to_history(message): global history_channel if history_channel is None: history_channel = client.get_channel(HISTORY_CHANNEL_ID) await history_channel.send(message) @client.event async def on_ready(): print(f"{client.user} has connected to Discord!\n") guild = discord.utils.get(client.guilds, name=GUILD) print( f"{client.user} is connected to the following guild:\n" f"{guild.name}(id: {guild.id})" ) @client.event async def on_message(message): msg = "A valid command plox" cntnt = message.content.lower() # Check bot prefix if (cntnt.split()[0] != "!si") or message.author.bot: return # Check if the author is an admin if ADMIN_ID not in [i.id for i in message.author.roles]: await message.channel.send("Only admins allowed") return # remove the prefix cntnt = " ".join(cntnt.split()[1:]) # help if cntnt == "help": msg = help() # display scoreboard elif cntnt == "scoreboard": msg = print_scoreboard() # update team score elif cntnt.split()[0] == "update": _, from_team_id, to_team_id, delta = cntnt.split() if int(delta) < 0: msg = "Only positive score can be transferred.\nCheck !si.help" else: logs = f"{message.author} requested for transferring {delta} points from {from_team_id} to {to_team_id}" msg = update_score(int(from_team_id), int(to_team_id), int(delta)) if msg is None: msg = "Failed to update score" logs += "\n\nStatus: FAILED" else: logs += "\n\nStatus: Successful" await add_to_history(logs) await message.channel.send(msg) def main(): global db # setup database and tables db = SQL() db.setup_table() if db.count_rows() == 0: db.populate_table(team_names) client.run(TOKEN) if __name__ == "__main__": while True: try: main() except Exception as e: print(e) sleep(10)
UTF-8
Python
false
false
3,806
py
3
bot.py
2
0.596689
0.585129
0
174
20.873563
116
zaswedyg/Algorithms
5,214,090,335,203
2eca1c78e7c0a5f5c3d5011fcc9aa7b100e9c3ee
96ca5294a67294885a7519c558e4036801815211
/HW2.py
0d62e3ac4b9902a685257c109d132f18cd8116b1
[]
no_license
https://github.com/zaswedyg/Algorithms
be8cf3d19b3a9b2c5c4e30a52a43ba3b980b716c
2954e26cececebcd5d74bcc4121b337ac441ea7b
refs/heads/main
2023-06-26T06:18:58.490317
2021-07-28T03:08:19
2021-07-28T03:08:19
383,977,546
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# 1. Split in Half #Given a string. Split it into two equal parts. Swap these parts and return the result. #If the string has odd characters, the first part should be one character greater than the second part. #Example: string = 'bbbbbcaaaaa'. Result = ‘aaaaabbbbbc’. """ def split_in_half(s): first_half = "" second_half = "" string_length = len(s) if string_length % 2 == 0: first_half = s[0:(string_length/2-1)] second_half = s[string_length/2:] return (second_half + first_half) else: first_half = s[0:(string_length // 2 + 1)] second_half = s[string_length // 2 + 1:] return (second_half + first_half) print(split_in_half("bbbbbcaaaaa")) """ # 2. Unique Characters in String # Given a string, determine if it consists of all unique characters. # For example, the string 'abcde' has all unique characters and should return True. # The string 'aabcde' contains duplicate characters and should return False. """ def unique_char(s): chars = set() for char in s: if char in chars: return False else: chars.add(char) return True print(unique_char('abcde')) print(unique_char('aabcde')) """
UTF-8
Python
false
false
1,218
py
8
HW2.py
7
0.64168
0.630972
0
42
27.880952
103
soyoungcheng/senti_c
4,045,859,195,557
9bada3e0148b96096293a40d3fb8136d8a35f8e4
4af5e167a8b49298b994e68411217f5baf666709
/src/senti_c/model_structure.py
9b3b64a1898e6383758b0827251fc53930b817d1
[]
no_license
https://github.com/soyoungcheng/senti_c
bdb18f608f9e761c0f32cc2628040b12e58e0dfa
4ea14b83040ef586d1edbd995f6fb1eef8a3282a
refs/heads/master
2023-04-02T22:34:37.418203
2021-04-06T00:43:13
2021-04-06T00:43:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# coding=utf-8 # Some of structures or codes in this script are referenced from HuggingFace Inc. team. # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. 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. '''放置句子情感分類、屬性情感分析模型架構''' import torch import torch.nn as nn from torch.nn import BCEWithLogitsLoss from torch.nn import CrossEntropyLoss from torch.nn import NLLLoss from transformers import ( BertModel, BertPreTrainedModel, ) import numpy as np import os import torch.nn.functional as F from .utils import chg_labels_to_aspect_and_sentiment,get_domain_embedding class MyNewBertForSequenceClassification(BertPreTrainedModel): '''BERT輸出接上一層線性層;此外額外加入domain embedding layer,等於最後BERT輸出和domain embedding連接、饋入分類層,是句子情感分類的模型''' def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.bert = BertModel(config) self.dropout = nn.Dropout(config.hidden_dropout_prob) ### 加入 domain embedding layer file_path = os.path.split(os.path.realpath(__file__))[0] + "/utils/new_restaurant_emb.vec.npy" get_domain_embedding(file_path) domain_emb = np.load(file_path) self.domain_embedding = nn.Embedding(domain_emb.shape[0], domain_emb.shape[1]) self.domain_embedding.weight = nn.Parameter(torch.from_numpy(domain_emb), requires_grad=True) self.first_classifier = nn.Linear(config.hidden_size+domain_emb.shape[1],config.hidden_size) self.classifier = nn.Linear(config.hidden_size, self.config.num_labels) self.init_weights() def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, ): outputs = self.bert( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, ) pooled_output = outputs[1] pooled_output = self.dropout(pooled_output) ### 加入 domain embedding ### input_embedding = self.domain_embedding(input_ids) ### 將每筆資料中每個字的embedding拼起來平均 ### sent_embedding = torch.mean(input_embedding,dim=1) #針對seq部分做平均 ### 將平均後的embedding和bert的CLS位置輸出連接 ### combine_emb = torch.cat((sent_embedding,pooled_output),dim=1) ### 經過兩層線性層、中間添加tanh活化函數 ### firsts = self.first_classifier(combine_emb) firsts = torch.tanh(firsts) logits = self.classifier(firsts) outputs = (logits,) + outputs[2:] if labels is not None: loss_fct = BCEWithLogitsLoss() #改成多標籤分類(每個標籤做二元分類的感覺) labels = labels.float() loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1, self.num_labels)) outputs = (loss,) + outputs return outputs # class MyNewBertForSequenceClassification(BertPreTrainedModel): # '''BERT輸出接上一層線性層,是句子情感分類的模型''' # def __init__(self, config): # super().__init__(config) # self.num_labels = config.num_labels # self.bert = BertModel(config) # self.dropout = nn.Dropout(config.hidden_dropout_prob) # self.classifier = nn.Linear(config.hidden_size, self.config.num_labels) # self.init_weights() # def forward( # self, # input_ids=None, # attention_mask=None, # token_type_ids=None, # position_ids=None, # head_mask=None, # inputs_embeds=None, # labels=None, # ): # outputs = self.bert( # input_ids, # attention_mask=attention_mask, # token_type_ids=token_type_ids, # position_ids=position_ids, # head_mask=head_mask, # inputs_embeds=inputs_embeds, # ) # pooled_output = outputs[1] # pooled_output = self.dropout(pooled_output) # logits = self.classifier(pooled_output) # outputs = (logits,) + outputs[2:] # add hidden states and attention if they are here # if labels is not None: # loss_fct = BCEWithLogitsLoss() #改成多標籤分類(每個標籤做二元分類的感覺) # labels = labels.float() # loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1, self.num_labels)) # outputs = (loss,) + outputs # return outputs class MyNewBertForTokenClassification(BertPreTrainedModel): '''將BERT每個位置輸出接上線性層預測屬性,並輔以屬性轉移矩陣設置;另外將BERT輸出額外接上另一線性層預測情感,之後用情感轉移矩陣獲得最終情感預測結果,是屬性情感分析的模型''' def __init__(self, config): super().__init__(config) self.bert = BertModel(config) self.dropout = nn.Dropout(config.hidden_dropout_prob) ### 將BERT輸出傳到這層來做屬性標記預測 ### self.aspect_classfier = nn.Linear(config.hidden_size,3) #768 -> 3 (BIO) ### 增加屬性轉移矩陣 ### # transition_path = {'B': ['B','I', 'O'], # 'I': ['B', 'I', 'O'], # 'O': ['B','O']} self.transition_scores_aspect = [[1/3,1/3,1/3],[1/3,1/3,1/3],[1/2,0,1/2]] #3*3矩陣,為B/I/O到B/I/O的機率 self.transition_scores_aspect = np.array(self.transition_scores_aspect, dtype='float32').transpose() ### 增加情感轉移矩陣 (FOR 屬性標籤預測情感標籤) ### # transition_path = {'B': ['NEG','NEU','POS'], # 'I': ['NEG','NEU','POS'], # 'O': ['O']} self.transition_scores_sentiment = [[1/3,1/3,1/3,0],[1/3,1/3,1/3,0],[0,0,0,1]] #3*4矩陣,為B/I/O到NEG/NEU/POS/O的機率 self.transition_scores_sentiment = np.array(self.transition_scores_sentiment, dtype='float32').transpose() ### 將BERT輸出傳到這層來預測情感標記 ### self.sentiment_classifier = nn.Linear(config.hidden_size, 4) #768 -> 4 (POS/NEU/NEG/O) self.init_weights() def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, ): outputs = self.bert( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, ) tagger_input = outputs[0] tagger_input = self.dropout(tagger_input) #### 以下開始對屬性部分做處理 #### aspect_tagger_pred = self.aspect_classfier(tagger_input) pred_aspect = F.softmax(aspect_tagger_pred,dim=2) if torch.cuda.is_available(): self.transitions_aspect = torch.tensor(self.transition_scores_aspect).cuda() else: self.transitions_aspect = torch.tensor(self.transition_scores_aspect) combined_aspect_pred = [] for bsz in range(pred_aspect.size(0)) : current_sample = pred_aspect[bsz] current_sample_transition = [] for t in range(current_sample.size(0)): if t == 0 or t == 1: #對 cls & 對 cls後的第一個字 => 兩者都不用做轉移矩陣運算 current_sample_transition.append(current_sample[t]) else: transition_pred = torch.mm(self.transitions_aspect,current_sample_transition[t-1].view(3,-1)) #轉移矩陣乘上前一個token已經權衡相加後的值 ### 計算 confidence value (用轉移矩陣算出的值的重要程度) ### val = torch.sum(current_sample_transition[t-1].view(3,-1) * current_sample_transition[t-1].view(3,-1)) alpha = val * 0.6 new_aspect_pred = alpha * transition_pred + (1-alpha) * current_sample[t].view(3,-1) current_sample_transition.append(new_aspect_pred.view(-1)) combined_aspect_pred.append(torch.stack(current_sample_transition, 0)) aspect_tagger = torch.stack(combined_aspect_pred, 0) ### 以下開始對情感部分做處理 ### sentiment_pred = self.sentiment_classifier(tagger_input) if torch.cuda.is_available(): self.transitions_sentiment = torch.tensor(self.transition_scores_sentiment).cuda() else: self.transitions_sentiment = torch.tensor(self.transition_scores_sentiment) sentiment_pred = F.softmax(sentiment_pred,dim=2) combined_sentiment_pred = [] for bsz in range(sentiment_pred.size(0)) : current_sample_aspect = aspect_tagger[bsz] current_sample_sentiment = sentiment_pred[bsz] current_sample_transition = [] for t in range(current_sample_sentiment.size(0)): if t == 0: #對cls不用做轉移矩陣運算 current_sample_transition.append(current_sample_sentiment[t]) else: transition_pred = torch.mm(self.transitions_sentiment,current_sample_aspect[t].view(3,-1)) #轉移矩陣乘上屬性預測標籤 ### 計算 confidence value (這個用轉移矩陣算出的值的重要程度) ### val = torch.sum(current_sample_aspect[t].view(3,-1) * current_sample_aspect[t].view(3,-1)) alpha = val * 0.6 new_sentiment_pred = alpha * transition_pred + (1-alpha) * current_sample_sentiment[t].view(4,-1) current_sample_transition.append(new_sentiment_pred.view(-1)) combined_sentiment_pred.append(torch.stack(current_sample_transition, 0)) logits = torch.stack(combined_sentiment_pred, 0) outputs = (aspect_tagger,) + (logits,) + outputs[2:] ### 輸入的label map: {'B-NEG': 0, 'B-NEU': 1, 'B-POS': 2, 'I-NEG': 3, 'I-NEU': 4, 'I-POS': 5, 'O': 6} ## 自定義的新label map : # aspect_labels : {"B" : 0, "I":1, "O": 2} # sentiment_labels {"NEG": 0 ,"NEU":1, "POS":2, "O":3} if labels is not None: #處理 labels、讓它符合joint屬性模型格式 aspect_labels, sentiment_labels = chg_labels_to_aspect_and_sentiment(labels) aspect_tagger = torch.log(aspect_tagger + 1e-20) #將屬性預測部分經過log logits = torch.log(logits + 1e-20) #將情感預測部分經過log loss_fct = NLLLoss() #因為已經過softmax和log,不能使用CrossEntropyLoss if attention_mask is not None: active_loss = attention_mask.view(-1) == 1 active_logits = aspect_tagger.view(-1, 3) active_labels = torch.where( active_loss, aspect_labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels) ) aspect_loss = loss_fct(active_logits, active_labels) active_loss = attention_mask.view(-1) == 1 active_logits = logits.view(-1, 4) active_labels = torch.where( active_loss, sentiment_labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels) ) sentiment_loss = loss_fct(active_logits, active_labels) loss = aspect_loss + sentiment_loss else: aspect_loss = loss_fct(aspect_tagger.view(-1, 3), aspect_labels.view(-1)) sentiment_loss = loss_fct(logits.view(-1, 4), sentiment_labels.view(-1)) loss = aspect_loss + sentiment_loss outputs = (loss,) + (aspect_loss,) + (sentiment_loss,) + outputs return outputs # class MyNewBertForTokenClassification(BertPreTrainedModel): # '''把bert輸出分別接上一層線性分類層,是屬性情感分析的模型''' # def __init__(self, config): # super().__init__(config) # self.bert = BertModel(config) # self.dropout = nn.Dropout(config.hidden_dropout_prob) # # 將bert輸出傳到這層來預測屬性標記 # self.aspect_classfier = nn.Linear(config.hidden_size,3) #768 -> 3 (BIO) # # 將bert輸出傳到這層來預測情感標記 # self.sentiment_classifier = nn.Linear(config.hidden_size, 4) #768 -> 4 (POS/NEU/NEG/O) # self.init_weights() # def forward( # self, # input_ids=None, # attention_mask=None, # token_type_ids=None, # position_ids=None, # head_mask=None, # inputs_embeds=None, # labels=None, # ): # outputs = self.bert( # input_ids, # attention_mask=attention_mask, # token_type_ids=token_type_ids, # position_ids=position_ids, # head_mask=head_mask, # inputs_embeds=inputs_embeds, # ) # tagger_input = outputs[0] # tagger_input = self.dropout(tagger_input) # aspect_tagger = self.aspect_classfier(tagger_input) #輸出預測的屬性標註, 維度是bsz,seq,num_labels (3,因為標BIO) # logits = self.sentiment_classifier(tagger_input) #得到最後經過情感標註後的結果 # outputs = (aspect_tagger,) + (logits,) + outputs[2:] # ### 輸入的label map: {'B-NEG': 0, 'B-NEU': 1, 'B-POS': 2, 'I-NEG': 3, 'I-NEU': 4, 'I-POS': 5, 'O': 6} # ## 需轉成自定義的新label map : # # aspect_labels : {"B" : 0, "I":1, "O": 2} # # sentiment_labels {"NEG": 0 ,"NEU":1, "POS":2, "O":3} # if labels is not None: # #處理 labels、讓它符合joint屬性模型格式 # aspect_labels, sentiment_labels = chg_labels_to_aspect_and_sentiment(labels) # loss_fct = CrossEntropyLoss() # if attention_mask is not None: # # 先算屬性標記的loss: # active_loss = attention_mask.view(-1) == 1 # active_logits = aspect_tagger.view(-1, 3) # active_labels = torch.where( # active_loss, aspect_labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels) # ) # aspect_loss = loss_fct(active_logits, active_labels) # active_loss = attention_mask.view(-1) == 1 # active_logits = logits.view(-1, 4) # active_labels = torch.where( # active_loss, sentiment_labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels) # ) # sentiment_loss = loss_fct(active_logits, active_labels) # loss = aspect_loss + sentiment_loss #兩個loss會一起訓練 # else: # aspect_loss = loss_fct(aspect_tagger.view(-1, 3), aspect_labels.view(-1)) # sentiment_loss = loss_fct(logits.view(-1, 4), sentiment_labels.view(-1)) # loss = aspect_loss + sentiment_loss #兩個loss會一起訓練 # outputs = (loss,) + (aspect_loss,) + (sentiment_loss,) + outputs # return outputs
UTF-8
Python
false
false
17,198
py
15
model_structure.py
10
0.550063
0.537469
0
413
37.641646
139
doamaral/MIA
566,935,694,076
ff53daf2e608630130f4ddb21cb401353a0f214a
60cbc3aae5cc975b962d6a57c376af608355f4d7
/pest/envsim/__init__.py
6808c33e877bfb34492bfd119163fb5d7e3f2146
[]
no_license
https://github.com/doamaral/MIA
553c0c1732c50470108e8c21b71fbe0f6c2e2c07
7deb195f8a98e2ce0d53b03dc5e9c4ba71205deb
refs/heads/master
2021-01-10T01:02:31.216041
2015-06-18T11:18:40
2015-06-18T11:18:40
31,398,747
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
__author__ = 'Usuário'
UTF-8
Python
false
false
24
py
12
__init__.py
10
0.565217
0.565217
0
1
22
22
jeansyo/Python
7,799,660,618,766
6bf8d19ab8cf175214a0171b64f59cf8b0ddc9fd
353955d50f75ec7363961aad7c6a9761ae0bc46d
/suma_de_matrizes.py
b9bf3d5d186f919a51a36cc467c20c367c781ea2
[]
no_license
https://github.com/jeansyo/Python
06f86894b5c5b6e0449cd5e6fedbc1c509550d5c
96badd322b793849e82500543d26981cc9af0360
refs/heads/master
2022-09-25T07:20:18.918979
2020-06-06T05:36:38
2020-06-06T05:36:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- """ Created on Wed May 6 21:30:25 2020 @author: DELL.E5430.SSD """ m = int(input('Digite la cantidad de filas: ')) n = int(input('Digite la cantidad de columnas: ')) matriz_a = [] matriz_b = [] matriz_suma = [] for i in range(m): matriz_a.append([0]*n) for i in range(m): matriz_b.append([0]*n) print('Matriz A:') for i in range(m): for j in range(n): matriz_a[i][j] = int(input(f'Matriz A --> Fila {i+1}, columna {j+1}: ')) print() print('Matriz B:') for i in range(m): for j in range(n): matriz_b[i][j] = int(input(f'Matriz B --> Fila {i+1}, columna {j+1}: ')) print() print('Matriz A') for i in matriz_a: print(i) print() print('Matriz B') for i in matriz_b: print(i) print() #sumamos for i in range(m): matriz_suma.append([0]*n) for i in range(m): for j in range(n): matriz_suma[i][j] = matriz_a[i][j] + matriz_b[i][j] print('La matriz suma es: ') for i in matriz_suma: print(i)
UTF-8
Python
false
false
1,021
py
97
suma_de_matrizes.py
97
0.553379
0.530852
0
55
17.581818
80
odify/PORT-OF-PYTHON
6,055,903,913,726
a1386c7be4c7fd74cb891a7565a8dd2001fab47c
3af1a0ba485f28ee695c9a95773140b6cfa721f1
/CLI/metas-cli/metaextractor.py
19e7b802e248701a88111cf215a14e867a4c833a
[]
no_license
https://github.com/odify/PORT-OF-PYTHON
d985e1a25ac20072f375ed96b4186279e17f237e
b7335af2c55eb10768e3a0b9ad621e263e1b766d
refs/heads/main
2023-08-18T06:48:19.103446
2021-10-13T18:37:41
2021-10-13T18:37:41
311,485,221
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/local/bin/python3 from colored import stylize, fg from PIL import Image from PIL.ExifTags import TAGS # EXTRACT METADATA FROM IMG class Metadata: def __init__(self, file): self.file = file def __repr__(self): metadata = self.extract_metadata(self.file) if len(metadata) == 0: return stylize(f"\n{self.file} No metadata.\n", fg("red")) else: print(stylize(f"\nMetadata of {self.file}:\n", fg("red"))) for data in metadata: print(data) return "" def extract_metadata(self, file): image = Image.open(file) exifdata = image.getexif() metadata = [] for tag_id in exifdata: tag = TAGS.get(tag_id, tag_id) data = exifdata.get(tag_id) if isinstance(data, bytes): data = data.decode() metadata.append(f"{tag:25}: {data}") return metadata if __name__ == "__main__": filename = input("Filename: ") print(Metadata(filename))
UTF-8
Python
false
false
1,058
py
85
metaextractor.py
53
0.545369
0.541588
0
49
20.591837
70
cash2one/xai
19,232,863,562,926
6b2dbefb5db45211a1230a314ae6b1ba34b8c88d
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/nouns/_dog.py
28708a46d37edb8ee9d3422bc35e91a4912bec0d
[ "MIT" ]
permissive
https://github.com/cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#calss header class _DOG(): def __init__(self,): self.name = "DOG" self.definitions = [u'a common animal with four legs, especially kept by people as a pet or to hunt or guard things: ', u'a man who is unpleasant or not to be trusted: ', u'a woman who is not attractive'] self.parents = [] self.childen = [] self.properties = [] self.jsondata = {} self.specie = 'nouns' def run(self, obj1 = [], obj2 = []): return self.jsondata
UTF-8
Python
false
false
454
py
37,275
_dog.py
37,266
0.640969
0.636564
0
17
25.588235
206
franciscovillaescusa/Quijote-simulations
4,758,823,787,835
a2e68f0f1828debab440cfca7a30aa93366acb94
fb228c9604964b9bea7d099e581906918cd24e5b
/Bk/Bk_halos.py
26d0b17bdb6cd3118490391b889febc04857f06b
[ "MIT" ]
permissive
https://github.com/franciscovillaescusa/Quijote-simulations
927efec911799858a74a57f27fb5a9178f22cc8c
36644e63c5ca421a3a1e664d0fe735f40abb7d27
refs/heads/master
2023-08-21T15:30:44.937134
2023-08-16T14:11:41
2023-08-16T14:11:41
183,778,267
81
256
MIT
false
2023-03-22T01:34:32
2019-04-27T13:45:47
2023-01-15T10:01:57
2023-03-22T01:34:31
71,354
69
131
1
Python
false
false
# This script computes the halo bispectrum in real- and redshift-space. It takes as input # the first and last number of the wanted realizations, the cosmology and the snapnum # In redshift-space it computes the bispectrum along the 3 different axes. import argparse from mpi4py import MPI import numpy as np import sys,os import readgadget,readfof import redshift_space_library as RSL from pyspectrum import pyspectrum as pySpec ###### MPI DEFINITIONS ###### comm = MPI.COMM_WORLD nprocs = comm.Get_size() myrank = comm.Get_rank() # read the first and last realization to identify voids parser = argparse.ArgumentParser(description="This script computes the bispectrum") parser.add_argument("first", help="first realization number", type=int) parser.add_argument("last", help="last realization number", type=int) parser.add_argument("cosmo", help="folder with the realizations") parser.add_argument("snapnum", help="snapshot number", type=int) args = parser.parse_args() first, last, cosmo, snapnum = args.first, args.last, args.cosmo, args.snapnum # This routine computes and saves the bispectrum def find_Bk(folder, snapdir, snapnum, axis, Ngrid, step, Ncut, Nmax, do_RSD, fixed_Mmin, Mmin, Nhalos): # read header head = readgadget.header(snapdir) BoxSize = head.boxsize/1e3 #Mpc/h Omega_m = head.omega_m Omega_l = head.omega_l redshift = head.redshift Hubble = 100.0*np.sqrt(Omega_m*(1.0+redshift)**3+Omega_l)#km/s/(Mpc/h) h = head.hubble # read halo catalogue FoF = readfof.FoF_catalog(folder, snapnum, long_ids=False, swap=False, SFR=False, read_IDs=False) pos_h = FoF.GroupPos/1e3 #Mpc/h mass = FoF.GroupMass*1e10 #Msun/h vel_h = FoF.GroupVel*(1.0+redshift) #km/s if fixed_Mmin: indexes = np.where(mass>Mmin)[0] pos_h = pos_h[indexes]; vel_h = vel_h[indexes]; del indexes else: indexes = np.argsort(mass)[-Nhalos:] #take the Nhalos most massive halos pos_h = pos_h[indexes]; vel_h = vel_h[indexes]; del indexes # move halos to redshift-space if do_RSD: RSL.pos_redshift_space(pos_h, vel_h, BoxSize, Hubble, redshift, axis) # calculate bispectrum b123out = pySpec.Bk_periodic(pos_h.T, Lbox=BoxSize, Ngrid=Ngrid, step=step, Ncut=Ncut, Nmax=Nmax, fft='pyfftw', nthreads=1, silent=False) i_k = b123out['i_k1'] j_k = b123out['i_k2'] l_k = b123out['i_k3'] p0k1 = b123out['p0k1'] p0k2 = b123out['p0k2'] p0k3 = b123out['p0k3'] b123 = b123out['b123'] b_sn = b123out['b123_sn'] q123 = b123out['q123'] cnts = b123out['counts'] hdr = ('halo bispectrum; k_f = 2pi/%.1f, Nhalo=%i'%(BoxSize, pos_h.shape[0])) np.savetxt(fbk, np.array([i_k, j_k, l_k, p0k1, p0k2, p0k3, b123, q123, b_sn, cnts]).T, fmt='%i %i %i %.5e %.5e %.5e %.5e %.5e %.5e %.5e', delimiter='\t', header=hdr) root = '/simons/scratch/fvillaescusa/pdf_information' ##################################### INPUT ######################################### # Bk parameters Ngrid = 360 Nmax = 40 Ncut = 3 step = 3 # halo parameters fixed_Mmin = True #whether fix Mmin or nbar Mmin = 3.2e13 #Msun/h; fixed Mmin Nhalos = 150000 #also consider the Nhalos more massive of the sim (nbar fixed) # output folder name root_out = '/simons/scratch/fvillaescusa/pdf_information/Bk/Mmin_3.2e13/' ##################################################################################### # find the redshift z = {4:0, 3:0.5, 2:1, 1:2, 0:3}[snapnum] # create output folder if it does not exist if myrank==0: if not(os.path.exists(root_out+cosmo)): os.system('mkdir %s/%s/'%(root_out,cosmo)) # get the realizations each cpu works on numbers = np.where(np.arange(args.first, args.last)%nprocs==myrank)[0] numbers = np.arange(args.first, args.last)[numbers] ######## standard simulations ######### for i in numbers: folder = '%s/Halos/%s/%d'%(root,cosmo,i) #folder with the halo catalogue if not(os.path.exists(folder)): continue snapdir = '%s/%s/%d/snapdir_%03d/snap_%03d'%(root,cosmo,i,snapnum,snapnum) # real-space fbk = '%s/%s/Bk_%d_z=%s.txt'%(root_out,cosmo,i,z) if not(os.path.exists(fbk)): do_RSD, axis = False, 0 find_Bk(folder, snapdir, snapnum, axis, Ngrid, step, Ncut, Nmax, do_RSD, fixed_Mmin, Mmin, Nhalos) # redshift-space for axis in [0,1,2]: fbk = '%s/%s/Bk_RS%d_%d_z=%s.txt'%(root_out,cosmo,axis,i,z) if not(os.path.exists(fbk)): do_RSD = True find_Bk(folder, snapdir, snapnum, axis, Ngrid, step, Ncut, Nmax, do_RSD, fixed_Mmin, Mmin, Nhalos) ###### paired fixed realizations ###### for i in numbers: for pair in [0,1]: folder = '%s/Halos/%s/NCV_%d_%d'%(root,cosmo,pair,i) #halo catalogue folder if not(os.path.exists(folder)): continue snapdir = '%s/%s/NCV_%d_%d/snapdir_%03d/snap_%03d'\ %(root,cosmo,pair,i,snapnum,snapnum) # real-space fbk = '%s/%s/Bk_NCV_%d_%d_z=%s.txt'%(root_out,cosmo,pair,i,z) if not(os.path.exists(fbk)): do_RSD, axis = False, 0 find_Bk(folder, snapdir, snapnum, axis, Ngrid, step, Ncut, Nmax, do_RSD, fixed_Mmin, Mmin, Nhalos) # redshift-space for axis in [0,1,2]: fbk = '%s/%s/Bk_RS%d_NCV_%d_%d_z=%s.txt'%(root_out,cosmo,axis,pair,i,z) if not(os.path.exists(fbk)): do_RSD = True find_Bk(folder, snapdir, snapnum, axis, Ngrid, step, Ncut, Nmax, do_RSD, fixed_Mmin, Mmin, Nhalos)
UTF-8
Python
false
false
5,888
py
115
Bk_halos.py
56
0.584239
0.557575
0
151
37.907285
90
nurse/nkf
6,725,918,799,152
52e8949fb60d7f7fd49435cb3d6c4afad2624d40
ec5fc1c97ec8638966099d1699e363b728e5d2f7
/NKF.python3/setup.py
c68d03cef593907031c448f2adeccfe795d80c75
[]
no_license
https://github.com/nurse/nkf
a29e950709af320bcbcb871b1b9158d4b8ae5e22
a937062004418d776cef426876def9aba6d8e94f
refs/heads/master
2022-12-12T13:45:42.854398
2022-08-08T09:57:16
2022-08-08T09:57:16
3,713,060
72
19
null
false
2022-12-06T03:38:34
2012-03-14T00:44:33
2022-09-20T12:57:11
2022-08-08T09:57:16
1,066
69
15
1
C
false
false
#!/usr/bin/env python from distutils.core import setup, Extension setup (name = "nkf", version="1.0", description="Python Interface to NKF", author="Matsumoto Tadashi", author_email="ma2@city.plala.jp", ext_modules = [ Extension("nkf", ["NKF_python.c"], extra_link_args = ['-s'])])
UTF-8
Python
false
false
359
py
21
setup.py
2
0.548747
0.54039
0
12
28.916667
52
Ebuyuktas/11-HAFTA-OOP
6,597,069,806,266
4787aad7c5732a2c14ad8b99228739511a343935
b822f5f418092f44b3b8c4111561961f905261a0
/odev2.py
dfccaeb54e8feda6c5ea89d3b19f91d7c74ddffe
[]
no_license
https://github.com/Ebuyuktas/11-HAFTA-OOP
d250f3ca697eefd0ecc1857965d5849e6974a92d
04337e5ed113a09bf73b8d791ce92853391a6ef5
refs/heads/master
2020-07-12T05:54:36.344834
2019-08-30T17:52:13
2019-08-30T17:52:13
204,736,772
0
0
null
true
2019-08-27T18:46:50
2019-08-27T15:46:50
2019-08-26T09:50:26
2019-08-26T09:50:25
1
0
0
0
null
false
false
#hafta 11 odev 2# #muzik listesi# import random class walkman(): liste=[] def cal(self,sarki): if sarki in self.liste: print(sarki,"yurutuluyor..") else: print("Malesef repertuvarimizda mevcut degil") def temizle(self): self.liste.clear() print("yurutme listesi bos") def goruntule(self): print("Sarkilar:\n") for i in self.liste: print(i) def ekle(self,sarki): self.liste.append(sarki) print(sarki,"eklendi iyi dinlemeler..\n\n") def sil(self,sarki): self.liste.pop(self.liste.index(sarki)) print(sarki,"listeden kaldirildi\n") def sonraki(self,sarki): x=self.liste.index(sarki) print("Bir sonraki parcamiz: ") print(self.liste[x+1],"caliniyor...") def onceki(self,sarki): x=self.liste.index(sarki) print("onceki sarkimiz: \n") print(self.liste[x-1], "caliniyor...") def karisik(self): karisik=random.randint(0,len(self.liste)) print(self.liste[karisik], "Caliniyor..") repertuvar= walkman() repertuvar.ekle("Sagopa-366. gun") repertuvar.ekle("Hayko Cepkin-Gelin olmus") repertuvar.ekle("Duman-Eski koprunun altinda") repertuvar.ekle("Cem karaca-kara sevda") repertuvar.ekle("Tarkan-Yolla") repertuvar.goruntule() repertuvar.sil("Hayko Cepkin-Gelin olmus") repertuvar.sonraki("Duman-Eski koprunun altinda") repertuvar.onceki("Sagopa-366. gun") repertuvar.karisik() repertuvar.temizle()
UTF-8
Python
false
false
1,463
py
2
odev2.py
2
0.663021
0.654819
0
54
25.092593
52
jiamo/concurrent_server
3,143,916,083,613
8ea4e701963363f8337da6bf40759d13cb194ff3
f640756039e04dae4a3e4adfb69b0b15eda3c54a
/epoll_server.py
f16e7c4a47626ff475183b8666c0bd8807639e05
[]
no_license
https://github.com/jiamo/concurrent_server
de0b518a3e729be1a678d0ee1371a0abcbefed8b
9a6d661b2afe2a7207cc3b6eb2eab45976f604a8
refs/heads/master
2021-06-02T09:09:20.124364
2020-01-13T04:43:18
2020-01-13T04:43:18
144,312,145
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python """Simple server using epoll. running in linux""" from __future__ import print_function from contextlib import contextmanager import socket import select from enum import Enum class ProcessingState(Enum): INITIAL_ACK = 0 WAIT_FOR_MSG = 1 IN_MSG = 2 class PeerState: def __init__(self, process_state=None, sendbuf=None, sendbuf_end=None, sendptr=None): self.process_state = process_state self.sendbuf = sendbuf or [] self.sendbuf_end = sendbuf_end self.sendptr = sendptr SENDBUF_SIZE = 1024 MAX_SOCKS = 1000 global_states = [PeerState() for i in range(MAX_SOCKS)] class SockStatus: def __init__(self, want_read, want_write): self.want_read = want_read self.want_write = want_write sock_status_R = SockStatus(True, False) sock_status_W = SockStatus(False, True) sock_status_RW = SockStatus(True, True) sock_status_NORW = SockStatus(False, False) @contextmanager def socketcontext(*args, **kwargs): """Context manager for a socket.""" s = socket.socket(*args, **kwargs) try: yield s finally: print("Close socket") s.close() @contextmanager def epollcontext(*args, **kwargs): """Context manager for an epoll loop.""" e = select.epoll() e.register(*args, **kwargs) try: yield e finally: print("\nClose epoll loop") e.unregister(args[0]) e.close() def init_connection(server, connections, requests, responses, epoll): """Initialize a connection.""" connection, address = server.accept() connection.setblocking(0) fd = connection.fileno() epoll.register(fd, select.EPOLLIN) connections[fd] = connection requests[fd] = '' responses[fd] = '' def on_peer_connected(conn, address): print(f"on accept {address}") fd = conn.fileno() assert fd < MAX_SOCKS peer_state = global_states[fd] peer_state.process_state = ProcessingState.INITIAL_ACK peer_state.sendbuf.insert(0, "*") peer_state.sendptr = 0 peer_state.sendbuf_end = 1 return sock_status_W def on_peer_ready_recv(fd, connections): sock = connections[fd] peer_state = global_states[fd] print(f"on_peer_ready_recv {peer_state.process_state} {fd}") print(f"on_peer_ready_recv f{fd} {id(peer_state)}") if peer_state.process_state == ProcessingState.INITIAL_ACK or \ peer_state.sendptr < peer_state.sendbuf_end: return sock_status_W buffer_len = 1024 data = sock.recv(buffer_len) print(f"on_peer_ready_recv {data} {peer_state.process_state}") if not data: return sock_status_NORW # failed has except for simple reason don't handle it ready_to_send = False for i, ch in enumerate(data): if peer_state.process_state == ProcessingState.INITIAL_ACK: assert "can't reach here" elif peer_state.process_state == ProcessingState.WAIT_FOR_MSG: if data[i] == ord(b'^'): print("recv ^") peer_state.process_state = ProcessingState.IN_MSG elif peer_state.process_state == ProcessingState.IN_MSG: if data[i] == ord(b'$'): peer_state.process_state = ProcessingState.WAIT_FOR_MSG else: assert peer_state.sendbuf_end < 1024 peer_state.sendbuf.insert(peer_state.sendbuf_end, chr(data[i] + 1)) peer_state.sendbuf_end += 1 ready_to_send = True # change a little # return SockStatus( # want_read=(not ready_to_send), # want_write=ready_to_send, # ) if ready_to_send: return sock_status_W else: return sock_status_R def on_peer_ready_send(fd, connections): # print("on_peer_ready_send") sock = connections[fd] peer_state = global_states[fd] if peer_state.sendptr >= peer_state.sendbuf_end: return sock_status_RW send_len = peer_state.sendbuf_end - peer_state.sendptr send_data = peer_state.sendbuf[ peer_state.sendptr: peer_state.sendptr + send_len ] nsent = sock.send(''.join(send_data).encode()) if nsent < send_len: print("nsent < send_len") return sock_status_RW else: print(f"send {nsent} : {send_data}") peer_state.sendptr = 0 peer_state.sendbuf_end = 0 if peer_state.process_state == ProcessingState.INITIAL_ACK: peer_state.process_state = ProcessingState.WAIT_FOR_MSG return sock_status_R def do_register(peer_status, fd, epoll): if peer_status == sock_status_RW: try: epoll.register(fd, select.EPOLLIN | select.EPOLLOUT) except FileExistsError: epoll.modify(fd, select.EPOLLIN | select.EPOLLOUT) if peer_status == sock_status_R: try: epoll.register(fd, select.EPOLLIN) except FileExistsError: epoll.modify(fd, select.EPOLLIN) if peer_status == sock_status_W: try: epoll.register(fd, select.EPOLLOUT) except FileExistsError: epoll.modify(fd, select.EPOLLOUT) if peer_status == sock_status_NORW: try: epoll.unregister(fd) except FileNotFoundError: pass def run_server(socket_options, address): """Run a simple TCP server using epoll.""" with socketcontext(*socket_options) as server, \ epollcontext(server.fileno(), select.EPOLLIN) as epoll: server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.bind(address) server.listen(5) server.setblocking(0) server.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) print("Listening") connections = {} server_fd = server.fileno() while True: events = epoll.poll(1) for fileno, event in events: if fileno == server_fd: connection, client_address = server.accept() connection.setblocking(0) peer_status = on_peer_connected(connection, client_address) fd = connection.fileno() connections[fd] = connection # save fd sock relate do_register(peer_status, fd, epoll) elif event & select.EPOLLIN: peer_status = on_peer_ready_recv(fileno, connections) do_register(peer_status, fileno, epoll) elif event & select.EPOLLOUT: peer_status = on_peer_ready_send(fileno, connections) do_register(peer_status, fileno, epoll) else: print("event ", event) if __name__ == '__main__': try: run_server([socket.AF_INET, socket.SOCK_STREAM], ("0.0.0.0", 9090)) except KeyboardInterrupt as e: print("Shutdown")
UTF-8
Python
false
false
6,978
py
12
epoll_server.py
11
0.597592
0.591574
0
230
29.343478
79
mark-barrett/Ticketr-2
19,284,403,161,813
e68f0d0d53870b82bf03cd0155248a35d20e63d6
d98d650fe46caa922e9cf60cbecfc6a9f7e5b40d
/account/views.py
87b9f6cded93a5626e35a4c4d3ad2c588297f65a
[ "MIT" ]
permissive
https://github.com/mark-barrett/Ticketr-2
ca6cee6bfe9c94c78a30b8a6989fff8f0bbeb913
723bb2542bee818132b4c2315efe07c5ac3146c6
refs/heads/master
2021-09-07T20:02:43.370478
2018-02-28T09:00:28
2018-02-28T09:00:28
117,800,313
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django.shortcuts import render, redirect from django.contrib import messages # Create your views here. from django.views import View class SignIn(View): def get(self, request): if not request.user.is_authenticated: return render(request, 'sign-in.html') else: return redirect('/') def post(self, request): # Get the post information email = request.POST['email'] password = request.POST['password'] # Authenticate the user with their email as the username user = authenticate(username=email, password=password) # Check if the user logged in okay if user is not None: login(request, user) return redirect('/') else: messages.error(request, 'The email or password is invalid.') return redirect('/account/sign-in') class SignUp(View): def get(self, request): if not request.user.is_authenticated(): return render(request, 'sign-up.html') else: return redirect('/') def post(self, request): first_name = request.POST['first_name'] last_name = request.POST['last_name'] email = request.POST['email'] password = request.POST['password'] # Try find the user to see if they exist try: db_user = User.objects.get(username=email) messages.error(request, 'A user with that email already exists.') return redirect('/account/sign-up') except: user, created = User.objects.get_or_create(username=email, email=email) if created: user.set_password(password) # This line will hash the password user.first_name = first_name user.last_name = last_name user.save() # DO NOT FORGET THIS LINE # Check if the user logged in okay if user is not None: login(request, user) messages.success(request, 'Your account has been setup.') return redirect('/') else: messages.error(request, 'There was an error signing up') return redirect('/account/sign-up') class SignOut(View): def get(self, request): if request.user.is_authenticated: logout(request) messages.success(request, "Logged out. Thanks for stopping by!") return redirect('/') class ForgotPassword(View): def get(self, request): pass def post(self, request): pass
UTF-8
Python
false
false
2,737
py
39
views.py
18
0.584216
0.584216
0
91
29.076923
83
KU2021-NLP17/odqa_baseline_code
4,861,903,024,649
24ae8e9f9dd5abf87d337998f0446c8cdf9047d7
277f60ec8afec6cb874906d1540e6cab1ec450b1
/retrieval/dense/dp_base.py
1e9053436a8e3927423bd18ab235d2deadcb2f6d
[ "Apache-2.0" ]
permissive
https://github.com/KU2021-NLP17/odqa_baseline_code
519a596e881b6f6af52709b147b96a8ec7bd6226
fd14652ebce050cd43dbcd58c6625caaeed0d5bd
refs/heads/main
2023-09-02T17:19:03.011957
2021-11-23T15:15:13
2021-11-23T15:15:13
428,232,707
2
1
Apache-2.0
true
2021-11-15T11:16:40
2021-11-15T11:16:40
2021-11-13T14:17:36
2021-06-19T13:35:31
7,246
0
0
0
null
false
false
from tqdm.auto import tqdm, trange import pickle import random import time import os.path as p from itertools import chain import torch import numpy as np import torch.nn.functional as F from datasets import load_from_disk, load_dataset from transformers import TrainingArguments from transformers import AdamW, get_linear_schedule_with_warmup from torch.utils.data import TensorDataset, DataLoader, RandomSampler from retrieval.dense import DenseRetrieval def get_retriever_dataset(args): if args.retriever.dense_train_dataset not in [ "train_dataset", "squad_kor_v1", "bm25_document_questions", "bm25_question_documents", ]: raise FileNotFoundError(f"{args.retriever.dense_train_dataset}은 DenseRetrieval 데이터셋이 아닙니다.") if args.retriever.dense_train_dataset == "squad_kor_v1": train_dataset = load_dataset(args.retriever.dense_train_dataset) else: dataset_path = p.join(args.path.train_data_dir, args.retriever.dense_train_dataset) assert p.exists(dataset_path), f"{args.retriever.dense_train_dataset}이 경로에 존재하지 않습니다." train_dataset = load_from_disk(dataset_path) return train_dataset def epoch_time(start_time, end_time): elapsed_time = end_time - start_time elapsed_mins = int(elapsed_time / 60) elapsed_secs = int(elapsed_time - (elapsed_mins * 60)) return elapsed_mins, elapsed_secs class DpRetrieval(DenseRetrieval): def __init__(self, args): super().__init__(args) # wiki context load self.mappings = [] self.window_size = 20 self.sample_per_phrase = 4 save_dir = p.join(args.path.embed, self.name) self.mappings_path = p.join(save_dir, "mappings.bin") def get_embedding(self): if p.isfile(self.embed_path) and p.isfile(self.encoder_path) and not self.args.retriever.retrain: with open(self.embed_path, "rb") as f: self.p_embedding = pickle.load(f) with open(self.mappings_path, "rb") as f: self.mappings = pickle.load(f) self.encoder = self._get_encoder() self.encoder.load_state_dict(torch.load(self.encoder_path)) else: self.p_embedding, self.encoder, self.mappings = self._exec_embedding() with open(self.embed_path, "wb") as f: pickle.dump(self.p_embedding, f) with open(self.mappings_path, "wb") as f: pickle.dump(self.mappings, f) torch.save(self.encoder.state_dict(), self.encoder_path) def get_relevant_doc_bulk(self, queries, topk=1): self.encoder.eval() # question encoder self.encoder.cuda() with torch.no_grad(): q_seqs_val = self.tokenizer( queries, padding="longest", truncation=True, max_length=512, return_tensors="pt" ).to("cuda") q_embedding = self.encoder(**q_seqs_val) q_embedding.squeeze_() # in-place q_embedding = q_embedding.cpu().detach().numpy() # p_embedding: numpy, q_embedding: numpy result = np.matmul(q_embedding, self.p_embedding.T) phrase_indices = np.argsort(result, axis=1)[:, -topk:][:, ::-1] doc_indices = [[self.mappings[phrase_indices[i][j]] for j in range(len(phrase_indices[i]))] for i in range(len(phrase_indices))] doc_scores = [] for i in range(len(phrase_indices)): doc_scores.append(result[i][[phrase_indices[i].tolist()]]) return doc_scores, doc_indices def _exec_embedding(self): p_encoder, q_encoder = self._load_model() train_dataset, eval_dataset = self._load_dataset(eval=True) args = TrainingArguments( output_dir="densephrase_retrieval", evaluation_strategy="epoch", learning_rate=self.args.retriever.learning_rate, per_device_train_batch_size=self.args.retriever.per_device_train_batch_size, per_device_eval_batch_size=self.args.retriever.per_device_eval_batch_size, num_train_epochs=self.args.retriever.num_train_epochs, weight_decay=self.args.retriever.weight_decay, gradient_accumulation_steps=self.args.retriever.gradient_accumulation_steps, ) p_encoder, q_encoder = self._train(args, train_dataset, p_encoder, q_encoder, eval_dataset) p_embedding = [] mappings = [] for idx, passage in enumerate(tqdm(self.contexts)): # wiki splitted = passage.split() for i in range(len(splitted) // self.window_size * 2): phrase = ' '.join(splitted[i*(self.window_size // 2):(i+2)*(self.window_size //2)]) phrase = self.tokenizer( phrase, padding="max_length", truncation=True, max_length=self.window_size, return_tensors="pt" ).to("cuda") p_emb = p_encoder(**phrase).to("cpu").detach().numpy() p_embedding.append(p_emb) mappings.append(idx) p_embedding = np.array(p_embedding).squeeze() # numpy return p_embedding, q_encoder, mappings class DPTrainMixin: def _load_dataset(self, eval=False): datasets = get_retriever_dataset(self.args) train_dataset = datasets["train"] # TODO delete # train_dataset = train_dataset.select(range(100)) # with negative examples questions = [] phrases = [] labels = [] for idx, question in enumerate(tqdm(train_dataset["question"])): answer_passage = train_dataset["context"][idx] splitted = answer_passage.split() for phrase_idx in range(len(splitted) // self.window_size * 2): phrase = ' '.join(splitted[phrase_idx*(self.window_size // 2):(phrase_idx+2)*(self.window_size //2)]) # NOTE: Overlap? while True: incorrect_passage = random.choice(train_dataset["context"]) incorrect_passage_splitted = incorrect_passage.split() if len(incorrect_passage_splitted) // self.window_size >= self.sample_per_phrase: break incorrect_phrase_indices = random.sample(range(0, len(incorrect_passage_splitted) // self.window_size), self.sample_per_phrase - 1) incorrect_phrases = [' '.join(incorrect_passage_splitted[i*(self.window_size // 2):(i+2)*(self.window_size //2)]) for i in incorrect_phrase_indices] incorrect_phrases.insert(phrase_idx % self.sample_per_phrase, phrase) questions.append(question) phrases.append(incorrect_phrases) labels.append(phrase_idx % self.sample_per_phrase) print('Dataset prepare success') print(f'Length : {len(questions)}') q_seqs = self.tokenizer( questions, padding="longest", truncation=True, max_length=512, return_tensors="pt" ) p_seqs = self.tokenizer( list(chain(*phrases)), padding="max_length", truncation=True, max_length=self.window_size, return_tensors="pt" ) embedding_size = p_seqs["input_ids"].shape[-1] for k in p_seqs.keys(): p_seqs[k] = p_seqs[k].reshape(-1, self.sample_per_phrase, embedding_size) train_dataset = TensorDataset( p_seqs["input_ids"], p_seqs["attention_mask"], p_seqs["token_type_ids"], q_seqs["input_ids"], q_seqs["attention_mask"], q_seqs["token_type_ids"], torch.tensor(labels) ) eval_dataset = None return train_dataset, eval_dataset def _train(self, training_args, train_dataset, p_model, q_model, eval_dataset): print("TRAINING IN DensePhrase TRAIN MIXIN") train_sampler = RandomSampler(train_dataset) train_dataloader = DataLoader( train_dataset, sampler=train_sampler, batch_size=training_args.per_device_train_batch_size, drop_last=True ) if eval_dataset: eval_sampler = RandomSampler(eval_dataset) eval_dataloader = DataLoader( eval_dataset, sampler=eval_sampler, batch_size=training_args.per_device_eval_batch_size ) optimizer_grouped_parameters = [{"params": p_model.parameters()}, {"params": q_model.parameters()}] optimizer = AdamW(optimizer_grouped_parameters, lr=training_args.learning_rate, eps=training_args.adam_epsilon) t_total = len(train_dataloader) // training_args.gradient_accumulation_steps * training_args.num_train_epochs scheduler = get_linear_schedule_with_warmup( optimizer, num_warmup_steps=training_args.warmup_steps, num_training_steps=t_total ) global_step = 0 p_model.train() q_model.train() p_model.zero_grad() q_model.zero_grad() torch.cuda.empty_cache() for epoch in range(training_args.num_train_epochs): train_loss = 0.0 start_time = time.time() for step, batch in enumerate(train_dataloader): if torch.cuda.is_available(): batch = tuple(t.cuda() for t in batch) embedding_size = batch[0].shape[-1] p_inputs = { "input_ids": batch[0].reshape(-1, embedding_size), "attention_mask": batch[1].reshape(-1, embedding_size), "token_type_ids": batch[2].reshape(-1, embedding_size) } q_inputs = { "input_ids": batch[3], "attention_mask": batch[4], "token_type_ids": batch[5] } adder = torch.arange(0, training_args.per_device_train_batch_size).long() * self.sample_per_phrase if torch.cuda.is_available(): adder = adder.to("cuda") label = torch.repeat_interleave(batch[6] + adder, self.sample_per_phrase) p_outputs = p_model(**p_inputs) q_outputs = q_model(**q_inputs) q_outputs = torch.repeat_interleave(q_outputs, self.sample_per_phrase, dim=0) sim_scores = torch.matmul(q_outputs, torch.transpose(p_outputs, 0, 1)) sim_scores = F.log_softmax(sim_scores, dim=1) loss = F.nll_loss(sim_scores, label) loss = loss / training_args.gradient_accumulation_steps # print(p_inputs["input_ids"].shape) # print(q_inputs["input_ids"].shape) # print(p_outputs.shape) # print(q_outputs.shape) # print(label.shape) # print(label) print(f"epoch: {epoch + 1:02} step: {step:02} loss: {loss}", end="\r") train_loss += loss.item() loss.backward() if ((step + 1) % training_args.gradient_accumulation_steps) == 0: optimizer.step() scheduler.step() p_model.zero_grad() q_model.zero_grad() global_step += 1 torch.cuda.empty_cache() end_time = time.time() epoch_mins, epoch_secs = epoch_time(start_time, end_time) print(f"Epoch: {epoch + 1:02} | Time: {epoch_mins}m {epoch_secs}s") print(f"\tTrain Loss: {train_loss / len(train_dataloader):.4f}") p_model.train() q_model.train() return p_model, q_model
UTF-8
Python
false
false
11,797
py
66
dp_base.py
50
0.57832
0.572194
0
295
38.844068
164
thipaulino/tpTools
17,497,696,779,952
e695402a0988274dfbbb086c9519896fc8c2fb9e
6956291893c1deef10b10e645d18dcacc2819969
/tpRig/tpRigBuilder/tpBuildable.py
50028398a8efa4a2d80103f2c090d10f1c922d14
[]
no_license
https://github.com/thipaulino/tpTools
19c8bcbd98b1e4d6fc6f015a6f73bd890cedac36
dbf799eb65b0da0db612b97c9b2bedf0e79bb537
refs/heads/master
2023-02-20T04:11:49.767739
2023-02-06T10:08:28
2023-02-06T10:08:28
249,549,932
9
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class Buildable(object): def __init__(self): self.build_methods_list = [] self.top_level_item = 'FaceRig' self.register_build_method('Pre-Build Utils', 'root', background_color='dark_magenta') self.register_build_method(self.top_level_item, 'root', background_color='dark_cyan') self.register_build_method('Post Build Utils', 'root', background_color='dark_green') # when item no parent and no method is added in register, code is breaking - improve def register_build_method(self, action_name, parent_action, method=None, after=None, background_color=None): """ Data Structure [{'method_name': method_name, 'parent': parent_action_name, 'method': self.method, 'after': method_name to be placed after}, {...}] :param action_name: :param parent_action: :param method: :param after: :param background_color: :return: """ method_data = { 'method_name': action_name, 'parent': parent_action, 'method': method, 'after': after, 'background_color': background_color, 'stop_flag': False} self.build_methods_list.append(method_data)
UTF-8
Python
false
false
1,440
py
31
tpBuildable.py
30
0.521528
0.521528
0
43
32.418605
94
arthuroe/ibu_backend
1,614,907,726,356
c1d5169aea0d1f9e6b7312630611ba231d1b597b
0d0286770c13134252e04fb9dc163855f0eb6d46
/api/patient/views.py
49feace29f001a87ca4ec066d4fb233e334fd67d
[]
no_license
https://github.com/arthuroe/ibu_backend
ac21834fe9e16dbf9e4e8a7746bdcb96fb4488d1
b08619f532649d875b117d021f601d6e511f58db
refs/heads/develop
2022-04-20T13:38:56.286907
2020-04-03T06:30:23
2020-04-03T06:30:23
251,427,051
0
0
null
false
2020-04-03T05:28:48
2020-03-30T20:59:29
2020-04-02T14:21:26
2020-04-03T05:28:47
23
0
0
2
Python
false
false
import logging from flask import Blueprint, request, make_response, jsonify from flask.views import MethodView from api.decorators import token_required from api.models import Patient class PatientView(MethodView): """ View to manage patients """ decorators = [token_required] def get(self, current_user, patient_id=None): try: if patient_id: patient = Patient.find_first(id=patient_id) if not patient: response = { 'status': 'fail', 'message': 'Patient does not exist' } return make_response(jsonify(response)), 400 response = { 'status': 'success', 'patient': patient.serialize() } return make_response(jsonify(response)), 200 patients = Patient.fetch_all() if not patients: response = { 'status': 'success', 'message': 'No patients have been added' } return make_response(jsonify(response)), 200 response = { 'status': 'success', 'patients': [patient.serialize() for patient in patients] } return make_response(jsonify(response)), 200 except Exception as e: logging.error(f"An error has occurred {e}") response = { 'status': 'fail', 'message': 'Failed to retrieve patients.' } return make_response(jsonify(response)), 500 def post(self, current_user): kwargs = request.json phone_number = kwargs.get('phone_number') if not phone_number: response = { 'status': 'fail', 'message': 'Phone number is required.' } return make_response(jsonify(response)), 400 patient = Patient.find_first(phone_number=kwargs.get('phone_number')) kp_code = ( kwargs.get('first_name')[0] + kwargs.get('second_name')[0] + kwargs.get('third_name')[0] + str( int(kwargs.get('date_of_birth')[5:7])) + str(int(kwargs.get('date_of_birth')[0:4])) + kwargs.get('gender')[0] ) kwargs.update({"kp_code": kp_code}) if not patient: try: patient = Patient(**kwargs) patient.save() response = { 'status': 'success', 'message': f"Successfully Added {kwargs.get('first_name')}." } return make_response(jsonify(response)), 201 except Exception as e: logging.error(f"An error has occurred {e}") response = { 'status': 'fail', 'message': 'Failed to add patient. Please try again.' } return make_response(jsonify(response)), 401 else: response = { 'status': 'fail', 'message': 'Patient already exists.', } return make_response(jsonify(response)), 409 def put(self, current_user, patient_id): kwargs = request.json kwargs.update({"id": patient_id}) try: patient = Patient.find_first(id=patient_id) if patient: patient.update(**kwargs) response = { 'status': 'success', 'message': f'Successfully updated {patient.first_name}.' } return make_response(jsonify(response)), 201 response = { 'status': 'fail', 'message': 'Patient does not exist.', } return make_response(jsonify(response)), 400 except Exception as e: logging.error(f"An error has occurred {e}") response = { 'status': 'fail', 'message': 'Update failed. Please try again.' } return make_response(jsonify(response)), 500 def delete(self, current_user, patient_id): try: patient = Patient.find_first(id=patient_id) if patient: patient.delete() response = { 'status': 'success', 'message': f'Successfully deleted {patient.first_name}.' } return make_response(jsonify(response)), 200 response = { 'status': 'fail', 'message': 'Patient does not exist.', } return make_response(jsonify(response)), 400 except Exception as e: logging.error(f"An error has occurred {e}") response = { 'status': 'fail', 'message': 'Delete failed. Please try again.' } return make_response(jsonify(response)), 500
UTF-8
Python
false
false
5,087
py
29
views.py
26
0.482406
0.471987
0
151
32.688742
80
openstack/python-troveclient
9,586,367,007,452
a472545a39390304fa4cb92be3e2c92ecb349da8
e1e8c24070460e5edc07f168663d9783fc18a8b1
/troveclient/tests/test_root.py
58d0e67b8ec8a9908464d8f58ee98ae16d996213
[ "Apache-2.0" ]
permissive
https://github.com/openstack/python-troveclient
5bfafda27ccb4b788118b2fe4e92ed862f02cd93
0415e4bc884b4acb341960f35678c6b93f262518
refs/heads/master
2023-09-04T13:04:02.033407
2022-05-11T10:03:17
2023-06-26T10:03:58
10,698,584
47
35
Apache-2.0
false
2021-04-30T06:12:22
2013-06-14T21:58:05
2021-04-29T02:44:53
2021-04-29T07:38:00
2,052
70
49
0
Python
false
false
# Copyright 2015 Tesora Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import testtools from unittest import mock from troveclient.v1 import root """ Unit tests for root.py """ class RootTest(testtools.TestCase): def setUp(self): super(RootTest, self).setUp() self.orig__init = root.Root.__init__ root.Root.__init__ = mock.Mock(return_value=None) self.root = root.Root() self.root.api = mock.Mock() self.root.api.client = mock.Mock() def tearDown(self): super(RootTest, self).tearDown() root.Root.__init__ = self.orig__init def _get_mock_method(self): self._resp = mock.Mock() self._body = None self._url = None def side_effect_func(url, body=None): self._body = body self._url = url return (self._resp, body) return mock.Mock(side_effect=side_effect_func) def test_delete(self): self.root.api.client.delete = self._get_mock_method() self._resp.status_code = 200 self.root.delete(1234) self.assertEqual('/instances/1234/root', self._url) self._resp.status_code = 400 self.assertRaises(Exception, self.root.delete, 1234)
UTF-8
Python
false
false
1,766
py
190
test_root.py
92
0.64043
0.625142
0
56
30.535714
78
someshwar123/python
15,315,853,403,521
2ec304ce33dd5a7ad255f5dc2517d621b01668ad
c9d8671400781bc2ec1cfe560cf49f17d436afcb
/set-9/lcm.py
180796c6cc15edbef517fca7b9e590744e081ea0
[]
no_license
https://github.com/someshwar123/python
7d6e9d5d4969742a999d0d7083415bef76a79346
55cbf4076ab48999c99fa8f3c595379e31d60150
refs/heads/master
2020-03-24T03:42:27.655146
2018-08-16T18:37:21
2018-08-16T18:37:21
142,429,758
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: Somesh # # Created: 14/08/2018 # Copyright: (c) Somesh 2018 # Licence: <your licence> #------------------------------------------------------------------------------- def lcm (a,b): if(a>b): greater=a else: greater=b while(True): if((greater%a==0) and(greater%b==0)): lcm =greater break greater =greater+1 return lcm a=int(input("enter the a value")) b=int(input("enter the b value")) z=lcm(48,60) print ("The lcm is : ",z)
UTF-8
Python
false
false
638
py
77
lcm.py
77
0.398119
0.366771
0
27
22.666667
80
BlaiseGratton/DataAnalysisNgin
13,125,420,056,641
84547c95f2e58b05b074ee8640c02aa47365b071
39f9d416f11e9136ed404c25a876d6a83727c7c9
/anatolution/models/project_marker_option/__init__.py
a29d5a31a5b661536b7d9bce61ff0121e9b1e8e1
[ "MIT" ]
permissive
https://github.com/BlaiseGratton/DataAnalysisNgin
478dc24e50fd4915fdfe7661102e483a26c477e2
24d72320735faf6183d44ae728dd8557014abf8d
refs/heads/master
2016-09-23T10:53:24.412773
2016-09-10T18:37:16
2016-09-10T18:37:16
42,779,692
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
""" anatolution.project_marker_option ~~~~~~~~~~~~~~~~~~ """ from ...core import Service from .project_marker_option import ProjectMarkerOption class ProjectMarkerOptionService(Service): __model__ = ProjectMarkerOption
UTF-8
Python
false
false
233
py
122
__init__.py
88
0.690987
0.690987
0
10
22.3
54
McDermott-Group/Analysis
14,671,608,324,567
04d6711d1eac2d44023a87ee12e98c67aac581ef
93ef9d1738328036320d3dbff018b04f05a75b36
/projects/fluxNoise/python/analyze_P1_dwell_time.py
8df386a482ca8a19bd0b161e7d1e12ca1261ff7e
[]
no_license
https://github.com/McDermott-Group/Analysis
a1fcf314c0182dbd0261fb148843a998e183b966
1426997aa7e5a156deedca9e0f3381e1c7d0a7cc
refs/heads/master
2023-06-21T15:59:32.519975
2023-06-19T19:16:50
2023-06-19T19:16:50
37,875,133
0
3
null
null
null
null
null
null
null
null
null
null
null
null
null
import os import numpy as np import noiselib import importlib importlib.reload(noiselib) from noiselib import matpaths from dataChest import * import general.calibration as cal import matplotlib.pyplot as plt from scipy.optimize import curve_fit import datasets importlib.reload(datasets) from datasets import * # q, date, filesP1, filesT1, thresh = 'Q3', '04-29-20', range(112,493), range(0,381), 0.33 # really bad # q, date, filesP1, filesT1, thresh = 'Q3', '04-29-20', range(0,63), range(0,63), 0.25 # shows nothing # q, date, filesP1, filesT1, thresh = 'Q4', '04-30-20', range(0,231), range(0,231), 0.44 ################################# # ds = q4_0430_T1 # ds = q3_0501_T1 # ds = q1_0503_T1 ds = q2_0505_T1 fP1_I = matpaths(fileName='P1_I', fileNums='files_P1', **ds) fP1_X = matpaths(fileName='P1_X', fileNums='files_P1', **ds) dwellsDirty = np.array([]) dwellsClean = np.array([]) dwellsDirty1 = np.array([]) dwellsDirty2 = np.array([]) dwellsDirty3 = np.array([]) if 'recalibrate' in ds and ds['recalibrate']: data = noiselib.loadmat( fP1_I[0] ) iq0 = np.array((data['Is'],data['Qs'])) data = noiselib.loadmat( fP1_X[0] ) iq1 = np.array((data['Is'],data['Qs'])) c = cal.CalibratedStates( (0,iq0), (1,iq1), plot=False) for i,f in enumerate(fP1_I): try: data = noiselib.loadmat( f ) except: print('corrupted file:', f) data = {'Single_Shot_Occupations': [np.nan], 'Single_Shot_Occupation': [np.nan]} if 'recalibrate' in ds and ds['recalibrate']: states, SSO, _ = c.get_single_shot_occupation( np.array((data['Is'], data['Qs'])) ) else: states = data['Single_Shot_Occupations'] SSO = {1: data['Single_Shot_Occupation']} d0,d1 = noiselib.bin_dwell_times(states) if SSO[1] > ds['thresh_P1']: dwellsDirty = np.append(dwellsDirty, d0) if i in range(30,40): dwellsDirty1 = np.append(dwellsDirty, d0) elif i in range(80,88): dwellsDirty2 = np.append(dwellsDirty, d0) elif i in range(311,319): dwellsDirty3 = np.append(dwellsDirty, d0) else: dwellsClean = np.append(dwellsClean, d0) fig, ax = plt.subplots() ax.hist(dwellsDirty1, bins, color='red') ax.hist(dwellsDirty2, bins, color='blue', alpha=0.6) ax.hist(dwellsDirty3, bins, color='green', alpha=0.6) ax.set_xlabel('Dwell Time in 0 State Before Excitation [Reps=500us]') ax.set_ylabel('Counts') ax.set_yscale('log') fig.suptitle(ds['Q']+'\n'+str(ds['date'])) plt.draw() plt.pause(0.05) fig, ax = plt.subplots() hD, bins, _ = ax.hist(dwellsDirty,30, color='red') hC, bins, _ = ax.hist(dwellsClean, bins, color='blue', alpha=0.6) ax.set_xlabel('Dwell Time in 0 State Before Excitation [Reps=500us]') ax.set_ylabel('Counts') ax.set_yscale('log') fig.suptitle(ds['Q']+'\n'+str(ds['date'])) plt.draw() plt.pause(0.05) def exponential(t, a, tau): return a*np.exp(-t/tau) def poisoned_exponential(t, b, a, tau_r, n_qp, tau_qp): return b + a*np.exp(-t/tau_r)*np.exp(n_qp*(np.exp(-t/tau_qp)-1)) def poisoned_exponential_simul(t, a0, a1, tau_r, n_qp0, n_qp1, tau_qp0, tau_qp1): return np.ravel([poisoned_exponential(t, 0, a0, tau_r, n_qp0, tau_qp0), poisoned_exponential(t, 0, a1, tau_r, n_qp1, tau_qp1)]) t = (bins[1:]+bins[:-1])/2 poptD, pcovD = curve_fit(exponential, t[t.size/2:], hD[t.size/2:], p0=[hD.max()/2, .3]) poptC, pcovC = curve_fit(exponential, t[t.size/2:], hC[t.size/2:], p0=[hC.max()/2, .3]) ax.plot(t, exponential(t, *poptD), 'k:') ax.plot(t, exponential(t, *poptC), 'k:') ax.set_ylim([0.5, None]) plt.draw() plt.pause(0.05) popt, pcov = curve_fit(poisoned_exponential_simul, t, np.ravel([hD,hC]), p0=[poptD[0],poptC[0],poptC[1],1.,0.,.5,.5], bounds=(0,np.inf)) # bounds=([0,0,0,0,0,0,0],[np.inf,np.inf,np.inf,3,3,np.inf,np.inf])) fits = poisoned_exponential_simul(t, *popt).reshape((2,t.size)) ax.plot(t, np.transpose(fits), 'k', linewidth=2) plt.draw() plt.pause(0.05) text = '{:>7}{:>12}{:>12}\n'.format('','Dirty','Clean') # text += '{:>7}{:>12.3f}{:>12.3f}\n'.format('A',*popt[0:2]) text += '{:>7}{:>12.3f}{:>12}\n'.format('tau_R',popt[2]*500,'') text += '{:>7}{:>12.3f}{:>12.3f}\n'.format('n_QP',*popt[3:5]) text += '{:>7}{:>12.3f}{:>12.3f}\n'.format('tau_QP',popt[5]*500,popt[6]*500) text += '{:>7}{:>12.3f}{:>12.3f}\n'.format('tau',poptD[1]*500,poptC[1]*500) ax.text(t[-1],fits.max()/10, text, family='monospace', horizontalalignment='right') plt.draw() plt.pause(0.05)
UTF-8
Python
false
false
4,646
py
569
analyze_P1_dwell_time.py
322
0.596427
0.535945
0
128
35.304688
103
tell-k/code-snippets
14,791,867,401,119
021aaa1d1c307044c731ba73349b20976b105b96
4b0de0c936d8c2300de61c42a5ba7a549ed60ae1
/python/snippets/convert_nfc.py
243932bbb97cb907babb5e4083204c6a75d8104f
[]
no_license
https://github.com/tell-k/code-snippets
54adf5e1967af25c362e72af391fffc83dc9c291
ab85aa3e4e8f74aa3cb394aee427efd29ec623ec
refs/heads/master
2021-06-06T13:47:42.978609
2017-04-05T14:27:34
2017-04-05T14:27:34
365,239
0
2
null
false
2020-10-02T11:37:46
2009-11-08T13:40:22
2015-01-22T11:03:56
2017-04-05T14:32:45
108,440
0
2
1
ActionScript
false
false
from unicodedata import normalize import sys, codecs sys.stdout = codecs.getwriter("utf-8")(sys.stdout) with open('./templates/core/index.html') as f: hoge = f.readlines() hoge_body = "".join(hoge) hoge_nfc = normalize('NFC', hoge_body.decode('utf8')) print hoge_nfc
UTF-8
Python
false
false
287
py
300
convert_nfc.py
192
0.675958
0.66899
0
11
25
57
sintetizzatore/dsp
9,139,690,425,963
db8e45ba72d604700d1214c49e27de5c51f7088e
632b349062e6f4611a276d74dee3fe3a0d461d3b
/python/advanced_python_csv.py
cde9a5535a02757f564df16ee850b30b5ed82d67
[]
no_license
https://github.com/sintetizzatore/dsp
910be4ad20ffab08b2fea09d1b7a24d9b1923502
436ea8170426a3518cdc839441315d910667dc56
refs/heads/master
2020-04-07T12:44:37.545561
2015-09-24T23:26:32
2015-09-24T23:26:32
40,987,242
0
0
null
true
2015-08-18T17:35:08
2015-08-18T17:35:08
2015-08-13T14:48:23
2015-08-17T21:07:05
1,437
0
0
0
null
null
null
import csv with open('faculty.csv', 'r') as book1: with open('emails.csv', 'r') as book2: reader1 = csv.reader(book1, delimiter=',') reader2 = csv.reader(book2, delimiter=',') both = [] fields = reader1.next() reader2.next() for row1, row2 in zip(reader1, reader2): row2.append(row1[-1]) both.append(row2) with open('emails2.csv', 'w') as output: writer = csv.writer(output, delimiter=',') writer.writerow(fields) writer.writerows(both)
UTF-8
Python
false
false
560
py
9
advanced_python_csv.py
4
0.548214
0.517857
0
18
30.111111
54
BrutuZ/Flexget
9,655,086,493,598
34bf2c8e2c26570e5c9ed89d8613030292ebe82f
b18c069efe396a05b9e3156e527fd5a3bdb081b2
/flexget/components/sites/sites/eztv.py
20cd31bcf96d575d5b7d3dd2f47c66a5721ccac5
[ "MIT" ]
permissive
https://github.com/BrutuZ/Flexget
032692abeff3f6e5687dee2e7ba3d00a316400d4
2b7e8314d103c94cf4552bd0152699eeca0ad159
refs/heads/master
2023-08-30T22:31:16.746674
2023-08-28T15:14:04
2023-08-28T15:14:04
143,061,489
1
0
MIT
true
2022-11-06T17:25:03
2018-07-31T20:03:45
2022-03-19T22:29:58
2022-11-06T17:22:09
127,261
0
0
1
Python
false
false
import re from urllib.parse import urlparse, urlunparse from loguru import logger from requests import RequestException from flexget import plugin from flexget.components.sites.urlrewriting import UrlRewritingError from flexget.event import event from flexget.utils.soup import get_soup logger = logger.bind(name='eztv') EZTV_MIRRORS = [('http', 'eztv.ch'), ('https', 'eztv-proxy.net'), ('http', 'eztv.come.in')] class UrlRewriteEztv: """Eztv url rewriter.""" def url_rewritable(self, task, entry): return urlparse(entry['url']).netloc == 'eztv.ch' def url_rewrite(self, task, entry): url = entry['url'] page = None for scheme, netloc in EZTV_MIRRORS: try: _, _, path, params, query, fragment = urlparse(url) url = urlunparse((scheme, netloc, path, params, query, fragment)) page = task.requests.get(url).content except RequestException: logger.debug('Eztv mirror `{}` seems to be down', url) continue break if not page: raise UrlRewritingError('No mirrors found for url %s' % entry['url']) logger.debug('Eztv mirror `{}` chosen', url) try: soup = get_soup(page) mirrors = soup.find_all('a', attrs={'class': re.compile(r'download_\d')}) except Exception as e: raise UrlRewritingError(e) logger.debug('{} torrent mirrors found', len(mirrors)) if not mirrors: raise UrlRewritingError('Unable to locate download link from url %s' % url) entry['urls'] = [m.get('href') for m in mirrors] entry['url'] = mirrors[0].get('href') @event('plugin.register') def register_plugin(): plugin.register(UrlRewriteEztv, 'eztv', interfaces=['urlrewriter'], api_ver=2)
UTF-8
Python
false
false
1,852
py
854
eztv.py
737
0.613391
0.612311
0
57
31.491228
91
jongfranco/python-workshop-2
18,047,452,602,657
3b376c2319a691ae7e89e5408050c6ae552da1fb
f16545184a8fd369ef2f9ee9ebae8b1a3271cb9a
/day-1/if-else.py
c5034094cb529004ae54135f080b8d0dceea8b99
[]
no_license
https://github.com/jongfranco/python-workshop-2
81e86708d0e24428b8aebebe17063b05dfa5ebba
417e2f07e40e5ca5a66acaa919dcd84c922d1c14
refs/heads/master
2022-11-16T17:26:52.490254
2020-07-15T18:39:15
2020-07-15T18:39:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Structure of if else if predicate: code code code elif predicate2: (not cumpolsory) code code elif predicate3: (not cumpolsory) code code elif predicate4: (not cumpolsory) code code else: (not compulsory) code code elif --> else if """ # if 1 > 2: # print('i am in if block') # else: # print('i am in else block') # # print('i am outside if else') number = int(input()) if number < 5: print('less than 5') elif 5 <= number < 10: print('greater than equal to 5 and less than 10') elif 10 <= number < 20: print('very large number') else: print('OMG!!!!') print('outside if else block')
UTF-8
Python
false
false
662
py
31
if-else.py
31
0.60574
0.58006
0
42
14.761905
53
willist/dailyprogrammer
14,207,751,820,130
178f9958fa5510dc749e389ec143cf70e0643c32
733c57c8952a58b2a3fcaa818e56833bc0f34d8a
/049_hard.py
35ebd749eb605a8f8cfbdd022580c26904dbf786
[]
no_license
https://github.com/willist/dailyprogrammer
7ad308ad2f7801f80906973eb4ba53a31754bcc8
70592cd27847fae87b9e35927ad4a48173ff4514
refs/heads/master
2020-04-01T08:12:57.865946
2012-05-08T14:54:34
2012-05-08T14:55:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys from collections import defaultdict from contextlib import contextmanager from itertools import product from math import factorial def dice_iter(n): for item in range(n): yield range(1,7) def count_sums(iterator): counter = defaultdict(int) for item in iterator: if sum(item) == 5: print item counter[sum(item)] += 1 return counter def dice_sums(n): return count_sums(product(*dice_iter(n))) @contextmanager def no_recursion_limit(): limit = sys.getrecursionlimit() sys.setrecursionlimit(100000) yield sys.setrecursionlimit(limit) def combos(num_dice, target_sum, prev_die=None): if num_dice == 1 and prev_die <= target_sum <= 6: yield [target_sum] else: start = 1 if prev_die is None else prev_die end = 7 for head in range(start, end): remaining_sum = target_sum - head remaining_dice = num_dice - 1 if remaining_dice <= remaining_sum <= (remaining_dice * 6): for tail in combos(remaining_dice, remaining_sum, head): yield [head] + tail def counter(iterator): counter = defaultdict(int) for item in iterator: counter[item] += 1 return counter def j(num_dice, sum_dice): total = 0 top = factorial(num_dice) with no_recursion_limit(): for index, combo in enumerate(combos(num_dice, sum_dice)): count = counter(combo) bottoms = [factorial(c) for c in count.values()] bottom = reduce(lambda x,y: x*y, bottoms) sub_total = top/bottom if not index % 100000: print combo, sub_total total += sub_total return total if __name__ == "__main__": assert j(02, 07) == 6 assert j(02, 10) == 3 assert j(02, 12) == 1 assert j(03, 10) == 27 assert j(05, 20) == 651 assert j(07, 30) == 12117 assert j(10, 50) == 85228 print j(20, 100) print j(1100, 5000) % pow(10,7)
UTF-8
Python
false
false
2,030
py
5
049_hard.py
5
0.586207
0.543842
0
72
27.194444
72
AMDevG/MarathonTrackerServer
11,141,145,168,863
c64bb83044613ffad6bcef87bbcccc5292107d16
c98c1b73a30b7f9f961d5f5ff2cfcdcdb3c4d63d
/marathonapp/models.py
2ef9f71ceed0d537f4e91f46c8007580e17096f0
[]
no_license
https://github.com/AMDevG/MarathonTrackerServer
eb64bff7f4d030aa960b7c4506479a49be2d1d41
5338c4069a520c1d43f7fa635acfde50b5006e16
refs/heads/master
2018-12-23T13:06:14.843724
2018-10-16T17:12:19
2018-10-16T17:12:19
152,489,476
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.db import models class RunTrain(models.Model): date = models.DateTimeField(auto_now_add=True) distance = models.CharField(max_length=255, null=True, blank=True, default=None) time = models.CharField(max_length=255, null=True, blank=True, default=None) minsPerMile = models.CharField(max_length=255, null=True, blank=True, default=None) def __str__(self): return '{}'.format(self.name) class CrossTrain(models.Model): date = models.DateTimeField(auto_now_add=True) exercise = models.CharField(max_length=255, null=True, blank=True, default=None) time = models.CharField(max_length=255, null=True, blank=True, default=None) def __str__(self): return '{}'.format(self.name) class LiftTrain(models.Model): date = models.DateTimeField(auto_now_add=True) exercise = models.CharField(max_length=255, null=True, blank=True, default=None) time = models.CharField(max_length=255, null=True, blank=True, default=None) def __str__(self): return '{}'.format(self.name)
UTF-8
Python
false
false
1,024
py
4
models.py
4
0.714844
0.694336
0
27
36.962963
84
JosephLevinthal/Research-projects
5,222,680,248,812
50a3c182c322aacadd9983dcdd98b52d00005d25
d554b1aa8b70fddf81da8988b4aaa43788fede88
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4444/codes/1716_2504.py
b0ca13315e36aba4d3bd53bdc18d78b27047d013
[]
no_license
https://github.com/JosephLevinthal/Research-projects
a3bc3ca3b09faad16f5cce5949a2279cf14742ba
60d5fd6eb864a5181f4321e7a992812f3c2139f9
refs/heads/master
2022-07-31T06:43:02.686109
2020-05-23T00:24:26
2020-05-23T00:24:26
266,199,309
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
v=int(input("quantidade de virus: ")) l=int(input("qtd leucocitos: ")) pv=float(input(" percentual de mut virus: ")) pl=float(input(" percentual de mut leococutos: ")) dias=0 i=0 while(l<=2*v): v=v+v*pv/100 l=l+l*pl/100 i=i+1 dias=dias+1 print(dias)
UTF-8
Python
false
false
256
py
13,190
1716_2504.py
13,160
0.660156
0.617188
0
13
18.615385
50
oliverroick/rosi
14,010,183,344,908
e6ef060d5416d5c18bb801bd1f7213dc6d47563c
143580af7e40e292ce5cf2e2c47ac3ed98721a57
/tests/util.py
a2c5db2b6b223d9f28df45ad8d9dddc42527d061
[ "MIT" ]
permissive
https://github.com/oliverroick/rosi
46e4cb68596fc79fddd8d27c1a7591fae1e7f1ab
27cf94ae3e73c199a7533fa28937e2b25a4f6106
refs/heads/master
2020-03-30T12:51:21.319148
2018-10-06T11:20:06
2018-10-06T11:20:06
151,244,450
1
0
MIT
false
2018-10-06T11:01:15
2018-10-02T11:36:13
2018-10-06T10:32:45
2018-10-06T11:01:14
10
0
0
1
Python
false
null
def depth(L): return isinstance(L, list) and max(map(depth, L))+1
UTF-8
Python
false
false
70
py
6
util.py
3
0.657143
0.642857
0
2
34
55
liana-80/flask-vue-example
9,268,539,451,841
1af80ec811fde0cee0b833f4aa587890acb95e9f
0524b31a1185272af5ab572800783c4d6362b8eb
/api_rest/privileges.py
27ef8dcca3ba2685ea174a55e336618954978e47
[ "MIT" ]
permissive
https://github.com/liana-80/flask-vue-example
f17bbd922aaccc8783d582f854569a6a4b8360a1
c0fc343312b2baf0f3009eb0c114c224d5f5deed
refs/heads/master
2022-09-25T12:39:55.975663
2020-06-04T15:03:10
2020-06-04T15:03:10
269,379,966
0
0
MIT
true
2020-06-04T15:03:11
2020-06-04T14:21:37
2020-06-04T14:34:59
2020-06-04T15:03:10
41
0
0
0
Python
false
false
# coding=utf-8 """ desc: 定义权限 author: congqing.li date: 2016-10-31 """ from permission.permission import ItemPermission, VIEWNEEDS, MANAGENEEDS # 权限管理模块的查看权限 admin_view = ItemPermission("admin", u"用户角色管理", VIEWNEEDS) # 权限管理模块的管理权限 admin_manage = ItemPermission("admin", u"用户角色管理", MANAGENEEDS) # 学生管理权限 student_manage = ItemPermission("student", u"学生管理", MANAGENEEDS)
UTF-8
Python
false
false
473
py
27
privileges.py
25
0.742706
0.718833
0
18
19.944444
72
au3641/HEPY_site
7,318,624,292,662
ef57ad4eec2c79f236ed46d4919f8a96f69a6601
b8b8e640ce4c5f7084a6594c71ea5c3e51afbb9d
/HEPY_django/HEPY_new/migrations/0005_auto_20170716_1903.py
8fc1eacddc7fdf114a448bb2621afb838641cebc
[]
no_license
https://github.com/au3641/HEPY_site
8c51a6a33a61fcac39ed11fea171e158315aae9c
04036d5ab5480c060488617048092911dfc69f25
refs/heads/master
2020-05-20T15:06:10.032928
2017-07-24T21:30:40
2017-07-24T21:30:40
84,488,450
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-16 17:03 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('HEPY_new', '0004_auto_20170712_0716'), ] operations = [ migrations.AddField( model_name='question', name='group', field=models.IntegerField(blank=True, null=True), ), migrations.AlterField( model_name='answerweight', name='type', field=models.CharField(choices=[('risk', 'risk'), ('hepatitis_a_b', 'hepatitis_a_b'), ('not_a_b', 'not_a_b'), ('order', 'order')], default='risk', max_length=16), ), ]
UTF-8
Python
false
false
743
py
60
0005_auto_20170716_1903.py
19
0.570659
0.523553
0
25
28.72
174
baehll/python-exercise
11,493,332,511,971
9857286b0d593ab6737b873e9b78ecd467c86daa
ba53cac18be782295fd54f1a9558094dbec4d11d
/chapter12/managerui.py
14532bd6f54628831a51a2e6c95a1c8f48a31490
[]
no_license
https://github.com/baehll/python-exercise
fff775d3f8ace636709fa948acc36a80dbae3b7a
8a1f2578e59fec5046e541ca40607dce8095e685
refs/heads/master
2020-03-13T16:13:17.082255
2018-05-15T14:11:28
2018-05-15T14:11:28
131,192,437
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
##################### # Aufgabe 1,12.4.3# # v1.0 # # baehll # # 02.05.2018 # ##################### import pickle from musical import * class Manager: __menuetext = """ Musical-Manager ------------------ (n)eue Vorstellung (U)eberblick Vorstellungen (S)torniere Vorstellung (E)nde """ def __init__(self, datei): self.__datei = datei self.__lade_musical() self.__run() def __run(self): print(self.__menuetext) wahl = "-" while wahl not in ["e", "E"]: wahl = input("Auswahl: ") if wahl in ["n", "N"]: self.__neueVorstellung() elif wahl in ["u", "U"]: print(self.__musical) elif wahl in ["s", "S"]: self.__storniere() print(self.__menuetext) print("Danke für die Benutzung vom Musical-Manager") self.__speichern() def __storniere(self): datum = input("Datum der Vorstellung: ") text = self.__musical.storniere(datum) print(text) def __neueVorstellung(self): datum = input("Termin: ") beginn = input("Beginn der Vorstellung: ") vorstellung = Vorstellung(datum, beginn, self.__musical.saal) self.__musical.neueVorstellung(vorstellung) def __neuesMusical(self): titel = input("Titel: ") eintrittspreis = float(input("Eintrittspreis: ")) anzahl_reihen = int(input("Anzahl Sitzreihen: ")) liste = [] for i in range(anzahl_reihen): sitze = int(input("Sitze in Reihe " + str(i + 1) + ": ")) liste.append(sitze) saal = Saal(liste) self.__musical = Musical(titel, eintrittspreis, saal) def __lade_musical(self): try: f = open(self.__datei, "rb") self.__musical = pickle.load(f) f.close() print("\n W I L L K O M M E N") print("beim Manangement-System für das Musical", self.__musical.titel) except: print("Kein Musical gespeichert") print("Richten Sie ein neues Musical ein.") self.__neuesMusical() def __speichern(self): f = open(self.__datei, "wb") pickle.dump(self.__musical, f) f.close() m = Manager("daten/hairspray.txt")
UTF-8
Python
false
false
2,385
py
45
managerui.py
43
0.504406
0.497692
0
80
28.8
82
mfigat/public_rshpn_tool
1,151,051,275,070
81371fa5fb576508aa13a6fb0a0e0e41a2b53828
cfd374b34a6b1a6ae16b5d23f633a0c47ae471e1
/generated_python_code/ball_collector/teleoperated/scripts/subsystem_cs.py
a8addcfbb53cffe97cb94e2be8cea36f22e5d4af
[ "BSD-3-Clause" ]
permissive
https://github.com/mfigat/public_rshpn_tool
dd91d12e28d31a9c97c878b4d6e0a482a9bddfb6
3555cb8f1eb35ef12441b9aef63dae8f578c2aa7
refs/heads/master
2021-11-05T23:47:08.904506
2021-11-02T12:26:29
2021-11-02T12:26:29
207,675,046
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python ''' Copyright (c) 2019, Robot Control and Pattern Recognition Group, Warsaw University of Technology All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Warsaw University of Technology 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 <COPYright HOLDER> 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. Author: Maksym Figat ''' # Import other scripts # from auxiliary_functions import * from auxiliary_agent_teleoperated import * from auxiliary_subsystem_cs import * # Temporary definitions # IS_LOG = False # Flag determining if logs are shown in the terminal # IS_PRINT = True # Flag indicating if debug information for developer are shown in the terminal # class cs: ##### Subsystem cs constructor ##### def __init__(self): self.log("__init__ function") rospy.init_node("cs") self._subsystemName="cs" self._subsystemFrequency=10; self._currentSubsystemBehaviour="Behaviour_initBehaviour"; self._subsystemIterations=0 self._behaviourIterations=0 self.initialiseCommunicationModel() self.auxiliaryFunctions = AuxiliaryFunctions(self._subsystemFrequency) # initialize all input flags self._in_flag_taskCommand=False self._in_flag_robotStatus=False self._in_flag_ballInfoTele=False self._in_flag_obstacleDetectedTele=False self._in_flag_ballCollected=False # initialize all output flags self._out_flag_taskStatus=False self._out_flag_desiredRobotCommandTele=False pass ##### Start subsystem ##### def startSubsystem(self): self.log("startSubsystem") try: while self.auxiliaryFunctions.isSubsystemOK(): ''' Execute behaviour associated with _currentSubsystemBehaviour -- choose appropriate state based on _currentSubsystemBehaviour ''' if self._currentSubsystemBehaviour=="Behaviour_initBehaviour": self.log("_currentSubsystemBehaviour==Behaviour_initBehaviour") self.subsystemBehaviour_initBehaviour() continue if self._currentSubsystemBehaviour=="Behaviour_idleBehaviour": self.log("_currentSubsystemBehaviour==Behaviour_idleBehaviour") self.subsystemBehaviour_idleBehaviour() continue if self._currentSubsystemBehaviour=="Behaviour_terminateBehaviour": self.log("_currentSubsystemBehaviour==Behaviour_terminateBehaviour") self.subsystemBehaviour_terminateBehaviour() continue if self._currentSubsystemBehaviour=="Behaviour_terminatedBehaviour": self.log("_currentSubsystemBehaviour==Behaviour_terminatedBehaviour") self.subsystemBehaviour_terminatedBehaviour() continue if self._currentSubsystemBehaviour=="Behaviour_stopBehaviour": self.log("_currentSubsystemBehaviour==Behaviour_stopBehaviour") self.subsystemBehaviour_stopBehaviour() continue if self._currentSubsystemBehaviour=="Behaviour_moveFasterBehaviour": self.log("_currentSubsystemBehaviour==Behaviour_moveFasterBehaviour") self.subsystemBehaviour_moveFasterBehaviour() continue if self._currentSubsystemBehaviour=="Behaviour_moveSlowerBehaviour": self.log("_currentSubsystemBehaviour==Behaviour_moveSlowerBehaviour") self.subsystemBehaviour_moveSlowerBehaviour() continue if self._currentSubsystemBehaviour=="Behaviour_vacuumOnBehaviour": self.log("_currentSubsystemBehaviour==Behaviour_vacuumOnBehaviour") self.subsystemBehaviour_vacuumOnBehaviour() continue if self._currentSubsystemBehaviour=="Behaviour_vacuumOffBehaviour": self.log("_currentSubsystemBehaviour==Behaviour_vacuumOffBehaviour") self.subsystemBehaviour_vacuumOffBehaviour() continue if self._currentSubsystemBehaviour=="Behaviour_moveBackwardBehaviour": self.log("_currentSubsystemBehaviour==Behaviour_moveBackwardBehaviour") self.subsystemBehaviour_moveBackwardBehaviour() continue if self._currentSubsystemBehaviour=="Behaviour_moveFrontBehaviour": self.log("_currentSubsystemBehaviour==Behaviour_moveFrontBehaviour") self.subsystemBehaviour_moveFrontBehaviour() continue if self._currentSubsystemBehaviour=="Behaviour_moveRightBehaviour": self.log("_currentSubsystemBehaviour==Behaviour_moveRightBehaviour") self.subsystemBehaviour_moveRightBehaviour() continue if self._currentSubsystemBehaviour=="Behaviour_moveLeftBehaviour": self.log("_currentSubsystemBehaviour==Behaviour_moveLeftBehaviour") self.subsystemBehaviour_moveLeftBehaviour() continue if self._currentSubsystemBehaviour=="Behaviour_rotateLeftBehaviour": self.log("_currentSubsystemBehaviour==Behaviour_rotateLeftBehaviour") self.subsystemBehaviour_rotateLeftBehaviour() continue if self._currentSubsystemBehaviour=="Behaviour_rotateRightBehaviour": self.log("_currentSubsystemBehaviour==Behaviour_rotateRightBehaviour") self.subsystemBehaviour_rotateRightBehaviour() continue if self._currentSubsystemBehaviour=="Behaviour_whatCanYouSeeBehaviour": self.log("_currentSubsystemBehaviour==Behaviour_whatCanYouSeeBehaviour") self.subsystemBehaviour_whatCanYouSeeBehaviour() continue except Exception as e: print e self.error("Error found in function startSubsystem -- file subsystem_cs.py!") pass ##### Update data for input buffer: taskCommand ##### def update_taskCommand(self, data): self.log("update_taskCommand") self.taskCommand=data self._in_flag_taskCommand=True pass ##### Update data for input buffer: ballInfoTele ##### def update_ballInfoTele(self, data): self.log("update_ballInfoTele") self.ballInfoTele=data self._in_flag_ballInfoTele=True pass ##### Update data for input buffer: obstacleDetectedTele ##### def update_obstacleDetectedTele(self, data): self.log("update_obstacleDetectedTele") self.obstacleDetectedTele=data self._in_flag_obstacleDetectedTele=True pass ##### Update data for input buffer: ballCollected ##### def update_ballCollected(self, data): self.log("update_ballCollected") self.ballCollected=data self._in_flag_ballCollected=True pass ##### Initialise communication model ##### def initialiseCommunicationModel(self): self.log("initialiseCommunicationModel") self.initialiseSendChannel() self.initialiseSendChannelForDiagnostics() self.initialiseReceiveChannel() pass ##### Initialise send channel ##### def initialiseSendChannel(self): self.log("initialiseSendChannel") # Buffer name=taskStatus - Sender using NON-BLOCKING mode, receiver using NON-BLOCKING mode self._sender_taskStatus=rospy.Publisher("taskStatusChannelTele", String, queue_size=CHANNEL_SIZE) # Buffer name=desiredRobotCommandTele - Sender using NON-BLOCKING mode, receiver using NON-BLOCKING mode self._sender_desiredRobotCommandTele=rospy.Publisher("desiredRobotCommandChannelTele", String, queue_size=CHANNEL_SIZE) pass ##### Initialise send channel for diagnostics ##### def initialiseSendChannelForDiagnostics(self): self.log("initialiseSendChannelForDiagnostics") self._vectorOfSenderDiagnostics=[] self._vectorOfSenderDiagnostics.append(rospy.Publisher('cs/_currentSubsystemBehaviour', String, queue_size=CHANNEL_SIZE)) self._vectorOfSenderDiagnostics.append(rospy.Publisher('cs/_subsystemFrequency', Float64, queue_size=CHANNEL_SIZE)) self._vectorOfSenderDiagnostics.append(rospy.Publisher('cs/_subsystemName', String, queue_size=CHANNEL_SIZE)) self._vectorOfSenderDiagnostics.append(rospy.Publisher('cs/_subsystemIterations', Int64, queue_size=CHANNEL_SIZE)) self._vectorOfSenderDiagnostics.append(rospy.Publisher('cs/_behaviourIterations', Int64, queue_size=CHANNEL_SIZE)) self._vectorOfSenderDiagnostics.append(rospy.Publisher('cs/isNewCommandReceived', Int64, queue_size=CHANNEL_SIZE)) self._vectorOfSenderDiagnostics.append(rospy.Publisher('cs/_in_flag_taskCommand', Bool, queue_size=CHANNEL_SIZE)) self._vectorOfSenderDiagnostics.append(rospy.Publisher('cs/_in_flag_robotStatus', Bool, queue_size=CHANNEL_SIZE)) self._vectorOfSenderDiagnostics.append(rospy.Publisher('cs/_in_flag_ballInfoTele', Bool, queue_size=CHANNEL_SIZE)) self._vectorOfSenderDiagnostics.append(rospy.Publisher('cs/_in_flag_obstacleDetectedTele', Bool, queue_size=CHANNEL_SIZE)) self._vectorOfSenderDiagnostics.append(rospy.Publisher('cs/_in_flag_ballCollected', Bool, queue_size=CHANNEL_SIZE)) self._vectorOfSenderDiagnostics.append(rospy.Publisher('cs/_out_flag_taskStatus', Bool, queue_size=CHANNEL_SIZE)) self._vectorOfSenderDiagnostics.append(rospy.Publisher('cs/_out_flag_desiredRobotCommandTele', Bool, queue_size=CHANNEL_SIZE)) pass ##### Initialise receive channel based on input buffers ##### def initialiseReceiveChannel(self): self.log("initialiseReceiveChannel") # Buffer name=taskCommand sender NON-BLOCKING mode - receiver NON-BLOCKING mode self._subscriber_taskCommand=rospy.Subscriber("taskCommandChannel", String, self.update_taskCommand) # Buffer name=ballInfoTele sender NON-BLOCKING mode - receiver NON-BLOCKING mode self._subscriber_ballInfoTele=rospy.Subscriber("ballInfoChannelTele", CameraMessage, self.update_ballInfoTele) # Buffer name=obstacleDetectedTele sender NON-BLOCKING mode - receiver NON-BLOCKING mode self._subscriber_obstacleDetectedTele=rospy.Subscriber("obstacleDetectedChannelTele", ObstacleDetected, self.update_obstacleDetectedTele) # Buffer name=ballCollected sender NON-BLOCKING mode - receiver NON-BLOCKING mode self._subscriber_ballCollected=rospy.Subscriber("ballCollectedChannelTele", Bool, self.update_ballCollected) pass ##### Wait for all messages ##### def waitForAllMessages(self): self.log("waitForAllMessages") #rospy.wait_for_message("", String, timeout=TOPIC_TIMEOUT) #rospy.wait_for_message("", String, timeout=TOPIC_TIMEOUT) #rospy.wait_for_message("", CameraMessage, timeout=TOPIC_TIMEOUT) #rospy.wait_for_message("", ObstacleDetected, timeout=TOPIC_TIMEOUT) #rospy.wait_for_message("", Bool, timeout=TOPIC_TIMEOUT) pass ##### Publish on topics diagnostic data concerning the subsystem state ##### def sendDataForDiagnostics(self): self._vectorOfSenderDiagnostics[0].publish(self._currentSubsystemBehaviour) self._vectorOfSenderDiagnostics[1].publish(self._subsystemFrequency) self._vectorOfSenderDiagnostics[2].publish(self._subsystemName) self._vectorOfSenderDiagnostics[3].publish(self._subsystemIterations) self._vectorOfSenderDiagnostics[4].publish(self._behaviourIterations) ###### internal state ##### if(12 < len(self._vectorOfSenderDiagnostics) ): self._vectorOfSenderDiagnostics[5].publish(self.isNewCommandReceived) self._vectorOfSenderDiagnostics[6].publish(self._in_flag_taskCommand) self._vectorOfSenderDiagnostics[7].publish(self._in_flag_robotStatus) self._vectorOfSenderDiagnostics[8].publish(self._in_flag_ballInfoTele) self._vectorOfSenderDiagnostics[9].publish(self._in_flag_obstacleDetectedTele) self._vectorOfSenderDiagnostics[10].publish(self._in_flag_ballCollected) self._vectorOfSenderDiagnostics[11].publish(self._out_flag_taskStatus) self._vectorOfSenderDiagnostics[12].publish(self._out_flag_desiredRobotCommandTele) pass ##### Behaviour definitions ##### ##### Behaviour initBehaviour ##### ##### Terminal condition ##### def terminalCondition_initBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour initBehaviour] -- Checking Terminal Condition") return True pass ##### Error condition ##### def errorCondition_initBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour initBehaviour] -- Checking Error Condition") return False pass ##### Transition function ##### def transitionFunction_initBehaviour(self): self.log("[Behaviour initBehaviour] -- Calculating Transition Function") # Transition function # self.log("TRANSITION FUNCTION - initBehaviour consists of the following partial transition functions (decomposition based on output buffers)") # Partial transition function call: fun1 self.transitionFunction_initBehaviour_fun1() # Partial transition function call: set_buffer_flags_function self.transitionFunction_initBehaviour_set_buffer_flags_function() pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_initBehaviour_fun1(self): self.log("[Behaviour initBehaviour] -- Calculating Partial Transition Function fun1") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - initBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_initBehaviour_fun1_0() pass ##### Partial transition function: fun1_0 based on input buffers True ##### def transitionFunction_initBehaviour_fun1_0(self): self.log("[Behaviour initBehaviour] -- Calculating Partial Transition Function fun1_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - initBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code print("[CS - teleoperated] -- initBehaviour") self.taskCommand=String("empty") self.taskStatus=String("empty") self.desiredRobotCommandTele=String("empty") self.robotStatus=String("empty") self.isNewCommandReceived=Int64(0) # End - Partial Transition Function Code pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_initBehaviour_set_buffer_flags_function(self): self.log("[Behaviour initBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - initBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_initBehaviour_set_buffer_flags_function_0() pass ##### Partial transition function: set_buffer_flags_function_0 based on input buffers True ##### def transitionFunction_initBehaviour_set_buffer_flags_function_0(self): self.log("[Behaviour initBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - initBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code # End - Partial Transition Function Code pass ##### End of transition function ##### ##### Send data to other subsystems ##### def sendData_initBehaviour(self): self.log("[Behaviour initBehaviour] -- Sending Data") # DIAGNOSTICS SEND # self.sendDataForDiagnostics() # END OF DIAGNOSTICS SEND # # TYPICAL SEND CALL # # check if output buffer taskStatus has new data - i.e. is ready to send new data if( self._out_flag_taskStatus ): # send data from output buffer taskStatus # Buffer taskStatus - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_taskStatus.publish(self.taskStatus) # sending data from output buffer taskStatus # # indicate that data was sent and now the output buffer taskStatus is empty self._out_flag_taskStatus=False # check if output buffer desiredRobotCommandTele has new data - i.e. is ready to send new data if( self._out_flag_desiredRobotCommandTele ): # send data from output buffer desiredRobotCommandTele # Buffer desiredRobotCommandTele - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_desiredRobotCommandTele.publish(self.desiredRobotCommandTele) # sending data from output buffer desiredRobotCommandTele # # indicate that data was sent and now the output buffer desiredRobotCommandTele is empty self._out_flag_desiredRobotCommandTele=False # END OF TYPICAL SEND CALL # # BEGIN OF BODY SEND CALL # # END OF BODY SEND CALL # pass ##### Receive data from other subsystems ##### def receiveData_initBehaviour(self): self.log("[Behaviour initBehaviour] -- Receiving Data") # TYPICAL RECEIVE CALL # # Buffer taskCommand - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer taskCommand # Buffer ballInfoTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballInfoTele # Buffer obstacleDetectedTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer obstacleDetectedTele # Buffer ballCollected - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballCollected self.waitForAllMessages() # # END OF TYPICAL RECEIVE CALL # # BEGIN OF RECEIVE BODY CALL # # END OF RECEIVE BODY CALL # pass ##### Execute behaviour initBehaviour ##### def executeBehaviour_initBehaviour(self): self.log("[Behaviour initBehaviour] -- Executing initBehaviour Behaviour") stopBehaviourIteration=False # Execution of a single iteration of a behaviour initBehaviour # _behaviourIterations=0 # Starts execution! # while True: # Sleep is a method from class AuxiliaryFunctions which executes sleep from ROS # self.auxiliaryFunctions.sleep() # Calculates transition function -- output and internal buffers can only be modified by this function! # self.transitionFunction_initBehaviour() # Sends data! # self.sendData_initBehaviour() # Updates index! -- i.e. i:i+1 -- increment number of behaviour iterations and number of subsystem iterations # self._behaviourIterations=self._behaviourIterations+1 # Receives data! # self.receiveData_initBehaviour() # Check both conditions, i.e. terminal condition and error condition # stopBehaviourIteration = self.terminalCondition_initBehaviour() or self.errorCondition_initBehaviour() if stopBehaviourIteration or not self.auxiliaryFunctions.isSubsystemOK(): ''' Iterate within the while loop until stopBehaviourIteration is set true, i.e. one of error and terminal condition is fulfilled and isSubsystemOK is true. Otherwise subsystem must have been switched to another state or SIGINT was sent ''' break # Stops execution! # pass ##### Behaviour idleBehaviour ##### ##### Terminal condition ##### def terminalCondition_idleBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour idleBehaviour] -- Checking Terminal Condition") return checkCommand(self.taskCommand.data) and self.isNewCommandReceived.data>0 pass ##### Error condition ##### def errorCondition_idleBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour idleBehaviour] -- Checking Error Condition") return False pass ##### Transition function ##### def transitionFunction_idleBehaviour(self): self.log("[Behaviour idleBehaviour] -- Calculating Transition Function") # Transition function # self.log("TRANSITION FUNCTION - idleBehaviour consists of the following partial transition functions (decomposition based on output buffers)") # Partial transition function call: fun1 self.transitionFunction_idleBehaviour_fun1() # Partial transition function call: set_buffer_flags_function self.transitionFunction_idleBehaviour_set_buffer_flags_function() pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_idleBehaviour_fun1(self): self.log("[Behaviour idleBehaviour] -- Calculating Partial Transition Function fun1") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - idleBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if self._in_flag_taskCommand: self.transitionFunction_idleBehaviour_fun1_0() elif not (self._in_flag_taskCommand): self.transitionFunction_idleBehaviour_fun1_1() pass ##### Partial transition function: fun1_0 based on input buffers self._in_flag_taskCommand ##### def transitionFunction_idleBehaviour_fun1_0(self): self.log("[Behaviour idleBehaviour] -- Calculating Partial Transition Function fun1_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - idleBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code print("[CS - teleoperated] -- idleBehaviour - TRUE") self.isNewCommandReceived.data=1 # End - Partial Transition Function Code pass ##### Partial transition function: fun1_1 based on input buffers not (self._in_flag_taskCommand) ##### def transitionFunction_idleBehaviour_fun1_1(self): self.log("[Behaviour idleBehaviour] -- Calculating Partial Transition Function fun1_1") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - idleBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code print("[CS - teleoperated] -- idleBehaviour - FALSE") self.isNewCommandReceived.data=0 # End - Partial Transition Function Code pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_idleBehaviour_set_buffer_flags_function(self): self.log("[Behaviour idleBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - idleBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_idleBehaviour_set_buffer_flags_function_0() pass ##### Partial transition function: set_buffer_flags_function_0 based on input buffers True ##### def transitionFunction_idleBehaviour_set_buffer_flags_function_0(self): self.log("[Behaviour idleBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - idleBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code self._in_flag_taskCommand=False # End - Partial Transition Function Code pass ##### End of transition function ##### ##### Send data to other subsystems ##### def sendData_idleBehaviour(self): self.log("[Behaviour idleBehaviour] -- Sending Data") # DIAGNOSTICS SEND # self.sendDataForDiagnostics() # END OF DIAGNOSTICS SEND # # TYPICAL SEND CALL # # check if output buffer taskStatus has new data - i.e. is ready to send new data if( self._out_flag_taskStatus ): # send data from output buffer taskStatus # Buffer taskStatus - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_taskStatus.publish(self.taskStatus) # sending data from output buffer taskStatus # # indicate that data was sent and now the output buffer taskStatus is empty self._out_flag_taskStatus=False # check if output buffer desiredRobotCommandTele has new data - i.e. is ready to send new data if( self._out_flag_desiredRobotCommandTele ): # send data from output buffer desiredRobotCommandTele # Buffer desiredRobotCommandTele - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_desiredRobotCommandTele.publish(self.desiredRobotCommandTele) # sending data from output buffer desiredRobotCommandTele # # indicate that data was sent and now the output buffer desiredRobotCommandTele is empty self._out_flag_desiredRobotCommandTele=False # END OF TYPICAL SEND CALL # # BEGIN OF BODY SEND CALL # # END OF BODY SEND CALL # pass ##### Receive data from other subsystems ##### def receiveData_idleBehaviour(self): self.log("[Behaviour idleBehaviour] -- Receiving Data") # TYPICAL RECEIVE CALL # # Buffer taskCommand - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer taskCommand # Buffer ballInfoTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballInfoTele # Buffer obstacleDetectedTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer obstacleDetectedTele # Buffer ballCollected - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballCollected self.waitForAllMessages() # # END OF TYPICAL RECEIVE CALL # # BEGIN OF RECEIVE BODY CALL # # END OF RECEIVE BODY CALL # pass ##### Execute behaviour idleBehaviour ##### def executeBehaviour_idleBehaviour(self): self.log("[Behaviour idleBehaviour] -- Executing idleBehaviour Behaviour") stopBehaviourIteration=False # Execution of a single iteration of a behaviour idleBehaviour # _behaviourIterations=0 # Starts execution! # while True: # Sleep is a method from class AuxiliaryFunctions which executes sleep from ROS # self.auxiliaryFunctions.sleep() # Calculates transition function -- output and internal buffers can only be modified by this function! # self.transitionFunction_idleBehaviour() # Sends data! # self.sendData_idleBehaviour() # Updates index! -- i.e. i:i+1 -- increment number of behaviour iterations and number of subsystem iterations # self._behaviourIterations=self._behaviourIterations+1 # Receives data! # self.receiveData_idleBehaviour() # Check both conditions, i.e. terminal condition and error condition # stopBehaviourIteration = self.terminalCondition_idleBehaviour() or self.errorCondition_idleBehaviour() if stopBehaviourIteration or not self.auxiliaryFunctions.isSubsystemOK(): ''' Iterate within the while loop until stopBehaviourIteration is set true, i.e. one of error and terminal condition is fulfilled and isSubsystemOK is true. Otherwise subsystem must have been switched to another state or SIGINT was sent ''' break # Stops execution! # pass ##### Behaviour terminateBehaviour ##### ##### Terminal condition ##### def terminalCondition_terminateBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour terminateBehaviour] -- Checking Terminal Condition") return False pass ##### Error condition ##### def errorCondition_terminateBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour terminateBehaviour] -- Checking Error Condition") return False pass ##### Transition function ##### def transitionFunction_terminateBehaviour(self): self.log("[Behaviour terminateBehaviour] -- Calculating Transition Function") # Transition function # self.log("TRANSITION FUNCTION - terminateBehaviour consists of the following partial transition functions (decomposition based on output buffers)") # Partial transition function call: fun1 self.transitionFunction_terminateBehaviour_fun1() # Partial transition function call: set_buffer_flags_function self.transitionFunction_terminateBehaviour_set_buffer_flags_function() pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_terminateBehaviour_fun1(self): self.log("[Behaviour terminateBehaviour] -- Calculating Partial Transition Function fun1") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - terminateBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_terminateBehaviour_fun1_0() pass ##### Partial transition function: fun1_0 based on input buffers True ##### def transitionFunction_terminateBehaviour_fun1_0(self): self.log("[Behaviour terminateBehaviour] -- Calculating Partial Transition Function fun1_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - terminateBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code self._out_flag_taskStatus=True self._out_flag_desiredRobotCommandTele=True print("[CS - teleoperated] -- terminateBehaviour") if(self.taskStatus.data=="task terminated"): self._out_flag_taskStatus=False self._out_flag_desiredRobotCommandTele=False else: self.taskStatus.data="task terminated" self.desiredRobotCommandTele.data="terminate" # End - Partial Transition Function Code pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_terminateBehaviour_set_buffer_flags_function(self): self.log("[Behaviour terminateBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - terminateBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_terminateBehaviour_set_buffer_flags_function_0() pass ##### Partial transition function: set_buffer_flags_function_0 based on input buffers True ##### def transitionFunction_terminateBehaviour_set_buffer_flags_function_0(self): self.log("[Behaviour terminateBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - terminateBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code # End - Partial Transition Function Code pass ##### End of transition function ##### ##### Send data to other subsystems ##### def sendData_terminateBehaviour(self): self.log("[Behaviour terminateBehaviour] -- Sending Data") # DIAGNOSTICS SEND # self.sendDataForDiagnostics() # END OF DIAGNOSTICS SEND # # TYPICAL SEND CALL # # check if output buffer taskStatus has new data - i.e. is ready to send new data if( self._out_flag_taskStatus ): # send data from output buffer taskStatus # Buffer taskStatus - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_taskStatus.publish(self.taskStatus) # sending data from output buffer taskStatus # # indicate that data was sent and now the output buffer taskStatus is empty self._out_flag_taskStatus=False # check if output buffer desiredRobotCommandTele has new data - i.e. is ready to send new data if( self._out_flag_desiredRobotCommandTele ): # send data from output buffer desiredRobotCommandTele # Buffer desiredRobotCommandTele - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_desiredRobotCommandTele.publish(self.desiredRobotCommandTele) # sending data from output buffer desiredRobotCommandTele # # indicate that data was sent and now the output buffer desiredRobotCommandTele is empty self._out_flag_desiredRobotCommandTele=False # END OF TYPICAL SEND CALL # # BEGIN OF BODY SEND CALL # # END OF BODY SEND CALL # pass ##### Receive data from other subsystems ##### def receiveData_terminateBehaviour(self): self.log("[Behaviour terminateBehaviour] -- Receiving Data") # TYPICAL RECEIVE CALL # # Buffer taskCommand - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer taskCommand # Buffer ballInfoTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballInfoTele # Buffer obstacleDetectedTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer obstacleDetectedTele # Buffer ballCollected - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballCollected self.waitForAllMessages() # # END OF TYPICAL RECEIVE CALL # # BEGIN OF RECEIVE BODY CALL # # END OF RECEIVE BODY CALL # pass ##### Execute behaviour terminateBehaviour ##### def executeBehaviour_terminateBehaviour(self): self.log("[Behaviour terminateBehaviour] -- Executing terminateBehaviour Behaviour") stopBehaviourIteration=False # Execution of a single iteration of a behaviour terminateBehaviour # _behaviourIterations=0 # Starts execution! # while True: # Sleep is a method from class AuxiliaryFunctions which executes sleep from ROS # self.auxiliaryFunctions.sleep() # Calculates transition function -- output and internal buffers can only be modified by this function! # self.transitionFunction_terminateBehaviour() # Sends data! # self.sendData_terminateBehaviour() # Updates index! -- i.e. i:i+1 -- increment number of behaviour iterations and number of subsystem iterations # self._behaviourIterations=self._behaviourIterations+1 # Receives data! # self.receiveData_terminateBehaviour() # Check both conditions, i.e. terminal condition and error condition # stopBehaviourIteration = self.terminalCondition_terminateBehaviour() or self.errorCondition_terminateBehaviour() if stopBehaviourIteration or not self.auxiliaryFunctions.isSubsystemOK(): ''' Iterate within the while loop until stopBehaviourIteration is set true, i.e. one of error and terminal condition is fulfilled and isSubsystemOK is true. Otherwise subsystem must have been switched to another state or SIGINT was sent ''' break # Stops execution! # pass ##### Behaviour terminatedBehaviour ##### ##### Terminal condition ##### def terminalCondition_terminatedBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour terminatedBehaviour] -- Checking Terminal Condition") return False pass ##### Error condition ##### def errorCondition_terminatedBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour terminatedBehaviour] -- Checking Error Condition") return False pass ##### Transition function ##### def transitionFunction_terminatedBehaviour(self): self.log("[Behaviour terminatedBehaviour] -- Calculating Transition Function") # Transition function # self.log("TRANSITION FUNCTION - terminatedBehaviour consists of the following partial transition functions (decomposition based on output buffers)") # Partial transition function call: fun1 self.transitionFunction_terminatedBehaviour_fun1() # Partial transition function call: set_buffer_flags_function self.transitionFunction_terminatedBehaviour_set_buffer_flags_function() pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_terminatedBehaviour_fun1(self): self.log("[Behaviour terminatedBehaviour] -- Calculating Partial Transition Function fun1") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - terminatedBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_terminatedBehaviour_fun1_0() pass ##### Partial transition function: fun1_0 based on input buffers True ##### def transitionFunction_terminatedBehaviour_fun1_0(self): self.log("[Behaviour terminatedBehaviour] -- Calculating Partial Transition Function fun1_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - terminatedBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code print("[CS - teleoperated] -- terminatedBehaviour") # End - Partial Transition Function Code pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_terminatedBehaviour_set_buffer_flags_function(self): self.log("[Behaviour terminatedBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - terminatedBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_terminatedBehaviour_set_buffer_flags_function_0() pass ##### Partial transition function: set_buffer_flags_function_0 based on input buffers True ##### def transitionFunction_terminatedBehaviour_set_buffer_flags_function_0(self): self.log("[Behaviour terminatedBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - terminatedBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code # End - Partial Transition Function Code pass ##### End of transition function ##### ##### Send data to other subsystems ##### def sendData_terminatedBehaviour(self): self.log("[Behaviour terminatedBehaviour] -- Sending Data") # DIAGNOSTICS SEND # self.sendDataForDiagnostics() # END OF DIAGNOSTICS SEND # # TYPICAL SEND CALL # # check if output buffer taskStatus has new data - i.e. is ready to send new data if( self._out_flag_taskStatus ): # send data from output buffer taskStatus # Buffer taskStatus - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_taskStatus.publish(self.taskStatus) # sending data from output buffer taskStatus # # indicate that data was sent and now the output buffer taskStatus is empty self._out_flag_taskStatus=False # check if output buffer desiredRobotCommandTele has new data - i.e. is ready to send new data if( self._out_flag_desiredRobotCommandTele ): # send data from output buffer desiredRobotCommandTele # Buffer desiredRobotCommandTele - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_desiredRobotCommandTele.publish(self.desiredRobotCommandTele) # sending data from output buffer desiredRobotCommandTele # # indicate that data was sent and now the output buffer desiredRobotCommandTele is empty self._out_flag_desiredRobotCommandTele=False # END OF TYPICAL SEND CALL # # BEGIN OF BODY SEND CALL # # END OF BODY SEND CALL # pass ##### Receive data from other subsystems ##### def receiveData_terminatedBehaviour(self): self.log("[Behaviour terminatedBehaviour] -- Receiving Data") # TYPICAL RECEIVE CALL # # Buffer taskCommand - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer taskCommand # Buffer ballInfoTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballInfoTele # Buffer obstacleDetectedTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer obstacleDetectedTele # Buffer ballCollected - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballCollected self.waitForAllMessages() # # END OF TYPICAL RECEIVE CALL # # BEGIN OF RECEIVE BODY CALL # # END OF RECEIVE BODY CALL # pass ##### Execute behaviour terminatedBehaviour ##### def executeBehaviour_terminatedBehaviour(self): self.log("[Behaviour terminatedBehaviour] -- Executing terminatedBehaviour Behaviour") stopBehaviourIteration=False # Execution of a single iteration of a behaviour terminatedBehaviour # _behaviourIterations=0 # Starts execution! # while True: # Sleep is a method from class AuxiliaryFunctions which executes sleep from ROS # self.auxiliaryFunctions.sleep() # Calculates transition function -- output and internal buffers can only be modified by this function! # self.transitionFunction_terminatedBehaviour() # Sends data! # self.sendData_terminatedBehaviour() # Updates index! -- i.e. i:i+1 -- increment number of behaviour iterations and number of subsystem iterations # self._behaviourIterations=self._behaviourIterations+1 # Receives data! # self.receiveData_terminatedBehaviour() # Check both conditions, i.e. terminal condition and error condition # stopBehaviourIteration = self.terminalCondition_terminatedBehaviour() or self.errorCondition_terminatedBehaviour() if stopBehaviourIteration or not self.auxiliaryFunctions.isSubsystemOK(): ''' Iterate within the while loop until stopBehaviourIteration is set true, i.e. one of error and terminal condition is fulfilled and isSubsystemOK is true. Otherwise subsystem must have been switched to another state or SIGINT was sent ''' break # Stops execution! # pass ##### Behaviour stopBehaviour ##### ##### Terminal condition ##### def terminalCondition_stopBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour stopBehaviour] -- Checking Terminal Condition") return True pass ##### Error condition ##### def errorCondition_stopBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour stopBehaviour] -- Checking Error Condition") return False pass ##### Transition function ##### def transitionFunction_stopBehaviour(self): self.log("[Behaviour stopBehaviour] -- Calculating Transition Function") # Transition function # self.log("TRANSITION FUNCTION - stopBehaviour consists of the following partial transition functions (decomposition based on output buffers)") # Partial transition function call: fun1 self.transitionFunction_stopBehaviour_fun1() # Partial transition function call: set_buffer_flags_function self.transitionFunction_stopBehaviour_set_buffer_flags_function() pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_stopBehaviour_fun1(self): self.log("[Behaviour stopBehaviour] -- Calculating Partial Transition Function fun1") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - stopBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_stopBehaviour_fun1_0() pass ##### Partial transition function: fun1_0 based on input buffers True ##### def transitionFunction_stopBehaviour_fun1_0(self): self.log("[Behaviour stopBehaviour] -- Calculating Partial Transition Function fun1_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - stopBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code self._out_flag_taskStatus=True self._out_flag_desiredRobotCommandTele=True print("[CS - teleoperated] -- stopBehaviour") self.desiredRobotCommandTele.data="stop" self.taskStatus.data="task status: stop robot" # End - Partial Transition Function Code pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_stopBehaviour_set_buffer_flags_function(self): self.log("[Behaviour stopBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - stopBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_stopBehaviour_set_buffer_flags_function_0() pass ##### Partial transition function: set_buffer_flags_function_0 based on input buffers True ##### def transitionFunction_stopBehaviour_set_buffer_flags_function_0(self): self.log("[Behaviour stopBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - stopBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code # End - Partial Transition Function Code pass ##### End of transition function ##### ##### Send data to other subsystems ##### def sendData_stopBehaviour(self): self.log("[Behaviour stopBehaviour] -- Sending Data") # DIAGNOSTICS SEND # self.sendDataForDiagnostics() # END OF DIAGNOSTICS SEND # # TYPICAL SEND CALL # # check if output buffer taskStatus has new data - i.e. is ready to send new data if( self._out_flag_taskStatus ): # send data from output buffer taskStatus # Buffer taskStatus - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_taskStatus.publish(self.taskStatus) # sending data from output buffer taskStatus # # indicate that data was sent and now the output buffer taskStatus is empty self._out_flag_taskStatus=False # check if output buffer desiredRobotCommandTele has new data - i.e. is ready to send new data if( self._out_flag_desiredRobotCommandTele ): # send data from output buffer desiredRobotCommandTele # Buffer desiredRobotCommandTele - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_desiredRobotCommandTele.publish(self.desiredRobotCommandTele) # sending data from output buffer desiredRobotCommandTele # # indicate that data was sent and now the output buffer desiredRobotCommandTele is empty self._out_flag_desiredRobotCommandTele=False # END OF TYPICAL SEND CALL # # BEGIN OF BODY SEND CALL # # END OF BODY SEND CALL # pass ##### Receive data from other subsystems ##### def receiveData_stopBehaviour(self): self.log("[Behaviour stopBehaviour] -- Receiving Data") # TYPICAL RECEIVE CALL # # Buffer taskCommand - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer taskCommand # Buffer ballInfoTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballInfoTele # Buffer obstacleDetectedTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer obstacleDetectedTele # Buffer ballCollected - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballCollected self.waitForAllMessages() # # END OF TYPICAL RECEIVE CALL # # BEGIN OF RECEIVE BODY CALL # # END OF RECEIVE BODY CALL # pass ##### Execute behaviour stopBehaviour ##### def executeBehaviour_stopBehaviour(self): self.log("[Behaviour stopBehaviour] -- Executing stopBehaviour Behaviour") stopBehaviourIteration=False # Execution of a single iteration of a behaviour stopBehaviour # _behaviourIterations=0 # Starts execution! # while True: # Sleep is a method from class AuxiliaryFunctions which executes sleep from ROS # self.auxiliaryFunctions.sleep() # Calculates transition function -- output and internal buffers can only be modified by this function! # self.transitionFunction_stopBehaviour() # Sends data! # self.sendData_stopBehaviour() # Updates index! -- i.e. i:i+1 -- increment number of behaviour iterations and number of subsystem iterations # self._behaviourIterations=self._behaviourIterations+1 # Receives data! # self.receiveData_stopBehaviour() # Check both conditions, i.e. terminal condition and error condition # stopBehaviourIteration = self.terminalCondition_stopBehaviour() or self.errorCondition_stopBehaviour() if stopBehaviourIteration or not self.auxiliaryFunctions.isSubsystemOK(): ''' Iterate within the while loop until stopBehaviourIteration is set true, i.e. one of error and terminal condition is fulfilled and isSubsystemOK is true. Otherwise subsystem must have been switched to another state or SIGINT was sent ''' break # Stops execution! # pass ##### Behaviour moveFasterBehaviour ##### ##### Terminal condition ##### def terminalCondition_moveFasterBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour moveFasterBehaviour] -- Checking Terminal Condition") return True pass ##### Error condition ##### def errorCondition_moveFasterBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour moveFasterBehaviour] -- Checking Error Condition") return False pass ##### Transition function ##### def transitionFunction_moveFasterBehaviour(self): self.log("[Behaviour moveFasterBehaviour] -- Calculating Transition Function") # Transition function # self.log("TRANSITION FUNCTION - moveFasterBehaviour consists of the following partial transition functions (decomposition based on output buffers)") # Partial transition function call: fun1 self.transitionFunction_moveFasterBehaviour_fun1() # Partial transition function call: set_buffer_flags_function self.transitionFunction_moveFasterBehaviour_set_buffer_flags_function() pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_moveFasterBehaviour_fun1(self): self.log("[Behaviour moveFasterBehaviour] -- Calculating Partial Transition Function fun1") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - moveFasterBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_moveFasterBehaviour_fun1_0() pass ##### Partial transition function: fun1_0 based on input buffers True ##### def transitionFunction_moveFasterBehaviour_fun1_0(self): self.log("[Behaviour moveFasterBehaviour] -- Calculating Partial Transition Function fun1_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - moveFasterBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code self._out_flag_taskStatus=True self._out_flag_desiredRobotCommandTele=True print("[CS - teleoperated] -- moveFasterBehaviour") self.desiredRobotCommandTele.data="move faster" self.taskStatus.data="task status: move faster" # End - Partial Transition Function Code pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_moveFasterBehaviour_set_buffer_flags_function(self): self.log("[Behaviour moveFasterBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - moveFasterBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_moveFasterBehaviour_set_buffer_flags_function_0() pass ##### Partial transition function: set_buffer_flags_function_0 based on input buffers True ##### def transitionFunction_moveFasterBehaviour_set_buffer_flags_function_0(self): self.log("[Behaviour moveFasterBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - moveFasterBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code # End - Partial Transition Function Code pass ##### End of transition function ##### ##### Send data to other subsystems ##### def sendData_moveFasterBehaviour(self): self.log("[Behaviour moveFasterBehaviour] -- Sending Data") # DIAGNOSTICS SEND # self.sendDataForDiagnostics() # END OF DIAGNOSTICS SEND # # TYPICAL SEND CALL # # check if output buffer taskStatus has new data - i.e. is ready to send new data if( self._out_flag_taskStatus ): # send data from output buffer taskStatus # Buffer taskStatus - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_taskStatus.publish(self.taskStatus) # sending data from output buffer taskStatus # # indicate that data was sent and now the output buffer taskStatus is empty self._out_flag_taskStatus=False # check if output buffer desiredRobotCommandTele has new data - i.e. is ready to send new data if( self._out_flag_desiredRobotCommandTele ): # send data from output buffer desiredRobotCommandTele # Buffer desiredRobotCommandTele - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_desiredRobotCommandTele.publish(self.desiredRobotCommandTele) # sending data from output buffer desiredRobotCommandTele # # indicate that data was sent and now the output buffer desiredRobotCommandTele is empty self._out_flag_desiredRobotCommandTele=False # END OF TYPICAL SEND CALL # # BEGIN OF BODY SEND CALL # # END OF BODY SEND CALL # pass ##### Receive data from other subsystems ##### def receiveData_moveFasterBehaviour(self): self.log("[Behaviour moveFasterBehaviour] -- Receiving Data") # TYPICAL RECEIVE CALL # # Buffer taskCommand - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer taskCommand # Buffer ballInfoTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballInfoTele # Buffer obstacleDetectedTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer obstacleDetectedTele # Buffer ballCollected - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballCollected self.waitForAllMessages() # # END OF TYPICAL RECEIVE CALL # # BEGIN OF RECEIVE BODY CALL # # END OF RECEIVE BODY CALL # pass ##### Execute behaviour moveFasterBehaviour ##### def executeBehaviour_moveFasterBehaviour(self): self.log("[Behaviour moveFasterBehaviour] -- Executing moveFasterBehaviour Behaviour") stopBehaviourIteration=False # Execution of a single iteration of a behaviour moveFasterBehaviour # _behaviourIterations=0 # Starts execution! # while True: # Sleep is a method from class AuxiliaryFunctions which executes sleep from ROS # self.auxiliaryFunctions.sleep() # Calculates transition function -- output and internal buffers can only be modified by this function! # self.transitionFunction_moveFasterBehaviour() # Sends data! # self.sendData_moveFasterBehaviour() # Updates index! -- i.e. i:i+1 -- increment number of behaviour iterations and number of subsystem iterations # self._behaviourIterations=self._behaviourIterations+1 # Receives data! # self.receiveData_moveFasterBehaviour() # Check both conditions, i.e. terminal condition and error condition # stopBehaviourIteration = self.terminalCondition_moveFasterBehaviour() or self.errorCondition_moveFasterBehaviour() if stopBehaviourIteration or not self.auxiliaryFunctions.isSubsystemOK(): ''' Iterate within the while loop until stopBehaviourIteration is set true, i.e. one of error and terminal condition is fulfilled and isSubsystemOK is true. Otherwise subsystem must have been switched to another state or SIGINT was sent ''' break # Stops execution! # pass ##### Behaviour moveSlowerBehaviour ##### ##### Terminal condition ##### def terminalCondition_moveSlowerBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour moveSlowerBehaviour] -- Checking Terminal Condition") return True pass ##### Error condition ##### def errorCondition_moveSlowerBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour moveSlowerBehaviour] -- Checking Error Condition") return False pass ##### Transition function ##### def transitionFunction_moveSlowerBehaviour(self): self.log("[Behaviour moveSlowerBehaviour] -- Calculating Transition Function") # Transition function # self.log("TRANSITION FUNCTION - moveSlowerBehaviour consists of the following partial transition functions (decomposition based on output buffers)") # Partial transition function call: fun1 self.transitionFunction_moveSlowerBehaviour_fun1() # Partial transition function call: set_buffer_flags_function self.transitionFunction_moveSlowerBehaviour_set_buffer_flags_function() pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_moveSlowerBehaviour_fun1(self): self.log("[Behaviour moveSlowerBehaviour] -- Calculating Partial Transition Function fun1") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - moveSlowerBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_moveSlowerBehaviour_fun1_0() pass ##### Partial transition function: fun1_0 based on input buffers True ##### def transitionFunction_moveSlowerBehaviour_fun1_0(self): self.log("[Behaviour moveSlowerBehaviour] -- Calculating Partial Transition Function fun1_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - moveSlowerBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code self._out_flag_taskStatus=True self._out_flag_desiredRobotCommandTele=True print("[CS - teleoperated] -- moveSlowerBehaviour") self.desiredRobotCommandTele.data="move slower" self.taskStatus.data="task status: move slower" # End - Partial Transition Function Code pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_moveSlowerBehaviour_set_buffer_flags_function(self): self.log("[Behaviour moveSlowerBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - moveSlowerBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_moveSlowerBehaviour_set_buffer_flags_function_0() pass ##### Partial transition function: set_buffer_flags_function_0 based on input buffers True ##### def transitionFunction_moveSlowerBehaviour_set_buffer_flags_function_0(self): self.log("[Behaviour moveSlowerBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - moveSlowerBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code # End - Partial Transition Function Code pass ##### End of transition function ##### ##### Send data to other subsystems ##### def sendData_moveSlowerBehaviour(self): self.log("[Behaviour moveSlowerBehaviour] -- Sending Data") # DIAGNOSTICS SEND # self.sendDataForDiagnostics() # END OF DIAGNOSTICS SEND # # TYPICAL SEND CALL # # check if output buffer taskStatus has new data - i.e. is ready to send new data if( self._out_flag_taskStatus ): # send data from output buffer taskStatus # Buffer taskStatus - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_taskStatus.publish(self.taskStatus) # sending data from output buffer taskStatus # # indicate that data was sent and now the output buffer taskStatus is empty self._out_flag_taskStatus=False # check if output buffer desiredRobotCommandTele has new data - i.e. is ready to send new data if( self._out_flag_desiredRobotCommandTele ): # send data from output buffer desiredRobotCommandTele # Buffer desiredRobotCommandTele - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_desiredRobotCommandTele.publish(self.desiredRobotCommandTele) # sending data from output buffer desiredRobotCommandTele # # indicate that data was sent and now the output buffer desiredRobotCommandTele is empty self._out_flag_desiredRobotCommandTele=False # END OF TYPICAL SEND CALL # # BEGIN OF BODY SEND CALL # # END OF BODY SEND CALL # pass ##### Receive data from other subsystems ##### def receiveData_moveSlowerBehaviour(self): self.log("[Behaviour moveSlowerBehaviour] -- Receiving Data") # TYPICAL RECEIVE CALL # # Buffer taskCommand - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer taskCommand # Buffer ballInfoTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballInfoTele # Buffer obstacleDetectedTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer obstacleDetectedTele # Buffer ballCollected - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballCollected self.waitForAllMessages() # # END OF TYPICAL RECEIVE CALL # # BEGIN OF RECEIVE BODY CALL # # END OF RECEIVE BODY CALL # pass ##### Execute behaviour moveSlowerBehaviour ##### def executeBehaviour_moveSlowerBehaviour(self): self.log("[Behaviour moveSlowerBehaviour] -- Executing moveSlowerBehaviour Behaviour") stopBehaviourIteration=False # Execution of a single iteration of a behaviour moveSlowerBehaviour # _behaviourIterations=0 # Starts execution! # while True: # Sleep is a method from class AuxiliaryFunctions which executes sleep from ROS # self.auxiliaryFunctions.sleep() # Calculates transition function -- output and internal buffers can only be modified by this function! # self.transitionFunction_moveSlowerBehaviour() # Sends data! # self.sendData_moveSlowerBehaviour() # Updates index! -- i.e. i:i+1 -- increment number of behaviour iterations and number of subsystem iterations # self._behaviourIterations=self._behaviourIterations+1 # Receives data! # self.receiveData_moveSlowerBehaviour() # Check both conditions, i.e. terminal condition and error condition # stopBehaviourIteration = self.terminalCondition_moveSlowerBehaviour() or self.errorCondition_moveSlowerBehaviour() if stopBehaviourIteration or not self.auxiliaryFunctions.isSubsystemOK(): ''' Iterate within the while loop until stopBehaviourIteration is set true, i.e. one of error and terminal condition is fulfilled and isSubsystemOK is true. Otherwise subsystem must have been switched to another state or SIGINT was sent ''' break # Stops execution! # pass ##### Behaviour vacuumOnBehaviour ##### ##### Terminal condition ##### def terminalCondition_vacuumOnBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour vacuumOnBehaviour] -- Checking Terminal Condition") return True pass ##### Error condition ##### def errorCondition_vacuumOnBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour vacuumOnBehaviour] -- Checking Error Condition") return False pass ##### Transition function ##### def transitionFunction_vacuumOnBehaviour(self): self.log("[Behaviour vacuumOnBehaviour] -- Calculating Transition Function") # Transition function # self.log("TRANSITION FUNCTION - vacuumOnBehaviour consists of the following partial transition functions (decomposition based on output buffers)") # Partial transition function call: fun1 self.transitionFunction_vacuumOnBehaviour_fun1() # Partial transition function call: set_buffer_flags_function self.transitionFunction_vacuumOnBehaviour_set_buffer_flags_function() pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_vacuumOnBehaviour_fun1(self): self.log("[Behaviour vacuumOnBehaviour] -- Calculating Partial Transition Function fun1") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - vacuumOnBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_vacuumOnBehaviour_fun1_0() pass ##### Partial transition function: fun1_0 based on input buffers True ##### def transitionFunction_vacuumOnBehaviour_fun1_0(self): self.log("[Behaviour vacuumOnBehaviour] -- Calculating Partial Transition Function fun1_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - vacuumOnBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code self._out_flag_taskStatus=True self._out_flag_desiredRobotCommandTele=True print("[CS - teleoperated] -- vacuumOnBehaviour") self.desiredRobotCommandTele.data="vacuum turn on" self.taskStatus.data="task status: vacuum turn on" # End - Partial Transition Function Code pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_vacuumOnBehaviour_set_buffer_flags_function(self): self.log("[Behaviour vacuumOnBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - vacuumOnBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_vacuumOnBehaviour_set_buffer_flags_function_0() pass ##### Partial transition function: set_buffer_flags_function_0 based on input buffers True ##### def transitionFunction_vacuumOnBehaviour_set_buffer_flags_function_0(self): self.log("[Behaviour vacuumOnBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - vacuumOnBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code # End - Partial Transition Function Code pass ##### End of transition function ##### ##### Send data to other subsystems ##### def sendData_vacuumOnBehaviour(self): self.log("[Behaviour vacuumOnBehaviour] -- Sending Data") # DIAGNOSTICS SEND # self.sendDataForDiagnostics() # END OF DIAGNOSTICS SEND # # TYPICAL SEND CALL # # check if output buffer taskStatus has new data - i.e. is ready to send new data if( self._out_flag_taskStatus ): # send data from output buffer taskStatus # Buffer taskStatus - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_taskStatus.publish(self.taskStatus) # sending data from output buffer taskStatus # # indicate that data was sent and now the output buffer taskStatus is empty self._out_flag_taskStatus=False # check if output buffer desiredRobotCommandTele has new data - i.e. is ready to send new data if( self._out_flag_desiredRobotCommandTele ): # send data from output buffer desiredRobotCommandTele # Buffer desiredRobotCommandTele - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_desiredRobotCommandTele.publish(self.desiredRobotCommandTele) # sending data from output buffer desiredRobotCommandTele # # indicate that data was sent and now the output buffer desiredRobotCommandTele is empty self._out_flag_desiredRobotCommandTele=False # END OF TYPICAL SEND CALL # # BEGIN OF BODY SEND CALL # # END OF BODY SEND CALL # pass ##### Receive data from other subsystems ##### def receiveData_vacuumOnBehaviour(self): self.log("[Behaviour vacuumOnBehaviour] -- Receiving Data") # TYPICAL RECEIVE CALL # # Buffer taskCommand - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer taskCommand # Buffer ballInfoTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballInfoTele # Buffer obstacleDetectedTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer obstacleDetectedTele # Buffer ballCollected - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballCollected self.waitForAllMessages() # # END OF TYPICAL RECEIVE CALL # # BEGIN OF RECEIVE BODY CALL # # END OF RECEIVE BODY CALL # pass ##### Execute behaviour vacuumOnBehaviour ##### def executeBehaviour_vacuumOnBehaviour(self): self.log("[Behaviour vacuumOnBehaviour] -- Executing vacuumOnBehaviour Behaviour") stopBehaviourIteration=False # Execution of a single iteration of a behaviour vacuumOnBehaviour # _behaviourIterations=0 # Starts execution! # while True: # Sleep is a method from class AuxiliaryFunctions which executes sleep from ROS # self.auxiliaryFunctions.sleep() # Calculates transition function -- output and internal buffers can only be modified by this function! # self.transitionFunction_vacuumOnBehaviour() # Sends data! # self.sendData_vacuumOnBehaviour() # Updates index! -- i.e. i:i+1 -- increment number of behaviour iterations and number of subsystem iterations # self._behaviourIterations=self._behaviourIterations+1 # Receives data! # self.receiveData_vacuumOnBehaviour() # Check both conditions, i.e. terminal condition and error condition # stopBehaviourIteration = self.terminalCondition_vacuumOnBehaviour() or self.errorCondition_vacuumOnBehaviour() if stopBehaviourIteration or not self.auxiliaryFunctions.isSubsystemOK(): ''' Iterate within the while loop until stopBehaviourIteration is set true, i.e. one of error and terminal condition is fulfilled and isSubsystemOK is true. Otherwise subsystem must have been switched to another state or SIGINT was sent ''' break # Stops execution! # pass ##### Behaviour vacuumOffBehaviour ##### ##### Terminal condition ##### def terminalCondition_vacuumOffBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour vacuumOffBehaviour] -- Checking Terminal Condition") return True pass ##### Error condition ##### def errorCondition_vacuumOffBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour vacuumOffBehaviour] -- Checking Error Condition") return False pass ##### Transition function ##### def transitionFunction_vacuumOffBehaviour(self): self.log("[Behaviour vacuumOffBehaviour] -- Calculating Transition Function") # Transition function # self.log("TRANSITION FUNCTION - vacuumOffBehaviour consists of the following partial transition functions (decomposition based on output buffers)") # Partial transition function call: fun1 self.transitionFunction_vacuumOffBehaviour_fun1() # Partial transition function call: set_buffer_flags_function self.transitionFunction_vacuumOffBehaviour_set_buffer_flags_function() pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_vacuumOffBehaviour_fun1(self): self.log("[Behaviour vacuumOffBehaviour] -- Calculating Partial Transition Function fun1") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - vacuumOffBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_vacuumOffBehaviour_fun1_0() pass ##### Partial transition function: fun1_0 based on input buffers True ##### def transitionFunction_vacuumOffBehaviour_fun1_0(self): self.log("[Behaviour vacuumOffBehaviour] -- Calculating Partial Transition Function fun1_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - vacuumOffBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code self._out_flag_taskStatus=True self._out_flag_desiredRobotCommandTele=True print("[CS - teleoperated] -- vacuumOffBehaviour") self.desiredRobotCommandTele.data="vacuum off" self.taskStatus.data="task status: vacuum off" # End - Partial Transition Function Code pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_vacuumOffBehaviour_set_buffer_flags_function(self): self.log("[Behaviour vacuumOffBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - vacuumOffBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_vacuumOffBehaviour_set_buffer_flags_function_0() pass ##### Partial transition function: set_buffer_flags_function_0 based on input buffers True ##### def transitionFunction_vacuumOffBehaviour_set_buffer_flags_function_0(self): self.log("[Behaviour vacuumOffBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - vacuumOffBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code # End - Partial Transition Function Code pass ##### End of transition function ##### ##### Send data to other subsystems ##### def sendData_vacuumOffBehaviour(self): self.log("[Behaviour vacuumOffBehaviour] -- Sending Data") # DIAGNOSTICS SEND # self.sendDataForDiagnostics() # END OF DIAGNOSTICS SEND # # TYPICAL SEND CALL # # check if output buffer taskStatus has new data - i.e. is ready to send new data if( self._out_flag_taskStatus ): # send data from output buffer taskStatus # Buffer taskStatus - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_taskStatus.publish(self.taskStatus) # sending data from output buffer taskStatus # # indicate that data was sent and now the output buffer taskStatus is empty self._out_flag_taskStatus=False # check if output buffer desiredRobotCommandTele has new data - i.e. is ready to send new data if( self._out_flag_desiredRobotCommandTele ): # send data from output buffer desiredRobotCommandTele # Buffer desiredRobotCommandTele - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_desiredRobotCommandTele.publish(self.desiredRobotCommandTele) # sending data from output buffer desiredRobotCommandTele # # indicate that data was sent and now the output buffer desiredRobotCommandTele is empty self._out_flag_desiredRobotCommandTele=False # END OF TYPICAL SEND CALL # # BEGIN OF BODY SEND CALL # # END OF BODY SEND CALL # pass ##### Receive data from other subsystems ##### def receiveData_vacuumOffBehaviour(self): self.log("[Behaviour vacuumOffBehaviour] -- Receiving Data") # TYPICAL RECEIVE CALL # # Buffer taskCommand - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer taskCommand # Buffer ballInfoTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballInfoTele # Buffer obstacleDetectedTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer obstacleDetectedTele # Buffer ballCollected - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballCollected self.waitForAllMessages() # # END OF TYPICAL RECEIVE CALL # # BEGIN OF RECEIVE BODY CALL # # END OF RECEIVE BODY CALL # pass ##### Execute behaviour vacuumOffBehaviour ##### def executeBehaviour_vacuumOffBehaviour(self): self.log("[Behaviour vacuumOffBehaviour] -- Executing vacuumOffBehaviour Behaviour") stopBehaviourIteration=False # Execution of a single iteration of a behaviour vacuumOffBehaviour # _behaviourIterations=0 # Starts execution! # while True: # Sleep is a method from class AuxiliaryFunctions which executes sleep from ROS # self.auxiliaryFunctions.sleep() # Calculates transition function -- output and internal buffers can only be modified by this function! # self.transitionFunction_vacuumOffBehaviour() # Sends data! # self.sendData_vacuumOffBehaviour() # Updates index! -- i.e. i:i+1 -- increment number of behaviour iterations and number of subsystem iterations # self._behaviourIterations=self._behaviourIterations+1 # Receives data! # self.receiveData_vacuumOffBehaviour() # Check both conditions, i.e. terminal condition and error condition # stopBehaviourIteration = self.terminalCondition_vacuumOffBehaviour() or self.errorCondition_vacuumOffBehaviour() if stopBehaviourIteration or not self.auxiliaryFunctions.isSubsystemOK(): ''' Iterate within the while loop until stopBehaviourIteration is set true, i.e. one of error and terminal condition is fulfilled and isSubsystemOK is true. Otherwise subsystem must have been switched to another state or SIGINT was sent ''' break # Stops execution! # pass ##### Behaviour moveBackwardBehaviour ##### ##### Terminal condition ##### def terminalCondition_moveBackwardBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour moveBackwardBehaviour] -- Checking Terminal Condition") return True pass ##### Error condition ##### def errorCondition_moveBackwardBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour moveBackwardBehaviour] -- Checking Error Condition") return False pass ##### Transition function ##### def transitionFunction_moveBackwardBehaviour(self): self.log("[Behaviour moveBackwardBehaviour] -- Calculating Transition Function") # Transition function # self.log("TRANSITION FUNCTION - moveBackwardBehaviour consists of the following partial transition functions (decomposition based on output buffers)") # Partial transition function call: fun1 self.transitionFunction_moveBackwardBehaviour_fun1() # Partial transition function call: set_buffer_flags_function self.transitionFunction_moveBackwardBehaviour_set_buffer_flags_function() pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_moveBackwardBehaviour_fun1(self): self.log("[Behaviour moveBackwardBehaviour] -- Calculating Partial Transition Function fun1") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - moveBackwardBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_moveBackwardBehaviour_fun1_0() pass ##### Partial transition function: fun1_0 based on input buffers True ##### def transitionFunction_moveBackwardBehaviour_fun1_0(self): self.log("[Behaviour moveBackwardBehaviour] -- Calculating Partial Transition Function fun1_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - moveBackwardBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code self._out_flag_taskStatus=True self._out_flag_desiredRobotCommandTele=True print("[CS - teleoperated] -- moveBackwardBehaviour") self.desiredRobotCommandTele.data="move backwards" self.taskStatus.data="task status: move backwards" # End - Partial Transition Function Code pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_moveBackwardBehaviour_set_buffer_flags_function(self): self.log("[Behaviour moveBackwardBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - moveBackwardBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_moveBackwardBehaviour_set_buffer_flags_function_0() pass ##### Partial transition function: set_buffer_flags_function_0 based on input buffers True ##### def transitionFunction_moveBackwardBehaviour_set_buffer_flags_function_0(self): self.log("[Behaviour moveBackwardBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - moveBackwardBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code # End - Partial Transition Function Code pass ##### End of transition function ##### ##### Send data to other subsystems ##### def sendData_moveBackwardBehaviour(self): self.log("[Behaviour moveBackwardBehaviour] -- Sending Data") # DIAGNOSTICS SEND # self.sendDataForDiagnostics() # END OF DIAGNOSTICS SEND # # TYPICAL SEND CALL # # check if output buffer taskStatus has new data - i.e. is ready to send new data if( self._out_flag_taskStatus ): # send data from output buffer taskStatus # Buffer taskStatus - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_taskStatus.publish(self.taskStatus) # sending data from output buffer taskStatus # # indicate that data was sent and now the output buffer taskStatus is empty self._out_flag_taskStatus=False # check if output buffer desiredRobotCommandTele has new data - i.e. is ready to send new data if( self._out_flag_desiredRobotCommandTele ): # send data from output buffer desiredRobotCommandTele # Buffer desiredRobotCommandTele - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_desiredRobotCommandTele.publish(self.desiredRobotCommandTele) # sending data from output buffer desiredRobotCommandTele # # indicate that data was sent and now the output buffer desiredRobotCommandTele is empty self._out_flag_desiredRobotCommandTele=False # END OF TYPICAL SEND CALL # # BEGIN OF BODY SEND CALL # # END OF BODY SEND CALL # pass ##### Receive data from other subsystems ##### def receiveData_moveBackwardBehaviour(self): self.log("[Behaviour moveBackwardBehaviour] -- Receiving Data") # TYPICAL RECEIVE CALL # # Buffer taskCommand - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer taskCommand # Buffer ballInfoTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballInfoTele # Buffer obstacleDetectedTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer obstacleDetectedTele # Buffer ballCollected - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballCollected self.waitForAllMessages() # # END OF TYPICAL RECEIVE CALL # # BEGIN OF RECEIVE BODY CALL # # END OF RECEIVE BODY CALL # pass ##### Execute behaviour moveBackwardBehaviour ##### def executeBehaviour_moveBackwardBehaviour(self): self.log("[Behaviour moveBackwardBehaviour] -- Executing moveBackwardBehaviour Behaviour") stopBehaviourIteration=False # Execution of a single iteration of a behaviour moveBackwardBehaviour # _behaviourIterations=0 # Starts execution! # while True: # Sleep is a method from class AuxiliaryFunctions which executes sleep from ROS # self.auxiliaryFunctions.sleep() # Calculates transition function -- output and internal buffers can only be modified by this function! # self.transitionFunction_moveBackwardBehaviour() # Sends data! # self.sendData_moveBackwardBehaviour() # Updates index! -- i.e. i:i+1 -- increment number of behaviour iterations and number of subsystem iterations # self._behaviourIterations=self._behaviourIterations+1 # Receives data! # self.receiveData_moveBackwardBehaviour() # Check both conditions, i.e. terminal condition and error condition # stopBehaviourIteration = self.terminalCondition_moveBackwardBehaviour() or self.errorCondition_moveBackwardBehaviour() if stopBehaviourIteration or not self.auxiliaryFunctions.isSubsystemOK(): ''' Iterate within the while loop until stopBehaviourIteration is set true, i.e. one of error and terminal condition is fulfilled and isSubsystemOK is true. Otherwise subsystem must have been switched to another state or SIGINT was sent ''' break # Stops execution! # pass ##### Behaviour moveFrontBehaviour ##### ##### Terminal condition ##### def terminalCondition_moveFrontBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour moveFrontBehaviour] -- Checking Terminal Condition") return True pass ##### Error condition ##### def errorCondition_moveFrontBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour moveFrontBehaviour] -- Checking Error Condition") return False pass ##### Transition function ##### def transitionFunction_moveFrontBehaviour(self): self.log("[Behaviour moveFrontBehaviour] -- Calculating Transition Function") # Transition function # self.log("TRANSITION FUNCTION - moveFrontBehaviour consists of the following partial transition functions (decomposition based on output buffers)") # Partial transition function call: fun1 self.transitionFunction_moveFrontBehaviour_fun1() # Partial transition function call: set_buffer_flags_function self.transitionFunction_moveFrontBehaviour_set_buffer_flags_function() pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_moveFrontBehaviour_fun1(self): self.log("[Behaviour moveFrontBehaviour] -- Calculating Partial Transition Function fun1") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - moveFrontBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_moveFrontBehaviour_fun1_0() pass ##### Partial transition function: fun1_0 based on input buffers True ##### def transitionFunction_moveFrontBehaviour_fun1_0(self): self.log("[Behaviour moveFrontBehaviour] -- Calculating Partial Transition Function fun1_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - moveFrontBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code self._out_flag_taskStatus=True self._out_flag_desiredRobotCommandTele=True print("[CS - teleoperated] -- moveFrontBehaviour") self.desiredRobotCommandTele.data="move front" self.taskStatus.data="task status: move front" # End - Partial Transition Function Code pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_moveFrontBehaviour_set_buffer_flags_function(self): self.log("[Behaviour moveFrontBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - moveFrontBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_moveFrontBehaviour_set_buffer_flags_function_0() pass ##### Partial transition function: set_buffer_flags_function_0 based on input buffers True ##### def transitionFunction_moveFrontBehaviour_set_buffer_flags_function_0(self): self.log("[Behaviour moveFrontBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - moveFrontBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code # End - Partial Transition Function Code pass ##### End of transition function ##### ##### Send data to other subsystems ##### def sendData_moveFrontBehaviour(self): self.log("[Behaviour moveFrontBehaviour] -- Sending Data") # DIAGNOSTICS SEND # self.sendDataForDiagnostics() # END OF DIAGNOSTICS SEND # # TYPICAL SEND CALL # # check if output buffer taskStatus has new data - i.e. is ready to send new data if( self._out_flag_taskStatus ): # send data from output buffer taskStatus # Buffer taskStatus - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_taskStatus.publish(self.taskStatus) # sending data from output buffer taskStatus # # indicate that data was sent and now the output buffer taskStatus is empty self._out_flag_taskStatus=False # check if output buffer desiredRobotCommandTele has new data - i.e. is ready to send new data if( self._out_flag_desiredRobotCommandTele ): # send data from output buffer desiredRobotCommandTele # Buffer desiredRobotCommandTele - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_desiredRobotCommandTele.publish(self.desiredRobotCommandTele) # sending data from output buffer desiredRobotCommandTele # # indicate that data was sent and now the output buffer desiredRobotCommandTele is empty self._out_flag_desiredRobotCommandTele=False # END OF TYPICAL SEND CALL # # BEGIN OF BODY SEND CALL # # END OF BODY SEND CALL # pass ##### Receive data from other subsystems ##### def receiveData_moveFrontBehaviour(self): self.log("[Behaviour moveFrontBehaviour] -- Receiving Data") # TYPICAL RECEIVE CALL # # Buffer taskCommand - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer taskCommand # Buffer ballInfoTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballInfoTele # Buffer obstacleDetectedTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer obstacleDetectedTele # Buffer ballCollected - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballCollected self.waitForAllMessages() # # END OF TYPICAL RECEIVE CALL # # BEGIN OF RECEIVE BODY CALL # # END OF RECEIVE BODY CALL # pass ##### Execute behaviour moveFrontBehaviour ##### def executeBehaviour_moveFrontBehaviour(self): self.log("[Behaviour moveFrontBehaviour] -- Executing moveFrontBehaviour Behaviour") stopBehaviourIteration=False # Execution of a single iteration of a behaviour moveFrontBehaviour # _behaviourIterations=0 # Starts execution! # while True: # Sleep is a method from class AuxiliaryFunctions which executes sleep from ROS # self.auxiliaryFunctions.sleep() # Calculates transition function -- output and internal buffers can only be modified by this function! # self.transitionFunction_moveFrontBehaviour() # Sends data! # self.sendData_moveFrontBehaviour() # Updates index! -- i.e. i:i+1 -- increment number of behaviour iterations and number of subsystem iterations # self._behaviourIterations=self._behaviourIterations+1 # Receives data! # self.receiveData_moveFrontBehaviour() # Check both conditions, i.e. terminal condition and error condition # stopBehaviourIteration = self.terminalCondition_moveFrontBehaviour() or self.errorCondition_moveFrontBehaviour() if stopBehaviourIteration or not self.auxiliaryFunctions.isSubsystemOK(): ''' Iterate within the while loop until stopBehaviourIteration is set true, i.e. one of error and terminal condition is fulfilled and isSubsystemOK is true. Otherwise subsystem must have been switched to another state or SIGINT was sent ''' break # Stops execution! # pass ##### Behaviour moveRightBehaviour ##### ##### Terminal condition ##### def terminalCondition_moveRightBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour moveRightBehaviour] -- Checking Terminal Condition") return True pass ##### Error condition ##### def errorCondition_moveRightBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour moveRightBehaviour] -- Checking Error Condition") return False pass ##### Transition function ##### def transitionFunction_moveRightBehaviour(self): self.log("[Behaviour moveRightBehaviour] -- Calculating Transition Function") # Transition function # self.log("TRANSITION FUNCTION - moveRightBehaviour consists of the following partial transition functions (decomposition based on output buffers)") # Partial transition function call: fun1 self.transitionFunction_moveRightBehaviour_fun1() # Partial transition function call: set_buffer_flags_function self.transitionFunction_moveRightBehaviour_set_buffer_flags_function() pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_moveRightBehaviour_fun1(self): self.log("[Behaviour moveRightBehaviour] -- Calculating Partial Transition Function fun1") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - moveRightBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_moveRightBehaviour_fun1_0() pass ##### Partial transition function: fun1_0 based on input buffers True ##### def transitionFunction_moveRightBehaviour_fun1_0(self): self.log("[Behaviour moveRightBehaviour] -- Calculating Partial Transition Function fun1_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - moveRightBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code self._out_flag_desiredRobotCommandTele=True self._out_flag_taskStatus=True print("[CS - teleoperated] -- moveRightBehaviour") self.desiredRobotCommandTele.data="move right" self.taskStatus.data="task status: move right" # End - Partial Transition Function Code pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_moveRightBehaviour_set_buffer_flags_function(self): self.log("[Behaviour moveRightBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - moveRightBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_moveRightBehaviour_set_buffer_flags_function_0() pass ##### Partial transition function: set_buffer_flags_function_0 based on input buffers True ##### def transitionFunction_moveRightBehaviour_set_buffer_flags_function_0(self): self.log("[Behaviour moveRightBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - moveRightBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code # End - Partial Transition Function Code pass ##### End of transition function ##### ##### Send data to other subsystems ##### def sendData_moveRightBehaviour(self): self.log("[Behaviour moveRightBehaviour] -- Sending Data") # DIAGNOSTICS SEND # self.sendDataForDiagnostics() # END OF DIAGNOSTICS SEND # # TYPICAL SEND CALL # # check if output buffer taskStatus has new data - i.e. is ready to send new data if( self._out_flag_taskStatus ): # send data from output buffer taskStatus # Buffer taskStatus - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_taskStatus.publish(self.taskStatus) # sending data from output buffer taskStatus # # indicate that data was sent and now the output buffer taskStatus is empty self._out_flag_taskStatus=False # check if output buffer desiredRobotCommandTele has new data - i.e. is ready to send new data if( self._out_flag_desiredRobotCommandTele ): # send data from output buffer desiredRobotCommandTele # Buffer desiredRobotCommandTele - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_desiredRobotCommandTele.publish(self.desiredRobotCommandTele) # sending data from output buffer desiredRobotCommandTele # # indicate that data was sent and now the output buffer desiredRobotCommandTele is empty self._out_flag_desiredRobotCommandTele=False # END OF TYPICAL SEND CALL # # BEGIN OF BODY SEND CALL # # END OF BODY SEND CALL # pass ##### Receive data from other subsystems ##### def receiveData_moveRightBehaviour(self): self.log("[Behaviour moveRightBehaviour] -- Receiving Data") # TYPICAL RECEIVE CALL # # Buffer taskCommand - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer taskCommand # Buffer ballInfoTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballInfoTele # Buffer obstacleDetectedTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer obstacleDetectedTele # Buffer ballCollected - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballCollected self.waitForAllMessages() # # END OF TYPICAL RECEIVE CALL # # BEGIN OF RECEIVE BODY CALL # # END OF RECEIVE BODY CALL # pass ##### Execute behaviour moveRightBehaviour ##### def executeBehaviour_moveRightBehaviour(self): self.log("[Behaviour moveRightBehaviour] -- Executing moveRightBehaviour Behaviour") stopBehaviourIteration=False # Execution of a single iteration of a behaviour moveRightBehaviour # _behaviourIterations=0 # Starts execution! # while True: # Sleep is a method from class AuxiliaryFunctions which executes sleep from ROS # self.auxiliaryFunctions.sleep() # Calculates transition function -- output and internal buffers can only be modified by this function! # self.transitionFunction_moveRightBehaviour() # Sends data! # self.sendData_moveRightBehaviour() # Updates index! -- i.e. i:i+1 -- increment number of behaviour iterations and number of subsystem iterations # self._behaviourIterations=self._behaviourIterations+1 # Receives data! # self.receiveData_moveRightBehaviour() # Check both conditions, i.e. terminal condition and error condition # stopBehaviourIteration = self.terminalCondition_moveRightBehaviour() or self.errorCondition_moveRightBehaviour() if stopBehaviourIteration or not self.auxiliaryFunctions.isSubsystemOK(): ''' Iterate within the while loop until stopBehaviourIteration is set true, i.e. one of error and terminal condition is fulfilled and isSubsystemOK is true. Otherwise subsystem must have been switched to another state or SIGINT was sent ''' break # Stops execution! # pass ##### Behaviour moveLeftBehaviour ##### ##### Terminal condition ##### def terminalCondition_moveLeftBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour moveLeftBehaviour] -- Checking Terminal Condition") return True pass ##### Error condition ##### def errorCondition_moveLeftBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour moveLeftBehaviour] -- Checking Error Condition") return False pass ##### Transition function ##### def transitionFunction_moveLeftBehaviour(self): self.log("[Behaviour moveLeftBehaviour] -- Calculating Transition Function") # Transition function # self.log("TRANSITION FUNCTION - moveLeftBehaviour consists of the following partial transition functions (decomposition based on output buffers)") # Partial transition function call: fun1 self.transitionFunction_moveLeftBehaviour_fun1() # Partial transition function call: set_buffer_flags_function self.transitionFunction_moveLeftBehaviour_set_buffer_flags_function() pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_moveLeftBehaviour_fun1(self): self.log("[Behaviour moveLeftBehaviour] -- Calculating Partial Transition Function fun1") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - moveLeftBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_moveLeftBehaviour_fun1_0() pass ##### Partial transition function: fun1_0 based on input buffers True ##### def transitionFunction_moveLeftBehaviour_fun1_0(self): self.log("[Behaviour moveLeftBehaviour] -- Calculating Partial Transition Function fun1_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - moveLeftBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code self._out_flag_taskStatus=True self._out_flag_desiredRobotCommandTele=True print("[CS - teleoperated] -- moveLeftBehaviour") self.desiredRobotCommandTele.data="move left" self.taskStatus.data="task status: move left" # End - Partial Transition Function Code pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_moveLeftBehaviour_set_buffer_flags_function(self): self.log("[Behaviour moveLeftBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - moveLeftBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_moveLeftBehaviour_set_buffer_flags_function_0() pass ##### Partial transition function: set_buffer_flags_function_0 based on input buffers True ##### def transitionFunction_moveLeftBehaviour_set_buffer_flags_function_0(self): self.log("[Behaviour moveLeftBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - moveLeftBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code # End - Partial Transition Function Code pass ##### End of transition function ##### ##### Send data to other subsystems ##### def sendData_moveLeftBehaviour(self): self.log("[Behaviour moveLeftBehaviour] -- Sending Data") # DIAGNOSTICS SEND # self.sendDataForDiagnostics() # END OF DIAGNOSTICS SEND # # TYPICAL SEND CALL # # check if output buffer taskStatus has new data - i.e. is ready to send new data if( self._out_flag_taskStatus ): # send data from output buffer taskStatus # Buffer taskStatus - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_taskStatus.publish(self.taskStatus) # sending data from output buffer taskStatus # # indicate that data was sent and now the output buffer taskStatus is empty self._out_flag_taskStatus=False # check if output buffer desiredRobotCommandTele has new data - i.e. is ready to send new data if( self._out_flag_desiredRobotCommandTele ): # send data from output buffer desiredRobotCommandTele # Buffer desiredRobotCommandTele - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_desiredRobotCommandTele.publish(self.desiredRobotCommandTele) # sending data from output buffer desiredRobotCommandTele # # indicate that data was sent and now the output buffer desiredRobotCommandTele is empty self._out_flag_desiredRobotCommandTele=False # END OF TYPICAL SEND CALL # # BEGIN OF BODY SEND CALL # # END OF BODY SEND CALL # pass ##### Receive data from other subsystems ##### def receiveData_moveLeftBehaviour(self): self.log("[Behaviour moveLeftBehaviour] -- Receiving Data") # TYPICAL RECEIVE CALL # # Buffer taskCommand - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer taskCommand # Buffer ballInfoTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballInfoTele # Buffer obstacleDetectedTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer obstacleDetectedTele # Buffer ballCollected - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballCollected self.waitForAllMessages() # # END OF TYPICAL RECEIVE CALL # # BEGIN OF RECEIVE BODY CALL # # END OF RECEIVE BODY CALL # pass ##### Execute behaviour moveLeftBehaviour ##### def executeBehaviour_moveLeftBehaviour(self): self.log("[Behaviour moveLeftBehaviour] -- Executing moveLeftBehaviour Behaviour") stopBehaviourIteration=False # Execution of a single iteration of a behaviour moveLeftBehaviour # _behaviourIterations=0 # Starts execution! # while True: # Sleep is a method from class AuxiliaryFunctions which executes sleep from ROS # self.auxiliaryFunctions.sleep() # Calculates transition function -- output and internal buffers can only be modified by this function! # self.transitionFunction_moveLeftBehaviour() # Sends data! # self.sendData_moveLeftBehaviour() # Updates index! -- i.e. i:i+1 -- increment number of behaviour iterations and number of subsystem iterations # self._behaviourIterations=self._behaviourIterations+1 # Receives data! # self.receiveData_moveLeftBehaviour() # Check both conditions, i.e. terminal condition and error condition # stopBehaviourIteration = self.terminalCondition_moveLeftBehaviour() or self.errorCondition_moveLeftBehaviour() if stopBehaviourIteration or not self.auxiliaryFunctions.isSubsystemOK(): ''' Iterate within the while loop until stopBehaviourIteration is set true, i.e. one of error and terminal condition is fulfilled and isSubsystemOK is true. Otherwise subsystem must have been switched to another state or SIGINT was sent ''' break # Stops execution! # pass ##### Behaviour rotateLeftBehaviour ##### ##### Terminal condition ##### def terminalCondition_rotateLeftBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour rotateLeftBehaviour] -- Checking Terminal Condition") return True pass ##### Error condition ##### def errorCondition_rotateLeftBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour rotateLeftBehaviour] -- Checking Error Condition") return False pass ##### Transition function ##### def transitionFunction_rotateLeftBehaviour(self): self.log("[Behaviour rotateLeftBehaviour] -- Calculating Transition Function") # Transition function # self.log("TRANSITION FUNCTION - rotateLeftBehaviour consists of the following partial transition functions (decomposition based on output buffers)") # Partial transition function call: fun1 self.transitionFunction_rotateLeftBehaviour_fun1() # Partial transition function call: set_buffer_flags_function self.transitionFunction_rotateLeftBehaviour_set_buffer_flags_function() pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_rotateLeftBehaviour_fun1(self): self.log("[Behaviour rotateLeftBehaviour] -- Calculating Partial Transition Function fun1") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - rotateLeftBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_rotateLeftBehaviour_fun1_0() pass ##### Partial transition function: fun1_0 based on input buffers True ##### def transitionFunction_rotateLeftBehaviour_fun1_0(self): self.log("[Behaviour rotateLeftBehaviour] -- Calculating Partial Transition Function fun1_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - rotateLeftBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code self._out_flag_taskStatus=True self._out_flag_desiredRobotCommandTele=True print("[CS - teleoperated] -- rotateLeftBehaviour") self.desiredRobotCommandTele.data="rotate left" self.taskStatus.data="task status: rotate left" # End - Partial Transition Function Code pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_rotateLeftBehaviour_set_buffer_flags_function(self): self.log("[Behaviour rotateLeftBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - rotateLeftBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_rotateLeftBehaviour_set_buffer_flags_function_0() pass ##### Partial transition function: set_buffer_flags_function_0 based on input buffers True ##### def transitionFunction_rotateLeftBehaviour_set_buffer_flags_function_0(self): self.log("[Behaviour rotateLeftBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - rotateLeftBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code # End - Partial Transition Function Code pass ##### End of transition function ##### ##### Send data to other subsystems ##### def sendData_rotateLeftBehaviour(self): self.log("[Behaviour rotateLeftBehaviour] -- Sending Data") # DIAGNOSTICS SEND # self.sendDataForDiagnostics() # END OF DIAGNOSTICS SEND # # TYPICAL SEND CALL # # check if output buffer taskStatus has new data - i.e. is ready to send new data if( self._out_flag_taskStatus ): # send data from output buffer taskStatus # Buffer taskStatus - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_taskStatus.publish(self.taskStatus) # sending data from output buffer taskStatus # # indicate that data was sent and now the output buffer taskStatus is empty self._out_flag_taskStatus=False # check if output buffer desiredRobotCommandTele has new data - i.e. is ready to send new data if( self._out_flag_desiredRobotCommandTele ): # send data from output buffer desiredRobotCommandTele # Buffer desiredRobotCommandTele - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_desiredRobotCommandTele.publish(self.desiredRobotCommandTele) # sending data from output buffer desiredRobotCommandTele # # indicate that data was sent and now the output buffer desiredRobotCommandTele is empty self._out_flag_desiredRobotCommandTele=False # END OF TYPICAL SEND CALL # # BEGIN OF BODY SEND CALL # # END OF BODY SEND CALL # pass ##### Receive data from other subsystems ##### def receiveData_rotateLeftBehaviour(self): self.log("[Behaviour rotateLeftBehaviour] -- Receiving Data") # TYPICAL RECEIVE CALL # # Buffer taskCommand - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer taskCommand # Buffer ballInfoTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballInfoTele # Buffer obstacleDetectedTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer obstacleDetectedTele # Buffer ballCollected - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballCollected self.waitForAllMessages() # # END OF TYPICAL RECEIVE CALL # # BEGIN OF RECEIVE BODY CALL # # END OF RECEIVE BODY CALL # pass ##### Execute behaviour rotateLeftBehaviour ##### def executeBehaviour_rotateLeftBehaviour(self): self.log("[Behaviour rotateLeftBehaviour] -- Executing rotateLeftBehaviour Behaviour") stopBehaviourIteration=False # Execution of a single iteration of a behaviour rotateLeftBehaviour # _behaviourIterations=0 # Starts execution! # while True: # Sleep is a method from class AuxiliaryFunctions which executes sleep from ROS # self.auxiliaryFunctions.sleep() # Calculates transition function -- output and internal buffers can only be modified by this function! # self.transitionFunction_rotateLeftBehaviour() # Sends data! # self.sendData_rotateLeftBehaviour() # Updates index! -- i.e. i:i+1 -- increment number of behaviour iterations and number of subsystem iterations # self._behaviourIterations=self._behaviourIterations+1 # Receives data! # self.receiveData_rotateLeftBehaviour() # Check both conditions, i.e. terminal condition and error condition # stopBehaviourIteration = self.terminalCondition_rotateLeftBehaviour() or self.errorCondition_rotateLeftBehaviour() if stopBehaviourIteration or not self.auxiliaryFunctions.isSubsystemOK(): ''' Iterate within the while loop until stopBehaviourIteration is set true, i.e. one of error and terminal condition is fulfilled and isSubsystemOK is true. Otherwise subsystem must have been switched to another state or SIGINT was sent ''' break # Stops execution! # pass ##### Behaviour rotateRightBehaviour ##### ##### Terminal condition ##### def terminalCondition_rotateRightBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour rotateRightBehaviour] -- Checking Terminal Condition") return True pass ##### Error condition ##### def errorCondition_rotateRightBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour rotateRightBehaviour] -- Checking Error Condition") return False pass ##### Transition function ##### def transitionFunction_rotateRightBehaviour(self): self.log("[Behaviour rotateRightBehaviour] -- Calculating Transition Function") # Transition function # self.log("TRANSITION FUNCTION - rotateRightBehaviour consists of the following partial transition functions (decomposition based on output buffers)") # Partial transition function call: fun1 self.transitionFunction_rotateRightBehaviour_fun1() # Partial transition function call: set_buffer_flags_function self.transitionFunction_rotateRightBehaviour_set_buffer_flags_function() pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_rotateRightBehaviour_fun1(self): self.log("[Behaviour rotateRightBehaviour] -- Calculating Partial Transition Function fun1") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - rotateRightBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_rotateRightBehaviour_fun1_0() pass ##### Partial transition function: fun1_0 based on input buffers True ##### def transitionFunction_rotateRightBehaviour_fun1_0(self): self.log("[Behaviour rotateRightBehaviour] -- Calculating Partial Transition Function fun1_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - rotateRightBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code self._out_flag_taskStatus=True self._out_flag_desiredRobotCommandTele=True print("[CS - teleoperated] -- rotateRightBehaviour") self.desiredRobotCommandTele.data="rotate right" self.taskStatus.data="task status: rotate right" # End - Partial Transition Function Code pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_rotateRightBehaviour_set_buffer_flags_function(self): self.log("[Behaviour rotateRightBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - rotateRightBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_rotateRightBehaviour_set_buffer_flags_function_0() pass ##### Partial transition function: set_buffer_flags_function_0 based on input buffers True ##### def transitionFunction_rotateRightBehaviour_set_buffer_flags_function_0(self): self.log("[Behaviour rotateRightBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - rotateRightBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code # End - Partial Transition Function Code pass ##### End of transition function ##### ##### Send data to other subsystems ##### def sendData_rotateRightBehaviour(self): self.log("[Behaviour rotateRightBehaviour] -- Sending Data") # DIAGNOSTICS SEND # self.sendDataForDiagnostics() # END OF DIAGNOSTICS SEND # # TYPICAL SEND CALL # # check if output buffer taskStatus has new data - i.e. is ready to send new data if( self._out_flag_taskStatus ): # send data from output buffer taskStatus # Buffer taskStatus - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_taskStatus.publish(self.taskStatus) # sending data from output buffer taskStatus # # indicate that data was sent and now the output buffer taskStatus is empty self._out_flag_taskStatus=False # check if output buffer desiredRobotCommandTele has new data - i.e. is ready to send new data if( self._out_flag_desiredRobotCommandTele ): # send data from output buffer desiredRobotCommandTele # Buffer desiredRobotCommandTele - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_desiredRobotCommandTele.publish(self.desiredRobotCommandTele) # sending data from output buffer desiredRobotCommandTele # # indicate that data was sent and now the output buffer desiredRobotCommandTele is empty self._out_flag_desiredRobotCommandTele=False # END OF TYPICAL SEND CALL # # BEGIN OF BODY SEND CALL # # END OF BODY SEND CALL # pass ##### Receive data from other subsystems ##### def receiveData_rotateRightBehaviour(self): self.log("[Behaviour rotateRightBehaviour] -- Receiving Data") # TYPICAL RECEIVE CALL # # Buffer taskCommand - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer taskCommand # Buffer ballInfoTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballInfoTele # Buffer obstacleDetectedTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer obstacleDetectedTele # Buffer ballCollected - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballCollected self.waitForAllMessages() # # END OF TYPICAL RECEIVE CALL # # BEGIN OF RECEIVE BODY CALL # # END OF RECEIVE BODY CALL # pass ##### Execute behaviour rotateRightBehaviour ##### def executeBehaviour_rotateRightBehaviour(self): self.log("[Behaviour rotateRightBehaviour] -- Executing rotateRightBehaviour Behaviour") stopBehaviourIteration=False # Execution of a single iteration of a behaviour rotateRightBehaviour # _behaviourIterations=0 # Starts execution! # while True: # Sleep is a method from class AuxiliaryFunctions which executes sleep from ROS # self.auxiliaryFunctions.sleep() # Calculates transition function -- output and internal buffers can only be modified by this function! # self.transitionFunction_rotateRightBehaviour() # Sends data! # self.sendData_rotateRightBehaviour() # Updates index! -- i.e. i:i+1 -- increment number of behaviour iterations and number of subsystem iterations # self._behaviourIterations=self._behaviourIterations+1 # Receives data! # self.receiveData_rotateRightBehaviour() # Check both conditions, i.e. terminal condition and error condition # stopBehaviourIteration = self.terminalCondition_rotateRightBehaviour() or self.errorCondition_rotateRightBehaviour() if stopBehaviourIteration or not self.auxiliaryFunctions.isSubsystemOK(): ''' Iterate within the while loop until stopBehaviourIteration is set true, i.e. one of error and terminal condition is fulfilled and isSubsystemOK is true. Otherwise subsystem must have been switched to another state or SIGINT was sent ''' break # Stops execution! # pass ##### Behaviour whatCanYouSeeBehaviour ##### ##### Terminal condition ##### def terminalCondition_whatCanYouSeeBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour whatCanYouSeeBehaviour] -- Checking Terminal Condition") return True pass ##### Error condition ##### def errorCondition_whatCanYouSeeBehaviour(self): # String taskCommand, String robotStatus, CameraMessage ballInfoTele, ObstacleDetected obstacleDetectedTele, Bool ballCollected, Int64 isNewCommandReceived, std_msgs::Bool _in_flag_taskCommand, std_msgs::Bool _in_flag_robotStatus, std_msgs::Bool _in_flag_ballInfoTele, std_msgs::Bool _in_flag_obstacleDetectedTele, std_msgs::Bool _in_flag_ballCollected, std_msgs::Bool _out_flag_taskStatus, std_msgs::Bool _out_flag_desiredRobotCommandTele # self.log("[Behaviour whatCanYouSeeBehaviour] -- Checking Error Condition") return False pass ##### Transition function ##### def transitionFunction_whatCanYouSeeBehaviour(self): self.log("[Behaviour whatCanYouSeeBehaviour] -- Calculating Transition Function") # Transition function # self.log("TRANSITION FUNCTION - whatCanYouSeeBehaviour consists of the following partial transition functions (decomposition based on output buffers)") # Partial transition function call: fun1 self.transitionFunction_whatCanYouSeeBehaviour_fun1() # Partial transition function call: set_buffer_flags_function self.transitionFunction_whatCanYouSeeBehaviour_set_buffer_flags_function() pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_whatCanYouSeeBehaviour_fun1(self): self.log("[Behaviour whatCanYouSeeBehaviour] -- Calculating Partial Transition Function fun1") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - whatCanYouSeeBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_whatCanYouSeeBehaviour_fun1_0() pass ##### Partial transition function: fun1_0 based on input buffers True ##### def transitionFunction_whatCanYouSeeBehaviour_fun1_0(self): self.log("[Behaviour whatCanYouSeeBehaviour] -- Calculating Partial Transition Function fun1_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - whatCanYouSeeBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code self._out_flag_taskStatus=True self._out_flag_desiredRobotCommandTele=True print("[CS - teleoperated] -- whatCanYouSeeBehaviour") self.desiredRobotCommandTele.data="what can you see" self.taskCommand.data="empty" self.taskStatus.data="task status: what can you see" # End - Partial Transition Function Code pass ##### Decomposition of partial transition function based on input buffers ##### def transitionFunction_whatCanYouSeeBehaviour_set_buffer_flags_function(self): self.log("[Behaviour whatCanYouSeeBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function") # Partial Transition Function - the first layer # self.log("PARTIAL TRANSITION FUNCTION - FIRST LAYER - whatCanYouSeeBehaviour consists of the following partial transition functions (decomposition based on input buffers)") if True: self.transitionFunction_whatCanYouSeeBehaviour_set_buffer_flags_function_0() pass ##### Partial transition function: set_buffer_flags_function_0 based on input buffers True ##### def transitionFunction_whatCanYouSeeBehaviour_set_buffer_flags_function_0(self): self.log("[Behaviour whatCanYouSeeBehaviour] -- Calculating Partial Transition Function set_buffer_flags_function_0") # Partial Transition Function - the second layer # self.log("PARTIAL TRANSITION FUNCTION - SECOND LAYER - whatCanYouSeeBehaviour consists of the following partial transition functions (decomposition based on input buffers)") # Begin - Partial Transition Function Code # End - Partial Transition Function Code pass ##### End of transition function ##### ##### Send data to other subsystems ##### def sendData_whatCanYouSeeBehaviour(self): self.log("[Behaviour whatCanYouSeeBehaviour] -- Sending Data") # DIAGNOSTICS SEND # self.sendDataForDiagnostics() # END OF DIAGNOSTICS SEND # # TYPICAL SEND CALL # # check if output buffer taskStatus has new data - i.e. is ready to send new data if( self._out_flag_taskStatus ): # send data from output buffer taskStatus # Buffer taskStatus - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_taskStatus.publish(self.taskStatus) # sending data from output buffer taskStatus # # indicate that data was sent and now the output buffer taskStatus is empty self._out_flag_taskStatus=False # check if output buffer desiredRobotCommandTele has new data - i.e. is ready to send new data if( self._out_flag_desiredRobotCommandTele ): # send data from output buffer desiredRobotCommandTele # Buffer desiredRobotCommandTele - NON-BLOCKING Sender mode - NON-BLOCKING Receiver mode self._sender_desiredRobotCommandTele.publish(self.desiredRobotCommandTele) # sending data from output buffer desiredRobotCommandTele # # indicate that data was sent and now the output buffer desiredRobotCommandTele is empty self._out_flag_desiredRobotCommandTele=False # END OF TYPICAL SEND CALL # # BEGIN OF BODY SEND CALL # # END OF BODY SEND CALL # pass ##### Receive data from other subsystems ##### def receiveData_whatCanYouSeeBehaviour(self): self.log("[Behaviour whatCanYouSeeBehaviour] -- Receiving Data") # TYPICAL RECEIVE CALL # # Buffer taskCommand - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer taskCommand # Buffer ballInfoTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballInfoTele # Buffer obstacleDetectedTele - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer obstacleDetectedTele # Buffer ballCollected - Sender using NON-BLOCKING MODE - Receiver using NON-BLOCKING MODE # ROS topic generated for the input buffer ballCollected self.waitForAllMessages() # # END OF TYPICAL RECEIVE CALL # # BEGIN OF RECEIVE BODY CALL # # END OF RECEIVE BODY CALL # pass ##### Execute behaviour whatCanYouSeeBehaviour ##### def executeBehaviour_whatCanYouSeeBehaviour(self): self.log("[Behaviour whatCanYouSeeBehaviour] -- Executing whatCanYouSeeBehaviour Behaviour") stopBehaviourIteration=False # Execution of a single iteration of a behaviour whatCanYouSeeBehaviour # _behaviourIterations=0 # Starts execution! # while True: # Sleep is a method from class AuxiliaryFunctions which executes sleep from ROS # self.auxiliaryFunctions.sleep() # Calculates transition function -- output and internal buffers can only be modified by this function! # self.transitionFunction_whatCanYouSeeBehaviour() # Sends data! # self.sendData_whatCanYouSeeBehaviour() # Updates index! -- i.e. i:i+1 -- increment number of behaviour iterations and number of subsystem iterations # self._behaviourIterations=self._behaviourIterations+1 # Receives data! # self.receiveData_whatCanYouSeeBehaviour() # Check both conditions, i.e. terminal condition and error condition # stopBehaviourIteration = self.terminalCondition_whatCanYouSeeBehaviour() or self.errorCondition_whatCanYouSeeBehaviour() if stopBehaviourIteration or not self.auxiliaryFunctions.isSubsystemOK(): ''' Iterate within the while loop until stopBehaviourIteration is set true, i.e. one of error and terminal condition is fulfilled and isSubsystemOK is true. Otherwise subsystem must have been switched to another state or SIGINT was sent ''' break # Stops execution! # pass ##### Definition of functions responsible for switching subsystem cs between states : Behaviour_initBehaviour Behaviour_idleBehaviour Behaviour_terminateBehaviour Behaviour_terminatedBehaviour Behaviour_stopBehaviour Behaviour_moveFasterBehaviour Behaviour_moveSlowerBehaviour Behaviour_vacuumOnBehaviour Behaviour_vacuumOffBehaviour Behaviour_moveBackwardBehaviour Behaviour_moveFrontBehaviour Behaviour_moveRightBehaviour Behaviour_moveLeftBehaviour Behaviour_rotateLeftBehaviour Behaviour_rotateRightBehaviour Behaviour_whatCanYouSeeBehaviour ##### # Behaviour initBehaviour: # def subsystemBehaviour_initBehaviour(self): self.log("subsystemBehaviour_initBehaviour") # Executing behaviour initBehaviour # self.executeBehaviour_initBehaviour() # Behaviour has been terminated # # Checking initial condition for behaviour initBehaviour: switching to behaviour idleBehaviour # if self.initialCondition_From_Behaviour_initBehaviour_To_Behaviour_idleBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_idleBehaviour" pass # Behaviour idleBehaviour: # def subsystemBehaviour_idleBehaviour(self): self.log("subsystemBehaviour_idleBehaviour") # Executing behaviour idleBehaviour # self.executeBehaviour_idleBehaviour() # Behaviour has been terminated # # Checking initial condition for behaviour idleBehaviour: switching to behaviour terminateBehaviour # if self.initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_terminateBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_terminateBehaviour" # Checking initial condition for behaviour idleBehaviour: switching to behaviour stopBehaviour # if self.initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_stopBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_stopBehaviour" # Checking initial condition for behaviour idleBehaviour: switching to behaviour moveFasterBehaviour # if self.initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_moveFasterBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_moveFasterBehaviour" # Checking initial condition for behaviour idleBehaviour: switching to behaviour moveSlowerBehaviour # if self.initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_moveSlowerBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_moveSlowerBehaviour" # Checking initial condition for behaviour idleBehaviour: switching to behaviour vacuumOnBehaviour # if self.initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_vacuumOnBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_vacuumOnBehaviour" # Checking initial condition for behaviour idleBehaviour: switching to behaviour vacuumOffBehaviour # if self.initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_vacuumOffBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_vacuumOffBehaviour" # Checking initial condition for behaviour idleBehaviour: switching to behaviour moveBackwardBehaviour # if self.initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_moveBackwardBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_moveBackwardBehaviour" # Checking initial condition for behaviour idleBehaviour: switching to behaviour moveFrontBehaviour # if self.initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_moveFrontBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_moveFrontBehaviour" # Checking initial condition for behaviour idleBehaviour: switching to behaviour moveRightBehaviour # if self.initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_moveRightBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_moveRightBehaviour" # Checking initial condition for behaviour idleBehaviour: switching to behaviour moveLeftBehaviour # if self.initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_moveLeftBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_moveLeftBehaviour" # Checking initial condition for behaviour idleBehaviour: switching to behaviour rotateLeftBehaviour # if self.initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_rotateLeftBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_rotateLeftBehaviour" # Checking initial condition for behaviour idleBehaviour: switching to behaviour rotateRightBehaviour # if self.initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_rotateRightBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_rotateRightBehaviour" # Checking initial condition for behaviour idleBehaviour: switching to behaviour whatCanYouSeeBehaviour # if self.initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_whatCanYouSeeBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_whatCanYouSeeBehaviour" pass # Behaviour terminateBehaviour: # def subsystemBehaviour_terminateBehaviour(self): self.log("subsystemBehaviour_terminateBehaviour") # Executing behaviour terminateBehaviour # self.executeBehaviour_terminateBehaviour() # Behaviour has been terminated # # Checking initial condition for behaviour terminateBehaviour: switching to behaviour terminatedBehaviour # if self.initialCondition_From_Behaviour_terminateBehaviour_To_Behaviour_terminatedBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_terminatedBehaviour" pass # Behaviour terminatedBehaviour: # def subsystemBehaviour_terminatedBehaviour(self): self.log("subsystemBehaviour_terminatedBehaviour") # Executing behaviour terminatedBehaviour # self.executeBehaviour_terminatedBehaviour() # Behaviour has been terminated # pass # Behaviour stopBehaviour: # def subsystemBehaviour_stopBehaviour(self): self.log("subsystemBehaviour_stopBehaviour") # Executing behaviour stopBehaviour # self.executeBehaviour_stopBehaviour() # Behaviour has been terminated # # Checking initial condition for behaviour stopBehaviour: switching to behaviour idleBehaviour # if self.initialCondition_From_Behaviour_stopBehaviour_To_Behaviour_idleBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_idleBehaviour" pass # Behaviour moveFasterBehaviour: # def subsystemBehaviour_moveFasterBehaviour(self): self.log("subsystemBehaviour_moveFasterBehaviour") # Executing behaviour moveFasterBehaviour # self.executeBehaviour_moveFasterBehaviour() # Behaviour has been terminated # # Checking initial condition for behaviour moveFasterBehaviour: switching to behaviour idleBehaviour # if self.initialCondition_From_Behaviour_moveFasterBehaviour_To_Behaviour_idleBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_idleBehaviour" pass # Behaviour moveSlowerBehaviour: # def subsystemBehaviour_moveSlowerBehaviour(self): self.log("subsystemBehaviour_moveSlowerBehaviour") # Executing behaviour moveSlowerBehaviour # self.executeBehaviour_moveSlowerBehaviour() # Behaviour has been terminated # # Checking initial condition for behaviour moveSlowerBehaviour: switching to behaviour idleBehaviour # if self.initialCondition_From_Behaviour_moveSlowerBehaviour_To_Behaviour_idleBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_idleBehaviour" pass # Behaviour vacuumOnBehaviour: # def subsystemBehaviour_vacuumOnBehaviour(self): self.log("subsystemBehaviour_vacuumOnBehaviour") # Executing behaviour vacuumOnBehaviour # self.executeBehaviour_vacuumOnBehaviour() # Behaviour has been terminated # # Checking initial condition for behaviour vacuumOnBehaviour: switching to behaviour idleBehaviour # if self.initialCondition_From_Behaviour_vacuumOnBehaviour_To_Behaviour_idleBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_idleBehaviour" pass # Behaviour vacuumOffBehaviour: # def subsystemBehaviour_vacuumOffBehaviour(self): self.log("subsystemBehaviour_vacuumOffBehaviour") # Executing behaviour vacuumOffBehaviour # self.executeBehaviour_vacuumOffBehaviour() # Behaviour has been terminated # # Checking initial condition for behaviour vacuumOffBehaviour: switching to behaviour idleBehaviour # if self.initialCondition_From_Behaviour_vacuumOffBehaviour_To_Behaviour_idleBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_idleBehaviour" pass # Behaviour moveBackwardBehaviour: # def subsystemBehaviour_moveBackwardBehaviour(self): self.log("subsystemBehaviour_moveBackwardBehaviour") # Executing behaviour moveBackwardBehaviour # self.executeBehaviour_moveBackwardBehaviour() # Behaviour has been terminated # # Checking initial condition for behaviour moveBackwardBehaviour: switching to behaviour idleBehaviour # if self.initialCondition_From_Behaviour_moveBackwardBehaviour_To_Behaviour_idleBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_idleBehaviour" pass # Behaviour moveFrontBehaviour: # def subsystemBehaviour_moveFrontBehaviour(self): self.log("subsystemBehaviour_moveFrontBehaviour") # Executing behaviour moveFrontBehaviour # self.executeBehaviour_moveFrontBehaviour() # Behaviour has been terminated # # Checking initial condition for behaviour moveFrontBehaviour: switching to behaviour idleBehaviour # if self.initialCondition_From_Behaviour_moveFrontBehaviour_To_Behaviour_idleBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_idleBehaviour" pass # Behaviour moveRightBehaviour: # def subsystemBehaviour_moveRightBehaviour(self): self.log("subsystemBehaviour_moveRightBehaviour") # Executing behaviour moveRightBehaviour # self.executeBehaviour_moveRightBehaviour() # Behaviour has been terminated # # Checking initial condition for behaviour moveRightBehaviour: switching to behaviour idleBehaviour # if self.initialCondition_From_Behaviour_moveRightBehaviour_To_Behaviour_idleBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_idleBehaviour" pass # Behaviour moveLeftBehaviour: # def subsystemBehaviour_moveLeftBehaviour(self): self.log("subsystemBehaviour_moveLeftBehaviour") # Executing behaviour moveLeftBehaviour # self.executeBehaviour_moveLeftBehaviour() # Behaviour has been terminated # # Checking initial condition for behaviour moveLeftBehaviour: switching to behaviour idleBehaviour # if self.initialCondition_From_Behaviour_moveLeftBehaviour_To_Behaviour_idleBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_idleBehaviour" pass # Behaviour rotateLeftBehaviour: # def subsystemBehaviour_rotateLeftBehaviour(self): self.log("subsystemBehaviour_rotateLeftBehaviour") # Executing behaviour rotateLeftBehaviour # self.executeBehaviour_rotateLeftBehaviour() # Behaviour has been terminated # # Checking initial condition for behaviour rotateLeftBehaviour: switching to behaviour idleBehaviour # if self.initialCondition_From_Behaviour_rotateLeftBehaviour_To_Behaviour_idleBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_idleBehaviour" pass # Behaviour rotateRightBehaviour: # def subsystemBehaviour_rotateRightBehaviour(self): self.log("subsystemBehaviour_rotateRightBehaviour") # Executing behaviour rotateRightBehaviour # self.executeBehaviour_rotateRightBehaviour() # Behaviour has been terminated # # Checking initial condition for behaviour rotateRightBehaviour: switching to behaviour idleBehaviour # if self.initialCondition_From_Behaviour_rotateRightBehaviour_To_Behaviour_idleBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_idleBehaviour" pass # Behaviour whatCanYouSeeBehaviour: # def subsystemBehaviour_whatCanYouSeeBehaviour(self): self.log("subsystemBehaviour_whatCanYouSeeBehaviour") # Executing behaviour whatCanYouSeeBehaviour # self.executeBehaviour_whatCanYouSeeBehaviour() # Behaviour has been terminated # # Checking initial condition for behaviour whatCanYouSeeBehaviour: switching to behaviour idleBehaviour # if self.initialCondition_From_Behaviour_whatCanYouSeeBehaviour_To_Behaviour_idleBehaviour(): # incrementing the number determining how many times subsystem has switched between behaviours # self._subsystemIterations=self._subsystemIterations+1 self._currentSubsystemBehaviour="Behaviour_idleBehaviour" pass ##### Initial condition for behaviour initBehaviour: switching to behaviour idleBehaviour ##### def initialCondition_From_Behaviour_initBehaviour_To_Behaviour_idleBehaviour(self): # Initial condition specified by user # return True ##### Initial condition for behaviour idleBehaviour: switching to behaviour terminateBehaviour ##### def initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_terminateBehaviour(self): # Initial condition specified by user # return self.taskCommand.data=="terminate" ##### Initial condition for behaviour idleBehaviour: switching to behaviour stopBehaviour ##### def initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_stopBehaviour(self): # Initial condition specified by user # return self.taskCommand.data=="stop" ##### Initial condition for behaviour idleBehaviour: switching to behaviour moveFasterBehaviour ##### def initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_moveFasterBehaviour(self): # Initial condition specified by user # return self.taskCommand.data=="speed up" ##### Initial condition for behaviour idleBehaviour: switching to behaviour moveSlowerBehaviour ##### def initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_moveSlowerBehaviour(self): # Initial condition specified by user # return self.taskCommand.data=="speed down" ##### Initial condition for behaviour idleBehaviour: switching to behaviour vacuumOnBehaviour ##### def initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_vacuumOnBehaviour(self): # Initial condition specified by user # return self.taskCommand.data=="vacuum turn on" ##### Initial condition for behaviour idleBehaviour: switching to behaviour vacuumOffBehaviour ##### def initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_vacuumOffBehaviour(self): # Initial condition specified by user # return self.taskCommand.data=="vacuum off" ##### Initial condition for behaviour idleBehaviour: switching to behaviour moveBackwardBehaviour ##### def initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_moveBackwardBehaviour(self): # Initial condition specified by user # return self.taskCommand.data=="backwards" ##### Initial condition for behaviour idleBehaviour: switching to behaviour moveFrontBehaviour ##### def initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_moveFrontBehaviour(self): # Initial condition specified by user # return self.taskCommand.data=="front" ##### Initial condition for behaviour idleBehaviour: switching to behaviour moveRightBehaviour ##### def initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_moveRightBehaviour(self): # Initial condition specified by user # return self.taskCommand.data=="right" ##### Initial condition for behaviour idleBehaviour: switching to behaviour moveLeftBehaviour ##### def initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_moveLeftBehaviour(self): # Initial condition specified by user # return self.taskCommand.data=="left" ##### Initial condition for behaviour idleBehaviour: switching to behaviour rotateLeftBehaviour ##### def initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_rotateLeftBehaviour(self): # Initial condition specified by user # return self.taskCommand.data=="rotate left" ##### Initial condition for behaviour idleBehaviour: switching to behaviour rotateRightBehaviour ##### def initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_rotateRightBehaviour(self): # Initial condition specified by user # return self.taskCommand.data=="rotate right" ##### Initial condition for behaviour idleBehaviour: switching to behaviour whatCanYouSeeBehaviour ##### def initialCondition_From_Behaviour_idleBehaviour_To_Behaviour_whatCanYouSeeBehaviour(self): # Initial condition specified by user # return self.taskCommand.data=="what can you see" ##### Initial condition for behaviour terminateBehaviour: switching to behaviour terminatedBehaviour ##### def initialCondition_From_Behaviour_terminateBehaviour_To_Behaviour_terminatedBehaviour(self): # Initial condition specified by user # return True ##### Initial condition for behaviour stopBehaviour: switching to behaviour idleBehaviour ##### def initialCondition_From_Behaviour_stopBehaviour_To_Behaviour_idleBehaviour(self): # Initial condition specified by user # return True ##### Initial condition for behaviour moveFasterBehaviour: switching to behaviour idleBehaviour ##### def initialCondition_From_Behaviour_moveFasterBehaviour_To_Behaviour_idleBehaviour(self): # Initial condition specified by user # return True ##### Initial condition for behaviour moveSlowerBehaviour: switching to behaviour idleBehaviour ##### def initialCondition_From_Behaviour_moveSlowerBehaviour_To_Behaviour_idleBehaviour(self): # Initial condition specified by user # return True ##### Initial condition for behaviour vacuumOnBehaviour: switching to behaviour idleBehaviour ##### def initialCondition_From_Behaviour_vacuumOnBehaviour_To_Behaviour_idleBehaviour(self): # Initial condition specified by user # return True ##### Initial condition for behaviour vacuumOffBehaviour: switching to behaviour idleBehaviour ##### def initialCondition_From_Behaviour_vacuumOffBehaviour_To_Behaviour_idleBehaviour(self): # Initial condition specified by user # return True ##### Initial condition for behaviour moveBackwardBehaviour: switching to behaviour idleBehaviour ##### def initialCondition_From_Behaviour_moveBackwardBehaviour_To_Behaviour_idleBehaviour(self): # Initial condition specified by user # return True ##### Initial condition for behaviour moveFrontBehaviour: switching to behaviour idleBehaviour ##### def initialCondition_From_Behaviour_moveFrontBehaviour_To_Behaviour_idleBehaviour(self): # Initial condition specified by user # return True ##### Initial condition for behaviour moveRightBehaviour: switching to behaviour idleBehaviour ##### def initialCondition_From_Behaviour_moveRightBehaviour_To_Behaviour_idleBehaviour(self): # Initial condition specified by user # return True ##### Initial condition for behaviour moveLeftBehaviour: switching to behaviour idleBehaviour ##### def initialCondition_From_Behaviour_moveLeftBehaviour_To_Behaviour_idleBehaviour(self): # Initial condition specified by user # return True ##### Initial condition for behaviour rotateLeftBehaviour: switching to behaviour idleBehaviour ##### def initialCondition_From_Behaviour_rotateLeftBehaviour_To_Behaviour_idleBehaviour(self): # Initial condition specified by user # return True ##### Initial condition for behaviour rotateRightBehaviour: switching to behaviour idleBehaviour ##### def initialCondition_From_Behaviour_rotateRightBehaviour_To_Behaviour_idleBehaviour(self): # Initial condition specified by user # return True ##### Initial condition for behaviour whatCanYouSeeBehaviour: switching to behaviour idleBehaviour ##### def initialCondition_From_Behaviour_whatCanYouSeeBehaviour_To_Behaviour_idleBehaviour(self): # Initial condition specified by user # return True ##### Function indicating basic log/debug message ##### def log(self, str): if(IS_LOG): rospy.loginfo("[SUBSYSTEM cs] -- LOG -- "+str) if(IS_PRINT): print "[SUBSYSTEM cs] -- LOG -- " + str pass ##### Function indicating basic error message ##### def error(self, str): sys.stderr.write("[SUBSYSTEM cs] -- ERROR -- " + str) if(IS_LOG): rospy.loginfo("[SUBSYSTEM cs] -- ERROR -- "+str) sys.exit() pass ##### MAIN FUNCTION FOR SUBSYSTEM cs ##### if __name__ == '__main__': try: subsystem_cs = cs() subsystem_cs.startSubsystem() except rospy.ROSInterruptException: pass
UTF-8
Python
false
false
174,238
py
59
subsystem_cs.py
32
0.750795
0.748252
0
3,007
56.943798
554
nagpureabhirag/Graph-1
17,471,926,969,178
a932817460a1c07c44956c28efae9a826375e875
1c5de78c2f731a6e5c34524880912bfe89593048
/find_the_town_judge.py
12cfdfc1cc478a69e5a4e72aa60fe3afcd2924e1
[]
no_license
https://github.com/nagpureabhirag/Graph-1
cc6a19178e5e9e26e4e588088ebb009f152e2619
a813d3b086bb6c899fb79f1a5b1438f69ab16fd2
refs/heads/master
2023-08-26T09:08:26.208774
2021-10-18T16:09:05
2021-10-18T16:09:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Did this code successfully run on Leetcode : YES # approach # calculate difference between indegrees and outdegrees # TC: O(N) # SC: O(N) class Solution: def findJudge(self, n: int, trust: List[List[int]]) -> int: degrees = [0 for _ in range(n)] for [i, j] in trust: degrees[j-1] += 1 degrees[i-1] -= 1 for d in range(n): if degrees[d] == n-1: return d+1 return -1
UTF-8
Python
false
false
456
py
2
find_the_town_judge.py
2
0.537281
0.519737
0
17
25.882353
63
Ochwada/Thesis_-Data_Analysis-Public
11,012,296,162,218
0f851d8f9f361781b6b920668062ea119f13c6f0
1c7c2690c4439be51135c85533f6f0d3cf4ff1ce
/wind_histogram.py
af10a3026442e4295738734ad0702b60f4a5657f
[]
no_license
https://github.com/Ochwada/Thesis_-Data_Analysis-Public
516c4c15464511f0ef969f56c8bbb648c2767b94
ac1e8a7bff96521c9e9b2134d56f3a09c1a72524
refs/heads/master
2020-04-09T02:45:24.202761
2018-12-01T14:48:49
2018-12-01T14:48:49
159,952,732
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # -*- codiing for wind_histogram -*- import matplotlib.pyplot as plt import numpy as np #import scipy.stats as stats from scipy import stats import matplotlib.mlab as mlab import statsmodels.api as sm import wind_data as wd import plot_winddata as pwd from helper import date_to_doy, doy_to_date, moving_average, altitude_to_int, weib import project_config as conf import math #import matplotlib.font_manager as font_manager axis_font = {'fontname':'Arial', 'size':'16'} # ----------------------------------------------------------------------- #Central Tendency # ----------------------------------------------------------------------- #mean def mean_speed(data): total = 0 mean = 0 for item in data: total += item mean_speed = total/float(len(data)) return mean_speed def mean_power(data): total = 0 mean = 0 for item in data: total+= item mean_power = total/float(len(data)) return mean_power # ----------------------------------------------------------------------- #Weibull pdf # ----------------------------------------------------------------------- def weibull_plot_speed(data, params): bins = np.arange(0, 32.0, 0.5) plt.hist(data, bins, histtype='bar', edgecolor='black',normed=True, alpha=0.5, rwidth=1.0); x = np.arange(0, 32.0, 0.1) plt.plot(x,stats.exponweib.pdf(x, *params), label="Weibull PDF") mean_value = data.mean() plt.axvline(mean_value, color='m', linestyle='dashed', linewidth=1, label="Mean power" ) #plt.title('Wind speed distribution for Germany at Level 1') plt.xlabel('Wind Speed (m/s)', **axis_font) plt.ylabel('Wind speed frequency', **axis_font) plt.legend(loc=1, prop={'size': 16}) plt.show() #plt.savefig('image1') #print(result) #======================================================================= if __name__ == '__main__': # ----------------------------------------------------------------------- # ----------------------------------------------------------------------- #Central Tendancy - Compute for 0-9 speedall = conf.load_all_windspeeds() meanspeed = mean_speed(speedall[:,1]) #print(meanspeed) powerall = conf.load_all_windpower() meanpower = mean_power(powerall[:,8]) #print(meanpower) #--------------------------Weibull PDF---------------------- #----------------------------------------------------------- #------------windspeed speedall = conf.load_all_windspeeds() data_speed = speedall [:,1] #params_speed = stats.exponweib.fit(data_speed,floc=0) #windspeed -----stats.exponweib.fit(data_speed,floc=0) params_speed = (1.1113449643109912, 1.6809413157101651, 0, 7.2972382976005772)#Level 1 #params_speed =(1.0635878486058918, 1.7129895275983615, 0, 8.0111689684382323)#Level 2 #params_speed =(1.0704643275819068, 1.6853620845145747, 0, 8.3604171276602486)#Level 3 #params_speed =(1.1113173256840196, 1.6301269094327573, 0, 8.4365496561132183)#Level 4 #params_speed =(1.1600496620157552, 1.5765771265205082, 0, 8.4068808687607639)#Level 5 #params_speed =(1.2147903730266001, 1.5256215491691232, 0, 8.3224080743411264)#Level 6 #params_speed =(1.2558199288860206, 1.4950921999766487, 0, 8.2474385764630327)#Level 7 #params_speed =(1.2949475501898591, 1.469286787656831, 0, 8.1859121591777537)#Level 8 #params_speed =(1.3035611603623392, 1.4695586916574541, 0, 8.2236837246717638)#Level 9 print('p\n', params_speed) #weibull_plot_speed(data_speed, params_speed) #------------windpower dist = stats.lognorm powerall = conf.load_all_windpower() data_power = powerall [:,9] #params_power = dist.fit(data_power,floc=0) params_power = (2.1848911866776488, 0, 195.85401224562315) #lognorm print('p\n', params_power) #--2--params_power=(1.0945801093499283, 0.56150661053208051, 0, 274.89152413198588)#Level 1 #weibull_plot_power(data_power, params_power, dist) #================================================================================================== #------------windpower location base -------- dist = stats.lognorm wind_Konigssee = wd.WindMeasurements().load(conf.connected_filename(47.5, 13.5) ) data_power_Konigssee = wind_Konigssee.windpower[:,9] params_power_Konigssee = dist.fit(data_power_Konigssee,floc=0) print('p\n', params_power_Konigssee) #weibull_plot_power(data_power_Konigssee, params_power_Konigssee, dist) #------------------------------------------------- #------------------------------------------------- #speedall = conf.load_all_windspeeds() #mediumspeed = median_speed(speedall [:,0]) #print(mediumspeed) #powerall = conf.load_all_windpower() #mediumpower = median_power(powerall [:,0]) #print(mediumpower) # ----------------------------------------------------------------------- #indata_Konigssee = wd.WindMeasurements().load(conf.connected_filename(47.5, 13.5) ) # Ten years at this location #check_distribution(indata_Konigssee.get_windspeed_at(0)) #speedall = conf.load_all_windspeeds() # np.load(conf.npz_folder_path + "windspeed_complete.npz", allow_pickle=False)['arr_0'] #powerall = conf.load_all_windpower() # np.load(conf.npz_folder_path + "windspower_complete.npz", allow_pickle=False)['arr_0'] #print(speedall.shape) #check_distribution(speedall[:,1]) #pass
UTF-8
Python
false
false
5,467
py
10
wind_histogram.py
9
0.56338
0.449241
0
140
38.057143
131
TheDrHax/streamlink
8,693,013,818,674
d3c223fe1854552333643c1d17387b59ce411cbb
716501ff054d10f095879f986d74882778fa72c5
/tests/plugins/test_webcast_india_gov.py
9e83d7dded01b3393c4227b4e511a4f73a88d4bd
[ "BSD-2-Clause" ]
permissive
https://github.com/TheDrHax/streamlink
017fdfd999277089a0c89a209ba4f64df9e54916
4dfd0d516fd8484438389518985e3b5131b7a253
refs/heads/master
2021-10-26T17:43:50.402219
2020-10-11T22:43:53
2021-10-25T19:10:01
223,461,822
4
0
BSD-2-Clause
true
2019-11-22T18:25:47
2019-11-22T18:25:46
2019-11-22T15:37:19
2019-11-22T16:48:00
35,041
0
0
0
null
false
false
from streamlink.plugins.webcast_india_gov import WebcastIndiaGov from tests.plugins import PluginCanHandleUrl class TestPluginCanHandleUrlWebcastIndiaGov(PluginCanHandleUrl): __plugin__ = WebcastIndiaGov should_match = [ "http://webcast.gov.in/ddpunjabi/", "http://webcast.gov.in/#Channel1", "http://webcast.gov.in/#Channel3", ]
UTF-8
Python
false
false
368
py
111
test_webcast_india_gov.py
103
0.711957
0.706522
0
12
29.666667
64
colinmipapi/italian
14,190,571,951,544
437a9635f279630430e9296b4f70dd2f82ab51b9
cfbf93c27ea19920d620dabd1f0648fe082f9391
/blog/models.py
5980326e7c80d5d524c45e9763a75f9e549ebb9e
[]
no_license
https://github.com/colinmipapi/italian
63c8ee03e55c3a572d89c42f3211687c60422ea1
8dbd270d6c7b9b2acb9f5e5fd964379030731f37
refs/heads/master
2021-01-21T17:17:17.988107
2017-03-16T03:36:58
2017-03-16T03:36:58
85,148,252
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from __future__ import unicode_literals from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator from django.http import HttpResponseRedirect # Create your models here. class Post(models.Model): title = models.CharField(max_length=300) slug = models.CharField(max_length=100, unique=True) content = models.TextField() published = models.BooleanField(default=False) pub_date = models.DateTimeField(auto_now_add=True) rating_info = models.ForeignKey( 'blog.rating', on_delete=models.CASCADE, ) image_one = models.ImageField( upload_to='static/blog/media/uploads', default = '/None/no-img.jpg') def __unicode__(self): return '%s' % self.title class Rating(models.Model): sandwich_name = models.CharField(max_length=300, null = True) bread_quality = models.PositiveIntegerField(default=0, validators=[MaxValueValidator(10),], null = True) meat_quality = models.PositiveIntegerField(default=0, validators=[MaxValueValidator(10),], null = True) meat_quantity = models.PositiveIntegerField(default=0, validators=[MaxValueValidator(10),],null = True) veg_quality = models.PositiveIntegerField(default=0, validators=[MaxValueValidator(10),],null = True) veg_quantity = models.PositiveIntegerField(default=0, validators=[MaxValueValidator(10),],null = True) dressing_quality = models.PositiveIntegerField(default=0, validators=[MaxValueValidator(10),],null = True) dressing_quantity = models.PositiveIntegerField(default=0, validators=[MaxValueValidator(10),],null = True) def __unicode__(self): return '%s' % self.sandwich_name def score(self): b_ql = int(self.bread_quality) m_ql = int(self.meat_quality) m_qt = int(self.meat_quantity) v_ql = int(self.veg_quality) v_qt = int(self.veg_quantity) d_ql = int(self.dressing_quality) d_qt = int(self.dressing_quantity) total = b_ql + m_ql + m_qt + v_ql + v_qt + d_ql + d_qt return total class Restaurant(models.Model): name = models.CharField( max_length=200, unique=True, ) address = models.CharField(max_length=500, null = True) website = models.CharField(max_length=200, null = True) phone_number = models.CharField(max_length=12, null = True) email = models.CharField(max_length=75, null = True) rating_info = models.ForeignKey( 'blog.rating', on_delete=models.CASCADE, null=True, blank = True, ) latitude = models.IntegerField( blank=True, null=True, ) longitude = models.IntegerField( blank=True, null=True, ) def __unicode__(self): return '%s' % self.name def get_lat_long(self): from googlemaps import GoogleMaps gmaps = GoogleMaps(italian-1489414695369) Address = self.address lat, lng = gmaps.address_to_latlng(address) self.latitude = lat self.longitude = lng save()
UTF-8
Python
false
false
3,074
py
18
models.py
10
0.657775
0.639558
0
88
33.931818
112
kurodo/apiprueba
17,583,596,128,773
11fd527bb4ed0167cf1e1591b7391d99580f4e52
b41805d913e7bc0f09399bec558d7079863e331b
/catalogo/urls.py
ed0ac18afd608514b00565f422339fde25d38631
[]
no_license
https://github.com/kurodo/apiprueba
21fb5cd569ba2311d0f2de887c34ed0e8c065c98
7db0682f2b054dcfdbc4d98e713cb3b067651f09
refs/heads/master
2020-05-17T15:55:53.227062
2019-05-05T00:17:18
2019-05-05T00:17:18
183,805,181
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.urls import path, include from rest_framework import routers from .views import * router = routers.DefaultRouter() router.register(r'producto', ProductoViewSet) router.register(r'precio', PrecioProductoViewSet) router.register(r'variacion', VariacionViewSet) router.register(r'producto_variacion', ProdcutoVariacionViewSet) router.register(r'categoria', CategoriaViewSet) urlpatterns = [ path('', include(router.urls)), path('build/variaciones/<int:pk>/',CrearVariaciones.as_view()) ] urlpatterns += router.urls
UTF-8
Python
false
false
535
py
38
urls.py
36
0.781308
0.781308
0
17
30.470588
66
mengyuqianxun/Python-Algorithm-interview
6,854,767,851,226
8150bdd89ac24e0504450d895cabe091697ec4be
fdfbcf4451f3f165ad6c897c74563dc1f04908db
/ch3_binary_tree/5.py
f2f7763f7f731f78996a097caa6eae12752983dd
[]
no_license
https://github.com/mengyuqianxun/Python-Algorithm-interview
3c9baac00657fea68786876706b526140c1f7799
95b6aa69fdffb2e8cbc696cc958d8d5ee8eb5c29
refs/heads/master
2020-08-29T06:50:37.178084
2020-02-17T03:11:48
2020-02-17T03:11:48
217,958,936
4
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import math class BiTNode: def __init__(self): self.data = None self.lchild = None self.rchild = None def array2tree(arr,start,end): root = None if end >= start: root = BiTNode() mid = math.floor((start + end +1)/2) root.data = arr[mid] root.lchild = array2tree(arr,start,mid-1) root.rchild = array2tree(arr,mid+1,end) else: root =None return root class Test: def __init__(self): self.pHead = None self.pEnd = None def BiT2List(self,root): if root == None: return #转换root的左子树 self.BiT2List(root.lchild) root.lchild = self.pEnd if self.pEnd == None: self.pHead = root else: self.pEnd.rchild = root self.pEnd = root self.BiT2List(root.rchild) if __name__ == "__main__": arr =[1,2,3,4,5,6,7] root = array2tree(arr,0,len(arr)-1) test = Test() print(u'双向链表正向遍历:') test.BiT2List(root) cur = test.pHead while cur != None: print(cur.data,end = ' ') cur = cur.rchild print('\n'+u'转换后双向链表逆向遍历:') cur = test.pEnd while cur != None: print(cur.data,end = ' ') cur = cur.lchild
UTF-8
Python
false
false
1,328
py
84
5.py
68
0.518838
0.502355
0
55
21.963636
49
2877992943/count_record
19,679,540,180,773
bfc7192cf95786ec3455a8b28e8f3de0dadcfd5a
fca9fbaae9bff52d5ebb9cbce424983734101143
/demo1028_tagitApp_QueryCleanData_chenyuTeam_walkRunRid_countRecord_ios.py
f4129a769e2470e2da3e54c04dd1903914e5bca0
[]
no_license
https://github.com/2877992943/count_record
c15383b38b10334eac482b49e3bcd3661acf6cc5
cfd53d30c606a9dadca9f9a33b66ad670b1934f9
refs/heads/master
2016-09-01T16:07:57.582265
2015-11-23T12:17:09
2015-11-23T12:17:09
46,718,267
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # encoding=utf-8 """ tagit app android count the number of record for each data collector not visualize,cleaning,store data """ import numpy as np import cPickle,math,random from leancloud import Object from leancloud import Query import leancloud import time,os deviceId={'huawei':'ffffffff-c7a8-3cd1-ffff-ffffea16e571', 'xiaomi':'ffffffff-c7a7-c7d4-0000-000031a92fbe', 'mine':'ffffffff-c95d-196f-0000-00007e282437', 'chenyu':'ffffffff-c43f-692d-ffff-fffff4d57110', 'wangx':'ffffffff-c28a-1bf0-0000-00005e774605', 'zhangx':'ffffffff-f259-8a54-0000-0000300c3e8c', 'liyt':'ffffffff-c7a8-3c91-ffff-ffffa2dc21fc', 'donggy':'ffffffff-c95e-eae5-ffff-ffffce758366', 'hangwz':'ffffffff-c43f-77d4-0000-00001b78f081', 'wangf':'ffffffff-c7a8-3bf6-ffff-ffffb8d6d318', 'biany':'ffffffff-c28b-7966-0000-000049d75b84', 'liuxuan':'ffffffff-f259-8a2f-0000-0000040de9c1', 'wangzhenfang':'00000000-53a7-c4ef-ffff-fffffd609c24', 'cuiyajie':'ffffffff-910d-998f-0000-0000585e3d7e' } sensor_list=["magneticSensor","accelerometer","proximity"] inst_id_zhangnn_ios='L2OGFhzaHM2IbNzJ1NjEHceroElYVdk2' inst_id_chenyu_ios='yg80UzhxQFPPcwicTtU4lDTyP9IcqDs2' inst_id_lb_ios='G93jbBRhtiWVGFULyLR9gPHDjUkl3S3R' inst_id_zhangnn1_ios='GsjMrEReu1OC2wtkUpM5asbWEyJ5AdQ1' #######################each class generate fea c_list=['running','walking','riding','sitting','driving'] dataPath='/home/yr/magnetic_fea/data1027/' test_pack=11040#01234 #012 not sure walk |mod<15 rid | mod>=15 walkrun|but differ between people para_pack=0#1with liangbin riding into trainset class_type=c_list[1] ###########query label.data device=deviceId['wangzhenfang'] sensor=sensor_list[1] ##########query log.tracer txt_i=2 see_flag=True inst_id=inst_id_chenyu_ios ########## def generate_stamp(period): #[8,28,8,33]->[(2015, 10, 20, 22, 30, 0, 0, 0, 0),(2015, 10, 20, 22, 48, 0, 0, 0, 0)]->stamp dur= [(2015, period[0], period[1], period[2], period[3], 0, 0, 0, 0),\ (2015, period[4], period[5], period[6], period[7], 0, 0, 0, 0)] stamp_range0=[time2stamp(dur[0]),time2stamp(dur[1])] stamp_range=[t*1000 for t in stamp_range0] return stamp_range def time2stamp(t): #t = (2015, 9, 28, 12, 36, 38, 0, 0, 0) stamp = int(time.mktime( t )) ; return stamp def connect_db_label():#label.data import leancloud,cPickle appid = "ckjjqzf3jqwl8k1u4o10j2hqp0rm0q6ferqcfb0xpw00e8zl" appkey = "rn0qw8ib96xl0km63kylo6v5afuxclc8jti5ol8rx4kylqob" leancloud.init(appid, appkey) def connect_db_log():##sensor.log.tracer not label.sensor, import leancloud,cPickle appid = "9ra69chz8rbbl77mlplnl4l2pxyaclm612khhytztl8b1f9o" appkey = "1zohz2ihxp9dhqamhfpeaer8nh1ewqd9uephe9ztvkka544b" #appid = "ckjjqzf3jqwl8k1u4o10j2hqp0rm0q6ferqcfb0xpw00e8zl" #appkey = "rn0qw8ib96xl0km63kylo6v5afuxclc8jti5ol8rx4kylqob" leancloud.init(appid, appkey) ##################### def get_content(results):#result is from find() obs={}; r=results for i in range(1): #print type(r.get("events")) if len(r.get("events"))>=1: print r.get("motion"),r.get("events").__len__() ll=r.get("events") #ll=[ {},{}...] for dic in ll[:]:#dic={timestamp:xxxx,value:[1,2,3]...} #print dic["timestamp"],' ',dic["values"][0],' ',dic["values"][1],' ',dic["values"][2] if dic["timestamp"] not in obs.keys(): obs[ dic["timestamp"] ]=[r.get("motion"),\ dic["values"][0],dic["values"][1],dic["values"][2] ] ###data form: {timestamp:[obs],...} [obs]=[motion,x,y,z] ########################### """ for k,v in obs.items(): print k,' ',v """ print 'final',obs.__len__() #print 'i',i,count #query-has-limit100,real-count=320 ###################3 return obs def get_all(query,skip,result): limit=500 query.limit(limit) query.skip(skip) found=query.find() if found and len(found)>0: result.extend(found) print 'av_utils get all,now result len:',len(result),'skip',skip return get_all(query,skip+limit,result) else: return result def save2pickle(c,name): write_file=open(dataPath+str(name),'wb') cPickle.dump(c,write_file,-1)#[ (timestamp,[motion,x,y,z]),...] write_file.close() def load_pickle(path_i): f=open(path_i,'rb') data=cPickle.load(f)#[ [time,[xyz],y] ,[],[]...] f.close() #print data.__len__(),data[0] return data def see_record_num(period_label_dic): valid_num=0 ####init connect_db_log() log = leancloud.Object.extend('Log') log_query = leancloud.Query(log) #print 'all',log_query.count()##error inst_query = leancloud.Query(leancloud.Installation) #print 'install',inst_query.count()#2335 inst = inst_query.equal_to('objectId', inst_id).find();#print '1',inst[0] # for label,periods in period_label_dic.items(): for period in periods: stamp_range=generate_stamp(period) #################each period log_query.equal_to('installation', inst[0]).equal_to("type",'sensor').\ less_than("timestamp", stamp_range[1]).greater_than("timestamp",stamp_range[0]) print label,period,'count',log_query.count() if log_query.count()>0:valid_num+=log_query.count() print 'total valid count',valid_num def remove_punct(line): for punct in ['.','-',':','/','\\']: if punct in line:line=line.replace(punct,' ') return line ############3 if __name__=="__main__": txt_path='/home/yr/magnetic_fea/txt_1123/' period_label={}; for filename in os.listdir(txt_path)[txt_i:txt_i+1]: print 'file '+filename inpath=txt_path+filename content=open(inpath,'r') line=content.readline().strip('\n').strip('\r').strip(' ') #period=[0,0,0,0,0,0,0,0]#month day minu sec .... while line: line=remove_punct(line) line=line.split(' ');print line period=[int(line[0]),int(line[1]),int(line[2]),int(line[3]),\ int(line[0]),int(line[1]),int(line[4]),int(line[5])] label=line[-1] if label not in period_label: period_label[label]=[period] elif label in period_label: period_label[label].append(period) #####next line=content.readline().strip('\n').strip('\r').strip(' ') ################### for k,v in period_label.items():#{label:[period,p,...],label:{}... print k,v.__len__() #########see valid record if see_flag==True : see_record_num(period_label) elif see_flag==False:print 'file '+filename
UTF-8
Python
false
false
6,408
py
1
demo1028_tagitApp_QueryCleanData_chenyuTeam_walkRunRid_countRecord_ios.py
1
0.647784
0.571941
0
224
27.388393
100
ohjho/pyp-w1-gw-language-detector
3,762,391,372,115
43d54a81c4a6636972bcb519188cdebf60cc6d2b
23c333a9db3bedf1688a346bf1573e2f5bd34117
/language_detector/main.py
c39596f4d92bac9f2427cb78c0c74dfafbd361ab
[ "MIT" ]
permissive
https://github.com/ohjho/pyp-w1-gw-language-detector
ee5215e35dea4a304fefe77c6a58c77bce37b1c1
d40f9ab7b02eb568208c02a8add591a81b627236
refs/heads/master
2021-01-23T10:56:34.334393
2017-06-02T02:18:48
2017-06-02T02:18:48
93,109,242
0
0
null
true
2017-06-01T23:56:54
2017-06-01T23:56:54
2017-01-12T23:09:17
2017-06-01T23:29:51
20
0
0
0
null
null
null
# -*- coding: utf-8 -*- def detect_language(text, languages): """Returns the detected language of given text.""" count = {} for language in languages: matches = (len(set(text.split(' ')) & set(language['common_words']))) count[language['name']] = matches return max(count, key=count.get)
UTF-8
Python
false
false
337
py
2
main.py
2
0.58457
0.581602
0
11
28.727273
77
h-mayorquin/mnist_deep_neural_network_BPNNs
9,500,467,661,736
3b1d73bd2a961ffa0f686f1e0d7d42812d8a511e
a5aa4c7d0b7b2a6202c1befadd11a4a31d571da1
/distort_pattern.py
4275c3c6cc4172597e08ac47102c25f4db06ce6e
[]
no_license
https://github.com/h-mayorquin/mnist_deep_neural_network_BPNNs
793b60985df41f4895e266829b8308bbf62952dd
a679e09b5f5b18ce95282e6963662ab700c227d6
refs/heads/master
2021-01-01T19:47:19.908058
2015-05-08T16:57:37
2015-05-08T16:57:37
31,664,159
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import numpy as np import matplotlib.pyplot as plt from load_binary_files import training_ims, training_labels from corrupt_functions import distort_binnary from copy import deepcopy # Select quantity of data to use N_data_total = len(training_labels) percentage = 0.01 N_to_use = int(percentage * N_data_total) # Decide how much data to use X = training_ims[0:N_to_use] Y = training_labels[0:N_to_use] N_hypercolumns = X.shape[1] units_per_hypercolumn = 2 index = 0 size = 28 percentage = 0.1 pattern = deepcopy(X[index]) dis_pattern = distort_binnary(index, percentage, X) plt.subplot(1, 3, 1) plt.title('Corrupted') plt.imshow(dis_pattern.reshape((size, size))) plt.subplot(1, 3, 2) plt.title('Normal pattern') plt.imshow(pattern.reshape((size, size))) plt.subplot(1, 3, 3) plt.title('Normal should be') plt.imshow(X[index].reshape((size, size))) plt.show()
UTF-8
Python
false
false
867
py
23
distort_pattern.py
22
0.734717
0.710496
0
35
23.771429
59
TheClearwind/DeepISP
1,228,360,690,722
5a3fae6bb03628b93bdb2cea8b2499dbdcd1edca
3a37356348b1961a70dac753980c61e21a7ae725
/utils.py
936648a6bd9a083ea261ce16a58beb617b73277d
[]
no_license
https://github.com/TheClearwind/DeepISP
cf328be53ba42ca5ba929fd56bd5f33bdc582eef
0e88c8915eab0723989a5f8632b09f2fa57d240d
refs/heads/master
2022-11-23T06:43:51.022142
2020-07-15T06:44:21
2020-07-15T06:44:21
279,495,723
8
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import numpy as np def extract_bayer_channels(raw): # RGGB模式 ch_B = raw[1::2, 1::2] ch_Gb = raw[0::2, 1::2] ch_R = raw[0::2, 0::2] ch_Gr = raw[1::2, 0::2] return ch_R, ch_Gr, ch_B, ch_Gb def extract_bayer_channels_v2(raw): # RGGB模式 ch_R = np.zeros_like(raw) ch_G = np.zeros_like(raw) ch_B = np.zeros_like(raw) ch_B[1::2, 1::2] = raw[1::2, 1::2] ch_R[0::2, 0::2] = raw[0::2, 0::2] ch_G[0::2, 1::2] = raw[0::2, 1::2] ch_G[1::2, 0::2] = raw[1::2, 0::2] return ch_R, ch_G, ch_B def pack_raw(raw): ch_B, ch_Gb, ch_R, ch_Gr = extract_bayer_channels(raw) packed = np.dstack((ch_B, ch_Gb, ch_R, ch_Gr)) packed = np.transpose(packed, [2, 0, 1]) return packed def pack_raw_v2(raw): ch_R, ch_G, ch_B = extract_bayer_channels_v2(raw) packed = np.dstack((ch_R, ch_G, ch_B)) packed = np.transpose(packed, [2, 0, 1]) return packed if __name__ == '__main__': raw = np.random.randn(224, 224) packed = pack_raw_v2(raw) print(packed.shape)
UTF-8
Python
false
false
1,045
py
9
utils.py
8
0.537126
0.47541
0
44
22.568182
58
Sovetnikov/livelock
2,413,771,641,869
7e88346d92d017aba1a4973a11d39333d2302304
6b6a99d78765d71b1024c3876753013cb3cb0398
/livelock/server.py
816cf39bbb09849538eee4f0ced410c3be7bd101
[]
no_license
https://github.com/Sovetnikov/livelock
a8beead745405f957576e6f8e2af0e82b1436c6a
237b01c2ab2efebf5e74c2a5653ca5168ede65dd
refs/heads/master
2022-12-24T14:46:43.013963
2022-12-14T15:32:24
2022-12-14T15:32:24
193,243,160
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import asyncio import logging import os import signal import socket import time import uuid from asyncio import StreamReader, IncompleteReadError, Event from timeit import default_timer from livelock.memory_storage import InMemoryLockStorage from livelock.shared import DEFAULT_RELEASE_ALL_TIMEOUT, DEFAULT_BIND_TO, DEFAULT_LIVELOCK_SERVER_PORT, get_settings, DEFAULT_MAX_PAYLOAD, pack_resp, DEFAULT_SHUTDOWN_SUPPORT, \ DEFAULT_PROMETHEUS_PORT, DEFAULT_TCP_KEEPALIVE_TIME, DEFAULT_TCP_KEEPALIVE_INTERVAL, DEFAULT_TCP_KEEPALIVE_PROBES, DEFAULT_LOGLEVEL, DEFAULT_DISABLE_DUMP_LOAD, \ DEFAULT_TCP_USER_TIMEOUT_SECONDS, DEFAULT_MAINTENANCE_TIMEOUT_MS, DEFAULT_MAINTENANCE_PERIOD, get_float_settings, get_int_settings, SERVER_TERMINATING, CONN_HAS_ID_ERROR, \ WRONG_ARGS, CONN_REQUIRED_ERROR, UNKNOWN_COMMAND_ERROR, PASS_ERROR, ERRORS, LazyArg from livelock.stats import latency, max_lock_live_time, stats_collection_time, prometheus_client_installed, maintenance_time, stats_collection_count, maintenance_count, lock_count from livelock.storage import LockStorage from livelock.tcp_opts import set_tcp_keepalive ABSOLUTE_PATH = lambda x: os.path.abspath(os.path.join(os.path.abspath(os.path.dirname(__file__)), x)) logger = logging.getLogger(__name__) # Надо сделать # 3. Протоколирование длительности операций # 4. Хранение clientinfo class StorageAdaptor(LockStorage): def __init__(self, store): self.store = store self.kill_active = False self._storage_operations_in_process = 0 self._commands_in_process = 0 self._data_dumped = False self._maintenance_event = Event() signal.signal(signal.SIGINT, self._on_kill_requested) signal.signal(signal.SIGTERM, self._on_kill_requested) super().__init__() def terminate(self): self._on_kill_requested() def on_storage_operation_start(self): self._storage_operations_in_process += 1 def on_storage_operation_end(self): self._storage_operations_in_process -= 1 if self._storage_operations_in_process < 0: raise Exception('Storage active operations counter broken') if self.kill_active and not self._storage_operations_in_process: # Last storage operation ended, good point to dump storage data # then exit() after sending replies to clients self.dump_before_die() def is_commands_in_process(self): return self._commands_in_process > 0 async def on_command_start(self): await self._maintenance_event.wait() self._commands_in_process += 1 def on_command_end(self): self._commands_in_process -= 1 if self.kill_active and not self._commands_in_process: if self._storage_operations_in_process: logger.error('Last command executed, but storage operations counter has value') self.die() def _on_kill_requested(self, *args, **kwargs): # Must wait for active commands to complete, then dump data, close all connections and exit self.kill_active = True logger.info('Received terminate signal %s %s', args, kwargs) if not self._storage_operations_in_process: # Good time to dump and exit(), but there is chance that some client's will not get their responses self.dump_before_die() # In case any storage operations is in progress, we will dump data after last operations completes # and will exit() when last reply is sent if not self._commands_in_process: self.die() def dump_before_die(self): # Just dump data, because all storage operations ended self.store.dump() self._data_dumped = True logger.debug('Dumped data') def die(self): # All commands processed, can exit safely if not self._data_dumped: self.store.dump() logger.debug('Exit') exit(1) def acquire(self, *args, **kwargs): with StorageOperationGuard(self): return self.store.acquire(*args, **kwargs) def release(self, *args, **kwargs): with StorageOperationGuard(self): return self.store.release(*args, **kwargs) def release_all(self, client_id): with StorageOperationGuard(self): return self.store.release_all(client_id=client_id, timeout=self.release_all_timeout) def unrelease_all(self, *args, **kwargs): with StorageOperationGuard(self): return self.store.unrelease_all(*args, **kwargs) def locked(self, *args, **kwargs): return self.store.locked(*args, **kwargs) def set_client_last_address(self, *args, **kwargs): with StorageOperationGuard(self): return self.store.set_client_last_address(*args, **kwargs) def add_signal(self, *args, **kwargs): with StorageOperationGuard(self): return self.store.add_signal(*args, **kwargs) def has_signal(self, *args, **kwargs): return self.store.has_signal(*args, **kwargs) def remove_signal(self, *args, **kwargs): with StorageOperationGuard(self): return self.store.remove_signal(*args, **kwargs) def get_client_last_address(self, *args, **kwargs): return self.store.get_client_last_address(*args, **kwargs) def find(self, *args, **kwargs): return self.store.find(*args, **kwargs) def dump(self): return self.store.dump() def load_dump(self): return self.store.load_dump() def clear_dump(self): return self.store.clear_dump() def stats(self): return self.store.stats() def maintenance(self, *args, **kwargs): logger.debug('Doing maintenance') try: self._maintenance_event.clear() return self.store.maintenance(*args, **kwargs) finally: self._maintenance_event.set() class CommandProtocol(asyncio.Protocol): def __init__(self, tcp_keepalive_time=None, tcp_keepalive_interval=None, tcp_keepalive_probes=None, tcp_user_timeout_seconds=None, *args, **kwargs): self.transport = None self._reader = None """ https://blog.cloudflare.com/when-tcp-sockets-refuse-to-die/ http://coryklein.com/tcp/2015/11/25/custom-configuration-of-tcp-socket-keep-alive-timeouts.html Keep-Alive Process There are three configurable properties that determine how Keep-Alives work. On Linux they are1: tcp_keepalive_time default 7200 seconds tcp_keepalive_probes default 9 tcp_keepalive_intvl default 75 seconds The process works like this: 1. Client opens TCP connection 2. If the connection is silent for tcp_keepalive_time seconds, send a single empty ACK packet.1 3. Did the server respond with a corresponding ACK of its own? - No 1. Wait tcp_keepalive_intvl seconds, then send another ACK 2. Repeat until the number of ACK probes that have been sent equals tcp_keepalive_probes. 3. If no response has been received at this point, send a RST and terminate the connection. - Yes: Return to step 2 """ self.tcp_keepalive_time = int(tcp_keepalive_time) self.tcp_keepalive_interval = int(tcp_keepalive_interval) self.tcp_keepalive_probes = int(tcp_keepalive_probes) self.tcp_user_timeout_seconds = int(tcp_user_timeout_seconds) super().__init__(*args, **kwargs) def data_received(self, data): if self.kill_active: return self._reader.feed_data(data) def connection_made(self, transport): if self.kill_active: return sock = transport.get_extra_info('socket') set_tcp_keepalive(sock, opts=dict(tcp_keepalive=True, tcp_keepalive_idle=self.tcp_keepalive_time, tcp_keepalive_intvl=self.tcp_keepalive_interval, tcp_keepalive_cnt=self.tcp_keepalive_probes, )) # https://eklitzke.org/the-caveats-of-tcp-nodelay sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) if hasattr(socket, 'TCP_USER_TIMEOUT'): logger.debug('Setting TCP_USER_TIMEOUT to %s', self.tcp_user_timeout_seconds * 1000) sock.setsockopt(socket.SOL_TCP, socket.TCP_USER_TIMEOUT, self.tcp_user_timeout_seconds * 1000) self.transport = transport self._reader = StreamReader() self._reader.set_transport(transport) loop = asyncio.get_event_loop() loop.create_task(self.receive_commands()) super().connection_made(transport) def connection_lost(self, exc): if self.kill_active: return if self._reader is not None: if exc is None: self._reader.feed_eof() else: self._reader.set_exception(exc) super().connection_lost(exc) def eof_received(self): if self.kill_active: return self._reader.feed_eof() return super().eof_received() async def _read_int(self): if self.kill_active: return line = await self._reader.readuntil(b'\r\n') return int(line.decode().strip()) async def _read_float(self): if self.kill_active: return line = await self._reader.readuntil(b'\r\n') return float(line.decode().strip()) async def _read_bytes(self): if self.kill_active: return len = await self._read_int() line = await self._reader.readexactly(max(2, len + 2)) if line[-1] != ord(b'\n'): raise Exception(r"line[-1] != ord(b'\n')") if line[-2] != ord(b'\r'): raise Exception(r"line[-2] != ord(b'\r')") if len < 0: return None if len == 0: return b'' return line[:-2] async def _read_array(self): if self.kill_active: return len = await self._read_int() r = [] while len: c = await self._reader.readexactly(1) value = await self._receive_resp(c) r.append(value) len -= 1 return r async def _receive_resp(self, c): if self.kill_active: return if c == b':': return await self._read_int() elif c == b'$': return await self._read_bytes() elif c == b'*': return await self._read_array() elif c == b',': return await self._read_float() else: raise Exception('Unknown RESP start char %s' % c) async def receive_commands(self): while True: if self.kill_active: self.reply_terminating() return try: c = await self._reader.readexactly(1) if c in b':*$,': value = await self._receive_resp(c) if not isinstance(value, list): value = [value, ] else: command = c + await self._reader.readuntil(b'\r\n') value = [x.strip().encode() for x in command.decode().split(' ')] except (ConnectionAbortedError, ConnectionResetError, IncompleteReadError, TimeoutError) as e: # Connection is closed self.receive_commands_end(e) return await self.on_command_received(*value) async def on_command_received(self, command): raise NotImplemented() def reply_terminating(self): raise NotImplemented() def receive_commands_end(self, exc): raise NotImplemented() class LiveLockProtocol(CommandProtocol): def __init__(self, adaptor, password, max_payload, shutdown_support=False, *args, **kwargs): self.password = password self.adaptor = adaptor self.max_payload = max_payload self.client_id = None self.client_info = None self.shutdown_support = shutdown_support self._authorized = None self.transport = None self.debug = get_settings(None, 'LIVELOCK_DEBUG', False) self.lazy_client_display = LazyArg(self.client_display) super().__init__(*args, **kwargs) def client_display(self): if self.transport: peername = self.transport.get_extra_info('peername') else: peername = 'no_peer_address' return f'{peername} ({self.client_info}), client={self.client_id}' def connection_made(self, transport): if self.adaptor.kill_active: return logger.debug('Connection from %s', LazyArg(lambda: transport.get_extra_info('peername'))) self.transport = transport super().connection_made(transport) def receive_commands_end(self, exc): logger.debug('Receive command loop ended for %s, Exception=%s', self.lazy_client_display, exc) def eof_received(self): logger.debug('EOF received for %s', self.lazy_client_display) return super().eof_received() def connection_lost(self, exc): peername = self.transport.get_extra_info('peername') if self.adaptor.kill_active: logger.debug('Connection lost on active kill %s client=%s, Exception=%s', self.lazy_client_display, self.client_id, exc) return logger.debug('Connection lost %s, Exception=%s', self.lazy_client_display, exc) if self.client_id: last_address = self.adaptor.get_client_last_address(self.client_id) if last_address is None: logger.warning('Client last address is empty') if (last_address and last_address == peername) or last_address is None: # Releasing all client locks only if last known connection is dropped # other old connection can be dead self.adaptor.release_all(self.client_id) super().connection_lost(exc) @property def kill_active(self): return self.adaptor.kill_active async def on_command_received(self, command, *args): st = default_timer() verb = 'unknown' try: verb = await self.process_command(command, *args) finally: latency.labels(verb if verb is not None else 'unknown').observe(max(default_timer() - st, 0)) async def process_command(self, command, *args): if self.kill_active: self.reply_terminating() return peername = self.transport.get_extra_info('peername') verb = command.decode().lower() logger.debug('Got command %s from %s', command, self.lazy_client_display) await self.adaptor.on_command_start() try: if self.password and not self._authorized: if verb == 'pass': if len(args) == 1 and args[0]: password = args[0].decode() if password == self.password: self._authorized = True self._reply(True) return self._reply(PASS_ERROR) self.transport.close() if verb == 'conn': if self.client_id: self._reply(CONN_HAS_ID_ERROR) if args: if not args[0]: self._reply(WRONG_ARGS) return self.client_id = args[0].decode() # Restoring client locks self.adaptor.unrelease_all(self.client_id) else: self.client_id = str(uuid.uuid4()) # Saving client last connection source address for making decision to call release_all on connection lost self.adaptor.set_client_last_address(self.client_id, peername) self._reply(self.client_id) return else: if not self.client_id: self._reply(CONN_REQUIRED_ERROR) return if verb == 'conninfo': if len(args) != 1 or not args[0]: self._reply(WRONG_ARGS) return try: client_info = args[0].decode() except: self._reply(WRONG_ARGS) return logger.debug('Got client info for %s = %s', self.lazy_client_display, client_info) if self.client_info: if self.client_info != client_info: logger.warning('Client info changed for %s', self.lazy_client_display) self.client_info = client_info self._reply(True) elif verb in ('aq', 'aqr'): if len(args) != 1 or not args[0]: self._reply(WRONG_ARGS) return try: lock_id = args[0].decode() except: self._reply(WRONG_ARGS) return res = self.acquire(client_id=self.client_id, lock_id=lock_id, reentrant=(verb == 'aqr')) self._reply(res) elif verb == 'release': if len(args) != 1 or not args[0]: self._reply(WRONG_ARGS) return try: lock_id = args[0].decode() except: self._reply(WRONG_ARGS) return res = self.release(client_id=self.client_id, lock_id=lock_id) self._reply(res) elif verb == 'locked': if len(args) != 1 or not args[0]: self._reply(WRONG_ARGS) return try: lock_id = args[0].decode() except: self._reply(WRONG_ARGS) return res = self.locked(lock_id=lock_id) self._reply(res) elif verb == 'sigset': if len(args) != 2 or not args[0] or not args[1]: self._reply(WRONG_ARGS) return try: lock_id = args[0].decode() signal = args[1].decode() except: self._reply(WRONG_ARGS) return res = self.add_signal(lock_id, signal) self._reply(res) elif verb == 'sigexists': if len(args) != 2 or not args[0] or not args[1]: self._reply(WRONG_ARGS) return try: lock_id = args[0].decode() signal = args[1].decode() except: self._reply(WRONG_ARGS) return res = self.has_signal(lock_id, signal) self._reply(res) elif verb == 'sigdel': if len(args) != 2 or not args[0] or not args[1]: self._reply(WRONG_ARGS) return try: lock_id = args[0].decode() signal = args[1].decode() except: self._reply(WRONG_ARGS) return res = self.remove_signal(lock_id, signal) self._reply(res) elif verb == 'ping': self._reply('PONG') elif verb == 'find': if len(args) != 1 or not args[0]: self._reply(WRONG_ARGS) return result = list(self.adaptor.find(args[0].decode())) self._reply_data(result) elif verb == 'stats': if len(args): self._reply(WRONG_ARGS) return result = self.adaptor.stats() self._reply_data(result) elif verb == 'shutdown' and self.shutdown_support: logger.debug('SHUTDOWN invoked by %s', self.lazy_client_display) self.adaptor.terminate() self._reply('1') else: if self.debug: if verb == 'dump': if hasattr(self.adaptor, 'dump'): self.adaptor.dump() self._reply('1') else: self._reply('0') return self._reply(UNKNOWN_COMMAND_ERROR) finally: self.adaptor.on_command_end() # For stats returning verb return verb def _reply_data(self, data): payload = pack_resp(data) self.transport.write(payload) def reply_terminating(self): self._reply(SERVER_TERMINATING) def _reply(self, content): prefix = '+' if content is True: content = '1' elif content is False: content = '0' elif isinstance(content, int): content = '%s %s' % (content, ERRORS[content]) prefix = '-' payload = '%s%s\r\n' % (prefix, content) payload = payload.encode() self.transport.write(payload) def acquire(self, client_id, lock_id, reentrant): res = self.adaptor.acquire(client_id, lock_id, reentrant) return res def release(self, client_id, lock_id): res = self.adaptor.release(client_id, lock_id) return res def locked(self, lock_id): res = self.adaptor.locked(lock_id) return res def add_signal(self, lock_id, signal): res = self.adaptor.add_signal(lock_id, signal.lower()) return res def has_signal(self, lock_id, signal): res = self.adaptor.has_signal(lock_id, signal.lower()) return res def remove_signal(self, lock_id, signal): res = self.adaptor.remove_signal(lock_id, signal.lower()) return res class StorageOperationGuard(object): def __init__(self, parent): self.parent = parent def __enter__(self): if self.parent.kill_active: raise Exception('Lock storage write operations disabled') self.parent.on_storage_operation_start() def __exit__(self, exc_type, exc_val, exc_tb): self.parent.on_storage_operation_end() async def stats_collector(adaptor): while True: st = time.time() max_live_lock = 0 locks = list(adaptor.find('*')) if locks: now = time.time() first_lock = min(locks, key=lambda x: x[1]) max_live_lock = int(now - first_lock[1]) lock_count.set(len(locks)) max_lock_live_time.set(max_live_lock) stats_collection_time.inc(time.time() - st) stats_collection_count.inc() await asyncio.sleep(5) async def maintenance_scheduler(adaptor, period, timeout_ms): """ "Sampling" scheduler of maintenance call """ logger.debug('Starting maintenance scheduler, period %s, timeout_ms %s', period, timeout_ms) while True: if not adaptor.is_commands_in_process() and not adaptor.kill_active: # Can do maintenance st = time.time() adaptor.maintenance(timeout_ms=timeout_ms) ed = time.time() t = (ed - st) * 1000 logger.debug('Maintenance time %s ms', t) if t > timeout_ms: logger.warning('Maintenance timeout exceeded, configured=%s ms, actual=%s ms, ', timeout_ms, t) maintenance_time.inc(t) maintenance_count.inc() else: logger.debug('Skipping maintenance') await asyncio.sleep(period) async def live_lock_server(bind_to, port, release_all_timeout, password=None, max_payload=None, data_dir=None, shutdown_support=None, tcp_keepalive_time=None, tcp_keepalive_interval=None, tcp_keepalive_probes=None, tcp_user_timeout_seconds=None, disable_dump_load=None, ): # Sanitize values tcp_keepalive_time = int(tcp_keepalive_time) if tcp_keepalive_time else None tcp_keepalive_interval = int(tcp_keepalive_interval) if tcp_keepalive_interval else None tcp_keepalive_probes = int(tcp_keepalive_probes) if tcp_keepalive_probes else None tcp_user_timeout_seconds = int(tcp_user_timeout_seconds) if tcp_user_timeout_seconds else None loop = asyncio.get_running_loop() try: port = int(port) except: raise Exception(f'Live lock server port is not integer: {port}') if data_dir: os.chdir(data_dir) else: data_dir = os.getcwd() storage = InMemoryLockStorage(release_all_timeout=release_all_timeout) if not disable_dump_load: logger.info('Loading dump') storage.load_dump() stats = storage.stats() logger.info('Locks loaded from dump: %s', stats.get("lock_count", 0)) logger.info('Starting live lock server at %s, %s', bind_to, port) logger.debug('release_all_timeout=%s', release_all_timeout) logger.debug('data_dir=%s', data_dir) adaptor = StorageAdaptor(storage) server = await loop.create_server(lambda: LiveLockProtocol(adaptor=adaptor, password=password, max_payload=max_payload, shutdown_support=shutdown_support, tcp_keepalive_time=tcp_keepalive_time, tcp_keepalive_interval=tcp_keepalive_interval, tcp_keepalive_probes=tcp_keepalive_probes, tcp_user_timeout_seconds=tcp_user_timeout_seconds, ), bind_to, port) def exception_handler(loop, context): if not isinstance(context['exception'], SystemExit): raise context['exception'] loop.set_exception_handler(exception_handler) if prometheus_client_installed: stats_collector_task = loop.create_task(stats_collector(adaptor)) maintenance_scheduler_task = loop.create_task(maintenance_scheduler(adaptor, period=get_float_settings(None, 'LIVELOCK_MAINTENANCE_PERIOD', DEFAULT_MAINTENANCE_PERIOD), timeout_ms=get_int_settings(None, 'LIVELOCK_MAINTENANCE_TIMEOUT_MS', DEFAULT_MAINTENANCE_TIMEOUT_MS))) async with server: await server.serve_forever() if prometheus_client_installed: stats_collector_task.cancel() maintenance_scheduler_task.cancel() def start(bind_to=DEFAULT_BIND_TO, port=None, release_all_timeout=None, password=None, max_payload=None, data_dir=None, shutdown_support=None, tcp_keepalive_time=None, tcp_keepalive_interval=None, tcp_keepalive_probes=None, tcp_user_timeout_seconds=None, disable_dump_load=None, ): sentry_dsn = get_settings(None, 'SENTRY_DSN', None) if sentry_dsn: logger.debug('Turning ON sentry') try: import sentry_sdk sentry_sdk.init(dsn=sentry_dsn) except ImportError: logger.error('No sentry-sdk installed') env_loglevel = get_settings(None, 'LIVELOCK_LOGLEVEL', DEFAULT_LOGLEVEL) loglevel = getattr(logging, env_loglevel.upper()) logging.basicConfig(level=loglevel, format='%(name)s:[%(levelname)s]: %(message)s') prometheus_port = get_settings(port, 'LIVELOCK_PROMETHEUS_PORT', DEFAULT_PROMETHEUS_PORT) if prometheus_port: try: prometheus_port = int(prometheus_port) except: logger.critical('Wrong prometheus port %s', prometheus_port) prometheus_port = None if prometheus_port: try: from prometheus_client import start_http_server except ImportError: logger.info('Prometheus port is set but prometheus_client not installed (pip install prometheus-client)') prometheus_port = None if prometheus_port: logger.info('Starting prometheus metrics server at port %s', prometheus_port) start_http_server(prometheus_port) asyncio.run(live_lock_server(bind_to=get_settings(bind_to, DEFAULT_BIND_TO, 'LIVELOCK_BIND_TO'), port=get_settings(port, 'LIVELOCK_PORT', DEFAULT_LIVELOCK_SERVER_PORT), release_all_timeout=get_settings(release_all_timeout, 'LIVELOCK_RELEASE_ALL_TIMEOUT', DEFAULT_RELEASE_ALL_TIMEOUT), password=get_settings(password, 'LIVELOCK_PASSWORD', None), max_payload=get_settings(max_payload, 'LIVELOCK_MAX_PAYLOAD', DEFAULT_MAX_PAYLOAD), data_dir=get_settings(data_dir, 'LIVELOCK_DATA_DIR', None), shutdown_support=get_settings(shutdown_support, 'LIVELOCK_SHUTDOWN_SUPPORT', DEFAULT_SHUTDOWN_SUPPORT), tcp_keepalive_time=get_settings(tcp_keepalive_time, 'LIVELOCK_TCP_KEEPALIVE_TIME', DEFAULT_TCP_KEEPALIVE_TIME), tcp_keepalive_interval=get_settings(tcp_keepalive_interval, 'LIVELOCK_TCP_KEEPALIVE_INTERVAL', DEFAULT_TCP_KEEPALIVE_INTERVAL), tcp_keepalive_probes=get_settings(tcp_keepalive_probes, 'LIVELOCK_TCP_KEEPALIVE_PROBES', DEFAULT_TCP_KEEPALIVE_PROBES), tcp_user_timeout_seconds=get_settings(tcp_user_timeout_seconds, 'LIVELOCK_TCP_USER_TIMEOUT_SECONDS', DEFAULT_TCP_USER_TIMEOUT_SECONDS), disable_dump_load=get_settings(disable_dump_load, 'LIVELOCK_DISABLE_DUMP_LOAD', DEFAULT_DISABLE_DUMP_LOAD), ))
UTF-8
Python
false
false
31,248
py
19
server.py
16
0.55163
0.5482
0
769
39.563069
179
Oneflow-Inc/oneflow_convert_tools
3,307,124,850,380
36e9733468c3d435d9be826a6472de1b0c544134
9c4987a2db63a269ca86b035fb1c5924342a8ee6
/oneflow_onnx/oneflow2onnx/handlers/math.py
588f52195d7f141d76df440f4d1e36677faedfbe
[]
no_license
https://github.com/Oneflow-Inc/oneflow_convert_tools
6d50b11a190f173071b89984a851c266af888995
6bb9b54dcfa78eaaddaa117b8af423ab328451cb
refs/heads/main
2023-07-09T19:46:46.472939
2023-03-07T07:38:58
2023-03-07T07:38:58
347,891,709
22
4
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Copyright 2020 The OneFlow 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. """ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT license. from __future__ import division from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import import logging import math import oneflow import numpy as np from onnx import onnx_pb from onnx import TensorProto from oneflow_onnx import constants, util from oneflow_onnx.oneflow2onnx.handler import flow_op from oneflow_onnx.oneflow2onnx.handlers import common logger = logging.getLogger(__name__) # pylint: disable=unused-argument,missing-docstring @flow_op(["broadcast_add", "scalar_add_by_tensor"], onnx_op="Add") @flow_op(["broadcast_sub", "scalar_sub_by_tensor"], onnx_op="Sub", flow_ibns=["x", "y"]) @flow_op(["multiply", "broadcast_mul", "scalar_mul_by_tensor"], onnx_op="Mul") @flow_op(["broadcast_div", "scalar_div_by_tensor"], onnx_op="Div", flow_ibns=["x", "y"]) class BroadcastOp(common.BroadcastOp): pass @flow_op("scalar_mul", "Mul") @flow_op("scalar_add", "Add") @flow_op("scalar_div", "Div") class ScalarBinaryOp: @classmethod def Version_6(cls, ctx, node, **kwargs): scalar_val = node.attrs["int_operand"] if node.attrs["has_int_operand"] else node.attrs["float_operand"] np_dtype = util.Onnx2NumpyDtype(ctx.get_dtype(node.input_tensor_names[0])) scalar_node = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("scalar"), np.array([scalar_val]).astype(np_dtype)) node.input_tensor_names.append(scalar_node.output_tensor_names[0]) @flow_op("add_n", onnx_op="Add") class AddN: @classmethod def Version_1(cls, ctx, node, **kwargs): input_length = len(node.input_tensor_names) if input_length <= 2: pass else: ctx.RemoveNode(node.name) ctx.MakeNode("Sum", node.input_tensor_names, outputs=[node.output_tensor_names[0]], op_name_scope=node.name, name="mul") @flow_op("bias_add", onnx_op="Add", flow_ibns=["a", "b"]) class BiasAdd(common.BroadcastOp): @classmethod def Version_6(cls, ctx, node, **kwargs): axis = node.attrs["axis"] unsqueeze_axes = [] x_rank = len(ctx.get_shape(node.input_tensor_names[0])) for i in range(x_rank): if axis != i: unsqueeze_axes.append(i) unsqueeze_shape = [1] * x_rank assert len(ctx.get_shape(node.input_tensor_names[1])) == 1 unsqueeze_shape[axis] = ctx.get_shape(node.input_tensor_names[1])[0] unsqueeze_dtype = ctx.get_dtype(node.input_tensor_names[1]) ctx.InsertNewNodeOnInput(node, "Unsqueeze", node.input_tensor_names[1], axes=unsqueeze_axes) ctx.set_shape(node.input_tensor_names[1], unsqueeze_shape) ctx.set_dtype(node.input_tensor_names[1], unsqueeze_dtype) super().Version_6(ctx, node, **kwargs) @classmethod def Version_13(cls, ctx, node, **kwargs): axis = node.attrs["axis"] unsqueeze_axes = [] x_rank = len(ctx.get_shape(node.input_tensor_names[0])) for i in range(x_rank): if axis != i: unsqueeze_axes.append(i) assert len(ctx.get_shape(node.input_tensor_names[1])) == 1 shape_node = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("shape"), np.array(unsqueeze_axes)) ctx.InsertNewNodeOnInput(node, "Unsqueeze", [node.input_tensor_names[1], shape_node.output_tensor_names[0]]) super().Version_6(ctx, node, **kwargs) @flow_op(["leaky_relu", "softplus"], onnx_op=["LeakyRelu", "Softplus"]) class DirectOpSinceOpset1: @classmethod def Version_1(cls, ctx, node, **kwargs): pass @flow_op("prelu", onnx_op="PRelu", flow_ibns=["x", "alpha"]) class PReLUOp: @classmethod def Version_1(cls, ctx, node, **kwargs): input_shape = ctx.get_shape(node.input_tensor_names[0]) alpha_shape = ctx.get_shape(node.input_tensor_names[1]) if len(alpha_shape) == 1: new_shape = [] new_shape.append(alpha_shape[0]) for _ in range(1, len(input_shape) - 1): new_shape.append(1) ctx.set_shape(node.input_tensor_names[1], new_shape) @flow_op( [ "abs", "ceil", "elu", "exp", "floor", "log", "neg", "sigmoid", "sigmoid_v2", "sqrt", "tanh", "reciprocal", "relu", ], [ "Abs", "Ceil", "Elu", "Exp", "Floor", "Log", "Neg", "Sigmoid", "Sigmoid", "Sqrt", "Tanh", "Reciprocal", "Relu", ], ) class DirectOp: @classmethod def Version_1(cls, ctx, node, **kwargs): pass @classmethod def Version_6(cls, ctx, node, **kwargs): pass @flow_op( ["acos", "asin", "atan", "cos", "sin", "tan"], ["Acos", "Asin", "Atan", "Cos", "Sin", "Tan"], ) class TrigOpSinceOpset7: @classmethod def Version_7(cls, ctx, node, **kwargs): pass @flow_op( ["acosh", "asinh", "atanh", "cosh", "sinh"], ["Acosh", "Asinh", "Atanh", "Cosh", "Sinh"], ) class TrigOpSinceOpset9: @classmethod def Version_9(cls, ctx, node, **kwargs): pass def _MakeMinOrMaxOp(ctx, op_type, inputs, outputs, output_shapes=None, output_dtypes=None): # support more dtype supported_dtypes = [ onnx_pb.TensorProto.FLOAT, onnx_pb.TensorProto.FLOAT16, onnx_pb.TensorProto.DOUBLE, ] target_dtype = onnx_pb.TensorProto.FLOAT need_cast = False cast_inputs = [] for inp in inputs: dtype = ctx.get_dtype(inp) util.MakeSure(dtype is not None, "dtype of {} is None".format(inp)) if dtype not in supported_dtypes: cast_inp = ctx.MakeNode("Cast", [inp], attr={"to": target_dtype}) cast_inputs.append(cast_inp.output_tensor_names[0]) need_cast = True else: cast_inputs.append(inp) node = ctx.MakeNode(op_type, cast_inputs, shapes=output_shapes) actual_outputs = node.output_tensor_names if need_cast: origin_dtype = ctx.get_dtype(inputs[0]) if output_dtypes is not None: origin_dtype = output_dtypes[0] ctx.set_dtype(node.output_tensor_names[0], target_dtype) cast_name = oneflow._oneflow_internal.UniqueStr(node.name) cast_node = ctx.InsertNewNodeOnOutput("Cast", node.output_tensor_names[0], name=cast_name, to=origin_dtype) ctx.set_dtype(cast_node.output_tensor_names[0], origin_dtype) ctx.CopyShape(node.output_tensor_names[0], cast_node.output_tensor_names[0]) actual_outputs = cast_node.output_tensor_names ctx.MakeNode( "Identity", actual_outputs, outputs=outputs, shapes=output_shapes, dtypes=output_dtypes, ) # onnx < opset 8 does not support broadcasting # handle this by doing something like: # y = min(x1, add(x2, sub(x1, x1))), where x1, x2 are the inputs and x2 is a scalar # this will create a tensor of zeros of the shape of x1, adds x2 to it (which broadcasts) and use that for min. shapeo = ctx.get_shape(node.output_tensor_names[0]) needs_broadcast_op = [] has_correct_shape = [] if ctx.opset < 8: for i, input_name in enumerate(node.input_tensor_names): if ctx.get_shape(input_name) != shapeo: needs_broadcast_op.append(i) else: has_correct_shape.append(input_name) if needs_broadcast_op: has_correct_shape = has_correct_shape[0] for i in needs_broadcast_op: input_node = node.input_nodes[i] # get a tensor with zeros (since there is no Fill op as of opset8) sub_node = ctx.MakeNode( "Sub", [has_correct_shape, has_correct_shape], op_name_scope=input_node.name, ) # use add as 'broadcast' op add_node = ctx.MakeNode( "Add", [input_node.output_tensor_names[0], sub_node.output_tensor_names[0]], op_name_scope=input_node.name, ) node.input_tensor_names[i] = add_node.output_tensor_names[0] @flow_op("broadcast_minimum", onnx_op="Min") @flow_op("broadcast_maximum", onnx_op="Max") @flow_op("elementwise_minimum", onnx_op="Min") @flow_op("elementwise_maximum", onnx_op="Max") class MinMaxOp: @classmethod def Version_1(cls, ctx, node, **kwargs): shapes = node.output_shapes dtypes = node.output_dtypes ctx.RemoveNode(node.name) _MakeMinOrMaxOp( ctx, node.op_type, node.input_tensor_names, node.output_tensor_names, shapes, dtypes, ) @flow_op("hardswish", onnx_op="HardSwish") class HardSwish: @classmethod def Version_1(cls, ctx, node, **kwargs): dtypes = node.output_dtypes node1 = ctx.MakeNode("HardSigmoid", [node.input_tensor_names[0]], op_name_scope=node.name, name="hard_sigmoid", dtypes=dtypes, attr={"alpha": 1.0 / 6}) ctx.RemoveNode(node.name) ctx.MakeNode("Mul", [node.input_tensor_names[0], node1.output_tensor_names[0]], outputs=[node.output_tensor_names[0]], op_name_scope=node.name, name="mul") @classmethod def Version_14(cls, ctx, node, **kwargs): pass @flow_op("silu", onnx_op="Mul") class Silu: @classmethod def Version_1(cls, ctx, node, **kwargs): dtypes = node.output_dtypes sigmoid_node = ctx.MakeNode("Sigmoid", [node.input_tensor_names[0]], op_name_scope=node.name, name="sigmoid", dtypes=dtypes) ctx.RemoveNode(node.name) ctx.MakeNode("Mul", [node.input_tensor_names[0], sigmoid_node.output_tensor_names[0]], outputs=[node.output_tensor_names[0]], op_name_scope=node.name, name="mul") @classmethod def Version_10(cls, ctx, node, **kwargs): cls.Version_1(ctx, node, **kwargs) @flow_op(["gelu", "fast_gelu", "quick_gelu"]) class Gelu: @classmethod def Version_9(cls, ctx, node, **kwargs): dtypes = node.output_dtypes if node.op_type == "fast_gelu": kBeta = math.sqrt(2 / math.pi) kKappa = 0.044715 beta = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("beta"), np.array(kBeta, dtype=util.Onnx2NumpyDtype(dtypes[0]))) kappa = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("kKappa"), np.array(kKappa, dtype=util.Onnx2NumpyDtype(dtypes[0]))) one = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("one"), np.array(1.0, dtype=util.Onnx2NumpyDtype(dtypes[0]))) half = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("half"), np.array(0.5, dtype=util.Onnx2NumpyDtype(dtypes[0]))) mul_node_1 = ctx.MakeNode("Mul", [node.input_tensor_names[0], node.input_tensor_names[0]], op_name_scope=node.name, name="mul1", dtypes=dtypes) cube = ctx.MakeNode("Mul", [node.input_tensor_names[0], mul_node_1.output_tensor_names[0]], op_name_scope=node.name, name="cube", dtypes=dtypes) mul_node_2 = ctx.MakeNode("Mul", [kappa.output_tensor_names[0], cube.output_tensor_names[0]], op_name_scope=node.name, name="mul2", dtypes=dtypes) add_node_1 = ctx.MakeNode("Add", [mul_node_2.output_tensor_names[0], node.input_tensor_names[0]], op_name_scope=node.name, name="add1", dtypes=dtypes) inner = ctx.MakeNode("Mul", [add_node_1.output_tensor_names[0], beta.output_tensor_names[0]], op_name_scope=node.name, name="inner", dtypes=dtypes) tanh_node = ctx.MakeNode("Tanh", [inner.output_tensor_names[0]], op_name_scope=node.name, name="tanh", dtypes=dtypes) add_node_2 = ctx.MakeNode("Add", [tanh_node.output_tensor_names[0], one.output_tensor_names[0]], op_name_scope=node.name, name="add2", dtypes=dtypes) mul_node_3 = ctx.MakeNode("Mul", [add_node_2.output_tensor_names[0], node.input_tensor_names[0]], op_name_scope=node.name, name="mul3", dtypes=dtypes) ctx.RemoveNode(node.name) ctx.MakeNode("Mul", [mul_node_3.output_tensor_names[0], half.output_tensor_names[0]], outputs=[node.output_tensor_names[0]], op_name_scope=node.name, name="mul4", dtypes=dtypes) elif node.op_type == "gelu": _sqrt2 = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("sqrt2"), np.array(1.4142135623730951, dtype=util.Onnx2NumpyDtype(dtypes[0]))) div1 = ctx.MakeNode("Div", [node.input_tensor_names[0], _sqrt2.output_tensor_names[0]], op_name_scope=node.name, name="div1", dtypes=dtypes) erf = ctx.MakeNode("Erf", [div1.output_tensor_names[0]], op_name_scope=node.name, name="erf", dtypes=dtypes) one = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("one"), np.array(1.0, dtype=util.Onnx2NumpyDtype(dtypes[0]))) erf_plusone = ctx.MakeNode("Add", [one.output_tensor_names[0], erf.output_tensor_names[0]], op_name_scope=node.name, name="erf_plusone", dtypes=dtypes) half = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("half"), np.array(0.5, dtype=util.Onnx2NumpyDtype(dtypes[0]))) mul_node_1 = ctx.MakeNode("Mul", [node.input_tensor_names[0], erf_plusone.output_tensor_names[0]], op_name_scope=node.name, name="mul1", dtypes=dtypes) ctx.RemoveNode(node.name) ctx.MakeNode("Mul", [mul_node_1.output_tensor_names[0], half.output_tensor_names[0]], outputs=[node.output_tensor_names[0]], op_name_scope=node.name, name="mul2", dtypes=dtypes) elif node.op_type == "quick_gelu": beta = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("beta"), np.array(1.702, dtype=util.Onnx2NumpyDtype(dtypes[0]))) mul_node_1 = ctx.MakeNode("Mul", [node.input_tensor_names[0], beta.output_tensor_names[0]], op_name_scope=node.name, name="mul1", dtypes=dtypes) sigmoid_node = ctx.MakeNode("Sigmoid", [mul_node_1.output_tensor_names[0]], op_name_scope=node.name, name="sigmoid", dtypes=dtypes) ctx.RemoveNode(node.name) ctx.MakeNode("Mul", [node.input_tensor_names[0], sigmoid_node.output_tensor_names[0]], outputs=[node.output_tensor_names[0]], op_name_scope=node.name, name="mul2", dtypes=dtypes) @flow_op("hardsigmoid", onnx_op="HardSigmoid") class HardSigmoid: @classmethod def Version_1(cls, ctx, node, **kwargs): node.attrs["alpha"] = 1.0 / 6 pass @flow_op("scalar_pow", onnx_op="Pow") class ScalarPow: @classmethod def Version_1(cls, ctx, node, **kwargs): np_dtype = util.Onnx2NumpyDtype(ctx.get_dtype(node.input_tensor_names[0])) if node.attrs["has_float_operand"]: y = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("start"), np.array(node.attrs["float_operand"]).astype(np_dtype)) node.input_tensor_names.append(y.output_tensor_names[0]) else: y = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("start"), np.array(node.attrs["int_operand"]).astype(np_dtype)) node.input_tensor_names.append(y.output_tensor_names[0]) @flow_op("scalar_logical_less", onnx_op="Less") @flow_op("scalar_logical_greater", onnx_op="Greater") class ScalarPow: @classmethod def Version_1(cls, ctx, node, **kwargs): np_dtype = util.Onnx2NumpyDtype(ctx.get_dtype(node.input_tensor_names[0])) node.attrs["broadcast"] = 1 if node.attrs["has_float_operand"]: y = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("start"), np.array(node.attrs["float_operand"]).astype(np_dtype)) node.input_tensor_names.append(y.output_tensor_names[0]) elif node.attrs["has_int_operand"]: y = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("start"), np.array(node.attrs["int_operand"]).astype(np_dtype)) node.input_tensor_names.append(y.output_tensor_names[0]) @flow_op("arange", onnx_op="Range") class Arange: @classmethod def Version_1(cls, ctx, node, **kwargs): if node.attrs["dtype"] == 1: starts = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("start"), np.array(node.attrs["float_start"])) node.input_tensor_names.append(starts.output_tensor_names[0]) limits = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("limit"), np.array(node.attrs["float_limit"])) node.input_tensor_names.append(limits.output_tensor_names[0]) delta = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("delta"), np.array(node.attrs["float_delta"])) node.input_tensor_names.append(delta.output_tensor_names[0]) else: starts = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("start"), np.array(node.attrs["integer_start"])) node.input_tensor_names.append(starts.output_tensor_names[0]) limits = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("limit"), np.array(node.attrs["integer_limit"])) node.input_tensor_names.append(limits.output_tensor_names[0]) delta = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("delta"), np.array(node.attrs["integer_delta"])) node.input_tensor_names.append(delta.output_tensor_names[0]) @classmethod def Version_11(cls, ctx, node, **kwargs): cls.Version_1(ctx, node, **kwargs) class ClipOps: @classmethod def Version_1(cls, ctx, node, min_val=None, max_val=None, **kwargs): # relu6 = min(max(features, 0), 6) node.op_type = "Clip" if min_val is not None: node.attrs["min"] = float(min_val) if max_val is not None: node.attrs["max"] = float(max_val) @classmethod def Version_11(cls, ctx, node, min_val=None, max_val=None, **kwargs): # add min and max as inputs node.op_type = "Clip" onnx_dtype = ctx.get_dtype(node.input_tensor_names[0]) np_dtype = util.ONNX_2_NUMPY_DTYPE[onnx_dtype] if min_val is not None: clip_min = ctx.MakeConst( oneflow._oneflow_internal.UniqueStr("{}_min".format(node.name)), np.array(min_val, dtype=np_dtype), ) node.input_tensor_names.append(clip_min.output_tensor_names[0]) else: node.input_tensor_names.append("") if max_val is not None: clip_max = ctx.MakeConst( oneflow._oneflow_internal.UniqueStr("{}_max".format(node.name)), np.array(max_val, dtype=np_dtype), ) node.input_tensor_names.append(clip_max.output_tensor_names[0]) else: node.input_tensor_names.append("") @flow_op("hardtanh", onnx_op="Clip") class HardTanh(ClipOps): @classmethod def Version_1(cls, ctx, node, **kwargs): min_val = 0.0 max_val = 6.0 super().Version_1(ctx, node, min_val, max_val) @flow_op(["clip_by_scalar", "clip_by_scalar_min", "clip_by_scalar_max"], onnx_op="Clip") class ClipByValueOp(ClipOps): @classmethod def Version_1(cls, ctx, node, **kwargs): min_val = node.attrs.get("floating_min", None) or node.attrs.get("integral_min", None) max_val = node.attrs.get("floating_max", None) or node.attrs.get("integral_max", None) super().Version_1(ctx, node, min_val, max_val) @classmethod def Version_11(cls, ctx, node, **kwargs): min_val = node.attrs.get("floating_min", None) or node.attrs.get("integral_min", None) max_val = node.attrs.get("floating_max", None) or node.attrs.get("integral_max", None) super().Version_11(ctx, node, min_val, max_val) @flow_op("softmax", "Softmax") class Softmax: @classmethod def Version_1(cls, ctx, node, **kwargs): # T output = Softmax(T logits). The axis softmax would be performed on is always on -1. # T output = Softmax(T input, @int axis). Default axis is 1. logits_rank = len(ctx.get_shape(node.input_tensor_names[0])) node.attrs["axis"] = logits_rank - 1 @classmethod def Version_11(cls, ctx, node, **kwargs): cls.Version_1(ctx, node, **kwargs) @flow_op("square", None) class Square: @classmethod def Version_1(cls, ctx, node, **kwargs): node.op_type = "Mul" node.input_tensor_names.append(node.input_tensor_names[0]) @flow_op("rsqrt", None) class Rsqrt: @classmethod def Version_1(cls, ctx, node, **kwargs): node.op_type = "Sqrt" op_name = oneflow._oneflow_internal.UniqueStr(node.name) reciprocal = ctx.InsertNewNodeOnOutput("Reciprocal", node.output_tensor_names[0], name=op_name) ctx.CopyShape(node.output_tensor_names[0], reciprocal.output_tensor_names[0]) @flow_op("squared_difference", None) class SquaredDifference: @classmethod def Version_1(cls, ctx, node, **kwargs): node.op_type = "Sub" op_name = oneflow._oneflow_internal.UniqueStr(node.name) mul = ctx.InsertNewNodeOnOutput("Mul", node.output_tensor_names[0], name=op_name) mul.input_tensor_names.append(node.output_tensor_names[0]) @flow_op("sign", onnx_op="Sign") class Sign: @classmethod def Version_1(cls, ctx, node, **kwargs): """Sign op.""" # T sign = Sign(T Input) node_dtype = ctx.get_dtype(node.output_tensor_names[0]) util.MakeSure(node_dtype, "Dtype of {} is None".format(node.name)) if node_dtype in [ onnx_pb.TensorProto.COMPLEX64, onnx_pb.TensorProto.COMPLEX128, ]: raise ValueError("dtype " + str(node_dtype) + " is not supported in onnx for now") zero_name = oneflow._oneflow_internal.UniqueStr("{}_zero".format(node.name)) ctx.MakeConst(zero_name, np.array(0, dtype=np.float32)) if node_dtype not in [ onnx_pb.TensorProto.FLOAT16, onnx_pb.TensorProto.FLOAT, onnx_pb.TensorProto.DOUBLE, ]: cast_node_0 = ctx.MakeNode("Cast", [node.input_tensor_names[0]], {"to": onnx_pb.TensorProto.FLOAT}) greater_node = ctx.MakeNode("Greater", [cast_node_0.output_tensor_names[0], zero_name]) less_node = ctx.MakeNode("Less", [cast_node_0.output_tensor_names[0], zero_name]) else: greater_node = ctx.MakeNode("Greater", [node.input_tensor_names[0], zero_name]) less_node = ctx.MakeNode("Less", [node.input_tensor_names[0], zero_name]) cast_node_1 = ctx.MakeNode("Cast", [greater_node.output_tensor_names[0]], {"to": node_dtype}) cast_node_2 = ctx.MakeNode("Cast", [less_node.output_tensor_names[0]], {"to": node_dtype}) shapes = node.output_shapes dtypes = node.output_dtypes ctx.RemoveNode(node.name) ctx.MakeNode( "Sub", [cast_node_1.output_tensor_names[0], cast_node_2.output_tensor_names[0]], outputs=[node.output_tensor_names[0]], shapes=shapes, dtypes=dtypes, ) @classmethod def Version_9(cls, ctx, node, **kwargs): node_dtype = ctx.get_dtype(node.output_tensor_names[0]) util.MakeSure(node_dtype, "dtype of {} is None".format(node.name)) if node_dtype in [ onnx_pb.TensorProto.BOOL, onnx_pb.TensorProto.COMPLEX64, onnx_pb.TensorProto.COMPLEX128, ]: raise ValueError("dtype " + str(node_dtype) + " is not supported in onnx for now") @flow_op(["matmul", "batch_matmul", "broadcast_matmul"], "MatMul", flow_ibns=["a", "b"]) class MatMul: @classmethod def Version_1(cls, ctx, node, **kwargs): transpose_a = node.attrs.get("transpose_a", 0) transpose_b = node.attrs.get("transpose_b", 0) alpha = node.attrs.get("alpha") if transpose_a != 0: shape = ctx.get_shape(node.input_tensor_names[0]) if shape: perm = list(range(0, len(shape))) tmp = perm[-1] perm[-1] = perm[-2] perm[-2] = tmp ctx.InsertNewNodeOnInput(node, "Transpose", node.input_tensor_names[0], perm=perm) if transpose_b != 0: shape = ctx.get_shape(node.input_tensor_names[1]) if shape: perm = list(range(0, len(shape))) tmp = perm[-1] perm[-1] = perm[-2] perm[-2] = tmp ctx.InsertNewNodeOnInput(node, "Transpose", node.input_tensor_names[1], perm=perm) unsupported = ["a_is_sparse", "b_is_sparse"] for i in unsupported: val = node.attrs.get(i, 0) if val != 0: raise ValueError(node.op_type + " attribute " + i + " is not supported") if alpha != 1.0: dtypes = node.output_dtypes alpha = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("alpha"), np.array(alpha, dtype=util.Onnx2NumpyDtype(dtypes[0]))) op_name = oneflow._oneflow_internal.UniqueStr(node.name) mul = ctx.InsertNewNodeOnOutput("Mul", node.output_tensor_names[0], op_name_scope=node.name, name=op_name) mul.input_tensor_names.append(alpha.output_tensor_names[0]) ctx.set_dtype(mul.output_tensor_names[0], ctx.get_dtype(node.output_tensor_names[0])) ctx.CopyShape(node.output_tensor_names[0], mul.output_tensor_names[0]) @flow_op("fused_self_attention_query_mul_key_and_value") class FusedSelfAttention: @classmethod def Version_1(cls, ctx, node, **kwargs): head_size = node.attrs.get("head_size") scope = node.name output_name1 = node.output_tensor_names[0] output_name2 = node.output_tensor_names[1] dtypes = node.output_dtypes shape = ctx.get_shape(node.input_tensor_names[0]) new_shape = [shape[0], shape[1], int(shape[2] / 3 / head_size), 3 * head_size] starts_q = ctx.MakeConst( oneflow._oneflow_internal.UniqueStr("start_q"), np.array([0]).astype(np.int64), ) ends_q = ctx.MakeConst( oneflow._oneflow_internal.UniqueStr("stop_q"), np.array([head_size]).astype(np.int64), ) starts_k = ctx.MakeConst( oneflow._oneflow_internal.UniqueStr("start_k"), np.array([head_size]).astype(np.int64), ) ends_k = ctx.MakeConst( oneflow._oneflow_internal.UniqueStr("stop_k"), np.array([2 * head_size]).astype(np.int64), ) starts_v = ctx.MakeConst( oneflow._oneflow_internal.UniqueStr("start_v"), np.array([2 * head_size]).astype(np.int64), ) ends_v = ctx.MakeConst( oneflow._oneflow_internal.UniqueStr("stop_v"), np.array([3 * head_size]).astype(np.int64), ) steps = ctx.MakeConst( oneflow._oneflow_internal.UniqueStr("steps"), np.array([1]).astype(np.int64), ) axes = ctx.MakeConst( oneflow._oneflow_internal.UniqueStr("axes"), np.array([3]).astype(np.int64), ) # reshape new_shape_name = oneflow._oneflow_internal.UniqueStr("new_shape") ctx.MakeConst(new_shape_name, np.array(new_shape, dtype=np.int64)) reshape = ctx.MakeNode("Reshape", [node.input_tensor_names[0], new_shape_name]) # query slice_node_q = ctx.MakeNode( "Slice", [ reshape.output_tensor_names[0], starts_q.output_tensor_names[0], ends_q.output_tensor_names[0], axes.output_tensor_names[0], steps.output_tensor_names[0], ], ) transpose_node_q = ctx.MakeNode("Transpose", [slice_node_q.output_tensor_names[0]], attr={"perm": [1, 2, 0, 3]}) # key slice_node_k = ctx.MakeNode( "Slice", [ reshape.output_tensor_names[0], starts_k.output_tensor_names[0], ends_k.output_tensor_names[0], axes.output_tensor_names[0], steps.output_tensor_names[0], ], ) transpose_node_k = ctx.MakeNode("Transpose", [slice_node_k.output_tensor_names[0]], attr={"perm": [1, 2, 3, 0]}) # value slice_node_v = ctx.MakeNode( "Slice", [ reshape.output_tensor_names[0], starts_v.output_tensor_names[0], ends_v.output_tensor_names[0], axes.output_tensor_names[0], steps.output_tensor_names[0], ], ) transpose_node_v = ctx.MakeNode("Transpose", [slice_node_v.output_tensor_names[0]], attr={"perm": [1, 2, 0, 3]}) # q * k matmul_node_qk = ctx.MakeNode( "MatMul", [transpose_node_q.output_tensor_names[0], transpose_node_k.output_tensor_names[0]], name="matmul_qk", op_name_scope=scope, ) ctx.RemoveNode(node.name) ctx.MakeNode("Identity", [matmul_node_qk.output_tensor_names[0]], outputs=[output_name1], op_name_scope=node.name, dtypes=[dtypes[0]]) ctx.MakeNode("Identity", [transpose_node_v.output_tensor_names[0]], outputs=[output_name2], op_name_scope=node.name, dtypes=[dtypes[0]]) @flow_op("erf", onnx_op="Erf") class Erf: @classmethod def Version_1(cls, ctx, node, **kwargs): """Error function.""" # constant names a1 = "erf_a1" a2 = "erf_a2" a3 = "erf_a3" a4 = "erf_a4" a5 = "erf_a5" p = "erf_p" one = "erf_one" null = "erf_null" n = node.name output_name = node.output_tensor_names[0] erf_a1_node = ctx.get_node_by_output("erf_a1") if erf_a1_node is None: # insert the constants for erf once ctx.MakeConst(a1, np.array(0.254829592, dtype=np.float32)) ctx.MakeConst(a2, np.array(-0.284496736, dtype=np.float32)) ctx.MakeConst(a3, np.array(1.421413741, dtype=np.float32)) ctx.MakeConst(a4, np.array(-1.453152027, dtype=np.float32)) ctx.MakeConst(a5, np.array(1.061405429, dtype=np.float32)) ctx.MakeConst(p, np.array(0.3275911, dtype=np.float32)) ctx.MakeConst(one, np.array(1.0, dtype=np.float32)) ctx.MakeConst(null, np.array(0.0, dtype=np.float32)) x = node.input_tensor_names[0] # erf(x): # sign = 1 if x >= 0 else -1 # x = abs(x) # # A&S formula 7.1.26 # t = 1.0 / (1.0 + p * x) # y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * math.exp(-x * x) # return sign * y # erf(-x) = -erf(x) x_node = ctx.MakeNode("Abs", [x], op_name_scope=node.name, name="x") negx_node = ctx.MakeNode("Sub", [null, x], op_name_scope=node.name, name="negx") is_positive_node = ctx.MakeNode("Greater", [x, null], op_name_scope=node.name, name="isPositive") is_positive_value_node = ctx.MakeNode( "Cast", is_positive_node.output_tensor_names, op_name_scope=node.name, name="isPositiveValue", attr={"to": onnx_pb.TensorProto.FLOAT}, ) is_neg_node = ctx.MakeNode("Less", [x, null], op_name_scope=node.name, name="isNeg") ig_neg_value_node = ctx.MakeNode( "Cast", is_neg_node.output_tensor_names, op_name_scope=node.name, name="isNegValue", attr={"to": onnx_pb.TensorProto.FLOAT}, ) sign0_node = ctx.MakeNode( "Sub", [ is_positive_value_node.output_tensor_names[0], ig_neg_value_node.output_tensor_names[0], ], op_name_scope=node.name, name="sign0", ) sign_add_one_node = ctx.MakeNode( "Add", [sign0_node.output_tensor_names[0], one], op_name_scope=node.name, name="signAddOne", ) non_zero_node = ctx.MakeNode( "Abs", sign0_node.output_tensor_names, op_name_scope=node.name, name="nonZero", ) sign_node = ctx.MakeNode( "Sub", [ sign_add_one_node.output_tensor_names[0], non_zero_node.output_tensor_names[0], ], op_name_scope=node.name, name="sign", ) num_4_node = ctx.MakeNode("Mul", [x_node.output_tensor_names[0], p], op_name_scope=node.name, name="4") num_5_node = ctx.MakeNode( "Add", [num_4_node.output_tensor_names[0], one], op_name_scope=node.name, name="5", ) t_node = ctx.MakeNode( "Div", [one, num_5_node.output_tensor_names[0]], op_name_scope=node.name, name="t", ) xsq_node = ctx.MakeNode( "Mul", [x, negx_node.output_tensor_names[0]], op_name_scope=node.name, name="xsq", ) num_6_node = ctx.MakeNode("Exp", xsq_node.output_tensor_names, op_name_scope=node.name, name="6") num_7_node = ctx.MakeNode( "Mul", [num_6_node.output_tensor_names[0], t_node.output_tensor_names[0]], op_name_scope=node.name, name="7", ) num_8_node = ctx.MakeNode( "Mul", [t_node.output_tensor_names[0], a5], op_name_scope=node.name, name="8", ) num_9_node = ctx.MakeNode( "Add", [num_8_node.output_tensor_names[0], a4], op_name_scope=node.name, name="9", ) num_10_node = ctx.MakeNode( "Mul", [num_9_node.output_tensor_names[0], t_node.output_tensor_names[0]], op_name_scope=node.name, name="10", ) num_11_node = ctx.MakeNode( "Add", [num_10_node.output_tensor_names[0], a3], op_name_scope=node.name, name="11", ) num_12_node = ctx.MakeNode( "Mul", [num_11_node.output_tensor_names[0], t_node.output_tensor_names[0]], op_name_scope=node.name, name="12", ) num_13_node = ctx.MakeNode( "Add", [num_12_node.output_tensor_names[0], a2], op_name_scope=node.name, name="13", ) num_14_node = ctx.MakeNode( "Mul", [num_13_node.output_tensor_names[0], t_node.output_tensor_names[0]], op_name_scope=node.name, name="14", ) num_15_node = ctx.MakeNode( "Add", [num_14_node.output_tensor_names[0], a1], op_name_scope=node.name, name="15", ) num_16_node = ctx.MakeNode( "Mul", [num_15_node.output_tensor_names[0], num_7_node.output_tensor_names[0]], op_name_scope=node.name, name="16", ) num_17_node = ctx.MakeNode( "Sub", [one, num_16_node.output_tensor_names[0]], op_name_scope=node.name, name="17", ) shapes = node.output_shapes dtypes = node.output_dtypes ctx.RemoveNode(node.name) ctx.MakeNode( "Mul", [num_17_node.output_tensor_names[0], sign_node.output_tensor_names[0]], outputs=[output_name], name=n, shapes=shapes, dtypes=dtypes, ) @classmethod def Version_9(cls, ctx, node, **kwargs): pass @flow_op("broadcast_floor_mod", onnx_op="FloorMod") class FloorMod: @classmethod def Version_7(cls, ctx, node, **kwargs): # T output = FloorMod(T x, T y) div = ctx.MakeNode(op_type="Div", inputs=node.input_tensor_names) dtype = ctx.get_dtype(node.input_tensor_names[0]) if dtype in [ onnx_pb.TensorProto.FLOAT, onnx_pb.TensorProto.FLOAT16, onnx_pb.TensorProto.DOUBLE, ]: div = ctx.MakeNode(op_type="Floor", inputs=div.output_tensor_names) mul = ctx.MakeNode( op_type="Mul", inputs=[div.output_tensor_names[0], node.input_tensor_names[1]], ) # res node will take over shape&dtype&output connection info of original "node" shapes = node.output_shapes dtypes = node.output_dtypes ctx.RemoveNode(node.name) ctx.MakeNode( op_type="Sub", inputs=[node.input_tensor_names[0], mul.output_tensor_names[0]], name=node.name, outputs=node.output_tensor_names, shapes=shapes, dtypes=dtypes, ) @flow_op("round", onnx_op="Round") class Round: @classmethod def Version_11(cls, ctx, node, **kwargs): pass def _AddCastToInputs(graph, node, supported_dtypes, target_dtype): is_support = True for inp in node.input_tensor_names: if graph.get_dtype(inp) not in supported_dtypes: is_support = False break if not is_support: for inp in node.input_tensor_names: inp_cast = graph.InsertNewNodeOnInput(node, "Cast", inp, to=target_dtype) graph.CopyShape(inp, inp_cast.output_tensor_names[0]) graph.set_dtype(inp_cast.output_tensor_names[0], target_dtype) def _AddCastToOutput(graph, node): # oneflow logical ops produce int8 tensor while onnx logical ops produce bool tensor output = node.output_tensor_names[0] cast_node = graph.InsertNewNodeOnOutput("Cast", output, oneflow._oneflow_internal.UniqueStr("cast"), to=graph.get_dtype(output)) graph.CopyShape(output, node.output_tensor_names[0]) graph.set_dtype(node.output_tensor_names[0], TensorProto.BOOL) # oneflow doesn't have logical_not and broadcast_logical_or, but # it is easy to implement onnx converter in advance @flow_op("logical_not", onnx_op="Not") class DirectOp: @classmethod def Version_1(cls, ctx, node, **kwargs): _AddCastToOutput(ctx, node) @flow_op("broadcast_logical_and", onnx_op="And", flow_ibns=["x", "y"]) @flow_op("broadcast_logical_or", onnx_op="Or", flow_ibns=["x", "y"]) class BroadcastOp(common.BroadcastOp): @classmethod def Version_1(cls, ctx, node, **kwargs): _AddCastToOutput(ctx, node) super().Version_1(ctx, node, **kwargs) @flow_op( ["broadcast_equal", "broadcast_not_equal"], ["Equal", "NotEqual"], flow_ibns=["x", "y"], ) class Equal: @classmethod def Version_7(cls, ctx, node, **kwargs): # T2 output = Equal(T1, x, T1 y), T1 \in {bool, int32, int64} _AddCastToOutput(ctx, node) need_not = node.op_type == "NotEqual" supported_dtypes = [TensorProto.BOOL, TensorProto.INT32, TensorProto.INT64] if any([ctx.get_dtype(inp) not in supported_dtypes for inp in node.input_tensor_names]): raise ValueError("Version 7 Equal op only supports bool, int32 and int64 inputs. Please set opset > 11 and try again.") if need_not: node.op_type = "Equal" output_name = node.output_tensor_names[0] not_node = ctx.InsertNewNodeOnOutput("Not", output_name, name=oneflow._oneflow_internal.UniqueStr(node.name)) ctx.CopyShape(output_name, not_node.output_tensor_names[0]) ctx.CopyDtype(output_name, not_node.output_tensor_names[0]) @classmethod def Version_11(cls, ctx, node, **kwargs): # starting with opset-11, equal supports all types _AddCastToOutput(ctx, node) need_not = node.op_type == "NotEqual" if need_not: node.op_type = "Equal" output_name = node.output_tensor_names[0] not_node = ctx.InsertNewNodeOnOutput("Not", output_name, name=oneflow._oneflow_internal.UniqueStr(node.name)) ctx.CopyShape(output_name, not_node.output_tensor_names[0]) ctx.CopyDtype(output_name, not_node.output_tensor_names[0]) @flow_op(["broadcast_greater", "broadcast_less"], ["Greater", "Less"], flow_ibns=["x", "y"]) class GreaterLess: @classmethod def Version_7(cls, ctx, node, **kwargs): _AddCastToOutput(ctx, node) # T2 output = Greater(T1 x, T1 y), T2=tensor(bool) # T2 output = Less(T1 x, T1 y), T2=tensor(bool) # Great/Less in opset7 only supports limited types, insert Cast if needed supported_dtypes = [TensorProto.FLOAT, TensorProto.FLOAT16, TensorProto.DOUBLE] target_dtype = TensorProto.FLOAT _AddCastToInputs(ctx, node, supported_dtypes, target_dtype) @flow_op("broadcast_greater_equal", onnx_op="Less", flow_ibns=["x", "y"]) @flow_op("broadcast_less_equal", onnx_op="Greater", flow_ibns=["x", "y"]) class GreaterLessEqual: @classmethod def Version_7(cls, ctx, node, **kwargs): _AddCastToOutput(ctx, node) GreaterLess.Version_7(ctx, node, **kwargs) output_name = node.output_tensor_names[0] new_node = ctx.InsertNewNodeOnOutput("Not", output_name, name=oneflow._oneflow_internal.UniqueStr(node.name)) ctx.CopyShape(output_name, new_node.output_tensor_names[0]) ctx.set_dtype(new_node.output_tensor_names[0], ctx.get_dtype(output_name)) @flow_op(["var"]) class Var: @classmethod def Version_13(cls, ctx, node, **kwargs): origin_dim = node.attrs.get("dim", None) unbiased = node.attrs.get("unbiased", None) keepdim = node.attrs.get("keepdim", None) num_elements = 1 dtypes = node.output_dtypes input_shape = ctx.get_shape(node.input_tensor_names[0]) keepdim_mean = 0 if origin_dim is None else keepdim if origin_dim is None: dim = [] for i in range(len(input_shape)): num_elements *= input_shape[i] dim.append(i) reduce_mean_node = ctx.MakeNode("ReduceMean", [node.input_tensor_names[0]], op_name_scope=node.name, name="reduce_mean", dtypes=dtypes, attr={"axes": dim, "keepdims": 0}) t_mean = reduce_mean_node.output_tensor_names[0] else: reduce_mean_node = ctx.MakeNode("ReduceMean", [node.input_tensor_names[0]], op_name_scope=node.name, name="reduce_mean", dtypes=dtypes, attr={"axes": origin_dim, "keepdims": 1}) t_mean = reduce_mean_node.output_tensor_names[0] for i in range(len(origin_dim)): num_elements *= input_shape[i] sub_node = ctx.MakeNode("Sub", [node.input_tensor_names[0], t_mean], op_name_scope=node.name, name="sub", dtypes=dtypes) sub_v = sub_node.output_tensor_names[0] mul_node = ctx.MakeNode("Mul", [sub_v, sub_v], op_name_scope=node.name, name="mul", dtypes=dtypes) sqr_sub = mul_node.output_tensor_names[0] if unbiased is None: unbiased = False ctx.RemoveNode(node.name) if unbiased: var_node = ctx.MakeNode("ReduceMean", [sqr_sub], op_name_scope=node.name, name="var", dtypes=dtypes, attr={"axes": origin_dim, "keepdims": keepdim_mean}) var = var_node.output_tensor_names[0] scalar_node = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("scalar"), np.array([num_elements]).astype(np.float32)) one = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("constant"), np.array([1]).astype(np.float32)) num_elements = scalar_node.output_tensor_names[0] mul = ctx.MakeNode("Mul", [var, num_elements]) sub = ctx.MakeNode("Sub", [num_elements, one.output_tensor_names[0]]) var = ctx.MakeNode("Div", [mul.output_tensor_names[0], sub.output_tensor_names[0]], outputs=[node.output_tensor_names[0]]) else: var_node = ctx.MakeNode( "ReduceMean", [sqr_sub], op_name_scope=node.name, name="var", dtypes=dtypes, attr={"axes": origin_dim, "keepdims": keepdim_mean}, outputs=[node.output_tensor_names[0]] ) @flow_op("fill_", onnx_op="Constant") class Fill: @classmethod def Version_1(cls, ctx, node, **kwargs): is_floating_value = node.attrs["is_floating_value"] output_name = node.output_tensor_names[0] out_shape = ctx.get_shape(output_name) if is_floating_value: values = np.full(shape=out_shape, fill_value=node.attrs["floating_value"], dtype=np.float32) else: values = np.full(shape=out_shape, fill_value=node.attrs["integral_value"], dtype=np.float32) ctx.RemoveNode(node.name) ctx.MakeConst(output_name, values) @classmethod def Version_9(cls, ctx, node, **kwargs): cls.Version_1(ctx, node, **kwargs) @classmethod def Version_11(cls, ctx, node, **kwargs): cls.Version_1(ctx, node, **kwargs) @classmethod def Version_13(cls, ctx, node, **kwargs): cls.Version_1(ctx, node, **kwargs) @flow_op("fused_bias_add_scale_mask_softmax_dropout") class FusedBiasAddScaleMaskSoftmaxDropout: @classmethod def Version_1(cls, ctx, node, **kwargs): dtypes = node.output_dtypes scale_value = node.attrs.get("scale_value") mask_fill_value = node.attrs.get("mask_fill_value") output_name1 = node.output_tensor_names[0] output_name2 = node.output_tensor_names[1] scale = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("scale"), np.array(scale_value, dtype=util.Onnx2NumpyDtype(dtypes[0]))) mask_fill = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("mask_fill"), np.array(mask_fill_value, dtype=util.Onnx2NumpyDtype(dtypes[0]))) one = ctx.MakeConst(oneflow._oneflow_internal.UniqueStr("one"), np.array(1, dtype=util.Onnx2NumpyDtype(dtypes[0]))) ctx.set_dtype(node.input_tensor_names[2], ctx.get_dtype(one.output_tensor_names[0])) add_node_1 = ctx.MakeNode("Add", [node.input_tensor_names[0], node.input_tensor_names[1]], op_name_scope=node.name, name="add_node_1", dtypes=[dtypes[0]]) mul_node_1 = ctx.MakeNode("Mul", [add_node_1.output_tensor_names[0], node.input_tensor_names[2]], op_name_scope=node.name, name="mul_node_1", dtypes=[dtypes[0]]) masked = ctx.MakeNode("Mul", [mul_node_1.output_tensor_names[0], scale.output_tensor_names[0]], op_name_scope=node.name, name="masked", dtypes=[dtypes[0]]) unmask = ctx.MakeNode("Sub", [one.output_tensor_names[0], node.input_tensor_names[2]], op_name_scope=node.name, name="unmask", dtypes=[dtypes[0]]) mul_node_2 = ctx.MakeNode("Mul", [mask_fill.output_tensor_names[0], unmask.output_tensor_names[0]], op_name_scope=node.name, name="mul_node_2", dtypes=[dtypes[0]]) mul_node_3 = ctx.MakeNode("Mul", [masked.output_tensor_names[0], node.input_tensor_names[2]], op_name_scope=node.name, name="mul_node_3", dtypes=[dtypes[0]]) sub_node_1 = ctx.MakeNode("Sub", [mul_node_2.output_tensor_names[0], mul_node_3.output_tensor_names[0]], op_name_scope=node.name, name="sub_node_1", dtypes=[dtypes[0]]) add_node_2 = ctx.MakeNode("Add", [sub_node_1.output_tensor_names[0], masked.output_tensor_names[0]], op_name_scope=node.name, name="add_node_2", dtypes=[dtypes[0]]) softmax_y = ctx.MakeNode("Softmax", [add_node_2.output_tensor_names[0]], attr={"axis": 2}, op_name_scope=node.name, name="softmax_node_1", dtypes=[dtypes[0]]) ctx.RemoveNode(node.name) ctx.MakeNode("Identity", [softmax_y.output_tensor_names[0]], outputs=[output_name1], op_name_scope=node.name, dtypes=[dtypes[0]]) ctx.MakeNode("Identity", [softmax_y.output_tensor_names[0]], outputs=[output_name2], op_name_scope=node.name, dtypes=[dtypes[0]])
UTF-8
Python
false
false
48,404
py
30
math.py
17
0.599289
0.582369
0
1,145
41.274236
190
PADAS/das-clients
4,776,003,639,402
e62b7e4e0d071b6b24963c3680a2644c64ca2f69
729926a37895feba9b754739e7e9e2f09113f8b4
/python/dasclient/dasclient.py
3e31f334912660d2d5924c143d7e9ca5831dd40b
[ "MIT" ]
permissive
https://github.com/PADAS/das-clients
159959d6c5c6cc776f27ff86d77a386e25d3138e
05a9ca1ff395bfaef4ab9af0cb75aab18b6150a2
refs/heads/main
2022-12-12T21:41:10.250817
2022-07-12T19:13:27
2022-07-12T19:13:27
84,587,693
4
0
MIT
false
2022-12-08T15:44:05
2017-03-10T18:08:56
2022-05-06T15:56:08
2022-12-08T15:44:03
183
5
0
3
Python
false
false
from datetime import datetime, timedelta import urllib.parse from urllib3.util.retry import Retry import pytz import logging import re import dateparser import concurrent.futures import math import requests from requests.adapters import HTTPAdapter import io import json from .version import __version__ version_string = __version__ def linkify(url, params): p = ['='.join((str(x), str(y))) for x, y in params.items()] p = '&'.join(p) return '?'.join((url, p)) def split_link(url): url, qs = url.split('?') params = dict([p.split('=') for p in qs.split('&')]) return (url, params) class DasClient(object): """ DasClient provides basic access to a DAS API. It requires the coordinates of a DAS API service as well as valid credentials for a user. The boiler-plate code handles authentication, so you don't have to think about Oauth2 or refresh tokens. As of May 12, 2017 it includes just a basic set of functions to access Subject data and to post observations. June 6, 2017: Added methods to add a photo or document to an Event. """ def __init__(self, **kwargs): """ Initialize a DasClient instance. :param username: DAS username :param password: DAS password :param service_root: The root of the DAS API (Ex. https://demo.pamdas.org/api/v1.0) :param token_url: The auth token url for DAS (Ex. https://demo.pamdas.org/oauth2/token) :param provider_key: provider-key for posting observation data (Ex. xyz_provider) :param client_id: Auth client ID (Ex. das_web_client) """ self.auth = None self.auth_expires = pytz.utc.localize(datetime.min) self._http_session = None self.max_retries = kwargs.get('max_http_retries', 5) self.service_root = kwargs.get('service_root') self.client_id = kwargs.get('client_id') self.provider_key = kwargs.get('provider_key') self.token_url = kwargs.get('token_url') self.username = kwargs.get('username') self.password = kwargs.get('password') self.realtime_url = kwargs.get('realtime_url') if kwargs.get('token'): self.token = kwargs.get('token') self.auth = dict(token_type='Bearer', access_token=kwargs.get('token')) self.auth_expires = datetime(2099, 1, 1, tzinfo=pytz.utc) self.user_agent = 'das-client/{}'.format(version_string) self.logger = logging.getLogger(self.__class__.__name__) self._http_session = requests.Session() retries = Retry(total = 5, backoff_factor=1.5, status_forcelist=[502]) self._http_session.mount("http", HTTPAdapter(max_retries=retries)) self._http_session.mount("https", HTTPAdapter(max_retries=retries)) def _auth_is_valid(self): return self.auth_expires > pytz.utc.localize(datetime.utcnow()) def auth_headers(self): if self.auth: if not self._auth_is_valid(): if not self.refresh_token(): if not self.login(): raise DasClientException('Login failed.') else: if not self.login(): raise DasClientException('Login failed.') return {'Authorization': '{} {}'.format(self.auth['token_type'], self.auth['access_token']), 'Accept-Type': 'application/json'} def refresh_token(self): payload = {'grant_type': 'refresh_token', 'refresh_token': self.auth['refresh_token'], 'client_id': self.client_id } return self._token_request(payload) def login(self): payload = {'grant_type': 'password', 'username': self.username, 'password': self.password, 'client_id': self.client_id } return self._token_request(payload) def _token_request(self, payload): response = requests.post(self.token_url, data=payload) if response.ok: self.auth = json.loads(response.text) expires_in = int(self.auth['expires_in']) - 5 * 60 self.auth_expires = pytz.utc.localize( datetime.utcnow()) + timedelta(seconds=expires_in) return True self.auth = None self.auth_expires = pytz.utc.localize(datetime.min) return False def _das_url(self, path): return '/'.join((self.service_root, path)) def _get(self, path, stream=False, **kwargs): headers = {'User-Agent': self.user_agent} headers.update(self.auth_headers()) if(not path.startswith("http")): path = self._das_url(path) response = None if(self._http_session): response = self._http_session.get(path, headers=headers, params=kwargs.get('params'), stream=stream) else: response = requests.get(path, headers=headers, params=kwargs.get('params'), stream=stream) if response.ok: if kwargs.get('return_response', False): return response data = json.loads(response.text) if 'metadata' in data: return data['metadata'] elif 'data' in data: return data['data'] else: return data if response.status_code == 404: # not found self.logger.error(f"404 when calling {path}") raise DasClientNotFound() if response.status_code == 403: # forbidden try: _ = json.loads(response.text) reason = _['status']['detail'] except: reason = 'unknown reason' raise DasClientPermissionDenied(reason) self.logger.debug("Fail: " + response.text) raise DasClientException( f"Failed to call DAS web service at {response.url}. {response.status_code} {response.text}") def _call(self, path, payload, method, params=None): headers = {'Content-Type': 'application/json', 'User-Agent': self.user_agent} headers.update(self.auth_headers()) def time_converter(t): if isinstance(t, datetime): return t.isoformat() body = json.dumps(payload, default=time_converter) fmap = None if(self._http_session): fmap = {'POST': self._http_session.post, 'PATCH': self._http_session.patch} else: fmap = {'POST': requests.post, 'PATCH': requests.patch} try: fn = fmap[method] except KeyError: self.logger.error('method must be one of...') else: response = fn(self._das_url(path), data=body, headers=headers, params=params) if response and response.ok: res_json = response.json() if('data' in res_json): return res_json['data'] else: return res_json if response.status_code == 404: # not found self.logger.error(f"Could not load {path}") raise DasClientNotFound() try: _ = json.loads(response.text) reason = _['status']['detail'] except: reason = 'unknown reason' if response.status_code == 403: # forbidden raise DasClientPermissionDenied(reason) if response.status_code == 504 or response.status_code == 502: # gateway timeout or bad gateway self.logger.error(f"ER service unavailable", extra=dict(provider_key=self.provider_key, service=self.service_root, path=path, status_code=response.status_code, reason=reason, text=response.text)) raise DasClientServiceUnavailable(f"ER service unavailable") self.logger.error(f"ER returned bad response", extra=dict(provider_key=self.provider_key, service=self.service_root, path=path, status_code=response.status_code, reason=reason, text=response.text)) message = f"provider_key: {self.provider_key}, service: {self.service_root}, path: {path},\n\t {response.status_code} from ER. Message: {reason} {response.text}" raise DasClientException( f"Failed to {fn} to DAS web service. {message}") def _post(self, path, payload, params={}): return self._call(path, payload, "POST", params) def _patch(self, path, payload, params={}): return self._call(path, payload, "PATCH", params) def add_event_to_incident(self, event_id, incident_id): params = { 'to_event_id': event_id, 'type': 'contains' } result = self._post('activity/event/' + incident_id + '/relationships', params) def remove_event_from_incident(self, event_id, incident_id, relationship_type='contains'): result = self._delete( f'activity/event/{incident_id}/relationship/{relationship_type}/{event_id}/') def _delete(self, path): headers = {'User-Agent': self.user_agent} headers.update(self.auth_headers()) resonse = None if(self._http_session): response = self._http_session.delete(self._das_url(path), headers=headers) else: response = requests.delete(self._das_url(path), headers=headers) if response.ok: return True if response.status_code == 404: # not found self.logger.error(f"404 when calling {path}") raise DasClientNotFound() if response.status_code == 403: # forbidden try: _ = json.loads(response.text) reason = _['status']['detail'] except: reason = 'unknown reason' raise DasClientPermissionDenied(reason) raise DasClientException( f'Failed to delete: {response.status_code} {response.text}') def delete_event(self, event_id): self._delete('activity/event/' + event_id + '/') def delete_source(self, source_id): self._delete('source/' + source_id + '/') def delete_subject(self, subject_id): self._delete('subject/' + subject_id + '/') def delete_message(self, message_id): self._delete('messages/' + message_id + '/') def delete_patrol(self, patrol_id): self._delete('activity/patrols/' + patrol_id + '/') def _post_form(self, path, body=None, files=None): headers = {'User-Agent': self.user_agent} headers.update(self.auth_headers()) body = body or {} response = requests.post(self._das_url( path), data=body, headers=headers, files=files) if response and response.ok: return json.loads(response.text)['data'] if response.status_code == 404: # not found raise DasClientNotFound() if response.status_code == 403: # forbidden try: _ = json.loads(response.text) reason = _['status']['detail'] except: reason = 'unknown reason' raise DasClientPermissionDenied(reason) self.logger.error('provider_key: %s, path: %s\n\tBad result from das service. Message: %s', self.provider_key, path, response.text) raise DasClientException('Failed to post to DAS web service.') def post_eventprovider(self, eventprovider): self.logger.debug('Posting eventprovider: %s', eventprovider) result = self._post('activity/eventproviders/', payload=eventprovider) self.logger.debug('Result of eventprovider post is: %s', result) return result def post_eventsource(self, eventprovider_id, eventsource): self.logger.debug('Posting eventsource: %s', eventsource) result = self._post(f'activity/eventprovider/{eventprovider_id}/eventsources', payload=eventsource) self.logger.debug('Result of eventsource post is: %s', result) return result def post_event_photo(self, event_id, image): raise ValueError('post_event_photo is no longer valid.') photos_path = 'activity/event/' + str(event_id) + '/photos/' with open(image, "rb") as image_file: files = {'image': image_file} return self._post_form(photos_path, files=files) def post_camera_trap_report(self, camera_trap_payload, file=None): camera_trap_report_path = f'sensors/camera-trap/' + self.provider_key + '/status/' if file: files = {'filecontent.file': file} return self._post_form(camera_trap_report_path, body=camera_trap_payload, files=files) else: file_path = camera_trap_payload.get('file') with open(file_path, "rb") as f: files = {'filecontent.file': f} return self._post_form(camera_trap_report_path, body=camera_trap_payload, files=files) def delete_event_file(self, event_id, file_id): self._delete(f"activity/event/{event_id}/file/{file_id}") def delete_event_note(self, event_id, note_id): path = f"activity/event/{event_id}/note/{note_id}" self._delete(path) def post_event_file(self, event_id, filepath=None, comment=''): documents_path = 'activity/event/' + str(event_id) + '/files/' with open(filepath, "rb") as f: files = {'filecontent.file': f} return self._post_form(documents_path, body={'comment': comment}, files=files) def post_event_note(self, event_id, notes): created = [] if(not isinstance(notes, list)): notes = [notes, ] for note in notes: notesRequest = { 'event': event_id, 'text': note } result = self._post('activity/event/' + event_id + '/notes', notesRequest) created.append(result) return created def get_me(self): """ Get details for the 'me', the current DAS user. :return: """ return self._get('user/me') def post_subject(self, subject): ''' Post a subject payload to create a new subject. :param subject: :return: ''' self.logger.debug(f"Posting subject {subject.get('name')}") return self._post('subjects', payload=subject) def post_source(self, source): ''' Post a source payload to create a new source. :param source: :return: ''' self.logger.debug('Posting source for manufacturer_id: %s', source.get('manufacturer_id')) return self._post('sources', payload=source) def _clean_observation(self, observation): if hasattr(observation['recorded_at'], 'isoformat'): observation['recorded_at'] = observation['recorded_at'].isoformat() return observation def _clean_event(self, event): return event def post_radio_observation(self, observation): # Clean-up data before posting observation['recorded_at'] = observation['recorded_at'].isoformat() self.logger.debug('Posting observation: %s', observation) result = self._post( 'sensors/dasradioagent/{}/status'.format(self.provider_key), payload=observation) self.logger.debug('Result of post is: %s', result) return result def post_radio_heartbeat(self, data): self.logger.debug('Posting heartbeat: %s', data) result = self._post( 'sensors/dasradioagent/{}/status'.format(self.provider_key), payload=data) self.logger.debug('Result of heartbeat post is: %s', result) def post_observation(self, observation): """ Post a new observation, or a list of observations. """ if isinstance(observation, (list, set)): payload = [self._clean_observation(o) for o in observation] else: payload = self._clean_observation(observation) self.logger.debug('Posting observation: %s', payload) return self._post('observations', payload=payload) def post_sensor_observation(self, observation, sensor_type='generic'): """ Post a new observation, or a list of observations. """ if isinstance(observation, (list, set)): payload = [self._clean_observation(o) for o in observation] else: payload = self._clean_observation(observation) self.logger.debug('Posting observation: %s', observation) result = self._post( 'sensors/{}/{}/status'.format(sensor_type, self.provider_key), payload=observation) self.logger.debug('Result of post is: %s', result) return result def post_patrol(self, data): payload = self._clean_event(data) self.logger.debug('Posting patrol: %s', payload) result = self._post('activity/patrols', payload=payload) self.logger.debug('Result of patrol post is: %s', result) return result def patch_event_type(self, event_type): self.logger.debug('Patching event type: %s', event_type) result = self._patch( f"activity/events/eventtypes/{event_type['id']}", payload=event_type) self.logger.debug('Result of event type patch is: %s', result) return result def post_event_type(self, event_type): self.logger.debug('Posting event type: %s', event_type) result = self._post('activity/events/eventtypes/', payload=event_type) self.logger.debug('Result of event type post is: %s', result) return result def post_report(self, data): payload = self._clean_event(data) self.logger.debug('Posting report: %s', payload) result = self._post('activity/events', payload=payload) self.logger.debug('Result of report post is: %s', result) return result def post_event_category(self, data): self.logger.debug('Posting event category: %s', data) result = self._post('activity/events/categories', payload=data) self.logger.debug('Result of report category post is: %s', result) return result def patch_event_category(self, data): self.logger.debug('Patching event category: %s', data) result = self._patch( f'activity/events/categories/{data["id"]}', payload=data) self.logger.debug('Result of report category patch is: %s', result) return result def post_event(self, event): """ Post a new Event. """ return self.post_report(event) def add_events_to_patrol_segment(self, events, patrol_segment): for event in events: payload = { 'id': event['id'], 'patrol_segments': [ patrol_segment['id'] ] } result = self._patch( f"activity/event/{event['id']}", payload=payload) def patch_event(self, event_id, payload): self.logger.debug('Patching event: %s', payload) result = self._patch('activity/event/' + event_id, payload=payload) self.logger.debug('Result of event patch is: %s', result) return result def get_file(self, url): return self._get(url, stream=True, return_response=True) def get_event_type(self, event_type_name): return self._get(f'activity/events/schema/eventtype/{event_type_name}') def get_event_categories(self, include_inactive=False): return self._get(f'activity/events/categories', params={"include_inactive": include_inactive}) def get_messages(self): results = self._get(path='messages') while True: if results and results.get('results'): for r in results['results']: yield r if results and results['next']: url, params = split_link(results['next']) p['page'] = params['page'] results = self._get(path='messages') else: break def get_event_types(self, include_inactive = False, include_schema = False): return self._get('activity/events/eventtypes', params = {"include_inactive": include_inactive, "include_schema": include_schema}) def get_event_schema(self, event_type): return self._get(f'activity/events/schema/eventtype/{event_type}') def _get_objects_count(self, params): params = params.copy() params["page"] = 1 params["page_size"] = 1 events = self._get(params['object'], params=params) if events and events.get('count'): return events['count'] return 0 def get_objects(self, **kwargs): params = dict((k, v) for k, v in kwargs.items() if k not in ('page')) if(not params.get('object')): raise ValueError("Must specify object URL") self.logger.debug(f"Getting {params['object']}: ", params) count = 0 results = self._get(params['object'], params=params) while True: if(not results): break if('results' in results): for result in results['results']: yield result count += 1 if(('max_results' in params) and (count >= params['max_results'])): return next = results.get('next') if (next and ('page' not in params)): url = next self.logger.debug('Getting more objects: ' + url) results = self._get(url) else: break elif(type(results) == list): for o in results: yield o break else: yield results break def get_objects_multithreaded(self, **kwargs): threads = kwargs.get("threads", 5) params = dict((k, v) for k, v in kwargs.items() if k not in ('page')) if(not params.get('object')): raise ValueError("Must specify object URL") if(not params.get('page_size')): params['page_size'] = 100 count = self._get_objects_count(params) self.logger.debug(f"Loading {count} {params['object']} from ER with page size {params['page_size']} and {threads} threads") with concurrent.futures.ThreadPoolExecutor(max_workers = threads) as executor: futures = [] for page in range(1,math.ceil(count/params['page_size'])+1): temp_params = params.copy() temp_params["page"] = page futures.append(executor.submit(self._get, params['object'], params=temp_params)) for future in concurrent.futures.as_completed(futures): max_retries = kwargs.get("retries", 0) tries = 0 while(True): tries += 1 try: result = future.result() for e in result['results']: yield e break except Exception as e: if(tries > max_retries): logging.error(f"Error occurred loading events: {e}") raise e else: logging.warning(f"Attempt {tries} of {max_retries}: Error occurred loading events: {e}.") def get_events(self, **kwargs): params = dict((k, v) for k, v in kwargs.items() if k in ('state', 'page_size', 'page', 'event_type', 'filter', 'include_notes', 'include_related_events', 'include_files', 'include_details', 'updated_since', 'include_updates', 'max_results', 'oldest_update_date', 'event_ids')) self.logger.debug('Getting events: ', params) events = self._get('activity/events', params=params) count = 0 while True: if events and events.get('results'): for result in events['results']: yield result count += 1 if(('max_results' in params) and (count >= params['max_results'])): return if events['next'] and ('page' not in params): url = events['next'] url = re.sub('.*activity/events?', 'activity/events', events['next']) self.logger.debug('Getting more events: ' + url) events = self._get(url) else: break def get_patrols(self, **kwargs): params = dict((k, v) for k, v in kwargs.items() if k in ('state', 'page_size', 'page', 'event_type', 'filter')) self.logger.debug('Getting patrols: ', params) patrols = self._get('activity/patrols', params=params) while True: if patrols and patrols.get('results'): for result in patrols['results']: yield result if patrols['next']: url = patrols['next'] url = re.sub('.*activity/patrols?', 'activity/patrols', patrols['next']) self.logger.debug('Getting more patrols: ' + url) patrols = self._get(url) else: break def get_events_export(self, filter=None): params = None if filter: params = { 'filter': filter} response = self._get('activity/events/export/', params=params, return_response=True) return response def pulse(self, message=None): """ Convenience method for getting status of the DAS api. :param message: :return: """ return self._get('status') def get_subject_sources(self, subject_id): return self._get(path=f'subject/{subject_id}/sources') def get_subjectsources(self, subject_id): return self._get(path=f'subject/{subject_id}/subjectsources') def get_source_provider(self, provider_key): results = self.get_objects(object="sourceproviders") for r in results: if(r.get('provider_key') == provider_key): return r return None def get_subject_tracks(self, subject_id='', start=None, end=None): """ Get the latest tracks for the Subject having the given subject_id. """ p = {} if start is not None and isinstance(start, datetime): p['since'] = start.isoformat() if end is not None and isinstance(end, datetime): p['until'] = end.isoformat() return self._get(path='subject/{0}/tracks'.format(subject_id), params=p) def get_subject_trackingdata(self, subject_id=None, subject_chronofile=None, include_inactive=True, start=None, end=None, out_format='json', filter_flag=0, current_status=False): p = {} if start is not None and isinstance(start, datetime): p['after_date'] = start.isoformat() if end is not None and isinstance(end, datetime): p['before_date'] = end.isoformat() if subject_id: p['subject_id'] = subject_id elif subject_chronofile: p['subject_chronofile'] = subject_chronofile else: raise ValueError('specify subject_id or subject_chronofile') p['include_inactive'] = include_inactive p['format'] = out_format # should be 'json' or 'csv' p['filter'] = 'null' if filter_flag is None else filter_flag p['current_status'] = current_status return self._get(path='trackingdata/export', params=p) def get_subject_trackingmetadata(self, include_inactive=True, out_format='json'): p = {} p['include_inactive'] = include_inactive p['format'] = out_format # should be 'json' or 'csv' return self._get(path='trackingmetadata/export', params=p) def get_subject_observations(self, subject_id, start=None, end=None, filter_flag=0, include_details=True, page_size=10000): return self.get_observations(subject_id=subject_id, start=start, end=end, filter_flag=filter_flag, include_details=include_details, page_size=page_size) def get_source_observations(self, source_id, start=None, end=None, filter_flag=0, include_details=True, page_size=10000): return self.get_observations(source_id=source_id, start=start, end=end, filter_flag=filter_flag, include_details=include_details, page_size=page_size) def get_observations(self, subject_id=None, source_id=None, start=None, end=None, filter_flag=0, include_details=True, page_size=10000): p = {} if start is not None and isinstance(start, datetime): p['since'] = start.isoformat() if end is not None and isinstance(end, datetime): p['until'] = end.isoformat() if subject_id: p['subject_id'] = subject_id elif source_id: p['source_id'] = source_id p['filter'] = 'null' if filter_flag is None else filter_flag p['include_details'] = include_details p['page_size'] = page_size # current limit results = self._get(path='observations', params=p) while True: if results and results.get('results'): for r in results['results']: yield r if results and results['next']: url, params = split_link(results['next']) p['page'] = params['page'] results = self._get(path='observations', params=p) else: break def get_subjects(self, subject_group_id=None, **kwargs): """ Get the list of subjects to whom the user has access. :return: """ params = dict((k, v) for k, v in kwargs.items() if k in ('subject_group', 'include_inactive')) return self._get('subjects', params=params) def get_subject(self, subject_id=''): """ get the subject given the subject id :param subject_id: the UUID for the subject :return: """ return self._get(path='subject/{0}'.format(subject_id)) def get_source_by_id(self, id): """ get the source by id :param id: source id :return: """ return self._get(path='source/{0}'.format(id)) def get_source_by_manufacturer_id(self, id): """ get the source by manufacturer id or collar id :param id: the manufacturer id :return: """ return self._get(path='source/{0}'.format(id)) def get_subjectgroups(self, include_inactive=False, include_hidden=True, isvisible=True, flat=True, group_name=None): """Get the list of visible subjectgroups including members. By default don't include inactive subjects to get all subject groups whether visible or not, call with include_hidden=True Args: include_inactive (bool, optional): set to True to include inactive subjects. Defaults to False. include_hidden (bool, optional): include subject groups that are not visible (isvisible flag is false). Defaults to True. isvisible (bool, optional): either include all visible groups, or only include not visible groups. Defaults to True. flat (bool, optional): unnest parent/child subjectgroups returning a flat list of subjectgroups group_name (string, optional): filter the subjectgroups to this name Returns: [type]: [description] """ p = dict() p['include_inactive'] = include_inactive p['include_hidden'] = include_hidden p['isvisible'] = isvisible p['flat'] = flat p['group_name'] = group_name return self._get('subjectgroups', params=p) def get_sources(self, page_size=100): """Return all sources""" params = dict(page_size=page_size) sources = 'sources' results = self._get(path=sources, params=params) while True: if results and results.get('results'): for r in results['results']: yield r if results and results['next']: _, qparam = split_link(results['next']) params['page'] = qparam['page'] results = self._get(path=sources, params=params) else: break def get_users(self): return self._get('users') class DasClientException(Exception): pass class DasClientPermissionDenied(DasClientException): pass class DasClientServiceUnavailable(DasClientException): pass class DasClientNotFound(DasClientException): pass
UTF-8
Python
false
false
34,143
py
18
dasclient.py
8
0.558387
0.555165
0
902
36.85255
169
MaxT2/EWPythonDevelopment
14,774,687,502,634
49def9b3e9840ab2ea8c904543c6cf2385d290ad
f05e792af806f1069238aae3ce966a3268708f41
/RandomStuff/SpaceBackgroundScreenshot/SpaceBackgroundCreator.py
84dc5d491e56d1d093bd144c91ab3e9748bb6c83
[]
no_license
https://github.com/MaxT2/EWPythonDevelopment
9de608e32f319132b85e0ea4a1548872d2c90b55
6154b85a0b35438bb51944eddc742684469e6b60
refs/heads/master
2020-06-18T12:10:56.381449
2019-07-11T18:39:04
2019-07-11T18:39:04
196,299,153
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# import pygame library so we can use it! import pygame import random from pathlib import Path from PythonCodingClub import pygameColors # class definitions class Star(pygame.sprite.Sprite): def __init__(self, screen_width, screen_height): pygame.sprite.Sprite.__init__(self) # setup random numbers self.x_speed = 0 self.y_speed = 0 #setup pygame image stuff self.random_size = random.randint(1, 5) self.image = pygame.Surface((self.random_size, self.random_size)) self.image.fill((255, 255, 255)) # setup create bounding box and set position self.rect = self.image.get_rect() self.rect.center = (random.randint(0, screen_width), random.randint(0, screen_height)) # def update(self): # self.rect.x += self.x_speed # self.rect.y += self.y_speed # # # check to see if sprite left screen and reverse direction # if self.rect.top > display_height: # self.kill() # game code that needs to run only once pygame.init() # setup display dimensions display_width = 1000 display_height = 1000 gameSurface = pygame.display.set_mode((display_width, display_height)) # pygame.display.set_caption('Window Caption!') # setup game clock FPS = 60 clock = pygame.time.Clock() # setup game resources # color definitions # create a sprite group to keep track of sprites all_sprites = pygame.sprite.Group() # create stars and put them into all_sprites group so we can update and draw them for x in range(200): all_sprites.add(Star(display_width, display_height)) # draw the display sprites once and show them # fill entire screen with color gameSurface.fill(pygameColors.BLACK) all_sprites.draw(gameSurface) pygame.display.flip() # save a screenshot of the background # check if file exists is not working properly so it always takes a screenshot image_screen_shot = Path("/spaceBackground.jpg") if image_screen_shot.exists(): print("screenshot already exists") else: pygame.image.save(gameSurface, "screenshot1.jpg") print("screenshot saved") # main game loop running = True # when running is True game loop will run while running == True: # get input events and respond to them # if event is .QUIT for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # UPDATE STUFF # if all_sprites.__sizeof__() < 50: # all_sprites.add(Star(display_width, display_height)) # only update FPS (60) times a second clock.tick(FPS) # run update on all sprites in all_sprites group # all_sprites.update() # DRAW STUFF # clear display every frame(redraw background) # gameSurface.fill(pygameColors.BLACK) # draw all sprites in all_sprites groups # all_sprites.draw(gameSurface) # update and redraw entire screen # pygame.display.flip() # update some of the screen # pygame.display.update()
UTF-8
Python
false
false
2,957
py
52
SpaceBackgroundCreator.py
49
0.682448
0.671288
0
103
27.708738
94
eshenkulovilias/month_3
10,110,353,014,800
247546cead6969bef3fe65b9ae4fa2d6bdabdd22
3575106d0386044a3e010c3d454d74bf2ec911f9
/twit_post.py
728aee6ade9be404c405cea9cd23046df533e212
[]
no_license
https://github.com/eshenkulovilias/month_3
92d4a2b7198e18a48ef5c6d8be2471cfb735666b
716e1b5b1677fc47951c21aa78abffbf983ec6a1
refs/heads/main
2023-05-08T11:52:31.614816
2021-06-02T03:26:39
2021-06-02T03:26:39
370,043,570
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class CharField: def __init__(self, char, max_length): self.char = char self.max_length = max_length def __str__(self): return self.char class User: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return self.name class Post: def __init__(self, title, body, author): self.title = CharField(title, 10) self.body = CharField(body, 140) self.author = author def __str__(self): return f'Author: {self.author}\nTitle: {self.title}\n{self.body}' user = User('John', 18) post = Post('Welcome!', 'Hi, my name is John.', user) print(post)
UTF-8
Python
false
false
677
py
5
twit_post.py
5
0.564254
0.553914
0
31
20.83871
73
joelcolucci/mailgunpi
16,595,753,656,094
1e69a10db5d8d50c33bb5ef62518a657c8110332
52fc554d8f11e2b3e2e3dda9a13815b2adc45b62
/tests/mailgunservice/test_api.py
471a57de418665730ecc87a30d8d5ad0f8164757
[]
no_license
https://github.com/joelcolucci/mailgunpi
759fc0b47b8b72062a3a11a867271fccfe4e2ed1
186109e1b5f0aa7575ae2b8ff6636e0c003c6786
refs/heads/master
2016-06-13T15:00:22.305192
2016-06-13T03:00:02
2016-06-13T03:00:02
56,538,257
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
"""Unit tests for mailgunservice api blueprint """ import json from unittest import TestCase from unittest import main from flask import Flask from smokinggun.mailgunservice import service_api # Create Flask application for blueprint only app = Flask(__name__) app.register_blueprint(service_api, url_prefix='') class MailgunServiceApiTestCase(TestCase): def setUp(self): app.config['TESTING'] = True self.app = app.test_client() def tearDown(self): pass def test_event_endpoint(self): """Test events endpoint returns json response""" response = self.app.get('/mailgunservice/api/v1/event') try: data = json.loads(response.data) except Exception: self.fail("Endpoint did not return JSON") self.assertIsInstance(data, dict) def test_unsubscribe_endpoint(self): """Test events unsubscribe returns json response""" response = self.app.get('/mailgunservice/api/v1/unsubscribe') try: data = json.loads(response.data) except Exception: self.fail("Endpoint did not return JSON") self.assertIsInstance(data, dict) def test_complaint_endpoint(self): """Test events complaint returns json response""" response = self.app.get('/mailgunservice/api/v1/complaint') try: data = json.loads(response.data) except Exception: self.fail("Endpoint did not return JSON") self.assertIsInstance(data, dict) def test_bounce_endpoint(self): """Test events bounce returns json response""" response = self.app.get('/mailgunservice/api/v1/bounce') try: data = json.loads(response.data) except Exception: self.fail("Endpoint did not return JSON") self.assertIsInstance(data, dict) if __name__ == '__main__': main()
UTF-8
Python
false
false
1,917
py
20
test_api.py
15
0.636411
0.634324
0
74
24.905405
69
andarabr/simvas
9,981,504,029,995
38507d86a308dd2fcec2f25c7e32375450b98f4e
aa694370905208d986a0e29a678f18aef328dfed
/mvasapi/apps.py
c74bb7d6f33348d8467c74b96c6ae71b00c12627
[]
no_license
https://github.com/andarabr/simvas
4d1369a5f2935554f42b330e1630ce7831706016
bb4a9bbc16c0e4c84e754194947756fb7d568b12
refs/heads/master
2023-08-26T22:43:55.396918
2021-11-11T07:54:47
2021-11-11T07:54:47
421,659,325
0
0
null
false
2021-11-11T07:54:48
2021-10-27T03:07:03
2021-11-10T09:29:24
2021-11-11T07:54:47
41
0
0
0
Python
false
false
from django.apps import AppConfig class MvasapiConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'mvasapi'
UTF-8
Python
false
false
146
py
21
apps.py
14
0.746575
0.746575
0
6
23.333333
56
mhw32/PersistentHomology
2,585,570,342,328
45c4fe229c4ade63c2971be48a2e4956c18cb776
3096e153fa8400f7c4686ba94d733d0e05c6a54f
/paper/image_tools/gen_fig9_v2.py
2183276ba0f1f46d7be6339905402babe56590f3
[]
no_license
https://github.com/mhw32/PersistentHomology
be9982fcf022cb63541187cfff6421e889dce6ca
db806a5e091eb9c14f03c0720d11eabe9dd089de
refs/heads/master
2021-05-01T12:36:15.017641
2017-10-31T06:24:20
2017-10-31T06:24:20
42,668,152
1
0
null
false
2017-04-22T17:05:36
2015-09-17T16:36:51
2017-01-16T18:58:49
2017-04-22T17:05:36
355,699
0
0
1
Jupyter Notebook
null
null
import sys, numpy as np sys.path.append('/Users/mikewu/Desktop/Research/persist-homology/') import sub_parse reload(sub_parse) import matplotlib.pyplot as plt import matplotlib import seaborn as sns import warnings warnings.filterwarnings('ignore') name = '/Users/mikewu/Desktop/Research/persist-homology/saved_states/large_sub_set_test/results-' norm = 'True' base = '0.1' paths = [name+str(i)+'-'+base+'baseNorm'+norm+'.txt' for i in range(1, 101)] singles = ['all-silh', 'euler', 'all-euler', 'silh-euler'] doubles = ['indiv_silh', 'indiv-euler', 'contour'] resArr = np.array([sub_parse.parse(f) for f in paths]) bighash = {} for characteristic in singles: bighash[characteristic] = sub_parse.prepare1d(resArr, characteristic) for characteristic in doubles: for dim in [0,1,2]: bighash[characteristic+'-dim-'+str(dim)] = sub_parse.prepare2d(resArr, characteristic, dim) def safelog10(B, noise=1e-5): B[B == 0] += noise return np.log10(B) import rpy2.robjects as robjects from rpy2.robjects.numpy2ri import numpy2ri import numpy as np def rds_to_np(Rfile): ''' Convert .RData to be able to load the array into Python. Rfile := (str) location of file to translate to Python. ''' raw = robjects.r['readRDS'](Rfile) return raw # bighash for CORR: if norm == 'False': corr_data = np.array(rds_to_np('/Users/mikewu/Desktop/Research/persist-homology/correlation/sub_output/voronoi_proba_norm(0).rds')) pi_data = np.load('/Users/mikewu/Desktop/Research/persist-homology/intensity/output/sub_proba/nonorm/ans-voronoi-nodim.npy') wkc_data = np.load('/Users/mikewu/Desktop/Research/persist-homology/intensity/output/sub_proba/nonorm/ans-voronoi-bydim.npy') else: corr_data = np.array(rds_to_np('/Users/mikewu/Desktop/Research/persist-homology/correlation/sub_output/voronoi_proba_norm(1).rds')) pi_data = np.load('/Users/mikewu/Desktop/Research/persist-homology/intensity/output/sub_proba/yesnorm/ans-voronoi-nodim.npy') wkc_data = np.load('/Users/mikewu/Desktop/Research/persist-homology/intensity/output/sub_proba/yesnorm/ans-voronoi-bydim.npy') bighash_corr = {'corr': np.array(corr_data.T)} # bighash for wik wkc_data = np.log(1 - np.exp(wkc_data)) pi_data = np.log(1 - np.exp(pi_data)) wkc_0 = wkc_data[:, 0, :] wkc_1 = wkc_data[:, 1, :] wkc_2 = wkc_data[:, 2, :] pi_all = pi_data bighash_wik = {'wik_0': np.array(wkc_0.T), 'wik_1': np.array(wkc_1.T), 'wik_2': np.array(wkc_2.T), 'pi': np.array(pi_data.T) } def get_align_dict(keys, step=0.01): alignment_hash = {} mid_pt = len(allkeys) / 2 base_val = mid_pt * -step for i, key in enumerate(allkeys): alignment_hash[key] = base_val base_val += step return alignment_hash def hard_line_plot(allkeys, allticks, allcolors, bighash, custom_ylim=None, save_path=None): xvalues = np.arange(0.1, 0.35, 0.05) align_values = get_align_dict(allkeys, 0.005) matplotlib.rc('xtick', labelsize=27) matplotlib.rc('ytick', labelsize=27) fig, ax = plt.subplots(figsize=(20,5)) plt.ylabel(r'$log_{10}(p)$', fontsize=40) plt.xlabel('PercFil', fontsize=40) for it in range(5): store_error_max = [] store_error_min = [] for k, c, t in zip(allkeys, allcolors, allticks): xvalue = xvalues[it] + align_values[k] yvalue = [np.percentile(np.log10(np.exp(i)), 50) for i in bighash[k]][it] lower_error = [np.percentile(np.log10(np.exp(i)), 25) for i in bighash[k]] upper_error = [np.percentile(np.log10(np.exp(i)), 75) for i in bighash[k]] store_error_min.append(lower_error[it]) store_error_max.append(upper_error[it]) store_error_min = np.array(store_error_min) store_error_max = np.array(store_error_max) for k, c, t in zip(allkeys, allcolors, allticks): xvalue = xvalues[it] + align_values[k] yvalue = [np.percentile(np.log10(np.exp(i)), 50) for i in bighash[k]][it] lower_error = [np.percentile(np.log10(np.exp(i)), 25) for i in bighash[k]] upper_error = [np.percentile(np.log10(np.exp(i)), 75) for i in bighash[k]] pos = [xvalue] ypt = [yvalue] err = [[yvalue - lower_error[it]], [upper_error[it] - yvalue]] plt.errorbar(pos, ypt, yerr=err, lw=6, alpha=0.4, color=c, capsize=20, capthick=6) for k, c, t in zip(allkeys, allcolors, allticks): xvalue = xvalues[it] + align_values[k] yvalue = [np.percentile(np.log10(np.exp(i)), 50) for i in bighash[k]][it] plt.scatter([xvalue], [yvalue], color=c, marker='o', alpha=1, s=300) # put it here so dots are the legend plt.legend(allticks, fontsize=30, loc='lower left') ax.xaxis.grid(False) plt.tick_params(axis='both', which='major', labelsize=35) plt.tight_layout() plt.xlim(0.02, 0.33) ax.set_xticklabels([0.00, '', '10%', '15%', '20%', '25%', '30%']) if not custom_ylim is None: plt.ylim(custom_ylim[0], custom_ylim[1]) if save_path: plt.savefig(save_path) else: plt.show() def merge_dicts(*dict_args): ''' Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. ''' result = {} for dictionary in dict_args: result.update(dictionary) return result # allkeys = ['euler', 'all-euler', 'indiv-euler-dim-0', 'indiv-euler-dim-1', 'indiv-euler-dim-2'] # allticks = ['EC', 'EC (0:2)', 'EC (0)', 'EC (1)', 'EC (2)'] # allcolors = ['#44B3C2', '#F1A94E', '#E45641', '#5D4C46', '#7B8D8E'] # hard_line_plot(allkeys, allticks, allcolors, bighash, custom_ylim=[-7, 1], save_path='figure_8_euler_group_normed.pdf') # allkeys = ['silh-euler', 'all-silh', 'indiv_silh-dim-0', 'indiv_silh-dim-1', 'indiv_silh-dim-2'] # allticks = ['SIL (EC)', 'SIL (0:2)', 'SIL (0)', 'SIL (1)', 'SIL (2)'] # allcolors = ['#44B3C2', '#F1A94E', '#E45641', '#5D4C46', '#7B8D8E'] # hard_line_plot(allkeys, allticks, allcolors, bighash, custom_ylim=[-3.5, 0.5], save_path='figure_8_silhouette_group_normed.pdf') # allkeys = ['contour-dim-0', 'contour-dim-1', 'contour-dim-2'] # allticks = ['IK (0)', 'IK (1)', 'IK (2)'] # allcolors = ['#44B3C2', '#F1A94E', '#E45641', '#5D4C46', '#7B8D8E'] # hard_line_plot(allkeys, allticks, allcolors, bighash, custom_ylim=[-1.8, 0], save_path='figure_8_contour_group_normed.pdf') # allkeys = ['corr'] # allticks = ['CORR'] # allcolors = ['#44B3C2'] # hard_line_plot(allkeys, allticks, allcolors, bighash_corr, custom_ylim=[-5, 1], save_path='figure_8_correlation_group_normed.pdf') # allkeys = ['wik_0', 'wik_1', 'wik_2', 'pi'] # allticks = ['WIK (0)', 'WIK (1)', 'WIK (2)', 'PI'] # allcolors = ['#44B3C2', '#F1A94E', '#E45641', '#5D4C46'] # hard_line_plot(allkeys, allticks, allcolors, bighash_wik, custom_ylim=[-1.2, 0], save_path='figure_8_weighted_contour_group_normed.pdf') bighash_best = merge_dicts(bighash, bighash_wik) allkeys = ['euler', 'silh-euler', 'contour-dim-2', 'wik_2'] allticks = ['EC', 'SIL (EC)', 'IK (2)', 'WIK (2)'] allcolors = ['#44B3C2', '#F1A94E', '#E45641', '#5D4C46'] hard_line_plot(allkeys, allticks, allcolors, bighash_best, save_path='figure_8_best_group_normed.pdf')
UTF-8
Python
false
false
7,749
py
70
gen_fig9_v2.py
61
0.597755
0.562137
0
198
38.131313
138
mongesan/Atcoder-m0_ngesan-py
18,236,431,170,095
a3b01ee380964443acd439460f9528f168f60863
d27af9d58b91b8cd998ac0eb87d980d304ff0670
/Beginner-Contest/ABC178/ABC178_F.py
63f77f925218a53ab97c450c0ccb5e4a53ff520f
[]
no_license
https://github.com/mongesan/Atcoder-m0_ngesan-py
29dd79daab149003ffc8b6b6bad5fa2e7daa9646
6654af034d4ff4cece1be04c2c8b756976d99a4b
refs/heads/master
2023-08-20T19:50:04.547025
2021-10-27T12:24:51
2021-10-27T12:24:51
258,486,105
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
cnt=0 for i in range(10): for j in range(10): if 0<i<9 and 0<j<9: continue else: print(i,j) cnt+=1 print(cnt)
UTF-8
Python
false
false
165
py
193
ABC178_F.py
191
0.436364
0.375758
0
9
17.444444
27
nadav7679/Hopfield-Model
12,386,685,716,093
6099dd1004f63e91ffaa7fd7d2b0ff502d11f37c
0aca4f6434bf86958205098f4bc669790ef8c93b
/network.py
c7b16613fdcce7620adefc1f7808754fa81075f0
[]
no_license
https://github.com/nadav7679/Hopfield-Model
6650869509cc2cf429c8cd9b56a864eeb4b275c4
77cfcd5a2bad3ca4979b008e81d4ddc40a0b47e3
refs/heads/master
2022-06-26T11:41:07.779961
2020-05-10T20:42:59
2020-05-10T20:42:59
262,868,494
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Hopfield model - Network class ## By Nadav Porat # ------------------------------------ import numpy as np import matplotlib.pyplot as plt import idx2numpy from scipy.special import erfc from PIL import Image import matplotlib.animation as animation from IPython.display import HTML get_ipython().run_line_magic('matplotlib', 'inline') # -------------- Helpful functions ------------------# def heaviside(value): if value > 0: return 1 else: return -1 def arrayToCell(arr): # A small helpfull function that makes Cell arrays from int arrays res = [] for i in arr: res.append(heaviside(i-0.2)) return res def matrixToArray(mat): arr = [] for i in range(np.shape(mat)[0]): for j in range(np.shape(mat)[1]): arr.append(mat[i][j]) return arr def arrayToMatrix(arr, n, m): # n is the numer of rows, m is the number of columes mat = np.zeros((n,m)) count = 0 for i in range(n): for j in range(m): mat[i][j] = arr[count] count += 1 return mat def overlap(arr1,arr2): if not len(arr1) == len(arr2): print ("Error - The configuration you have entered needs to be a Cell array with length = N") return summ = 0 for i in range(len(arr1)): summ += arr1[i] * arr2[i] return summ/len(arr1) def noiseItUp(arr, p = 0.3): N = len(arr) amount = int(p*N) res = np.copy(arr) for i in range(amount): res[np.random.randint(N)] *= -1 return res def jpgToMatrix(path): im = Image.open(path) im_np = np.asarray(im) try: im_np = im_np[:, :, 0] except IndexError: pass im_np = np.where(im_np<128, -1, 1) return im_np # -------------- The Network Class ------------------# class Network: def __init__(self,N,error=0.01): # Creats a Neuronal network with N neurons and maximum error. # N += 1 # IMPORTENT: I add one artificial Cell to the Network, netTemp = [] # its job is to prevent the system from going in the "Inverted" direction weights = np.zeros((N,N)) for i in range(N): netTemp.append(1) self.length = N self.net = netTemp self.maxError = error self.weights = weights self.numOfMem = 0 self.pError = 0 self.maxMem = 0 prob = 0 while prob < self.maxError: self.maxMem += 1 prob = 0.5*erfc(np.sqrt(N/(2*self.maxMem))) # Calculating the maximum amount of memories that are allowed #to enter the Network def insertMemory(self,mem): # Inserting a memory to the system, mem needs to be an N lengthed array self.numOfMem += 1 N = self.length if len(mem) != len(self.net): # Dealing with wrong enteries print ("Error - The memory you have entered needs to be a Cell array with length = N") return # if self.numOfMem != 1: # self.weights *= (self.numOfMem-1) # This line's intent is to remove the previous normalization. #You can imagine how annoyed iv'e beeb when I realized I missed this petty detial at first. for i in range(len(mem)): for j in range(len(mem)): if i == j: self.weights[i][j] = 0 else: self.weights[i][j] += (mem[i] * mem[j])/N # Adding in the Generalized-Hebb-rule weights # self.weights *= 1/self.numOfMem # Re-normalization self.pError = 0.5*erfc(np.sqrt(self.length/(2*self.numOfMem))) # Recalculating the current error of the Network with the new memory def update(self): # Updating a single random Cell in the network omega = self.weights N = self.length net = self.net num = np.random.randint(0,N) summ = 0 for i in range(N): summ += omega[num][i]*net[i] # Weighted sum self.net[num] = heaviside(summ) # Updating the num Cell def quickUpdate(self): # Updating the system N times (N number of Cells) for i in range(self.length): self.update() def printNet(self): for i in range(self.length): if i == 0: print("[%d" %self.net[i], end="") elif i == self.length-1: print(", %d]" %self.net[i]) # Just trying to make it pretty :) else: print(", %d" %self.net[i],end="") def setNet(self,config): # Setting some configuration to the system if not len(config) == self.length: print ("Error - The configuration you have entered needs to be a Cell array with length = N") return for i in range(self.length): self.net[i] = heaviside(config[i]) def clear(self): N = self.length netTemp = [] weights = np.zeros((N,N)) for i in range(N): netTemp.append(1) self.net = netTemp self.weights = weights self.numOfMem = 0 self.pError = 0 def energy(self): summ = 0 for i in range(self.length): for j in range(self.length): if i == j: continue summ += self.weights[i][j]*self.net[i]*self.net[j] return (-1/2)*summ def crosstalk(self,mem, num = -100): # The memory inserted (mem) must be a memory that is already embedded in the Network (otherwise the result has no meaning) # The crosstalk is calculated for a single cell denoted with num. If a cell is not given, one is chosen randomly. N = self.length if num == -100 : num = np.random.randint(0,N) weights = self.weights summ = 0 if not len(mem) == self.length: print ("Error - The configuration you have entered needs to be a Cell array with length = N") for i in range(N): for j in range(N): weights[i][j] -= mem[i] summ += weights[num][i]*mem[i] return summ*mem[num]*(-1) # -------------- Network assisting functions ------------------# def loadMatToNet(Net,mat): mem = matrixToArray(mat) mem1 = arrayToCell(mem) Net.insertMemory(mem1) def makeVid(net,updates = -1,test = None, name = None, title = None): if updates == -1: updates = 5*net.length ims = [] length = int(np.sqrt(net.length)) step = 5*(1+int(length/100)) # The step size is taken from trial and error fig = plt.figure(figsize=(6,6)) for i in range(updates): if i%step == 0: if test != None: net_copy = np.copy(net.net) for j in range(net.length): if net_copy[j] != test[j]: net_copy[j] = -0.2 if title != None: plt.title(title) mat = arrayToMatrix(net_copy,length,length) im = plt.imshow(mat, animated=True,cmap="gray") plt.axis("off") else: if title != None: plt.title(title) mat = arrayToMatrix(net.net,length,length) im = plt.imshow(mat, animated=True,cmap="gray") plt.axis("off") ims.append([im]) net.update() ani = animation.ArtistAnimation(fig, ims, interval=10, blit=True,repeat_delay=500) HTML(ani.to_html5_video()) if name != None: ani.save(name + ".mp4") return
UTF-8
Python
false
false
8,258
py
2
network.py
2
0.49782
0.486922
0
293
27.174061
141
liman21/qiyexinyong
7,567,732,390,180
b176ece3f890b701874475bfacff3a832fe0791b
5c6df020950d6f684903d3c6cd22f74c7bacbf34
/企查查/xin/zhanghao.py
8449b8016c8cf75e386e33bdb6791bf31a85d497
[]
no_license
https://github.com/liman21/qiyexinyong
5a569b1a03ec5492897b81cc856ab81e0d0c7e4d
9f05332e934c33b2ce446f78a699e29abda93485
refs/heads/master
2022-12-05T11:35:33.193184
2020-08-31T03:26:27
2020-08-31T03:26:27
291,604,379
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import requests,re url='https://www.yinsiduanxin.com/' con=requests.get(url).content.decode('utf-8').replace('\n','').replace('\t','').replace('\r','') conts=re.findall(' <a href="/(\w+)-phone-number/verification-code-(\d+)\.html" class="clickA"',con) for cont in conts: tell=cont[1] link='https://www.yinsiduanxin.com/'+cont[0]+f'-phone-number/verification-code-{tell}.html' con1 = requests.get(link).content.decode('utf-8').replace('\n', '').replace('\t', '').replace('\r', '') print('vv')
UTF-8
Python
false
false
508
py
23
zhanghao.py
20
0.637795
0.627953
0
10
49.9
107
gabbpuy/django-discordbot
3,856,880,636,815
fbe1308b848910334c5fe10724e5ed508fb66f71
24c9e2bdb02debeb5f95ac439760f36f3c7171f1
/discordbot/botevents/__init__.py
50bac56d1297158acafb5275ff808f78d1efea0b
[ "MIT" ]
permissive
https://github.com/gabbpuy/django-discordbot
a63f3ce0b042c56475863158a3d6a2595627f127
7da39206b9b01f615447ca824851e79fafbe9305
refs/heads/master
2023-05-24T10:19:32.436866
2021-06-10T19:05:34
2021-06-10T19:05:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from discordbot.botevents.on_command_error import setup as setup_on_command_error from discordbot.botevents.on_command import setup as setup_on_command from discordbot.botevents.on_message import setup as setup_on_message from discordbot.botevents.general import setup as setup_general def setup(bot): setup_on_command_error(bot) setup_on_command(bot) setup_on_message(bot) setup_general(bot)
UTF-8
Python
false
false
409
py
60
__init__.py
55
0.792176
0.792176
0
10
40
81
manch93/vfs-slots-api-monitor
10,849,087,412,761
b85c047a7fee80b48de14eb40b1f024c3fb8f963
e0089c60a870e1837c321ef9a1293ff75359a306
/PingVFS.py
97d55a252966331c7d061363ad124b7cad438325
[ "MIT" ]
permissive
https://github.com/manch93/vfs-slots-api-monitor
bf6fdbdf1bc0843199837ee69f90b3636701d747
864342fd1e144971df2a31e45b120fb22536f2bd
refs/heads/main
2023-06-14T21:30:16.700534
2021-07-15T02:19:11
2021-07-15T02:19:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import os import sys import time import json import requests import subprocess from playsound import playsound from urllib.parse import urlencode, quote_plus from datetime import datetime, timedelta class PingVFS: # default constructor def __init__(self, params): self.url = params["url"] self.urlparams = params["urlparams"] self.paths = params["paths"] self.auth = "" self.start_time = datetime.now() self.sound = params["sound"] def get_auth_token(self): if not os.path.isfile(self.paths["auth"]): return False path = os.path.realpath(self.paths["auth"]) read = open(path, "r") auth = read.read().replace("\n", " ") read.close() if auth == self.auth: return self.auth self.auth = auth # os.remove(path) return self.auth def store_output(self, output): # Saving the output in result.txt. with open(self.paths["output"], "a") as file_object: # Append 'hello' at the end of file file_object.write(output) def get_foramtted_date(self, date): return datetime.strptime(str(date), "%Y-%m-%d").strftime("%d/%m/%Y") def hit_vfs(self): headers = { "Content-length" : "0", "Content-type" : "application/json", } headers["Authorization"] = self.auth from_date = datetime.now().date() + timedelta(days = 1) to_date = from_date + timedelta(days = 90) self.urlparams["fromDate"] = str(self.get_foramtted_date(from_date)) self.urlparams["toDate"] = str(self.get_foramtted_date(to_date)) url = self.url \ + "?" \ + urlencode(self.urlparams, quote_via=quote_plus) try: resp = requests.get(url, headers=headers) except: return "ERROR Connection Refused" if os.path.isfile(self.paths["auth"]): self.get_auth_token() try: resp = resp.json() except: return "ERROR " + str(resp.status_code) return json.dumps(resp) def init(self): auth = self.get_auth_token() count = 0 print(""" ██  ██ ███████ ███████  ███████ ██  ██████  ████████ ███████  ██  ██ ██      ██       ██      ██  ██    ██    ██    ██       ██  ██ █████  ███████  ███████ ██  ██  ██  ██  ███████   ██  ██  ██          ██       ██ ██  ██  ██  ██       ██   ████   ██  ███████  ███████ ███████  ██████   ██  ███████ ██ ██ ██""") print("\n") print("Started at:", end =" ") print(datetime.now()) print("Trying to access VFS appointment API for slots...") print("\n") while True: time.sleep(5) request = self.hit_vfs() count += 1 output = "\nOutput: " \ + str(request) \ + "\nTime: " \ + str(datetime.now()) \ + "\nCount: " \ + str(count) \ + "\n===" self.store_output(output) # Printing the output in terminal. # print(output) print(".", end="", flush=True), if request == "[[]]": continue try: request = json.loads(request) except: continue try: if request[0]["counters"] != None: break except: continue subprocess.call([ "/usr/bin/notify-send", "VFS Slots!!!", "Something Positive May Have Happend." ]) print("\n") print(str(count) + " times HTTP 200 response received.") print("Ended at:", end =" ") print(datetime.now()) time_diff = datetime.now() - self.start_time time_diff = time_diff.total_seconds() / 60.0 print("Script ran for " + str(time_diff) + " minutes") # Will play the alert sound. playsound(self.sound) def main(params): if not os.path.isfile(params): return False path = os.path.realpath(params) read = open(path, "r") params = json.loads(read.read()) read.close() ping = PingVFS(params) ping.init() if __name__ == "__main__": main("./ping_creds.json")
UTF-8
Python
false
false
5,062
py
9
PingVFS.py
4
0.463415
0.46031
0
158
27.544304
83
vanshdevgan/Crypton
1,589,137,913,906
c2f4cf155aba2b72dc6902c883daec4683d19376
9c923224c9422f4da3336bb6bdadb9d550a30eb0
/RSA-encryption/Attack-Coppersmith/exploit.py
41062c7e23746cd15d55bb7b3f5e2422642b7c3d
[ "MIT" ]
permissive
https://github.com/vanshdevgan/Crypton
d8f79f6d0a456fb13253913ffb27ebc6f47a6454
92033a94bc6e7a543117dcef51407121ac7acfa2
refs/heads/master
2021-07-02T08:40:40.068449
2020-10-02T15:57:58
2020-10-02T15:57:58
181,874,564
0
2
MIT
true
2020-10-16T16:10:05
2019-04-17T11:08:37
2020-10-02T15:58:02
2020-10-02T15:57:59
1,138
0
2
1
Python
false
false
from sage.all import * # f is the monic polynomial f(x) = (m + x)**e - c whose roots we have to find def stereotyped(f, N): P.<x> = PolynomialRing(Zmod(N)) beta = 1 dd = f.degree() # Degree of the polynomial epsilon = beta/7 XX = ceil(N**((beta**2/dd) - epsilon)) rt = f.small_roots(XX, beta, epsilon) return rt def N-factorize(f, N): P.<x> = PolynomialRing(Zmod(N)) beta = 0.5 dd = f.degree() # Degree of the polynomial epsilon = beta/7 XX = ceil(N**((beta**2/dd) - epsilon)) rt = f.small_roots(XX, beta, epsilon) return rt
UTF-8
Python
false
false
588
py
204
exploit.py
69
0.585034
0.573129
0
20
28.4
77
ytgw/01_MicroMouse2016
7,567,732,402,304
db987e08beaf2aff796f56c2b59b79bc9e700208
20ab163d5c8052322e8ea235d2c32fd99ab83c03
/middleware.py
a0b13829539f5f440f0e29ca9a5703efbd3f7da4
[]
no_license
https://github.com/ytgw/01_MicroMouse2016
3eea19a1c3567ddc33d0d57b71124ae4e4aced9c
b4bc0c1d0f6e940be88b3b8b7bf6b6cd3d0cfea8
refs/heads/master
2017-04-26T19:41:35.663047
2016-08-30T13:25:13
2016-08-30T13:25:13
66,799,173
0
0
null
true
2016-08-29T00:51:29
2016-08-29T00:51:29
2016-08-04T16:18:10
2016-08-28T16:35:15
876
0
0
0
null
null
null
# coding: UTF-8 #-----------------------------------------------------------------------------# # Declation # #-----------------------------------------------------------------------------# # 各デバイスドライバのパス sensor_driver = "/dev/rtlightsensor0" switch_driver = [ "/dev/rtswitch0", "/dev/rtswitch1"] buzzer_driver = "/dev/rtbuzzer0" motor_driver = [ "/dev/rtmotor_raw_l0", "/dev/rtmotor_raw_r0"] led_driver = [ "/dev/rtled0", "/dev/rtled1", "/dev/rtled2", "/dev/rtled3"] # デバイスドライバから取得した値を格納する配列 sensor_data = [0, 0, 0, 0] # [距離センサー0の取得値, 1の値, 2の値, 3の値] switch_state = [0, 0, 0] # [タクトスイッチ0の取得値, 1の値, 2の値] #-----------------------------------------------------------------------------# # Input system (入力系) # #-----------------------------------------------------------------------------# def sensorinfo(): # 距離センサの値を取得する # デバイスドライバが見つかった場合 => tryの処理 # デバイスドライバが見つからなかった場合 => exceptの処理 try: filename = sensor_driver with open(filename,"r") as f: # f.readlin() の返り値は 8要素の配列データ(すべての要素は文字列) # 要素0 = 距離センサ0の取得値(文字列) # 要素1 = スペース(文字列) # 要素2 = 距離センサ1の取得値(文字列) # 要素3 = スペース(文字列) # 要素4 = 距離センサ2の取得値(文字列) # 要素5 = スペース(文字列) # 要素6 = 距離センサ3の取得値(文字列) # 要素7 = \n(改行コード) temp = f.readline() # デバイスドライバから取得できる値は文字列なので数値に変換する # 要素1,要素3, 要素5のスペースを削除 # 要素7の改行コードを削除 info = [int(temp[0]), int(temp[2]), int(temp[4]), int(temp[6])] except: # デバイスドライバが見つからない場合は全ての要素に数値の255を代入する info = [ 255, 255, 255, 255 ] sensor_info = info return sensor_info def switchstate(): # タクトスイッチの値を取得する # デバイスドライバが見つかった場合 => tryの処理 # デバイスドライバが見つからなかった場合 => exceptの処理 try: for i, filename in enumerate(switch_driver): with open(filename,"r") as f: # f.readlin() の返り値は 2要素の配列データ(すべての要素は文字列) # 要素0 = "0":押されてない or "1":押されている # 要素1 = \n(改行コード) temp = f.readline() # デバイスドライバから取得できる値は文字列なので数値に変換する # 要素1は改行コードなので削除 state[i] = int(temp[0]) except: # デバイスドライバが見つからない場合は全ての要素に数値の-1を代入する state = [ -1, -1, -1 ] switch_state = state return switch_state #-----------------------------------------------------------------------------# # Output system (出力系) # #-----------------------------------------------------------------------------# def buzzer(frequency): # ブザーを鳴らす # 引数は鳴らす音の周波数(Hz) # デバイスドライバが見つかった場合 => tryの処理 # デバイスドライバが見つからなかった場合 => exceptの処理 try: filename = buzzer_driver with open(filename,"w") as f: f.write(frequency) ret = True except: ret = False return ret def motor(speed): # モーターを駆動する # 引数は配列データ( speed = [ 左モータの回転数(Hz), 右モータの回転数(Hz) ] ) # デバイスドライバが見つかった場合 => tryの処理 # デバイスドライバが見つからなかった場合 => exceptの処理 try: for i, filename in enumerate(motor_driver): with open(filename,"w") as f_r_m: f.write(str(speed[i])) ret = True except: ret = False return ret def led(led_state): # LEDを駆動する # 引数は配列データ( led_state = [ led_0, led_1, led_2,led_3 ] ) # "led_X = 0" => Off , "led_X = 1" => ON # デバイスドライバが見つかった場合 => tryの処理 # デバイスドライバが見つからなかった場合 => exceptの処理 try: for i,filename in enumerate(led_driver): with open(filename,'w') as f: f.write(led_state[i]) ret = True except: ret = False return ret
UTF-8
Python
false
false
5,152
py
4
middleware.py
3
0.455315
0.434691
0
110
33.390909
79
jl223vy/Catching-a-Python
19,628,000,563,000
b804a6f8f0ea07a96eabbe6fc2fbd9bc1a4293e4
8689bf35529fd245df659abbbeaaa158d91cf749
/Test/用户登录(三次机会).py
de98a903bb9a96e1308bb385078c9560ddc45d6c
[]
no_license
https://github.com/jl223vy/Catching-a-Python
56a5ebd5994b221233b6504dd0de975fa7b4738e
1a8495bfc35f4a98d061783c65d84bfe415c3f13
refs/heads/master
2021-05-08T19:05:39.701496
2018-07-09T13:58:44
2018-07-09T13:58:44
119,550,132
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def main(): name = "Kate" psw = "666666" flag = 1 for i in range(3): tName = input() tPsw = input() if tName == name and tPsw == psw: print("登录成功!") break else: flag = 0 if flag == 0: print("3次用户名或者密码均有误!退出程序。") main()
UTF-8
Python
false
false
361
py
41
用户登录(三次机会).py
40
0.429022
0.394322
0
17
17.647059
41
abbasjam/abbas_repo
2,319,282,364,171
5dd40a792a30e6f0134a1eb3beb7501b77d0d1c9
8ff01e8bbb04a6411a16766f29ff6bc94878be0c
/python/dev-ops/python/pythan-class/set_example2.py
3d3fac7648bca127372c2422830502278c8a1e23
[]
no_license
https://github.com/abbasjam/abbas_repo
5642db639e12b5ec99f88834b472e44567b5e3aa
6a55288ba7c7e44f55f034b0e4978c51da6d2116
refs/heads/master
2020-08-17T23:12:47.168145
2020-03-23T09:15:41
2020-03-23T09:15:41
215,722,331
4
4
null
null
null
null
null
null
null
null
null
null
null
null
null
print ("Set Manipulations") print ("-----------------") x={1,2,3,4,5,6} print ("Given x is :",x) x.discard(5) print ("after discard(5):",x) x.discard(100) print ("After discard(100):",x)
UTF-8
Python
false
false
187
py
229
set_example2.py
153
0.572193
0.497326
0
8
22.375
31
Kuroko0o/eje_python
13,683,765,806,392
617cc3362893cf70d5fb52e38a59a92b155bef2b
d2078cf5931ceb38307ee74da918ada83d28b867
/promedios.py
e37ccb5f98e0088b23ff631a1eb94c3d59725727
[ "Apache-2.0" ]
permissive
https://github.com/Kuroko0o/eje_python
98255d08ba262b343ea75eaf375bf827812cd1fe
12580bdcb2b70b89b20e2566bf17870ba4532ef2
refs/heads/master
2022-11-09T13:34:46.832207
2020-06-21T03:58:29
2020-06-21T03:58:29
273,349,945
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
print(" ****** Bienvenido al Registro de Promedios por Materias Y Alumnos ****** ") print(" ") print ("*******************************************************") print(" ") k = input("Ingresar la cantidad deseada de nombres de alumnos y promedios que desea conseguir: \n") try: cant = int(k) except : print("La Cantidad ingresada no es valida! Intentelo nuevamente reiniciando el registro!") for cuenta in range(cant): a = input("Ingresar nombre de alumno completo: \n") b = input("Ingresar la materia (Lengua/Historia/Matematica/Geografia/Quimica/ Etc.): \n") c = input("Ingresar Calificación del Primer Trimestre: \n") d = input("Ingresar Calificación del Segundo Trimestre: \n") e = input ("Ingresar Calificación del Tercer Trimestre: \n") try: n = float(c) nu = float(d) num = float(e) except : print("-----------------------------------------------------------------------------") print("Valor ingresado en calificación NO es valido, vuelva a intentarlo!") print("-----------------------------------------------------------------------------") break total = (n + nu + num) / 3 print("---------------------------------------------------------------------------------") print(" El alumno: \n", a , "\n tiene un promedio de: \n", total, "\n en la materia: \n", b) print("---------------------------------------------------------------------------------") print("************************************************************") print(" ****** Sus promedios fueron mostrados, gracias por usar el registro ******")
UTF-8
Python
false
false
1,630
py
5
promedios.py
3
0.456335
0.45572
0
32
49.8125
99
xielinshai1992/PyQt5
11,553,462,035,406
787724c7d651a4e447a4673a2d5a4868a3ff5b0e
b9004f0539279fe61539164076d8e71b8a884965
/create_airportdata/adsb_mainForm.py
2c8360d0b8ccf90a19ad819d51850de563a8581d
[]
no_license
https://github.com/xielinshai1992/PyQt5
2576eaa3dd672da94a0cab389ad3a1a5eb48df50
a295b8d97165f8fec7f7e4b64ffc75604ac91269
refs/heads/master
2021-06-15T18:18:12.748160
2021-05-14T09:02:52
2021-05-14T09:02:52
200,157,657
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'adsb_mainForm.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(1550, 880) MainWindow.setMaximumSize(QtCore.QSize(1550, 880)) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("C:/Users/Administrator/.designer/backup/pic/airport.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) MainWindow.setWindowIcon(icon) MainWindow.setToolTipDuration(0) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.groupBox_2 = QtWidgets.QGroupBox(self.centralwidget) self.groupBox_2.setGeometry(QtCore.QRect(920, 370, 611, 491)) font = QtGui.QFont() font.setFamily("宋体") font.setPointSize(11) self.groupBox_2.setFont(font) self.groupBox_2.setObjectName("groupBox_2") self.tabWidget = QtWidgets.QTabWidget(self.groupBox_2) self.tabWidget.setGeometry(QtCore.QRect(10, 25, 591, 461)) self.tabWidget.setObjectName("tabWidget") self.tab = QtWidgets.QWidget() self.tab.setObjectName("tab") self.frame_target = QtWidgets.QFrame(self.tab) self.frame_target.setGeometry(QtCore.QRect(0, 0, 591, 421)) self.frame_target.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_target.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_target.setObjectName("frame_target") self.groupBox_tcas_target1 = QtWidgets.QGroupBox(self.frame_target) self.groupBox_tcas_target1.setGeometry(QtCore.QRect(310, 50, 271, 361)) self.groupBox_tcas_target1.setObjectName("groupBox_tcas_target1") self.btn_stopsend_tcas_target1 = QtWidgets.QPushButton(self.groupBox_tcas_target1) self.btn_stopsend_tcas_target1.setGeometry(QtCore.QRect(10, 318, 251, 28)) self.btn_stopsend_tcas_target1.setObjectName("btn_stopsend_tcas_target1") self.layoutWidget = QtWidgets.QWidget(self.groupBox_tcas_target1) self.layoutWidget.setGeometry(QtCore.QRect(10, 40, 251, 261)) self.layoutWidget.setObjectName("layoutWidget") self.gridLayout_3 = QtWidgets.QGridLayout(self.layoutWidget) self.gridLayout_3.setContentsMargins(0, 0, 0, 0) self.gridLayout_3.setObjectName("gridLayout_3") self.label_27 = QtWidgets.QLabel(self.layoutWidget) self.label_27.setScaledContents(True) self.label_27.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.label_27.setObjectName("label_27") self.gridLayout_3.addWidget(self.label_27, 0, 0, 1, 1) self.txt_Track_ID_target1 = QtWidgets.QLineEdit(self.layoutWidget) self.txt_Track_ID_target1.setEnabled(False) self.txt_Track_ID_target1.setMaximumSize(QtCore.QSize(150, 16777215)) self.txt_Track_ID_target1.setText("") self.txt_Track_ID_target1.setObjectName("txt_Track_ID_target1") self.gridLayout_3.addWidget(self.txt_Track_ID_target1, 0, 1, 1, 1) self.label_26 = QtWidgets.QLabel(self.layoutWidget) self.label_26.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.label_26.setObjectName("label_26") self.gridLayout_3.addWidget(self.label_26, 1, 0, 1, 1) self.txt_Tcas_Altitude_target1 = QtWidgets.QLineEdit(self.layoutWidget) self.txt_Tcas_Altitude_target1.setEnabled(False) self.txt_Tcas_Altitude_target1.setMaximumSize(QtCore.QSize(150, 16777215)) self.txt_Tcas_Altitude_target1.setText("") self.txt_Tcas_Altitude_target1.setObjectName("txt_Tcas_Altitude_target1") self.gridLayout_3.addWidget(self.txt_Tcas_Altitude_target1, 1, 1, 1, 1) self.label_23 = QtWidgets.QLabel(self.layoutWidget) self.label_23.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.label_23.setObjectName("label_23") self.gridLayout_3.addWidget(self.label_23, 2, 0, 1, 1) self.txt_Relative_Direction_target1 = QtWidgets.QLineEdit(self.layoutWidget) self.txt_Relative_Direction_target1.setEnabled(False) self.txt_Relative_Direction_target1.setMaximumSize(QtCore.QSize(150, 16777215)) self.txt_Relative_Direction_target1.setText("") self.txt_Relative_Direction_target1.setObjectName("txt_Relative_Direction_target1") self.gridLayout_3.addWidget(self.txt_Relative_Direction_target1, 2, 1, 1, 1) self.label_21 = QtWidgets.QLabel(self.layoutWidget) self.label_21.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.label_21.setObjectName("label_21") self.gridLayout_3.addWidget(self.label_21, 3, 0, 1, 1) self.txt_Relative_Distance_target1 = QtWidgets.QLineEdit(self.layoutWidget) self.txt_Relative_Distance_target1.setEnabled(False) self.txt_Relative_Distance_target1.setMaximumSize(QtCore.QSize(150, 16777215)) self.txt_Relative_Distance_target1.setText("") self.txt_Relative_Distance_target1.setObjectName("txt_Relative_Distance_target1") self.gridLayout_3.addWidget(self.txt_Relative_Distance_target1, 3, 1, 1, 1) self.btn_import_info_target1 = QtWidgets.QPushButton(self.frame_target) self.btn_import_info_target1.setGeometry(QtCore.QRect(10, 15, 241, 28)) self.btn_import_info_target1.setObjectName("btn_import_info_target1") self.groupBox_adsb_target1 = QtWidgets.QGroupBox(self.frame_target) self.groupBox_adsb_target1.setGeometry(QtCore.QRect(10, 50, 291, 361)) self.groupBox_adsb_target1.setObjectName("groupBox_adsb_target1") self.layoutWidget1 = QtWidgets.QWidget(self.groupBox_adsb_target1) self.layoutWidget1.setGeometry(QtCore.QRect(9, 34, 271, 318)) self.layoutWidget1.setObjectName("layoutWidget1") self.gridLayout_2 = QtWidgets.QGridLayout(self.layoutWidget1) self.gridLayout_2.setContentsMargins(0, 0, 0, 0) self.gridLayout_2.setObjectName("gridLayout_2") self.label_4 = QtWidgets.QLabel(self.layoutWidget1) self.label_4.setMaximumSize(QtCore.QSize(144, 16777215)) self.label_4.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.label_4.setObjectName("label_4") self.gridLayout_2.addWidget(self.label_4, 2, 0, 1, 1) self.txt_Heading_Track_Angle_target1 = QtWidgets.QLineEdit(self.layoutWidget1) self.txt_Heading_Track_Angle_target1.setEnabled(False) self.txt_Heading_Track_Angle_target1.setMaximumSize(QtCore.QSize(150, 16777215)) self.txt_Heading_Track_Angle_target1.setText("") self.txt_Heading_Track_Angle_target1.setObjectName("txt_Heading_Track_Angle_target1") self.gridLayout_2.addWidget(self.txt_Heading_Track_Angle_target1, 7, 1, 1, 1) self.txt_FlightID_target1 = QtWidgets.QLineEdit(self.layoutWidget1) self.txt_FlightID_target1.setEnabled(False) self.txt_FlightID_target1.setMaximumSize(QtCore.QSize(150, 16777215)) self.txt_FlightID_target1.setText("") self.txt_FlightID_target1.setObjectName("txt_FlightID_target1") self.gridLayout_2.addWidget(self.txt_FlightID_target1, 1, 1, 1, 1) self.txt_V_EW_target1 = QtWidgets.QLineEdit(self.layoutWidget1) self.txt_V_EW_target1.setEnabled(False) self.txt_V_EW_target1.setMaximumSize(QtCore.QSize(150, 16777215)) self.txt_V_EW_target1.setText("") self.txt_V_EW_target1.setObjectName("txt_V_EW_target1") self.gridLayout_2.addWidget(self.txt_V_EW_target1, 4, 1, 1, 1) self.txt_Latitude_target1 = QtWidgets.QLineEdit(self.layoutWidget1) self.txt_Latitude_target1.setEnabled(False) self.txt_Latitude_target1.setMaximumSize(QtCore.QSize(150, 16777215)) self.txt_Latitude_target1.setText("") self.txt_Latitude_target1.setObjectName("txt_Latitude_target1") self.gridLayout_2.addWidget(self.txt_Latitude_target1, 5, 1, 1, 1) self.label_11 = QtWidgets.QLabel(self.layoutWidget1) self.label_11.setMaximumSize(QtCore.QSize(90, 16777215)) self.label_11.setScaledContents(True) self.label_11.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.label_11.setObjectName("label_11") self.gridLayout_2.addWidget(self.label_11, 0, 0, 1, 1) self.label_12 = QtWidgets.QLabel(self.layoutWidget1) self.label_12.setMaximumSize(QtCore.QSize(16777215, 16777214)) self.label_12.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.label_12.setObjectName("label_12") self.gridLayout_2.addWidget(self.label_12, 3, 0, 1, 1) self.txt_V_SN_target1 = QtWidgets.QLineEdit(self.layoutWidget1) self.txt_V_SN_target1.setEnabled(False) self.txt_V_SN_target1.setMaximumSize(QtCore.QSize(150, 16777215)) self.txt_V_SN_target1.setText("") self.txt_V_SN_target1.setObjectName("txt_V_SN_target1") self.gridLayout_2.addWidget(self.txt_V_SN_target1, 3, 1, 1, 1) self.label_15 = QtWidgets.QLabel(self.layoutWidget1) self.label_15.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.label_15.setObjectName("label_15") self.gridLayout_2.addWidget(self.label_15, 4, 0, 1, 1) self.label_14 = QtWidgets.QLabel(self.layoutWidget1) self.label_14.setMaximumSize(QtCore.QSize(90, 16777215)) self.label_14.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.label_14.setObjectName("label_14") self.gridLayout_2.addWidget(self.label_14, 1, 0, 1, 1) self.txt_Longitude_target1 = QtWidgets.QLineEdit(self.layoutWidget1) self.txt_Longitude_target1.setEnabled(False) self.txt_Longitude_target1.setMaximumSize(QtCore.QSize(150, 16777215)) self.txt_Longitude_target1.setText("") self.txt_Longitude_target1.setObjectName("txt_Longitude_target1") self.gridLayout_2.addWidget(self.txt_Longitude_target1, 6, 1, 1, 1) self.label_17 = QtWidgets.QLabel(self.layoutWidget1) self.label_17.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.label_17.setObjectName("label_17") self.gridLayout_2.addWidget(self.label_17, 8, 0, 1, 1) self.label_18 = QtWidgets.QLabel(self.layoutWidget1) self.label_18.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.label_18.setObjectName("label_18") self.gridLayout_2.addWidget(self.label_18, 7, 0, 1, 1) self.label_13 = QtWidgets.QLabel(self.layoutWidget1) self.label_13.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.label_13.setObjectName("label_13") self.gridLayout_2.addWidget(self.label_13, 5, 0, 1, 1) self.txt_ICAO_target1 = QtWidgets.QLineEdit(self.layoutWidget1) self.txt_ICAO_target1.setEnabled(False) self.txt_ICAO_target1.setMaximumSize(QtCore.QSize(150, 16777215)) self.txt_ICAO_target1.setText("") self.txt_ICAO_target1.setObjectName("txt_ICAO_target1") self.gridLayout_2.addWidget(self.txt_ICAO_target1, 0, 1, 1, 1) self.txt_Altitude_target1 = QtWidgets.QLineEdit(self.layoutWidget1) self.txt_Altitude_target1.setEnabled(False) self.txt_Altitude_target1.setMaximumSize(QtCore.QSize(150, 16777215)) self.txt_Altitude_target1.setText("") self.txt_Altitude_target1.setObjectName("txt_Altitude_target1") self.gridLayout_2.addWidget(self.txt_Altitude_target1, 2, 1, 1, 1) self.label_16 = QtWidgets.QLabel(self.layoutWidget1) self.label_16.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.label_16.setObjectName("label_16") self.gridLayout_2.addWidget(self.label_16, 6, 0, 1, 1) self.txt_GroundSpeed_target1 = QtWidgets.QLineEdit(self.layoutWidget1) self.txt_GroundSpeed_target1.setEnabled(False) self.txt_GroundSpeed_target1.setMaximumSize(QtCore.QSize(150, 16777215)) self.txt_GroundSpeed_target1.setText("") self.txt_GroundSpeed_target1.setObjectName("txt_GroundSpeed_target1") self.gridLayout_2.addWidget(self.txt_GroundSpeed_target1, 8, 1, 1, 1) self.btn_stopsend_adsb_target1 = QtWidgets.QPushButton(self.layoutWidget1) self.btn_stopsend_adsb_target1.setObjectName("btn_stopsend_adsb_target1") self.gridLayout_2.addWidget(self.btn_stopsend_adsb_target1, 9, 0, 1, 2) self.tabWidget.addTab(self.tab, "") self.groupBox_3 = QtWidgets.QGroupBox(self.centralwidget) self.groupBox_3.setGeometry(QtCore.QRect(1230, 0, 301, 361)) font = QtGui.QFont() font.setFamily("宋体") font.setPointSize(11) self.groupBox_3.setFont(font) self.groupBox_3.setObjectName("groupBox_3") self.btn_start = QtWidgets.QPushButton(self.groupBox_3) self.btn_start.setGeometry(QtCore.QRect(50, 120, 201, 28)) self.btn_start.setObjectName("btn_start") self.btn_stop = QtWidgets.QPushButton(self.groupBox_3) self.btn_stop.setEnabled(False) self.btn_stop.setGeometry(QtCore.QRect(50, 180, 201, 28)) self.btn_stop.setObjectName("btn_stop") self.groupBox = QtWidgets.QGroupBox(self.centralwidget) self.groupBox.setGeometry(QtCore.QRect(920, 0, 291, 361)) font = QtGui.QFont() font.setFamily("宋体") font.setPointSize(11) self.groupBox.setFont(font) self.groupBox.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.groupBox.setFlat(False) self.groupBox.setCheckable(False) self.groupBox.setObjectName("groupBox") self.layoutWidget2 = QtWidgets.QWidget(self.groupBox) self.layoutWidget2.setGeometry(QtCore.QRect(20, 30, 241, 318)) self.layoutWidget2.setObjectName("layoutWidget2") self.gridLayout = QtWidgets.QGridLayout(self.layoutWidget2) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setObjectName("gridLayout") self.txt_GroundSpeed_own = QtWidgets.QLineEdit(self.layoutWidget2) self.txt_GroundSpeed_own.setEnabled(False) self.txt_GroundSpeed_own.setMaximumSize(QtCore.QSize(150, 16777215)) self.txt_GroundSpeed_own.setText("") self.txt_GroundSpeed_own.setObjectName("txt_GroundSpeed_own") self.gridLayout.addWidget(self.txt_GroundSpeed_own, 13, 2, 1, 1) self.label_2 = QtWidgets.QLabel(self.layoutWidget2) self.label_2.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.label_2.setObjectName("label_2") self.gridLayout.addWidget(self.label_2, 2, 1, 1, 1) self.txt_Altitude_own = QtWidgets.QLineEdit(self.layoutWidget2) self.txt_Altitude_own.setEnabled(False) self.txt_Altitude_own.setMaximumSize(QtCore.QSize(150, 16777215)) self.txt_Altitude_own.setText("") self.txt_Altitude_own.setObjectName("txt_Altitude_own") self.gridLayout.addWidget(self.txt_Altitude_own, 3, 2, 1, 1) self.txt_FlightID_own = QtWidgets.QLineEdit(self.layoutWidget2) self.txt_FlightID_own.setEnabled(False) self.txt_FlightID_own.setMaximumSize(QtCore.QSize(150, 16777215)) self.txt_FlightID_own.setText("") self.txt_FlightID_own.setObjectName("txt_FlightID_own") self.gridLayout.addWidget(self.txt_FlightID_own, 2, 2, 1, 1) self.txt_V_EW_own = QtWidgets.QLineEdit(self.layoutWidget2) self.txt_V_EW_own.setEnabled(False) self.txt_V_EW_own.setMaximumSize(QtCore.QSize(150, 16777215)) self.txt_V_EW_own.setText("") self.txt_V_EW_own.setObjectName("txt_V_EW_own") self.gridLayout.addWidget(self.txt_V_EW_own, 5, 2, 1, 1) self.label_7 = QtWidgets.QLabel(self.layoutWidget2) self.label_7.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.label_7.setObjectName("label_7") self.gridLayout.addWidget(self.label_7, 6, 1, 1, 1) self.txt_V_SN_own = QtWidgets.QLineEdit(self.layoutWidget2) self.txt_V_SN_own.setEnabled(False) self.txt_V_SN_own.setMaximumSize(QtCore.QSize(150, 16777215)) self.txt_V_SN_own.setText("") self.txt_V_SN_own.setObjectName("txt_V_SN_own") self.gridLayout.addWidget(self.txt_V_SN_own, 4, 2, 1, 1) self.label_9 = QtWidgets.QLabel(self.layoutWidget2) self.label_9.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.label_9.setObjectName("label_9") self.gridLayout.addWidget(self.label_9, 9, 1, 1, 1) self.label_3 = QtWidgets.QLabel(self.layoutWidget2) self.label_3.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.label_3.setObjectName("label_3") self.gridLayout.addWidget(self.label_3, 3, 1, 1, 1) self.label_6 = QtWidgets.QLabel(self.layoutWidget2) self.label_6.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.label_6.setObjectName("label_6") self.gridLayout.addWidget(self.label_6, 5, 1, 1, 1) self.txt_Heading_Track_Angle_own = QtWidgets.QLineEdit(self.layoutWidget2) self.txt_Heading_Track_Angle_own.setEnabled(False) self.txt_Heading_Track_Angle_own.setMaximumSize(QtCore.QSize(150, 16777215)) self.txt_Heading_Track_Angle_own.setText("") self.txt_Heading_Track_Angle_own.setObjectName("txt_Heading_Track_Angle_own") self.gridLayout.addWidget(self.txt_Heading_Track_Angle_own, 9, 2, 1, 1) self.label_8 = QtWidgets.QLabel(self.layoutWidget2) self.label_8.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.label_8.setObjectName("label_8") self.gridLayout.addWidget(self.label_8, 8, 1, 1, 1) self.txt_Longitude_own = QtWidgets.QLineEdit(self.layoutWidget2) self.txt_Longitude_own.setEnabled(False) self.txt_Longitude_own.setMaximumSize(QtCore.QSize(150, 16777215)) self.txt_Longitude_own.setText("") self.txt_Longitude_own.setObjectName("txt_Longitude_own") self.gridLayout.addWidget(self.txt_Longitude_own, 8, 2, 1, 1) self.label = QtWidgets.QLabel(self.layoutWidget2) self.label.setScaledContents(True) self.label.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.label.setObjectName("label") self.gridLayout.addWidget(self.label, 1, 1, 1, 1) self.txt_Latitude_own = QtWidgets.QLineEdit(self.layoutWidget2) self.txt_Latitude_own.setEnabled(False) self.txt_Latitude_own.setMaximumSize(QtCore.QSize(150, 16777215)) self.txt_Latitude_own.setText("") self.txt_Latitude_own.setObjectName("txt_Latitude_own") self.gridLayout.addWidget(self.txt_Latitude_own, 6, 2, 1, 1) self.label_5 = QtWidgets.QLabel(self.layoutWidget2) self.label_5.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.label_5.setObjectName("label_5") self.gridLayout.addWidget(self.label_5, 4, 1, 1, 1) self.label_10 = QtWidgets.QLabel(self.layoutWidget2) self.label_10.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.label_10.setObjectName("label_10") self.gridLayout.addWidget(self.label_10, 13, 1, 1, 1) self.txt_ICAO_own = QtWidgets.QLineEdit(self.layoutWidget2) self.txt_ICAO_own.setEnabled(False) self.txt_ICAO_own.setMaximumSize(QtCore.QSize(150, 16777215)) self.txt_ICAO_own.setText("") self.txt_ICAO_own.setObjectName("txt_ICAO_own") self.gridLayout.addWidget(self.txt_ICAO_own, 1, 2, 1, 1) self.btn_import_info_own = QtWidgets.QPushButton(self.layoutWidget2) self.btn_import_info_own.setObjectName("btn_import_info_own") self.gridLayout.addWidget(self.btn_import_info_own, 0, 1, 1, 2) self.horizontalLayoutWidget = QtWidgets.QWidget(self.centralwidget) self.horizontalLayoutWidget.setGeometry(QtCore.QRect(10, 10, 901, 851)) self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget") self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget) self.horizontalLayout_3.setContentsMargins(0, 0, 0, 0) self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.layoutWidget3 = QtWidgets.QWidget(self.centralwidget) self.layoutWidget3.setGeometry(QtCore.QRect(0, 0, 2, 2)) self.layoutWidget3.setObjectName("layoutWidget3") self.horizontalLayout = QtWidgets.QHBoxLayout(self.layoutWidget3) self.horizontalLayout.setContentsMargins(0, 0, 0, 0) self.horizontalLayout.setObjectName("horizontalLayout") self.layoutWidget4 = QtWidgets.QWidget(self.centralwidget) self.layoutWidget4.setGeometry(QtCore.QRect(0, 0, 2, 2)) self.layoutWidget4.setObjectName("layoutWidget4") self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.layoutWidget4) self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0) self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.layoutWidget5 = QtWidgets.QWidget(self.centralwidget) self.layoutWidget5.setGeometry(QtCore.QRect(0, 0, 2, 2)) self.layoutWidget5.setObjectName("layoutWidget5") self.verticalLayout = QtWidgets.QVBoxLayout(self.layoutWidget5) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") self.layoutWidget6 = QtWidgets.QWidget(self.centralwidget) self.layoutWidget6.setGeometry(QtCore.QRect(0, 0, 2, 2)) self.layoutWidget6.setObjectName("layoutWidget6") self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.layoutWidget6) self.horizontalLayout_4.setContentsMargins(0, 0, 0, 0) self.horizontalLayout_4.setObjectName("horizontalLayout_4") MainWindow.setCentralWidget(self.centralwidget) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.action1 = QtWidgets.QAction(MainWindow) self.action1.setObjectName("action1") self.action2 = QtWidgets.QAction(MainWindow) self.action2.setObjectName("action2") self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "模拟飞机数据产生软件")) self.groupBox_2.setTitle(_translate("MainWindow", "目标机信息")) self.groupBox_tcas_target1.setTitle(_translate("MainWindow", "TCAS")) self.btn_stopsend_tcas_target1.setText(_translate("MainWindow", "暂停发送TCAS数据")) self.label_27.setText(_translate("MainWindow", "Track_ID:")) self.label_26.setText(_translate("MainWindow", "压强高度(m):")) self.label_23.setText(_translate("MainWindow", "相对本机方位(deg):")) self.label_21.setText(_translate("MainWindow", "相对本机距离(km):")) self.btn_import_info_target1.setText(_translate("MainWindow", "导入飞机信息")) self.groupBox_adsb_target1.setTitle(_translate("MainWindow", "ADS-B")) self.label_4.setText(_translate("MainWindow", "压强高度(m):")) self.label_11.setText(_translate("MainWindow", "ICAO码:")) self.label_12.setText(_translate("MainWindow", "南北速度(km/h):")) self.label_15.setText(_translate("MainWindow", "东西速度(km/h):")) self.label_14.setText(_translate("MainWindow", "航班号:")) self.label_17.setText(_translate("MainWindow", "地速(km/h):")) self.label_18.setText(_translate("MainWindow", "航向角(deg):")) self.label_13.setText(_translate("MainWindow", "纬度(deg):")) self.label_16.setText(_translate("MainWindow", "经度(deg):")) self.btn_stopsend_adsb_target1.setText(_translate("MainWindow", "暂停发送ADS-B数据")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "1号目标机")) self.groupBox_3.setTitle(_translate("MainWindow", "控制台")) self.btn_start.setText(_translate("MainWindow", "开始")) self.btn_stop.setText(_translate("MainWindow", "停止")) self.groupBox.setTitle(_translate("MainWindow", "本机信息")) self.label_2.setText(_translate("MainWindow", "航班号:")) self.label_7.setText(_translate("MainWindow", "纬度(deg):")) self.label_9.setText(_translate("MainWindow", "航向角(deg):")) self.label_3.setText(_translate("MainWindow", "压强高度(m):")) self.label_6.setText(_translate("MainWindow", "东西速度(km/h):")) self.label_8.setText(_translate("MainWindow", "经度(deg):")) self.label.setText(_translate("MainWindow", "ICAO码:")) self.label_5.setText(_translate("MainWindow", "南北速度(km/h):")) self.label_10.setText(_translate("MainWindow", "地速(km/h):")) self.btn_import_info_own.setText(_translate("MainWindow", "导入飞机信息")) self.action1.setText(_translate("MainWindow", "本机")) self.action2.setText(_translate("MainWindow", "目标机"))
UTF-8
Python
false
false
26,115
py
20
adsb_mainForm.py
13
0.697866
0.652364
0
408
62.289216
133
ruoyuryc/Deep-Learning-and-Practice-2020-Spring
10,015,863,742,504
cf013a25a98a87241155c3a652812f76407a55a8
1a7b47bb1ff483b236211aaa5cc648b9c7854853
/Lab6/dataset/preprocess.py
d7f6f828773917338ced47463e4c8f1aed341920
[]
no_license
https://github.com/ruoyuryc/Deep-Learning-and-Practice-2020-Spring
4929ed3aa83312029daf724d76554f8768a23e4c
7ac9fc9163635aff8ae386c610396ae4646f8095
refs/heads/master
2022-10-20T04:45:37.648427
2020-06-15T15:24:25
2020-06-15T15:24:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import PIL from PIL import Image import torch import json from torchvision import transforms from tqdm import tqdm with open('objects.json', 'r') as f: objects = json.load(f) with open('labels.json', 'r') as f: labels = json.load(f) trans = transforms.Compose([ transforms.Resize((64, 64)), transforms.ToTensor(), transforms.Normalize( mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5] ) ]) torch.save(trans(PIL.Image.open('png/background.png').convert('RGB')), 'background.pth') lbls = [] imgs = [] for idx in tqdm(range(6004)): for sub_idx in range(3): key = f'CLEVR_train_{idx:06}_{sub_idx}.png' lbls.append(torch.LongTensor([objects[labels[key][-1]]])) imgs.append(trans(PIL.Image.open(f'png/{key}').convert("RGB"))) lbls = torch.stack(lbls) imgs = torch.stack(imgs) torch.save(lbls, 'labels.pth') torch.save(imgs, 'images.pth')
UTF-8
Python
false
false
902
py
79
preprocess.py
54
0.638581
0.611973
0
39
22.128205
88
radtek/Server-Monitoring
9,423,158,281,982
7219366ebfbf87e59f6fdd2fd5ccae0112e74180
5cd16658110d9a65556b63a16cf07a9b6ea338fc
/Ver2.0/zabbix/CentOS-7/vdisk_status.py
7c0126bdacdb53b979ffaff12a108657d624781c
[]
no_license
https://github.com/radtek/Server-Monitoring
60a21c837bddd786bddb41ee463ba2f5c11acce5
9f3ca9876a0ed5e9f4971cec873e524f06fd87ab
refs/heads/master
2023-05-02T16:20:52.299839
2021-05-19T14:57:15
2021-05-19T14:57:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os import re import sys def get_pdisk_status(logicaldrive): conent=os.popen("sudo hpacucli ctrl all show config").readlines() for index in range(len(conent)): if logicaldrive in conent[index] and re.split(r'[ ]',conent[index])[7].strip()==logicaldrive: return re.split(r'[) ]',conent[index])[12].strip() if __name__=='__main__': if get_pdisk_status(sys.argv[1])=="OK": print 1 else: print 0
UTF-8
Python
false
false
413
py
74
vdisk_status.py
40
0.677966
0.663438
0
15
26.533333
95
baidw/languages
11,965,778,916,584
d13a61b51cf2af8b54e138d63029d9326688fd45
2f4c7fae43c7d13d1925f8d5a53d05021865c34b
/python/trainning/train_001_farbic.py
e23676cea992ef58f7f2852115628f5ac1a9a023
[]
no_license
https://github.com/baidw/languages
87aafe620d6873e6bffc6d0aafe517939784bba0
5e7cccc737cc6f415e0b1e91f441a84b6286603b
refs/heads/master
2020-05-22T06:40:33.668235
2018-10-23T05:59:22
2018-10-23T05:59:22
60,157,718
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__='baidw' def tribonacci(signature,n): #your code here temp = signature slen=len(temp) if n ==0: return [] if n==1 and len(list(set(signature)))==1: return signature[:1] while slen<n: temp.append(int(temp[slen-1])+int(temp[slen-2])+int(temp[slen-3])) slen=len(temp) return temp x= tribonacci([1,1,1],1) print x
UTF-8
Python
false
false
434
py
78
train_001_farbic.py
66
0.56682
0.539171
0
21
19.714286
74
cpressland/dictfilter
15,693,810,512,280
73cec6a3d0e754d20788f3fe19326ddf0f70fc83
80cad9acb46be23437f22344e23b79caf3c45e98
/dictfilter/__init__.py
64fa0354e1a5c9182228aaf6b3a9d30c6ed0590a
[ "MIT" ]
permissive
https://github.com/cpressland/dictfilter
fbd1e5ba6b47253c529eb2c25b666e223dcae90c
a55f68d1719bc951e283b8dccbd7eee315bbdee5
refs/heads/master
2023-03-12T16:08:14.512146
2023-02-28T13:46:46
2023-02-28T13:46:46
289,022,266
0
0
null
true
2020-08-20T14:05:32
2020-08-20T14:05:31
2020-08-20T13:57:11
2020-08-20T13:57:07
0
0
0
0
null
false
false
from dictfilter.core import query # noqa
UTF-8
Python
false
false
42
py
10
__init__.py
5
0.785714
0.785714
0
1
41
41
dcherix/apiontology-demonstrator
1,829,656,074,901
1c132bae81dadeec1fa82712aa2177961c35223c
d62283766afd59ddde1a630c80eb92d52cf3df0f
/apiontology-demonstrator-example-services/citylatlong.py
15ff810ace2780c3d5a5ec1a00e3a9b56c1af313
[]
no_license
https://github.com/dcherix/apiontology-demonstrator
129d16e4081f22677642f38a62a7ec49ecb1c1b1
9a4974f1cfdbba6b7e05e5f64beaa7e2792592cd
refs/heads/master
2022-12-22T17:19:40.697607
2018-10-18T05:14:53
2019-09-04T19:56:21
42,429,342
2
0
null
false
2022-12-16T09:52:56
2015-09-14T05:40:31
2019-09-04T19:57:03
2022-12-16T09:52:52
5,566
2
0
10
Java
false
false
''' service returns for a given city and adminarea the corresponding lat,long @author a.both ''' from service import init_service import csv from pprint import pprint def citylatlong( cityname, adminarea ): ''' returns the companys city, country and stock name as strings for a given company name ''' global citylatlong_data try: result = citylatlong_data[cityname][adminarea] except: result = {} print("in: ",cityname,adminarea," out: ",result) return result def main(): # read data from CSV file reader = csv.reader(open('citylatlong.csv', 'r')) global citylatlong_data citylatlong_data = {} for row in reader: cityname,adminarea,latlong = row #print cityname,adminarea,latlong long,lat = latlong.split() citylatlong_data[cityname] = { adminarea: {'lat':lat, 'long':long} } init_service( port=8182, servicename='CityLatLong', userfunction=citylatlong, args={'cityname':str, 'adminarea':str}, returns={'lat':str, 'long':str} ) if __name__ =='__main__': main()
UTF-8
Python
false
false
1,064
py
75
citylatlong.py
49
0.665414
0.661654
0
45
22.666667
89
Richard-CH-NG/djangular_project
3,728,031,638,696
55d208038bc4f61ccdeddc5720f80405fe8a0516
cc8445d0af32a7134ffd8c5b45851d7bd73069a3
/accounts/forms.py
7a2d40f0ee12fb875f5e64ca998d198314a07b1e
[]
no_license
https://github.com/Richard-CH-NG/djangular_project
5a5ad33b080bc25ae7a93f15e7e507961d1f4a9f
fa121457cf9ae81886df034692811141d8868daa
refs/heads/master
2017-07-31T17:12:25.470749
2017-06-29T06:00:07
2017-06-29T06:00:07
95,001,627
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django import forms from django.contrib.auth import ( authenticate, get_user_model, login, logout, ) User = get_user_model() class UserLoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def clean(self): username = self.cleaned_data['username'] password = self.cleaned_data['password'] user = authenticate(username=username, password=password) if not user: raise forms.ValidationError("This username/password does not exist.") # if not user.check_password(password): # raise forms.ValidationError("Incorrect Password.") if not user.is_active: raise forms.ValidationError("This user is no longer active") # if everthing's okay, return the default clean return super(UserLoginForm, self).clean() class UserRegisterForm(forms.ModelForm): email2 = forms.EmailField(label="Confirm Email") class Meta: model = User fields = [ 'username', 'email', 'email2', 'password', ] widgets = { 'password' : forms.PasswordInput } # if use clean_email method, will give KeyError # becuz order matter, email2 exists after email, # so u won't see email2 in cleaned_data yet when "cleaning" email def clean(self): """cleaning email for which the default does not do that""" print(self.cleaned_data) email = self.cleaned_data['email'] email2 = self.cleaned_data['email2'] if email != email2: raise forms.ValidationError("Email input fields do not match.") if User.objects.filter(email=email).exists(): raise forms.ValidationError("This email has already been registered.") return super(UserRegisterForm, self).clean()
UTF-8
Python
false
false
1,894
py
31
forms.py
18
0.629356
0.62566
0
56
32.821429
82
guchio3/kaggle-homecredit
14,671,608,304,654
4e58d936853ac71598de202f0ec4a27cc48d6fd4
e29103f2f7e4a44dbb4626f4f138ed09555d2dcc
/protos/shared_kfold/split.py
c66a33d0cee56735c0558f7ee054e78c3d7075c4
[]
no_license
https://github.com/guchio3/kaggle-homecredit
e800eac42dd0f2428de9099d6052139c2df6e2ac
210a7bb3a5e124bd4a9895cf95be8d5269c1a225
refs/heads/master
2020-04-27T23:56:57.408848
2019-03-16T07:05:56
2019-03-16T07:05:56
174,797,829
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from sklearn.cross_validation import KFold import numpy as np def splitter(clf, x_train, y, x_test): NFOLDS = 5 SEED = 71 kf = KFold(len(x_train), n_folds=NFOLDS, shuffle=True, random_state=SEED) fold_train_test = {} for i, (train_index, test_index) in enumerate(kf): fold_train_test[i] = { 'train_index': train_index, 'test_index':test_index } return fold_train_test import glob, gc import pandas as pd df = pd.read_pickle('../my-nural/00-dump.pkl') train_df = df[df['TARGET'].notnull()] test_df = df[df['TARGET'].isnull()] feats = [f for f in train_df.columns if f not in ['TARGET','SK_ID_CURR','SK_ID_BUREAU','SK_ID_PREV','index']] y = train_df['TARGET'] # この差は4件あるが、7.95だしているカーネルによるとこれは、正しい print(train_df.shape) print(pd.read_csv('../input/application_train.csv').shape) check = pd.read_pickle('../my-nural/00-dump.pkl') print( check[check['TARGET'].notnull()].shape ) fold_train_test = splitter(None, train_df, y.values, test_df) import pickle pickle.dump(fold_train_test, open('fold_train_test.pkl', 'wb')) # pickle形式で保存 # 例) 2foldのtrain_indexにアクセス # fold_train_test = pickle.load(open('fold_train_test.pkl', 'rb')) print(fold_train_test[2]['train_index'] )
UTF-8
Python
false
false
1,280
py
307
split.py
16
0.684474
0.673623
0
35
33.2
109
eymenkurdoglu/ml_projects
15,882,789,085,006
f3e620a9e29086f57bc765a48ed5564769bf515d
1c1d8f76da7fb157af608ece27d9759b0b6c8bbf
/time-ser-forecast/svr.py
9df9f4792ee82d1b15e818763f01bc5158dd512a
[]
no_license
https://github.com/eymenkurdoglu/ml_projects
f3a4c7b160621e4d603bd2b5e2c000897e6da0a0
1756d6a274952864ad23b835843734684a6ca17f
refs/heads/master
2021-04-15T15:10:24.684323
2018-03-27T02:24:27
2018-03-27T02:24:27
126,917,214
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import csv import numpy as np from sklearn.svm import SVR import matplotlib.pyplot as plt dates = [] prices = [] def get_data(filename): with open(filename, 'r') as csvfile: csvFileReader = csv.reader(csvfile) next(csvFileReader) for row in csvFileReader: dates.append(int(row[0].split('-')[0])) prices.append(float(row[1])) return def predict_price(dates, prices, x): dates = np.reshape(dates,(len(dates),1)) # convert to vector of length n svr_lin = SVR( kernel = 'linear', C = 1e3 ) svr_poly = SVR( kernel = 'poly', C = 1e3, degree = 2 ) svr_rbf = SVR( kernel = 'rbf', C = 1e3, gamma = 0.1 ) svr_lin.fit( dates, prices ) svr_poly.fit( dates, prices ) svr_rbf.fit( dates, prices ) plt.scatter( dates, prices, color = 'black', label = 'Data' ) plt. plot( dates, svr_lin.predict( dates ), color= 'green', label= 'Linear model' ) plt. plot( dates, svr_poly.predict( dates ), color= 'blue', label= 'Polynomial model' ) plt. plot( dates, svr_rbf.predict( dates ), color= 'red', label= 'RBF model' ) plt.xlabel('Date') plt.ylabel('Price') plt.legend() plt.show() return svr_rbf.predict(x)[0], svr_lin.predict(x)[0], svr_poly.predict(x)[0] get_data('googl.csv') predicted_price = predict_price(dates, prices, 29)
UTF-8
Python
false
false
1,254
py
3
svr.py
1
0.660287
0.645933
0
42
28.857143
89
Semenyshyn/CodeWars
17,076,789,999,317
4735c2217f97658ae8046d13262f1bc4575dea45
72220530641dd387f5cf178a3ed53b4a6815a22f
/Sum consecutives.py
73e43ffbb2590369dd4777cfa0c4333b20b05881
[]
no_license
https://github.com/Semenyshyn/CodeWars
7516d7ba27e46ab47364c5266ef578de95b4be7b
131ac35c55402853ddbeda38a8e27210ac1a7c7c
refs/heads/master
2020-06-23T13:41:04.134166
2016-08-20T11:56:11
2016-08-20T11:56:11
66,144,292
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
s = [1, 1, 1, 0, 1, 2, 2, -3, -3, -3] def sum_consecutives(s): prev = None x = [] for i in s: if i == prev: x[-1] += i else: x.append(i) prev = i return x print(sum_consecutives(s))
UTF-8
Python
false
false
248
py
15
Sum consecutives.py
15
0.407258
0.362903
0
15
15.6
37
uit-no/python-open-mike
14,499,809,609,993
31abe97f6eb43e59b864334d735deeb9ef29e6d2
21d7c98b8c7d62dd182f04d3a9ea092b8c330dea
/solutions/2/most-frequent/most_frequent.py
59149faf9558d3034f132ce342cbdf43313baac3
[]
no_license
https://github.com/uit-no/python-open-mike
951678870b61d63203e0b8c248c9189687473d9a
2a83b27ca31959f0c0de2ee6f72abca440d76ec8
refs/heads/gh-pages
2020-03-30T12:42:37.311093
2019-09-11T14:13:06
2019-09-11T14:13:06
151,236,182
2
4
null
false
2018-11-19T13:12:01
2018-10-02T10:16:25
2018-11-19T09:41:01
2018-11-19T13:12:00
363
0
2
0
Python
false
null
#!/usr/bin/env python3 from collections import Counter def strip_special_chars(string): return "".join(char for char in string if char.isalpha()) def char_counter(string, number): chars = filter(str.isalpha, string) return Counter(chars).most_common(number) def word_counter(string, number): words = map(strip_special_chars, string.split()) return Counter(words).most_common(number) if __name__ == "__main__": file_name = "poem.txt" with open(file_name) as page: lines = page.read().lower() print("# Most frequent words:", word_counter(lines, 5)) print("# Most frequent chars:", char_counter(lines, 5))
UTF-8
Python
false
false
655
py
45
most_frequent.py
31
0.668702
0.664122
0
24
26.291667
61
Jayashsatolia403/Projects
13,889,924,259,540
c3f9d3dc3dfdc3c8f7b66286d5c85f2a008a25ff
6e083faecc108f78210c9b43f5e19f2e29be8b56
/EcommerceFullStack/FullStack/EcommerceProject/order/migrations/0013_remove_order_users.py
82051cd23177920bbada0bcf7f77dc24f244d320
[]
no_license
https://github.com/Jayashsatolia403/Projects
d86240124ca189c00f706d5788b78c360b433cab
d98dc8600e29ae8e751da6c68d31902d3f5e9142
refs/heads/master
2023-06-26T01:01:49.983012
2021-07-20T11:28:01
2021-07-20T11:28:01
385,829,888
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Generated by Django 3.1.7 on 2021-04-13 20:28 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('order', '0012_auto_20210414_0150'), ] operations = [ migrations.RemoveField( model_name='order', name='users', ), ]
UTF-8
Python
false
false
324
py
114
0013_remove_order_users.py
97
0.574074
0.478395
0
17
18.058824
47
w-x-me/PyImageSearch
1,486,058,703,088
ce640a62583d401723fadc67b29991ba287401e4
e1def0cb3ea2f1b9e7e8c9183ef3eae6eb4f2d97
/Moudel1/Threshold3.py
a4fc0edef07bce52f351456350845733feb4a2e4
[]
no_license
https://github.com/w-x-me/PyImageSearch
58084fd4834457a10a75383702093f5d98a0e6e4
fc6034ae43767f9ec5cc0d4e6bb771d70a866a56
refs/heads/master
2020-03-20T07:50:17.690517
2018-06-14T02:08:51
2018-06-14T02:08:51
134,201,710
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from skimage.filters import threshold_adaptive import argparse import cv2 ap = argparse.ArgumenParser() ap.add_argument("-i", "--image", required = True, help = "Path to the image") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blurred = cv2.GussianBlur(image, (5, 5), 0) cv2.imshow("Image", image) thresh = cv2.adaptiveThreshold(blurred, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 25, 15) cv2.imshow("OpenCV Mean Thresh", thresh) thresh = threshold_adaptive(blurred, 29, offset = 5).astype("uint8") * 255 thresh = cv2.bitwise_not(thresh) cv2.imshow("scikit-image Mean Thresh", thresh) cv2.waitKey(0)
UTF-8
Python
false
false
683
py
65
Threshold3.py
60
0.7306
0.683748
0
20
33.15
103
machukhinktato/test_tasks_python
11,003,706,223,296
7e317a238433dece7c80b26c1d27912986d35974
c4ad8eb9ad11e821806c01953e630617a2dc274a
/task2/SRC/task2.py
1322ab674b152fa8add9dacb98f8056a10cdba7e
[]
no_license
https://github.com/machukhinktato/test_tasks_python
09cac9d2d2fac651efbe4bff8cb8327e62aa3b54
7dcf494742dbd24e6a271db368be91e64eeed26f
refs/heads/master
2023-02-17T00:21:15.459882
2021-01-20T15:48:50
2021-01-20T15:48:50
311,645,105
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import json def file_loader(name): """Загружает json файл с данынми""" with open(name) as f: try: file = json.load(f) except: file = f.readlines() f.close() return file def main(filename): """ Основная функция, принимает исходные значения, сортирует данные и отдаёт их на обработку профильным функциям """ # task_dict = file_loader(input('Enter the file name, to start program: ')) task_dict = file_loader(filename) sphere_coords, line_coords = [], [] for i in range(3): sphere_coords.append(( ((task_dict.get('sphere').get('center')[i]) - (task_dict.get('sphere').get('radius'))), (((task_dict.get('sphere').get('center')[i])) + (task_dict.get('sphere').get('radius')))) ) line_coords.append(( [task_dict.get('line')[0][i], task_dict.get('line')[1][i]] )) line = {'sections': { 'x': line_coords[0], 'y': line_coords[1], 'z': line_coords[2], }} result = comparison(line, sphere_coords) try: for key in result.keys(): # ok.append(f"{key} = {result.get(key)}") print(f"{key} : {result.get(key)}") return '' except: return print('Коллизий не найдено') def comparison(line, sphere): """Функция находящая точки внутри сферы""" x = 0 section = line.get('sections') for key in section.keys(): for i in range(2): if section[key][i] >= sphere[0][0] and section[key][i] <= sphere[x][1]: section.get(key).append(True) else: section.get(key).append(None) x += 1 return cross_finder(line, sphere) def cross_finder(sections, sphere): """ Функция производящая финальную оценку по точкам линии проходящим через или входящим в сферу """ x = 0 sections = sections.get('sections') crosspoints = dict() for key in sections.keys(): if sections[key][2] and sections[key][3] == True or \ float(sections[key][0]) < min(sphere[x]) and \ float(sections[key][1]) < min(sphere[x]) or \ float(sections[key][0]) > max(sphere[x]) and \ float(sections[key][1]) > max(sphere[x]): continue elif sections[key][2] == True: if sections[key][0] > sections[key][1]: # Номера присватваются в зависимот от элемента вхождения crosspoints[key + '_1'] = sphere[x][0] else: crosspoints[key + '_1'] = sphere[x][1] elif sections[key][3] == True: if sections[key][1] > sections[key][0]: crosspoints[key + '_2'] = sphere[x][0] else: crosspoints[key + '_2'] = sphere[x][1] cords = ['x_1', 'y_1', 'z_1', 'x_2', 'y_2', 'z_2'] for point in cords: if point in crosspoints: return crosspoints if __name__ == '__main__': main('test.txt')
UTF-8
Python
false
false
3,345
py
6
task2.py
4
0.521113
0.508347
0
97
30.505155
83
Alicia1529/ComputerScience
14,267,881,406,749
45a2b31320d52a14c4382ce3c0753920e5f9fa04
77106803619fd019cca5ec2b7744bfd1a70e0fc9
/CodeJam/2019-pre/test3.py
09dcb33583f132eb0ee90396d2039e3e5d92d812
[]
no_license
https://github.com/Alicia1529/ComputerScience
dc18960eeb4f7a4deb2a6b99d33bcf08c1afe583
4529f4cb2797d59684fa68c615c8a0b6525f7004
refs/heads/master
2020-06-28T17:01:05.363189
2019-08-02T20:59:53
2019-08-02T20:59:53
200,290,236
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def foundInit(n,N): for i in range(1,N): if is_prime(i) and is_prime(n//i) and (n//i)*i==n: return i,n//i def is_prime(n): if n == 2 or n == 3: return True if n < 2 or n%2 == 0: return False if n < 9: return True if n%3 == 0: return False r = int(n**0.5) f = 5 while f <= r: if n%f == 0: return False if n%(f+2) == 0: return False f +=6 return True num = input().strip() while num=="": num = input().strip() num = int(num) for i in range(num): line = input().strip() while line=="": line = input().strip() N,L = line.split(" ") N,L = int(N),int(L) line = input().strip() while line=="": line = input().strip() data = line.split(" ") array = [] for j in range(len(data)): if j==0: this,nextOne = foundInit(int(data[j]),N) if (int(data[j+1])//nextOne)*nextOne==int(data[j+1]) and is_prime(int(data[j+1])//nextOne): pass else: this,nextOne = nextOne,this array.append(this) array.append(nextOne) else: array.append(int(data[j])//nextOne) nextOne = int(data[j])//nextOne index = list(set(array)) index.sort() output = [] for j in range(len(array)): idx = index.index(array[j]) letter = chr(65+idx) output.append(letter) string = "Case #"+str(i+1)+":" print(string,"".join(output))
UTF-8
Python
false
false
1,498
py
52
test3.py
46
0.493324
0.477971
0
56
25.732143
103
Donnadonnam/SOEN487-ResoluteLeopards
5,823,975,674,440
c79e22863ade7eef8a81289ba398b028fd7e5658
86eae54c21c850a3c00c7dffa22f2b76c35cc857
/user_api/config.py
22faf3814a7c33eb41c95eeb53a87fe193e55190
[]
no_license
https://github.com/Donnadonnam/SOEN487-ResoluteLeopards
916675735645db319c20e1017871354844abd493
48de7ba82ddcbe3627920e9e435bb05b49845186
refs/heads/master
2023-03-18T15:49:20.944037
2020-03-04T12:38:00
2020-03-04T12:38:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os class Config(object): SQLALCHEMY_DATABASE_URI = r"sqlite:///userdb.sqlite" SQLALCHEMY_TRACK_MODIFICATIONS = False class ProdConfig(Config): pass class DevConfig(Config): KEY_LIST_PATH = os.path.join(os.path.dirname(__file__), "keys/keylist.json") DEBUG = True class TestConfig(Config): TESTING = True KEY_LIST_PATH = os.path.join(os.path.dirname(__file__), "tests/keys/keylist.json") SQLALCHEMY_DATABASE_URI = r"sqlite:///tests/test_userdb.sqlite"
UTF-8
Python
false
false
497
py
76
config.py
45
0.692153
0.692153
0
21
22.714286
86