hexsha
stringlengths
40
40
size
int64
6
782k
ext
stringclasses
7 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
237
max_stars_repo_name
stringlengths
6
72
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
list
max_stars_count
int64
1
53k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
184
max_issues_repo_name
stringlengths
6
72
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
list
max_issues_count
int64
1
27.1k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
184
max_forks_repo_name
stringlengths
6
72
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
list
max_forks_count
int64
1
12.2k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
6
782k
avg_line_length
float64
2.75
664k
max_line_length
int64
5
782k
alphanum_fraction
float64
0
1
4b3991d6634086616a231e164657cd86332b065f
511
py
Python
Curso-Em-Video-Python/2Exercicios/039_Alistamento_Militar.py
pedrohd21/Cursos-Feitos
b223aad83867bfa45ad161d133e33c2c200d42bd
[ "MIT" ]
null
null
null
Curso-Em-Video-Python/2Exercicios/039_Alistamento_Militar.py
pedrohd21/Cursos-Feitos
b223aad83867bfa45ad161d133e33c2c200d42bd
[ "MIT" ]
null
null
null
Curso-Em-Video-Python/2Exercicios/039_Alistamento_Militar.py
pedrohd21/Cursos-Feitos
b223aad83867bfa45ad161d133e33c2c200d42bd
[ "MIT" ]
null
null
null
from datetime import date atual = date.today().year print('ALISTAMENTO MILITAR BRASIL') print('-' * 30) nascimento = int(input('Qual ano voçê nasceu? ')) idade = atual - nascimento if idade < 18: print('Você tem {} anos. Em {} voçe vai ta capacitado a se alistar.'.format(idade, nascimento+18)) elif idade == 18: print('Você tem {} anos. Ja pode se alistar, so se apresentar!!'.format(idade)) else: print('Você tem {} anos. Ja passou a hora de se alistar que era em {}'.format(idade, nascimento+18))
42.583333
104
0.688845
d9aa07a1ad9eebfbf37228d3c16a083c87428778
985
py
Python
2-resources/__DATA-Structures/Code-Challenges/cc71meanMedianMode/solution.py
eengineergz/Lambda
1fe511f7ef550aed998b75c18a432abf6ab41c5f
[ "MIT" ]
null
null
null
2-resources/__DATA-Structures/Code-Challenges/cc71meanMedianMode/solution.py
eengineergz/Lambda
1fe511f7ef550aed998b75c18a432abf6ab41c5f
[ "MIT" ]
null
null
null
2-resources/__DATA-Structures/Code-Challenges/cc71meanMedianMode/solution.py
eengineergz/Lambda
1fe511f7ef550aed998b75c18a432abf6ab41c5f
[ "MIT" ]
null
null
null
# https://youtu.be/r0xWh4QqS9Q # https://piazza.com/class/j63w1pdyopf7kj?cid=83 from functools import reduce from collections import Counter def findMean(numbers): sum = reduce(lambda x, y: x + y, numbers) mean = sum / len(numbers) return mean def findMedian(numbers): numbers.sort() mid = len(numbers) // 2 if len(numbers) % 2 is 0: return findMean([numbers[mid], numbers[mid-1]]) return numbers[mid] # Non-Pythonic solution # def findMode(numbers): # mode = None # mapping = {x: 0 for x in numbers} # greatestFrequency = 0 # for n in numbers: # mapping[n] += 1 # if mapping[n] > greatestFrequency: # greatestFrequency = mapping[n] # mode = n # return mode # Pythonic solution def findMode(numbers): counter = Counter(numbers) return counter.most_common(1)[0][0] def meanMedianMode(numbers): mmm_dict = { 'mean': findMean(numbers), 'median': findMedian(numbers), 'mode': findMode(numbers) } return mmm_dict
22.386364
51
0.670051
8a5c453075a2f22762f63e4da02b6ef663164f45
33,393
py
Python
edu-mail-auto-generator-main/bot.py
Zusyaku/Termux-And-Lali-Linux-V2
b1a1b0841d22d4bf2cc7932b72716d55f070871e
[ "Apache-2.0" ]
2
2021-11-17T03:35:03.000Z
2021-12-08T06:00:31.000Z
edu-mail-auto-generator-main/bot.py
Zusyaku/Termux-And-Lali-Linux-V2
b1a1b0841d22d4bf2cc7932b72716d55f070871e
[ "Apache-2.0" ]
null
null
null
edu-mail-auto-generator-main/bot.py
Zusyaku/Termux-And-Lali-Linux-V2
b1a1b0841d22d4bf2cc7932b72716d55f070871e
[ "Apache-2.0" ]
2
2021-11-05T18:07:48.000Z
2022-02-24T21:25:07.000Z
import time import re import string import random import sys import colorama from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import Select from random import randint from __constants.const import * from __banner.myBanner import bannerTop from __colors__.colors import * ######## This script is only for educational purpose ######## ######## use it on your own RISK ######## ######## I'm not responsible for any loss or damage ######## ######## caused to you using this script ######## def postFix(n): range_start = 10**(n-1) range_end = (10**n)-1 return randint(range_start, range_end) def random_phone_num_generator(): first = str(random.choice(country_codes)) second = str(random.randint(1, 888)).zfill(3) last = (str(random.randint(1, 9998)).zfill(4)) while last in ['1111', '2222', '3333', '4444', '5555', '6666', '7777', '8888']: last = (str(random.randint(1, 9998)).zfill(4)) return '{}-{}-{}'.format(first, second, last) def start_bot(start_url, email, college, collegeID): studentPhone = random_phone_num_generator() ex_split = studentAddress.split("\n") streetAddress = ex_split[0] if(re.compile(',').search(ex_split[1]) != None): ex_split1 = ex_split[1].split(', ') cityAddress = ex_split1[0] ex_split2 = ex_split1[1].split(' ') stateAddress = ex_split2[0] postalCode = ex_split2[1] else: ex_split3 = ex_split[1].split(' ') cityAddress = ex_split3[0] stateAddress = ex_split3[1] postalCode = ex_split3[2] random.seed() letters = string.ascii_uppercase middleName = random.choice(letters) fp = open('prefBrowser.txt', 'r') typex = fp.read() try: # For Chrome if typex == 'chrome': driver = webdriver.Chrome(executable_path=r'./webdriver/chromedriver') # For Firefox elif typex == 'firefox': # cap = DesiredCapabilities().FIREFOX # cap['marionette'] = True driver = webdriver.Firefox(executable_path=r'./webdriver/geckodriver') elif typex == '': print(fr + 'Error - Run setup.py first') exit() except Exception as e: time.sleep(0.4) print('\n' + fr + 'Error - '+ str(e)) exit() driver.maximize_window() driver.get(start_url) time.sleep(1) driver.find_element_by_xpath('//*[@id="portletContent_u16l1n18"]/div/div[2]/div/a[2]').click() time.sleep(1) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.ID, "accountFormSubmit")) ).click() print(fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fy + 'Account Progress - 1/3', end='') WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.ID, "inputFirstName")) ).send_keys(firstName) time.sleep(0.7) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.ID, "inputMiddleName")) ).send_keys(middleName) time.sleep(0.7) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.ID, "inputLastName")) ).send_keys(LastName) time.sleep(0.7) driver.find_element_by_xpath('//*[@id="hasOtherNameNo"]').click() driver.find_element_by_xpath('//*[@id="hasPreferredNameNo"]').click() time.sleep(0.7) WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#inputBirthDateMonth option[value="' + str(randomMonth) + '"]')) ).click() time.sleep(0.7) WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#inputBirthDateDay option[value="' + str(randomDay) + '"]')) ).click() time.sleep(0.7) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.ID, 'inputBirthDateYear')) ).send_keys(randomYear) time.sleep(0.7) WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#inputBirthDateMonthConfirm option[value="' + str(randomMonth) + '"]')) ).click() time.sleep(0.7) WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#inputBirthDateDayConfirm option[value="' + str(randomDay) + '"]')) ).click() time.sleep(0.7) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.ID, 'inputBirthDateYearConfirm')) ).send_keys(randomYear) time.sleep(0.7) WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.ID, '-have-ssn-no')) ).click() time.sleep(4) element = driver.find_element_by_id('accountFormSubmit') desired_y = (element.size['height'] / 2) + element.location['y'] window_h = driver.execute_script('return window.innerHeight') window_y = driver.execute_script('return window.pageYOffset') current_y = (window_h / 2) + window_y scroll_y_by = desired_y - current_y driver.execute_script("window.scrollBy(0, arguments[0]);", scroll_y_by) time.sleep(1) element.click() print(fg + ' (Success)') print(fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fy + 'Account Progress - 2/3', end='') time.sleep(0.7) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.ID, 'inputEmail')) ).send_keys(email) time.sleep(0.7) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.ID, 'inputEmailConfirm')) ).send_keys(email) time.sleep(0.7) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.ID, 'inputSmsPhone')) ).send_keys(studentPhone) time.sleep(0.7) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.ID, 'inputStreetAddress1')) ).send_keys(streetAddress) time.sleep(0.7) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.ID, 'inputCity')) ).send_keys(cityAddress) time.sleep(0.7) WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#inputState option[value="' + stateAddress + '"]')) ).click() time.sleep(0.7) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.ID, 'inputPostalCode')) ).send_keys(postalCode) time.sleep(2) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.ID, 'accountFormSubmit')) ).click() # driver.find_element_by_xpath('//*[@id="accountFormSubmit"]').click() try: time.sleep(1) driver.find_element_by_xpath('//*[@id="messageFooterLabel"]').click() opError = True while opError != False: chkInputPhone = driver.find_element_by_id('inputSmsPhone') chkError = chkInputPhone.get_attribute('class') if chkError == 'portlet-form-input-field error': print('\n' + fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fr + 'Invalid Number, Retrying....') chkInputPhone.clear() studentPhone = random_phone_num_generator() chkInputPhone.send_keys(studentPhone) time.sleep(0.4) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.ID, 'inputAlternatePhone_auth_txt')) ).click() try: time.sleep(2) WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.XPATH, '//*[@id="messageFooterLabel"]')) ).click() except: opError = False else: opError = False break except Exception as e: print(e) time.sleep(4) WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, 'accountFormSubmit')) ).click() try: time.sleep(1) WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, 'messageFooterLabel')) ).click() time.sleep(0.7) WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.ID, 'inputAddressValidationOverride')) ).click() time.sleep(2) WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, 'accountFormSubmit')) ).click() except: pass print(fg + ' (Success)') userName = firstName + str(postFix(7)) pwd = LastName + str(postFix(5)) pin = postFix(4) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.ID, 'inputUserId')) ).send_keys(userName) time.sleep(0.7) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.ID, 'inputPasswd')) ).send_keys(pwd) time.sleep(0.7) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.ID, 'inputPasswdConfirm')) ).send_keys(pwd) time.sleep(0.7) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.ID, 'inputPin')) ).send_keys(pin) time.sleep(0.7) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.ID, 'inputPinConfirm')) ).send_keys(pin) time.sleep(0.7) ######### Question 1 ######### WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#inputSecurityQuestion1 option[value="5"]')) ).click() time.sleep(1) random.seed(10) letters = string.ascii_lowercase sec_ans1 = LastName + ''.join(random.choices(letters,k=4)) sec_ans2 = LastName + ''.join(random.choices(letters,k=4)) sec_ans3 = LastName + ''.join(random.choices(letters,k=4)) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.ID, 'inputSecurityAnswer1')) ).send_keys(sec_ans1) time.sleep(1) ######### Question 2 ######### WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#inputSecurityQuestion2 option[value="6"]')) ).click() time.sleep(1) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.ID, 'inputSecurityAnswer2')) ).send_keys(sec_ans2) time.sleep(1) ######### Question 3 ######### WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#inputSecurityQuestion3 option[value="7"]')) ).click() time.sleep(1) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.ID, 'inputSecurityAnswer3')) ).send_keys(sec_ans3) print(fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fr + 'Please fill the captcha in webdriver to proceed further') for d in range(1, 200): xx = driver.find_element_by_name('captchaResponse') tdt = xx.get_attribute('value') if tdt != '': print(fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fg + 'Captcha Solved, Executing Further') solved = 1 break else: time.sleep(2) solved = 0 if solved == 1: time.sleep(2) element = driver.find_element_by_id('accountFormSubmit') desired_y = (element.size['height'] / 2) + element.location['y'] window_h = driver.execute_script('return window.innerHeight') window_y = driver.execute_script('return window.pageYOffset') current_y = (window_h / 2) + window_y scroll_y_by = desired_y - current_y driver.execute_script("window.scrollBy(0, arguments[0]);", scroll_y_by) time.sleep(1) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.ID, "accountFormSubmit")) ).click() print(fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fy + 'Account Progress - 3/3' + fg + ' (Success)') fp = open('myccAcc.txt', 'a') birthDay = str(randomMonth) + '/' + str(randomDay) + '/' + str(randomYear) fp.write('Email - ' + email + ' Password - ' + pwd + ' UserName - ' + userName + ' First Name - ' + firstName + ' Middle Name - ' + middleName + ' Last Name - ' + LastName + ' College - ' + college + ' Pin - ' + str(pin) + ' Birthday - ' + birthDay +'\n\n') fp.close() print(fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fg + 'Account Created Successfully, Details saved in myccAcc.txt, Filling Application Form Now') time.sleep(1) WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.XPATH, '//*[@id="registrationSuccess"]/main/div[2]/div/div/button')) ).click() time.sleep(0.7) print(fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fy + 'Details Progress - 1/8', end='') WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.NAME, 'application.termId')) ) dropdown_menu = Select(driver.find_element_by_name('application.termId')) dropdown_menu.select_by_index(1) time.sleep(0.7) WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#inputEduGoal option[value="B"]')) ).click() time.sleep(2) dropdown_menu = Select(driver.find_element_by_id('inputMajorId')) dropdown_menu.select_by_index(random.randint(1, 7)) time.sleep(2.5) WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.NAME, '_eventId_continue')) ).click() print(fg + ' (Success)') WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.ID, 'inputAddressSame')) ).click() time.sleep(2.5) WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.XPATH, '//*[@id="column2"]/div[6]/ol/li[2]/button')) ).click() # Page 2 dropdown_menu = Select(driver.find_element_by_name('appEducation.enrollmentStatus')) dropdown_menu.select_by_index(1) time.sleep(0.7) WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#inputHsEduLevel option[value="4"]')) ).click() time.sleep(0.7) rndPassYear = [3, 4] WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#inputHsCompMM option[value="' + str(random.choice(rndPassYear)) + '"]')) ).click() time.sleep(0.7) WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#inputHsCompDD option[value="' + str(randomEduDay) + '"]')) ).click() time.sleep(0.7) WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.ID, 'inputHsCompYYYY')) ).send_keys(randomEduYear) time.sleep(1) WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.ID, 'inputCaHsGradYes')) ).click() time.sleep(1) WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.ID, 'inputCaHs3yearNo')) ).click() time.sleep(0.7) # WebDriverWait(driver, 60).until( # EC.element_to_be_clickable((By.ID, 'inputHsAttendance')) # ).click() WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#inputHsAttendance option[value="1"]')) ).click() time.sleep(0.7) bad_states = ['AA', 'AE', 'AP'] if stateAddress in bad_states: stateAddress = 'CA' WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#hs-input-sf-state option[value="' + stateAddress + '"]')) ).click() search = driver.find_element_by_id('hs-school-name') search.clear() search.send_keys('high') auto_complete = WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.ID, 'hs-suggestions')) ) time.sleep(2) parentElement = driver.find_element_by_class_name('autocomplete-menu') it = parentElement.find_elements_by_tag_name("li") if len(it) < 5: print(fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fr + 'Changing State....') Select(driver.find_element_by_id('hs-input-sf-state')).select_by_value('CA') search.clear() search.send_keys('high', Keys.ENTER) auto_complete = WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.ID, 'hs-suggestions')) ) time.sleep(2) parentElement = driver.find_element_by_class_name('autocomplete-menu') it = parentElement.find_elements_by_tag_name("li") if len(it) > 5: print(fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fy + 'State Changed, Resuming') try: time.sleep(1) it[random.randint(4, 8)].click() except Exception as e: print(fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fr + str(e), 'can\'t click') time.sleep(0.4) WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.ID, 'inputGPA')) ).send_keys(Keys.BACKSPACE, '400') time.sleep(0.4) WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#inputHighestEnglishCourse option[value="4"]')) ).click() time.sleep(0.7) WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#inputHighestEnglishGrade option[value="A"]')) ).click() time.sleep(0.7) WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#inputHighestMathCourseTaken option[value="7"]')) ).click() time.sleep(0.7) WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#inputHighestMathTakenGrade option[value="A"]')) ).click() time.sleep(4) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.XPATH, '//*[@id="column2"]/div[14]/ol/li[2]/button')) ).click() print(fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fy + 'Details Progress - 2/8' + fg + ' (Success)') print(fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fy + 'Details Progress - 3/8', end='') # Military time.sleep(4) WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#inputCitizenshipStatus option[value="1"]')) ).click() time.sleep(1) WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#inputMilitaryStatus option[value="1"]')) ).click() time.sleep(1) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.XPATH, '//*[@id="column2"]/div[6]/ol/li[2]/button')) ).click() print(fg + ' (Success)') print(fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fy + 'Details Progress - 4/8', end='') # Residency WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.ID, 'inputCaRes2YearsYes')) ).click() time.sleep(1) WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.ID, 'inputHomelessYouthNo')) ).click() time.sleep(1) WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.ID, 'inputIsEverInFosterCareNo')) ).click() time.sleep(4) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.XPATH, '//*[@id="column2"]/div[7]/ol/li[2]/button')) ).click() # driver.find_element_by_xpath('//*[@id="column2"]/div[7]/ol/li[2]/button').click() print(fg + ' (Success)') print(fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fy + 'Details Progress - 5/8', end='') # Intersts WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.ID, 'inputEnglishYes')) ).click() time.sleep(2) WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.ID, 'inputFinAidInfoNo')) ).click() time.sleep(1) WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.ID, 'inputAssistanceNo')) ).click() time.sleep(1) WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.ID, 'inputAthleticInterest1')) ).click() time.sleep(1) parentElement = driver.find_elements_by_class_name('ccc-form-layout')[5] element = parentElement desired_y = (element.size['height'] / 2) + element.location['y'] window_h = driver.execute_script('return window.innerHeight') window_y = driver.execute_script('return window.pageYOffset') current_y = (window_h / 2) + window_y scroll_y_by = desired_y - current_y driver.execute_script("window.scrollBy(0, arguments[0]);", scroll_y_by) allElements = parentElement.find_elements_by_tag_name('li') rndList = [2, 1, 2, 2] occurance = 0 inputChecked = False while occurance < 2: for elementxx in allElements: myRandom = random.choice(rndList) time.sleep(0.4) xx = elementxx.find_element_by_class_name('portlet-form-input-checkbox') if xx.get_attribute('id') == 'inputOnlineClasses' and inputChecked == False: myRandom = 1 inputChecked = True if myRandom == 1: occurance += 1 element = xx desired_y = (element.size['height'] / 2) + element.location['y'] window_h = driver.execute_script('return window.innerHeight') window_y = driver.execute_script('return window.pageYOffset') current_y = (window_h / 2) + window_y scroll_y_by = desired_y - current_y driver.execute_script("window.scrollBy(0, arguments[0]);", scroll_y_by) time.sleep(0.4) xx.click() time.sleep(2) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.XPATH, '//*[@id="column2"]/div[9]/ol/li[2]/button')) ).click() # driver.find_element_by_xpath('//*[@id="column2"]/div[9]/ol/li[2]/button').click() print(fg + ' (Success)') print(fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fy + 'Details Progress - 6/8', end='') # Demographic time.sleep(4) WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#inputGender option[value="Male"]')) ).click() time.sleep(1) WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#inputTransgender option[value="No"]')) ).click() time.sleep(1) WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#inputOrientation option[value="StraightHetrosexual"]')) ).click() time.sleep(1) WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#inputParentGuardianEdu1 option[value="6"]')) ).click() time.sleep(1) WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#inputParentGuardianEdu2 option[value="2"]')) ).click() time.sleep(1) WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.ID, 'inputHispanicNo')) ).click() time.sleep(1) WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.ID, 'inputRaceEthnicity800')) ).click() WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.ID, 'inputRaceEthnicity' + str(random.randint(801, 809)))) ).click() time.sleep(4) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.XPATH, '//*[@id="column2"]/div[7]/ol/li[2]/button')) ).click() # driver.find_element_by_xpath('//*[@id="column2"]/div[7]/ol/li[2]/button').click() print(fg + ' (Success)') print(fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fy + 'Details Progress - 7/8', end='') # Supplemental if collegeID == 1: WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#_supp_MENU_1 option[value="AAAS"]')) ).click() time.sleep(0.7) WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#_supp_MENU_2 option[value="HS"]')) ).click() time.sleep(0.7) WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#_supp_MENU_3 option[value="6"]')) ).click() time.sleep(0.7) WebDriverWait(driver, 60).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, '#_supp_MENU_4 option[value="H"]')) ).click() time.sleep(0.7) WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.ID, 'YESNO_1_no')) ).click() time.sleep(4) WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.XPATH, '//*[@id="applyForm"]/main/div[3]/div[5]/ol/li[2]/button')) ).click() # driver.find_element_by_xpath('//*[@id="applyForm"]/main/div[3]/div[5]/ol/li[2]/button').click() elif collegeID == 2: pass elif collegeID == 3: try: element = WebDriverWait(driver, 60).until( EC.presence_of_element_located((By.ID, "_supp_MENU_1")) ) except: pass Select(driver.find_element_by_id("_supp_MENU_1")).select_by_value('ENG') time.sleep(2) Select(driver.find_element_by_id("_supp_MENU_5")).select_by_value('N') Select(driver.find_element_by_id("_supp_MENU_6")).select_by_value('N') Select(driver.find_element_by_id("_supp_MENU_4")).select_by_value('OPT2') driver.find_element_by_id("_supp_CHECK_5").click() time.sleep(2) driver.find_element_by_name("_eventId_continue").click() elif collegeID == 4: time.sleep(2) driver.find_element_by_id("YESNO_1_yes").click() driver.find_element_by_id("YESNO_2_yes").click() time.sleep(2) driver.find_element_by_id("_supp_TEXT_1").send_keys(studentPhone.replace('-', '')) time.sleep(2) GPA = Select(driver.find_element_by_id('_supp_MENU_2')) GPA.select_by_value('4') time.sleep(2) units = Select(driver.find_element_by_id('_supp_MENU_8')) units.select_by_value('4') time.sleep(2) money = Select(driver.find_element_by_id('_supp_MENU_3')) money.select_by_value('30') time.sleep(2) house = Select(driver.find_element_by_id('_supp_MENU_4')) house.select_by_value('1') time.sleep(2) house = Select(driver.find_element_by_id('_supp_MENU_5')) house.select_by_value('B') time.sleep(2) driver.find_element_by_id("YESNO_4_yes").click() driver.find_element_by_id("YESNO_5_yes").click() time.sleep(2) driver.find_element_by_id("YESNO_6_yes").click() driver.find_element_by_id("YESNO_7_no").click() time.sleep(2) driver.find_element_by_id("YESNO_8_yes").click() driver.find_element_by_id("YESNO_9_no").click() driver.find_element_by_id("YESNO_10_no").click() time.sleep(1) driver.find_element_by_id("YESNO_11_yes").click() time.sleep(1) driver.find_element_by_id("YESNO_12_no").click() time.sleep(2) driver.find_element_by_id("YESNO_13_no").click() driver.find_element_by_id("YESNO_14_yes").click() question = Select(driver.find_element_by_id('_supp_MENU_6')) question.select_by_value('What school did you attend for sixth grade?') time.sleep(2) question = Select(driver.find_element_by_id('_supp_MENU_7')) question.select_by_value( 'What is the first name of your least favorite relative?') time.sleep(1) driver.find_element_by_id("_supp_TEXT_3").send_keys("Nulled") driver.find_element_by_id("_supp_TEXT_4").send_keys("Nulled") time.sleep(2) driver.find_element_by_name("_eventId_continue").click() print(fg + ' (Success)') print(fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fy + 'Details Progress - 8/8', end='') # Submission WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.ID, 'inputConsentYes')) ).click() time.sleep(1) WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.ID, 'inputESignature')) ).click() time.sleep(1) WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.ID, 'inputFinancialAidAck')) ).click() time.sleep(1) print(fg + ' (Success)') print(fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fy + 'Sleeping for 30 seconds, HOLD ON !!') time.sleep(30) element = driver.find_element_by_xpath('//*[@id="submit-application-button"]') desired_y = (element.size['height'] / 2) + element.location['y'] window_h = driver.execute_script('return window.innerHeight') window_y = driver.execute_script('return window.pageYOffset') current_y = (window_h / 2) + window_y scroll_y_by = desired_y - current_y driver.execute_script("window.scrollBy(0, arguments[0]);", scroll_y_by) time.sleep(1) # driver.find_element_by_xpath('//*[@id="submit-application-button"]').click() element.click() time.sleep(2) confirmedText = driver.find_element_by_class_name('mypath-confirmation-text').text print(fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fg + confirmedText) driver.close() else: print(fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fr + 'Timeout while Checking for captcha') def main(): sys.stdout.write(bannerTop()) print(fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fg + 'Select a college from all available colleges to proceed....\n') time.sleep(0.4) bad_colors = ['BLACK', 'WHITE', 'LIGHTBLACK_EX', 'RESET'] codes = vars(colorama.Fore) colors = [codes[color] for color in codes if color not in bad_colors] for index, college in enumerate(allColleges): print(fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fy + str(index + 1) + ' - ' + random.choice(colors) + college) isIDError = True while isIDError != False: print('\n' + fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fg + 'Enter college id for ex - 1 or 2 or 3.... : ', end='') userInput = int(input()) if userInput > len(allColleges) or userInput < 1: print(fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fr + 'Wrong College id') else: userInput = userInput - 1 isIDError = False time.sleep(0.4) print('\n' + fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fg + 'Selected College: ' + fy + allColleges[userInput]) time.sleep(0.4) print('\n' + fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fg + 'Enter Your Email: ', end='') userEmail = input() time.sleep(0.4) print('\n' + fc + sd + '[' + fm + sb + '*' + fc + sd + '] ' + fg + 'Hold on Starting now, Keep checking this terminal for instructions') time.sleep(1) reg_url = start_url + clg_ids[userInput] start_bot(reg_url, userEmail, allColleges[userInput], userInput + 1) if __name__ == '__main__': main()
32.139557
265
0.575929
8abddef59adc2efe22b6dfd5d8ec1e2909d89aa3
1,198
pyde
Python
sketches/globe03/globe03.pyde
kantel/processingpy
74aae222e46f68d1c8f06307aaede3cdae65c8ec
[ "MIT" ]
4
2018-06-03T02:11:46.000Z
2021-08-18T19:55:15.000Z
sketches/globe03/globe03.pyde
kantel/processingpy
74aae222e46f68d1c8f06307aaede3cdae65c8ec
[ "MIT" ]
null
null
null
sketches/globe03/globe03.pyde
kantel/processingpy
74aae222e46f68d1c8f06307aaede3cdae65c8ec
[ "MIT" ]
3
2019-12-23T19:12:51.000Z
2021-04-30T14:00:31.000Z
a = 0.0 def setup(): global globe size(400, 400, P3D) world = loadImage("bluemarble01.jpg") globe = makeSphere(150, 5, world) frameRate(30) def draw(): global globe, a background(0) translate(width/2, height/2) lights() with pushMatrix(): rotateX(radians(-25)) rotateY(a) a += 0.01 shape(globe) def makeSphere(r, step, tex): s = createShape() s.beginShape(QUAD_STRIP) s.texture(tex) s.noStroke() i = 0 while i < 180: sini = sin(radians(i)) cosi = cos(radians(i)) sinip = sin(radians(i + step)) cosip = cos(radians(i + step)) j = 0 while j <= 360: sinj = sin(radians(j)) cosj = cos(radians(j)) s.normal(cosj*sini, -cosi, sinj*sini) s.vertex(r*cosj*sini, r*-cosi, r*sinj*sini, tex.width-j*tex.width/360.0, i*tex.height/180.0) s.normal(cosj*sinip, -cosip, sinj*sinip) s.vertex(r*cosj*sinip, r*-cosip, r*sinj*sinip, tex.width-j*tex.width/360.0, (i+step)*tex.height/180.0) j += step i += step s.endShape() return s
26.622222
76
0.521703
0a2c8b7cc8fe80c6ff9e803ac21d550be63a833e
1,177
py
Python
movie/migrations/0001_initial.py
StevenMedina/MovieAPI
805e79d396e197383bce6095febf0252231a1018
[ "MIT" ]
null
null
null
movie/migrations/0001_initial.py
StevenMedina/MovieAPI
805e79d396e197383bce6095febf0252231a1018
[ "MIT" ]
null
null
null
movie/migrations/0001_initial.py
StevenMedina/MovieAPI
805e79d396e197383bce6095febf0252231a1018
[ "MIT" ]
null
null
null
# Generated by Django 2.2.2 on 2019-07-13 16:46 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Movie', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=256, unique=True, verbose_name='nombre')), ('description', models.TextField(max_length=300, verbose_name='descripción')), ('summary', models.TextField(max_length=500, verbose_name='resumen')), ('created_at', models.DateTimeField(auto_now=True, verbose_name='fecha de creación')), ('is_recommended', models.BooleanField(default=False, verbose_name='es recomendada')), ('is_active', models.BooleanField(default=False, verbose_name='activa')), ], options={ 'verbose_name': 'película', 'verbose_name_plural': 'películas', 'ordering': ['-created_at'], }, ), ]
36.78125
114
0.585387
0a5e5f501b6b958ec33375a0e46f1d246c94a7bd
155
py
Python
exercises/zh/solution_03_03.py
tuanducdesign/spacy-course
f8d092c5fa2997fccb3f367d174dce8667932b3d
[ "MIT" ]
2
2020-07-07T01:46:37.000Z
2021-04-20T03:19:43.000Z
exercises/zh/solution_03_03.py
tuanducdesign/spacy-course
f8d092c5fa2997fccb3f367d174dce8667932b3d
[ "MIT" ]
null
null
null
exercises/zh/solution_03_03.py
tuanducdesign/spacy-course
f8d092c5fa2997fccb3f367d174dce8667932b3d
[ "MIT" ]
null
null
null
import spacy # 读取zh_core_web_sm流程 nlp = spacy.load("zh_core_web_sm") # 打印流程组件的名字 print(nlp.pipe_names) # 打印完整流程的(name, component)元组 print(nlp.pipeline)
14.090909
34
0.774194
0ae0b85854555e8b12b26d942780073890f3a8ba
4,890
py
Python
src/bo4e/com/tarifberechnungsparameter.py
bo4e/BO4E-python
28b12f853c8a496d14b133759b7aa2d6661f79a0
[ "MIT" ]
1
2022-03-02T12:49:44.000Z
2022-03-02T12:49:44.000Z
src/bo4e/com/tarifberechnungsparameter.py
bo4e/BO4E-python
28b12f853c8a496d14b133759b7aa2d6661f79a0
[ "MIT" ]
21
2022-02-04T07:38:46.000Z
2022-03-28T14:01:53.000Z
src/bo4e/com/tarifberechnungsparameter.py
bo4e/BO4E-python
28b12f853c8a496d14b133759b7aa2d6661f79a0
[ "MIT" ]
null
null
null
""" Contains Tarifberechnungsparameter class and corresponding marshmallow schema for de-/serialization """ from decimal import Decimal from typing import List, Optional import attr from marshmallow import fields from marshmallow_enum import EnumField # type:ignore[import] from bo4e.com.com import COM, COMSchema from bo4e.com.preis import Preis, PreisSchema from bo4e.com.tarifpreis import Tarifpreis, TarifpreisSchema from bo4e.enum.messpreistyp import Messpreistyp from bo4e.enum.tarifkalkulationsmethode import Tarifkalkulationsmethode # yes. there is no description in the official docs. # https://github.com/Hochfrequenz/BO4E-python/issues/328 # pylint: disable=too-few-public-methods, empty-docstring, too-many-instance-attributes @attr.s(auto_attribs=True, kw_only=True) class Tarifberechnungsparameter(COM): """ .. HINT:: `Tarifberechnungsparameter JSON Schema <https://json-schema.app/view/%23?url=https://raw.githubusercontent.com/Hochfrequenz/BO4E-python/main/json_schemas/com/TarifberechnungsparameterSchema.json>`_ """ # there are no required attributes # optional attributes #: Gibt an, wie die Einzelpreise des Tarifes zu verarbeiten sind berechnungsmethode: Optional[Tarifkalkulationsmethode] = attr.ib( default=None, validator=attr.validators.optional(attr.validators.instance_of(Tarifkalkulationsmethode)) ) #: True, falls der Messpreis im Grundpreis (GP) enthalten ist messpreis_in_gp_enthalten: Optional[bool] = attr.ib( default=None, validator=attr.validators.optional(attr.validators.instance_of(bool)) ) messpreis_beruecksichtigen: Optional[bool] = attr.ib( default=None, validator=attr.validators.optional(attr.validators.instance_of(bool)) ) """ True, falls bei der Bildung des Durchschnittspreises für die Höchst- und Mindestpreisbetrachtung der Messpreis mit berücksichtigt wird """ #: Typ des Messpreises messpreistyp: Optional[Messpreistyp] = attr.ib( default=None, validator=attr.validators.optional(attr.validators.instance_of(Messpreistyp)) ) #: Im Preis bereits eingeschlossene Leistung (für Gas) kw_inklusive: Optional[Decimal] = attr.ib( default=None, validator=attr.validators.optional(attr.validators.instance_of(Decimal)) ) # todo: type decimal is most likely wrong: https://github.com/Hochfrequenz/BO4E-python/issues/327 #: Intervall, indem die über "kwInklusive" hinaus abgenommene Leistung kostenpflichtig wird (z.B. je 5 kW 20 EURO) kw_weitere_mengen: Optional[Decimal] = attr.ib( default=None, validator=attr.validators.optional(attr.validators.instance_of(Decimal)) ) # todo: type decimal is most likely wrong: https://github.com/Hochfrequenz/BO4E-python/issues/327 #: Höchstpreis für den Durchschnitts-Arbeitspreis NT hoechstpreis_n_t: Optional[Preis] = attr.ib( default=None, validator=attr.validators.optional(attr.validators.instance_of(Preis)) ) #: Höchstpreis für den Durchschnitts-Arbeitspreis HT hoechstpreis_h_t: Optional[Preis] = attr.ib( default=None, validator=attr.validators.optional(attr.validators.instance_of(Preis)) ) #: Mindestpreis für den Durchschnitts-Arbeitspreis mindestpreis: Optional[Preis] = attr.ib( default=None, validator=attr.validators.optional(attr.validators.instance_of(Preis)) ) #: Liste mit zusätzlichen Preisen, beispielsweise Messpreise und/oder Leistungspreise zusatzpreise: Optional[List[Tarifpreis]] = attr.ib( default=None, validator=attr.validators.optional( attr.validators.deep_iterable( member_validator=attr.validators.instance_of(Tarifpreis), iterable_validator=attr.validators.instance_of(list), ) ), ) class TarifberechnungsparameterSchema(COMSchema): """ Schema for de-/serialization of Tarifberechnungsparameter """ class_name = Tarifberechnungsparameter # optional attributes berechnungsmethode = EnumField(Tarifkalkulationsmethode, allow_none=True) messpreis_in_gp_enthalten = fields.Bool(allow_none=True, data_key="messpreisInGpEnthalten") messpreis_beruecksichtigen = fields.Bool(allow_none=True, data_key="messpreisBeruecksichtigen") messpreistyp = EnumField(Messpreistyp, allow_none=True) kw_inklusive = fields.Decimal(as_string=True, allow_none=True, data_key="kwInklusive") kw_weitere_mengen = fields.Decimal(as_string=True, allow_none=True, data_key="kwWeitereMengen") hoechstpreis_n_t = fields.Nested(PreisSchema, data_key="hoechstpreisHT", allow_none=True) hoechstpreis_h_t = fields.Nested(PreisSchema, data_key="hoechstpreisNT", allow_none=True) mindestpreis = fields.Nested(PreisSchema, allow_none=True) zusatzpreise = fields.List(fields.Nested(TarifpreisSchema), allow_none=True)
44.862385
205
0.75501
7c415154b7e8446e9f7f436bba49ecf1b8b216d9
7,987
py
Python
research/cv/vnet/src/data_manager.py
leelige/mindspore
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
[ "Apache-2.0" ]
77
2021-10-15T08:32:37.000Z
2022-03-30T13:09:11.000Z
research/cv/vnet/src/data_manager.py
leelige/mindspore
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
[ "Apache-2.0" ]
3
2021-10-30T14:44:57.000Z
2022-02-14T06:57:57.000Z
research/cv/vnet/src/data_manager.py
leelige/mindspore
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
[ "Apache-2.0" ]
24
2021-10-15T08:32:45.000Z
2022-03-24T18:45:20.000Z
# Copyright 2021 Huawei Technologies Co., Ltd # # 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. # ============================================================================ """convert CT images to numpy data""" import os import numpy as np import SimpleITK as sitk class DataManager(): """MR image manager module""" def __init__(self, imagelist, data_folder, parameters): self.imagelist = imagelist self.imageFolder = os.path.join(data_folder, 'img') self.GTFolder = os.path.join(data_folder, 'gt') self.params = parameters def createImageFileList(self): self.imageFileList = np.genfromtxt(self.imagelist, dtype=str) self.imageFileList.sort() def createGTFileList(self): self.GTFileList = [f.split('.')[0]+'_segmentation.mhd' for f in self.imageFileList] self.GTFileList.sort() def loadImages(self): self.sitkImages = dict() rescalFilt = sitk.RescaleIntensityImageFilter() rescalFilt.SetOutputMaximum(1) rescalFilt.SetOutputMinimum(0) for f in self.imageFileList: img_id = f.split('.')[0] self.sitkImages[img_id] = rescalFilt.Execute(sitk.Cast( sitk.ReadImage(os.path.join(self.imageFolder, f)), sitk.sitkFloat32)) def loadGT(self): self.sitkGT = dict() for f in self.GTFileList: img_id = f.split('.')[0] self.sitkGT[img_id] = sitk.Cast(sitk.ReadImage(os.path.join(self.GTFolder, f)) > 0.5, sitk.sitkFloat32) def loadTrainingData(self): self.createImageFileList() self.createGTFileList() self.loadImages() self.loadGT() def loadTestingData(self): self.createImageFileList() self.createGTFileList() self.loadImages() self.loadGT() def loadInferData(self): self.createImageFileList() self.loadImages() def getNumpyImages(self): dat = self.getNumpyData(self.sitkImages, sitk.sitkLinear) for key in dat: mean = np.mean(dat[key][dat[key] > 0]) std = np.std(dat[key][dat[key] > 0]) dat[key] -= mean dat[key] /= std return dat def getNumpyGT(self): dat = self.getNumpyData(self.sitkGT, sitk.sitkLinear) for key in dat: dat[key] = (dat[key] > 0.5).astype(dtype=np.float32) return dat def getNumpyData(self, dat, method): """get numpy data from MR images""" ret = dict() for key in dat: ret[key] = np.zeros([self.params['VolSize'][0], self.params['VolSize'][1], self.params['VolSize'][2]], dtype=np.float32) img = dat[key] factor = np.asarray(img.GetSpacing()) / [self.params['dstRes'][0], self.params['dstRes'][1], self.params['dstRes'][2]] factorSize = np.asarray(img.GetSize() * factor, dtype=float) newSize = np.max([factorSize, self.params['VolSize']], axis=0) newSize = newSize.astype(dtype='int') T = sitk.AffineTransform(3) T.SetMatrix(img.GetDirection()) resampler = sitk.ResampleImageFilter() resampler.SetReferenceImage(img) resampler.SetOutputSpacing([self.params['dstRes'][0], self.params['dstRes'][1], self.params['dstRes'][2]]) resampler.SetSize(newSize.tolist()) resampler.SetInterpolator(method) if self.params['normDir']: resampler.SetTransform(T.GetInverse()) imgResampled = resampler.Execute(img) imgCentroid = np.asarray(newSize, dtype=float) / 2.0 imgStartPx = (imgCentroid - np.array(self.params['VolSize']) / 2.0).astype(dtype='int') regionExtractor = sitk.RegionOfInterestImageFilter() size_2_set = np.array(self.params['VolSize']).astype(dtype='int') regionExtractor.SetSize(size_2_set.tolist()) regionExtractor.SetIndex(imgStartPx.tolist()) imgResampledCropped = regionExtractor.Execute(imgResampled) ret[key] = np.transpose(sitk.GetArrayFromImage(imgResampledCropped).astype(dtype=float), [2, 1, 0]) return ret def writeResultsFromNumpyLabel(self, result, key, resultTag, ext): """get MR images from numpy data""" img = self.sitkImages[key] resultDir = self.params['dirPredictionImage'] if not os.path.exists(resultDir): os.makedirs(resultDir, exist_ok=True) print("original img shape{}".format(img.GetSize())) toWrite = sitk.Image(img.GetSize()[0], img.GetSize()[1], img.GetSize()[2], sitk.sitkFloat32) factor = np.asarray(img.GetSpacing()) / [self.params['dstRes'][0], self.params['dstRes'][1], self.params['dstRes'][2]] factorSize = np.asarray(img.GetSize() * factor, dtype=float) newSize = np.max([factorSize, np.array(self.params['VolSize'])], axis=0) newSize = newSize.astype(dtype=int) T = sitk.AffineTransform(3) T.SetMatrix(img.GetDirection()) resampler = sitk.ResampleImageFilter() resampler.SetReferenceImage(img) resampler.SetOutputSpacing([self.params['dstRes'][0], self.params['dstRes'][1], self.params['dstRes'][2]]) resampler.SetSize(newSize.tolist()) resampler.SetInterpolator(sitk.sitkNearestNeighbor) if self.params['normDir']: resampler.SetTransform(T.GetInverse()) toWrite = resampler.Execute(toWrite) imgCentroid = np.asarray(newSize, dtype=float) / 2.0 imgStartPx = (imgCentroid - np.array(self.params['VolSize']) / 2.0).astype(dtype=int) for dstX, srcX in zip(range(0, result.shape[0]), range(imgStartPx[0], int(imgStartPx[0] + self.params['VolSize'][0]))): for dstY, srcY in zip(range(0, result.shape[1]), range(imgStartPx[1], int(imgStartPx[1]+self.params['VolSize'][1]))): for dstZ, srcZ in zip(range(0, result.shape[2]), range(imgStartPx[2], int(imgStartPx[2]+self.params['VolSize'][2]))): toWrite.SetPixel(int(srcX), int(srcY), int(srcZ), float(result[dstX, dstY, dstZ])) resampler.SetOutputSpacing([img.GetSpacing()[0], img.GetSpacing()[1], img.GetSpacing()[2]]) resampler.SetSize(img.GetSize()) if self.params['normDir']: resampler.SetTransform(T) toWrite = resampler.Execute(toWrite) thfilter = sitk.BinaryThresholdImageFilter() thfilter.SetInsideValue(1) thfilter.SetOutsideValue(0) thfilter.SetLowerThreshold(0.5) toWrite = thfilter.Execute(toWrite) cc = sitk.ConnectedComponentImageFilter() toWritecc = cc.Execute(sitk.Cast(toWrite, sitk.sitkUInt8)) arrCC = np.transpose(sitk.GetArrayFromImage(toWritecc).astype(dtype=float), [2, 1, 0]) lab = np.zeros(int(np.max(arrCC) + 1), dtype=float) for i in range(1, int(np.max(arrCC) + 1)): lab[i] = np.sum(arrCC == i) activeLab = np.argmax(lab) toWrite = (toWritecc == activeLab) toWrite = sitk.Cast(toWrite, sitk.sitkUInt8) writer = sitk.ImageFileWriter() writer.SetFileName(os.path.join(resultDir, key + resultTag + ext)) writer.Execute(toWrite)
46.16763
118
0.607487
7cc5a6d0232f51b69f22604b6201246450e833ec
362
py
Python
src/onegov/file/__init__.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
src/onegov/file/__init__.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
src/onegov/file/__init__.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
from onegov.file.collection import FileCollection, FileSetCollection from onegov.file.integration import DepotApp from onegov.file.models import ( File, FileSet, AssociatedFiles, SearchableFile ) __all__ = ( 'AssociatedFiles', 'DepotApp', 'File', 'FileCollection', 'FileSet', 'FileSetCollection', 'SearchableFile', )
19.052632
68
0.696133
7ccc98be66c4a3412762a48fd4b157ab1a634271
9,364
py
Python
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/plugins/modules/system/pam_limits.py
tr3ck3r/linklight
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
[ "MIT" ]
null
null
null
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/plugins/modules/system/pam_limits.py
tr3ck3r/linklight
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
[ "MIT" ]
null
null
null
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/plugins/modules/system/pam_limits.py
tr3ck3r/linklight
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
[ "MIT" ]
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2014, Sebastien Rohaut <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: pam_limits author: - "Sebastien Rohaut (@usawa)" short_description: Modify Linux PAM limits description: - The C(pam_limits) module modifies PAM limits. The default file is C(/etc/security/limits.conf). For the full documentation, see C(man 5 limits.conf). options: domain: description: - A username, @groupname, wildcard, uid/gid range. required: true limit_type: description: - Limit type, see C(man 5 limits.conf) for an explanation required: true choices: [ "hard", "soft", "-" ] limit_item: description: - The limit to be set required: true choices: - "core" - "data" - "fsize" - "memlock" - "nofile" - "rss" - "stack" - "cpu" - "nproc" - "as" - "maxlogins" - "maxsyslogins" - "priority" - "locks" - "sigpending" - "msgqueue" - "nice" - "rtprio" - "chroot" value: description: - The value of the limit. required: true backup: description: - Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly. required: false type: bool default: "no" use_min: description: - If set to C(yes), the minimal value will be used or conserved. If the specified value is inferior to the value in the file, file content is replaced with the new value, else content is not modified. required: false type: bool default: "no" use_max: description: - If set to C(yes), the maximal value will be used or conserved. If the specified value is superior to the value in the file, file content is replaced with the new value, else content is not modified. required: false type: bool default: "no" dest: description: - Modify the limits.conf path. required: false default: "/etc/security/limits.conf" comment: description: - Comment associated with the limit. required: false default: '' notes: - If C(dest) file doesn't exist, it is created. ''' EXAMPLES = ''' - name: Add or modify nofile soft limit for the user joe pam_limits: domain: joe limit_type: soft limit_item: nofile value: 64000 - name: Add or modify fsize hard limit for the user smith. Keep or set the maximal value. pam_limits: domain: smith limit_type: hard limit_item: fsize value: 1000000 use_max: yes - name: Add or modify memlock, both soft and hard, limit for the user james with a comment. pam_limits: domain: james limit_type: '-' limit_item: memlock value: unlimited comment: unlimited memory lock for james - name: Add or modify hard nofile limits for wildcard domain pam_limits: domain: '*' limit_type: hard limit_item: nofile value: 39693561 ''' import os import os.path import tempfile import re from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_native def main(): pam_items = ['core', 'data', 'fsize', 'memlock', 'nofile', 'rss', 'stack', 'cpu', 'nproc', 'as', 'maxlogins', 'maxsyslogins', 'priority', 'locks', 'sigpending', 'msgqueue', 'nice', 'rtprio', 'chroot'] pam_types = ['soft', 'hard', '-'] limits_conf = '/etc/security/limits.conf' module = AnsibleModule( # not checking because of daisy chain to file module argument_spec=dict( domain=dict(required=True, type='str'), limit_type=dict(required=True, type='str', choices=pam_types), limit_item=dict(required=True, type='str', choices=pam_items), value=dict(required=True, type='str'), use_max=dict(default=False, type='bool'), use_min=dict(default=False, type='bool'), backup=dict(default=False, type='bool'), dest=dict(default=limits_conf, type='str'), comment=dict(required=False, default='', type='str') ) ) domain = module.params['domain'] limit_type = module.params['limit_type'] limit_item = module.params['limit_item'] value = module.params['value'] use_max = module.params['use_max'] use_min = module.params['use_min'] backup = module.params['backup'] limits_conf = module.params['dest'] new_comment = module.params['comment'] changed = False if os.path.isfile(limits_conf): if not os.access(limits_conf, os.W_OK): module.fail_json(msg="%s is not writable. Use sudo" % limits_conf) else: limits_conf_dir = os.path.dirname(limits_conf) if os.path.isdir(limits_conf_dir) and os.access(limits_conf_dir, os.W_OK): open(limits_conf, 'a').close() changed = True else: module.fail_json(msg="directory %s is not writable (check presence, access rights, use sudo)" % limits_conf_dir) if use_max and use_min: module.fail_json(msg="Cannot use use_min and use_max at the same time.") if not (value in ['unlimited', 'infinity', '-1'] or value.isdigit()): module.fail_json(msg="Argument 'value' can be one of 'unlimited', 'infinity', '-1' or positive number. Refer to manual pages for more details.") # Backup if backup: backup_file = module.backup_local(limits_conf) space_pattern = re.compile(r'\s+') message = '' f = open(limits_conf, 'rb') # Tempfile nf = tempfile.NamedTemporaryFile(mode='w+') found = False new_value = value for line in f: line = to_native(line, errors='surrogate_or_strict') if line.startswith('#'): nf.write(line) continue newline = re.sub(space_pattern, ' ', line).strip() if not newline: nf.write(line) continue # Remove comment in line newline = newline.split('#', 1)[0] try: old_comment = line.split('#', 1)[1] except Exception: old_comment = '' newline = newline.rstrip() if not new_comment: new_comment = old_comment line_fields = newline.split(' ') if len(line_fields) != 4: nf.write(line) continue line_domain = line_fields[0] line_type = line_fields[1] line_item = line_fields[2] actual_value = line_fields[3] if not (actual_value in ['unlimited', 'infinity', '-1'] or actual_value.isdigit()): module.fail_json(msg="Invalid configuration of '%s'. Current value of %s is unsupported." % (limits_conf, line_item)) # Found the line if line_domain == domain and line_type == limit_type and line_item == limit_item: found = True if value == actual_value: message = line nf.write(line) continue actual_value_unlimited = actual_value in ['unlimited', 'infinity', '-1'] value_unlimited = value in ['unlimited', 'infinity', '-1'] if use_max: if value.isdigit() and actual_value.isdigit(): new_value = str(max(int(value), int(actual_value))) elif actual_value_unlimited: new_value = actual_value else: new_value = value if use_min: if value.isdigit() and actual_value.isdigit(): new_value = str(min(int(value), int(actual_value))) elif value_unlimited: new_value = actual_value else: new_value = value # Change line only if value has changed if new_value != actual_value: changed = True if new_comment: new_comment = "\t#" + new_comment new_limit = domain + "\t" + limit_type + "\t" + limit_item + "\t" + new_value + new_comment + "\n" message = new_limit nf.write(new_limit) else: message = line nf.write(line) else: nf.write(line) if not found: changed = True if new_comment: new_comment = "\t#" + new_comment new_limit = domain + "\t" + limit_type + "\t" + limit_item + "\t" + new_value + new_comment + "\n" message = new_limit nf.write(new_limit) f.close() nf.flush() # Copy tempfile to newfile module.atomic_move(nf.name, f.name) try: nf.close() except Exception: pass res_args = dict( changed=changed, msg=message ) if backup: res_args['backup_file'] = backup_file module.exit_json(**res_args) if __name__ == '__main__': main()
29.632911
152
0.59088
6b092633ebd77184c0cfa8bce6dee69c1818eef4
1,772
py
Python
vkapp/vk/views.py
ParuninPavel/lenta4_hack
6d3340201deadf5757e37ddd7cf5580b928d7bda
[ "MIT" ]
1
2017-11-23T13:33:13.000Z
2017-11-23T13:33:13.000Z
vkapp/vk/views.py
ParuninPavel/lenta4_hack
6d3340201deadf5757e37ddd7cf5580b928d7bda
[ "MIT" ]
null
null
null
vkapp/vk/views.py
ParuninPavel/lenta4_hack
6d3340201deadf5757e37ddd7cf5580b928d7bda
[ "MIT" ]
null
null
null
from django.shortcuts import render # def init(request, api_url, api_settings, viewer_id, group_id, is_app_user): # return render(request, 'vk/index.html', context) # api_url=https://api.vk.com/api.php # &api_settings=0 # &viewer_id=123456 # &group_id=654321 # &is_app_user=0 \\ from django.views.decorators.clickjacking import xframe_options_exempt from vkapp.bot.dao.newsDAO import get_news_proposed_today from vkapp.bot.models import Blogger, News, AdminReview, Publication from datetime import datetime, timedelta, time @xframe_options_exempt def init(request, **request_params): param = list(request.GET.items()) #.get('viewer_id') news_cnt = News.objects.filter(date_time__lte=today_end, date_time__gte=today_start).count() return render(request, 'vk/index.html', {'news_count': news_cnt}) # context = {'data': param} # return render(request, 'vk/index.html', context) @xframe_options_exempt def blogers(request): return render(request, 'vk/news.html', {'news': news}) @xframe_options_exempt def news(request): return render(request, 'vk/news1.html', {'news': news}) @xframe_options_exempt def news1(request): return render(request, 'vk/news2.html', {'news': news}) @xframe_options_exempt def news2(request): return render(request, 'vk/news.html', {'news': news}) @xframe_options_exempt def like(request, news_id): news = News.objects.filter(id=news_id) review = AdminReview.objects.get(news=news) review.rating = 1 review.save() return render(request, 'vk/init.html') @xframe_options_exempt def dislike(request, news_id): news = News.objects.filter(id=news_id) review = AdminReview.objects.get(news=news) review.rating = -1 review.save() return render(request, 'vk/init.html')
32.814815
96
0.733634
865d260283d98621112da3fbca505d742bd932a1
14,446
py
Python
model_zoo/ernie-doc/run_semantic_matching.py
mukaiu/PaddleNLP
0315365dbafa6e3b1c7147121ba85e05884125a5
[ "Apache-2.0" ]
null
null
null
model_zoo/ernie-doc/run_semantic_matching.py
mukaiu/PaddleNLP
0315365dbafa6e3b1c7147121ba85e05884125a5
[ "Apache-2.0" ]
null
null
null
model_zoo/ernie-doc/run_semantic_matching.py
mukaiu/PaddleNLP
0315365dbafa6e3b1c7147121ba85e05884125a5
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2021 PaddlePaddle 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. import argparse import collections from collections import namedtuple, defaultdict import os import random from functools import partial import time import numpy as np import paddle import paddle.nn as nn from paddle.io import DataLoader from paddle.metric import Accuracy from paddle.optimizer import AdamW from paddlenlp.transformers import ErnieDocModel from paddlenlp.transformers import ErnieDocForSequenceClassification from paddlenlp.transformers import ErnieDocTokenizer from paddlenlp.transformers import LinearDecayWithWarmup from paddlenlp.utils.log import logger from paddlenlp.datasets import load_dataset from paddlenlp.ops.optimizer import layerwise_lr_decay from data import SemanticMatchingIterator from model import ErnieDocForTextMatching # yapf: disable parser = argparse.ArgumentParser() parser.add_argument("--batch_size", default=6, type=int, help="Batch size per GPU/CPU for training.") parser.add_argument("--model_name_or_path", type=str, default="ernie-doc-base-zh", help="Pretraining model name or path") parser.add_argument("--max_seq_length", type=int, default=512, help="The maximum total input sequence length after SentencePiece tokenization.") parser.add_argument("--learning_rate", type=float, default=5e-5, help="Learning rate used to train.") parser.add_argument("--save_steps", type=int, default=1000, help="Save checkpoint every X updates steps.") parser.add_argument("--logging_steps", type=int, default=1, help="Log every X updates steps.") parser.add_argument("--output_dir", type=str, default='checkpoints/', help="Directory to save model checkpoint") parser.add_argument("--epochs", type=int, default=15, help="Number of epoches for training.") parser.add_argument("--device", type=str, default="gpu", choices=["cpu", "gpu"], help="Select cpu, gpu devices to train model.") parser.add_argument("--seed", type=int, default=1, help="Random seed for initialization.") parser.add_argument("--memory_length", type=int, default=128, help="Length of the retained previous heads.") parser.add_argument("--weight_decay", default=0.01, type=float, help="Weight decay if we apply some.") parser.add_argument("--warmup_proportion", default=0.1, type=float, help="Linear warmup proption over the training process.") parser.add_argument("--dataset", default="cail2019_scm", choices=["cail2019_scm"], type=str, help="The training dataset") parser.add_argument("--dropout", default=0.1, type=float, help="Dropout ratio of ernie_doc") parser.add_argument("--layerwise_decay", default=1.0, type=float, help="Layerwise decay ratio") parser.add_argument("--max_steps", default=-1, type=int, help="If > 0: set total number of training steps to perform. Override num_train_epochs.",) # yapf: enable args = parser.parse_args() DATASET_INFO = { "cail2019_scm": (ErnieDocTokenizer, "dev", "test", Accuracy()), } def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) paddle.seed(args.seed) def init_memory(batch_size, memory_length, d_model, n_layers): return [ paddle.zeros([batch_size, memory_length, d_model], dtype="float32") for _ in range(n_layers) ] @paddle.no_grad() def evaluate(model, metric, data_loader, memories0, pair_memories0): model.eval() losses = [] # copy the memory memories = list(memories0) pair_memories = list(pair_memories0) tic_train = time.time() eval_logging_step = 500 probs_dict = defaultdict(list) label_dict = dict() global_steps = 0 for step, batch in enumerate(data_loader, start=1): input_ids, position_ids, token_type_ids, attn_mask, \ pair_input_ids, pair_position_ids, pair_token_type_ids, pair_attn_mask, \ labels, qids, gather_idx, need_cal_loss = batch logits, memories, pair_memories = model(input_ids, pair_input_ids, memories, pair_memories, token_type_ids, position_ids, attn_mask, pair_token_type_ids, pair_position_ids, pair_attn_mask) logits, labels, qids = list( map(lambda x: paddle.gather(x, gather_idx), [logits, labels, qids])) # Need to collect probs for each qid, so use softmax_with_cross_entropy loss, probs = nn.functional.softmax_with_cross_entropy( logits, labels, return_softmax=True) losses.append(loss.mean().numpy()) # Shape: [B, NUM_LABELS] np_probs = probs.numpy() # Shape: [B, 1] np_qids = qids.numpy() np_labels = labels.numpy().flatten() for i, qid in enumerate(np_qids.flatten()): probs_dict[qid].append(np_probs[i]) label_dict[qid] = np_labels[i] # Same qid share same label. if step % eval_logging_step == 0: logger.info("Step %d: loss: %.5f, speed: %.5f steps/s" % (step, np.mean(losses), eval_logging_step / (time.time() - tic_train))) tic_train = time.time() # Collect predicted labels preds = [] labels = [] for qid, probs in probs_dict.items(): mean_prob = np.mean(np.array(probs), axis=0) preds.append(mean_prob) labels.append(label_dict[qid]) preds = paddle.to_tensor(np.array(preds, dtype='float32')) labels = paddle.to_tensor(np.array(labels, dtype='int64')) metric.update(metric.compute(preds, labels)) acc_or_f1 = metric.accumulate() logger.info("Eval loss: %.5f, %s: %.5f" % (np.mean(losses), metric.__class__.__name__, acc_or_f1)) metric.reset() model.train() return acc_or_f1 def do_train(args): set_seed(args) tokenizer_class, eval_name, test_name, eval_metric = DATASET_INFO[ args.dataset] tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path) # Get dataset train_ds, eval_ds, test_ds = load_dataset( args.dataset, splits=["train", eval_name, test_name]) num_classes = len(train_ds.label_list) # Initialize model paddle.set_device(args.device) trainer_num = paddle.distributed.get_world_size() if trainer_num > 1: paddle.distributed.init_parallel_env() rank = paddle.distributed.get_rank() if rank == 0: if os.path.exists(args.model_name_or_path): logger.info("init checkpoint from %s" % args.model_name_or_path) ernie_doc = ErnieDocModel.from_pretrained(args.model_name_or_path, cls_token_idx=0) model = ErnieDocForTextMatching(ernie_doc, num_classes, args.dropout) model_config = model.ernie_doc.config if trainer_num > 1: model = paddle.DataParallel(model) train_ds_iter = SemanticMatchingIterator( train_ds, args.batch_size, tokenizer, trainer_num, trainer_id=rank, memory_len=model_config["memory_len"], max_seq_length=args.max_seq_length, random_seed=args.seed) eval_ds_iter = SemanticMatchingIterator( eval_ds, args.batch_size, tokenizer, trainer_num, trainer_id=rank, memory_len=model_config["memory_len"], max_seq_length=args.max_seq_length, random_seed=args.seed, mode="eval") test_ds_iter = SemanticMatchingIterator( test_ds, args.batch_size, tokenizer, trainer_num, trainer_id=rank, memory_len=model_config["memory_len"], max_seq_length=args.max_seq_length, random_seed=args.seed, mode="test") train_dataloader = paddle.io.DataLoader.from_generator(capacity=70, return_list=True) train_dataloader.set_batch_generator(train_ds_iter, paddle.get_device()) eval_dataloader = paddle.io.DataLoader.from_generator(capacity=70, return_list=True) eval_dataloader.set_batch_generator(eval_ds_iter, paddle.get_device()) test_dataloader = paddle.io.DataLoader.from_generator(capacity=70, return_list=True) test_dataloader.set_batch_generator(test_ds_iter, paddle.get_device()) num_training_examples = train_ds_iter.get_num_examples() num_training_steps = args.epochs * num_training_examples // args.batch_size // trainer_num logger.info("Device count: %d, trainer_id: %d" % (trainer_num, rank)) logger.info("Num train examples: %d" % num_training_examples) logger.info("Max train steps: %d" % num_training_steps) logger.info("Num warmup steps: %d" % int(num_training_steps * args.warmup_proportion)) lr_scheduler = LinearDecayWithWarmup(args.learning_rate, num_training_steps, args.warmup_proportion) # Generate parameter names needed to perform weight decay. # All bias and LayerNorm parameters are excluded. decay_params = [ p.name for n, p in model.named_parameters() if not any(nd in n for nd in ["bias", "norm"]) ] # Construct dict name_dict = dict() for n, p in model.named_parameters(): name_dict[p.name] = n simple_lr_setting = partial(layerwise_lr_decay, args.layerwise_decay, name_dict, model_config["num_hidden_layers"]) optimizer = AdamW(learning_rate=lr_scheduler, parameters=model.parameters(), weight_decay=args.weight_decay, apply_decay_param_fun=lambda x: x in decay_params, lr_ratio=simple_lr_setting) criterion = paddle.nn.loss.CrossEntropyLoss() metric = paddle.metric.Accuracy() global_steps = 0 best_acc = -1 create_memory = partial(init_memory, args.batch_size, args.memory_length, model_config["hidden_size"], model_config["num_hidden_layers"]) # Copy the memory memories = create_memory() pair_memories = create_memory() tic_train = time.time() for epoch in range(args.epochs): train_ds_iter.shuffle_sample() train_dataloader.set_batch_generator(train_ds_iter, paddle.get_device()) for step, batch in enumerate(train_dataloader, start=1): global_steps += 1 input_ids, position_ids, token_type_ids, attn_mask, \ pair_input_ids, pair_position_ids, pair_token_type_ids, pair_attn_mask, \ labels, qids, gather_idx, need_cal_loss = batch logits, memories, pair_memories = model( input_ids, pair_input_ids, memories, pair_memories, token_type_ids, position_ids, attn_mask, pair_token_type_ids, pair_position_ids, pair_attn_mask) logits, labels = list( map(lambda x: paddle.gather(x, gather_idx), [logits, labels])) loss = criterion(logits, labels) * need_cal_loss mean_loss = loss.mean() mean_loss.backward() optimizer.step() lr_scheduler.step() optimizer.clear_grad() # Rough acc result, not a precise acc acc = metric.compute(logits, labels) * need_cal_loss metric.update(acc) if global_steps % args.logging_steps == 0: logger.info( "train: global step %d, epoch: %d, loss: %f, acc:%f, lr: %f, speed: %.2f step/s" % (global_steps, epoch, mean_loss, metric.accumulate(), lr_scheduler.get_lr(), args.logging_steps / (time.time() - tic_train))) tic_train = time.time() if global_steps % args.save_steps == 0: # Evaluate logger.info("Eval:") eval_acc = evaluate(model, eval_metric, eval_dataloader, create_memory(), create_memory()) # Save if rank == 0: output_dir = os.path.join(args.output_dir, "model_%d" % (global_steps)) if not os.path.exists(output_dir): os.makedirs(output_dir) model_to_save = model._layers if isinstance( model, paddle.DataParallel) else model save_param_path = os.path.join(output_dir, 'model_state.pdparams') paddle.save(model_to_save.state_dict(), save_param_path) tokenizer.save_pretrained(output_dir) if eval_acc > best_acc: logger.info("Save best model......") best_acc = eval_acc best_model_dir = os.path.join(args.output_dir, "best_model") if not os.path.exists(best_model_dir): os.makedirs(best_model_dir) save_param_path = os.path.join(best_model_dir, 'model_state.pdparams') paddle.save(model_to_save.state_dict(), save_param_path) tokenizer.save_pretrained(best_model_dir) if args.max_steps > 0 and global_steps >= args.max_steps: return logger.info("Final test result:") eval_acc = evaluate(model, eval_metric, test_dataloader, create_memory(), create_memory()) if __name__ == "__main__": do_train(args)
42.866469
147
0.63277
814091f9b77f6f67cb87191426ee47c7c79ebe5c
4,079
py
Python
GZP_GTO_QGIS/INSTALLATION/GeoTaskOrganizer/gto_windows.py
msgis/swwat-gzp-template
080afbe9d49fb34ed60ba45654383d9cfca01e24
[ "MIT" ]
3
2019-06-18T15:28:09.000Z
2019-07-11T07:31:45.000Z
GZP_GTO_QGIS/INSTALLATION/GeoTaskOrganizer/gto_windows.py
msgis/swwat-gzp-template
080afbe9d49fb34ed60ba45654383d9cfca01e24
[ "MIT" ]
2
2019-07-11T14:03:25.000Z
2021-02-08T16:14:04.000Z
GZP_GTO_QGIS/INSTALLATION/GeoTaskOrganizer/gto_windows.py
msgis/swwat-gzp-template
080afbe9d49fb34ed60ba45654383d9cfca01e24
[ "MIT" ]
1
2019-06-12T11:07:37.000Z
2019-06-12T11:07:37.000Z
from builtins import str from builtins import object import win32gui import re class WindowMgr(object): """Encapsulates some calls to the winapi for window management""" def __init__ (self,gtoObj,debug): """Constructor""" self._handle = None self.debug = debug self.gtoObj =gtoObj def find_window(self, class_name, window_name = None): """find a window by its class_name""" self._handle = win32gui.FindWindow(class_name, window_name) if self.debug: self.gtoObj.info.log("Found window handle:",window_name, self.handle) def _window_enum_callback(self, hwnd, wildcard): '''Pass to win32gui.EnumWindows() to check all the opened windows''' if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) != None: self._handle = hwnd def find_window_wildcard(self, wildcard): self._handle = None win32gui.EnumWindows(self._window_enum_callback, wildcard) def set_foreground(self): """put the window in the foreground""" win32gui.SetForegroundWindow(self._handle) def ActivateApp (gtoObj,debug,title,file): if debug:gtoObj.info.log('ActivateApp:', title,file ) import win32com.client import win32process import os try: wmgr = WindowMgr(gtoObj,debug) wmgr.find_window_wildcard(title) hwnd = wmgr._handle if debug: gtoObj.info.log ("Found window handle for <%s>:" % title,hwnd) _, pid = win32process.GetWindowThreadProcessId(wmgr._handle) shell = win32com.client.Dispatch("WScript.Shell") if hwnd is None: if debug: gtoObj.info.log("Start file:",file) os.startfile(file) #shell.Run(file) else: if debug: gtoObj.info.log("Activate app:",hwnd) shell.AppActivate(pid) shell.SendKeys ("% r{ENTER}") except Exception as e: gtoObj.info.err(e) def ReactivatePreviousApp (): import win32com.client import win32gui import win32process hwnd = win32gui.GetForegroundWindow() _, pid = win32process.GetWindowThreadProcessId(hwnd) shell = win32com.client.Dispatch("WScript.Shell") shell.AppActivate('Console2') shell.SendKeys('{UP}{ENTER}') shell.AppActivate(pid) def getLogin(): import win32api import win32net import win32netcon def UserGetInfo(): dc = win32net.NetServerEnum(None, 100, win32netcon.SV_TYPE_DOMAIN_CTRL) user = win32api.GetUserName() if dc[0]: dcname = dc[0][0]['name'] return win32net.NetUserGetInfo("\\\\" + dcname, user, 1) else: return win32net.NetUserGetInfo(None, user, 1) def openfile(file): import win32com.client def raw(text): escape_dict = {'\a': r'\a', '\b': r'\b', '\c': r'\c', '\f': r'\f', '\n': r'\n', '\r': r'\r', '\t': r'\t', '\v': r'\v', '\'': r'\'', '\"': r'\"', '\0': r'\0', '\1': r'\1', '\2': r'\2', '\3': r'\3', '\4': r'\4', '\5': r'\5', '\6': r'\6', '\7': r'\7', '\8': r'\8', '\9': r'\9', '\256': r'\256'} # notice this line is the first 3 digits of the resolution for k in escape_dict: if text.find(k) > -1: text = text.replace(k, escape_dict[k]) return text shell = win32com.client.Dispatch("WScript.Shell") try: shell.Run(str(file)) return True except: pass try: shell.Run(raw("\\" + file)) return True except: pass#unc failed try: shell.Run(raw(file)) return True except: pass #raw only failed
30.901515
99
0.532483
07f56f55f27634736297646e96b67fcd5cf9ab68
12,341
py
Python
fence/blueprints/oauth2.py
scottyellis/fence
012ba76a58853169e9ee8e3f44a0dc510f4b2543
[ "Apache-2.0" ]
31
2018-01-05T22:49:33.000Z
2022-02-02T10:30:23.000Z
fence/blueprints/oauth2.py
scottyellis/fence
012ba76a58853169e9ee8e3f44a0dc510f4b2543
[ "Apache-2.0" ]
737
2017-12-11T17:42:11.000Z
2022-03-29T22:42:52.000Z
fence/blueprints/oauth2.py
scottyellis/fence
012ba76a58853169e9ee8e3f44a0dc510f4b2543
[ "Apache-2.0" ]
46
2018-02-23T09:04:23.000Z
2022-02-09T18:29:51.000Z
# pylint: disable=protected-access,unused-argument """ Define the ``OAuth2Provider`` used by fence and set its related handler functions for storing and loading ``Grant`` models and loading ``Client`` models. In the implementation here with JWT, a grant is a thin wrapper around the client from which an authorization request was issued, and the code being used for a specific request; additionally, the grant is able to throw itself away when the procedure is completed or after a short timeout. The token setter and getter functions for the OAuth provider do pretty much nothing, since the JWTs contain all the necessary information and are stateless. """ from authlib.common.urls import add_params_to_uri from authlib.oauth2.rfc6749 import AccessDeniedError, InvalidRequestError, OAuth2Error import flask import json from authutils.errors import JWTExpiredError from fence.blueprints.login import IDP_URL_MAP from fence.errors import Unauthorized, UserError from fence.jwt.errors import JWTError from fence.jwt.token import SCOPE_DESCRIPTION from fence.models import Client from fence.oidc.endpoints import RevocationEndpoint from fence.oidc.server import server from fence.utils import clear_cookies from fence.user import get_current_user from fence.config import config blueprint = flask.Blueprint("oauth2", __name__) @blueprint.route("/authorize", methods=["GET", "POST"]) def authorize(*args, **kwargs): """ OIDC Authorization Endpoint From the OIDC Specification: 3.1.1. Authorization Code Flow Steps The Authorization Code Flow goes through the following steps. - Client prepares an Authentication Request containing the desired request parameters. - Client sends the request to the Authorization Server. - Authorization Server Authenticates the End-User. - Authorization Server obtains End-User Consent/Authorization. - Authorization Server sends the End-User back to the Client with an Authorization Code. - Client requests a response using the Authorization Code at the Token Endpoint. - Client receives a response that contains an ID Token and Access Token in the response body. - Client validates the ID token and retrieves the End-User's Subject Identifier. Args: *args: additional arguments **kwargs: additional keyword arguments """ need_authentication = False user = None try: user = get_current_user() except Unauthorized: need_authentication = True idp = flask.request.args.get("idp") fence_idp = flask.request.args.get("fence_idp") shib_idp = flask.request.args.get("shib_idp") login_url = None if not idp: # use default login IDP idp = config.get("DEFAULT_LOGIN_IDP") if not idp: if "default" in config.get("ENABLED_IDENTITY_PROVIDERS", {}): # fall back on ENABLED_IDENTITY_PROVIDERS.default idp = config["ENABLED_IDENTITY_PROVIDERS"]["default"] else: # fall back on deprecated DEFAULT_LOGIN_URL login_url = config.get("DEFAULT_LOGIN_URL") if need_authentication or not user: redirect_url = config.get("BASE_URL") + flask.request.full_path params = {"redirect": redirect_url} if not login_url: if idp not in IDP_URL_MAP or idp not in config["OPENID_CONNECT"]: raise UserError("idp {} is not supported".format(idp)) idp_url = IDP_URL_MAP[idp] login_url = "{}/login/{}".format(config.get("BASE_URL"), idp_url) # handle valid extra params for fence multi-tenant and shib login if idp == "fence" and fence_idp: params["idp"] = fence_idp if fence_idp == "shibboleth": params["shib_idp"] = shib_idp elif idp == "shibboleth" and shib_idp: params["shib_idp"] = shib_idp # store client_id for later use in login endpoint prepare_login_log() flask.session["client_id"] = flask.request.args.get("client_id") login_url = add_params_to_uri(login_url, params) return flask.redirect(login_url) try: grant = server.validate_consent_request(end_user=user) except OAuth2Error as e: raise Unauthorized("Failed to authorize: {}".format(str(e))) client_id = grant.client.client_id with flask.current_app.db.session as session: client = session.query(Client).filter_by(client_id=client_id).first() # TODO: any way to get from grant? confirm = flask.request.form.get("confirm") or flask.request.args.get("confirm") if client.auto_approve: confirm = "yes" if confirm is not None: response = _handle_consent_confirmation(user, confirm) # if it's a 302 for POST confirm, return 200 instead and include # redirect url in body because browser ajax POST doesn't follow # cross origin redirect if flask.request.method == "POST" and response.status_code == 302: response = flask.jsonify({"redirect": response.headers["Location"]}) else: # no confirm param, so no confirmation has occured yet response = _authorize(user, grant, client) return response def _handle_consent_confirmation(user, is_confirmed): """ Return server response given user consent. Args: user (fence.models.User): authN'd user is_confirmed (str): confirmation param """ if is_confirmed == "yes": # user has already given consent, continue flow response = server.create_authorization_response(grant_user=user) else: # user did not give consent response = server.create_authorization_response(grant_user=None) return response def _authorize(user, grant, client): """ Return server response when user has not yet provided consent. Args: user (fence.models.User): authN'd user grant (fence.oidc.grants.AuthorizationCodeGrant): request grant client (fence.models.Client): request client """ scope = flask.request.args.get("scope") response = _get_auth_response_for_prompts(grant.prompt, grant, user, client, scope) return response def _get_auth_response_for_prompts(prompts, grant, user, client, scope): """ Get response based on prompt parameter. TODO: not completely conforming yet FIXME: To conform to spec, some of the prompt params should be handled before AuthN or if it fails (so adequate and useful errors are provided). Right now the behavior is that the endpoint will just continue to redirect the user to log in without checking these params.... Args: prompts (TYPE): Description grant (TYPE): Description user (TYPE): Description client (TYPE): Description scope (TYPE): Description Returns: TYPE: Description """ show_consent_screen = True if prompts: prompts = prompts.split(" ") if "none" in prompts: # don't auth or consent, error if user not logged in show_consent_screen = False # if none is here, there shouldn't be others if len(prompts) != 1: error = InvalidRequestError( state=grant.params.get("state"), uri=grant.params.get("uri") ) return _get_authorize_error_response( error, grant.params.get("redirect_uri") ) try: get_current_user() response = server.create_authorization_response(user) except Unauthorized: error = AccessDeniedError( state=grant.params.get("state"), uri=grant.params.get("uri") ) return _get_authorize_error_response( error, grant.params.get("redirect_uri") ) if "login" in prompts: show_consent_screen = True try: # Re-AuthN user (kind of). # TODO (RR 2018-03-16): this could also include removing active # refresh tokens. flask.session.clear() # For a POST, return the redirect in JSON instead of headers. if flask.request.method == "POST": redirect_response = flask.make_response( flask.jsonify({"redirect": response.headers["Location"]}) ) else: redirect_response = flask.make_response( flask.redirect(flask.url_for(".authorize")) ) clear_cookies(redirect_response) return redirect_response except Unauthorized: error = AccessDeniedError( state=grant.params.get("state"), uri=grant.params.get("uri") ) return _get_authorize_error_response( error, grant.params.get("redirect_uri") ) if "consent" in prompts: # show consent screen (which is default behavior so pass) pass if "select_account" in prompts: # allow user to select one of their accounts, we # don't support this at the moment pass if show_consent_screen: shown_scopes = [] if not scope else scope.split(" ") if "openid" in shown_scopes: shown_scopes.remove("openid") enabled_idps = config.get("OPENID_CONNECT", {}) idp_names = [] for idp, info in enabled_idps.items(): # prefer name if its there, then just use the key for the provider idp_name = info.get("name") or idp.title() idp_names.append(idp_name) resource_description = [ SCOPE_DESCRIPTION[s].format(idp_names=" and ".join(idp_names)) for s in shown_scopes ] privacy_policy = config.get("BASE_URL").rstrip("/") + "/privacy-policy" response = flask.render_template( "oauthorize.html", grant=grant, user=user, client=client, app_name=config.get("APP_NAME"), resource_description=resource_description, privacy_policy=privacy_policy, ) return response def _get_authorize_error_response(error, redirect_uri): """ Get error response as defined by OIDC spec. Args: error (authlib.oauth2.rfc6749.error.OAuth2Error): Specific Oauth2 error redirect_uri (str): Redirection url """ params = error.get_body() uri = add_params_to_uri(redirect_uri, params) headers = [("Location", uri)] response = flask.Response("", status=302, headers=headers) return response @blueprint.route("/token", methods=["POST"]) def get_token(*args, **kwargs): """ Handle exchanging code for and refreshing the access token. See the OpenAPI documentation for detailed specification, and the OAuth2 tests for examples of some operation and correct behavior. """ try: response = server.create_token_response() except (JWTError, JWTExpiredError) as e: # - in Authlib 0.11, create_token_response does not raise OAuth2Error # - fence.jwt.errors.JWTError: blacklisted refresh token # - JWTExpiredError (cdiserrors.AuthNError subclass): expired # refresh token # Returns code 400 per OAuth2 spec body = {"error": "invalid_grant", "error_description": e.message} response = flask.Response( json.dumps(body), mimetype="application/json", status=400 ) return response @blueprint.route("/revoke", methods=["POST"]) def revoke_token(): """ Revoke a refresh token. If the operation is successful, return an empty response with a 204 status code. Otherwise, return error message in JSON with a 400 code. Return: Tuple[str, int]: JSON response and status code """ return server.create_endpoint_response(RevocationEndpoint.ENDPOINT_NAME) @blueprint.route("/errors", methods=["GET"]) def display_error(): """ Define the errors endpoint for the OAuth provider. """ return flask.jsonify(flask.request.args)
35.564841
87
0.64622
ed5b4d88cd296dd0bf25bdfac438410506ec0e3d
245
py
Python
benchmarks/fib.py
axiom-labs/cghost
ca19282dc5e122d83c101bebf106631f92d80dce
[ "MIT" ]
4
2020-04-19T23:56:17.000Z
2020-05-30T18:54:01.000Z
benchmarks/fib.py
axiom-labs/cghost
ca19282dc5e122d83c101bebf106631f92d80dce
[ "MIT" ]
19
2020-05-08T22:08:51.000Z
2020-05-30T20:59:04.000Z
benchmarks/fib.py
ghost-language/cghost
ca19282dc5e122d83c101bebf106631f92d80dce
[ "MIT" ]
2
2020-04-28T05:23:33.000Z
2020-05-26T16:35:06.000Z
from __future__ import print_function import time def fib(n): if n < 2: return n return fib(n - 1) + fib(n - 2) start = time.process_time() print(fib(35) == 9227465) end = time.process_time() print("elapsed:") print(str(end - start))
17.5
37
0.665306
1301b07326622d1814e183b7bf9989a8e79d1cbe
1,772
py
Python
src/bo4e/com/zeitreihenwertkompakt.py
bo4e/BO4E-python
28b12f853c8a496d14b133759b7aa2d6661f79a0
[ "MIT" ]
1
2022-03-02T12:49:44.000Z
2022-03-02T12:49:44.000Z
src/bo4e/com/zeitreihenwertkompakt.py
bo4e/BO4E-python
28b12f853c8a496d14b133759b7aa2d6661f79a0
[ "MIT" ]
21
2022-02-04T07:38:46.000Z
2022-03-28T14:01:53.000Z
src/bo4e/com/zeitreihenwertkompakt.py
bo4e/BO4E-python
28b12f853c8a496d14b133759b7aa2d6661f79a0
[ "MIT" ]
null
null
null
""" Contains Zeitreihenwertkompakt class and corresponding marshmallow schema for de-/serialization """ from decimal import Decimal from typing import Optional import attr from marshmallow import fields from marshmallow_enum import EnumField # type:ignore[import] from bo4e.com.com import COM, COMSchema from bo4e.enum.messwertstatus import Messwertstatus from bo4e.enum.messwertstatuszusatz import Messwertstatuszusatz # pylint: disable=too-few-public-methods @attr.s(auto_attribs=True, kw_only=True) class Zeitreihenwertkompakt(COM): """ Abbildung eines kompakten Zeitreihenwertes in dem ausschliesslich der Wert und Statusinformationen stehen. .. HINT:: `Zeitreihenwertkompakt JSON Schema <https://json-schema.app/view/%23?url=https://raw.githubusercontent.com/Hochfrequenz/BO4E-python/main/json_schemas/com/ZeitreihenwertkompaktSchema.json>`_ """ # required attributes wert: Decimal = attr.ib(validator=attr.validators.instance_of(Decimal)) #: Der im Zeitintervall gültige Wert. # optional attributes status: Optional[Messwertstatus] = attr.ib( default=None ) #: Der Status gibt an, wie der Wert zu interpretieren ist, z.B. in Berechnungen. statuszusatz: Optional[Messwertstatuszusatz] = attr.ib( default=None ) #: Eine Zusatzinformation zum Status, beispielsweise ein Grund für einen fehlenden Wert. class ZeitreihenwertkompaktSchema(COMSchema): """ Schema for de-/serialization of Zeitreihenwertkompakt. """ class_name = Zeitreihenwertkompakt # required attributes wert = fields.Decimal(as_string=True) # optional attributes status = EnumField(Messwertstatus, load_default=None) statuszusatz = EnumField(Messwertstatuszusatz, load_default=None)
33.433962
197
0.76298
b9893058efc7802eddda7f2fdca65a3fd918310b
1,076
py
Python
same-tree/same-tree.py
hyeseonko/LeetCode
48dfc93f1638e13041d8ce1420517a886abbdc77
[ "MIT" ]
2
2021-12-05T14:29:06.000Z
2022-01-01T05:46:13.000Z
same-tree/same-tree.py
hyeseonko/LeetCode
48dfc93f1638e13041d8ce1420517a886abbdc77
[ "MIT" ]
null
null
null
same-tree/same-tree.py
hyeseonko/LeetCode
48dfc93f1638e13041d8ce1420517a886abbdc77
[ "MIT" ]
null
null
null
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: if not p and not q: return True elif (p and not q) or (not p and q): return False else: stack=[(p, q)] while(stack): cur_p, cur_q = stack.pop(0) if cur_p.val!=cur_q.val: return False if cur_p.left and cur_q.left: stack.append((cur_p.left, cur_q.left)) if cur_p.right and cur_q.right: stack.append((cur_p.right, cur_q.right)) if (cur_p.left and not cur_q.left) or (not cur_p.left and cur_q.left): return False if (cur_p.right and not cur_q.right) or (not cur_p.right and cur_q.right): return False return True
39.851852
90
0.51487
b9c8642e7db30be173b2f63b0bda6ceed2d50e6b
4,002
py
Python
norden/norden/doctype/nvs/nvs.py
thispl/norden
2a208056e948cae42da688e28c15024124254867
[ "MIT" ]
null
null
null
norden/norden/doctype/nvs/nvs.py
thispl/norden
2a208056e948cae42da688e28c15024124254867
[ "MIT" ]
null
null
null
norden/norden/doctype/nvs/nvs.py
thispl/norden
2a208056e948cae42da688e28c15024124254867
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright (c) 2021, Teampro and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class NVS(Document): pass @frappe.whitelist() def get_nvs_header(doc): data = '<tr><td style="background-color:#6e1f56;" colspan="3"><b style="color:white;font-size:14px">Specifications</b></td></tr>' data += '<tr><td style="background-color:#e9d8e2;" ><b>Model</b></td><td style="background-color:#e9d8e2;" colspan="3"><b style="font-size:11px;">%s</b></td></tr>'%(doc.type) return data @frappe.whitelist() def get_category_alignment(selected_ca,doc): if selected_ca == 'Left': category_alignment = '<div id="left-cat"><svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="45px" height="250px"\ viewBox="0 0 119.000000 855.000000" preserveAspectRatio="xMidYMid meet">\ <g transform="translate(0.000000,855.000000) scale(0.100000,-0.100000)" fill="#7A1F5E" stroke="none">\ <path d="M10 4280 c0 -2343 2 -4260 4 -4260 10 0 992 652 1045 693 35 27 67\ 64 86 98 l30 54 3 3390 c2 3072 1 3395 -14 3445 -27 93 -84 139 -633 500 -272\ 179 -500 329 -507 333 -12 7 -14 -666 -14 -4253z" /></g>\ <text font-size="60px" font-weight="bold" fill="#FFFFFF" transform="translate(80,620) rotate(-90)">%s</text></svg></div>'%(doc.categories) else: category_alignment = '<div style="float:right; margin-right:-15px">\ <div style="position: fixed;top:600px">\ <svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="45px" height="250px"\ viewBox="0 0 118.000000 854.000000" preserveAspectRatio="xMidYMid meet">\ <g transform="translate(0.000000,854.000000) scale(0.100000,-0.100000)" fill="#7A1F5E" stroke="none">\ <path d="M647 8181 c-279 -186 -526 -355 -548 -377 -21 -21 -49 -59 -62 -84\ l-22 -45 0 -3405 0 -3405 22 -47 c12 -26 41 -66 65 -88 24 -23 274 -194 556\ -380 l512 -339 0 4254 c0 2340 -3 4255 -7 4254 -5 0 -237 -152 -516 -338z" /></g>\ <text font-size="60px" font-weight="bold" fill="#FFFFFF" transform="translate(75,650) rotate(-90)">%s</text></svg>\ </div>\ </div>'%(doc.categories) return category_alignment @frappe.whitelist() def get_nvs_specification(doc,child,label,pb): if len(child) > 0: data = '<tr><td rowspan=%s style="vertical-align: middle;">%s</td>'%(len(child),label) for c in child: data += '<td>%s</td><td><p style="font-size:11px">%s</p></td></tr><tr>'%(c.title,c.specification) data += '</tr>' if pb == 1: data += '</table><p style="page-break-before: always;">&nbsp;</p><table class="table table-condensed table-border">' data += '<tr><td style="background-color:#6e1f56;" colspan="3"><b style="color:white">Specifications</b></td></tr>' data += '<tr><td style="background-color:#e9d8e2;" >Model</td><td style="background-color:#e9d8e2;"colspan="3"><center>%s</center></td></tr>'%(doc.type) return data else: return '' # @frappe.whitelist() # def get_nvs_specification(doc,child,label,pb): # if len(child) > 0: # data = '<tr><td rowspan=%s style="border: 1px solid #4d004d"><center>%s</center></td>'%(len(child),label) # for c in child: # data += '<td style="border: 1px solid #4d004d">%s</td><td style="border: 1px solid #4d004d">%s</td></tr><tr>'%(c.title,c.specification) # data += '</tr>' # if pb == 1: # data += '</table><p style="page-break-before: always;">&nbsp;</p><table class="table table-condensed">' # data += '<tr><td style="background-color:#6e1f56;border:1px solid #4d004d;" colspan="3"><text color="white">Specifications</text></td></tr>' # data += '<tr><td style="border: 1px solid #4d004d; background-color:#e9d8e2;" >Model</td><td style="border: 1px solid #4d004d; background-color:#DDA0DD;" colspan="2"><center>%s</center></td></tr>'%(doc.type) # return data # else: # return ''
56.366197
212
0.632934
1644f3bade3433c08445ea631ccbaa439e7e8c91
2,837
py
Python
Code/plot.py
knirschl/Proseminar-Anthropomatik
0408e54cf220c40a6f3deae6ae8d38c5f1f4f387
[ "MIT" ]
null
null
null
Code/plot.py
knirschl/Proseminar-Anthropomatik
0408e54cf220c40a6f3deae6ae8d38c5f1f4f387
[ "MIT" ]
null
null
null
Code/plot.py
knirschl/Proseminar-Anthropomatik
0408e54cf220c40a6f3deae6ae8d38c5f1f4f387
[ "MIT" ]
null
null
null
import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors import os DEFAULT_VALUE = 4 def cart2pol(x, y): r = np.sqrt(x**2 + y**2) phi = np.arctan2(y, x) return (r, phi) def pol2cart(r, phi): x = r * np.cos(phi) y = r * np.sin(phi) return (x, y) ''' Plot an 2D ndarray ''' def plot(points, centered=2, color=colors.CSS4_COLORS['dodgerblue'], markersize=3, system='cart', saveTo=''): x_axis = points[:, 0] y_axis = points[:, 1] xmin = np.min(x_axis) xmax = np.max(x_axis) ymin = np.min(y_axis) ymax = np.max(y_axis) xabsmax = np.max(np.abs(x_axis)) yabsmax = np.max(np.abs(y_axis)) if (xmin == -np.inf): xmin = -DEFAULT_VALUE if (ymin == -np.inf): ymin = -DEFAULT_VALUE if (xmax == np.inf): xmax = DEFAULT_VALUE if (ymax == np.inf): ymax = DEFAULT_VALUE if (xabsmax == np.inf): xabsmax = DEFAULT_VALUE if (yabsmax == np.inf): yabsmax = DEFAULT_VALUE ax = plt.subplot(polar=(system == 'pol')) #ax.spines['left'].set_position('center') ax.plot(x_axis, y_axis, color=color, linestyle='', marker='.', markersize=markersize) #plt.axis('equal') #plt.gca().set_aspect('equal', adjustable='box') #ax.set_xlim([xmin-0.05, xmax+0.05]) #ax.set_ylim([ymin-0.05, ymax+0.05]) if (centered == 1): ax.set_xlim([-xabsmax, xabsmax]) ax.set_ylim([ymin, ymax]) elif (centered == -1): ax.set_xlim([xmin, xmax]) ax.set_ylim([-yabsmax, yabsmax]) elif (centered == 0): ax.set_xlim([-xabsmax, xabsmax]) ax.set_ylim([-yabsmax, yabsmax]) else: ax.set_xlim([xmin, xmax]) ax.set_ylim([ymin, ymax]) if (saveTo != ''): print('SAVING ENABLED') _, ext = os.path.splitext(saveTo) ext = ext.replace('.', '') plt.savefig(saveTo, format=ext, dpi=1200) else: print('SAVING DISABLED') plt.show() def plot1(x, f_x): plt.plot(x, f_x, 'r') plt.show() def plot2(x, f_x, U, f_x_inv): fig, (ax1, ax2) = plt.subplots(1, 2) ax1.plot(x, f_x, 'r') ax2.plot(U, f_x_inv, 'b') plt.show() # len(X) % columns == 0 def plotM(X, F, titles=[], columns=2, colors = ['tab:green', 'tab:red', 'tab:blue', 'tab:orange', 'tab:cyan']): if (len(X) != len(F)): print("ERROR") return cid = 0 rows = int(len(X)/columns) fig, axs = plt.subplots(rows, columns, num='Distribution functions and their inverses') for a in range(0, rows): for b in range(0, columns): idx = a * columns + b if (len(titles) != 0): axs[a, b].set_title(titles[idx]) axs[a, b].plot(X[idx], F[idx], colors[cid]) cid = (cid + 1) % len(colors) plt.tight_layout()
28.37
111
0.557631
e6aefaf8c8e08d12422f537b29033c7b3d25cf45
26,192
py
Python
Utils/py/RL_ActionSelection/env_0/tools/naoth/CommonTypes_pb2.py
tarsoly/NaoTH
dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52
[ "ECL-2.0", "Apache-2.0" ]
15
2015-01-12T10:46:29.000Z
2022-03-28T05:13:14.000Z
Utils/py/RL_ActionSelection/env_0/tools/naoth/CommonTypes_pb2.py
tarsoly/NaoTH
dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52
[ "ECL-2.0", "Apache-2.0" ]
2
2019-01-20T21:07:50.000Z
2020-01-22T14:00:28.000Z
Utils/py/RL_ActionSelection/env_0/tools/naoth/CommonTypes_pb2.py
tarsoly/NaoTH
dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52
[ "ECL-2.0", "Apache-2.0" ]
5
2018-02-07T18:18:10.000Z
2019-10-15T17:01:41.000Z
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: CommonTypes.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='CommonTypes.proto', package='naothmessages', serialized_pb=_b('\n\x11\x43ommonTypes.proto\x12\rnaothmessages\"$\n\x0c\x46loatVector2\x12\t\n\x01x\x18\x01 \x02(\x02\x12\t\n\x01y\x18\x02 \x02(\x02\"%\n\rDoubleVector2\x12\t\n\x01x\x18\x01 \x02(\x01\x12\t\n\x01y\x18\x02 \x02(\x01\"\"\n\nIntVector2\x12\t\n\x01x\x18\x01 \x02(\x05\x12\t\n\x01y\x18\x02 \x02(\x05\"M\n\x06Pose2D\x12\x31\n\x0btranslation\x18\x01 \x02(\x0b\x32\x1c.naothmessages.DoubleVector2\x12\x10\n\x08rotation\x18\x02 \x02(\x01\"0\n\rDoubleVector3\x12\t\n\x01x\x18\x01 \x02(\x01\x12\t\n\x01y\x18\x02 \x02(\x01\x12\t\n\x01z\x18\x03 \x02(\x01\"\x19\n\x0c\x44oubleVector\x12\t\n\x01v\x18\x01 \x03(\x01\"k\n\x06Pose3D\x12\x31\n\x0btranslation\x18\x01 \x02(\x0b\x32\x1c.naothmessages.DoubleVector3\x12.\n\x08rotation\x18\x02 \x03(\x0b\x32\x1c.naothmessages.DoubleVector3\"z\n\x0bLineSegment\x12*\n\x04\x62\x61se\x18\x01 \x02(\x0b\x32\x1c.naothmessages.DoubleVector2\x12/\n\tdirection\x18\x02 \x02(\x0b\x32\x1c.naothmessages.DoubleVector2\x12\x0e\n\x06length\x18\x03 \x02(\x01\"\xdf\x02\n\x0cIntersection\x12\x30\n\nposInImage\x18\x01 \x01(\x0b\x32\x1c.naothmessages.DoubleVector2\x12\x30\n\nposOnField\x18\x02 \x01(\x0b\x32\x1c.naothmessages.DoubleVector2\x12:\n\x04type\x18\x03 \x01(\x0e\x32,.naothmessages.Intersection.IntersectionType\x12\x17\n\x0fsegmentOneIndex\x18\x06 \x01(\r\x12\x17\n\x0fsegmentTwoIndex\x18\x07 \x01(\r\x12\x1a\n\x12segmentOneDistance\x18\x08 \x01(\x01\x12\x1a\n\x12segmentTwoDistance\x18\t \x01(\x01\"E\n\x10IntersectionType\x12\x0b\n\x07unknown\x10\x00\x12\x05\n\x01T\x10\x01\x12\x05\n\x01L\x10\x02\x12\x05\n\x01\x43\x10\x03\x12\x08\n\x04none\x10\x04\x12\x05\n\x01X\x10\x05*\x90\x01\n\x05\x43olor\x12\x08\n\x04none\x10\x00\x12\n\n\x06orange\x10\x01\x12\n\n\x06yellow\x10\x02\x12\x0b\n\x07skyblue\x10\x03\x12\t\n\x05white\x10\x04\x12\x07\n\x03red\x10\x05\x12\x08\n\x04\x62lue\x10\x06\x12\t\n\x05green\x10\x07\x12\t\n\x05\x62lack\x10\x08\x12\x08\n\x04pink\x10\t\x12\x08\n\x04gray\x10\n\x12\x10\n\x0cyellowOrange\x10\x0b*\x1f\n\x08\x43\x61meraID\x12\x07\n\x03top\x10\x00\x12\n\n\x06\x62ottom\x10\x01*\xa5\x03\n\x07JointID\x12\r\n\tHeadPitch\x10\x00\x12\x0b\n\x07HeadYaw\x10\x01\x12\x11\n\rRShoulderRoll\x10\x02\x12\x11\n\rLShoulderRoll\x10\x03\x12\x12\n\x0eRShoulderPitch\x10\x04\x12\x12\n\x0eLShoulderPitch\x10\x05\x12\x0e\n\nRElbowRoll\x10\x06\x12\x0e\n\nLElbowRoll\x10\x07\x12\r\n\tRElbowYaw\x10\x08\x12\r\n\tLElbowYaw\x10\t\x12\x10\n\x0cRHipYawPitch\x10\n\x12\x10\n\x0cLHipYawPitch\x10\x0b\x12\r\n\tRHipPitch\x10\x0c\x12\r\n\tLHipPitch\x10\r\x12\x0c\n\x08RHipRoll\x10\x0e\x12\x0c\n\x08LHipRoll\x10\x0f\x12\x0e\n\nRKneePitch\x10\x10\x12\x0e\n\nLKneePitch\x10\x11\x12\x0f\n\x0bRAnklePitch\x10\x12\x12\x0f\n\x0bLAnklePitch\x10\x13\x12\x0e\n\nRAnkleRoll\x10\x14\x12\x0e\n\nLAnkleRoll\x10\x15\x12\r\n\tLWristYaw\x10\x16\x12\r\n\tRWristYaw\x10\x17\x12\t\n\x05LHand\x10\x18\x12\t\n\x05RHand\x10\x19\x42\x16\n\x14\x64\x65.naoth.rc.messages') ) _sym_db.RegisterFileDescriptor(DESCRIPTOR) _COLOR = _descriptor.EnumDescriptor( name='Color', full_name='naothmessages.Color', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='none', index=0, number=0, options=None, type=None), _descriptor.EnumValueDescriptor( name='orange', index=1, number=1, options=None, type=None), _descriptor.EnumValueDescriptor( name='yellow', index=2, number=2, options=None, type=None), _descriptor.EnumValueDescriptor( name='skyblue', index=3, number=3, options=None, type=None), _descriptor.EnumValueDescriptor( name='white', index=4, number=4, options=None, type=None), _descriptor.EnumValueDescriptor( name='red', index=5, number=5, options=None, type=None), _descriptor.EnumValueDescriptor( name='blue', index=6, number=6, options=None, type=None), _descriptor.EnumValueDescriptor( name='green', index=7, number=7, options=None, type=None), _descriptor.EnumValueDescriptor( name='black', index=8, number=8, options=None, type=None), _descriptor.EnumValueDescriptor( name='pink', index=9, number=9, options=None, type=None), _descriptor.EnumValueDescriptor( name='gray', index=10, number=10, options=None, type=None), _descriptor.EnumValueDescriptor( name='yellowOrange', index=11, number=11, options=None, type=None), ], containing_type=None, options=None, serialized_start=893, serialized_end=1037, ) _sym_db.RegisterEnumDescriptor(_COLOR) Color = enum_type_wrapper.EnumTypeWrapper(_COLOR) _CAMERAID = _descriptor.EnumDescriptor( name='CameraID', full_name='naothmessages.CameraID', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='top', index=0, number=0, options=None, type=None), _descriptor.EnumValueDescriptor( name='bottom', index=1, number=1, options=None, type=None), ], containing_type=None, options=None, serialized_start=1039, serialized_end=1070, ) _sym_db.RegisterEnumDescriptor(_CAMERAID) CameraID = enum_type_wrapper.EnumTypeWrapper(_CAMERAID) _JOINTID = _descriptor.EnumDescriptor( name='JointID', full_name='naothmessages.JointID', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='HeadPitch', index=0, number=0, options=None, type=None), _descriptor.EnumValueDescriptor( name='HeadYaw', index=1, number=1, options=None, type=None), _descriptor.EnumValueDescriptor( name='RShoulderRoll', index=2, number=2, options=None, type=None), _descriptor.EnumValueDescriptor( name='LShoulderRoll', index=3, number=3, options=None, type=None), _descriptor.EnumValueDescriptor( name='RShoulderPitch', index=4, number=4, options=None, type=None), _descriptor.EnumValueDescriptor( name='LShoulderPitch', index=5, number=5, options=None, type=None), _descriptor.EnumValueDescriptor( name='RElbowRoll', index=6, number=6, options=None, type=None), _descriptor.EnumValueDescriptor( name='LElbowRoll', index=7, number=7, options=None, type=None), _descriptor.EnumValueDescriptor( name='RElbowYaw', index=8, number=8, options=None, type=None), _descriptor.EnumValueDescriptor( name='LElbowYaw', index=9, number=9, options=None, type=None), _descriptor.EnumValueDescriptor( name='RHipYawPitch', index=10, number=10, options=None, type=None), _descriptor.EnumValueDescriptor( name='LHipYawPitch', index=11, number=11, options=None, type=None), _descriptor.EnumValueDescriptor( name='RHipPitch', index=12, number=12, options=None, type=None), _descriptor.EnumValueDescriptor( name='LHipPitch', index=13, number=13, options=None, type=None), _descriptor.EnumValueDescriptor( name='RHipRoll', index=14, number=14, options=None, type=None), _descriptor.EnumValueDescriptor( name='LHipRoll', index=15, number=15, options=None, type=None), _descriptor.EnumValueDescriptor( name='RKneePitch', index=16, number=16, options=None, type=None), _descriptor.EnumValueDescriptor( name='LKneePitch', index=17, number=17, options=None, type=None), _descriptor.EnumValueDescriptor( name='RAnklePitch', index=18, number=18, options=None, type=None), _descriptor.EnumValueDescriptor( name='LAnklePitch', index=19, number=19, options=None, type=None), _descriptor.EnumValueDescriptor( name='RAnkleRoll', index=20, number=20, options=None, type=None), _descriptor.EnumValueDescriptor( name='LAnkleRoll', index=21, number=21, options=None, type=None), _descriptor.EnumValueDescriptor( name='LWristYaw', index=22, number=22, options=None, type=None), _descriptor.EnumValueDescriptor( name='RWristYaw', index=23, number=23, options=None, type=None), _descriptor.EnumValueDescriptor( name='LHand', index=24, number=24, options=None, type=None), _descriptor.EnumValueDescriptor( name='RHand', index=25, number=25, options=None, type=None), ], containing_type=None, options=None, serialized_start=1073, serialized_end=1494, ) _sym_db.RegisterEnumDescriptor(_JOINTID) JointID = enum_type_wrapper.EnumTypeWrapper(_JOINTID) none = 0 orange = 1 yellow = 2 skyblue = 3 white = 4 red = 5 blue = 6 green = 7 black = 8 pink = 9 gray = 10 yellowOrange = 11 top = 0 bottom = 1 HeadPitch = 0 HeadYaw = 1 RShoulderRoll = 2 LShoulderRoll = 3 RShoulderPitch = 4 LShoulderPitch = 5 RElbowRoll = 6 LElbowRoll = 7 RElbowYaw = 8 LElbowYaw = 9 RHipYawPitch = 10 LHipYawPitch = 11 RHipPitch = 12 LHipPitch = 13 RHipRoll = 14 LHipRoll = 15 RKneePitch = 16 LKneePitch = 17 RAnklePitch = 18 LAnklePitch = 19 RAnkleRoll = 20 LAnkleRoll = 21 LWristYaw = 22 RWristYaw = 23 LHand = 24 RHand = 25 _INTERSECTION_INTERSECTIONTYPE = _descriptor.EnumDescriptor( name='IntersectionType', full_name='naothmessages.Intersection.IntersectionType', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='unknown', index=0, number=0, options=None, type=None), _descriptor.EnumValueDescriptor( name='T', index=1, number=1, options=None, type=None), _descriptor.EnumValueDescriptor( name='L', index=2, number=2, options=None, type=None), _descriptor.EnumValueDescriptor( name='C', index=3, number=3, options=None, type=None), _descriptor.EnumValueDescriptor( name='none', index=4, number=4, options=None, type=None), _descriptor.EnumValueDescriptor( name='X', index=5, number=5, options=None, type=None), ], containing_type=None, options=None, serialized_start=821, serialized_end=890, ) _sym_db.RegisterEnumDescriptor(_INTERSECTION_INTERSECTIONTYPE) _FLOATVECTOR2 = _descriptor.Descriptor( name='FloatVector2', full_name='naothmessages.FloatVector2', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='x', full_name='naothmessages.FloatVector2.x', index=0, number=1, type=2, cpp_type=6, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='y', full_name='naothmessages.FloatVector2.y', index=1, number=2, type=2, cpp_type=6, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=36, serialized_end=72, ) _DOUBLEVECTOR2 = _descriptor.Descriptor( name='DoubleVector2', full_name='naothmessages.DoubleVector2', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='x', full_name='naothmessages.DoubleVector2.x', index=0, number=1, type=1, cpp_type=5, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='y', full_name='naothmessages.DoubleVector2.y', index=1, number=2, type=1, cpp_type=5, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=74, serialized_end=111, ) _INTVECTOR2 = _descriptor.Descriptor( name='IntVector2', full_name='naothmessages.IntVector2', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='x', full_name='naothmessages.IntVector2.x', index=0, number=1, type=5, cpp_type=1, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='y', full_name='naothmessages.IntVector2.y', index=1, number=2, type=5, cpp_type=1, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=113, serialized_end=147, ) _POSE2D = _descriptor.Descriptor( name='Pose2D', full_name='naothmessages.Pose2D', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='translation', full_name='naothmessages.Pose2D.translation', index=0, number=1, type=11, cpp_type=10, label=2, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='rotation', full_name='naothmessages.Pose2D.rotation', index=1, number=2, type=1, cpp_type=5, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=149, serialized_end=226, ) _DOUBLEVECTOR3 = _descriptor.Descriptor( name='DoubleVector3', full_name='naothmessages.DoubleVector3', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='x', full_name='naothmessages.DoubleVector3.x', index=0, number=1, type=1, cpp_type=5, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='y', full_name='naothmessages.DoubleVector3.y', index=1, number=2, type=1, cpp_type=5, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='z', full_name='naothmessages.DoubleVector3.z', index=2, number=3, type=1, cpp_type=5, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=228, serialized_end=276, ) _DOUBLEVECTOR = _descriptor.Descriptor( name='DoubleVector', full_name='naothmessages.DoubleVector', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='v', full_name='naothmessages.DoubleVector.v', index=0, number=1, type=1, cpp_type=5, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=278, serialized_end=303, ) _POSE3D = _descriptor.Descriptor( name='Pose3D', full_name='naothmessages.Pose3D', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='translation', full_name='naothmessages.Pose3D.translation', index=0, number=1, type=11, cpp_type=10, label=2, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='rotation', full_name='naothmessages.Pose3D.rotation', index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=305, serialized_end=412, ) _LINESEGMENT = _descriptor.Descriptor( name='LineSegment', full_name='naothmessages.LineSegment', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='base', full_name='naothmessages.LineSegment.base', index=0, number=1, type=11, cpp_type=10, label=2, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='direction', full_name='naothmessages.LineSegment.direction', index=1, number=2, type=11, cpp_type=10, label=2, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='length', full_name='naothmessages.LineSegment.length', index=2, number=3, type=1, cpp_type=5, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=414, serialized_end=536, ) _INTERSECTION = _descriptor.Descriptor( name='Intersection', full_name='naothmessages.Intersection', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='posInImage', full_name='naothmessages.Intersection.posInImage', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='posOnField', full_name='naothmessages.Intersection.posOnField', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='type', full_name='naothmessages.Intersection.type', index=2, number=3, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='segmentOneIndex', full_name='naothmessages.Intersection.segmentOneIndex', index=3, number=6, type=13, cpp_type=3, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='segmentTwoIndex', full_name='naothmessages.Intersection.segmentTwoIndex', index=4, number=7, type=13, cpp_type=3, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='segmentOneDistance', full_name='naothmessages.Intersection.segmentOneDistance', index=5, number=8, type=1, cpp_type=5, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='segmentTwoDistance', full_name='naothmessages.Intersection.segmentTwoDistance', index=6, number=9, type=1, cpp_type=5, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ _INTERSECTION_INTERSECTIONTYPE, ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=539, serialized_end=890, ) _POSE2D.fields_by_name['translation'].message_type = _DOUBLEVECTOR2 _POSE3D.fields_by_name['translation'].message_type = _DOUBLEVECTOR3 _POSE3D.fields_by_name['rotation'].message_type = _DOUBLEVECTOR3 _LINESEGMENT.fields_by_name['base'].message_type = _DOUBLEVECTOR2 _LINESEGMENT.fields_by_name['direction'].message_type = _DOUBLEVECTOR2 _INTERSECTION.fields_by_name['posInImage'].message_type = _DOUBLEVECTOR2 _INTERSECTION.fields_by_name['posOnField'].message_type = _DOUBLEVECTOR2 _INTERSECTION.fields_by_name['type'].enum_type = _INTERSECTION_INTERSECTIONTYPE _INTERSECTION_INTERSECTIONTYPE.containing_type = _INTERSECTION DESCRIPTOR.message_types_by_name['FloatVector2'] = _FLOATVECTOR2 DESCRIPTOR.message_types_by_name['DoubleVector2'] = _DOUBLEVECTOR2 DESCRIPTOR.message_types_by_name['IntVector2'] = _INTVECTOR2 DESCRIPTOR.message_types_by_name['Pose2D'] = _POSE2D DESCRIPTOR.message_types_by_name['DoubleVector3'] = _DOUBLEVECTOR3 DESCRIPTOR.message_types_by_name['DoubleVector'] = _DOUBLEVECTOR DESCRIPTOR.message_types_by_name['Pose3D'] = _POSE3D DESCRIPTOR.message_types_by_name['LineSegment'] = _LINESEGMENT DESCRIPTOR.message_types_by_name['Intersection'] = _INTERSECTION DESCRIPTOR.enum_types_by_name['Color'] = _COLOR DESCRIPTOR.enum_types_by_name['CameraID'] = _CAMERAID DESCRIPTOR.enum_types_by_name['JointID'] = _JOINTID FloatVector2 = _reflection.GeneratedProtocolMessageType('FloatVector2', (_message.Message,), dict( DESCRIPTOR = _FLOATVECTOR2, __module__ = 'CommonTypes_pb2' # @@protoc_insertion_point(class_scope:naothmessages.FloatVector2) )) _sym_db.RegisterMessage(FloatVector2) DoubleVector2 = _reflection.GeneratedProtocolMessageType('DoubleVector2', (_message.Message,), dict( DESCRIPTOR = _DOUBLEVECTOR2, __module__ = 'CommonTypes_pb2' # @@protoc_insertion_point(class_scope:naothmessages.DoubleVector2) )) _sym_db.RegisterMessage(DoubleVector2) IntVector2 = _reflection.GeneratedProtocolMessageType('IntVector2', (_message.Message,), dict( DESCRIPTOR = _INTVECTOR2, __module__ = 'CommonTypes_pb2' # @@protoc_insertion_point(class_scope:naothmessages.IntVector2) )) _sym_db.RegisterMessage(IntVector2) Pose2D = _reflection.GeneratedProtocolMessageType('Pose2D', (_message.Message,), dict( DESCRIPTOR = _POSE2D, __module__ = 'CommonTypes_pb2' # @@protoc_insertion_point(class_scope:naothmessages.Pose2D) )) _sym_db.RegisterMessage(Pose2D) DoubleVector3 = _reflection.GeneratedProtocolMessageType('DoubleVector3', (_message.Message,), dict( DESCRIPTOR = _DOUBLEVECTOR3, __module__ = 'CommonTypes_pb2' # @@protoc_insertion_point(class_scope:naothmessages.DoubleVector3) )) _sym_db.RegisterMessage(DoubleVector3) DoubleVector = _reflection.GeneratedProtocolMessageType('DoubleVector', (_message.Message,), dict( DESCRIPTOR = _DOUBLEVECTOR, __module__ = 'CommonTypes_pb2' # @@protoc_insertion_point(class_scope:naothmessages.DoubleVector) )) _sym_db.RegisterMessage(DoubleVector) Pose3D = _reflection.GeneratedProtocolMessageType('Pose3D', (_message.Message,), dict( DESCRIPTOR = _POSE3D, __module__ = 'CommonTypes_pb2' # @@protoc_insertion_point(class_scope:naothmessages.Pose3D) )) _sym_db.RegisterMessage(Pose3D) LineSegment = _reflection.GeneratedProtocolMessageType('LineSegment', (_message.Message,), dict( DESCRIPTOR = _LINESEGMENT, __module__ = 'CommonTypes_pb2' # @@protoc_insertion_point(class_scope:naothmessages.LineSegment) )) _sym_db.RegisterMessage(LineSegment) Intersection = _reflection.GeneratedProtocolMessageType('Intersection', (_message.Message,), dict( DESCRIPTOR = _INTERSECTION, __module__ = 'CommonTypes_pb2' # @@protoc_insertion_point(class_scope:naothmessages.Intersection) )) _sym_db.RegisterMessage(Intersection) DESCRIPTOR.has_options = True DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\024de.naoth.rc.messages')) # @@protoc_insertion_point(module_scope)
33.752577
2,876
0.723885
e6df87fe50ce8ffd8f0096f9440651f2b9260afc
2,366
py
Python
travelplanner/command.py
UCL/mphy0021-2019-travel-planner-sukrire
5f8b3479b858c46a01b68ee866560dd28d5be47a
[ "MIT" ]
null
null
null
travelplanner/command.py
UCL/mphy0021-2019-travel-planner-sukrire
5f8b3479b858c46a01b68ee866560dd28d5be47a
[ "MIT" ]
null
null
null
travelplanner/command.py
UCL/mphy0021-2019-travel-planner-sukrire
5f8b3479b858c46a01b68ee866560dd28d5be47a
[ "MIT" ]
null
null
null
from argparse import ArgumentParser from travelplanner.read_passengers import Read_passengers, Read_route from travelplanner.Passenger import Passenger from travelplanner.Route import Route from travelplanner.Journey import Journey import numpy as np import matplotlib.pyplot as plt import travelplanner def process(): parser = ArgumentParser(description='travelplanner') parser.add_argument('routefile', type=str, help='Please give full pathname to route.csv') parser.add_argument('passfile', type=str, help='Please give full pathname to passenger.csv') parser.add_argument('--speed', default=10, type=int, help='Give the speed of the bus, lower is faster') parser.add_argument('--saveplots', action='store_true', help='Optional, If given, save the plots.') arguments = parser.parse_args() pft = travelplanner.Journey(arguments.routefile, arguments.passfile, speed=arguments.speed) route_for_timetable = travelplanner.Route(arguments.routefile, speed=arguments.speed) timetable = route_for_timetable.timetable() stoptimes = [stop[1] for stop in timetable if stop[0]] stoplabels = [label[0] for label in timetable if label[0]] for i in range(len(stoptimes)): print("Bus Stop:", stoplabels[i], "Bus will arrive at", stoptimes[i], "mins") for j in range(len(pft.passenger.passengers)): if pft.passenger_trip_time(j)[1] == 0: print("Passenger no:", [j+1], "will walk for", pft.travel_time()[j][0], "mins") else: print("Passenger no:", [j+1], "will get on at stop:", pft.timetable[pft.passenger_trip(j)[0][1]][0], "and will get off at stop", pft.timetable[pft.passenger_trip(j)[1][1]][0], "\n", "they will walk for:", pft.travel_time()[i][0], "mins", "\n", "and will be on the bus for", pft.travel_time()[i][1], "mins") if arguments.saveplots: route_map = route_for_timetable.plot_map() plt.savefig('./map.png') bus_load_map = pft.plot_bus_load() plt.savefig('./load.png') if __name__ == "__main__": process()
43.018182
79
0.607354
fc052d37ff94f3d18eb956597d7e8ea3df108603
5,999
py
Python
src/visuanalytics/tests/analytics/transform/types/test_transform_compare.py
mxsph/Data-Analytics
c82ff54b78f50b6660d7640bfee96ea68bef598f
[ "MIT" ]
3
2020-08-24T19:02:09.000Z
2021-05-27T20:22:41.000Z
src/visuanalytics/tests/analytics/transform/types/test_transform_compare.py
mxsph/Data-Analytics
c82ff54b78f50b6660d7640bfee96ea68bef598f
[ "MIT" ]
342
2020-08-13T10:24:23.000Z
2021-08-12T14:01:52.000Z
src/visuanalytics/tests/analytics/transform/types/test_transform_compare.py
visuanalytics/visuanalytics
f9cce7bc9e3227568939648ddd1dd6df02eac752
[ "MIT" ]
8
2020-09-01T07:11:18.000Z
2021-04-09T09:02:11.000Z
import unittest from visuanalytics.tests.analytics.transform.transform_test_helper import prepare_test class TestTransformCompare(unittest.TestCase): def setUp(self): self.data = { "value1": 5, "value2": 5, "value3": 30, "text1": "result" } def test_transform_compare_equal(self): values = [ { "type": "compare", "value_left": "_req|value1", "value_right": "_req|value2", "on_equal": [ { "type": "replace", "keys": ["_req|text1"], "old_value": "result", "new_value": "equal" } ], "on_higher": [ { "type": "replace", "keys": ["_req|text1"], "old_value": "result", "new_value": "value_left is higher" } ], "on_lower": [ { "type": "replace", "keys": ["_req|text1"], "old_value": "result", "new_value": "value_left is lower" } ] } ] expected_data = { "_req": { "value1": 5, "value2": 5, "value3": 30, "text1": "equal" } } exp, out = prepare_test(values, self.data, expected_data) self.assertDictEqual(exp, out, "compare equal Failed") def test_transform_compare_not_equal(self): values = [ { "type": "compare", "value_left": "_req|value1", "value_right": "_req|value3", "on_not_equal": [ { "type": "replace", "keys": ["_req|text1"], "old_value": "result", "new_value": "not equal" } ], "on_higher": [ { "type": "replace", "keys": ["_req|text1"], "old_value": "result", "new_value": "value_left is higher" } ], "on_lower": [ { "type": "replace", "keys": ["_req|text1"], "old_value": "result", "new_value": "value_left is lower" } ] } ] expected_data = { "_req": { "value1": 5, "value2": 5, "value3": 30, "text1": "not equal" } } exp, out = prepare_test(values, self.data, expected_data) self.assertDictEqual(exp, out, "compare not equal Failed") def test_transform_compare_higher(self): values = [ { "type": "compare", "value_left": "_req|value3", "value_right": "_req|value2", "on_equal": [ { "type": "replace", "keys": ["_req|text1"], "old_value": "result", "new_value": "equal" } ], "on_higher": [ { "type": "replace", "keys": ["_req|text1"], "old_value": "result", "new_value": "value_left is higher" } ], "on_lower": [ { "type": "replace", "keys": ["_req|text1"], "old_value": "result", "new_value": "value_left is lower" } ] } ] expected_data = { "_req": { "value1": 5, "value2": 5, "value3": 30, "text1": "value_left is higher" } } exp, out = prepare_test(values, self.data, expected_data) self.assertDictEqual(exp, out, "compare higher Failed") def test_transform_compare_lower(self): values = [ { "type": "compare", "value_left": "_req|value2", "value_right": "_req|value3", "on_equal": [ { "type": "replace", "keys": ["_req|text1"], "old_value": "result", "new_value": "equal" } ], "on_higher": [ { "type": "replace", "keys": ["_req|text1"], "old_value": "result", "new_value": "value_left is higher" } ], "on_lower": [ { "type": "replace", "keys": ["_req|text1"], "old_value": "result", "new_value": "value_left is lower" } ] } ] expected_data = { "_req": { "value1": 5, "value2": 5, "value3": 30, "text1": "value_left is lower" } } exp, out = prepare_test(values, self.data, expected_data) self.assertDictEqual(exp, out, "compare lower Failed")
30.92268
86
0.331222
fca1e76f827983a13f40b05e5e1e90b1176cfbcb
421
py
Python
day05/avgHeights.py
nurmatthias/100DaysOfCode
22002e4b31d13e6b52e6b9222d2e91c2070c5744
[ "Apache-2.0" ]
null
null
null
day05/avgHeights.py
nurmatthias/100DaysOfCode
22002e4b31d13e6b52e6b9222d2e91c2070c5744
[ "Apache-2.0" ]
null
null
null
day05/avgHeights.py
nurmatthias/100DaysOfCode
22002e4b31d13e6b52e6b9222d2e91c2070c5744
[ "Apache-2.0" ]
null
null
null
# 🚨 Don't change the code below 👇 student_heights = input("Input a list of student heights ").split() for n in range(0, len(student_heights)): student_heights[n] = int(student_heights[n]) # 🚨 Don't change the code above 👆 #Write your code below this row 👇 allHeights = 0 entryCounter = 0 for height in student_heights: allHeights += height entryCounter += 1 print(f"avg. height is {allHeights/entryCounter}")
28.066667
67
0.719715
5d8dd2a6dfa3ccc8b4909cc0044d3ee37a0df641
7,325
py
Python
src/test/tests/databases/timesliders.py
visit-dav/vis
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
[ "BSD-3-Clause" ]
226
2018-12-29T01:13:49.000Z
2022-03-30T19:16:31.000Z
src/test/tests/databases/timesliders.py
visit-dav/vis
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
[ "BSD-3-Clause" ]
5,100
2019-01-14T18:19:25.000Z
2022-03-31T23:08:36.000Z
src/test/tests/databases/timesliders.py
visit-dav/vis
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
[ "BSD-3-Clause" ]
84
2019-01-24T17:41:50.000Z
2022-03-10T10:01:46.000Z
# ---------------------------------------------------------------------------- # CLASSES: nightly # # Test Case: timesliders.py # # Tests: mesh - 2D, curvilinear, single domain # plots - FilledBoundary # databases - PDB # # Purpose: This test case tests out using multiple time sliders. # # Programmer: Brad Whitlock # Date: Fri Mar 19 11:45:12 PDT 2004 # # Modifications: # Brad Whitlock, Wed Mar 31 10:34:27 PDT 2004 # I changed the calls to SetActiveTimeSlider so they can accept the # unexpanded database names instead of requiring fully qualified # database names. # # Brad Whitlock, Mon Apr 19 09:20:29 PDT 2004 # I added a few more tests to make sure we get the desired list of time # sliders under more conditions. # # Brad Whitlock, Wed Feb 9 11:10:29 PDT 2005 # I added another test section to make sure that we get the right time # sliders (or lack of) after deleting plots. # # Brad Whitlock, Thu Dec 21 11:57:52 PDT 2006 # Added code to make sure that the dictionary keys in one of the tests # are always sorted. # # Mark C. Miller, Wed Jan 20 07:37:11 PST 2010 # Added ability to switch between Silo's HDF5 and PDB data. # ---------------------------------------------------------------------------- # # Look at the first few lines of the string representation of the # WindowInformation to see the list of time sliders, etc. # def TestWindowInformation(testname): # Get the window information and convert it to a string. s = str(GetWindowInformation()) # Only use the first 5 or so lines from the string. lines = s.split("\n") s = "" for i in range(5): if(i < len(lines)): s = s + lines[i] s = s + "\n" TestText(testname, s) def SetTheView(): v0 = View3DAttributes() v0.viewNormal = (-0.735926, 0.562657, 0.376604) v0.focus = (5, 0.753448, 2.5) v0.viewUp = (0.454745, 0.822858, -0.340752) v0.viewAngle = 30 v0.parallelScale = 5.6398 v0.nearPlane = -11.2796 v0.farPlane = 11.2796 v0.imagePan = (0.0589778, 0.0898255) v0.imageZoom = 1.32552 v0.perspective = 1 v0.eyeAngle = 2 SetView3D(v0) # Print the dictionary so its keys are always sorted a particular way. def PrintDict(dict): keys = list(dict.keys()) keys.sort() s = "{" i = 0 for k in keys: if type(k) == type(str("")): kstr = "'" + str(k) + "'" else: kstr = str(k) s = s + kstr + ": " + str(dict[k]) if i < len(keys)-1: s = s + ", " i = i + 1 s = s + "}" return s # The plotted databases. dbs = (data_path("pdb_test_data/dbA00.pdb"), data_path("pdb_test_data/dbB00.pdb"), data_path("pdb_test_data/dbC00.pdb")) # Create a plot from one database TestSection("Set time using different time sliders") OpenDatabase(dbs[0]) AddPlot("FilledBoundary", "material(mesh)") DrawPlots() Test("timesliders00") TestWindowInformation("timesliders01") # Create a plot from another database OpenDatabase(dbs[1]) AddPlot("FilledBoundary", "material(mesh)") DrawPlots() Test("timesliders02") TestWindowInformation("timesliders03") # Change the time state for the second time slider. # note: py3 div creates float SetTimeSliderState(int(TimeSliderGetNStates() / 2)) Test("timesliders04") TestWindowInformation("timesliders05") # Make sure that GetTimeSliders returned the right dictionary. testString = "GetTimeSliders returned:\n %s" % PrintDict(GetTimeSliders()) TestText("timesliders06", testString) # Set the time slider back to the first time slider. SetActiveTimeSlider(dbs[0]) # Set the time state for the first time slider. SetTimeSliderState(7) Test("timesliders07") TestWindowInformation("timesliders08") # Create a database correlation for the first two databases. This correlation # will be an IndexForIndex correlation since we passed 0 for the correlation # method. TestSection("Time slider behavior with a correlation") correlation1 = "A_and_B" CreateDatabaseCorrelation(correlation1, dbs[:-1], 0) SetActiveTimeSlider(correlation1) Test("timesliders09") TestWindowInformation("timesliders10") # Set the time state for the active time slider since it is now the A_and_B # database correlation. SetTimeSliderState(0) Test("timesliders11") TestWindowInformation("timesliders12") SetTimeSliderState(5) Test("timesliders13") TestWindowInformation("timesliders14") SetTimeSliderState(19) Test("timesliders15") TestWindowInformation("timesliders16") # Set the time slider to B. Only B should change. SetActiveTimeSlider(dbs[1]) SetTimeSliderState(5) Test("timesliders17") TestWindowInformation("timesliders18") # Add a new window and make sure that the time sliders are copied to it. TestSection("Make sure cloned window gets time sliders") CloneWindow() SetActiveWindow(2) DrawPlots() Test("timesliders19") TestWindowInformation("timesliders20") SetTimeSliderState(19) Test("timesliders21") TestWindowInformation("timesliders22") DeleteWindow() # Make sure switching between different databases give the right time sliders. TestSection("Make sure opening ST database clears time slider list") DeleteAllPlots() OpenDatabase(dbs[0]) SetTimeSliderState(0) TestWindowInformation("timesliders23") OpenDatabase(silo_data_path("curv2d.silo")) AddPlot("Pseudocolor", "u") DrawPlots() ResetView() Test("timesliders24") TestWindowInformation("timesliders25") # Make sure doing various replace sequences give the right time sliders. TestSection("Make sure replace sequences give right time sliders") DeleteAllPlots() OpenDatabase(dbs[0]) AddPlot("FilledBoundary", "material(mesh)") DrawPlots() Test("timesliders26") TestWindowInformation("timesliders27") ReplaceDatabase(dbs[1]) Test("timesliders28") TestWindowInformation("timesliders29") ReplaceDatabase(dbs[0]) Test("timesliders30") # There should only be 1 time slider at this point. TestWindowInformation("timesliders31") # Make sure that when we replace an MT database with an ST database, we get # the right time sliders. DeleteAllPlots() OpenDatabase(silo_data_path("wave*.silo database"), 30) AddPlot("Pseudocolor", "pressure") DrawPlots() SetTheView() Test("timesliders32") TestWindowInformation("timesliders33") # Replace with an ST database ReplaceDatabase(silo_data_path("wave0000.silo")) Test("timesliders34") TestWindowInformation("timesliders35") # Make sure that we get the right time sliders after we delete plots. TestSection("Make sure we get the right time sliders after deleting plots.") DeleteAllPlots() # Close all the sources so we get fresh time sliders. for source in GetGlobalAttributes().sources: CloseDatabase(source) OpenDatabase(silo_data_path("wave.visit")) AddPlot("Pseudocolor", "pressure") OpenDatabase(silo_data_path("curv3d.silo")) AddPlot("Pseudocolor", "p") DrawPlots() ResetView() v = GetView3D() v.viewNormal = (0.163324, 0.442866, 0.881586) v.viewUp = (-0.0889191, 0.896556, -0.433913) v.parallelScale = 16.9558 v.imagePan = (0.0834786, 0.0495278) v.imageZoom = 1.53171 SetView3D(v) Test("timesliders36") TestWindowInformation("timesliders37") SetActivePlots(0) DeleteActivePlots() Test("timesliders38") TestWindowInformation("timesliders39") DeleteActivePlots() TestWindowInformation("timesliders40") Exit()
29.65587
78
0.710034
5d69b1f00bd8c76d6fb50568daafff6e0e70b933
1,311
py
Python
PINp/2014/Platonova Olga/task_9_21.py
YukkaSarasti/pythonintask
eadf4245abb65f4400a3bae30a4256b4658e009c
[ "Apache-2.0" ]
null
null
null
PINp/2014/Platonova Olga/task_9_21.py
YukkaSarasti/pythonintask
eadf4245abb65f4400a3bae30a4256b4658e009c
[ "Apache-2.0" ]
null
null
null
PINp/2014/Platonova Olga/task_9_21.py
YukkaSarasti/pythonintask
eadf4245abb65f4400a3bae30a4256b4658e009c
[ "Apache-2.0" ]
null
null
null
# Задача 9. Вариант 21. #Создайте игру, в которой компьютер выбирает какое-либо слово, а игрок должен его отгадать. Компьютер сообщает игроку, сколько букв в слове, и дает пять попыток узнать, есть ли какая-либо буква в слове, причем программа может отвечать только "Да" и "Нет". Вслед за тем игрок должен попробовать отгадать слово. # Platonova O. A. # 29.05.2016 import random words=("кортежи","списки","словари","циклы","ветвление","работа","компьютер") compword=random.choice(words) live=5 letter="" number=len(compword) if 10<=number<=20 or number%10==0 or 5<=number%10<=9: ok='' elif number%10==1: ok="а" else: ok="ы" print("Я загадал слово, угадайте его. В этом слове",number,"букв"+ok+".") print("У вас",live,"попыток, чтобы угадать буквы") while live>0: letter=input("Введите букву\n") if letter in list(compword): print("Да.") live=live-1 else: print("Нет.") live=live-1 if 10<=live<=20 or live%10==0 or 5<=live%10<=9: ok='ок' elif live%10==1: ok="а" else: ok="и" print("Осталось",live,"попыт"+ok) if live==0: myword=input("А теперь вам пора угадать слово!") if myword==compword: print("Вы угадали слово") else: print("Вы не угадали слово") input("Нажмите Enter для выхода.")
31.214286
309
0.64836
5395ebb61f6806eeee6a318809a595ce4cae0133
10,566
py
Python
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/plugins/modules/onyx_username.py
tr3ck3r/linklight
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
[ "MIT" ]
null
null
null
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/plugins/modules/onyx_username.py
tr3ck3r/linklight
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
[ "MIT" ]
null
null
null
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/plugins/modules/onyx_username.py
tr3ck3r/linklight
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
[ "MIT" ]
null
null
null
#!/usr/bin/python # # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: onyx_username author: "Anas Shami (@anass)" short_description: Configure username module description: - This module provides declarative management of users/roles on Mellanox ONYX network devices. notes: options: username: description: - Create/Edit user using username type: str required: True full_name: description: - Set the full name of this user type: str nopassword: description: - Clear password for such user type: bool default: False password: description: - Set password fot such user type: str encrypted_password: description: - Decide the type of setted password (plain text or encrypted) type: bool default: False capability: description: - Grant capability to this user account type: str choices: ['monitor', 'unpriv', 'v_admin', 'admin'] reset_capability: description: - Reset capability to this user account type: bool default: False disconnected: description: - Disconnect all sessions of this user type: bool default: False disabled: description: - Disable means of logging into this account type: str choices: ['none', 'login', 'password', 'all'] state: description: - Set state of the given account default: present type: str choices: ['present', 'absent'] ''' EXAMPLES = """ - name: create new user onyx_username: username: anass - name: set the user full-name onyx_username: username: anass full_name: anasshami - name: set the user encrypted password onyx_username: username: anass password: 12345 encrypted_password: True - name: set the user capability onyx_username: username: anass capability: monitor - name: reset the user capability onyx_username: username: anass reset_capability: True - name: remove the user configuration onyx_username: username: anass state: absent """ RETURN = """ commands: description: The list of configuration mode commands to send to the device. returned: always type: list sample: - username * - username * password * - username * nopassword - username * disable login - username * capability admin - no username * - no username * disable """ import re from ansible.module_utils.basic import AnsibleModule from ansible_collections.community.general.plugins.module_utils.network.onyx.onyx import BaseOnyxModule, show_cmd class OnyxUsernameModule(BaseOnyxModule): ACCOUNT_STATE = { 'Account locked out': dict(disabled='all'), 'No password required for login': dict(nopassword=True), 'Local password login disabled': dict(disabled='password'), 'Account disabled': dict(disabled='all') } ENCRYPTED_ID = 7 def init_module(self): """ module initialization """ element_spec = dict() argument_spec = dict(state=dict(choices=['absent', 'present'], default='present'), username=dict(type='str', required=True), disabled=dict(choices=['none', 'login', 'password', 'all']), capability=dict(choices=['monitor', 'unpriv', 'v_admin', 'admin']), nopassword=dict(type='bool', default=False), password=dict(type='str', no_log=True), encrypted_password=dict(type='bool', default=False), reset_capability=dict(type="bool", default=False), disconnected=dict(type='bool', default=False), full_name=dict(type='str')) argument_spec.update(element_spec) self._module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, mutually_exclusive=[['password', 'nopassword']]) def get_required_config(self): self._required_config = dict() module_params = self._module.params params = {} ''' Requred/Default fields ''' params['username'] = module_params.get('username') params['state'] = module_params.get('state') params['encrypted_password'] = module_params.get('encrypted_password') params['reset_capability'] = module_params.get('reset_capability') ''' Other fields ''' for key, value in module_params.items(): if value is not None: params[key] = value self.validate_param_values(params) self._required_config = params def _get_username_config(self): return show_cmd(self._module, "show usernames", json_fmt=True, fail_on_error=False) def _set_current_config(self, users_config): ''' users_config ex: { admin": [ { "CAPABILITY": "admin", "ACCOUNT STATUS": "No password required for login", "FULL NAME": "System Administrator" } ], } ''' if not users_config: return current_config = self._current_config for username, config in users_config.items(): config_json = config[0] current_config[username] = current_config.get(username, {}) account_status = config_json.get('ACCOUNT STATUS') status_value = self.ACCOUNT_STATE.get(account_status) if status_value is not None: # None for enabled account with password account "Password set (SHA512 | MD5)" so we won't change any attribute here. current_config[username].update(status_value) current_config[username].update({ 'capability': config_json.get('CAPABILITY'), 'full_name': config_json.get('FULL NAME') }) def load_current_config(self): self._current_config = dict() users_config = self._get_username_config() self._set_current_config(users_config) def generate_commands(self): current_config, required_config = self._current_config, self._required_config username = required_config.get('username') current_user = current_config.get(username) if current_user is not None: '''created account we just need to edit his attributes''' full_name = required_config.get('full_name') if full_name is not None and current_user.get('full_name') != full_name: self._commands.append("username {0} full-name {1}".format(username, full_name)) disabled = required_config.get('disabled') if disabled is not None and current_user.get('disabled') != disabled: if disabled == 'none': self._commands.append("no username {0} disable".format(username)) elif disabled == 'all': self._commands.append("username {0} disable".format(username)) else: self._commands.append("username {0} disable {1}".format(username, disabled)) state = required_config.get('state') if state == 'absent': # this will remove the user self._commands.append("no username {0}".format(username)) capability = required_config.get('capability') if capability is not None and current_user.get('capability') != capability: self._commands.append("username {0} capability {1}".format(username, capability)) reset_capability = required_config.get('reset_capability') if reset_capability: self._commands.append("no username {0} capability".format(username)) password = required_config.get('password') if password is not None: encrypted = required_config.get('encrypted_password') if encrypted: self._commands.append("username {0} password {1} {2}".format(username, self.ENCRYPTED_ID, password)) else: self._commands.append("username {0} password {1}".format(username, password)) nopassword = required_config.get('nopassword') if nopassword and nopassword != current_user.get('nopassword', False): self._commands.append("username {0} nopassword".format(username)) disconnected = required_config.get('disconnected') if disconnected: self._commands.append("username {0} disconnect".format(username)) else: '''create new account if we have valid inforamtion, just check for username, capability, full_name, password''' capability = required_config.get('capability') password = required_config.get('password') full_name = required_config.get('full_name') if capability is not None or password is not None or full_name is not None: if capability is not None: self._commands.append("username {0} capability {1}".format(username, capability)) if password is not None: encrypted = required_config.get('encrypted_password') if encrypted: self._commands.append("username {0} password {1} {2} ".format(username, self.ENCRYPTED_ID, password)) else: self._commands.append("username {0} password {1}".format(username, password)) if full_name is not None: self._commands.append("username {0} full-name {1}".format(username, full_name)) else: self._commands.append("username {0}".format(username)) def main(): """ main entry point for module execution """ OnyxUsernameModule.main() if __name__ == '__main__': main()
36.434483
134
0.598902
53cfabf7a5cc02abd2fe30486782b6d0585be1ad
15,305
py
Python
Packs/CrowdStrikeFalconSandbox/Integrations/CrowdstrikeFalconSandboxV2/CrowdStrikeFalconSandboxV2_test.py
cstone112/content
7f039931b8cfc20e89df52d895440b7321149a0d
[ "MIT" ]
2
2021-12-06T21:38:24.000Z
2022-01-13T08:23:36.000Z
Packs/CrowdStrikeFalconSandbox/Integrations/CrowdstrikeFalconSandboxV2/CrowdStrikeFalconSandboxV2_test.py
cstone112/content
7f039931b8cfc20e89df52d895440b7321149a0d
[ "MIT" ]
87
2022-02-23T12:10:53.000Z
2022-03-31T11:29:05.000Z
Packs/CrowdStrikeFalconSandbox/Integrations/CrowdstrikeFalconSandboxV2/CrowdStrikeFalconSandboxV2_test.py
cstone112/content
7f039931b8cfc20e89df52d895440b7321149a0d
[ "MIT" ]
2
2022-01-05T15:27:01.000Z
2022-02-01T19:27:43.000Z
import io import json import pytest from freezegun import freeze_time import demistomock as demisto from CommonServerPython import Common, ScheduledCommand, DBotScoreReliability from CrowdStrikeFalconSandboxV2 import Client, \ validated_search_terms, get_search_term_args, split_query_to_term_args, crowdstrike_result_command, \ crowdstrike_scan_command, map_dict_keys, BWCFile, crowdstrike_submit_url_command, crowdstrike_submit_sample_command, \ get_api_id, get_submission_arguments, crowdstrike_analysis_overview_summary_command, \ crowdstrike_analysis_overview_command, get_default_file_name, validated_term, \ crowdstrike_analysis_overview_refresh_command, main BASE_URL = 'https://test.com' def util_load_json(path): with io.open(path, mode='r', encoding='utf-8') as f: return json.loads(f.read()) client = Client(base_url=BASE_URL, verify=False, proxy=False, headers={}) def test_validated_term(): assert 'USA' == validated_term('country', 'USA') assert 1 == validated_term('verdict', 'Whitelisted') def test_validated_search_terms(): """ Given: - query arguments that need to be converted When: - Turning demisto args into query args Then: - We get proper key-val pairs """ pre_validation = {"hello": "world", "verdict": 'NoSpecificThreat'} post_validation = validated_search_terms(pre_validation) assert post_validation == {'hello': 'world', 'verdict': 3} def test_validated_search_terms_bad_arg(): """ Given: - A bad country code When: - Turning demisto args into query args Then: - We get an error """ pre_validation = {"country": "US", "verdict": 'NoSpecificThreat'} with pytest.raises(ValueError) as e: validated_search_terms(pre_validation) if not e: assert False else: assert e.value.args[0] == 'Country ISO code should be 3 characters long' @pytest.mark.parametrize('demisto_args, st_args', [ ({'query': 'country:USA,port:8080'}, {'country': 'USA', 'port': '8080'}), ({'country': 'USA', 'port': '8080'}, {'country': 'USA', 'port': '8080'})]) def test_get_search_term_args(demisto_args, st_args): """ Given: - arguments coming in as query or not When: - Turning demisto args into query args Then: - We get results regardless of how it came in """ assert st_args == get_search_term_args(demisto_args) @pytest.mark.parametrize('query_string, query_dict', [('hello:world,three:split:fine,heelo:, another: arg ', {'hello': 'world', 'three': 'split:fine', 'another': 'arg'}), ('arg1 :val1, arg2: val2 ', {'arg1': 'val1', 'arg2': 'val2'}) ]) def test_split_query_to_term_args(query_string, query_dict): """ Given: - arguments coming in as joint query string When: - Turning demisto args into query args Then: - Query argument gets parsed properly """ assert query_dict == split_query_to_term_args(query_string) @pytest.mark.parametrize('state', ['IN_PROGRESS', 'IN_QUEUE']) def test_results_poll_state_polling_true(state, mocker, requests_mock): """ Given: - result request, polling true When: - result response in progress Then: - Get a scheduledcommand result """ mocker.patch.object(ScheduledCommand, 'raise_error_if_not_supported') key = "dummy_key" filetype = "pdf" args = {'JobID': key, 'polling': True, 'file-type': 'pdf'} requests_mock.get(BASE_URL + f"/report/{key}/report/{filetype}", status_code=404) state_call = requests_mock.get(BASE_URL + f"/report/{key}/state", json={'state': state}) response = crowdstrike_result_command(client, args) sc = response.scheduled_command assert state_call.called assert sc._args['polling'] assert sc._args['JobID'] == key assert sc._args['file-type'] == filetype assert sc._args['hide_polling_output'] def test_results_in_progress_polling_true_with_file(mocker, requests_mock): """ Given: - result request with file given, polling true When: - result response is ready Then: - Get a final result and a scan result """ mocker.patch.object(demisto, 'params', return_value={'integrationReliability': DBotScoreReliability.D}) mocker.patch.object(ScheduledCommand, 'raise_error_if_not_supported') filetype = "pdf" hash_response_json = util_load_json('test_data/scan_response.json') args = {'file': 'abcd', 'environmentID': 300, 'polling': True, 'file-type': filetype} raw_response_data = 'RawDataOfFileResult' key = get_api_id(args) assert key == 'abcd:300' requests_mock.get(BASE_URL + f"/report/{key}/report/{filetype}", status_code=200, text=raw_response_data) requests_mock.post(BASE_URL + "/search/hashes", json=hash_response_json) response = crowdstrike_result_command(client, args) assert isinstance(response, list) file_result, scan_result = response assert file_result['Type'] == 9 assert file_result['File'].endswith("pdf") assert len(scan_result) == len(hash_response_json) + 1 assert ['SUCCESS', 'SUCCESS'] == [o['state'] for o in scan_result[0].outputs] assert ['malicious', 'malicious'] == [o['verdict'] for o in scan_result[0].outputs] assert [False, False] == [o.bwc_fields['url_analysis'] for o in map(lambda x: x.indicator, scan_result[1:])] def test_results_in_progress_polling_false(requests_mock): """ Given: - result request, polling false When: - result response in progress Then: - Get a 404 result """ key = "dummy_key" filetype = "pdf" args = {'JobID': key, 'polling': False, 'file-type': filetype} requests_mock.get(BASE_URL + f"/report/{key}/report/{filetype}", status_code=404) state_call = requests_mock.get(BASE_URL + f"/report/{key}/state", json={'state': 'IN_PROGRESS'}) response = crowdstrike_result_command(client, args) assert not state_call.called assert not response.scheduled_command assert response.readable_output == 'Falcon Sandbox returned an error: status code 404, response: ' def test_crowdstrike_scan_command_polling_true(mocker, requests_mock): """ Given: - result request, polling false When: - result response in progress Then: - Get a 404 result """ mocker.patch.object(ScheduledCommand, 'raise_error_if_not_supported') requests_mock.post(BASE_URL + '/search/hashes', json=[]) response = crowdstrike_scan_command(client, {"file": "filehash", "polling": True}) assert response.scheduled_command._args['file'] == 'filehash' assert response.scheduled_command._args['hide_polling_output'] def test_crowdstrike_scan_command_polling_false(requests_mock): """ Given: - result request, polling false When: - result response in progress Then: - Get a 404 result """ requests_mock.post(BASE_URL + '/search/hashes', json=[]) response = crowdstrike_scan_command(client, {"file": "filehash"}) assert len(response) == 1 assert response[0].scheduled_command is None assert response[0].outputs == [] def test_results_in_progress_polling_true_error_state(mocker, requests_mock): """ Given: - result request, polling false When: - result response in progress Then: - Get a 404 result """ mocker.patch.object(ScheduledCommand, 'raise_error_if_not_supported') key = "dummy_key" filetype = "pdf" args = {'JobID': key, 'polling': True, 'file-type': 'pdf'} requests_mock.get(BASE_URL + f"/report/{key}/report/{filetype}", status_code=404) requests_mock.get(BASE_URL + f"/report/{key}/state", json={'state': 'ERROR'}) with pytest.raises(Exception) as e: crowdstrike_result_command(client, args) assert e.value.args[0] == "Got Error state from server: {'state': 'ERROR'}" def test_map_dict_keys(): orig = {'propertyName': 'propertyValue', 'a': 'b', 'x': 'y'} res = map_dict_keys(orig, {'a': 'c', 'x': 'z'}, True) assert res['c'] == 'b' assert res.get('propertyName') is None res = map_dict_keys(orig, {'a': 'c', 'x': 'z'}, False) assert res['z'] == 'y' assert res['propertyName'] == 'propertyValue' def test_bwc_file_context(): """ Given: - creating a bwc file When: - getting context Then: - Get non-file fields as well """ ed_val = "Static Analysis" type_val = "typeval" sha256 = 'filehash' context = BWCFile({"environment_description": ed_val, "type": type_val}, {"type": "type1"}, False, sha256=sha256, dbot_score=Common.DBotScore.NONE).to_context() file_dict = context.popitem()[1] assert file_dict['type1'] == type_val assert file_dict['SHA256'] == sha256 assert file_dict['environment_description'] == ed_val def test_crowdstrike_submit_url_command_no_poll(requests_mock): """ Given: - poll false When: - submit url Then: - get submission result without polling scan """ submit_response = { "submission_type": "page_url", "job_id": "jobid", "submission_id": "submissionId", "environment_id": 100, "sha256": "filehash" } mock_call = requests_mock.post(BASE_URL + '/submit/url', json=submit_response) result = crowdstrike_submit_url_command(client, {'url': BASE_URL, 'environmentID': 300, 'comment': 'some comment'}) assert result[0].outputs['CrowdStrike.Submit(val.submission_id && val.submission_id === obj.submission_id)'] == \ submit_response assert 'environment_id' in mock_call.last_request.text assert 'comment' in mock_call.last_request.text def test_crowdstrike_submit_sample_command(mocker, requests_mock): submit_response = util_load_json("test_data/submission_response.json") requests_mock.post(BASE_URL + '/submit/file', json=submit_response) mocker.patch.object(demisto, 'getFilePath', return_value={'id': id, 'path': './test_data/scan_response.json', 'name': 'scan_response.json'}) result = crowdstrike_submit_sample_command(client, {'entryId': '33'}) assert result[0].outputs['CrowdStrike.Submit(val.submission_id && val.submission_id === obj.submission_id)'] == \ submit_response assert result[0].outputs['CrowdStrike.JobID'] == submit_response['job_id'] def test_crowdstrike_submit_url_command_poll(requests_mock, mocker): """ Given: - poll true, scan result in progress When: - submit url Then: - submission result returned and polling scan result """ mocker.patch.object(ScheduledCommand, 'raise_error_if_not_supported') submit_response = util_load_json("test_data/submission_response.json") mocker.patch.object(demisto, 'results') submit_call = requests_mock.post(BASE_URL + '/submit/url', json=submit_response) search_call = requests_mock.post(BASE_URL + '/search/hashes', json=[]) state_call = requests_mock.get(BASE_URL + "/report/12345/state", json={'state': 'IN_PROGRESS'}) result = crowdstrike_submit_url_command(client, {'url': BASE_URL, 'environmentID': 300, 'comment': 'some comment', "polling": True}) assert submit_call.called and search_call.called and state_call.called assert submit_response in [args.args[0]['Contents'] for args in list(demisto.results.call_args_list)] assert result.scheduled_command is not None def test_get_api_id_deprecated_env_id(): assert 'filename:200' == get_api_id({'environmentId': 200, 'environementID': 100, 'file': 'filename'}) def test_get_api_id_onlyfile(): with pytest.raises(ValueError) as e: get_api_id({'file': 'filename', 'environmentId': '', 'JobID': ''}) if not e: assert False else: assert e.value.args[0] == 'Must supply JobID or environmentID and file' def test_get_submission_arguments(): assert {'environment_id': 200, 'submit_name': 'steve'} == \ get_submission_arguments({'environmentId': 200, 'environmentID': 300, 'submit_name': 'steve'}) def test_crowdstrike_analysis_overview_summary_command(requests_mock): """ Given: - any file hash When: - getting analysis summary Then: - get a response """ response_json = { "sha256": "filehash", "threat_score": None, "verdict": "malicious", "analysis_start_time": None, "last_multi_scan": "2021-12-01T15:44:18+00:00", "multiscan_result": 88 } requests_mock.get(BASE_URL + '/overview/filehash/summary', json=response_json) result = crowdstrike_analysis_overview_summary_command(client, {'file': 'filehash'}) assert result.outputs == response_json def test_crowdstrike_analysis_overview_refresh_command(requests_mock): call = requests_mock.get(BASE_URL + '/overview/filehash/refresh', status_code=200, json={}) assert 'The request to refresh the analysis overview was sent successfully.' == \ crowdstrike_analysis_overview_refresh_command(client, {'file': 'filehash'}).readable_output \ and call.called def test_crowdstrike_analysis_overview_command(requests_mock): """ Given: - any file hash When: - getting analysis overview Then: - get a response """ response_json = { "sha256": "filehash", "threat_score": None, "verdict": "malicious", "analysis_start_time": None, "last_multi_scan": "2021-12-01T15:44:18+00:00", "multiscan_result": 88, 'size': 40, 'type': 'pdf', 'last_file_name': 'steven.pdf' } requests_mock.get(BASE_URL + '/overview/filehash', json=response_json) result = crowdstrike_analysis_overview_command(client, {'file': 'filehash'}) assert result.outputs == response_json assert result.indicator is not None @freeze_time("2000-10-31") def test_get_default_file_name(): assert 'CrowdStrike_report_972950400.pdf' == get_default_file_name('pdf') @pytest.mark.parametrize('command_name, method_name', [('cs-falcon-sandbox-search', 'crowdstrike_search_command'), ('crowdstrike-get-environments', 'crowdstrike_get_environments_command'), ('cs-falcon-sandbox-report-state', 'crowdstrike_report_state_command')]) def test_main(command_name, method_name, mocker): mocker.patch.object(demisto, 'command', return_value=command_name) mocker.patch.object(demisto, 'params', return_value={}) mocker.patch.object(demisto, 'args', return_value={}) env_method_mock = mocker.patch(f'CrowdStrikeFalconSandboxV2.{method_name}', return_value='OK') main() assert env_method_mock.called and env_method_mock.return_value == 'OK'
32.913978
122
0.660242
54f6a687d03d2d4f7f4e613f405131de0f4aac87
413
py
Python
Beginner/03. Python/PasswordGenerator.py
ankita080208/Hacktoberfest
2be849e89285260e7b6672f42979943ad6bbec78
[ "MIT" ]
1
2021-10-04T05:41:43.000Z
2021-10-04T05:41:43.000Z
Beginner/03. Python/PasswordGenerator.py
ankita080208/Hacktoberfest
2be849e89285260e7b6672f42979943ad6bbec78
[ "MIT" ]
null
null
null
Beginner/03. Python/PasswordGenerator.py
ankita080208/Hacktoberfest
2be849e89285260e7b6672f42979943ad6bbec78
[ "MIT" ]
null
null
null
import string import random def main(): s1 = string.ascii_lowercase s2 = string.ascii_uppercase s3 = string.digits s4 = string.punctuation plen = int(input("Enter password length:")) s = [] s.extend(list(s1)) s.extend(list(s2)) s.extend(list(s3)) s.extend(list(s4)) print("Your password: ", end="") print("".join(random.sample(s, plen))) main()
21.736842
48
0.590799
db9b183e377440fdc2d79858f088710b7181df57
152
py
Python
warehouse/warehouse/doctype/building_parameters/test_building_parameters.py
vijith2121/update_warehouse
a7a15784708a87fc4684377ba3617ae1889e11f1
[ "MIT" ]
null
null
null
warehouse/warehouse/doctype/building_parameters/test_building_parameters.py
vijith2121/update_warehouse
a7a15784708a87fc4684377ba3617ae1889e11f1
[ "MIT" ]
null
null
null
warehouse/warehouse/doctype/building_parameters/test_building_parameters.py
vijith2121/update_warehouse
a7a15784708a87fc4684377ba3617ae1889e11f1
[ "MIT" ]
1
2021-11-30T08:35:26.000Z
2021-11-30T08:35:26.000Z
# Copyright (c) 2021, wahni and Contributors # See license.txt # import frappe import unittest class TestBuildingParameters(unittest.TestCase): pass
16.888889
48
0.789474
5317d0912c3f32df2986dea2f6aef4dc12e4fc6c
76
py
Python
code/1/goff.py
pwang13/AutomatedSE_Coursework
b416672d9756fcc60367143b989d29b0c905cfc3
[ "Unlicense" ]
null
null
null
code/1/goff.py
pwang13/AutomatedSE_Coursework
b416672d9756fcc60367143b989d29b0c905cfc3
[ "Unlicense" ]
null
null
null
code/1/goff.py
pwang13/AutomatedSE_Coursework
b416672d9756fcc60367143b989d29b0c905cfc3
[ "Unlicense" ]
null
null
null
import utest @utest.ok def ok_goff() : print "Goff Test" assert (2 < 3)
12.666667
19
0.644737
f431d64d3b00c8fb6f933013647116111a46f0aa
103
py
Python
script/importimt.py
itmattersprin/itmattersprin.github.io
5f8d2838ee469f1ae0c88fb8625e32ef6fecca93
[ "BSD-3-Clause" ]
1
2021-02-10T14:34:49.000Z
2021-02-10T14:34:49.000Z
script/importimt.py
itmattersprin/itmattersprin.github.io
5f8d2838ee469f1ae0c88fb8625e32ef6fecca93
[ "BSD-3-Clause" ]
null
null
null
script/importimt.py
itmattersprin/itmattersprin.github.io
5f8d2838ee469f1ae0c88fb8625e32ef6fecca93
[ "BSD-3-Clause" ]
null
null
null
from importbib import * dest = "../_papers" site = "imt" importBibliography(dest, site+".bib", site)
17.166667
43
0.679612
be3f77988b0c46dd85f0cf0bc50270837ac6fcc9
4,882
py
Python
examples/model_interpretation/evaluation/consistency/cal_map.py
mukaiu/PaddleNLP
0315365dbafa6e3b1c7147121ba85e05884125a5
[ "Apache-2.0" ]
null
null
null
examples/model_interpretation/evaluation/consistency/cal_map.py
mukaiu/PaddleNLP
0315365dbafa6e3b1c7147121ba85e05884125a5
[ "Apache-2.0" ]
null
null
null
examples/model_interpretation/evaluation/consistency/cal_map.py
mukaiu/PaddleNLP
0315365dbafa6e3b1c7147121ba85e05884125a5
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2022 PaddlePaddle 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. """ This script includes code to calculating MAP score for results form sentiment analysis, textual similarity, and mrc task """ import json import re import os import math import numpy as np import argparse def get_args(): parser = argparse.ArgumentParser('map eval') parser.add_argument('--pred_path', required=True) parser.add_argument('--golden_path', required=True) parser.add_argument('--language', type=str, required=True, help='language that the model is built for') args = parser.parse_args() return args def evids_load(args, path): golden_f = open(args.golden_path, 'r') golden = {} ins_num = 0 for golden_line in golden_f.readlines(): line = json.loads(golden_line) if line['sample_type'] == 'disturb': ins_num += 1 golden[line['sent_id']] = line evids = {} with open(path, 'r') as f: for line in f.readlines(): dic = json.loads(line) dic['sample_type'] = golden[dic['id']]['sample_type'] if 'rel_ids' in golden[dic['id']]: dic['rel_ids'] = golden[dic['id']]['rel_ids'] evids[dic['id']] = dic return evids, ins_num def _calc_MAP_by_bin(top_p, length_adv, adv_attriRank_list, ori_attriRank_list): """ This is our old way to calculate MAP, which follows equation two in consistency section of README """ hits = 0 sum_precs = 0.0 length_t = math.ceil(length_adv * top_p) adv_t = adv_attriRank_list[:length_t] for char_idx, char in enumerate(adv_t): if char in ori_attriRank_list[:char_idx + 1]: hits += 1 sum_precs += hits / (char_idx + 1) if length_t > 0: sum_precs /= length_t return sum_precs def _calc_MAP_by_bin_paper(top_p, length_adv, adv_attriRank_list, ori_attriRank_list): """ This function calculates MAP using the equation in our paper, which follows equation one in consistency section of README """ total_precs = 0.0 for i in range(length_adv): hits = 0.0 i += 1 adv_t = adv_attriRank_list[:i] for char_idx, char in enumerate(adv_t): if char in ori_attriRank_list[:i]: hits += 1 hits = hits / i total_precs += hits if length_adv == 0: return 0 return total_precs / length_adv def _calc_map(evids, key, ins_num): t_map = 0.0 adv_num = 0 ori_num = 0 sample_length = len(evids) for ori_idx in evids: if evids[ori_idx]['sample_type'] == 'ori': ori = evids[ori_idx] ori_num += 1 # One original instance can be related to several disturbed instance for adv_idx in evids[ori_idx]['rel_ids']: if adv_idx in evids: adv_num += 1 adv = evids[adv_idx] ori_attriRank_list = list(ori['rationale_token'][key]) adv_attriRank_list = list(adv['rationale_token'][key]) length_adv = len(adv_attriRank_list) sum_precs = _calc_MAP_by_bin_paper(1, length_adv, adv_attriRank_list, ori_attriRank_list) t_map += sum_precs return t_map / ins_num, ori_num + adv_num def cal_MAP(args, pred_path, la): evids, ins_num = evids_load(args, pred_path) if not evids: print(pred_path + " file empty!") return 0 first_key = list(evids.keys())[0] t_map = 0 num = 0 for i in range(len(evids[first_key]['rationale'])): t_map_tmp, num_tmp = _calc_map(evids, i, ins_num) t_map += t_map_tmp num += num_tmp t_map /= len(evids[first_key]['rationale']) num /= len(evids[first_key]['rationale']) print('total\t%d\t%.1f' % \ (num, 100 * t_map)) return 0 if __name__ == '__main__': args = get_args() la = args.language pred_path = args.pred_path if os.path.exists(pred_path): cal_MAP(args, pred_path, la) else: print("Prediction file does not exists!")
32.118421
80
0.600983
228d58e4c355045791528c795492dd036aacf659
3,953
py
Python
shinrl/solvers/discrete_pi/_build_calc_params_mixin.py
omron-sinicx/ShinRL
09f4ae274a33d1fc1d9d542f816aef40014af6b5
[ "MIT" ]
34
2021-12-09T07:12:57.000Z
2022-03-11T08:17:20.000Z
shinrl/solvers/discrete_pi/_build_calc_params_mixin.py
omron-sinicx/ShinRL
09f4ae274a33d1fc1d9d542f816aef40014af6b5
[ "MIT" ]
null
null
null
shinrl/solvers/discrete_pi/_build_calc_params_mixin.py
omron-sinicx/ShinRL
09f4ae274a33d1fc1d9d542f816aef40014af6b5
[ "MIT" ]
4
2021-12-11T07:48:01.000Z
2022-03-01T23:50:33.000Z
"""MixIns to compute new params for nn-based algorithms. Author: Toshinori Kitamura Affiliation: NAIST & OSX """ from typing import Optional import gym import haiku as hk import jax import jax.numpy as jnp from chex import Array from jax import value_and_grad from optax import apply_updates import shinrl as srl from .config import PiConfig class BuildCalcParamsDpMixIn: def initialize(self, env: gym.Env, config: Optional[PiConfig] = None) -> None: super().initialize(env, config) self.calc_params = self._build_calc_params() def _build_calc_params(self): q_loss_fn = getattr(srl, self.config.q_loss_fn.name) def calc_q_loss(q_prm: hk.Params, q_targ: Array, obs: Array): pred = self.q_net.apply(q_prm, obs) return q_loss_fn(pred, q_targ) def calc_pol_loss(pol_prm: hk.Params, targ_logits: Array, obs: Array): logits = self.log_pol_net.apply(pol_prm, obs) return self.pol_loss_fn(logits, targ_logits) def calc_params(data: srl.DataDict) -> Array: obs = self.env.mdp.obs_mat q_prm, pol_prm = data["QNetParams"], data["LogPolNetParams"] q_opt_st, pol_opt_st = data["QOptState"], data["LogPolOptState"] # Compute new Pol-Net params q = self.q_net.apply(q_prm, obs) logits = self.target_log_pol(q, data) pol_loss, pol_grad = value_and_grad(calc_pol_loss)(pol_prm, logits, obs) updates, pol_state = self.log_pol_opt.update(pol_grad, pol_opt_st, pol_prm) new_pol_prm = apply_updates(pol_prm, updates) pol_res = pol_loss, new_pol_prm, pol_state # Compute new Q-Net params q_targ = self.target_q_deep_dp(data) q_loss, q_grad = value_and_grad(calc_q_loss)(q_prm, q_targ, obs) updates, q_state = self.q_opt.update(q_grad, q_opt_st, q_prm) new_q_prm = apply_updates(q_prm, updates) q_res = q_loss, new_q_prm, q_state return pol_res, q_res return jax.jit(calc_params) class BuildCalcParamsRlMixIn: def initialize(self, env: gym.Env, config: Optional[PiConfig] = None) -> None: super().initialize(env, config) self.calc_params = self._build_calc_params() def _build_calc_params(self): q_loss_fn = getattr(srl, self.config.q_loss_fn.name) def calc_q_loss(q_prm: hk.Params, q_targ: Array, obs: Array, act: Array): pred = self.q_net.apply(q_prm, obs) pred = jnp.take_along_axis(pred, act, axis=1) # Bx1 return q_loss_fn(pred, q_targ).mean() def calc_pol_loss(pol_prm: hk.Params, targ_logits: Array, obs: Array): logits = self.log_pol_net.apply(pol_prm, obs) return self.pol_loss_fn(logits, targ_logits) def calc_params(data: srl.DataDict, samples: srl.Sample) -> Array: obs, act = samples.obs, samples.act q_prm, pol_prm = data["QNetParams"], data["LogPolNetParams"] q_opt_st, pol_opt_st = data["QOptState"], data["LogPolOptState"] # Compute new Pol-Net params q = self.q_net.apply(q_prm, obs) logits = self.target_log_pol(q, data) pol_loss, pol_grad = value_and_grad(calc_pol_loss)(pol_prm, logits, obs) updates, pol_state = self.log_pol_opt.update(pol_grad, pol_opt_st, pol_prm) new_pol_prm = apply_updates(pol_prm, updates) pol_res = pol_loss, new_pol_prm, pol_state # Compute new Q-Net params q_targ = self.target_q_deep_rl(data, samples) q_loss, q_grad = value_and_grad(calc_q_loss)(q_prm, q_targ, obs, act) updates, q_state = self.q_opt.update(q_grad, q_opt_st, q_prm) new_q_prm = apply_updates(q_prm, updates) q_res = q_loss, new_q_prm, q_state return pol_res, q_res return jax.jit(calc_params)
39.929293
87
0.649127
a3a91acb8821c4d15f4716878184e61d43f6658c
315
py
Python
exercises/de/exc_02_10_03.py
Jette16/spacy-course
32df0c8f6192de6c9daba89740a28c0537e4d6a0
[ "MIT" ]
2,085
2019-04-17T13:10:40.000Z
2022-03-30T21:51:46.000Z
exercises/de/exc_02_10_03.py
Jette16/spacy-course
32df0c8f6192de6c9daba89740a28c0537e4d6a0
[ "MIT" ]
79
2019-04-18T14:42:55.000Z
2022-03-07T08:15:43.000Z
exercises/de/exc_02_10_03.py
Jette16/spacy-course
32df0c8f6192de6c9daba89740a28c0537e4d6a0
[ "MIT" ]
361
2019-04-17T13:34:32.000Z
2022-03-28T04:42:45.000Z
import spacy nlp = spacy.load("en_core_web_md") doc = nlp("This was a great restaurant. Afterwards, we went to a really nice bar.") # Erstelle Spans für "great restaurant" und "really nice bar" span1 = ____ span2 = ____ # Berechne die Ähnlichkeit der beiden Spans similarity = ____.____(____) print(similarity)
22.5
83
0.749206
a3e5c6a6a030e6487807dbcc8251a512f180eea6
212
py
Python
exercise11.py
nikhadif/Advanced-Programming
e5bf4f5014c17c252bc0cb93c9d44c7c615b79c0
[ "MIT" ]
1
2020-11-21T16:57:40.000Z
2020-11-21T16:57:40.000Z
exercise11.py
nikhadif/Advanced-Programming
e5bf4f5014c17c252bc0cb93c9d44c7c615b79c0
[ "MIT" ]
null
null
null
exercise11.py
nikhadif/Advanced-Programming
e5bf4f5014c17c252bc0cb93c9d44c7c615b79c0
[ "MIT" ]
null
null
null
def make_word_list(a_file): """Create a list of words from the file""" word_list = [] for line_str in a_file: line_list = line_str.split() for word in line_list: if
21.2
46
0.575472
60d2fd6b7c23d206581fbe19da12a56f13417ed6
885
py
Python
src/unittest/python/grundlegend/test_addition.py
dlangheiter-tgm/test-mirror
9878da44953c40abc1df0311f275c3eebc2e876b
[ "MIT" ]
null
null
null
src/unittest/python/grundlegend/test_addition.py
dlangheiter-tgm/test-mirror
9878da44953c40abc1df0311f275c3eebc2e876b
[ "MIT" ]
null
null
null
src/unittest/python/grundlegend/test_addition.py
dlangheiter-tgm/test-mirror
9878da44953c40abc1df0311f275c3eebc2e876b
[ "MIT" ]
null
null
null
""" Created on 27.12.2013 @author: Walter Rafeiner-Magor <[email protected]> """ import unittest from bruch.Bruch import * class TestAddition(unittest.TestCase): def setUp(self): self.b = Bruch(3, 2) self.b2 = Bruch(self.b) self.b3 = Bruch(4, 2) pass def tearDown(self): del self.b, self.b2, self.b3 pass def testplus(self): self.b = self.b + Bruch(4, 5) assert(float(self.b) == 2.3) def testplus2(self): self.b = self.b + self.b3 assert(float(self.b) == 3.5) def testplus3(self): self.b2 = self.b + 3 assert(float(self.b2) == 4.5) def testiAdd(self): self.b += 1 assert(self.b == Bruch(5, 2)) def testiAdd2(self): self.b += Bruch(1) assert(self.b == Bruch(5, 2)) if __name__ == "__main__": unittest.main()
20.581395
58
0.550282
717e7241f8d3f3d3ae3ceb46de13bb7070ec7b52
375
py
Python
Linkedin Learning/Learning Python/Excercise Files/Exercise Files/Ch2/variables_finished.py
rishav3101/Online-Courses-Learning
1e9356af331b27b6ee33d376d8d7104edaeac2fa
[ "MIT" ]
331
2019-10-22T09:06:28.000Z
2022-03-27T13:36:03.000Z
Linkedin Learning/Learning Python/Excercise Files/Exercise Files/Ch2/variables_finished.py
rishav3101/Online-Courses-Learning
1e9356af331b27b6ee33d376d8d7104edaeac2fa
[ "MIT" ]
8
2020-04-10T07:59:06.000Z
2022-02-06T11:36:47.000Z
Linkedin Learning/Learning Python/Excercise Files/Exercise Files/Ch2/variables_finished.py
rishav3101/Online-Courses-Learning
1e9356af331b27b6ee33d376d8d7104edaeac2fa
[ "MIT" ]
572
2019-07-28T23:43:35.000Z
2022-03-27T22:40:08.000Z
# Declare a variable and initialize it f = 0 print (f) # re-declaring the variable works f = "abc" print (f) # ERROR: variables of different types cannot be combined #print ("string type " + 123) print ("string type " + str(123)) # Global vs. local variables in functions def someFunction(): #global f f = "def" print (f) someFunction() print (f) del f print (f)
15.625
56
0.677333
e80208f1a4f0d8be68d4524f3f5af500cf4e9932
792
py
Python
gemtown/modelphotos/admin.py
doramong0926/gemtown
2c39284e3c68f0cc11994bed0ee2abaad0ea06b6
[ "MIT" ]
null
null
null
gemtown/modelphotos/admin.py
doramong0926/gemtown
2c39284e3c68f0cc11994bed0ee2abaad0ea06b6
[ "MIT" ]
5
2020-09-04T20:13:39.000Z
2022-02-17T22:03:33.000Z
gemtown/modelphotos/admin.py
doramong0926/gemtown
2c39284e3c68f0cc11994bed0ee2abaad0ea06b6
[ "MIT" ]
null
null
null
from django.contrib import admin from . import models @admin.register(models.ModelPhoto) class ModelPhotoAdmin(admin.ModelAdmin): fields = [ 'file', 'photo_type', 'confirm_status', 'modeler', 'contents_hash', 'blockchain_id', 'blockchain_txid', 'creator', ] list_display = [ 'id', 'file', 'photo_type', 'confirm_status', 'creator', 'created_at', 'updated_at', ] list_filter = [ 'file', 'photo_type', 'confirm_status', 'creator', ] search_fields = [ 'file', 'photo_type', 'confirm_status', 'contents_hash', 'blockchain_id', 'blockchain_txid', ]
18
40
0.497475
1c2c24be7988d5e0d24c50cfd0f5ee10081a7573
665
py
Python
day16/coffeeMachine/main.py
nurmatthias/100DaysOfCode
22002e4b31d13e6b52e6b9222d2e91c2070c5744
[ "Apache-2.0" ]
null
null
null
day16/coffeeMachine/main.py
nurmatthias/100DaysOfCode
22002e4b31d13e6b52e6b9222d2e91c2070c5744
[ "Apache-2.0" ]
null
null
null
day16/coffeeMachine/main.py
nurmatthias/100DaysOfCode
22002e4b31d13e6b52e6b9222d2e91c2070c5744
[ "Apache-2.0" ]
null
null
null
from menu import Menu, MenuItem from coffee_maker import CoffeeMaker from money_machine import MoneyMachine machine = CoffeeMaker() moneyBox = MoneyMachine() menu = Menu() machine_running = True while machine_running: choice = input(f"Our menu: {menu.get_items()} \nWhat would you like? ").lower() if choice == "off": machine_running = False print("Shutingdown...") elif choice == "report": machine.report() moneyBox.report() else: drink = menu.find_drink(choice) if machine.is_resource_sufficient(drink) and moneyBox.make_payment(drink.cost): machine.make_coffee(drink)
25.576923
87
0.666165
98bb4631d3babecd2d077a8db557bfc61277700a
1,192
py
Python
production/pygsl-0.9.5/pygsl/fft.py
juhnowski/FishingRod
457e7afb5cab424296dff95e1acf10ebf70d32a9
[ "MIT" ]
1
2019-07-29T02:53:51.000Z
2019-07-29T02:53:51.000Z
production/pygsl-0.9.5/pygsl/fft.py
juhnowski/FishingRod
457e7afb5cab424296dff95e1acf10ebf70d32a9
[ "MIT" ]
1
2021-09-11T14:30:32.000Z
2021-09-11T14:30:32.000Z
Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/pygsl/fft.py
poojavade/Genomics_Docker
829b5094bba18bbe03ae97daf925fee40a8476e8
[ "Apache-2.0" ]
2
2016-12-19T02:27:46.000Z
2019-07-29T02:53:54.000Z
""" Wrapper for the FFT tranform as provided by GSL """ from pygsl._transform import complex_backward, complex_backward_float, \ complex_forward, complex_forward_float, \ complex_inverse, complex_inverse_float, \ complex_radix2_backward, complex_radix2_backward_float, \ complex_radix2_dif_backward, complex_radix2_dif_backward_float, \ complex_radix2_dif_forward, complex_radix2_dif_forward_float, \ complex_radix2_dif_inverse, complex_radix2_dif_inverse_float, \ complex_radix2_forward, complex_radix2_forward_float, \ complex_radix2_inverse, complex_radix2_inverse_float, \ complex_wavetable, complex_wavetable_float, \ complex_workspace, complex_workspace_float, \ halfcomplex_inverse, halfcomplex_inverse_float, \ halfcomplex_radix2_inverse, halfcomplex_radix2_inverse_float, \ halfcomplex_radix2_transform, halfcomplex_radix2_transform_float, \ halfcomplex_radix2_unpack, halfcomplex_radix2_unpack_float, \ halfcomplex_transform, halfcomplex_transform_float, \ halfcomplex_wavetable, halfcomplex_wavetable_float, \ real_radix2_transform, real_radix2_transform_float, \ real_transform, real_transform_float, \ real_wavetable, real_wavetable_float, \ real_workspace, real_workspace_float
47.68
72
0.879195
c725b27f3c7fd34fae36eb1002a1a133a8712c97
1,185
py
Python
official/cv/cspdarknet53/src/head.py
leelige/mindspore
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
[ "Apache-2.0" ]
77
2021-10-15T08:32:37.000Z
2022-03-30T13:09:11.000Z
official/cv/cspdarknet53/src/head.py
leelige/mindspore
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
[ "Apache-2.0" ]
3
2021-10-30T14:44:57.000Z
2022-02-14T06:57:57.000Z
official/cv/cspdarknet53/src/head.py
leelige/mindspore
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
[ "Apache-2.0" ]
24
2021-10-15T08:32:45.000Z
2022-03-24T18:45:20.000Z
# Copyright 2021 Huawei Technologies Co., Ltd # # 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. # ============================================================================ """common head architecture.""" import mindspore.nn as nn from src.utils.custom_op import GlobalAvgPooling __all__ = ["CommonHead"] class CommonHead(nn.Cell): """Common Head.""" def __init__(self, num_classes, out_channels): super(CommonHead, self).__init__() self.avgpool = GlobalAvgPooling() self.fc = nn.Dense(out_channels, num_classes, has_bias=True).add_flags_recursive(fp16=True) def construct(self, x): x = self.avgpool(x) x = self.fc(x) return x
35.909091
99
0.673418
c7b539b2d0b355c4e958faaf2a5bfb195bc41914
892
py
Python
exercises/es/exc_01_12_02.py
tuanducdesign/spacy-course
f8d092c5fa2997fccb3f367d174dce8667932b3d
[ "MIT" ]
2
2020-07-07T01:46:37.000Z
2021-04-20T03:19:43.000Z
exercises/es/exc_01_12_02.py
tuanducdesign/spacy-course
f8d092c5fa2997fccb3f367d174dce8667932b3d
[ "MIT" ]
null
null
null
exercises/es/exc_01_12_02.py
tuanducdesign/spacy-course
f8d092c5fa2997fccb3f367d174dce8667932b3d
[ "MIT" ]
null
null
null
import spacy from spacy.matcher import Matcher nlp = spacy.load("es_core_news_sm") matcher = Matcher(nlp.vocab) doc = nlp( "descargué Fortnite en mi computadora, pero no puedo abrir el juego. " "Ayuda? Cuando estaba descargando Minecraft, conseguí la versión de Windows " "donde tiene una carpeta '.zip' y usé el programa por defecto para " "descomprimirlo…así que también tengo que descargar Winzip?" ) # Escribe un patrón que encuentre una forma de "descargar" más un nombre propio pattern = [{"LEMMA": ____}, {"POS": ____}] # Añade el patrón al matcher y usa el matcher sobre el documento matcher.add("DOWNLOAD_THINGS_PATTERN", [pattern]) matches = matcher(doc) print("Total de resultados encontrados:", len(matches)) # Itera sobre los resultados e imprime el texto del span for match_id, start, end in matches: print("Resultado encontrado:", doc[start:end].text)
35.68
81
0.743274
c7f59e216ad3f76aef2e359555c2ac2848068388
685
py
Python
haas_lib_bundles/python/libraries/soil_moisture/soil_moisture.py
wstong999/AliOS-Things
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
[ "Apache-2.0" ]
null
null
null
haas_lib_bundles/python/libraries/soil_moisture/soil_moisture.py
wstong999/AliOS-Things
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
[ "Apache-2.0" ]
null
null
null
haas_lib_bundles/python/libraries/soil_moisture/soil_moisture.py
wstong999/AliOS-Things
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
[ "Apache-2.0" ]
null
null
null
from driver import GPIO from driver import ADC class SoilMoisture(object): def __init__(self, DO, AO=None): self.DO = None self.AO = None if not isinstance(DO, GPIO): raise ValueError('parameter DO is not an GPIO object') if AO is not None and not isinstance(AO, ADC): raise ValueError('parameter AO should be ADC object or None') self.DO = DO self.AO = AO # 读取数字信号 def moistureDetect(self): return self.DO.read() # 读取模拟信号,电压 def getVoltage(self): if not self.AO: raise RuntimeError('Can not get voltage, AO is not inited') return self.AO.readVoltage()
27.4
73
0.607299
402d41fddc17a8cb0cdad0008755d95a9043df9b
337
py
Python
src/onegov/feriennet/collections/notification_template.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
src/onegov/feriennet/collections/notification_template.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
src/onegov/feriennet/collections/notification_template.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
from cached_property import cached_property from onegov.core.collection import GenericCollection class NotificationTemplateCollection(GenericCollection): @cached_property def model_class(self): # XXX circular import from onegov.feriennet.models import NotificationTemplate return NotificationTemplate
25.923077
64
0.789318
40fe87c6be127a28518fb160af9d79545f96c5f2
1,892
py
Python
exercise1.py
weibk/webauto
f494f8043d05739935d1fc22b941bbc9a7ba75b7
[ "MIT" ]
null
null
null
exercise1.py
weibk/webauto
f494f8043d05739935d1fc22b941bbc9a7ba75b7
[ "MIT" ]
null
null
null
exercise1.py
weibk/webauto
f494f8043d05739935d1fc22b941bbc9a7ba75b7
[ "MIT" ]
null
null
null
#!/usr/bin/python3 # encoding='utf-8' # author:weibk # @time:2021/10/22 10:43 from selenium import webdriver from threading import Thread class Test1(Thread): def run(self): driver1 = webdriver.Chrome() driver1.get(r'H:\G\pythonProject\webauto\html\autotest.html') driver1.find_element_by_xpath('//*[@id="accountID"]').send_keys('admin') driver1.find_element_by_xpath('//*[@id="passwordID"]').send_keys( 'admin') driver1.find_element_by_xpath('//*[@id="areaID"]').send_keys('北京市') driver1.find_element_by_xpath('//*[@id="sexID1"]').click() driver1.find_element_by_xpath('//*[@value="Auterm"]').click() driver1.find_element_by_xpath('//*[@value="winter"]').click() driver1.find_element_by_xpath('//*[@name="file" and @type="file"]') \ .send_keys(r'H:\G\pythonProject\webauto\html\pop.html') driver1.find_element_by_xpath('//*[@id="buttonID"]').click() driver1.switch_to.alert.accept() class Test2(Thread): def run(self): driver23 = webdriver.Chrome() driver23.get(r'H:\G\pythonProject\webauto\html\dialogs.html') driver23.find_element_by_xpath('//*[@id="alert"]').click() driver23.switch_to.alert.accept() driver23.find_element_by_xpath('//*[@id="confirm"]').click() # 点击确定 driver23.switch_to.alert.accept() driver23.find_element_by_xpath('//*[@id="confirm"]').click() # 点击取消 driver23.switch_to.alert.dismiss() class Test3(Thread): def run(self): driver3 = webdriver.Chrome() driver3.get(r'H:\G\pythonProject\webauto\html\pop.html') driver3.find_element_by_xpath('//*[@id="goo"]').click() count = len(driver3.window_handles) if count > 1: print('打开新窗口成功!') t1 = Test1() t2 = Test2() t3 = Test3() t1.start() t2.start() t3.start()
33.785714
80
0.625793
905f3878737af4ab146e491c258a5845cd855b55
1,068
py
Python
src/onegov/org/models/page_move.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
src/onegov/org/models/page_move.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
src/onegov/org/models/page_move.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
from onegov.core.orm.abstract import MoveDirection from onegov.core.utils import Bunch from onegov.page import PageCollection class AdjacencyListMove(object): """ Represents a single move of an adjacency list item. """ def __init__(self, session, subject, target, direction): self.session = session self.subject = subject self.target = target self.direction = direction @classmethod def for_url_template(cls): return cls( session=None, subject=Bunch(id='{subject_id}'), target=Bunch(id='{target_id}'), direction='{direction}' ) @property def subject_id(self): return self.subject.id @property def target_id(self): return self.target.id def execute(self): self.__collection__(self.session).move( subject=self.subject, target=self.target, direction=getattr(MoveDirection, self.direction) ) class PageMove(AdjacencyListMove): __collection__ = PageCollection
25.428571
63
0.636704
907d3f4582cce2baf38520a8956b16ef94bfd3c1
3,245
py
Python
7-assets/past-student-repos/Sorting-master/src/recursive_sorting/recursive_sorting.py
eengineergz/Lambda
1fe511f7ef550aed998b75c18a432abf6ab41c5f
[ "MIT" ]
null
null
null
7-assets/past-student-repos/Sorting-master/src/recursive_sorting/recursive_sorting.py
eengineergz/Lambda
1fe511f7ef550aed998b75c18a432abf6ab41c5f
[ "MIT" ]
null
null
null
7-assets/past-student-repos/Sorting-master/src/recursive_sorting/recursive_sorting.py
eengineergz/Lambda
1fe511f7ef550aed998b75c18a432abf6ab41c5f
[ "MIT" ]
null
null
null
import random # TO-DO: complete the helper function below to merge 2 sorted arrays def merge( arrA, arrB ): elements = len( arrA ) + len( arrB ) merged_arr = [0] * elements # Iterate through marged_arr to insert smallest item in arrA and arrB until merged_arr is full for i in range(0, len(merged_arr)): # If arrA is empty, use arrB to fill if len(arrA) == 0: merged_arr[i] = min(arrB) arrB.remove(min(arrB)) # If arrB is empty, use arrA to fill elif len(arrB) == 0: merged_arr[i] = min(arrA) arrA.remove(min(arrA)) # If the smallest item in arrA is smaller than the smallest item in arrB, insert arrA's smallest item and then remove from arrA elif min(arrA) < min(arrB): merged_arr[i] = min(arrA) arrA.remove(min(arrA)) # If the smallest item in arrB is smaller than the smallest item in arrA, insert arrB's smallest item and then remove from arrB elif min(arrA) >= min(arrB): merged_arr[i] = min(arrB) arrB.remove(min(arrB)) return merged_arr # TO-DO: implement the Merge Sort function below USING RECURSION def merge_sort( arr ): if len(arr) == 0 or len(arr) == 1: return arr mid_point = round(len(arr)/2) arrA = merge_sort(arr[:mid_point]) arrB = merge_sort(arr[mid_point:]) return merge(arrA,arrB) # STRETCH: implement an in-place merge sort algorithm def merge_in_place(arr, start, mid, end): # Updating the pointers # Getting past the halfway # Assign a variable to track the index of the other starting point # Decrement return arr def merge_sort_in_place(arr, l, r): # TO-DO return arr # STRETCH: implement the Timsort function below # hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt def insertion_sort(arr): for i in range(1, len(arr)): # Starts looping from first unsorted element unsorted = arr[i] # Starts comparing against last sorted element last_sorted_index = i-1 # While unsorted is less than the last sorted... while last_sorted_index >= 0 and unsorted < arr[last_sorted_index]: # Shifts last sorted to the right by one arr[last_sorted_index + 1] = arr[last_sorted_index] # Decrements down the last sorted index, until no longer larger than or hits zero last_sorted_index -= 1 # Places unsorted element into correct spot arr[last_sorted_index + 1] = unsorted return arr def timsort( arr ): # Divide arr into runs of 32 (or as chosen) # If arr size is smaller than run, it will just use insertion sort minirun = 32 for i in range(0, len(arr), minirun): counter = 0 range_start = minirun * counter range_end = minirun * (counter+1) print(range_start, range_end) print(f"i is: {i}") print(insertion_sort(arr[range_start:range_end])) counter += 1 # Sort runs using insertion sort # Merge arrays using merge sort # return insertion_sort(arr) test_sort = random.sample(range(100), 64) print(timsort(test_sort))
32.45
135
0.638829
90dee715c68f91d40df2397e96dd570d20372c66
1,742
py
Python
yolo/myconfig.py
wanglikang/zzuARTensorflow2
2e31108ca90f183ab93309aa481de1dd88f98a9b
[ "MIT" ]
null
null
null
yolo/myconfig.py
wanglikang/zzuARTensorflow2
2e31108ca90f183ab93309aa481de1dd88f98a9b
[ "MIT" ]
null
null
null
yolo/myconfig.py
wanglikang/zzuARTensorflow2
2e31108ca90f183ab93309aa481de1dd88f98a9b
[ "MIT" ]
null
null
null
#coding:utf-8 import os import datetime # # path and dataset parameter # print("first install some necessary lib") os.system('pip install -r requestments.txt') listenerport = 10002 qiniuDomain = 'p7ijy2tin.bkt.clouddn.com' ''' access_key = 'mMQxjyif6Uk8nSGIn9ZD3I19MBMEK3IUGngcX8_p' secret_key = 'J5gFhdpQ-1O1rkCnlqYnzPiH3XTst2Szlv9GlmQM' ''' access_key = '' secret_key = '' DATA_VERSION = 'V5' DATA_ROOT_PATH = 'DIYdata' DATA_ZIPNAME='DIYdata'+DATA_VERSION+'.zip' DATA_DownloadZipFileName = DATA_ZIPNAME DATA_UploadZipFileName = 'DIYdata'+DATA_VERSION+"Weights.zip" MYDATA_PATH = os.path.join(DATA_ROOT_PATH, 'pics') DATACFG_PATH = os.path.join(DATA_ROOT_PATH, 'cfg') CACHE_PATH = os.path.join(DATA_ROOT_PATH, 'cache') OUTPUT_DIR = os.path.join(DATA_ROOT_PATH, 'output') WEIGHTS_DIR = os.path.join(DATA_ROOT_PATH, 'weights') #WEIGHTS_FILE = None #WEIGHTS_FILE = os.path.join(DATA_ROOT_PATH, 'weights','YOLO_small.ckpt') WEIGHTS_FILE = 'YOLO_small.ckpt' ''' CLASSES = ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor','zhongtiww'] ''' CLASSES=[] FLIPPED = True # # model parameter # IMAGE_SIZE = 448 CELL_SIZE = 7 BOXES_PER_CELL = 2 ALPHA = 0.1 DISP_CONSOLE = False OBJECT_SCALE = 1.0 NOOBJECT_SCALE = 1.0 CLASS_SCALE = 2.0 COORD_SCALE = 5.0 # # solver parameter # GPU = '' #LEARNING_RATE = 0.0001 LEARNING_RATE = 0.001 DECAY_STEPS = 30000 DECAY_RATE = 0.1 STAIRCASE = True BATCH_SIZE = 45 #MAX_ITER = 15000 MAX_ITER = 5000 SUMMARY_ITER = 10 #SAVE_ITER = 1000 SAVE_ITER = 500 # # test parameter # THRESHOLD = 0.2 IOU_THRESHOLD = 0.5
17.247525
73
0.708955
90fe63823525d1e7e9f9649e85759fc3ac0ea163
475
py
Python
except_handling.py
KingRedfoo/InterstellarSiri
6fe48ee0680eaffdde8e8154e753592590aff07f
[ "Apache-2.0" ]
null
null
null
except_handling.py
KingRedfoo/InterstellarSiri
6fe48ee0680eaffdde8e8154e753592590aff07f
[ "Apache-2.0" ]
null
null
null
except_handling.py
KingRedfoo/InterstellarSiri
6fe48ee0680eaffdde8e8154e753592590aff07f
[ "Apache-2.0" ]
null
null
null
try: p =10 q = 5 p = q/0 f = open("abc.txt") # except Exception as e: #prints exception message as type # print(type(e)) # # # except Exception as e: #prints exception message # print(e) except ZeroDivisionError: print("Where is my Destiny.!") except FileNotFoundError as e: print("No such file or directory:", e.filename) except (FileNotFoundError, ZeroDivisionError): print("Kitne error krega bhai.!!")
18.269231
71
0.616842
311631a9ee87357b82e6c4a3b98fdee6c2e5f98c
3,587
py
Python
beispielanwendungen/packaging/src/helloworld/ui/ui_helloworld.py
pbouda/pyqt-und-pyside-buch
a4ec10663ccc8aeda075c9a06b9707ded52382c8
[ "CC-BY-4.0" ]
5
2017-03-11T13:27:27.000Z
2022-01-09T10:52:05.000Z
beispielanwendungen/packaging/src/helloworld/ui/ui_helloworld.py
pbouda/pyqt-und-pyside-buch
a4ec10663ccc8aeda075c9a06b9707ded52382c8
[ "CC-BY-4.0" ]
2
2021-02-14T10:59:59.000Z
2021-10-30T21:46:32.000Z
beispielanwendungen/packaging/src/helloworld/ui/ui_helloworld.py
pbouda/pyqt-und-pyside-buch
a4ec10663ccc8aeda075c9a06b9707ded52382c8
[ "CC-BY-4.0" ]
1
2019-08-07T03:08:18.000Z
2019-08-07T03:08:18.000Z
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/helloworld.ui' # # Created: Tue Aug 9 10:01:29 2011 # by: PyQt4 UI code generator 4.7.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(279, 204) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget) self.verticalLayout.setObjectName("verticalLayout") self.label = QtGui.QLabel(self.centralwidget) self.label.setObjectName("label") self.verticalLayout.addWidget(self.label) self.lineEdit = QtGui.QLineEdit(self.centralwidget) self.lineEdit.setText("") self.lineEdit.setObjectName("lineEdit") self.verticalLayout.addWidget(self.lineEdit) self.pushButton = QtGui.QPushButton(self.centralwidget) self.pushButton.setObjectName("pushButton") self.verticalLayout.addWidget(self.pushButton) self.graphicsView = QtGui.QGraphicsView(self.centralwidget) self.graphicsView.setObjectName("graphicsView") self.verticalLayout.addWidget(self.graphicsView) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 279, 23)) self.menubar.setObjectName("menubar") self.menuFile = QtGui.QMenu(self.menubar) self.menuFile.setObjectName("menuFile") MainWindow.setMenuBar(self.menubar) self.actionOpen = QtGui.QAction(MainWindow) self.actionOpen.setObjectName("actionOpen") self.actionSave = QtGui.QAction(MainWindow) self.actionSave.setObjectName("actionSave") self.actionSave_as = QtGui.QAction(MainWindow) self.actionSave_as.setObjectName("actionSave_as") self.actionQuit = QtGui.QAction(MainWindow) self.actionQuit.setObjectName("actionQuit") self.menuFile.addAction(self.actionOpen) self.menuFile.addAction(self.actionSave) self.menuFile.addAction(self.actionSave_as) self.menuFile.addSeparator() self.menuFile.addAction(self.actionQuit) self.menubar.addAction(self.menuFile.menuAction()) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "Hello World", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("MainWindow", "Hello World!", None, QtGui.QApplication.UnicodeUTF8)) self.pushButton.setText(QtGui.QApplication.translate("MainWindow", "Update", None, QtGui.QApplication.UnicodeUTF8)) self.menuFile.setTitle(QtGui.QApplication.translate("MainWindow", "File", None, QtGui.QApplication.UnicodeUTF8)) self.actionOpen.setText(QtGui.QApplication.translate("MainWindow", "Open...", None, QtGui.QApplication.UnicodeUTF8)) self.actionSave.setText(QtGui.QApplication.translate("MainWindow", "Save", None, QtGui.QApplication.UnicodeUTF8)) self.actionSave_as.setText(QtGui.QApplication.translate("MainWindow", "Save as...", None, QtGui.QApplication.UnicodeUTF8)) self.actionQuit.setText(QtGui.QApplication.translate("MainWindow", "Quit", None, QtGui.QApplication.UnicodeUTF8)) import helloworld_rc
51.985507
130
0.723446
9ec5755c56f447cc78c8417012b7f5f7578c4d58
1,858
py
Python
Utils/py/RL_ActionSelection/env_0/agent_DQN.py
tarsoly/NaoTH
dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
Utils/py/RL_ActionSelection/env_0/agent_DQN.py
tarsoly/NaoTH
dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
Utils/py/RL_ActionSelection/env_0/agent_DQN.py
tarsoly/NaoTH
dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
from keras.models import Sequential from keras.layers import Dense import numpy as np from state import State class agent(): memory = [] # hyper parameter epsilon = 1.0 epsilon_decay = 0.9 epsilon_min = 0.01 gamma = 0.95 learning_rate = 0.001 # initialize keras model def __init__(self, feature, action_space_size, load_model=False): self.action_space_size = action_space_size self.gen_feature = feature # function for generating the used features # has two outputs; the feature vector and the dimensions of the 'sub feature vectors' if not callable(self.gen_feature): raise TypeError self.feature_size = self.gen_feature(State())[0].shape[1] self._init_model() def _init_model(self, load_model=False): self.model = Sequential() self.model.add(Dense(units=128, input_dim=self.feature_size, activation='relu')) self.model.add(Dense(units=self.action_space_size, activation='softmax')) self.model.compile(loss='mse', optimizer='adam') def act(self, state): if np.random.rand() <= self.epsilon: return np.random.randint(0,self.action_space_size) try: features, _ = self.gen_feature(state) action_values = self.model.predict(features) except NameError: print "The model was not initialized ... \n\ or something else went wrong while predicting the next action." return np.argmax(action_values[0]) def remember(self, state, action, reward, next_state, done): self.memory.append((state, action, reward, next_state, done)) if __name__ == "__main__": import features Agent = agent(features.feature_vec) Agent.init_model() for i in range(10): print(Agent.act(State()))
26.542857
93
0.652314
7350bf24e87eb239b5cf53594904fd7629dcbe45
2,541
py
Python
assignments/ps4-template/tests.py
tallamjr/mit-6006
c2aa6bb48edef5800c0779ba2eebd697d44249b5
[ "MIT" ]
1
2022-02-26T13:52:31.000Z
2022-02-26T13:52:31.000Z
assignments/ps4-template/tests.py
tallamjr/mit-6006
c2aa6bb48edef5800c0779ba2eebd697d44249b5
[ "MIT" ]
null
null
null
assignments/ps4-template/tests.py
tallamjr/mit-6006
c2aa6bb48edef5800c0779ba2eebd697d44249b5
[ "MIT" ]
null
null
null
import unittest from tastiest_slice import tastiest_slice tests = ( ( [(-7, 8, 5), (2, -4, 3), (7, 10, -1), (4, -3, 9), (-5, 1, 9)], (4, 8, 26), ), ( [(15, -1, 0), (7, 11, -7), (20, -8, 9), (-16, -4, 13), (0, -11, 18), (19, -13, -8), (16, 1, -14), (-14, -3, 10), (-7, 13, 1), (6, -10, 17)], (6, 13, 59), ), ( [(3, 11, 30), (-25, -8, 16), (-21, 6, 31), (-3, 20, -3), (-9, -22, 8), (-24, 19, -23), (-7, -20, 11), (7, 27, 29), (-14, 22, -24), (24, 21, 11), (-17, 12, -24), (16, -13, 28), (-26, -27, -3), (-1, 29, -4), (-16, -29, -19)], (16, 11, 102), ), ( [(-41, 5, -4), (-43, 50, -1), (-19, -42, -32), (-34, 34, 30), (28, -5, -10), (14, -29, 21), (-31, -27, -8), (0, -48, -21), (44, -32, 19), (-3, 19, 8), (8, -35, -23), (22, 36, -21), (-49, -16, 31), (49, 15, 6), (-40, -13, 2), (2, -9, 43), (47, 3, 35), (-44, 45, 21), (17, 18, -10), (-50, -26, 7), (-10, -47, -14), (-2, 39, -27), (-36, -8, 2), (-25, -7, -13), (-1, -6, -27)], (-34, 45, 89), ), ( [(36, -81, -4), (24, -36, 55), (-37, -19, -58), (23, -85, 59), (46, 92, -73), (-57, 12, 13), (9, -1, 13), (-68, -94, -35), (-12, 83, 11), (62, -82, -17), (71, 69, 16), (-76, 25, -76), (-67, 11, -75), (95, 75, -3), (-39, 19, -77), (-3, -87, 45), (-66, -31, 31), (58, 22, -26), (-38, -89, 5), (-79, 26, 47), (-33, 39, 3), (-27, 97, 35), (72, -45, -11), (63, -30, 36), (-21, -69, -64), (-73, 28, -53), (-86, 66, -24), (32, -34, 33), (-17, -25, -60), (55, 7, 0), (47, -93, 49), (3, -90, -76), (-41, 78, 53), (76, -61, 81), (17, -70, 36), (0, 50, -61), (-51, 33, 100), (98, -75, -46), (54, 81, 88), (-52, 35, 91), (-23, 53, 49), (-96, -65, 66), (-22, 94, -42), (1, 45, 53), (18, -62, -12), (44, 34, -8), (-16, -74, -74), (-92, 2, -42), (-98, 96, 76), (10, -63, 98)], (76, -30, 301), ), ) def check(test): args, staff_sol = test _, _, T = staff_sol toppings = [x for x in args] X, Y, T_ = tastiest_slice(toppings) if T != T_: return False T_ = 0 for x, y, t in args: if x <= X and y <= Y: T_ += t return T == T_ class TestCases(unittest.TestCase): def test_01(self): self.assertTrue(check(tests[ 0])) def test_02(self): self.assertTrue(check(tests[ 1])) def test_03(self): self.assertTrue(check(tests[ 2])) def test_04(self): self.assertTrue(check(tests[ 3])) def test_05(self): self.assertTrue(check(tests[ 4])) if __name__ == '__main__': res = unittest.main(verbosity = 3, exit = False)
51.857143
769
0.415978
b4379b8fb1dc3fdb87883f95b1eea1ccda59492d
243
py
Python
src/wochenbericht/models.py
nexiles/odoo.wochenbericht
41f43327d40f849dc21e2b645810d562543fa073
[ "MIT" ]
null
null
null
src/wochenbericht/models.py
nexiles/odoo.wochenbericht
41f43327d40f849dc21e2b645810d562543fa073
[ "MIT" ]
null
null
null
src/wochenbericht/models.py
nexiles/odoo.wochenbericht
41f43327d40f849dc21e2b645810d562543fa073
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import time import logging import datetime from openerp import tools, api, models, fields, osv, _ class Tagesbericht(models.Model): _name = "wochenbericht.tagesbericht" date = fields.Date(_("Datum")) # EOF
16.2
54
0.695473
6f59cd480c8ce76ee7a830b041e88be92958be29
4,484
py
Python
_scripts/import_resources.py
marcomicera/guide
4135647f4730ae95f6b830330a0e0e7f6e2f6e43
[ "CC-BY-4.0" ]
40
2020-03-12T20:54:40.000Z
2021-12-21T19:35:20.000Z
_scripts/import_resources.py
marcomicera/guide
4135647f4730ae95f6b830330a0e0e7f6e2f6e43
[ "CC-BY-4.0" ]
366
2020-03-12T19:56:21.000Z
2021-09-28T01:06:32.000Z
_scripts/import_resources.py
marcomicera/guide
4135647f4730ae95f6b830330a0e0e7f6e2f6e43
[ "CC-BY-4.0" ]
44
2020-03-13T02:27:47.000Z
2020-06-04T16:53:43.000Z
#!/usr/bin/env python3 import argparse import csv import datetime import io import os import re import requests import yaml # Resource spreadsheet contents are published at this URL in the form of CSV RESOURCES_URL="https://docs.google.com/spreadsheets/d/e/2PACX-1vQMEdZXKgYNybkqNv4X26CVNoQZHuE0zb27wuBDgdDwtiyWCICQLhyU_LuLJVeHD5oTRnp-bEdFTuqi/pub?gid=650653420&single=true&output=csv" parser = argparse.ArgumentParser(description='Parse arguments for this script.') parser.add_argument('--dryrun', '-n', default=False, action="store_true", help='Only print out what would be done.') parser.add_argument('--clobber', default=False, action="store_true", help='Overwrite existing resource files.') args = parser.parse_args() """Commandline argument values are stored here.""" REQUIRED_COLUMNS = ['name', 'category', 'description'] """These columns must be non-empty for the row to be accepted.""" EXTRACT_ATTRIBUTES = ['name', 'category', 'country', 'state', 'target'] """Columns that will be added into MD file as attributes, in this order.""" def make_row_filename(row): """Constructs standardized base filename for this resource. Adds timestamp prefix, lowercased alphanumeric character from the title are retained, spaces replaced with dashes and total length of title limited at 35 characters. Returns the resulting base filename. """ sanitized_name = row['name'].lower().replace(" ", "-") sanitized_name = re.sub(r'[^-a-zA-Z0-9]', '', sanitized_name) sanitized_name = re.sub(r'--*', '-', sanitized_name) sanitized_name = sanitized_name[:35].strip("-") dt = datetime.datetime.strptime( row['timestamp'].split()[0], '%m/%d/%Y').date() return f'{dt.isoformat()}-{sanitized_name}.md' def format_row_contents(row): """Generate MD output for each row.""" attributes = {} for attr in EXTRACT_ATTRIBUTES: if row.get(attr, None): attributes[attr] = row[attr].strip() all_attributes = yaml.dump(attributes, default_flow_style=False) return (f"---\n{all_attributes}\n---\n\n{row['description'].strip()}") def get_resource_dir(): """Finds _resources/ directory or terminates this script.""" for res in ['_resources/', '../_resources']: if os.path.isdir(res): return res sys.exit("Can't find _resources/ directory.") return None USA_COUNTRY_NAMES = ['us', 'united states', 'united states of america'] def normalize_country_name(input_country): """Returns canonical country name.""" if input_country.strip().lower() in USA_COUNTRY_NAMES: return 'USA' return input_country COLUMN_FILTERS = { 'country': normalize_country_name, 'description': lambda x: x.replace("Covid-19", "COVID-19"), } def apply_filters(row): """Applies filters to the input data and returns transformed row.""" return {k: COLUMN_FILTERS.get(k, lambda x: x)(v) for k,v in row.items()} def main(): resource_dir = get_resource_dir() resources = requests.get(RESOURCES_URL) resources.encoding = 'utf-8' rows = csv.DictReader(io.StringIO(resources.text)) rows_accepted = 0 for row_num, row in enumerate(rows, start=2): # Skip if approved_by column is not populated if not row.get('approved_by', None): print(f'Row {row_num} not approved - skipping. URL: {row.get("url", None)}') # Check that all required columns are present has_required = True for reqd in REQUIRED_COLUMNS: if not row.get(reqd, None): print(f"Row {row_num} skipped. It is missing required column '{reqd}'.") has_required = False break if not has_required: continue row = apply_filters(row) filename = os.path.join(resource_dir, make_row_filename(row)) if os.path.isfile(filename) and not args.clobber: print(f"Resource file {filename} already exists, skipping.") continue rows_accepted += 1 if args.dryrun: print(f"*** Dry run *** {filename} would contain:") print(format_row_contents(row)) continue with open(filename, encoding='utf-8', mode='w+') as out_file: out_file.write(format_row_contents(row)) out_file.close() print(f'(Re)generated {rows_accepted} resource files.') if __name__ == '__main__': main()
35.872
184
0.660348
48ce048e11cded53a323068946bf8d6948738aca
194
py
Python
cs/python/python_general/30-seconds-of-python-code/test/bubble_sort/bubble_sort.py
tobias-fyi/vela
b0b3d3c6dc3fa397c8c7a492098a02cf75e0ff82
[ "MIT" ]
null
null
null
cs/python/python_general/30-seconds-of-python-code/test/bubble_sort/bubble_sort.py
tobias-fyi/vela
b0b3d3c6dc3fa397c8c7a492098a02cf75e0ff82
[ "MIT" ]
8
2020-03-24T17:47:23.000Z
2022-03-12T00:33:21.000Z
cs/python/python_general/30-seconds-of-python-code/test/bubble_sort/bubble_sort.py
tobias-fyi/vela
b0b3d3c6dc3fa397c8c7a492098a02cf75e0ff82
[ "MIT" ]
null
null
null
def bubble_sort(lst): for passnum in range(len(lst) - 1, 0, -1): for i in range(passnum): if lst[i] > lst[i + 1]: lst[i], lst[i + 1] = lst[i + 1], lst[i]
32.333333
55
0.463918
48fcfe6dbcb9299ce37829584ddd593124856857
2,068
py
Python
synchroload/downloader.py
rakennus/duraphilms.github.io
bdbecdfb55f4870b5ebf572cd2a7eb4e6770ea22
[ "MIT" ]
3
2020-07-08T08:58:46.000Z
2020-12-01T20:23:30.000Z
synchroload/downloader.py
rakennus/duraphilms.github.io
bdbecdfb55f4870b5ebf572cd2a7eb4e6770ea22
[ "MIT" ]
1
2020-12-30T12:49:43.000Z
2021-01-04T11:05:48.000Z
synchroload/downloader.py
rakennus/duraphilms.github.io
bdbecdfb55f4870b5ebf572cd2a7eb4e6770ea22
[ "MIT" ]
2
2018-06-21T17:45:11.000Z
2020-12-30T00:30:45.000Z
import youtube_dl import urllib.error import ffmpeg import json import requests def check_availability(url): try: youtube_dl.YoutubeDL({"quiet": True}).extract_info( url, download=False ) except urllib.error.HTTPError: return False except youtube_dl.utils.ExtractorError: return False except youtube_dl.utils.DownloadError: # Copyright return False except: return False return True def download(url, basename): fullname = basename + ".mkv" ydl = youtube_dl.YoutubeDL({ 'format': "bestvideo[ext=mp4]+bestaudio[ext=m4a]/bestvideo[ext=webm]+bestaudio[ext=webm]", 'outtmpl': fullname, "merge_output_format": "mkv" }) try: ydl.extract_info(url) except urllib.error.HTTPError: return "" except youtube_dl.utils.ExtractorError: return "" except youtube_dl.utils.DownloadError: # Copyright return "" except: return "" probe = ffmpeg.probe(fullname) outputName = basename + "." if probe["streams"][0]["codec_name"] == "vp9": outputName += "webm" elif probe["streams"][0]["codec_name"] == "h264": outputName += "mp4" else: outputName += "mkv" inputStream = ffmpeg.input(fullname) outputStream = ffmpeg.output( inputStream, outputName, c="copy", movflags="+faststart", strict="-2" ) ffmpeg.run(outputStream, overwrite_output=True) return outputName def downloadDirect(url, basename): print("[downloader] Downloading {}...".format(url)) local_filename = basename + "." + url.split('.')[-1] # NOTE the stream=True parameter below with requests.get(url, stream=True) as r: r.raise_for_status() with open(local_filename, 'wb') as f: for chunk in r.iter_content(chunk_size=8192): if chunk: # filter out keep-alive new chunks f.write(chunk) # f.flush() return local_filename
26.512821
98
0.605899
826ac521bd67fb134c951e620cb081c99e44d3ea
3,495
py
Python
garnet/lib/magma/include/magma_abi/magma.h.gen.py
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
3
2020-08-02T04:46:18.000Z
2020-08-07T10:10:53.000Z
garnet/lib/magma/include/magma_abi/magma.h.gen.py
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
null
null
null
garnet/lib/magma/include/magma_abi/magma.h.gen.py
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
1
2020-08-07T10:11:49.000Z
2020-08-07T10:11:49.000Z
#!/usr/bin/env python2.7 # Copyright 2019 The Fuchsia Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import textwrap import sys def usage(): print 'Usage:' print ' magma.h.gen.py INPUT OUTPUT' print ' INPUT json file containing the magma interface definition' print ' OUTPUT destination path for the magma header file to generate' print ' Example: ./magma.h.gen.py ./magma.json ./magma.h' print ' Generates the magma header based on a provided json definition.' print ' Description fields are generated in the Doxygen format.' # Generate a string for a comment with a Doxygen tag, wrapping text as necessary. def format_comment(type, comment): wrap = 100 prefix_first = '/// \\' + type + ' ' prefix_len = len(prefix_first) prefix_rest = '///'.ljust(prefix_len) lines = textwrap.wrap(comment, wrap - prefix_len) formatted = prefix_first + lines[0] + '\n' for line in lines[1:]: formatted += prefix_rest + line + '\n' return formatted # Generate a string for a magma export object, including its comment block. def format_export(export): signature = export['type'] + ' ' + export['name'] + '(\n' comment = '///\n' + format_comment('brief', export['description']) for argument in export['arguments']: signature += ' ' + argument['type'] + ' ' + argument['name'] + ',\n' comment += format_comment('param', argument['name'] + ' ' + argument['description']) signature = signature[:-2] + ');\n' comment += '///\n' return comment + signature # License string for the top of the file. def license(): ret = '' ret += '// Copyright 2016 The Fuchsia Authors. All rights reserved.\n' ret += '// Use of this source code is governed by a BSD-style license that can be\n' ret += '// found in the LICENSE file.\n' return ret # Guard macro that goes at the beginning/end of the header (after license). def guards(begin): macro = 'GARNET_LIB_MAGMA_INCLUDE_MAGMA_ABI_MAGMA_H_' if begin: return '#ifndef ' + macro + '\n#define ' + macro + '\n' return '#endif // ' + macro # Begin/end C linkage scope. def externs(begin): if begin: return '#if defined(__cplusplus)\nextern "C" {\n#endif\n' return '#if defined(__cplusplus)\n}\n#endif\n' # Includes list. def includes(): ret = '' ret += '#include "magma_common_defs.h"\n' ret += '#include <stdint.h>\n' return ret # Warning comment about auto-generation. def genwarning(): ret = '// NOTE: DO NOT EDIT THIS FILE!\n' ret += '// It is automatically generated by //garnet/lib/magma/include/magma_abi/magma.h.gen.py\n' return ret def genformatoff(): return '// clang-format off\n' def main(): if (len(sys.argv) != 3): usage() exit(-1) try: with open(sys.argv[1], 'r') as file: with open(sys.argv[2], 'w') as dest: magma = json.load(file)['magma-interface'] header = license() + '\n' header += genwarning() + '\n' header += genformatoff() + '\n' header += guards(True) + '\n' header += includes() + '\n' header += externs(True) + '\n' for export in magma['exports']: header += format_export(export) + '\n' header += externs(False) + '\n' header += guards(False) + '\n' dest.write(header) except Exception as e: print 'Error accessing files: ' + str(e) usage() exit(-2) if __name__ == '__main__': sys.exit(main())
33.285714
100
0.640343
6fae78f92edd0d3e68d62c2820e4b929ea7711da
112
py
Python
src/tests/create_genesis_block.py
TimmMoetz/blockchain-lab
02bb55cc201586dbdc8fdc252a32381f525e83ff
[ "RSA-MD" ]
2
2021-11-08T12:00:02.000Z
2021-11-12T18:37:52.000Z
src/tests/create_genesis_block.py
TimmMoetz/blockchain-lab
02bb55cc201586dbdc8fdc252a32381f525e83ff
[ "RSA-MD" ]
null
null
null
src/tests/create_genesis_block.py
TimmMoetz/blockchain-lab
02bb55cc201586dbdc8fdc252a32381f525e83ff
[ "RSA-MD" ]
1
2022-03-28T13:49:37.000Z
2022-03-28T13:49:37.000Z
from src.blockchain.blockchain import Blockchain blockchain = Blockchain() blockchain.create_genesis_block()
28
49
0.830357
fb512327ca77e49a71a0d3621749800cb1b38b40
8,759
py
Python
official/cv/vit/train.py
leelige/mindspore
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
[ "Apache-2.0" ]
1
2021-11-18T08:17:44.000Z
2021-11-18T08:17:44.000Z
official/cv/vit/train.py
leelige/mindspore
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
[ "Apache-2.0" ]
null
null
null
official/cv/vit/train.py
leelige/mindspore
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
[ "Apache-2.0" ]
2
2019-09-01T06:17:04.000Z
2019-10-04T08:39:45.000Z
# Copyright 2021 Huawei Technologies Co., Ltd # # 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. # ============================================================================ """training script""" import os import time import socket import numpy as np from mindspore import context from mindspore import Tensor from mindspore.train.model import Model, ParallelMode from mindspore.train.callback import ModelCheckpoint, CheckpointConfig from mindspore.train.loss_scale_manager import FixedLossScaleManager from mindspore.communication.management import init from mindspore.profiler.profiling import Profiler from mindspore.train.serialization import load_checkpoint import mindspore.dataset as ds from src.vit import get_network from src.dataset import get_dataset from src.cross_entropy import get_loss from src.optimizer import get_optimizer from src.lr_generator import get_lr from src.eval_engine import get_eval_engine from src.callback import StateMonitor from src.logging import get_logger from src.model_utils.config import config from src.model_utils.moxing_adapter import moxing_wrapper try: os.environ['MINDSPORE_HCCL_CONFIG_PATH'] = os.getenv('RANK_TABLE_FILE') device_id = int(os.getenv('DEVICE_ID')) # 0 ~ 7 local_rank = int(os.getenv('RANK_ID')) # local_rank device_num = int(os.getenv('RANK_SIZE')) # world_size print("distribute training") except TypeError: device_id = 0 # 0 ~ 7 local_rank = 0 # local_rank device_num = 1 # world_size print("standalone training") def add_static_args(args): """add_static_args""" args.weight_decay = float(args.weight_decay) args.eval_engine = 'imagenet' args.split_point = 0.4 args.poly_power = 2 args.aux_factor = 0.4 args.seed = 1 args.auto_tune = 0 if args.eval_offset < 0: args.eval_offset = args.max_epoch % args.eval_interval args.device_id = device_id args.local_rank = local_rank args.device_num = device_num args.dataset_name = 'imagenet' return args def modelarts_pre_process(): '''modelarts pre process function.''' start_t = time.time() val_file = os.path.join(config.data_path, 'val/imagenet_val.tar') train_file = os.path.join(config.data_path, 'train/imagenet_train.tar') tar_files = [val_file, train_file] print('tar_files:{}'.format(tar_files)) for tar_file in tar_files: if os.path.exists(tar_file): t1 = time.time() tar_dir = os.path.dirname(tar_file) print('cd {}; tar -xvf {} > /dev/null 2>&1'.format(tar_dir, tar_file)) os.system('cd {}; tar -xvf {} > /dev/null 2>&1'.format(tar_dir, tar_file)) t2 = time.time() print('uncompress, time used={:.2f}s'.format(t2 - t1)) os.system('cd {}; rm -rf {}'.format(tar_dir, tar_file)) else: print('file no exists:', tar_file) end_t = time.time() print('tar cost time {:.2f} sec'.format(end_t-start_t)) @moxing_wrapper(pre_process=modelarts_pre_process) def train_net(): """train_net""" args = add_static_args(config) np.random.seed(args.seed) args.logger = get_logger(args.save_checkpoint_path, rank=local_rank) context.set_context(device_id=device_id, mode=context.GRAPH_MODE, device_target="Ascend", save_graphs=False) if args.auto_tune: context.set_context(auto_tune_mode='GA') elif args.device_num == 1: pass else: context.set_auto_parallel_context(device_num=device_num, parallel_mode=ParallelMode.DATA_PARALLEL, gradients_mean=True) if args.open_profiler: profiler = Profiler(output_path="data_{}".format(local_rank)) # init the distribute env if not args.auto_tune and args.device_num > 1: init() # network net = get_network(backbone_name=args.backbone, args=args) # set grad allreduce split point parameters = [param for param in net.trainable_params()] parameter_len = len(parameters) if args.split_point > 0: print("split_point={}".format(args.split_point)) split_parameter_index = [int(args.split_point*parameter_len),] parameter_indices = 1 for i in range(parameter_len): if i in split_parameter_index: parameter_indices += 1 parameters[i].comm_fusion = parameter_indices else: print("warning!!!, no split point") if os.path.isfile(args.pretrained): load_checkpoint(args.pretrained, net, strict_load=False) # loss if not args.use_label_smooth: args.label_smooth_factor = 0.0 loss = get_loss(loss_name=args.loss_name, args=args) # train dataset epoch_size = args.max_epoch dataset = get_dataset(dataset_name=args.dataset_name, do_train=True, dataset_path=args.dataset_path, args=args) ds.config.set_seed(args.seed) step_size = dataset.get_dataset_size() args.steps_per_epoch = step_size # evaluation dataset eval_dataset = get_dataset(dataset_name=args.dataset_name, do_train=False, dataset_path=args.eval_path, args=args) # evaluation engine if args.auto_tune or args.open_profiler or eval_dataset is None or args.device_num == 1: args.eval_engine = '' eval_engine = get_eval_engine(args.eval_engine, net, eval_dataset, args) # loss scale loss_scale = FixedLossScaleManager(args.loss_scale, drop_overflow_update=False) # learning rate lr_array = get_lr(global_step=0, lr_init=args.lr_init, lr_end=args.lr_min, lr_max=args.lr_max, warmup_epochs=args.warmup_epochs, total_epochs=epoch_size, steps_per_epoch=step_size, lr_decay_mode=args.lr_decay_mode, poly_power=args.poly_power) lr = Tensor(lr_array) # optimizer, group_params used in grad freeze opt, _ = get_optimizer(optimizer_name=args.opt, network=net, lrs=lr, args=args) # model model = Model(net, loss_fn=loss, optimizer=opt, metrics=eval_engine.metric, eval_network=eval_engine.eval_network, loss_scale_manager=loss_scale, amp_level="O3") eval_engine.set_model(model) args.logger.save_args(args) t0 = time.time() # equal to model._init(dataset, sink_size=step_size) eval_engine.compile(sink_size=step_size) t1 = time.time() args.logger.info('compile time used={:.2f}s'.format(t1 - t0)) # callbacks state_cb = StateMonitor(data_size=step_size, tot_batch_size=args.batch_size * device_num, lrs=lr_array, eval_interval=args.eval_interval, eval_offset=args.eval_offset, eval_engine=eval_engine, logger=args.logger.info) cb = [state_cb,] if args.save_checkpoint and local_rank == 0: config_ck = CheckpointConfig(save_checkpoint_steps=args.save_checkpoint_epochs*step_size, keep_checkpoint_max=args.keep_checkpoint_max, async_save=True) ckpt_cb = ModelCheckpoint(prefix=args.backbone, directory=args.save_checkpoint_path, config=config_ck) cb += [ckpt_cb] t0 = time.time() model.train(epoch_size, dataset, callbacks=cb, sink_size=step_size) t1 = time.time() args.logger.info('training time used={:.2f}s'.format(t1 - t0)) last_metric = 'last_metric[{}]'.format(state_cb.best_acc) args.logger.info(last_metric) is_cloud = args.enable_modelarts if is_cloud: ip = os.getenv("BATCH_TASK_CURRENT_HOST_IP") else: ip = socket.gethostbyname(socket.gethostname()) args.logger.info('ip[{}], mean_fps[{:.2f}]'.format(ip, state_cb.mean_fps)) if args.open_profiler: profiler.analyse() if __name__ == '__main__': train_net()
36.045267
110
0.651102
83df9fade56aa0f79808eae6d13ab65f51bb6eab
4,090
py
Python
files/meas/Experiment_03/int/unitstep.py
mimeiners/ans
382e000e687d5ec0c80a84223087e60ed656a1dd
[ "MIT" ]
null
null
null
files/meas/Experiment_03/int/unitstep.py
mimeiners/ans
382e000e687d5ec0c80a84223087e60ed656a1dd
[ "MIT" ]
null
null
null
files/meas/Experiment_03/int/unitstep.py
mimeiners/ans
382e000e687d5ec0c80a84223087e60ed656a1dd
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Fri May 21 10:10:10 2021 @author: © Vadim Grebnev, Tim Hilker, Delphino Klinker """ import ltspice import matplotlib.pyplot as plt import matplotlib.ticker as mplt import numpy as np import redpitaya_scpi as scpi from time import sleep as delay import matplotlib matplotlib.use('Agg') #%% paths and adresses filename = 'unitstep' ELIE4 = '192.168.111.184' ELIE5 = '192.168.111.185' ELIE6 = '192.168.111.186' #%% measurement via RedPitaya # check if data was already saved for skip try: data = np.loadtxt('../../data/int/rect.csv', dtype='float', comments='#', delimiter='\t', converters=None, skiprows=0, unpack=False, ndmin=0) saved = True except OSError: print("No saved data found, begin setup and measurement!") saved = False save_plot = True time_factor = 1e6 # factor for x-axis voltage_division = 10 # Voltage divison factor # settings of the Red Pitaya waveform = 'SQUARE' # waveform of the Inputsignal Amp = 0.5 # amplitude of the input signal downsampling = 32 # downsamplingrate (decimation factor) triggerdt = '8192' # trigger delay sampling_rate = 125e6 # 125 MS/s # sampling rate with regard to actual decimation factor effective_sampling_rate = sampling_rate/downsampling buffer_size = 2**14 # 14 bit # taking sample every sampling_interval seconds sampling_interval = 1/effective_sampling_rate # total buffer size in seconds total_time = sampling_interval*buffer_size if not saved: print("Couldn't find data.") exit() dat = list() dat.append(data[:,0]) dat.append(data[:,1]) dat.append(data[:,2]) start = 910 end = start + int(0.6e-3/sampling_interval+2) # start plus 600 us dat[0] = np.arange(0, end-start, 1)*sampling_interval dat[1] = dat[1][start:end] dat[2] = dat[2][start:end] #%% set plotting window configurations plt.close('all') # close all figure windows plt.rc('xtick', labelsize=16) # fontsize of tick labels of x axis plt.rc('ytick', labelsize=16) # fontsize of tick labels of y axis plt.rc('axes', labelsize=20) # fontsize of text labels of both axis plt.rc('axes', titlesize=24) # fontsize of the title text plt.rc('lines', lw=1) # default linewidth plt.rc('legend', fontsize=18) # fontsize of the legend #%% plot of LTspice simulation and meassured data of an integrator circuit s1 = ltspice.Ltspice('../../spice/int/unitstep/unitstep-py.raw') s1.parse() t1 = s1.getTime()*time_factor Vin = s1.getData('V(input)') Vout = s1.getData('V(output)') fig = plt.figure(filename.upper().replace('_', ' ')) fig.set_size_inches(19.20, 10.80) ax1 = fig.add_subplot(211, projection='rectilinear') ax1.set_title('Simulation') ax1.set_xlabel(r'Zeit t in Mikrosekunden [$\mu$s]') ax1.set_ylabel(r'Spannung in Volt [V]') ax1.plot(t1, Vin, 'b-', label=r'LTspice $V_{In}$') for label in ax1.get_yticklabels(): label.set_color('blue') ax1.grid(linewidth=0.5) ax1.legend(loc='center left') # ax2 = ax1.twinx() ax2.plot(t1, Vout, 'r-', label=r'LTspice $V_{Out}$') ax2.set_xlim(min(t1), max(t1)) ax2.set_ylim(-9.5,9.5) for label in ax2.get_yticklabels(): label.set_color('red') ax2.legend(loc='center right') # ax3 = fig.add_subplot(212, projection='rectilinear') ax3.set_title('Messung') ax3.set_xlabel(r'Zeit t in Mikrosekunden [$\mu$s]') ax3.set_ylabel('Spannung in Volt [V]') ax3.plot(dat[0]*time_factor, dat[1], 'b.-', markersize=2, label=r'Messung $V_{In}$') for label in ax3.get_yticklabels(): label.set_color('blue') ax3.legend(loc='center left') # ax4 = ax3.twinx() ax4.plot(dat[0]*time_factor, dat[2], 'r.-', markersize=2, label=r'Messung $V_{Out}$') ax4.set_xlim(min(dat[0])*time_factor, max(dat[0])*time_factor) ax4.set_ylim(-9.5,9.5) for label in ax4.get_yticklabels(): label.set_color('red') ax4.grid(linewidth=0.5) ax4.legend(loc='center right') plt.tight_layout() plt.show() # save plot if save_plot: plt.savefig('../../fig/int/'+filename+".png") # save as .png-file plt.savefig('../../fig/int/'+filename+".svg") # save as .svg-file #%% EOF
28.802817
77
0.689487
5846202d18b8697fc5163cfb097f2ffd20b5ee97
3,002
py
Python
Lab1/script.py
ishaanx/Labs
9080e052a1655af28f14fcf3e777bf2a994f6543
[ "MIT" ]
null
null
null
Lab1/script.py
ishaanx/Labs
9080e052a1655af28f14fcf3e777bf2a994f6543
[ "MIT" ]
null
null
null
Lab1/script.py
ishaanx/Labs
9080e052a1655af28f14fcf3e777bf2a994f6543
[ "MIT" ]
null
null
null
## Lab 101 # Generate triangle def tri(n): for i in range(0,n): for j in range(0,i+1): print("* ",end="") print("\r") n=5 tri(n) # Print int, float, string def types(): x=5.555 print(int(x)) print(float(x)) print(str(x)) types() # Print List def list(): mylist= ["apple","orange"] print(mylist) list() # Print Tuple def tuple(): mytuple=("apple","bananas") print(mytuple) tuple() ## Create a program that asks the user to enter ## their name and their age. Print out a message ## addressed to them that tells them the year that ## they will turn 100 years old. import datetime as dt from random import randint def userprint(): print("Enter your name: ") myname=input() print("Enter your age: ") myage=input() myear=2050 current_year = dt.date.today().year age_calc = int(current_year) - int(myage) hundred_year = age_calc + 100 print("Hi " + myname + ", you will turn 100 years old in the year "+ str(hundred_year)) userprint() ## Ask the user for a number. Depending on ## whether the number is even or odd, print out an ## appropriate message to the user. def evenodd(): x = int(input("Enter a number: ")) if (x%2)==0: print("Number is even") else: print("Number is odd") evenodd() ## Write a program that accepts a sentence and calculate the number of letters and digits. def counting(): total_numbers = 0 total_strings = 0 string = str(input("Enter any string: ")) for s in string: if s.isnumeric(): total_numbers += 1 else: total_strings += 1 print("Total letters found: ",total_strings) print("Total digits found: ",total_numbers) counting() ## Define a function which can compute the sum of two numbers. def sum(): a= int(input("Enter first number: ")) b = int(input("Enter second number: ")) c = a + b print("The sum is: ", c) sum() ## Create a 8 character alphanumeric string random password generator. def paswd(): import random pass_data = "qwertyuiopasdfgjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890[];',./!@#$%^&*()_+:<>?" password = "".join(random.sample(pass_data, 8)) print(password) paswd() ## Write a function to compute 5/0 and use try/except to catch the exceptions. def five(): try: x = 5/0 except ZeroDivisionError: print("Cannot divide by zero") five() ## Generate a random number between 1 and 9 ## (including 1 and 9). Ask the user to guess the ## number, then tell them whether they guessed ## too low, too high, or exactly right. def random_gen(): import random userNumber = int(input("Enter any number: ")) randomNumber = randint(1,9) if userNumber == randomNumber: print("You guessed the exact number!") elif userNumber < randomNumber: print("You guessed too low") else: print("You guessed too high") random_gen() ##
25.65812
102
0.627915
54ad255b370fc1a79dfa3a9d672943d3f7d8b38c
45
py
Python
python_lessons/Textastic_Files/HelloDatabase.py
1986MMartin/coding-sections-markus
e13be32e5d83e69250ecfb3c76a04ee48a320607
[ "Apache-2.0" ]
null
null
null
python_lessons/Textastic_Files/HelloDatabase.py
1986MMartin/coding-sections-markus
e13be32e5d83e69250ecfb3c76a04ee48a320607
[ "Apache-2.0" ]
null
null
null
python_lessons/Textastic_Files/HelloDatabase.py
1986MMartin/coding-sections-markus
e13be32e5d83e69250ecfb3c76a04ee48a320607
[ "Apache-2.0" ]
null
null
null
import sqlite3 import os os.system('clear')
9
18
0.755556
49cf336641301a5749a095b18a6b00a851f8b532
162
py
Python
python_lessons/Textastic_Files/HelloWorld_Python.py
1986MMartin/coding-sections-markus
e13be32e5d83e69250ecfb3c76a04ee48a320607
[ "Apache-2.0" ]
null
null
null
python_lessons/Textastic_Files/HelloWorld_Python.py
1986MMartin/coding-sections-markus
e13be32e5d83e69250ecfb3c76a04ee48a320607
[ "Apache-2.0" ]
null
null
null
python_lessons/Textastic_Files/HelloWorld_Python.py
1986MMartin/coding-sections-markus
e13be32e5d83e69250ecfb3c76a04ee48a320607
[ "Apache-2.0" ]
null
null
null
# import # Hier kommt ein Kommentar für das erste Programm, geschrieben am iPad. print("Hello World 1") # Hier kommt nochmal ein Kommentar. print("Hallo Welt 2")
32.4
71
0.753086
3f8804ab953994c198ce1274f3581b92c6bc77b9
31,003
py
Python
sam_core/sam_core/utils_perf.py
csjy309450/SAM-Backend
a23569ea372f718ca4a167e21e8046336db00561
[ "MIT" ]
null
null
null
sam_core/sam_core/utils_perf.py
csjy309450/SAM-Backend
a23569ea372f718ca4a167e21e8046336db00561
[ "MIT" ]
null
null
null
sam_core/sam_core/utils_perf.py
csjy309450/SAM-Backend
a23569ea372f718ca4a167e21e8046336db00561
[ "MIT" ]
null
null
null
import json import os import datetime from sam_core.res_obj import * from sam_app.model_layer.model import * class UtilPerfLinux: def get_perf_info(self) -> ResPerfInfo: host_run_time = None host_idle_time = None login_user_count = None cpu_count = None load_level = None proc_count = None mem_size = None swap_size = None disk_size = None disk_usage = [] session = Session() db_item = session.query(PerfSummaryValues).all() print("T|db_item", db_item) for it in db_item: if it.key == SUMMARY_KEY_HOST_RUN_TIME: host_run_time = it.value_int print('T|host_run_time ', host_run_time) elif it.key == SUMMARY_KEY_HOST_IDLE_TIME: host_idle_time = it.value_int print('T|host_idle_time ', host_idle_time) elif it.key == SUMMARY_KEY_LOGIN_USER_COUNT: login_user_count = it.value_int print('T|login_user_count ', login_user_count) elif it.key == SUMMARY_KEY_CPU_COUNT: cpu_count = it.value_int print('T|cpu_count ', cpu_count) elif it.key == SUMMARY_KEY_LOAD_LEVE: load_level = it.value_int print('T|load_level ', load_level) elif it.key == SUMMARY_KEY_PROC_COUNT: proc_count = it.value_int print('T|proc_count ', proc_count) elif it.key == SUMMARY_KEY_MEMORY_SIZE: mem_size = it.value_int print('T|mem_size ', mem_size) elif it.key == SUMMARY_KEY_SWAP_SIZE: swap_size = it.value_int print('T|swap_size ', swap_size) elif it.key == SUMMARY_KEY_DISK_SIZE: disk_size = it.value_int print('T|disk_size ', disk_size) elif it.key == SUMMARY_KEY_DISK_USAGE: disk_usage = json.loads(it.value_str) print('T|disk_usage ', disk_usage) str_runtime = '' if not host_run_time else self.__get_runtime_str(int(host_run_time)) print("T|str_runtime", str_runtime) host_idle_rate = None if not host_idle_time and not host_run_time else int( host_idle_time / (host_run_time * cpu_count) * 100) print("T|host_idle_rate", host_idle_rate) # get loads '''时间获取获取最近30个采样''' last_30_loads_date = session.query(PerfLoadsHistory.date).order_by( PerfLoadsHistory.date.desc()).distinct().limit( 30).all() last_30_loads_date = [i[0] for i in last_30_loads_date] last_30_loads_date.sort() print('T|last_30_loads_date ', last_30_loads_date) last_30_loads = session.query(PerfLoadsHistory).filter(PerfLoadsHistory.date.in_(last_30_loads_date)).all() print('T|last_30_loads ', last_30_loads) date = [] one_min = [] five_min = [] fiften_min = [] for it in last_30_loads: date.append(it.date.strftime('%c')) one_min.append(it.one_min) five_min.append(it.five_min) fiften_min.append(it.fiften_min) one_min = [0] * (len(date) - len(one_min)) + one_min five_min = [0] * (len(date) - len(five_min)) + five_min fiften_min = [0] * (len(date) - len(fiften_min)) + fiften_min load_info = ResLoadInfo( level=load_level, date=date, one_min=one_min, five_min=one_min, fiften_min=one_min ) # get process # last_30_proc_stat last_30_proc_stat_date = session.query(PerfProcStatDistributionHistory.date).order_by( PerfProcStatDistributionHistory.date.desc()).distinct().limit( 30).all() last_30_proc_stat_date = [i[0] for i in last_30_proc_stat_date] last_30_proc_stat_date.sort() print('T|last_30_loads_date ', last_30_proc_stat_date) last_30_proc_stat = session.query(PerfProcStatDistributionHistory).filter( PerfProcStatDistributionHistory.date.in_(last_30_proc_stat_date)).all() print('T|last_30_proc_stat ', last_30_proc_stat) proc_stat_distribution = [ ["Stat", []], ["T", []], ["S", []], ["I", []], ["Z", []], ["D", []], ["P", []], ["W", []], ["X", []], ["<", []], ["N", []], ["L", []], ["s", []], ["l", []] ] for it in last_30_proc_stat: proc_stat_distribution[0][1].append(it.date.strftime('%c')) proc_stat_distribution[1][1].append(it.T) proc_stat_distribution[2][1].append(it.S) proc_stat_distribution[3][1].append(it.I) proc_stat_distribution[4][1].append(it.Z) proc_stat_distribution[5][1].append(it.D) proc_stat_distribution[6][1].append(it.P) proc_stat_distribution[7][1].append(it.W) proc_stat_distribution[8][1].append(it.X) proc_stat_distribution[9][1].append(it.H) proc_stat_distribution[10][1].append(it.N) proc_stat_distribution[11][1].append(it.L) proc_stat_distribution[12][1].append(it.thx_father) proc_stat_distribution[13][1].append(it.multi_thx) for it in proc_stat_distribution: it[1] = [0] * (len(last_30_proc_stat_date) - len(it[1])) + it[1] # proc_user_distribution last_30_proc_user_date = session.query(PerfProcUserDistributionHistory.date).order_by( PerfProcUserDistributionHistory.date.desc()).distinct().limit( 30).all() last_30_proc_user_date = [i[0] for i in last_30_proc_user_date] last_30_proc_user_date.sort() print('T|last_30_proc_user_date ', last_30_proc_user_date) last_30_proc_user = session.query(PerfProcUserDistributionHistory).filter( PerfProcStatDistributionHistory.date.in_(last_30_proc_user_date)).all() print('T|last_30_proc_user ', last_30_proc_user) proc_user_distribution = {} proc_user_distribution['User'] = [i.strftime('%c') for i in last_30_proc_user_date] for it in last_30_proc_user: if it.user_name not in proc_user_distribution: proc_user_distribution[it.user_name] = [] proc_user_distribution[it.user_name].append(it.proc_count) for it in proc_user_distribution: proc_user_distribution[it] = [0] * (len(last_30_proc_user_date) - len(proc_user_distribution[it])) + \ proc_user_distribution[it] proc_info = ResProcInfo( proc_count=proc_count, proc_stat_distribution=proc_stat_distribution, proc_user_distribution=proc_user_distribution ) # cpu last_30_cpu_date = session.query(PerfCpuUsageRateHistory.date).order_by( PerfCpuUsageRateHistory.date.desc()).distinct().limit( 30).all() last_30_cpu_date = [i[0] for i in last_30_cpu_date] last_30_cpu_date.sort() print('T|last_30_cpu_date ', last_30_cpu_date) last_30_cpu_usage = session.query(PerfCpuUsageRateHistory).filter( PerfCpuUsageRateHistory.date.in_(last_30_cpu_date)).all() print('T|last_30_cpu_usage ', last_30_cpu_usage) cpu_usage_rate = {} cpu_usage_rate['Cpu'] = [i.strftime('%c') for i in last_30_cpu_date] for it in last_30_cpu_usage: if it.cpu_name not in last_30_cpu_usage: cpu_usage_rate[it.cpu_name] = [] cpu_usage_rate[it.cpu_name].append(it.use_rate) for it in cpu_usage_rate: cpu_usage_rate[it] = [0] * (len(last_30_cpu_date) - len(cpu_usage_rate[it])) + \ cpu_usage_rate[it] cpu_info = ResCpuInfo( cpu_count=cpu_count, cpu_usage_rate=cpu_usage_rate ) # mem last_30_mem_usage_date = session.query(PerfMemUsageHistory.date).order_by( PerfMemUsageHistory.date.desc()).distinct().limit( 30).all() last_30_mem_usage_date = [i[0] for i in last_30_mem_usage_date] last_30_mem_usage_date.sort() print('T|last_30_mem_usage_date ', last_30_mem_usage_date) last_30_mem_usage = session.query(PerfMemUsageHistory).filter( PerfMemUsageHistory.date.in_(last_30_mem_usage_date)).all() print('T|last_30_mem_usage ', last_30_mem_usage) date = [] mem_usage = [] swap_usage = [] for it in last_30_mem_usage: date.append(it.date.strftime('%c')) mem_usage.append([it.mem_use, it.mem_free, it.mem_buffer]) swap_usage.append([it.swap_use, it.swap_free]) memory_info = ResMemoryInfo( date=date, mem_size=mem_size, mem_usage=mem_usage, swap_size=swap_size, swap_usage=swap_usage ) # disk last_30_disk_io_rate_date = session.query(PerfDiskIoRateHistory.date).order_by( PerfDiskIoRateHistory.date.desc()).distinct().limit( 30).all() last_30_disk_io_rate_date = [i[0] for i in last_30_disk_io_rate_date] last_30_disk_io_rate_date.sort() print('T|last_30_disk_io_rate_date ', last_30_disk_io_rate_date) last_30_disk_io_rate = session.query(PerfDiskIoRateHistory).filter( PerfDiskIoRateHistory.date.in_(last_30_disk_io_rate_date)).all() print('T|last_30_disk_io_rate ', last_30_disk_io_rate) date = [] disk_io_rate = {} for it in last_30_disk_io_rate: date.append(it.date.strftime("%c")) if it.disk_name not in disk_io_rate: disk_io_rate[it.disk_name] = [] disk_io_rate[it.disk_name].append([it.read_rate, it.write_rate]) for it in disk_io_rate: disk_io_rate[it] = [[0.0, 0.0]] * (len(date) - len(disk_io_rate[it])) + disk_io_rate[it] disk_io_rate['IoRate'] = date disk_info = ResDiskInfo( disk_size=disk_size, disk_usage=disk_usage ) # net last_30_net_io_rate_date = session.query(PerfNetIoRateHistory.date).order_by( PerfNetIoRateHistory.date.desc()).distinct().limit( 30).all() last_30_net_io_rate_date = [i[0] for i in last_30_net_io_rate_date] last_30_net_io_rate_date.sort() print('T|last_30_net_io_rate_date ', last_30_net_io_rate_date) last_30_net_io_rate = session.query(PerfNetIoRateHistory).filter( PerfNetIoRateHistory.date.in_(last_30_net_io_rate_date)).all() print('T|last_30_net_io_rate ', last_30_net_io_rate) date = [] net_io_rate = {} for it in last_30_net_io_rate: date.append(it.date.strftime("%c")) if it.net_dev_name not in net_io_rate: net_io_rate[it.net_dev_name] = [] net_io_rate[it.net_dev_name].append([it.read_rate, it.write_rate]) for it in net_io_rate: net_io_rate[it] = [[0.0, 0.0]] * (len(date) - len(net_io_rate[it])) + net_io_rate[it] net_io_rate['IoRate'] = date net_info = ResNetInfo( net_io_rate=net_io_rate ) last_30_summary_date = session.query(PerfSummaryHistory.date).order_by( PerfSummaryHistory.date.desc()).distinct().limit( 30).all() last_30_summary_date = [i[0] for i in last_30_summary_date] last_30_summary_date.sort() print('T|last_30_summary_date ', last_30_summary_date) last_30_summary = session.query(PerfSummaryHistory).filter( PerfSummaryHistory.date.in_(last_30_summary_date)).all() print('T|last_30_summary ', last_30_summary) sum_proc_count = 0 sum_login_user_count = 0 history_proc_count = [[],[]] history_login_user_count = [[],[]] for it in last_30_summary: sum_proc_count = sum_proc_count + it.proc_count sum_login_user_count = sum_login_user_count + it.login_user_count history_proc_count[0].append(it.date.strftime("%c")) history_proc_count[1].append(it.proc_count) history_login_user_count[0].append(it.date.strftime("%c")) history_login_user_count[1].append(it.login_user_count) avg_proc_count = sum_proc_count / len(last_30_summary) if len(last_30_summary) > 0 else 0 avg_login_user_count = sum_login_user_count / len(last_30_summary) if len(last_30_summary) > 0 else 0 # perf info perf_info = ResPerfInfo( host_run_time=str_runtime, avg_proc_count=avg_proc_count, history_proc_count=history_proc_count, avg_login_user_count=avg_login_user_count, history_login_user_count=history_login_user_count, host_idle_rate=host_idle_rate, login_user_count=login_user_count, load_info=load_info, cpu_info=cpu_info, proc_info=proc_info, memory_info=memory_info, disk_info=disk_info, net_info=net_info) return ResBase(0, data=perf_info) def sample_perf_data(self): # 1 sample data tm = datetime.datetime.now() print("D|tm", tm) # 1.1 summary info host_run_time, host_idle_time = self.__get_host_uptime() login_user_count = int(self.__run_shell('who | wc -l')) # 1.4 cpu info cpu_count, cpu_usage_rate = self.__get_cpu_info() # 1.2 load info loads, load_level = self.__get_load_info(cpu_count) # 1.3 process info proc_count, proc_stat_statistics, proc_user_statistics = self.__get_process_info() # 1.5 mem info mem_size, swap_size, mem_statistics = self.__get_memory_info() # 1.6 disk info disk_size, disk_usage, disk_io_rate = self.__get_disk_info() # 1.7 net info net_usage = self.__get_net_info() # 2 db op session = Session() # 2.1 save host_run_time item = session.query(PerfSummaryValues).filter_by(key=SUMMARY_KEY_HOST_RUN_TIME).first() if item: item.value_int = host_run_time else: item = PerfSummaryValues(key=SUMMARY_KEY_HOST_RUN_TIME, value_int=host_run_time) session.add(item) # 2.2 save host_idle_time item = session.query(PerfSummaryValues).filter_by(key=SUMMARY_KEY_HOST_IDLE_TIME).first() if item: item.value_int = host_idle_time else: item = PerfSummaryValues(key=SUMMARY_KEY_HOST_IDLE_TIME, value_int=host_idle_time) session.add(item) # 2.3 save login_user_count item = session.query(PerfSummaryValues).filter_by(key=SUMMARY_KEY_LOGIN_USER_COUNT).first() if item: item.value_int = login_user_count else: item = PerfSummaryValues(key=SUMMARY_KEY_LOGIN_USER_COUNT, value_int=login_user_count) session.add(item) # 2.4 save loads # 2.4.2 load_level item = session.query(PerfSummaryValues).filter_by(key=SUMMARY_KEY_LOAD_LEVE).first() if item: item.value_int = load_level else: item = PerfSummaryValues(key=SUMMARY_KEY_LOAD_LEVE, value_int=load_level) session.add(item) # 2.4.2 loads item = PerfLoadsHistory(date=tm, one_min=loads[0], five_min=loads[1], fiften_min=loads[2]) session.add(item) # 2.5 save proc info # 2.5.1 proc_count item = session.query(PerfSummaryValues).filter_by(key=SUMMARY_KEY_PROC_COUNT).first() if item: item.value_int = proc_count else: item = PerfSummaryValues(key=SUMMARY_KEY_PROC_COUNT, value_int=proc_count) session.add(item) # 2.5.2 proc_stat_statistics item = PerfProcStatDistributionHistory(date=tm, R=proc_stat_statistics['R'], S=proc_stat_statistics['S'], I=proc_stat_statistics['I'], Z=proc_stat_statistics['Z'], D=proc_stat_statistics['D'], T=proc_stat_statistics['T'], P=proc_stat_statistics['P'], W=proc_stat_statistics['W'], X=proc_stat_statistics['X'], H=proc_stat_statistics['<'], N=proc_stat_statistics['N'], L=proc_stat_statistics['L'], thx_father=proc_stat_statistics['s'], multi_thx=proc_stat_statistics['l']) session.add(item) # 2.5.3 proc_user_statistics for k in proc_user_statistics: item = PerfProcUserDistributionHistory(date=tm, user_name=k, proc_count=proc_user_statistics[k]) session.add(item) # 2.6 save cpu_usage_rate # 2.6.1 cpu count item = session.query(PerfSummaryValues).filter_by(key=SUMMARY_KEY_CPU_COUNT).first() if item: item.value_int = cpu_count else: item = PerfSummaryValues(key=SUMMARY_KEY_CPU_COUNT, value_int=cpu_count) session.add(item) # 2.6.2 cpu_usage_rate for k in cpu_usage_rate: item = PerfCpuUsageRateHistory(date=tm, cpu_name=k, use_rate=cpu_usage_rate[k]) session.add(item) # 2.7 save mem info # 2.7.1 save mem size item = session.query(PerfSummaryValues).filter_by(key=SUMMARY_KEY_MEMORY_SIZE).first() if item: item.value_int = mem_size else: item = PerfSummaryValues(key=SUMMARY_KEY_MEMORY_SIZE, value_int=mem_size) session.add(item) # 2.7.2 save swap size item = session.query(PerfSummaryValues).filter_by(key=SUMMARY_KEY_SWAP_SIZE).first() if item: item.value_int = swap_size else: item = PerfSummaryValues(key=SUMMARY_KEY_SWAP_SIZE, value_int=swap_size) session.add(item) # 2.7.3 save mem_statistics print('D| 2.7.3 ', mem_statistics) item = PerfMemUsageHistory(date=tm, mem_use=mem_statistics['Mem:'][0], mem_free=mem_statistics['Mem:'][1], mem_buffer=mem_statistics['Mem:'][2], swap_use=mem_statistics['Swap:'][0], swap_free=mem_statistics['Swap:'][1]) session.add(item) # 2.8 save disk_size, disk_usage, disk_io_rate # 2.8.1 save disk_size item = session.query(PerfSummaryValues).filter_by(key=SUMMARY_KEY_DISK_SIZE).first() if item: item.value_int = disk_size else: item = PerfSummaryValues(key=SUMMARY_KEY_DISK_SIZE, value_int=disk_size) session.add(item) # 2.8.2 disk_usage item = session.query(PerfSummaryValues).filter_by(key=SUMMARY_KEY_DISK_USAGE).first() if item: item.value_str = json.dumps(disk_usage) else: item = PerfSummaryValues(key=SUMMARY_KEY_DISK_USAGE, value_str=json.dumps(disk_usage)) session.add(item) # 2.8.3 disk_io_rate for it in disk_io_rate: item = PerfDiskIoRateHistory(date=tm, disk_name=it[0], read_rate=it[1][0], write_rate=it[1][1]) session.add(item) # 2.9 save net_usage for it in net_usage: item = PerfNetIoRateHistory(date=tm, net_dev_name=it[0], read_rate=it[1][0], write_rate=it[1][1]) session.add(item) # 2.10 save summary item = PerfSummaryHistory(date=tm, proc_count=proc_count, login_user_count=login_user_count) session.add(item) session.commit() def __get_net_info(self): val = self.__run_shell('ifstat') net_list = val.split('\n') net_list = net_list[3: -1] net_usage = [] print("D|__get_net_info", net_list) for i in range(int(len(net_list) / 2)): if not net_list[i * 2]: continue it_info = net_list[i * 2].split(' ') it_info = [x for x in it_info if x != ''] print('I|', it_info) read_byte = 0 if it_info[5][-1] == 'K': read_byte = int(it_info[5][:-1]) * 1024 pass elif it_info[5][-1] == 'M': read_byte = int(it_info[5][:-1]) * 1024 * 1024 pass elif it_info[5][-1] == 'G': read_byte = int(it_info[5][:-1]) * 1024 * 1024 * 1024 else: read_byte = int(it_info[5]) write_byte = 0 if it_info[5][-1] == 'K': write_byte = int(it_info[7][:-1]) * 1024 pass elif it_info[5][-1] == 'M': write_byte = int(it_info[7][:-1]) * 1024 * 1024 pass elif it_info[5][-1] == 'G': write_byte = int(it_info[7][:-1]) * 1024 * 1024 * 1024 else: write_byte = int(it_info[7]) net_usage.append([it_info[0], (read_byte, write_byte)]) return net_usage def __get_disk_info(self): val = self.__run_shell('df') disk_list = val[val.find('\n') + 1:-1].split('\n') disk_usage = {} disk_size = 0 for it in disk_list: if not it: continue it_info = it.split(' ') it_info = [x for x in it_info if x != ''] print('I|', it_info) disk_usage[it_info[5]] = (int(it_info[2]), int(it_info[3])) disk_size = disk_size + int(it_info[1]) val = self.__run_shell('iostat') disk_io_list = val.split('\n') disk_io_list = disk_io_list[6: -1] disk_io_rate = [] for it in disk_io_list: if not it: continue it_info = it.split(' ') it_info = [x for x in it_info if x != ''] print('I|', it_info) disk_io_rate.append([it_info[0], (float(it_info[2]), float(it_info[3]))]) print(disk_size, disk_usage, disk_io_rate) return disk_size, disk_usage, disk_io_rate def __get_memory_info(self): val = self.__run_shell('free') mem_list = val[val.find('\n') + 1:-1].split('\n') mem_statistics = {} mem_size = 0 swap_size = 0 print('D| __get_memory_info ', mem_list) for it in mem_list: if not it: continue it_info = it.split(' ') it_info = [x for x in it_info if x != ''] print('I|', it_info) if it_info[0] == 'Mem:': mem_size = mem_size + int(it_info[1]) mem_statistics[it_info[0]] = (int(it_info[2]), int(it_info[3]), int(it_info[5])) elif it_info[0] == 'Swap:': swap_size = swap_size + int(it_info[1]) mem_statistics[it_info[0]] = (int(it_info[2]), int(it_info[3])) return mem_size, swap_size, mem_statistics def __get_cpu_info(self): val = self.__run_shell('mpstat -P ALL') cpu_list = val.split('\n') cpu_list = cpu_list[3: -1] cpu_usage_rate = {} cpu_count = len(cpu_list) print("D|__get_cpu_info ", cpu_list) for it in cpu_list: if not it: continue it_info = it.split(' ') print('I|', it_info) it_info = [x for x in it_info if x != ''] cpu_usage_rate[it_info[2]] = float(it_info[3]) return cpu_count, cpu_usage_rate def __get_process_info(self): val = self.__run_shell('ps -uxa') proc_count = val.count('\n') - 1 # 获取 user 和 stat 分类统计值 proc_stat_statistics = { 'R': 0, 'S': 0, 'I': 0, 'Z': 0, 'D': 0, 'T': 0, 'P': 0, 'W': 0, 'X': 0, '<': 0, 'N': 0, 'L': 0, 's': 0, 'l': 0 } proc_user_statistics = {} proc_list = val[val.find('\n') + 1:-1].split('\n') # print('I | ', proc_list) for it in proc_list: if not it: continue p_info = it.split(' ') # print('I|', p_info) p_info = [x for x in p_info if x != ''] proc_stat_statistics[p_info[7][0]] = proc_stat_statistics[p_info[7][0]] + 1 proc_user_statistics[p_info[0]] = proc_user_statistics.get(p_info[0], 0) + 1 print('status:', proc_stat_statistics, '\nuser:', proc_user_statistics) return proc_count, proc_stat_statistics, proc_user_statistics def __get_load_info(self, ncpu): val = self.__run_shell('uptime') idx = val.find('load average: ') loads = val[idx + len('load average: '):-1].split(', ') print('I | ', loads) loads = [float(i) for i in loads] L1 = 1 if loads[0] < 0.7 * ncpu else 2 if 0.7 * ncpu <= loads[0] < 1 * ncpu else 3 if 1 * ncpu <= loads[ 0] < 5 * ncpu else 4 L5 = 1 if loads[1] < 0.7 * ncpu else 2 if 0.7 * ncpu <= loads[0] < 1 * ncpu else 3 if 1 * ncpu <= loads[ 0] < 5 * ncpu else 4 L15 = 1 if loads[2] < 0.7 * ncpu else 2 if 0.7 * ncpu <= loads[0] < 1 * ncpu else 3 if 1 * ncpu <= loads[ 0] < 5 * ncpu else 4 return (loads[0], loads[1], loads[2]), int((L1 + L5 * 5 + L15 * 15) / 84 * 100) def __run_shell(self, cmd): out = os.popen(cmd) msg = '' for tmp in out.readlines(): msg = msg + tmp return msg def __get_runtime_str(self, host_run_time): value = host_run_time sec = 0 min = 0 hour = 0 day = 0 year = 0 sec = value % 60 if value > 60: # 秒 value = int(value / 60) min = value % 60 if value > 60: # 分 value = int(value / 60) hour = value % 24 if value > 24: # 时 value = int(value / 24) day = value % 356 if value > 356: year = int(value / 356) s_runtime = str(sec) + '秒' if min > 0: s_runtime = str(min) + '分' + s_runtime if hour > 0: s_runtime = str(hour) + '时' + s_runtime if day > 0: s_runtime = str(day) + '日' + s_runtime if year > 0: s_runtime = str(year) + '年' + s_runtime return s_runtime def __get_host_uptime(self) -> (float, float): val = self.__run_shell('cat /proc/uptime') print('yz', val) s_host_run_time, s_host_idle_time = val.split(' ') return float(s_host_run_time), float(s_host_idle_time) def __get_host_idle_rate(self): return 60 def get_test_perf_info(self) -> ResPerfInfo: perf_info = ResPerfInfo(host_run_time='13h:14m:41s', host_idle_rate=60, login_user_count=3, load_info=ResLoadInfo(level=1, one_min=[150, 230, 102, 218, 567, 147, 260], five_min=[150, 230, 102, 218, 567, 147, 260], fiften_min=[150, 230, 102, 218, 567, 147, 260]), proc_info=ResProcInfo(proc_count=20, proc_stat_distribution=[ # 按状态分类统计进程数量历史序列 ["Stat", ["10/21 18:56", "10/21 18:57", "10/21 18:58"]], ["T", [12, 17, 5]], ["S", [12, 17, 5]], ["R", [12, 17, 5]], ], proc_user_distribution=[ # 按用户分类统计进程数量历史序列 ["User", ["10/21 18:56", "10/21 18:57", "10/21 18:58"]], ["root", [12, 17, 5]], ["mysql", [12, 17, 5]] ]), cpu_info=ResCpuInfo(cpu_count=8, cpu_usage_rate=[ # cpu使用率历史 "all", [0.54, 0.22, 0.24], "0", [0.54, 0.22, 0.24], "1", [0.54, 0.22, 0.24], "2", [0.54, 0.22, 0.24], "3", [0.54, 0.22, 0.24] ]), memory_info=ResMemoryInfo(mem_size=1020282828, mem_usage=[[26, 91, 281], [26, 91, 281], [26, 91, 281]], swap_size=1028848, swap_usage=[[26, 91, 281], [26, 91, 281], [26, 91, 281]]), disk_info=ResDiskInfo(disk_size=10291282, disk_usage=[["xxx1", 2818, 909], ["xxx2", 2818, 909]], disk_io_rate=[ # 磁盘IO速率历史 ["IoRate", ["10/21 18:56", "10/21 18:57", "10/21 18:58"]], ["xxx1", [192, 2919, 291], [192, 2919, 291]], ["xxx2", [192, 2919, 291], [192, 2919, 291]] ]), net_info=ResNetInfo( net_io_rate=[ # 网络IO速率历史 ["IoRate", ["10/21 18:56", "10/21 18:57", "10/21 18:58"]], ["xxx1", [192, 2919, 291], [192, 2919, 291]], ["xxx2", [192, 2919, 291], [192, 2919, 291]] ]) ) return ResBase(0, data=perf_info)
46.342302
116
0.5364
3f92e96bc630aca3f28cff080e96279fe8798760
134
py
Python
scripts/hello_world_tonymanou.py
breezage/Hacktoberfest-1
6f6d52248c79c0e72fd13b599500318fce3f9ab0
[ "MIT" ]
null
null
null
scripts/hello_world_tonymanou.py
breezage/Hacktoberfest-1
6f6d52248c79c0e72fd13b599500318fce3f9ab0
[ "MIT" ]
null
null
null
scripts/hello_world_tonymanou.py
breezage/Hacktoberfest-1
6f6d52248c79c0e72fd13b599500318fce3f9ab0
[ "MIT" ]
1
2019-10-24T06:45:21.000Z
2019-10-24T06:45:21.000Z
# LANGUAGE: Pyth # AUTHOR: Antoine Mann # GITHUB: https://github.com/tonymanou # LINK: https://github.com/isaacg1/pyth "Hello World!
19.142857
39
0.723881
b2003ac3dffdbd829f2c453abb6df9a5f0ce35cc
1,139
py
Python
scripts/test.py
JosiahCraw/Tiva-Helicopter-Controller-ENCE464-
207fda18bf8e4b562e47205fbbdc9aaaf274c54f
[ "MIT" ]
null
null
null
scripts/test.py
JosiahCraw/Tiva-Helicopter-Controller-ENCE464-
207fda18bf8e4b562e47205fbbdc9aaaf274c54f
[ "MIT" ]
null
null
null
scripts/test.py
JosiahCraw/Tiva-Helicopter-Controller-ENCE464-
207fda18bf8e4b562e47205fbbdc9aaaf274c54f
[ "MIT" ]
null
null
null
# Quick Tester for the logic used to reset the yaw slot count TOTAL_SLOTS = 10 MAX_ABSOLUTE_ROTATIONS = 10 def round_yaw(current_yaw, target_yaw): if (abs(current_yaw) >= TOTAL_SLOTS * MAX_ABSOLUTE_ROTATIONS): target_yaw = target_yaw - current_yaw current_yaw = 0 return (target_yaw, current_yaw) yaw_error = abs(current_yaw) % TOTAL_SLOTS yaw_change = 0 if (yaw_error > (TOTAL_SLOTS / 2)): yaw_change = TOTAL_SLOTS - yaw_error else: yaw_change = 0 - yaw_error if (current_yaw < 0): yaw_change = 0 - yaw_change current_yaw += yaw_change return (target_yaw, current_yaw) def tests(): yaws = [(5000, 5050),(-5000, -5050), (100, 100), (-100, -110), (26, 30), (-26, -30)] answers = [(50, 0), (-50, 0), (0, 0), (-10, 0), (30, 30), (-30, -30)] results = [] for yaw in yaws: ans = round_yaw(yaw[0], yaw[1]) results.append(ans) if (answers != results): print("Failed") else: print("Passed") print("Answers: {}".format(answers)) print("Results: {}".format(results)) tests()
25.311111
89
0.586479
b7ca6d63906d2ad8c1ab0c773e7ea3d4eed45b37
6,321
py
Python
awaiter.py
BigBoss1964/discord-rules
02257a84450388ceffbad5b6bb9e28175734403f
[ "MIT" ]
76
2018-02-12T15:26:16.000Z
2020-01-14T07:22:17.000Z
awaiter.py
BigBoss1964/discord-rules
02257a84450388ceffbad5b6bb9e28175734403f
[ "MIT" ]
2
2018-02-19T16:17:39.000Z
2018-02-19T16:19:36.000Z
awaiter.py
BigBoss1964/discord-rules
02257a84450388ceffbad5b6bb9e28175734403f
[ "MIT" ]
34
2018-02-12T15:26:20.000Z
2021-05-04T04:30:05.000Z
import asyncio import inspect import string from collections import defaultdict from typing import Any, Collection import discord from discord import Message, Guild, PartialEmoji, Embed, Color, Reaction, User, Role, TextChannel from discord.ext.commands import Bot, Context as CommandContext, Paginator _NoneType = type(None) async def await_if(func, *args, **kwargs): if inspect.iscoroutinefunction(func): return await func(*args, **kwargs) else: return func(*args, **kwargs) def keeper(keep): table = defaultdict(_NoneType) table.update({ord(c): c for c in keep}) return table digit_keeper = keeper(string.digits) YES_ANSWERS = ['yes', 'y'] NO_ANSWERS = ['n', 'no'] class AwaitException(BaseException): pass class AwaitCanceled(AwaitException): pass class AwaitTimedOut(AwaitException): pass class AdvancedAwaiter: def __init__(self, ctx: CommandContext): self.ctx: CommandContext = ctx self.bot: Bot = ctx.bot self.message: Message = ctx.message self.guild: Guild = ctx.guild def check_author(self, mes: Message): return mes.author == self.message.author and mes.channel == self.message.channel async def by_converter(self, text, check, converter) -> Any: obj = None while obj is None or not await await_if(check, obj): try: res = await self(text) obj = await await_if(converter, res) except AwaitException: raise except BaseException as e: print(e) return obj async def __call__(self, text, check=lambda mes: True) -> Message: await self.ctx.send( embed=Embed( color=Color.blurple(), description=text)) try: mes = await self.bot.wait_for('message', check=lambda mes: self.check_author(mes) and check(mes), timeout=120) if mes.content.lower() == "@cancel@": raise AwaitCanceled return mes except asyncio.TimeoutError: raise AwaitTimedOut async def converted_emoji(self, text: str, converter=lambda x: x, check=lambda x: True): thing = None while thing is None or not check(thing): try: ret = await self.emoji_reaction(text) thing = await await_if(converter, ret) except AwaitException: raise except BaseException as e: print(e) return thing async def emoji_reaction(self, text: str) -> PartialEmoji: await self.ctx.send( embed=Embed( color=Color.blurple(), description=text)) def check(reaction: Reaction, user: User): message: Message = reaction.message return message.channel == self.message.channel and user.id == self.message.author.id try: reaction, user = await self.bot.wait_for('reaction_add', check=check, timeout=30) return reaction except asyncio.TimeoutError: raise AwaitTimedOut async def guild_role(self, text: str, check=lambda role: True, list_ids=False) -> Role: async def converter(mes: Message): return discord.utils.get(self.guild.roles, id=int(mes.content.translate(digit_keeper))) if list_ids: guild: Guild = self.ctx.guild paginator = Paginator() for role in guild.roles: paginator.add_line(role.name + ' ' + str(role.id)) for page in paginator.pages: await self.ctx.send( embed=Embed( color=Color.blurple(), description=page)) return await self.by_converter( text, check=check, converter=converter) async def emoji_choice(self, text: str, choices: Collection[str]): emoji = '' while emoji not in choices: mes: Message = await self.ctx.send( embed=Embed( color=Color.blurple(), description=text)) for choice in choices: await mes.add_reaction(choice) def check(reaction: Reaction, user: User): message: Message = reaction.message return message.channel == self.message.channel and user.id == self.message.author.id try: reaction, user = await self.bot.wait_for('reaction_add', check=check, timeout=30) emoji = str(reaction.emoji) except asyncio.TimeoutError: raise AwaitTimedOut return emoji async def text(self, text: str): return (await self(text)).content async def guild_channel(self, text: str, check=lambda channel: True, writable=False) -> object: async def converter(mes: Message): return discord.utils.get(self.guild.channels, id=int(mes.content.translate(digit_keeper))) async def all_checks(channel: TextChannel): if writable and not channel.permissions_for(self.ctx.me).send_messages: return False return await await_if(check, channel) return await self.by_converter( text, check=all_checks, converter=converter) async def as_message(self, text: str, check=lambda mes: True, in_channel: TextChannel = None) -> Message: if in_channel is None: in_channel = self.ctx.channel async def converter(mes: Message): return await in_channel.get_message(mes.content) return await self.by_converter(text, check=check, converter=converter) async def yes_no_question(self, text: str) -> bool: response = '' while response not in (YES_ANSWERS + NO_ANSWERS): response = (await self.text(text)).lower() pass return response in YES_ANSWERS
34.353261
110
0.571903
4db040155117825cb90da49c7837bee5ac71986b
1,938
py
Python
Algorithms/Bit_Manipulation/sansa_and_xor.py
byung-u/HackerRank
4c02fefff7002b3af774b99ebf8d40f149f9d163
[ "MIT" ]
null
null
null
Algorithms/Bit_Manipulation/sansa_and_xor.py
byung-u/HackerRank
4c02fefff7002b3af774b99ebf8d40f149f9d163
[ "MIT" ]
null
null
null
Algorithms/Bit_Manipulation/sansa_and_xor.py
byung-u/HackerRank
4c02fefff7002b3af774b99ebf8d40f149f9d163
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 from functools import reduce for _ in range(int(input())): N = int(input()) arr = list(map(int, input().strip().split())) if N % 2 == 0: print(0) continue res = [arr[i] for i in range(0, N, 2)] print(reduce(lambda x, y: x ^ y, res)) """ for _ in range(int(input())): N = int(input()) arr = list(map(int, input().strip().split())) if N % 2 == 0: print(0) continue cnt = Counter() for i in range(1, N + 1): for j in range(0, N): if len(arr[j:i+j]) != i: continue for c in arr[j:i+j]: cnt[c] += 1 print(arr) print(cnt) res = [k for k, v in cnt.items() if v % 2 == 1] if len(res) == 0: print(0) else: print(reduce(lambda x, y: x ^ y, res)) """ ''' # XOR # X ^ X = 0 # X ^ 0 = X # 0 ^ 0 = 0 # Too slow (naive way) # tc = [reduce(lambda x, y: x ^ y, arr[j:i+j]) for i in range(1, N + 1) for j in range(0, N) if len(arr[j:i+j]) == i] # print(reduce(lambda x, y: x ^ y, tc)) # Explanation david_david188 about a year ago Explanation: Basic Rules 1. A^0=A -> Rule 1 2. A^A=0 -> Rule 2 3. A^(B^C)=(A^B)^C -> Rule 3 Considering the above rules Now Case 1 : Array length 3 (odd) input is 1 2 3 1^2^3^(1^2)^(2^3)^(1^2^3) now count each digit 1 - 3 counts (zeroth position) 2 - 4 counts (first position) 3 - 3 counts (second position) so we can rewrite the above as (1^1)^1^(2^2)^(2^2)^(3^3)^3 -> applying Rule 3 0^1^0^0^3 -> applying Rule 1 1^3 -> applying Rule 2 => Result = 2 So if the array length is odd then it is enough to XOR the 0,2,.... positions Case 2 : Array length 4 (even) input is 4 5 7 3 (for easy understanding I am changing last 5 to 3) 4^5^7^3^(4^5)^(5^7)^(7^3)^(4^5^7)^(5^7^3)^(4^5^7^3) 4 - 4 counts 5 - 6 counts 7 - 6 counts 3 - 4 counts since all the counts are even the result is 0. '''
20.617021
121
0.539732
4dc98c600de1e17f4a781f4419306387123149ae
929
py
Python
v2/memo.py
timm/py
28be3bb63433895e2bcab27ad82cb0b0cc994f37
[ "Unlicense" ]
1
2021-03-31T03:41:06.000Z
2021-03-31T03:41:06.000Z
v2/memo.py
timm/py
28be3bb63433895e2bcab27ad82cb0b0cc994f37
[ "Unlicense" ]
null
null
null
v2/memo.py
timm/py
28be3bb63433895e2bcab27ad82cb0b0cc994f37
[ "Unlicense" ]
null
null
null
# vim: ts=2 sw=2 sts=2 et : def mem1(f): "Caching, simple case, no arguments." cache = [0] # local memory def wrapper(*l, **kw): val = cache[0] = cache[0] or f(*l, **kw) return val return wrapper def memo(f): cache = {} # initialized at load time def g(*lst): # called at load time val = cache[lst] = cache.get(lst,None) or f(*lst) return val return g if __name__ == "__main__": # example usage class Test(object): def __init__(i): i.v = 0 @memo def inc_dec(self,arg): print(2) self.v -= arg return self.v @memo def inc_add(self,arg): print(1) self.v += arg return self.v t = Test() print(t.inc_add(10)) print(t.inc_add(20)) print(t.inc_add(10)) print(t.inc_dec(100)) print(t.inc_dec(100)) #assert t.inc_add(2) == t.inc_add(2) #assert Test.inc_add(t, 2) != Test.inc_add(t, 2)
22.119048
53
0.558665
4284bf18df2d16171add4f8688f407d509f3cd09
1,270
py
Python
programm/log.py
team172011/ps_cagebot
ab6f7bdbc74ad3baee3feebc4b7b0fa4f726b179
[ "MIT" ]
null
null
null
programm/log.py
team172011/ps_cagebot
ab6f7bdbc74ad3baee3feebc4b7b0fa4f726b179
[ "MIT" ]
null
null
null
programm/log.py
team172011/ps_cagebot
ab6f7bdbc74ad3baee3feebc4b7b0fa4f726b179
[ "MIT" ]
null
null
null
""" Logger builder for getting a logger that can be used for debugging (print on console) and for reales mode (disable console output) @author: wimmer, simon-justus """ import logging import os class logger_builder: def __init__(self, log_name = 'default Logger', log_dir='logging123'): self.log_dir = log_dir self.log_name = log_name self.logger = logging.Logger(str(log_name)) self.set_logging_config() def set_logging_config(self): logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s") logging.getLogger().addHandler(logging.StreamHandler()) self.logger.setLevel(logging.DEBUG) self.log_dir = "{0}/{1}".format(os.getcwd(),self.log_dir) if not os.path.isdir(self.log_dir): os.mkdir(self.log_dir) fileHandler = logging.FileHandler("{0}/{1}.log".format(self.log_dir,self.log_name)) fileHandler.setFormatter(logFormatter) self.logger.addHandler(fileHandler) consoleHandler = logging.StreamHandler() consoleHandler.setFormatter(logFormatter) self.logger.addHandler(consoleHandler) def get_logger(self): return self.logger
36.285714
111
0.659843
67b583cbfbb018f3826d4bd2aad9bda12a7ed086
304
py
Python
Python/turtle-drawing/mandala.py
DMeurer/small-projects
3d9e714db9cd8dd8a626d9b8f0faa44325ef10e1
[ "MIT" ]
1
2021-03-25T14:23:58.000Z
2021-03-25T14:23:58.000Z
Python/turtle-drawing/mandala.py
DMeurer/small-projects
3d9e714db9cd8dd8a626d9b8f0faa44325ef10e1
[ "MIT" ]
1
2021-01-15T17:03:06.000Z
2021-02-15T10:02:07.000Z
Python/turtle-drawing/mandala.py
DMeurer/small-projects
3d9e714db9cd8dd8a626d9b8f0faa44325ef10e1
[ "MIT" ]
null
null
null
import turtle t=turtle.Pen() t.hideturtle() t.turtlesize(10) t.speed(0) count = 0 a = 1 x = 10 while count < 23: count=count+1 a = 1 x = x + 5 t.penup() t.setposition(0, 0) t.pendown() while a < 80: t.forward(8) t.right(a) a = 1.02 * a turtle.done()
13.217391
23
0.523026
c0568a5360c6fd16a4c5b050f9e1697dfa8eda9c
482
py
Python
30-Days-of-Code/Day06-LetsReview.py
sadikkuzu/HackerRank
2b1ed2cf41f6a5404c5b9293186f301b646b5d33
[ "Apache-2.0" ]
5
2019-03-09T22:44:01.000Z
2021-09-14T00:11:38.000Z
30-Days-of-Code/Day06-LetsReview.py
jguerra7/HackerRank-4
7e1663d0050ffbb0fd885b8affdada9ea13b0e80
[ "Apache-2.0" ]
4
2018-08-16T09:39:47.000Z
2018-09-14T17:37:07.000Z
30-Days-of-Code/Day06-LetsReview.py
jguerra7/HackerRank-4
7e1663d0050ffbb0fd885b8affdada9ea13b0e80
[ "Apache-2.0" ]
1
2020-06-01T23:38:35.000Z
2020-06-01T23:38:35.000Z
# https://www.hackerrank.com/challenges/30-review-loop # Enter your code here. Read input from STDIN. Print output to STDOUT def gezgin(s): l = list(s) l.reverse() k, m = list(), list() while(len(l)>0): try: k.append(l.pop()) m.append(l.pop()) except: pass k = ''.join(k) m = ''.join(m) print k,m if __name__ == '__main__': n = int(raw_input()) for _ in xrange(n): gezgin(raw_input())
22.952381
69
0.526971
223af60b7d17a0cec1f80de72df87ff76493c83b
3,932
py
Python
transonic/test_typing.py
fluiddyn/transonic
a460e9f6d1139f79b668cb3306d1e8a7e190b72d
[ "BSD-3-Clause" ]
88
2019-01-08T16:39:08.000Z
2022-02-06T14:19:23.000Z
transonic/test_typing.py
fluiddyn/transonic
a460e9f6d1139f79b668cb3306d1e8a7e190b72d
[ "BSD-3-Clause" ]
13
2019-06-20T15:53:10.000Z
2021-02-09T11:03:29.000Z
transonic/test_typing.py
fluiddyn/transonic
a460e9f6d1139f79b668cb3306d1e8a7e190b72d
[ "BSD-3-Clause" ]
1
2019-11-05T03:03:14.000Z
2019-11-05T03:03:14.000Z
import numpy as np from transonic.typing import ( Array, NDim, str2type, UnionMeta, List, ListMeta, Dict, DictMeta, Set, SetMeta, typeof, str2shape, MemLayout, Optional, const, ) from transonic.backends.typing import base_type_formatter def compare_array_types(A0, A1): assert A0.dtype == A1.dtype if len(A0.ndim.values) > 1: raise NotImplementedError if len(A1.ndim.values) > 1: raise NotImplementedError assert A0.ndim.values[0] == A1.ndim.values[0] def test_NDim(): N = NDim(1, 3) repr(N + 1) repr(N - 1) def test_str2type_simple(): assert str2type("int") == int assert str2type("float") == float assert str2type("uint32") == np.uint32 def test_str2type_arrays(): A1 = Array[int, "1d"] compare_array_types(str2type("int[]"), A1) compare_array_types(str2type("int[:]"), A1) A2 = Array[np.uint32, "2d"] compare_array_types(str2type("uint32[:,:]"), A2) def test_str2type_or(): result = str2type("int or float") assert isinstance(result, UnionMeta) assert result.types == (int, float) result = str2type("int or float[]") assert isinstance(result, UnionMeta) compare_array_types(result.types[1], Array[float, "1d"]) def test_list(): L = List[List[int]] repr(L) assert isinstance(L, ListMeta) assert L.format_as_backend_type(base_type_formatter) == "int list list" def test_dict(): D = Dict[str, int] repr(D) assert isinstance(D, DictMeta) assert D.format_as_backend_type(base_type_formatter) == "str: int dict" def test_set(): str2type("int set") S = Set["str"] S.get_template_parameters() repr(S) assert isinstance(S, SetMeta) assert S.format_as_backend_type(base_type_formatter) == "str set" def test_tuple(): T = str2type("(int, float[:, :])") T.get_template_parameters() assert repr(T) == 'Tuple[int, Array[float, "2d"]]' assert T.format_as_backend_type(base_type_formatter) == "(int, float64[:, :])" def test_typeof_simple(): assert typeof(1) is int assert typeof(1.0) is float assert typeof(1j) is complex assert typeof("foo") is str def test_typeof_list(): L = typeof([[1, 2], [3, 4]]) assert isinstance(L, ListMeta) assert L.format_as_backend_type(base_type_formatter) == "int list list" def test_typeof_dict(): D = typeof({"a": 0, "b": 1}) assert isinstance(D, DictMeta) assert D.format_as_backend_type(base_type_formatter) == "str: int dict" def test_typeof_set(): S = typeof({"a", "b"}) assert isinstance(S, SetMeta) assert S.format_as_backend_type(base_type_formatter) == "str set" def test_typeof_array(): A = typeof(np.ones((2, 2))) compare_array_types(A, Array[np.float64, "2d"]) def test_typeof_np_scalar(): T = typeof(np.ones(1)[0]) assert T is np.float64 def test_shape(): assert str2shape("[]") == (None,) assert str2shape("[:]") == (None,) assert str2shape("[][]") == (None,) * 2 assert str2shape("[][ ]") == (None,) * 2 assert str2shape("[:,:]") == (None,) * 2 assert str2shape("[: ,:,:, ]") == (None,) * 3 assert str2shape("[3 ,:,:]") == (3, None, None) assert str2shape("[ : , :,3]") == (None, None, 3) A = Array[int, "[: ,:, 3]"] assert A.shape == (None, None, 3) assert A.ndim.values[0] == 3 assert repr(A) == 'Array[int, "[:,:,3]"]' assert ( base_type_formatter.make_array_code( int, 2, (3, None), False, MemLayout.C_or_F, positive_indices=False ) == "int[3, :]" ) def test_optional(): assert repr(Optional[int]) == "Union[int, None]" def test_const(): A = str2type("int[]") B = const(A) assert A.format_as_backend_type( base_type_formatter ) == B.format_as_backend_type(base_type_formatter) assert repr(B) == 'const(Array[int, "1d"])'
23.266272
82
0.619532
97f2c1e4039d208400d97e97ea51a6e49366fbb1
1,105
py
Python
HITCON/2020/Quals/revenge_of_pwn/exploit.py
mystickev/ctf-archives
89e99a5cd5fb6b2923cad3fe1948d3ff78649b4e
[ "MIT" ]
1
2021-11-02T20:53:58.000Z
2021-11-02T20:53:58.000Z
HITCON/2020/Quals/revenge_of_pwn/exploit.py
ruhan-islam/ctf-archives
8c2bf6a608c821314d1a1cfaa05a6cccef8e3103
[ "MIT" ]
null
null
null
HITCON/2020/Quals/revenge_of_pwn/exploit.py
ruhan-islam/ctf-archives
8c2bf6a608c821314d1a1cfaa05a6cccef8e3103
[ "MIT" ]
1
2021-12-19T11:06:24.000Z
2021-12-19T11:06:24.000Z
#!/usr/bin/env python3 from pwn import * import os host, port = '127.0.0.1', 1337 context.arch = 'amd64' context.timeout = 2 log.info('Version of pwntools: ' + pwnlib.__version__) r = remote(host, port) r.recvuntil('stack address @ 0x') stk = int(r.recvline(), 16) log.info('stk @ ' + hex(stk)) l = listen(31337) stage1 = asm( shellcraft.connect('127.0.0.1', 31337) + shellcraft.itoa('rbp') + shellcraft.write('rbp', 'rsp', 4) + shellcraft.read('rbp', stk + 48, 100) + shellcraft.mov('rax', stk + 48) + 'jmp rax' ) r.send(b'@' * 40 + p64(stk+48) + stage1) r.close() s = l.wait_for_connection() fd = str(s.recvuntil('@')[:-1], 'ascii') log.info('sock fd @ ' + fd) backdoor_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'backdoor') stage2 = asm(shellcraft.stager(fd, 0x4000)) s.send(stage2.ljust(100, b'\x90')) stage3 = asm(shellcraft.close(1) + shellcraft.dup2(fd, 1) + shellcraft.loader_append(open(backdoor_path, 'rb').read())) s.send(stage3.ljust(0x4000, b'\x90')) # pwned! s.recvuntil('Hooray! A custom ELF is executed!\n') log.info("Pwned!") s.close()
25.113636
119
0.651584
45295ca7b51cf9de0e1736fda2407cc538026756
495
py
Python
hardware/seat_cam/communication.py
BlueHC/TTHack-2018--Easy-Rider-1
8cd8f66de88ff80751a1083350c38985ac26914d
[ "Apache-2.0" ]
null
null
null
hardware/seat_cam/communication.py
BlueHC/TTHack-2018--Easy-Rider-1
8cd8f66de88ff80751a1083350c38985ac26914d
[ "Apache-2.0" ]
null
null
null
hardware/seat_cam/communication.py
BlueHC/TTHack-2018--Easy-Rider-1
8cd8f66de88ff80751a1083350c38985ac26914d
[ "Apache-2.0" ]
null
null
null
import requests url = "http://easyriderbackend.eu-gb.mybluemix.net/occupancy" querystring = {"mediumID":"1"} headers = { 'content-type': "application/json", 'cache-control': "no-cache" } def getPayload(val): return "{\n\t\"latitude\": 123432.222,\n\t\"longitude\": 42332.21,\n\t\"amount\": " + str(val) + "\n}" def send_status(occupancy): response = requests.request("POST", url, data=getPayload(occupancy), headers=headers, params=querystring) print(response.text)
27.5
109
0.670707
e1951fe6fa8690030231089eef11d51e8b502dc4
1,481
py
Python
Packs/LINENotify/Integrations/LINENotify/LINENotify.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
799
2016-08-02T06:43:14.000Z
2022-03-31T11:10:11.000Z
Packs/LINENotify/Integrations/LINENotify/LINENotify.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
9,317
2016-08-07T19:00:51.000Z
2022-03-31T21:56:04.000Z
Packs/LINENotify/Integrations/LINENotify/LINENotify.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
1,297
2016-08-04T13:59:00.000Z
2022-03-31T23:43:06.000Z
import demistomock as demisto # noqa: F401 from CommonServerPython import * # noqa: F401 import requests ''' MAIN FUNCTION ''' def main() -> None: api_token = demisto.params().get('apitoken') try: if demisto.command() == 'line-send-message': # This is for sending LINE notification to specific group headers = { "Authorization": "Bearer " + api_token, "Content-Type": "application/x-www-form-urlencoded" } linemsg = demisto.args().get('message') payload = {'message': linemsg} r = requests.post("https://notify-api.line.me/api/notify", headers=headers, params=payload) return_results(r) elif demisto.command() == 'test-module': headers = { "Authorization": "Bearer " + api_token, "Content-Type": "application/x-www-form-urlencoded" } result = requests.get("https://notify-api.line.me/api/status", headers=headers) if '200' not in str(result): return_results(result) else: return_results('ok') # Log exceptions and return errors except Exception as e: demisto.error(traceback.format_exc()) # print the traceback return_error(f'Failed to execute {demisto.command()} command.\nError:\n{str(e)}') ''' ENTRY POINT ''' if __name__ in ('__main__', '__builtin__', 'builtins'): main()
32.911111
103
0.579338
beff155279165122788b438616e9423cc050fd3b
328
py
Python
P8702N/userAccount.py
wittrup/crap
a77474588fd54a5a998e24df7b1e6e2ab473ded1
[ "MIT" ]
1
2017-12-12T13:58:08.000Z
2017-12-12T13:58:08.000Z
P8702N/userAccount.py
wittrup/crap
a77474588fd54a5a998e24df7b1e6e2ab473ded1
[ "MIT" ]
null
null
null
P8702N/userAccount.py
wittrup/crap
a77474588fd54a5a998e24df7b1e6e2ab473ded1
[ "MIT" ]
1
2019-11-03T10:16:35.000Z
2019-11-03T10:16:35.000Z
import impat impat.addfolder('python') from random import randrange from FunCom import find_between from session import login, host, usr, pwd import requests print(login) print(login.cookies) if login.status_code == requests.codes.ok: print('=~=~=~=~=~=~=~=~=~=~=~= =~=~=~=~=~=~=~=~=~=~=~=')
25.230769
90
0.594512
83057ccb9a36c7bd06b9229170bc6a518953d331
1,247
py
Python
Python/zzz_training_challenge/Python_Challenge/solutions/ch07_recursion_advanced/solutions/ex01_tower.py
Kreijeck/learning
eaffee08e61f2a34e01eb8f9f04519aac633f48c
[ "MIT" ]
null
null
null
Python/zzz_training_challenge/Python_Challenge/solutions/ch07_recursion_advanced/solutions/ex01_tower.py
Kreijeck/learning
eaffee08e61f2a34e01eb8f9f04519aac633f48c
[ "MIT" ]
null
null
null
Python/zzz_training_challenge/Python_Challenge/solutions/ch07_recursion_advanced/solutions/ex01_tower.py
Kreijeck/learning
eaffee08e61f2a34e01eb8f9f04519aac633f48c
[ "MIT" ]
null
null
null
from ch05_datastructures.solutions.ex02_stack import Stack class Tower: def __init__(self, name): self.name = name self.__values = Stack() def __str__(self): return "Tower [" + self.name + "]" def push(self, item): self.__values.push(item) def pop(self): return self.__values.pop() def print_tower(self, max_height): height = self.__values.size() - 1 visual = self.draw_top(max_height, height) visual += self.draw_slices(max_height, height) visual += self.draw_bottom(max_height) return visual def draw_top(self, max_height, height): visual = [" " * max_height + self.name + " " * max_height] for i in range(max_height - height - 1, 0, -1): visual.append(" " * max_height + "|" + " " * max_height) return visual def draw_slices(self, max_height, height): visual = [] for i in range(height, -1, -1): value = self.__values.get_at(i) padding = max_height - value visual.append(" " * padding + "#" * value + "|" + "#" * value + " " * padding) return visual def draw_bottom(self, height): return ["-" * (height * 2 + 1)]
26.531915
90
0.565357
c558364eaa8a028f99295762f0346c9a700d116a
1,415
py
Python
mongodb/mongodb_consistent_backup/official/mongodb_consistent_backup/Notify/Notify.py
smthkissinger/docker-images
35e868295d04fa780325ada4168381f1e80e8fe4
[ "BSD-3-Clause" ]
63
2018-02-04T03:31:22.000Z
2022-03-07T08:27:39.000Z
mongodb/mongodb_consistent_backup/official/mongodb_consistent_backup/Notify/Notify.py
smthkissinger/docker-images
35e868295d04fa780325ada4168381f1e80e8fe4
[ "BSD-3-Clause" ]
3
2017-09-17T02:33:18.000Z
2020-12-18T23:20:59.000Z
mongodb/mongodb_consistent_backup/official/mongodb_consistent_backup/Notify/Notify.py
smthkissinger/docker-images
35e868295d04fa780325ada4168381f1e80e8fe4
[ "BSD-3-Clause" ]
40
2018-01-22T16:31:16.000Z
2022-03-08T04:40:42.000Z
import logging from mongodb_consistent_backup.Errors import Error, NotifyError from mongodb_consistent_backup.Notify.Nsca import Nsca # NOQA from mongodb_consistent_backup.Pipeline import Stage class Notify(Stage): def __init__(self, manager, config, timer, base_dir, backup_dir): super(Notify, self).__init__(self.__class__.__name__, manager, config, timer, base_dir, backup_dir) self.task = self.config.notify.method self.notifications = [] self.init() def notify(self, message, success=False): notification = (success, message) self.notifications.append(notification) def run(self, *args): if self._task and len(self.notifications) > 0: try: logging.info("Sending %i notification(s) to: %s" % (len(self.notifications), self._task.server)) while len(self.notifications) > 0: try: (success, message) = self.notifications.pop() state = self._task.failed if success is True: state = self._task.success self._task.run(state, message) except NotifyError: continue except Exception, e: raise Error(e) def close(self): if self._task: return self._task.close()
36.282051
112
0.583746
3debbb06947ea28244cc5fdb3f64eada79b0f506
931
py
Python
agents/base_agent.py
yerfor/Soft-DRGN
0c96d1ea295077b949229261c37d8dde25001a03
[ "MIT" ]
2
2022-02-24T08:21:49.000Z
2022-03-10T08:57:35.000Z
agents/base_agent.py
yerfor/Soft-DRGN
0c96d1ea295077b949229261c37d8dde25001a03
[ "MIT" ]
1
2022-02-24T08:40:21.000Z
2022-02-24T12:01:58.000Z
agents/base_agent.py
yerfor/Soft-DRGN
0c96d1ea295077b949229261c37d8dde25001a03
[ "MIT" ]
null
null
null
import torch.nn as nn class BaseAgent(nn.Module): def __init__(self): self.learned_model = None self.target_model = None def action(self, sample, epsilon, action_mode): raise NotImplementedError def cal_q_loss(self, sample, losses, log_vars): raise NotImplementedError def update_target(self): raise NotImplementedError class BaseActorCriticAgent(nn.Module): def __init__(self): self.learned_actor_model = None self.target_actor_model = None self.learned_critic_model = None self.target_critic_model = None def action(self, sample, epsilon, action_mode): raise NotImplementedError def cal_p_loss(self, sample, losses, log_vars): raise NotImplementedError def cal_q_loss(self, sample, losses, log_vars): raise NotImplementedError def update_target(self): raise NotImplementedError
25.162162
51
0.691729
b19f2b80fbbac0a50bd46172488d8edbe7328430
1,522
py
Python
GFPGAN/main.py
FabianBell/24h-dezember-2021
139c5996479db0cdcb96189a2c89ee34c45a9d37
[ "Apache-2.0" ]
null
null
null
GFPGAN/main.py
FabianBell/24h-dezember-2021
139c5996479db0cdcb96189a2c89ee34c45a9d37
[ "Apache-2.0" ]
5
2021-12-17T09:52:50.000Z
2021-12-17T10:50:05.000Z
GFPGAN/main.py
FabianBell/24h-dezember-2021
139c5996479db0cdcb96189a2c89ee34c45a9d37
[ "Apache-2.0" ]
null
null
null
import cv2 import numpy as np from gfpgan import GFPGANer import pika import os import json import base64 MODEL_PATH = "models/GFPGANCleanv1-NoCE-C2.pth" INPUT_NAME = "FACE_RESTORE_TASK" OUTPUT_NAME = "FACE_RESTORE_RESPONSE" # init model model = GFPGANer( model_path=MODEL_PATH, upscale=2, arch="clean", channel_multiplier=2) host = os.environ.get('MQ_HOST') host = host if host is not None else 'localhost' print(f"Using hostname {host}") connection = pika.BlockingConnection(pika.ConnectionParameters(host)) output_channel = connection.channel() output_channel.queue_declare(queue=OUTPUT_NAME) def restore(input_channel, method, properties, body): body = json.loads(body) # decode img = base64.b64decode(body['image']) img = np.frombuffer(img, np.uint8) img = cv2.imdecode(img, cv2.IMREAD_COLOR) # model computation _, _, out_img = model.enhance(img, has_aligned=False, only_center_face=False, paste_back=True) # encode out = cv2.imencode('.' + body['extension'], out_img)[1].tobytes() body['image'] = base64.b64encode(out).decode('ascii') body = json.dumps(body) output_channel.basic_publish( exchange="", routing_key=OUTPUT_NAME, body=body) input_channel.basic_ack(delivery_tag = method.delivery_tag) input_channel = connection.channel() input_channel.queue_declare(queue=INPUT_NAME) input_channel.basic_consume( queue=INPUT_NAME, on_message_callback=restore) input_channel.start_consuming()
27.672727
98
0.726675
493ef41917b75c564d31e9ec519ea1e9e55c5d80
2,146
py
Python
src/visuanalytics/server/db/db.py
mxsph/Data-Analytics
c82ff54b78f50b6660d7640bfee96ea68bef598f
[ "MIT" ]
3
2020-08-24T19:02:09.000Z
2021-05-27T20:22:41.000Z
src/visuanalytics/server/db/db.py
mxsph/Data-Analytics
c82ff54b78f50b6660d7640bfee96ea68bef598f
[ "MIT" ]
342
2020-08-13T10:24:23.000Z
2021-08-12T14:01:52.000Z
src/visuanalytics/server/db/db.py
visuanalytics/visuanalytics
f9cce7bc9e3227568939648ddd1dd6df02eac752
[ "MIT" ]
8
2020-09-01T07:11:18.000Z
2021-04-09T09:02:11.000Z
import logging import os import sqlite3 import flask from visuanalytics.util import resources logger = logging.getLogger(__name__) DATABASE_LOCATION = "" def open_con(): """ Öffnet DB-Verbindung außerhalb des Flask-Kontexts. Dieese Methode wird u.a. für den DB-Scheduler benötigt, welcher unabhängig vom Flask-Server ausgeführt wird. """ con = sqlite3.connect( DATABASE_LOCATION, detect_types=sqlite3.PARSE_DECLTYPES, ) con.row_factory = sqlite3.Row return con def open_con_f(): """ Öffnet DB-Verbindung innerhalb des Flask-Kontexts. Diese Methode wird in den Endpunkt-Handler-Methoden verwendet. """ if 'db' not in flask.g: flask.g.db = sqlite3.connect( DATABASE_LOCATION, detect_types=sqlite3.PARSE_DECLTYPES ) flask.g.db.row_factory = sqlite3.Row return flask.g.db def close_con_f(e=None): """ Schließt DB-Verbindung innerhalb des Flask-Kontexts. """ db = flask.g.pop('db', None) if db is not None: db.close() def init_db(topics: list, db_path: str): """ Initialisiert DB außerhalb des Flask-Kontexts. Nur wenn noch keine Datenbank im "instance"-Ordner angelegt ist, wird eine neue erstellt. :param topics: Liste mit allen Themen. """ global DATABASE_LOCATION DATABASE_LOCATION = resources.path_from_root(db_path) if not os.path.exists(DATABASE_LOCATION): logger.info("Initialize Database ...") os.makedirs(os.path.dirname(DATABASE_LOCATION), exist_ok=True) with open_con() as con: with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'schema.sql')) as f: con.executescript(f.read()) con.commit() _init_topics(topics) logger.info("Database initialisation done!") def _init_topics(topics: list): logger.info("Initialize topics ...") with open_con() as con: for topic in topics: con.execute("INSERT INTO steps (steps_name,json_file_name)VALUES (?, ?)", [topic["name"], topic["file_name"]]) con.commit()
26.493827
112
0.655172
77086bf8b3390e8250512d45c718fbbe18ccaf61
315
py
Python
python/image_processing/opening.py
SayanGhoshBDA/code-backup
8b6135facc0e598e9686b2e8eb2d69dd68198b80
[ "MIT" ]
16
2018-11-26T08:39:42.000Z
2019-05-08T10:09:52.000Z
python/image_processing/opening.py
SayanGhoshBDA/code-backup
8b6135facc0e598e9686b2e8eb2d69dd68198b80
[ "MIT" ]
8
2020-05-04T06:29:26.000Z
2022-02-12T05:33:16.000Z
python/image_processing/opening.py
SayanGhoshBDA/code-backup
8b6135facc0e598e9686b2e8eb2d69dd68198b80
[ "MIT" ]
5
2020-02-11T16:02:21.000Z
2021-02-05T07:48:30.000Z
import cv2 import numpy as np img = cv2.imread('opening.png',0) kernel = np.ones((5,5),np.uint8) opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel) cv2.imshow('image cv2',img) cv2.imshow('image erosion',opening) cv2.waitKey(0) # to save the image # cv2.imwrite('image1.png',img) cv2.destroyAllWindows()
16.578947
55
0.720635
6558e37fb832289250b72956821ba09ceb5663f7
4,047
py
Python
examples/v1beta1/trial-images/enas-cnn-cifar10/RunTrial.py
d-gol/katib
2c8758b26ffd543e08b70464f8ac7b286f3ca2ea
[ "Apache-2.0" ]
17
2018-04-04T08:44:06.000Z
2018-04-19T18:02:05.000Z
examples/v1beta1/trial-images/enas-cnn-cifar10/RunTrial.py
d-gol/katib
2c8758b26ffd543e08b70464f8ac7b286f3ca2ea
[ "Apache-2.0" ]
58
2018-04-03T19:05:50.000Z
2018-04-19T16:14:04.000Z
examples/v1beta1/trial-images/enas-cnn-cifar10/RunTrial.py
d-gol/katib
2c8758b26ffd543e08b70464f8ac7b286f3ca2ea
[ "Apache-2.0" ]
10
2018-04-04T02:06:20.000Z
2018-04-19T08:53:04.000Z
# Copyright 2022 The Kubeflow Authors. # # 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. from tensorflow import keras from keras.datasets import cifar10 from ModelConstructor import ModelConstructor from tensorflow.keras.utils import to_categorical from keras.preprocessing.image import ImageDataGenerator import tensorflow as tf import argparse if __name__ == "__main__": parser = argparse.ArgumentParser(description='TrainingContainer') parser.add_argument('--architecture', type=str, default="", metavar='N', help='architecture of the neural network') parser.add_argument('--nn_config', type=str, default="", metavar='N', help='configurations and search space embeddings') parser.add_argument('--num_epochs', type=int, default=10, metavar='N', help='number of epoches that each child will be trained') parser.add_argument('--num_gpus', type=int, default=1, metavar='N', help='number of GPU that used for training') args = parser.parse_args() arch = args.architecture.replace("\'", "\"") print(">>> arch received by trial") print(arch) nn_config = args.nn_config.replace("\'", "\"") print(">>> nn_config received by trial") print(nn_config) num_epochs = args.num_epochs print(">>> num_epochs received by trial") print(num_epochs) num_gpus = args.num_gpus print(">>> num_gpus received by trial:") print(num_gpus) print("\n>>> Constructing Model...") constructor = ModelConstructor(arch, nn_config) num_physical_gpus = len(tf.config.experimental.list_physical_devices('GPU')) if 1 <= num_gpus <= num_physical_gpus: devices = ["/gpu:"+str(i) for i in range(num_physical_gpus)] else: num_physical_cpu = len(tf.config.experimental.list_physical_devices('CPU')) devices = ["/cpu:"+str(j) for j in range(num_physical_cpu)] strategy = tf.distribute.MirroredStrategy(devices) with strategy.scope(): test_model = constructor.build_model() test_model.summary() test_model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adam(learning_rate=1e-3, decay=1e-4), metrics=['accuracy']) print(">>> Model Constructed Successfully\n") (x_train, y_train), (x_test, y_test) = cifar10.load_data() x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 y_train = to_categorical(y_train) y_test = to_categorical(y_test) augmentation = ImageDataGenerator( width_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True) # TODO: Add batch size to args aug_data_flow = augmentation.flow(x_train, y_train, batch_size=128) print(">>> Data Loaded. Training starts.") for e in range(num_epochs): print("\nTotal Epoch {}/{}".format(e + 1, num_epochs)) history = test_model.fit(aug_data_flow, steps_per_epoch=int(len(x_train) / 128) + 1, epochs=1, verbose=1, validation_data=(x_test, y_test)) print("Training-Accuracy={}".format(history.history['accuracy'][-1])) print("Training-Loss={}".format(history.history['loss'][-1])) print("Validation-Accuracy={}".format(history.history['val_accuracy'][-1])) print("Validation-Loss={}".format(history.history['val_loss'][-1]))
41.295918
91
0.661478
65b7ac10f2593b81d10e7ceec3e26897a323dc76
1,219
py
Python
shinrl/solvers/continuous_ddpg/_build_net_act_mixin.py
omron-sinicx/ShinRL
09f4ae274a33d1fc1d9d542f816aef40014af6b5
[ "MIT" ]
34
2021-12-09T07:12:57.000Z
2022-03-11T08:17:20.000Z
shinrl/solvers/continuous_ddpg/_build_net_act_mixin.py
omron-sinicx/ShinRL
09f4ae274a33d1fc1d9d542f816aef40014af6b5
[ "MIT" ]
null
null
null
shinrl/solvers/continuous_ddpg/_build_net_act_mixin.py
omron-sinicx/ShinRL
09f4ae274a33d1fc1d9d542f816aef40014af6b5
[ "MIT" ]
4
2021-12-11T07:48:01.000Z
2022-03-01T23:50:33.000Z
"""MixIn building act_functions for GymExplore and GymEval MixIns. Author: Toshinori Kitamura Affiliation: NAIST & OSX """ from typing import Callable, Optional import gym import shinrl as srl from .config import DdpgConfig class BuildNetActMixIn: def initialize(self, env: gym.Env, config: Optional[DdpgConfig] = None) -> None: super().initialize(env, config) self.explore_act = self._build_act_fn(self.config.explore.name) self.eval_act = self._build_act_fn(self.config.evaluate.name) def _build_act_fn(self, flag) -> Callable[[], srl.ACT_FN]: net = self.pol_net if flag == "oracle" or flag == "greedy": net_act = srl.build_normal_diagonal_net_act(net) def act_fn(key, obs): params = self.data["PolNetParams"] return net_act(key, obs, params, 0) elif flag == "normal": net_act = srl.build_normal_diagonal_net_act(net) def act_fn(key, obs): scale = self.config.normal_scale params = self.data["PolNetParams"] return net_act(key, obs, params, scale) else: raise NotImplementedError return act_fn
29.731707
84
0.631665
02b472e054a4436edd129817288e04d1f6a12fa2
2,001
py
Python
scripts/upstream_changes.py
rendiputra/website
4b93c0608828e685881be1662e766d696f0b097b
[ "CC-BY-4.0" ]
3,157
2017-10-18T13:28:53.000Z
2022-03-31T06:41:57.000Z
scripts/upstream_changes.py
rendiputra/website
4b93c0608828e685881be1662e766d696f0b097b
[ "CC-BY-4.0" ]
27,074
2017-10-18T09:53:11.000Z
2022-03-31T23:57:19.000Z
scripts/upstream_changes.py
rendiputra/website
4b93c0608828e685881be1662e766d696f0b097b
[ "CC-BY-4.0" ]
11,539
2017-10-18T15:54:11.000Z
2022-03-31T12:51:54.000Z
#!/usr/bin/env python import re from subprocess import check_output import click def last_commit(path, git): """ Find the hash of the last commit that touched a file. """ cmd = [git, "log", "-n", "1", "--pretty=format:%H", "--", path] try: return check_output(cmd) except Exception as exc: raise exc def diff(reference_commit_hash, translation_commit_hash, reference_path, git): """ Returns the diff between two hashes on a specific file """ cmd = [git, "diff", "%s...%s" % (translation_commit_hash, reference_commit_hash), "--", reference_path] try: return check_output(cmd) except Exception as exc: raise exc def find_full_path(path, git): cmd = [git, "ls-tree", "--name-only", "--full-name", "HEAD", path] try: return check_output(cmd).strip() except Exception as exc: raise exc def find_reference(path, git): abs_path = find_full_path(path, git=git) return re.sub('content/(\w{2})/', 'content/en/', abs_path) @click.command() @click.argument("path") @click.option("--reference", "reference", help="Specify the reference version of the file. Default to the English one.", default=None) @click.option("--git-path", "git", help="Specify git path", default="git") def main(path, reference, git): """ Find what changes occurred between two versions ex: ./upstream_changes.py content/fr/_index.html """ if reference is None: reference = find_reference(path, git=git) reference_commit_hash = last_commit(path=reference, git=git) translation_commit_hash = last_commit(path=path, git=git) print(diff( reference_commit_hash=reference_commit_hash, translation_commit_hash=translation_commit_hash, reference_path=reference, git=git )) if __name__ == '__main__': main()
25.329114
92
0.616192
b21cbcaa26ca31e519292685c2cc61f9a9487fe9
322
py
Python
pacman-arch/test/pacman/tests/sync003.py
Maxython/pacman-for-termux
3b208eb9274cbfc7a27fca673ea8a58f09ebad47
[ "MIT" ]
23
2021-05-21T19:11:06.000Z
2022-03-31T18:14:20.000Z
source/pacman-6.0.1/test/pacman/tests/sync003.py
Scottx86-64/dotfiles-1
51004b1e2b032664cce6b553d2052757c286087d
[ "Unlicense" ]
11
2021-05-21T12:08:44.000Z
2021-12-21T08:30:08.000Z
source/pacman-6.0.1/test/pacman/tests/sync003.py
Scottx86-64/dotfiles-1
51004b1e2b032664cce6b553d2052757c286087d
[ "Unlicense" ]
1
2021-09-26T08:44:40.000Z
2021-09-26T08:44:40.000Z
self.description = "Install a package from a sync db, with a filesystem conflict" sp = pmpkg("dummy") sp.files = ["bin/dummy", "usr/man/man1/dummy.1"] self.addpkg2db("sync", sp) self.filesystem = ["bin/dummy"] self.args = "-S %s" % sp.name self.addrule("PACMAN_RETCODE=1") self.addrule("!PKG_EXIST=dummy")
23
81
0.667702
0c221875dd13afd534b86ec96cd3820a2eaca0c7
2,850
py
Python
Python/Buch_Python3_Das_umfassende_Praxisbuch/Kapitel_07_Sequenzen_Mengen_und_Generatoren/08_chapter_07_repetition_questions.py
Apop85/Scripts
e71e1c18539e67543e3509c424c7f2d6528da654
[ "MIT" ]
null
null
null
Python/Buch_Python3_Das_umfassende_Praxisbuch/Kapitel_07_Sequenzen_Mengen_und_Generatoren/08_chapter_07_repetition_questions.py
Apop85/Scripts
e71e1c18539e67543e3509c424c7f2d6528da654
[ "MIT" ]
6
2020-12-24T15:15:09.000Z
2022-01-13T01:58:35.000Z
Python/Buch_Python3_Das_umfassende_Praxisbuch/Kapitel_07_Sequenzen_Mengen_und_Generatoren/08_chapter_07_repetition_questions.py
Apop85/Scripts
1d8dad316c55e1f1343526eac9e4b3d0909e4873
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding:utf-8 -*- ### # File: 08_chapter_07_repetition_questions.py # Project: Kapitel_07_Sequenzen_Mengen_und_Generatoren # Created Date: Tuesday 05.03.2019, 16:17 # Author: Apop85 # ----- # Last Modified: Tuesday 05.03.2019, 16:43 # ----- # Copyright (c) 2019 Apop85 # This software is published under the MIT license. # Check http://www.opensource.org/licenses/MIT for further informations # ----- # Description: ### import re def output(title, string): max_length=80 max_delta=20 string+=' '*max_length print('╔'+'═'*max_length+'╗') print('║'+title.center(max_length).upper()+'║') print('╠'+'═'*max_length+'╣') search_pattern=re.compile(r'(.{'+str(max_length-max_delta-10)+r','+str(max_length-10)+r'}[^\w"])') reg_lines=search_pattern.findall(string) for line in reg_lines: print('║ '+line+' '*(max_length-len(line)-1)+'║') print('╚'+'═'*max_length+'╝') input() output('Aufgabe 1','Die Ausgangsliste lautet ["mond","stoff","treib","raum","schiff"]. Wie lautet die Ausgabe von folgenden Anweisungen?') output('Anweisung 1','print(liste[0])') output('Lösung Anweisung 1:','Das erste Item der Liste wird ausgegeben: "mond"') output('Anweisung 2','print(liste[2]+liste[1])') output('Lösung Anweisung 2:','Das dritte und zweite Item der liste wird konkatiniert: "treibstoff"') output('Anweisung 3','print(liste[-2]+liste[-1])') output('Lösung Anweisung 3:','Das zweitletzte und letzte Item der Liste wird konkatiniert: "raumschiff"') output('Anweisung 4','for wort in liste: if wort[0] == "s": print(wort)') output('Lösung Anweisung 4:','Alle Items der Liste die mit einem "s" beginnen werden ausgegeben: "stoff", "schiff"') output('Anweisung 5','for wort in liste: print(wort[1])') output('Lösung Anweisung 5:','Von jedem Item der Liste wird der 2. Buchstabe ausgegeben: o,t,r,a,c') output('Anweisung 6','liste=liste+["gestein"]') output('Lösung Anweisung 6:','Fügt der Liste ein weiteres Item mit dem Inhalt "gestein" hinzu: ["mond","stoff","treib","raum","schiff", "gestein"]') output('Anweisung 7','print(liste[0]+liste[-1])') output('Lösung Anweisung 7:','Das erste und letzte Item der Liste wird konkatiniert: "mondgestein"') output('Aufgabe 2','Welchen Wert haben die Listenobjekte s1,s2 und s3 jeweils nach folgenden Anweisungen:') output('Anweisung 1','s1 = [1]: s1=[1,s1]: s1=[1,s1]') output('Lösung Anweisung 1','s1=[1,[1,[1]]]') output('Anweisung 2','A=["Haus","Garten"]: B=["bau","tier","pflanze"]: s2=[i+j for i in A for j in B]') output('Lösung Anweisung 2','"Hausbau", "Haustier", "Hauspflanze", "Gartenbau", "Gartentier", "Gartenpflanze"') output('Anweisung 3','A=[1,2,3,4]: B=[2,3,4,5]: s3=[i for i in A+B if (i not in A) or (i not in B)') output('Lösung Anweisung 3','Es werden alle Zahlen ausgegeben welche nicht in beiden Listen vorkommen: 1,5')
50
148
0.683509
0c230992f1ad2f555331157b7145688f14ef7b19
1,101
py
Python
Aufgabe4-Implementierung/DrawRectangles.py
laugengebaeck/BwInf-37-R1
e048aec81cbeacdd7cc858824c99dae9684efb2b
[ "Apache-2.0" ]
1
2020-06-16T10:22:16.000Z
2020-06-16T10:22:16.000Z
Aufgabe4-Implementierung/DrawRectangles.py
laugengebaeck/BwInf-37-R1
e048aec81cbeacdd7cc858824c99dae9684efb2b
[ "Apache-2.0" ]
null
null
null
Aufgabe4-Implementierung/DrawRectangles.py
laugengebaeck/BwInf-37-R1
e048aec81cbeacdd7cc858824c99dae9684efb2b
[ "Apache-2.0" ]
null
null
null
import turtle import time f = open ("coordinates.txt", "r") coordinates = f.readlines() number = "" enclose = [] for a in coordinates[0]: if a != "," and a != "\n": number = number + a elif a == ",": enclose.append(int(number)*20) number = "" turtle.forward(enclose[0]) turtle.left(90) turtle.forward(enclose[1]) turtle.left(90) turtle.forward(enclose[0]) turtle.left(90) turtle.forward(enclose[1]) turtle.left(90) enclose = [] for b in coordinates: for a in b: if a != "," and a != "\n": number = number + a elif a == ",": enclose.append(int(number)*20) number = "" if len(enclose) > 2: turtle.penup() turtle.setposition(enclose[0], enclose[1]) turtle.pendown() turtle.forward(enclose[2]) turtle.left(90) turtle.forward(enclose[3]) turtle.left(90) turtle.forward(enclose[2]) turtle.left(90) turtle.forward(enclose[3]) turtle.left(90) enclose = [] time.sleep(10)
22.469388
51
0.534968
ac61e37f4098b532dcb9d24993da028ccecb5fc3
276
py
Python
backups/sandbox-backup/python/sandbox_start.py
roskenet/Playground
3cce70eeb38646b0f2ffbd071c3aaec7b8f5b9cb
[ "MIT" ]
null
null
null
backups/sandbox-backup/python/sandbox_start.py
roskenet/Playground
3cce70eeb38646b0f2ffbd071c3aaec7b8f5b9cb
[ "MIT" ]
null
null
null
backups/sandbox-backup/python/sandbox_start.py
roskenet/Playground
3cce70eeb38646b0f2ffbd071c3aaec7b8f5b9cb
[ "MIT" ]
1
2020-10-02T04:57:25.000Z
2020-10-02T04:57:25.000Z
#!/usr/bin/env python3 import subprocess import io process = subprocess.Popen(['ls', '-la'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout,stderr = process.communicate() output = stdout.decode("utf-8") for i in output.split("\n"): print(i)
17.25
41
0.666667
5a5637e816c2d8e210de113d895ea179b8cd8ee3
6,310
py
Python
InterviewBit_problems/Sorting/Max Sum Contiguous SubArray/solution.py
gbrls/CompetitiveCode
b6f1b817a655635c3c843d40bd05793406fea9c6
[ "MIT" ]
165
2020-10-03T08:01:11.000Z
2022-03-31T02:42:08.000Z
InterviewBit_problems/Sorting/Max Sum Contiguous SubArray/solution.py
gbrls/CompetitiveCode
b6f1b817a655635c3c843d40bd05793406fea9c6
[ "MIT" ]
383
2020-10-03T07:39:11.000Z
2021-11-20T07:06:35.000Z
InterviewBit_problems/Sorting/Max Sum Contiguous SubArray/solution.py
gbrls/CompetitiveCode
b6f1b817a655635c3c843d40bd05793406fea9c6
[ "MIT" ]
380
2020-10-03T08:05:04.000Z
2022-03-19T06:56:59.000Z
''' This program returns an integer representing the maximum possible sum of the contiguous subarray using Kadane's Algorithm - Creating a function maxSubArray() which will take one argument as a List A - Initializing two variables max_so_far and curr_max which will store the first element in the List A - Traversing the List A from second element till the last and find the maximum sum from the contiguous subarray - curr_max will store the maximum value between the current element and the curr_max + current element - max_so_far will store the maximum value between max_so_far and curr_max - At last returning the maximum possible sum of the contiguous subarray ''' def maxSubArray(A): max_so_far =A[0] curr_max = A[0] for i in range(1,len(A)): curr_max = max(A[i], curr_max + A[i]) max_so_far = max(max_so_far,curr_max) return max_so_far if __name__ == "__main__": A=[ -342, -193, 47, 33, -346, -245, -161, -153, 23, 99, -239, -256, -141, -94, -473, -185, -56, -243, -95, -118, -77, -122, -46, -56, -276, -208, -469, -429, -193, 61, -302, -247, -388, -348, 1, -431, -130, -216, -324, 12, -195, -408, -191, -368, 93, -269, -386, 43, -334, -19, 18, -291, -257, -325, 11, -200, -266, 85, -496, -30, -369, -236, -465, -476, -478, -211, 45, 56, -485, 11, 3, -201, 3, -22, -260, -400, -393, -422, -463, 79, -77, -114, -81, -301, -115, -102, -299, -468, -339, -433, 66, 53, 49, -343, -342, -189, 0, -392, 76, -226, -273, -355, -256, -317, -188, -286, -351, 59, -88, 65, -57, -67, 30, -92, -400, 9, -459, -334, -342, -259, -217, -330, -126, -279, -190, -350, -60, -437, 58, -143, -209, 60, -333, 68, -358, -335, -214, -186, -130, -54, -17, -480, -489, -448, -352, 40, -64, -469, -355, 24, -282, 6, -63, -325, -93, -60, 59, -307, -201, 79, -90, -61, -52, 77, -172, -18, -203, 6, -99, -303, -365, -256, 18, -252, -188, -128, 20, 48, -285, -135, -405, -462, -53, -61, -259, -423, -357, -224, -319, -305, -235, -360, -319, -70, -210, -364, -101, -205, -307, -165, -84, -497, 50, -366, -339, -262, -129, -410, -35, -236, -28, -486, -14, -267, -95, -424, -38, -424, -378, -237, -155, -386, -247, -186, -285, -489, -26, -148, -429, 64, -27, -358, -338, -469, -8, -330, -242, -434, -49, -385, -326, -2, -406, -372, -483, -69, -420, -116, -498, -484, -242, -441, -18, -395, -116, -297, -163, -238, -269, -472, -15, -69, -340, -498, -387, -365, -412, -413, -180, -104, -427, -306, -143, -228, -473, -475, -177, -105, 47, -408, -401, -118, -157, -27, -182, -319, 63, -300, 6, -64, -22, -68, -395, -423, -499, 34, -184, -238, -386, -54, 61, -25, -12, -285, -112, -145, 32, -294, -10, -325, -132, -143, -201, 53, -393, -33, -77, -300, -252, -123, 99, -39, -289, -415, -280, -163, -77, 53, -183, 32, -479, -358, -188, -42, -73, -130, -215, 75, 0, -80, -396, -145, -286, -443, 77, -296, -100, -410, 11, -417, -371, 8, -123, -341, -487, -419, -256, -179, -62, 90, -290, -400, -217, -240, 60, 26, -320, -227, -349, -295, -489, 15, -42, -267, -43, -77, 28, -456, -312, 68, -445, -230, -375, -47, -218, -344, -9, -196, -327, -336, -459, -93, 40, -166, -270, -52, -392, -271, -19, -419, -405, -499, -395, -257, -411, -289, -362, -242, -398, -147, -410, -62, -399, 15, -449, -286, -25, -319, -446, -422, -174, -439, -218, -230, -64, -96, -473, -252, 64, -284, -94, 41, -375, -273, -22, -363, -133, -172, -185, -99, 90, -360, -201, -395, -24, -113, 98, -496, -451, -164, -388, -192, -18, 86, -409, -469, -38, -194, -72, -318, -415, 66, -318, -400, -60, 2, -178, -55, 86, -367, -186, 9, -430, -309, -477, -388, -75, -369, -196, -261, -492, -142, -16, -386, -76, -330, 1, -332, 66, -115, -309, -485, -210, -189, 17, -202, -254, 72, -106, -490, -450, -259, -135, -30, -459, -215, -149, -110, -480, -107, -18, 91, -2, -269, -64, -347, -404, -346, -390, -300, 50, -33, 92, -91, -32, 77, -58, -336, 77, -483, -488, 49, -497, 33, -435, -431, -123, 68, -11, -125, -397, 9, -446, -267, -91, 63, -107, -49, 69, -368, -320, -348, -143, 51, -452, -96, 90, 83, -97, -84, 17, -3, -125, -124, -27, -439, 99, -379, -143, -101, -306, -364, -228, -289, -414, -411, -435, -51, -47, -353, -488, -232, -405, -90, -442, -242, 49, -196, 59, -281, -303, -33, -337, -427, -356, 32, -117, -438, 5, -158, 60, -252, -138, -131, 40, -41, 81, -459, -477, 100, -144, -495, 86, -321, 21, -30, -71, -40, -236, -180, -211, 64, -338, -67, -20, -428, -230, -262, -383, -463, 29, -166, -477, -393, -472, -405, -436, 25, -460, 59, -254, -337, 89, -232, -250, 41, -433, -125, -10, -74, 38, -351, -140, -92, -413, -279, 91, -63, -110, -81, -33, -55, -20, -148, 90, 73, -79, -91, -247, -219, -185, -133, -392, -427, -253, 65, -410, -368, 57, -66, -108, 90, -437, -90, -346, -51, -198, -287, 96, -386, 71, -406, -282, -42, -313, -164, -201, 7, -143, -8, -253, -78, -115, -99, -143, 25, 95, -448, -17, -309, -95, -433, -388, -353, -319, -172, -91, -274, -420, 78, -438, -244, -319, -164, -287, -197, 49, -78, -11, -262, -425, -40, -170, -182, 65, -466, -456, -453, 51, -382, -6, -177, -128, -55, 19, -260, -194, -52, 8, -482, -452, -99, -406, -323, -405, -154, -359, 74, -241, -253, -206, 58, -154, -311, -182, -433, -377, -81, -499, -468, -491, -292, -146, 81, -200, -145, -142, -238, -377, -98, -410, 37, -306, -233, -187, 96, 29, -415, -165, -127, 8, -497, -204, -409, -475, -420, -55, -25, 59, -490, -426, -178, -447, -412, 80, -305, -246, -398, -164, 93, -342, 76, 78, -387, -235, 34, -248, -11, -421, 85, -240, -159, -330, -381, -36, -317, -313, -221, -119, -181, 23, 11, -399, 75, -224, -154, -23, -66, 94, -488, 71, -74, -94, -292, -293, -154, 16, -39, -274, -23, -270, -231, 75, -439, -268, -94, 19, -8, -155, -213, 0, -124, -314, -74, -352, -294, -44, -465, -129, -342, -215, -472, -116, -17, -228, -28, -214, -164, 0, -299, -470, 15, -67, -238, 75, -48, -411, -72, -344, 100, -316, -365, -219, -274, -125, -162, 85, -344, -240, -411, -99, -211, -358, -67, -20, -154, -119, -153, -86, -406, 87, -366, -360, -479, -358, -431, -317, -26, -359, -423, -490, -244, -24, -124, 63, -416, -55, 17, -439, 46, -139, -234, 89, -329, -270, 36, 29, -32, -161, -165, -171, -14, -219, -225, -85, 24, -123, -249, -413, 58, 84, -1, -417, -492, -358, -397, -240, -47, -133, -163, -490, -171, 87, -418, -386, -355, -289, -323, -355, -379, 75, -52, -230, 93, -191, -31, -357, -164, -359, -188 ] print(maxSubArray(A))
286.818182
5,350
0.518859
cedcf88e4e5e29c1bd7e7732bb42f4a9d611eb55
5,630
py
Python
verto/processors/GenericContainerBlockProcessor.py
uccser/verto
d36aa88b208f1700fafc033679bd1e9775496d25
[ "MIT" ]
4
2017-04-10T06:09:54.000Z
2019-05-04T02:07:40.000Z
verto/processors/GenericContainerBlockProcessor.py
uccser/verto
d36aa88b208f1700fafc033679bd1e9775496d25
[ "MIT" ]
268
2017-04-03T20:40:46.000Z
2022-02-04T20:10:08.000Z
verto/processors/GenericContainerBlockProcessor.py
uccser/kordac
d36aa88b208f1700fafc033679bd1e9775496d25
[ "MIT" ]
1
2019-01-07T15:46:31.000Z
2019-01-07T15:46:31.000Z
from markdown.blockprocessors import BlockProcessor from verto.errors.TagNotMatchedError import TagNotMatchedError from verto.errors.ArgumentValueError import ArgumentValueError from verto.processors.utils import etree, parse_arguments, process_parameters, blocks_to_string from verto.utils.HtmlParser import HtmlParser from verto.utils.HtmlSerializer import HtmlSerializer import re class GenericContainerBlockProcessor(BlockProcessor): def __init__(self, processor, ext, *args, **kwargs): ''' Args: ext: An instance of the Verto Extension. ''' super().__init__(*args, **kwargs) self.processor = processor self.settings = ext.settings tag_argument = ext.processor_info[self.processor].get('tag_argument', self.processor) self.p_start = re.compile(r'(^|\n) *\{{{0} ?(?P<args>[^\}}]*)(?<! end)\}} *(\n|$)'.format(tag_argument)) self.p_end = re.compile(r'(^|\n) *\{{{0} end\}} *(\n|$)'.format(tag_argument)) self.arguments = ext.processor_info[self.processor]['arguments'] template_name = ext.processor_info[self.processor].get('template_name', self.processor) self.template = ext.jinja_templates[template_name] self.template_parameters = ext.processor_info[self.processor].get('template_parameters', None) self.process_parameters = lambda processor, parameters, argument_values: \ process_parameters(ext, processor, parameters, argument_values) def test(self, parent, block): ''' Tests a block to see if the run method should be applied. Args: parent: The parent node of the element tree that children will reside in. block: The block to be tested. Returns: True if there are any start or end tags within the block. ''' return self.p_start.search(block) is not None or self.p_end.search(block) is not None def run(self, parent, blocks): ''' Generic run method for container tags. Args: parent: The parent node of the element tree that children will reside in. blocks: A list of strings of the document, where the first block tests true. Raises: ArgumentValueError: If value for a given argument is incorrect. TagNotMatchedError: If end tag is not found for corresponding start tag. ''' block = blocks.pop(0) start_tag = self.p_start.search(block) end_tag = self.p_end.search(block) if ((start_tag is None and end_tag is not None) or (start_tag and end_tag and start_tag.end() > end_tag.start())): raise TagNotMatchedError(self.processor, block, 'end tag found before start tag') before = block[:start_tag.start()] after = block[start_tag.end():] if before.strip() != '': self.parser.parseChunk(parent, before) if after.strip() != '': blocks.insert(0, after) argument_values = parse_arguments(self.processor, start_tag.group('args'), self.arguments) content_blocks = [] the_rest = '' inner_start_tags = 0 inner_end_tags = 0 while len(blocks) > 0: block = blocks.pop(0) inner_tag = self.p_start.search(block) end_tag = self.p_end.search(block) if ((inner_tag and end_tag is None) or (inner_tag and end_tag and inner_tag.start() < end_tag.end())): inner_start_tags += 1 if end_tag and inner_start_tags == inner_end_tags: content_blocks.append(block[:end_tag.start()]) the_rest = block[end_tag.end():] break elif end_tag: inner_end_tags += 1 end_tag = None content_blocks.append(block) content_blocks, extra_args = self.custom_parsing(content_blocks, argument_values) argument_values.update(extra_args) if the_rest.strip() != '': blocks.insert(0, the_rest) if end_tag is None or inner_start_tags != inner_end_tags: raise TagNotMatchedError(self.processor, block, 'no end tag found to close start tag') content_tree = etree.Element('content') self.parser.parseChunk(content_tree, blocks_to_string(content_blocks)) content = '' for child in content_tree: content += HtmlSerializer.tostring(child) + '\n' content = content.strip('\n') if content.strip() == '': message = 'content cannot be blank.' raise ArgumentValueError(self.processor, 'content', content, message) argument_values['content'] = content context = self.process_parameters(self.processor, self.template_parameters, argument_values) html_string = self.template.render(context) parser = HtmlParser() parser.feed(html_string).close() parent.append(parser.get_root()) def custom_parsing(self, content_blocks, argument_values): ''' This serves as a placeholder method, to be used by processes that use the GenericContainerBlockProcessor but need to carry out further parsing of the block's contents. Args: content_blocks: List of strings to either be parsed or inserted as content in template. argument_values: Dictionary of values to be inserted in template. Returns: Tuple containing content_blocks (unchanged) and empty dictionary. ''' return (content_blocks, {})
40.797101
114
0.638188
cc168d1c4516aba78a4cd92281cd0fa4db4f638f
416
py
Python
BeautifulData/Admin/admin_setup.py
zhangyafeii/Flask
9c9a5ea282f77aabcda838796dad2411af9b519f
[ "MIT" ]
null
null
null
BeautifulData/Admin/admin_setup.py
zhangyafeii/Flask
9c9a5ea282f77aabcda838796dad2411af9b519f
[ "MIT" ]
null
null
null
BeautifulData/Admin/admin_setup.py
zhangyafeii/Flask
9c9a5ea282f77aabcda838796dad2411af9b519f
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ @Datetime: 2019/1/2 @Author: Zhang Yafei """ import settings from importlib import import_module def admin_auto_discover(): for app_name in settings.INSTALLED_APPS: try: __import__('{}.admin'.format(app_name)) except: try: import_module('{}.admin'.format(app_name)) except Exception as e: print(e)
21.894737
58
0.576923
4f4f1bdaa96d91a91b3307c1c06b58139a48f973
3,826
py
Python
tests/test_routines.py
keawe-software/Umbrella
eee5aded0bb8ef09583dcf320802e0ae0e41041f
[ "Apache-2.0" ]
null
null
null
tests/test_routines.py
keawe-software/Umbrella
eee5aded0bb8ef09583dcf320802e0ae0e41041f
[ "Apache-2.0" ]
null
null
null
tests/test_routines.py
keawe-software/Umbrella
eee5aded0bb8ef09583dcf320802e0ae0e41041f
[ "Apache-2.0" ]
1
2021-06-04T17:30:40.000Z
2021-06-04T17:30:40.000Z
#!/usr/bin/python import os import requests import sqlite3 import urlparse import json CRED = '\033[91m' CYEL = '\033[33m' CEND = '\033[0m' error_count = 0 # next three lines allow unicode handling import sys from multiprocessing import Condition reload(sys) sys.setdefaultencoding('utf8') def abortX(): global error_count error_count -= 1 if error_count < 1: assert(False) def expect(r,text=None): if text is None: # use first parameter as boolean assert r else: if text not in r.text: print r.text print CYEL+'expected text not found: '+CRED+text+CEND abortX() sys.stdout.write('.') sys.stdout.flush() def expectError(response,message): if '<div class="errors">' not in response.text: print response.text print CYEL+'error tag expected, but not found!'+CEND abortX() if message not in response.text: print response.text print CYEL+'error '+CRED+message+CYEL+' expected, but other text found!'+CEND abortX() def expectInfo(response,message): if '<div class="infos">' not in response.text: print response.text print CYEL+'info tag expected, but not found!'+CEND abortX() if message not in response.text: print response.text print CYEL+'info '+CRED+message+CYEL+' expected, but other text found!'+CEND abortX() def expectJson(response,json_string): j1 = json.loads(json_string) j2 = json.loads(response.text) if j1 == j2: sys.stdout.write('.') else: print '' print 'expected json: '+json.dumps(j1) print ' got json: '+json.dumps(j2) abortX() def expectNot(r,text): if text in r.text: print r.text print CYEL+'found unexpected text: '+CRED+text+CEND abortX() sys.stdout.write('.') sys.stdout.flush() def expectRedirect(response,url): keys = response.headers.keys() if ('Location' in keys): sys.stdout.write('.') else: print '' print CYEL+'response:'+CEND print response.text print CYEL+'No Location header set, but '+CRED+url+CYEL+' expected'+CEND abortX() if response.headers.get('Location') == url: sys.stdout.write('.') sys.stdout.flush() else: print CYEL+'Expected redirect to '+CRED+url+CYEL+', but found '+CRED+response.headers.get('Location')+CEND abortX() def expectWarning(response,message): if '<div class="warnings">' not in response.text: print response.text print CYEL+'warnings tag expected, but not found!'+CEND abortX() if message not in response.text: print response.text print CYEL+'warning '+CRED+message+CYEL+' expected, but other text found!'+CEND abortX() def params(url): return urlparse.parse_qs(urlparse.urlparse(url).query) def getSession(login, password, module): session = requests.session(); r = session.post('http://localhost/user/login', data={'username':login, 'pass': password},allow_redirects=False) # get token r = session.get('http://localhost/user/login?returnTo=http://localhost/'+module+'/',allow_redirects=False) expect('Location' in r.headers) redirect = r.headers.get('Location'); expect('http://localhost/'+module+'/?token=' in redirect) prefix,token=redirect.split('=') # create new session to test token function session = requests.session() # redirect should contain a token in the GET parameters, thus the page should redirect to the same url without token parameter r = session.get(redirect,allow_redirects=False) expectRedirect(r,'http://localhost/'+module+'/'); return session,token
29.430769
130
0.631992
4f85159e61c0af274a85a864951110abb13c9015
1,252
py
Python
Packs/CortexXDR/Scripts/EntryWidgetPieAlertsXDR/EntryWidgetPieAlertsXDR.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
799
2016-08-02T06:43:14.000Z
2022-03-31T11:10:11.000Z
Packs/CortexXDR/Scripts/EntryWidgetPieAlertsXDR/EntryWidgetPieAlertsXDR.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
9,317
2016-08-07T19:00:51.000Z
2022-03-31T21:56:04.000Z
Packs/CortexXDR/Scripts/EntryWidgetPieAlertsXDR/EntryWidgetPieAlertsXDR.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
1,297
2016-08-04T13:59:00.000Z
2022-03-31T23:43:06.000Z
import demistomock as demisto incident = demisto.incidents() data = { "Type": 17, "ContentsFormat": "pie", "Contents": { "stats": [ { "data": [ int(incident[0].get('CustomFields', {}).get('xdrhighseverityalertcount', 0)) ], "groups": None, "name": "high", "label": "incident.severity.high", "color": "rgb(255, 23, 68)" }, { "data": [ int(incident[0].get('CustomFields', {}).get('xdrmediumseverityalertcount', 0)) ], "groups": None, "name": "medium", "label": "incident.severity.medium", "color": "rgb(255, 144, 0)" }, { "data": [ int(incident[0].get('CustomFields', {}).get('xdrlowseverityalertcount', 0)) ], "groups": None, "name": "low", "label": "incident.severity.low", "color": "rgb(0, 205, 51)" }, ], "params": { "layout": "horizontal" } } } demisto.results(data)
28.454545
98
0.388179
4f8ed0e6691c3d7d350704e515ce76c39385c889
1,153
py
Python
main/assets/models/create_models_list.py
Lyniat/dungeon-hop
e8d19b2c933feb6665935f37f73785626698ea09
[ "MIT" ]
null
null
null
main/assets/models/create_models_list.py
Lyniat/dungeon-hop
e8d19b2c933feb6665935f37f73785626698ea09
[ "MIT" ]
null
null
null
main/assets/models/create_models_list.py
Lyniat/dungeon-hop
e8d19b2c933feb6665935f37f73785626698ea09
[ "MIT" ]
null
null
null
import os import json files = {} players = [] enemies = [] obstacles = [] path = os.getcwd()+"/json" #player models id = 0 print("\nadding files for player:") for file in os.listdir(path+"/players"): if file.endswith(".js"): name = file.split(".")[0] players.append({"name":name,"id":id}) id += 1 print(name) print("\nfinished player files") #obstacle models id = 0 print("\nadding files for obstacles:") for file in os.listdir(path+"/obstacles"): if file.endswith(".js"): name = file.split(".")[0] obstacles.append({"name":name,"id":id}) id += 1 print(name) print("\nfinished obstacle files") #enemy models id = 0 print("\nadding files for enemies:") for file in os.listdir(path+"/enemies"): if file.endswith(".js"): name = file.split(".")[0] enemies.append({"name":name,"id":id}) id += 1 print(name) print("\nmerging different objects") files["players"] = players files["enemies"] = enemies files["obstacles"] = obstacles with open(path+"/files.json", 'w') as outfile: json.dump(files, outfile) print("\nfinished enemy files")
20.589286
47
0.606245
8c3154123556ccdc7d8d96fcfd8f4ab8907be858
7,109
py
Python
5_DeepLearning-Visualization/DogsCats_Dataset_class.py
felixdittrich92/DeepLearning-tensorflow-keras
2880d8ed28ba87f28851affa92b6fa99d2e47be9
[ "Apache-2.0" ]
null
null
null
5_DeepLearning-Visualization/DogsCats_Dataset_class.py
felixdittrich92/DeepLearning-tensorflow-keras
2880d8ed28ba87f28851affa92b6fa99d2e47be9
[ "Apache-2.0" ]
null
null
null
5_DeepLearning-Visualization/DogsCats_Dataset_class.py
felixdittrich92/DeepLearning-tensorflow-keras
2880d8ed28ba87f28851affa92b6fa99d2e47be9
[ "Apache-2.0" ]
null
null
null
import os import numpy as np from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split import cv2 from skimage import transform from tensorflow.keras.utils import to_categorical from tensorflow.keras.preprocessing.image import ImageDataGenerator # Dataset : https://www.microsoft.com/en-us/download/details.aspx?id=54765 FILE_DIR = os.path.abspath("../DeepLearning/data/PetImages") # path to folder with dogs cats Dataset IMG_WIDTH = 64 IMG_HEIGHT = 64 IMG_DEPTH = 3 def extract_cats_vs_dogs(): cats_dir = os.path.join(FILE_DIR, "Cat") dogs_dir = os.path.join(FILE_DIR, "Dog") print("Deleting no .jpg images!") for f in os.listdir(cats_dir): if f.split(".")[-1] != "jpg": print("Removing file: ", f) os.remove(os.path.join(cats_dir, f)) for f in os.listdir(dogs_dir): if f.split(".")[-1] != "jpg": print("Removing file: ", f) os.remove(os.path.join(dogs_dir, f)) num_cats = len(os.listdir(cats_dir)) num_dogs = len(os.listdir(dogs_dir)) num_images = num_cats + num_dogs x = np.zeros(shape=(num_images, IMG_WIDTH, IMG_HEIGHT, IMG_DEPTH), dtype=np.float32) y = np.zeros(shape=(num_images), dtype=np.int8) cnt = 0 print("Start reading cat images!") for f in os.listdir(cats_dir): img_file = os.path.join(cats_dir, f) try: img = cv2.imread(img_file, cv2.IMREAD_COLOR) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) x[cnt] = transform.resize(img, (IMG_WIDTH, IMG_HEIGHT, IMG_DEPTH)) y[cnt] = 0 cnt += 1 except: print("Cat image %s cannot be read!" % f) os.remove(img_file) print("Start reading dog images!") for f in os.listdir(dogs_dir): img_file = os.path.join(dogs_dir, f) try: img = cv2.imread(img_file, cv2.IMREAD_COLOR) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) x[cnt] = transform.resize(img, (IMG_WIDTH, IMG_HEIGHT, IMG_DEPTH)) y[cnt] = 1 cnt += 1 except: print("Dog image %s cannot be read!" % f) os.remove(img_file) # Dropping not readable image idxs x = x[:cnt] y = y[:cnt] np.save(os.path.join(FILE_DIR, "x.npy"), x) np.save(os.path.join(FILE_DIR, "y.npy"), y) def load_cats_vs_dogs(test_size=0.33, extracting_images=False): file_x = os.path.join(FILE_DIR, "x.npy") file_y = os.path.join(FILE_DIR, "y.npy") if not os.path.isfile(file_x) or not os.path.isfile(file_y) or extracting_images: extract_cats_vs_dogs() x = np.load(file_x) y = np.load(file_y) x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=test_size) return (x_train, y_train), (x_test, y_test) class DOGSCATS: def __init__(self, test_size=0.33, extracting_images=False): # Load the data set # Class 0: Cat, Class 1: Dog (self.x_train, self.y_train), (self.x_test, self.y_test) = load_cats_vs_dogs( test_size=test_size, extracting_images=extracting_images) self.x_train_ = None self.x_val = None self.y_train_ = None self.y_val = None # Convert to float32 self.x_train = self.x_train.astype(np.float32) self.y_train = self.y_train.astype(np.float32) self.x_test = self.x_test.astype(np.float32) self.y_test = self.y_test.astype(np.float32) # Save important data attributes as variables self.train_size = self.x_train.shape[0] self.test_size = self.x_test.shape[0] self.train_splitted_size = 0 self.val_size = 0 self.width = self.x_train.shape[1] self.height = self.x_train.shape[2] self.depth = self.x_train.shape[3] self.num_classes = 2 # Constant for the data set self.num_features = self.width * self.height * self.depth # Reshape the y data to one hot encoding self.y_train = to_categorical(self.y_train, num_classes=self.num_classes) self.y_test = to_categorical(self.y_test, num_classes=self.num_classes) # Addtional class attributes self.scaler = None def get_train_set(self): return self.x_train, self.y_train def get_test_set(self): return self.x_test, self.y_test def get_splitted_train_validation_set(self, validation_size=0.33): self.x_train_, self.x_val, self.y_train_, self.y_val =\ train_test_split(self.x_train, self.y_train, test_size=validation_size) self.val_size = self.x_val.shape[0] self.train_splitted_size = self.x_train_.shape[0] return self.x_train_, self.x_val, self.y_train_, self.y_val def data_augmentation(self, augment_size=5000): # Create an instance of the image data generator class image_generator = ImageDataGenerator( rotation_range=10, zoom_range=0.05, width_shift_range=0.05, height_shift_range=0.05, fill_mode='constant', cval=0.0) # Fit the data generator image_generator.fit(self.x_train, augment=True) # Get random train images for the data augmentation rand_idxs = np.random.randint(self.train_size, size=augment_size) x_augmented = self.x_train[rand_idxs].copy() y_augmented = self.y_train[rand_idxs].copy() x_augmented = image_generator.flow(x_augmented, np.zeros(augment_size), batch_size=augment_size, shuffle=False).next()[0] # Append the augmented images to the train set self.x_train = np.concatenate((self.x_train, x_augmented)) self.y_train = np.concatenate((self.y_train, y_augmented)) self.train_size = self.x_train.shape[0] def data_preprocessing(self, preprocess_mode="standard", preprocess_params=None): # Preprocess the data if preprocess_mode == "standard": if preprocess_params: self.scaler = StandardScaler(**preprocess_params) else: self.scaler = StandardScaler(**preprocess_params) else: if preprocess_params: self.scaler = MinMaxScaler(**preprocess_params) else: self.scaler = MinMaxScaler(feature_range=(0, 1)) # Temporary flatteining of the x data self.x_train = self.x_train.reshape(self.train_size, self.num_features) self.x_test = self.x_test.reshape(self.test_size, self.num_features) # Fitting and transforming self.scaler.fit(self.x_train) self.x_train = self.scaler.transform(self.x_train) self.x_test = self.scaler.transform(self.x_test) # Reshaping the xdata back to the input shape self.x_train = self.x_train.reshape( (self.train_size, self.width, self.height, self.depth)) self.x_test = self.x_test.reshape( (self.test_size, self.width, self.height, self.depth))
40.163842
100
0.64341
8c3432369910cbb98badd2404a8465c2ccfcc272
9,463
py
Python
Utils/update_branch_from_version.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
799
2016-08-02T06:43:14.000Z
2022-03-31T11:10:11.000Z
Utils/update_branch_from_version.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
9,317
2016-08-07T19:00:51.000Z
2022-03-31T21:56:04.000Z
Utils/update_branch_from_version.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
1,297
2016-08-04T13:59:00.000Z
2022-03-31T23:43:06.000Z
import subprocess import argparse import os import click import ujson from ruamel.yaml import YAML from ruamel.yaml.scalarstring import FoldedScalarString from pkg_resources import parse_version import shutil ryaml = YAML() ryaml.preserve_quotes = True # type: ignore[assignment] # make sure long lines will not break (relevant for code section) ryaml.width = 50000 # type: ignore[assignment] DOCKERIMAGE_45_TOP_VERSION = '4.5.9' JSON_FOLDERS = ['IncidentFields', 'IncidentTypes', 'IndicatorFields', 'Layouts', 'Classifiers', 'Connections', 'Dashboards', 'IndicatorTypes', 'Reports', 'Widgets'] PLAYBOOK_FOLDERS = ['Playbooks', 'TestPlaybooks'] SCRIPT_FOLDERS = ['Scripts', 'Integrations'] ALL_NON_TEST_DIRS = JSON_FOLDERS.copy() + SCRIPT_FOLDERS.copy() + ['Playbooks'] def should_keep_yml_file(yml_content, new_from_version): # if the file's toversion is lower than the new from version we should delete it if parse_version(yml_content.get('toversion', '99.99.99')) < parse_version(new_from_version): return False return True def should_keep_json_file(json_content, new_from_version): # if the file's toVersion is lower than the new from version we should delete it if parse_version(json_content.get('toVersion', '99.99.99')) < parse_version(new_from_version): return False return True def delete_playbook(file_path): os.remove(file_path) print(f" - Deleting {file_path}") changelog_file = os.path.join(os.path.splitext(file_path)[0] + '_CHANGELOG.md') readme_file = os.path.join(os.path.splitext(file_path)[0] + '_README.md') if os.path.isfile(changelog_file): os.remove(changelog_file) if os.path.isfile(readme_file): os.remove(readme_file) def delete_script_or_integration(path): if os.path.isfile(path): os.remove(path) changelog_file = os.path.splitext(path)[0] + '_CHANGELOG.md' readme_file = os.path.join(os.path.splitext(path)[0] + '_README.md') if os.path.isfile(changelog_file): os.remove(changelog_file) if os.path.isfile(readme_file): os.remove(readme_file) else: shutil.rmtree(path) print(f" - Deleting {path}") def delete_json(file_path): os.remove(file_path) print(f" - Deleting {file_path}") changelog_file = os.path.join(os.path.splitext(file_path)[0] + '_CHANGELOG.md') if os.path.isfile(changelog_file): os.remove(changelog_file) def rewrite_json(file_path, json_content, new_from_version): # if there is no fromVersion in json or the fromVersion is lower than the new from version then update if ('fromVersion' in json_content and parse_version(json_content.get('fromVersion')) < parse_version(new_from_version)) \ or ('fromVersion' not in json_content): json_content['fromVersion'] = new_from_version with open(file_path, 'w') as f: ujson.dump(json_content, f, indent=4, encode_html_chars=True, escape_forward_slashes=False, ensure_ascii=False) print(f" - Updating {file_path}") def rewrite_yml(file_path, yml_content, new_from_version): # if there is no fromVersion in json or the fromversion is lower than the new from version then update if ('fromversion' in yml_content and parse_version(yml_content.get('fromversion')) < parse_version(new_from_version)) \ or ('fromversion' not in yml_content): yml_content['fromversion'] = new_from_version check_dockerimage45(yml_content, new_from_version) if 'script' in yml_content: if isinstance(yml_content.get('script'), str): if yml_content.get('script') not in ('-', ''): yml_content['script'] = FoldedScalarString(yml_content.get('script')) elif yml_content.get('script').get('script') not in ('-', ''): yml_content['script']['script'] = FoldedScalarString(yml_content.get('script').get('script')) with open(file_path, mode='w', encoding='utf-8') as f: ryaml.dump(yml_content, f) print(f" - Updating {file_path}") def check_dockerimage45(yml_content, new_from_version): # check in scripts if 'dockerimage45' in yml_content: if parse_version(new_from_version) > parse_version(DOCKERIMAGE_45_TOP_VERSION): del yml_content['dockerimage45'] # check in integrations elif 'dockerimage45' in yml_content.get('script', {}): if parse_version(new_from_version) > parse_version(DOCKERIMAGE_45_TOP_VERSION): del yml_content['script']['dockerimage45'] def edit_json_content_entity_directory(new_from_version, dir_path): for file_name in os.listdir(dir_path): file_path = os.path.join(dir_path, file_name) if os.path.isfile(file_path) and file_name.endswith('.json') and \ file_path != "Packs/NonSupported/IndicatorTypes/reputations.json": with open(file_path, 'r') as f: json_content = ujson.load(f) if should_keep_json_file(json_content, new_from_version): rewrite_json(file_path, json_content, new_from_version) else: delete_json(file_path) def edit_scripts_or_integrations_directory(new_from_version, dir_path): for script_name in os.listdir(dir_path): package_path = os.path.join(dir_path, script_name) if package_path.endswith('.md'): continue if os.path.isfile(package_path): yml_file_path = package_path else: yml_file_path = os.path.join(package_path, script_name + '.yml') # prevent going to pipfiles and non yml content if yml_file_path.endswith('.yml'): with open(yml_file_path, 'r') as yml_file: yml_content = ryaml.load(yml_file) if should_keep_yml_file(yml_content, new_from_version): rewrite_yml(yml_file_path, yml_content, new_from_version) else: delete_script_or_integration(package_path) def edit_playbooks_directory(new_from_version, dir_path): for file_name in os.listdir(dir_path): file_path = os.path.join(dir_path, file_name) if file_path.endswith('md'): continue if os.path.isfile(file_path): if file_path.endswith('.yml'): with open(file_path, 'r') as yml_file: yml_content = ryaml.load(yml_file) if should_keep_yml_file(yml_content, new_from_version): rewrite_yml(file_path, yml_content, new_from_version) else: delete_playbook(file_path) else: # in some cases test-playbooks are located in a directory within the TestPlaybooks directory. # this part handles these files. inner_dir_path = file_path for inner_file_name in os.listdir(inner_dir_path): file_path = os.path.join(inner_dir_path, inner_file_name) if file_path.endswith('.yml'): with open(file_path, 'r') as yml_file: yml_content = ryaml.load(yml_file) if should_keep_yml_file(yml_content, new_from_version): rewrite_yml(file_path, yml_content, new_from_version) else: delete_playbook(file_path) def check_clear_pack(pack_path): dirs_in_pack = os.listdir(pack_path) check = [True for entity in ALL_NON_TEST_DIRS if entity in dirs_in_pack] if len(check) == 0: click.secho(f"Deleting empty pack {pack_path}\n") shutil.rmtree(pack_path) def edit_pack(new_from_version, pack_name): pack_path = os.path.join('Packs', pack_name) click.secho(f"Starting process for {pack_path}:") for content_dir in os.listdir(pack_path): dir_path = os.path.join(pack_path, content_dir) if content_dir in PLAYBOOK_FOLDERS: edit_playbooks_directory(new_from_version, dir_path) elif content_dir in SCRIPT_FOLDERS: edit_scripts_or_integrations_directory(new_from_version, dir_path) elif content_dir in JSON_FOLDERS: edit_json_content_entity_directory(new_from_version, dir_path) # clearing empty pack folders click.secho("Checking for empty dirs") found_dirs = subprocess.check_output(["find", pack_path, "-type", "d", "-empty"]) if found_dirs: click.secho("Found empty dirs: {}".format(found_dirs.decode('utf-8').split('\n'))) subprocess.call(["find", pack_path, "-type", "d", "-empty", "-delete"]) check_clear_pack(pack_path) click.secho(f"Finished process for {pack_path}\n") def edit_all_packs(new_from_version): for pack_name in os.listdir('Packs'): edit_pack(new_from_version, pack_name) parser = argparse.ArgumentParser("Alter the branch to assign a new fromVersion to all relevant files.") parser.add_argument('-v', '--new-from-version', help='The new from version to assign.', required=True) def main(): new_from_version = parser.parse_args().new_from_version if new_from_version.count('.') == 1: new_from_version = new_from_version + ".0" click.secho("Starting Branch Editing") edit_all_packs(new_from_version) click.secho("Finished updating branch", fg="green") if __name__ == "__main__": main()
36.821012
125
0.670718
4fec7a99a0ba602c990c251a20b71507917d5deb
857
py
Python
sso-db/ssodb/common/models/city_model.py
faical-yannick-congo/sso-backend
e962006b0fecd68e4da94e54b4dc63547a5a2c21
[ "MIT" ]
null
null
null
sso-db/ssodb/common/models/city_model.py
faical-yannick-congo/sso-backend
e962006b0fecd68e4da94e54b4dc63547a5a2c21
[ "MIT" ]
null
null
null
sso-db/ssodb/common/models/city_model.py
faical-yannick-congo/sso-backend
e962006b0fecd68e4da94e54b4dc63547a5a2c21
[ "MIT" ]
null
null
null
import datetime from ..core import db import json from bson import ObjectId from ..models import Country class City(db.Document): created_at = db.StringField(default=str(datetime.datetime.utcnow())) updated_at = db.StringField(default=str(datetime.datetime.utcnow())) name = db.StringField(required=True) country = db.ReferenceField(Country, required=True) def save(self, *args, **kwargs): self.updated_at = str(datetime.datetime.utcnow()) return super(City, self).save(*args, **kwargs) def info(self): data = {'updated-at':self.updated_at, 'id':str(self.id), 'created_at':self.created_at, 'name':self.name, 'country':self.country.code} return data def to_json(self): data = self.info() return json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))
32.961538
81
0.665111
8c724475d6fbaec2c11778116b5afd4db2577711
3,764
py
Python
Generator/xml.py
Design-Computation-RWTH/ILC_Demonstrator
60046366383de053026a0d03b213f6af3610f608
[ "MIT" ]
1
2021-06-08T10:04:35.000Z
2021-06-08T10:04:35.000Z
mvdXMLGen/ILC_Demonstrator-master/Generator/xml.py
BIMInstitut/MRL-Datenbank
81130071d3b76eba010e7649a2cbaf0a1b7dcfc4
[ "MIT" ]
null
null
null
mvdXMLGen/ILC_Demonstrator-master/Generator/xml.py
BIMInstitut/MRL-Datenbank
81130071d3b76eba010e7649a2cbaf0a1b7dcfc4
[ "MIT" ]
1
2021-05-04T09:38:20.000Z
2021-05-04T09:38:20.000Z
# -*- coding: utf-8 -*- from string import Formatter #formatter for getting placeholder and set other value class FormatXML: def __init__(self, template_string): #self.template = open(template_file).read() self.template = template_string self.required_keys = [ele[1] for ele in Formatter().parse(self.template) if ele[1]] #print(self.required_keys) self.parameters = {} def set_value(self, key, value): self.parameters[key] = value def generate(self): if not all(k in self.parameters.keys() for k in self.required_keys): raise ValueError("Not enough keys.") return self.template.format(**self.parameters) def __str__(self): return str(self.generate()) #placeholderreplacement for different templates and parts of mvdxml class TempRule: @staticmethod def get_xml(template_string, template_rule): template_rule_format = FormatXML(template_string) template_rule_format.set_value("template_rule_parameters", template_rule) return template_rule_format.generate() class Concepts: @staticmethod def get_xml(concepts_string, concept_uuid, value_name, template_uuid, requirement, er_uuid, operator, template_rules): concepts_format = FormatXML(concepts_string) concepts_format.set_value("concept_uuid", concept_uuid) concepts_format.set_value("value_name", value_name) concepts_format.set_value("template_uuid", template_uuid) #ref uuid concepts_format.set_value("require", requirement) concepts_format.set_value("er_uuid", er_uuid) #ref uuid concepts_format.set_value("operator", operator) concepts_format.set_value("template_rules", "\n".join(template_rules)) return concepts_format.generate() class Applicability: @staticmethod def set_aplicaplility_format(applicability_string, template_uuid, vorbedingung): applicability_format = FormatXML(applicability_string) applicability_format.set_value("template_uuid", template_uuid) applicability_format.set_value("vorbedingung", "\n".join(vorbedingung)) return applicability_format.generate() class ConceptRoot: @staticmethod def set_cr_format(conceptroot_string, concept_root_uuid, cr_name, cr_name_ifc, applicability, concepts): conceptroot_format = FormatXML(conceptroot_string) conceptroot_format.set_value("concept_root_uuid", concept_root_uuid) conceptroot_format.set_value("cr_name", cr_name) conceptroot_format.set_value("cr_name_ifc", cr_name_ifc) conceptroot_format.set_value("applicability", "\n".join(applicability)) conceptroot_format.set_value("concepts", "\n".join(concepts)) return conceptroot_format.generate() class ModelView: @staticmethod def set_view_format(view_string, view_uuid, mv_name, er_uuid, er_name, concept_roots): view_format = FormatXML(view_string) view_format.set_value("view_uuid", view_uuid) view_format.set_value("mv_name", mv_name) view_format.set_value("er_uuid", er_uuid) view_format.set_value("er_name", er_name) view_format.set_value("concept_roots", "\n".join(concept_roots)) return view_format.generate() class ConceptTemplate: @staticmethod def set_temp_format(template_string): template_format = FormatXML(template_string) return template_format.generate() class create_XML: @staticmethod def get_xml(template, uuid, templates, views): formatter = FormatXML(template) formatter.set_value("uuid", uuid) formatter.set_value("templates", templates) formatter.set_value("views", views) return formatter.generate()
42.292135
122
0.722104