blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
288
content_id
stringlengths
40
40
detected_licenses
listlengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
684 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
147 values
src_encoding
stringclasses
25 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
128
12.7k
extension
stringclasses
142 values
content
stringlengths
128
8.19k
authors
listlengths
1
1
author_id
stringlengths
1
132
c5a1300c883da1921c805a18c66e4dce27d6c66e
c51eef37bb983a9c35635c7ccc96a0cf689a7438
/lecture/lecture_gn5/week1/03_parameter.py
21215f034b5e08cd1b40992831d3dda1790f6621
[]
no_license
Kyeongrok/python_crawler
0a717b43be36584af1b0f7c1ad0c79108a5d11e0
5a5da8af7bb080f752a9a066741ac8adab136a3a
refs/heads/master
2022-09-13T03:15:08.053639
2022-08-02T15:45:03
2022-08-02T15:45:03
124,719,435
40
34
null
2019-02-27T08:29:52
2018-03-11T03:20:32
HTML
UTF-8
Python
false
false
477
py
# parameter 파라메터 매개변수 # 변수 변하는 수(값) ""가 없음 # 상수 항상 같은 수(값) ""가 있음 def printMessage(message): print(message) printMessage("happy spring") # 차이점 # 1. 함수 이름 옆에 괄호에 뭐가 있다 없다. # 2. 함수를 호출 할 때 괄호안에 뭐가 있고 없고 # 3. print()함수에 "hello", message # ctrl + tab 이전 파일로 가기 # ctrl + tab + tab 전전으로 가기 # ctrl + e # command + e
[ "oceanfog1@gmail.com" ]
oceanfog1@gmail.com
aeac86300ebab4cf0eff0327474f80f2a6ed7843
3f06e7ae747e935f7a2d1e1bae27a764c36a77d1
/day11.py
f6ef0bfc5790ca1418db1e53ada53842434704b4
[]
no_license
mn113/adventofcode2016
94465f36c46e9aa21d879d82e043e1db8c55c9da
3a93b23519acbfe326b8bf7c056f1747bbea036a
refs/heads/master
2022-12-11T22:57:21.937221
2022-12-04T16:37:24
2022-12-04T16:37:24
75,545,017
0
0
null
null
null
null
UTF-8
Python
false
false
1,111
py
#! /usr/bin/env python # Transport all items to floor 4, avoiding dangerous situations # (Missionaries/cannibals problem) #4: #3: #2: lp #1: E trc LPTRC trips = 0 elev = 1 state = { # tuple represents: (chip's floor, generator's floor) 'V': (2,1), 'W': (2,1), 'X': (1,1), 'Y': (1,1), 'Z': (1,1) } goal = {key: (4,4) for key in 'VWXYZ'} computedStates = {0: state} newStates = [] def isValid(state): for k,v in state.items(): # Stay between 1 and 4 please: if v[0] > 4 or v[0] < 1 or v[1] > 4 or v[1] < 1: print v, "out of bounds" return False if v[0] != v[1]: # Chip and its generator are apart for k2,v2 in state.items(): if v2[0] == v[0]: # Another generator will infect this chip print "infection", state return False print state, "ok" return True # NEED TO STORE THEM ON EACH OTHER AND COUNT MOVES # binary search # 28 = too low # 53 = too high # 40 = too low # 47 = correct # part 2 # 61 = too low # 71 = correct
[ "recyclebing+github@gmail.com" ]
recyclebing+github@gmail.com
f538641ad09d7696971988e32aa9d00b57082efc
159aed4755e47623d0aa7b652e178296be5c9604
/data/scripts/templates/object/draft_schematic/furniture/shared_furniture_bookcase_modern.py
f02d735683dbae730eb4a049b73eda113bf64955
[ "MIT" ]
permissive
anhstudios/swganh
fb67d42776864b1371e95f769f6864d0784061a3
41c519f6cdef5a1c68b369e760781652ece7fec9
refs/heads/develop
2020-12-24T16:15:31.813207
2016-03-08T03:54:32
2016-03-08T03:54:32
1,380,891
33
44
null
2016-03-08T03:54:32
2011-02-18T02:32:45
Python
UTF-8
Python
false
false
464
py
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Intangible() result.template = "object/draft_schematic/furniture/shared_furniture_bookcase_modern.iff" result.attribute_template_id = -1 result.stfName("string_id_table","") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
[ "rwl3564@rit.edu" ]
rwl3564@rit.edu
bd56c0c31c38bfee93331f533c406ffe5b138e9f
4ba18540bfd8c523fe39bbe7d6c8fa29d4ec0947
/atlas/foundations_rest_api/src/test/filters/parsers/test_number_parser.py
f1fe582e071ade8fc93e52edbe6d1953879e05b3
[ "BSD-3-Clause", "MIT", "CC0-1.0", "Apache-2.0", "BSD-2-Clause", "MPL-2.0" ]
permissive
yottabytt/atlas
c9d8ef45a0921c9f46d3ed94d42342f11488a85e
b040e574fbc64c833039b003f8a90345dd98e0eb
refs/heads/master
2022-10-14T11:12:12.311137
2020-06-13T13:19:35
2020-06-13T13:19:35
272,008,756
0
0
Apache-2.0
2020-06-13T12:55:29
2020-06-13T12:55:28
null
UTF-8
Python
false
false
1,438
py
import unittest from foundations_rest_api.filters.parsers import NumberParser class TestNumberParser(unittest.TestCase): def setUp(self): self._parser = NumberParser() def test_random_value(self): value = 'attack' self.assertRaises(ValueError, self._parser.parse, value) def test_good_string_value(self): value = '3.14' parsed_value = self._parser.parse(value) expected_result = 3.14 self.assertEqual(expected_result, parsed_value) def test_good_float_value(self): value = 9.8 parsed_value = self._parser.parse(value) expected_result = 9.8 self.assertEqual(expected_result, parsed_value) def test_goog_int_value(self): value = 5 parsed_value = self._parser.parse(value) expected_result = 5 self.assertEqual(expected_result, parsed_value) def test_good_string_int_value(self): value = '10' parsed_value = self._parser.parse(value) expected_result = 10 self.assertEqual(expected_result, parsed_value) def test_bad_none_value(self): value = None with self.assertRaises(ValueError) as cm: self._parser.parse(value) self.assertEqual(str(cm.exception), 'Not able to convert "None" to a number') def test_bad_null_value(self): value = 'null' self.assertRaises(ValueError, self._parser.parse, value)
[ "mislam@squareup.com" ]
mislam@squareup.com
e072b567a6d98e5d00916d792ef4296106d3c78f
83552e8512ec76739310b2227c57a76b2080eccc
/plotObjects/fittingFunctions.py
f2bd51ae879114fe986fb46e4f0491881adcf19b
[]
no_license
mlink1990/experimentEagle
c4617e0ec1080ca04ec62b39c92f0c977ec28b09
90394c2d9c2ac68165647bcc8c57c09099c37cf6
refs/heads/master
2022-11-07T09:05:49.134877
2020-06-21T13:47:44
2020-06-21T13:47:44
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,180
py
# -*- coding: utf-8 -*- """ Created on Tue Apr 05 09:55:44 2016 @author: User """ import scipy #here is the class definition for fitting funtion class FittingFunction(object): """wrapper for a python fitting function. adds the optional guess functions, verbal description and allows """ def __init__(self, fittingFunction, guessFunction=None,desc=None,prettyEquationString=None): self.fittingFunction = fittingFunction self.guessFunction = guessFunction self.desc = desc self.prettyEquationString = prettyEquationString ####### #DEFINE FITTING FUNCTIONS AND GUESS FUNCTIONS ####### #standard fitting functions ################################################## def linear(x,m,c): return m*x+c def linear_guess(xs,ys): return {"m":(ys.max()-ys.min())/(xs.max()-xs.min()), "c":scipy.average(ys)} ################################################## def quadratic(x,a,b,c): return a*x**2+b*x+c ################################################## def gaussian(x,A, sigma, x0, B): return A*scipy.exp( -(x-x0)**2. / (2.*sigma**2. ) )+B def gaussian_guess(xs,ys): A=ys.max()-ys.min() B=ys.min() #x0 = (xs.max()+xs.min())/2.0 maximumIndex = scipy.argmax(A) x0 = xs[maximumIndex] sigma = (xs.max()-x0)/2.0 return {"A":A,"B":B,"x0":x0,"sigma":sigma} ################################################## def lorentzian(x,x0,gamma,A,B): return A*gamma**2 / ((x-x0)**2+gamma**2)+B def lorentzian_guess(xs,ys): A=ys.max()-ys.min() B=ys.min() #x0 = (xs.max()+xs.min())/2.0 maximumIndex = scipy.argmax(A) x0 = xs[maximumIndex] sigma = (xs.max()-x0)/2.0 return {"A":A,"B":B,"x0":x0,"sigma":sigma} ################################################## def parabola(x,x0,a,B): return a*(x-x0)**2+B def parabola_guess(xs,ys): return {"a":1, "B":scipy.average(ys),"x0":(xs.max()+xs.min())/2.0} ################################################## def exponentialDecay(x,A,tau,B): return A*scipy.exp(-x/tau)+B def exponentialDecay_guess(xs,ys): A=ys.max()-ys.min() B=ys.min() tau = (xs.max()+xs.min())/2.0 return {"A":A,"B":B,"tau":tau} ################################################## def sineWave(x, f, phi, A,B): return A*scipy.sin(2*scipy.pi*f*x+phi)+B def sineWave_guess(xs,ys): A=ys.max()-ys.min() B=ys.min() phi = 0.001 f = 1.0/(xs.max()-xs.min()) return {"A":A,"B":B,"phi":phi,"f":f} ################################################## def sineWaveDecay1(x, f, phi, A,B, tau): return A*scipy.exp(-x/tau)*scipy.sin(2*scipy.pi*f*x+phi)+B def sineWaveDecay1_guess(xs,ys): A=ys.max()-ys.min() B=ys.min() phi = 0.001 f = 1.0/(xs.max()-xs.min()) tau = (xs.max()+xs.min())/2.0 return {"A":A,"B":B,"phi":phi,"f":f, "tau":tau} ################################################## def sineWaveDecay2(x, f, phi, A,B, tau): return A*scipy.exp(-x/tau)*scipy.sin(2*scipy.pi*((f**2-(1/(2*scipy.pi*tau))**2)**0.5)*x+phi)+B def sineWaveDecay2_guess(xs,ys): A=ys.max()-ys.min() B=ys.min() phi = 0.001 f = 1.0/(xs.max()-xs.min()) tau = (xs.max()+xs.min())/2.0 return {"A":A,"B":B,"phi":phi,"f":f, "tau":tau} ################################################## def sincSquared(x,A,B,tau,x0): return A*(scipy.sinc(tau * 2*scipy.pi * (x-x0) ))**2 / (2*scipy.pi) + B ################################################## def sineSquared(x, f, phi, A, B): return A*scipy.sin(2*scipy.pi*f*x+phi)**2+B def sineSquared_guess(xs,ys): A=ys.max()-ys.min() B=ys.min() phi = 0.001 f = 1.0/(xs.max()-xs.min()) return {"A":A,"B":B,"phi":phi,"f":f} ################################################## def sineSquaredDecay(x, f, phi, A, B, tau): return A*scipy.exp(-x/tau)*scipy.sin(2*scipy.pi*f*(x+phi)/2.0)**2+B def sineSquaredDecay_guess(xs,ys): A=ys.max()-ys.min() B=ys.min() phi = 0.001 f = 1.0/(xs.max()-xs.min()) tau = (xs.max()+xs.min())/2.0 return {"A":A,"B":B,"phi":phi,"f":f, "tau":tau} ##################################################
[ "Martin.Link90@gmail.com" ]
Martin.Link90@gmail.com
9f6a4b3cea3a4768b3ed119ba3461165975946c9
15e4ea46e2b1944add82746c4b3369184550af1b
/9 Strings/Excersises/21.py
e82a496856e05d43914ebf743eed1cf243c8a9bb
[]
no_license
eduardogomezvidela/Summer-Intro
53204a61b05066d8b8bc1ef234e83e15f823934d
649a85b71a7e76eade3665554b03ca65108c648b
refs/heads/master
2021-04-29T13:34:26.873513
2018-02-16T13:35:48
2018-02-16T13:35:48
121,754,165
0
0
null
null
null
null
UTF-8
Python
false
false
824
py
#Caesar's Cipher message = "Hello World" #uryyb jbeyq encrypted_message = '' for char in message: o_char = char char = ord(char) if char + 13 < 122 and char + 13 > 104: #lowercase letters char = (char) +13 encrypted_message = encrypted_message + chr(char) elif (char) + 13 > 122: char = 96 + char + 13 - 122 encrypted_message = encrypted_message + chr(char) elif char + 13 < 90 and char + 13 > 64: #uppercase letters char = (char) +13 encrypted_message = encrypted_message + chr(char) elif (char) + 13 > 90: char = 64 + char + 13 - 90 encrypted_message = encrypted_message + chr(char) else: encrypted_message = encrypted_message + o_char #spaces and grammar print(encrypted_message)
[ "eduardogomezvidela@gmail.com" ]
eduardogomezvidela@gmail.com
b5870f9d11d9067baf5434f119b2c389ae719b51
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/nouns/_asia.py
1cdcd711f60b6da65ba29fce4d6bf8d63cc4eef0
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
385
py
#calss header class _ASIA(): def __init__(self,): self.name = "ASIA" self.definitions = [u'the continent that is to the east of Europe, the west of the Pacific Ocean, and the north of the Indian Ocean'] self.parents = [] self.childen = [] self.properties = [] self.jsondata = {} self.specie = 'nouns' def run(self, obj1 = [], obj2 = []): return self.jsondata
[ "xingwang1991@gmail.com" ]
xingwang1991@gmail.com
5e1ef1d6823ccae17da98b6f30009066aabdf8fc
01abb5fe2d6a51e8ee4330eaead043f4f9aad99d
/Repo_Files/Zips/plugin.video.streamhub/resources/lib/ssources/dizigold.py
2cd5ccfebc47753666aeae3c3f62630f4fe00744
[]
no_license
MrAnhell/StreamHub
01bb97bd3ae385205f3c1ac6c0c883d70dd20b9f
e70f384abf23c83001152eae87c6897f2d3aef99
refs/heads/master
2021-01-18T23:25:48.119585
2017-09-06T12:39:41
2017-09-06T12:39:41
87,110,979
0
0
null
2017-04-03T19:09:49
2017-04-03T19:09:49
null
UTF-8
Python
false
false
4,323
py
# -*- coding: utf-8 -*- ''' Exodus Add-on Copyright (C) 2016 Exodus This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import re,urlparse from resources.lib.smodules import cleantitle from resources.lib.smodules import client from resources.lib.smodules import cache from resources.lib.smodules import directstream class source: def __init__(self): self.priority = 1 self.language = ['en'] self.domains = ['dizigold.net', 'dizigold.org'] self.base_link = 'http://www.dizigold.org' self.player_link = 'http://player.dizigold.org/?id=%s&s=1&dil=or' def tvshow(self, imdb, tvdb, tvshowtitle, year): try: result = cache.get(self.dizigold_tvcache, 120) tvshowtitle = cleantitle.get(tvshowtitle) result = [i[0] for i in result if tvshowtitle == i[1]][0] url = urlparse.urljoin(self.base_link, result) url = urlparse.urlparse(url).path url = client.replaceHTMLCodes(url) url = url.encode('utf-8') return url except: return def dizigold_tvcache(self): try: result = client.request(self.base_link) result = client.parseDOM(result, 'div', attrs = {'class': 'dizis'})[0] result = re.compile('href="(.+?)">(.+?)<').findall(result) result = [(re.sub('http.+?//.+?/','/', i[0]), re.sub('&#\d*;','', i[1])) for i in result] result = [(i[0], cleantitle.get(i[1])) for i in result] return result except: return def episode(self, url, imdb, tvdb, title, premiered, season, episode): if url == None: return url = '/%s/%01d-sezon/%01d-bolum' % (url.replace('/', ''), int(season), int(episode)) url = client.replaceHTMLCodes(url) url = url.encode('utf-8') return url def sources(self, url, hostDict, hostprDict): try: sources = [] if url == None: return sources url = urlparse.urljoin(self.base_link, url) result = client.request(url) result = re.compile('var\s*view_id\s*=\s*"(\d*)"').findall(result)[0] query = self.player_link % result result = client.request(query, headers={'Referer': url}) try: url = client.parseDOM(result, 'iframe', ret='src')[-1] if 'openload' in url: host = 'openload.co' ; direct = False ; url = [{'url': url, 'quality': 'HD'}] elif 'ok.ru' in url: host = 'vk' ; direct = True ; url = directstream.odnoklassniki(url) elif 'vk.com' in url: host = 'vk' ; direct = True ; url = directstream.vk(url) else: raise Exception() for i in url: sources.append({'source': host, 'quality': i['quality'], 'language': 'en', 'url': i['url'], 'direct': direct, 'debridonly': False}) except: pass try: url = re.compile('"?file"?\s*:\s*"([^"]+)"\s*,\s*"?label"?\s*:\s*"(\d+)p?"').findall(result) links = [(i[0], '1080p') for i in url if int(i[1]) >= 1080] links += [(i[0], 'HD') for i in url if 720 <= int(i[1]) < 1080] links += [(i[0], 'SD') for i in url if 480 <= int(i[1]) < 720] for i in links: sources.append({'source': 'gvideo', 'quality': i[1], 'language': 'en', 'url': i[0], 'direct': True, 'debridonly': False}) except: pass return sources except: return sources def resolve(self, url): return url
[ "mediahubiptv@gmail.com" ]
mediahubiptv@gmail.com
ec3bb5480e949b6d5afe23cab0f0ff0f2bc524ae
62b75c03509dcd993a28eba2bb7004ae5f427f73
/astropy/vo/validator/setup_package.py
aceae1de0abb38b79a066bd58d1ede6767e1a321
[]
permissive
xiaomi1122/astropy
08aba5592d9bb54e725708352e34db89af2ec289
8876e902f5efa02a3fc27d82fe15c16001d4df5e
refs/heads/master
2020-04-09T12:27:36.768462
2018-12-06T01:11:23
2018-12-06T01:11:23
160,299,140
0
0
BSD-3-Clause
2018-12-04T04:52:22
2018-12-04T04:52:22
null
UTF-8
Python
false
false
273
py
# Licensed under a 3-clause BSD style license - see LICENSE.rst def get_package_data(): return { 'astropy.vo.validator': ['data/*.txt'], 'astropy.vo.validator.tests': ['data/*.json', 'data/*.xml', 'data/*.out']}
[ "lim@stsci.edu" ]
lim@stsci.edu
2754b656690e5da0db18e71746cd1661d2f373c1
9790af3da573b4fd28910ec23da9d877dbddc5e5
/.history/trang_thai_dau_20210906145049.py
af50a67a1a7d0f670f5deafea2e69773d60efe7e
[]
no_license
KhanhNguyen1308/THIET_BI_CANH_BAO-BUON_NGU
3e9f16252d21ff0406e7dba44033320542e80b10
88f1e8d037125e403b02ffe4ec0e838447aec7bb
refs/heads/main
2023-07-16T04:48:36.453245
2021-09-06T13:29:34
2021-09-06T13:29:34
403,448,230
0
0
null
null
null
null
UTF-8
Python
false
false
4,867
py
def trang_thai_dau(thuoc, mui_ten, gd, R, goc_chinh, goc_nghieng): if thuoc: if (gd[1]+R/2)<=mui_ten[1]: trang_thai = 'Cui' mode = 1 elif mui_ten[1] <= (gd[1]-R/2): trang_thai = 'Ngang' mode = 8 else: if -20 <= goc_nghieng <= 20: trang_thai = 'Thang' mode = 0 elif goc_nghieng < -20: trang_thai = 'Nghieng phai' mode = 2 else: trang_thai = 'Nghieng trai' mode = 3 else: if mui_ten[0] <= gd[0] and mui_ten[1] <= gd[1]: if goc_chinh <= 45: trang_thai = 'Nhin phai' mode = 6 else: trang_thai = 'Ngang' mode = 8 elif mui_ten[0] > gd[0] and mui_ten[1] <= gd[1]: if goc_chinh <= 45: trang_thai = 'Nhin trai' mode = 7 else: trang_thai = 'Ngang' mode = 8 elif mui_ten[0] <= gd[0] and mui_ten[1] > gd[1]: if -45 <= goc_chinh <= -20: trang_thai = 'Cui phai' mode = 4 elif goc_chinh > -20: trang_thai = 'Nhin phai' mode = 6 else: trang_thai = 'Cui' mode = 1 elif mui_ten[0] > gd[0] and mui_ten[1] > gd[1]: if 20 <= goc_chinh <= 45: trang_thai = 'Cui trai' mode = 5 elif goc_chinh < 20: trang_thai = 'Nhin trai' mode = 7 else: trang_thai = 'Cui' mode = 1 trang_thai_trc = trang_thai return trang_thai, mode, trang_thai_trc def trang_thai_mat(ty_le_mat, ty_le_mat_phai, ty_le_mat_trai, dem, mode, canh_bao, trang_thai_trc): if mode == 0: if ty_le_mat <= 0.25: trang_thai = 'Nham' dem += 1 if dem >= 20: canh_bao = True else: trang_thai = 'Mo' dem = 0 canh_bao = False elif mode == 1: if ty_le_mat <= 0.3: trang_thai = 'Nham' dem += 1 if dem >= 20: canh_bao = True else: trang_thai = 'Mo' dem = 0 canh_bao = False elif mode == 2: if ty_le_mat <= 0.28: trang_thai = 'Nham' dem += 1 if dem >= 20: larm = True else: trang_thai = 'Mo' dem = 0 canh_bao = False elif mode == 3: if ty_le_mat <= 0.28: trang_thai = 'Nham' dem += 1 if dem >= 20: canh_bao = True else: trang_thai = 'Mo' dem = 0 canh_bao = False elif mode == 4: if ty_le_mat_trai <= 0.28: trang_thai = 'Nham' dem += 1 if dem >= 20: canh_bao = True else: trang_thai = 'Mo' dem = 0 canh_bao = False elif mode == 5: if ty_le_mat_phai <= 0.28: trang_thai = 'Nham' dem += 1 if dem >= 20: canh_bao = True else: trang_thai = 'Mo' dem = 0 canh_bao = False elif mode == 6: if ty_le_mat_trai <= 0.28: trang_thai = 'Nham' dem += 1 if dem >= 20: canh_bao = True else: trang_thai = 'Mo' dem = 0 canh_bao = False elif mode == 7: if ty_le_mat_phai <= 0.28: trang_thai = 'Nham' dem += 1 if dem >= 20: canh_bao = True else: trang_thai = 'Mo' dem = 0 canh_bao = False elif mode == 8: if ty_le_mat <= 0.20: trang_thai = 'Nham' dem += 1 if dem >= 20: canh_bao = True else: trang_thai = 'Mo' dem = 0 canh_bao = False trang_thai_trc = trang_thai return trang_thai, trang_thai_trc, dem, canh_bao def gat_dau(trang_thai_trc, mode, dem, gat_num, trang_thai, canh_bao): if (trang_thai_trc == 0 or trang_thai_trc == 1) and mode == 0 and trang_thai == "Mo": trang_thai_trc == mode gat_num = 0 canh_bao = False if mode == 1 and trang_thai_trc == 0: if trang_thai == "Nham": dem += 1 trang_thai_trc = mode if mode == 0 and trang_thai_trc == 1: if dem <= 10 and dem != 0: gat_num = 1 dem = 0 canh_bao = True return gat_num, dem, trang_thai_trc, canh_bao
[ "khanhnguyenduy1308@gmail.com" ]
khanhnguyenduy1308@gmail.com
d4d4a6a0e44650a41c9924497d399ebb3be68541
913c018e5300ee601cacf0cb0efbe9341e00bbe9
/slides/slide-22.py
f804b444a6c5e1075fc8cd7a652bd8949251e1d5
[ "Unlicense" ]
permissive
a-abir/visionProcessingCV
8eeacad7598b25d50bf9af121c6a45b13c3079e9
0ed73c8205684abbe80c660e3d59b2d8d9f310f7
refs/heads/master
2020-04-13T03:06:26.503007
2019-11-09T16:12:58
2019-11-09T16:12:58
162,921,857
1
0
null
null
null
null
UTF-8
Python
false
false
3,311
py
import cv2 import numpy as np # Create an instance of camera 0 cap = cv2.VideoCapture(0) win = 'Result' nothing = lambda *args, **kwargs: None # create window with name win cv2.namedWindow(win, cv2.WINDOW_AUTOSIZE) # create trackbars cv2.createTrackbar('Hue Low', win, 27, 179, nothing) cv2.createTrackbar('Hue High', win, 40, 179, nothing) cv2.createTrackbar('Saturation Low', win, 100, 255, nothing) cv2.createTrackbar('Saturation High', win, 255, 255, nothing) cv2.createTrackbar('Value Low', win, 100, 255, nothing) cv2.createTrackbar('Value High', win, 255, 255, nothing) cv2.createTrackbar('Blur', win, 30, 100, nothing) x, y, radius = 0, 0, 0 while True: # Get the image from camera 0 _, image = cap.read() image = cv2.resize(image, (int(image.shape[1]//2), int(image.shape[0]//2))) # show image under window cv2.imshow("Raw Camera Data", image) result = cv2.cvtColor( image, cv2.COLOR_BGR2HSV ) # get values from trackbars HueLow = cv2.getTrackbarPos('Hue Low', win) HueHigh = cv2.getTrackbarPos('Hue High', win) SatLow = cv2.getTrackbarPos('Saturation Low', win) SatHigh = cv2.getTrackbarPos('Saturation High', win) ValLow = cv2.getTrackbarPos('Value Low', win) ValHigh = cv2.getTrackbarPos('Value High', win) Blur = cv2.getTrackbarPos('Blur', win) Blur = Blur if Blur % 2 == 1 else Blur + 1 # Literal values HSV_LOW = np.array([HueLow, SatLow, ValLow]) HSV_HIGH = np.array([HueHigh, SatHigh, ValHigh]) # Filter values with mask mask = cv2.inRange(result, HSV_LOW, HSV_HIGH) result = cv2.bitwise_and( result, result, mask=mask ) # Convert result to BGR then to GRAY result = cv2.cvtColor( result, cv2.COLOR_HSV2BGR ) # create morph kernel morphkernel = np.ones((1, 1), np.uint8) # removes specs result = cv2.morphologyEx( result, cv2.MORPH_OPEN, morphkernel ) # removes holes result = cv2.morphologyEx( result, cv2.MORPH_CLOSE, morphkernel ) result = cv2.GaussianBlur( result, (Blur, Blur), 0 ) # find irregular shapes using mask contours = cv2.findContours( mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE )[1] # if there is one or more contours if len(contours) > 0: # get shape with max area contour = max(contours, key=cv2.contourArea) # if that area is large enough if cv2.contourArea(contour) > 100: # get the centroid of object (x, y), radius = cv2.minEnclosingCircle(contour) center = (int(x), int(y)) radius = int(radius) # Draw Contour cv2.drawContours( result, [contour], -10, (0, 0, 255), 4 ) # Draw centroid cv2.circle(result, center, 10, (255, 0, 0), 20) cv2.circle(result, center, radius, (0, 255, 0), 4) if radius > 100: print("({}, {}), radius: {}".format(int(x), int(y), int(radius))) # result image under window cv2.imshow(win, result) # press 'q' key to break if cv2.waitKey(1) & 0xFF == ord("q"): break # stop cv2.destroyAllWindows()
[ "adam.mcdaniel17@gmail.com" ]
adam.mcdaniel17@gmail.com
ee993c51f2f4967c8388c89fad243c02b404fb0d
b73104aaee20ca8176bb5b3a85bdad191316793b
/terra_geocrud/migrations/0060_auto_20210122_1132.py
c630746e3bba1a93f2be87c42be33945c6a5d21c
[]
no_license
Terralego/django-terra-geocrud
d28b298d91fef9e0695240beac8dd04e825ea947
da1e4ffb40220e4a8e76e1ceb75892224869fe53
refs/heads/master
2022-07-07T07:15:03.420853
2022-06-30T15:56:15
2022-06-30T15:56:15
198,394,781
4
1
null
2022-06-30T15:49:17
2019-07-23T09:10:50
Python
UTF-8
Python
false
false
1,995
py
# Generated by Django 3.1.5 on 2021-01-22 11:32 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('geostore', '0044_auto_20201106_1638'), ('terra_geocrud', '0059_auto_20201022_0930'), ] operations = [ migrations.CreateModel( name='RoutingSettings', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('label', models.CharField(help_text='Label that will be shown on the list', max_length=250)), ('provider', models.CharField(choices=[('mapbox', 'Mapbox'), ('geostore', 'Geostore')], help_text="Provider's name", max_length=250)), ('mapbox_transit', models.CharField(blank=True, choices=[('driving', 'Driving'), ('walking', 'Walking'), ('cycling', 'Cycling')], help_text='Mabox transit', max_length=250)), ('crud_view', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='routing_settings', to='terra_geocrud.crudview')), ('layer', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='routing_settings', to='geostore.layer')), ], ), migrations.AddConstraint( model_name='routingsettings', constraint=models.UniqueConstraint(condition=models.Q(layer__isnull=False), fields=('provider', 'layer'), name='check_provider_layer'), ), migrations.AddConstraint( model_name='routingsettings', constraint=models.UniqueConstraint(condition=models.Q(_negated=True, mapbox_transit=''), fields=('provider', 'mapbox_transit'), name='check_provider_mapbox_transit'), ), migrations.AlterUniqueTogether( name='routingsettings', unique_together={('label', 'crud_view'), ('layer', 'crud_view')}, ), ]
[ "timothee.de_montety@isen.yncrea.fr" ]
timothee.de_montety@isen.yncrea.fr
0c08f0bf76cb7425cd21e1b839311f1a6f18fac6
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02715/s648085853.py
1690b0179ea73214c86aabcff11e11b6d66648e5
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
451
py
MOD = 10**9 + 7 def mod_pow(p, q): res = 1 while q > 0: if q & 1: res = (res * p) % MOD q //= 2 p = (p * p) % MOD return res def solve(n, k): dp = [0] * (k+1) ans = 0 for x in range(k, 0, -1): dp[x] = mod_pow((k // x), n) - sum(dp[y] for y in range(2*x, k+1, x)) dp[x] %= MOD ans += dp[x] * x return ans % MOD n, k = map(int, input().split()) print(solve(n, k))
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
cc1acebbeb60903b4eecac542d49dafb365417e2
5e6b385cf34605e9fd606cf8ca70171120c9a789
/urls.py
8af044f6507623d51f011b4dbd431366bf082d09
[]
no_license
jeffedlund/astrokit
6a8a361ba508a630fb0d0e29bbd389a9fe931650
bae69b88f6bf2b6cd4a307a1fd7342613eb1981e
refs/heads/master
2020-07-10T11:18:59.539234
2016-06-26T22:51:44
2016-06-26T22:51:44
null
0
0
null
null
null
null
UTF-8
Python
false
false
865
py
"""astrokit URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^s3upload/', include('s3direct.urls')), url(r'^', include('imageflow.urls')), ]
[ "ianw_git@ianww.com" ]
ianw_git@ianww.com
f2fd460bcc1d9881b286527a314b6aa57eb2f47c
f023692f73992354a0b7823d9c49ae730c95ab52
/AtCoderBeginnerContest/2XX/250/A.py
16a0a7a5857fb59f580771bb332e93d03882271f
[]
no_license
corutopi/AtCorder_python
a959e733f9a3549fab7162023e414ac2c99c4abe
a2c78cc647076071549e354c398155a65d5e331a
refs/heads/master
2023-08-31T09:40:35.929155
2023-08-20T06:19:35
2023-08-20T06:19:35
197,030,129
1
0
null
2022-06-22T04:06:28
2019-07-15T15:57:34
Python
UTF-8
Python
false
false
743
py
# import sys # sys.setrecursionlimit(10 ** 6) # # for pypy # import pypyjit # pypyjit.set_param('max_unroll_recursion=-1') # import bisect # from collections import deque # import string from math import ceil, floor inf = float('inf') mod = 10 ** 9 + 7 mod2 = 998244353 # from decorator import stop_watch # # # @stop_watch def solve(H,W,R,C): print((0 if H == 1 else 2 if 1 < R < H else 1) + (0 if W == 1 else 2 if 1 < C < W else 1)) if __name__ == '__main__': H, W = map(int, input().split()) R, C = map(int, input().split()) solve(H,W,R,C) # # test # from random import randint # import string # import tool.testcase as tt # from tool.testcase import random_str, random_ints # solve()
[ "39874652+corutopi@users.noreply.github.com" ]
39874652+corutopi@users.noreply.github.com
170d4bc8e9ff5699921eb404d75bb4f01be51dd0
be651253d2aabbf2f5481bbb9f806d85de3c87b8
/3.0 Attributes and Methods - Lab/03. Calculator.py
9fd25a160da08ad67f086b7201b1cf06a74e0177
[]
no_license
byAbaddon/OOP-Course-PYTHON-May-2020
49eed98885e610a9aa4f74cc13fee43c78a64ce3
ee8bdeef9ff15733d11127af45397b723d123a7a
refs/heads/main
2023-06-24T01:40:10.272556
2021-07-25T00:42:16
2021-07-25T00:42:16
381,504,139
0
0
null
null
null
null
UTF-8
Python
false
false
395
py
from functools import reduce class Calculator: @staticmethod def add(*args): return sum(list(args)) @staticmethod def multiply(*args): return reduce(lambda a, x: a * x, args) @staticmethod def divide(*args): return reduce(lambda a, x: a / x, args) @staticmethod def subtract(*args): return reduce(lambda a, x: a - x, args)
[ "noreply@github.com" ]
byAbaddon.noreply@github.com
3017088eeb0b53c19b693decc4dee0679ff5350b
5ff73a257eed74de87c0279c69552c19420fcc7d
/venv/bin/restauth-user.py
51addc518270df04d9c412d7b8681ce194d830b0
[]
no_license
GanapathiAmbore/api_auth_pro
9109f4fbd50ae0225875daa3f82418b7c9aa5381
d98e3cf1cade4c9b461fe298f94bdc38625c06aa
refs/heads/master
2022-06-13T08:31:49.728775
2019-07-16T05:16:37
2019-07-16T05:16:37
196,578,277
0
0
null
2022-04-22T21:55:26
2019-07-12T12:47:44
Python
UTF-8
Python
false
false
4,492
py
#!/home/ganapathi/PycharmProjects/authpro/venv/bin/python # -*- coding: utf-8 -*- # # This file is part of RestAuth (https://restauth.net). # # RestAuth is free software: you can redistribute it and/or modify it under the terms of the GNU # General Public License as published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # RestAuth is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License along with RestAuth. If not, # see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals import os import sys import getpass from pkg_resources import DistributionNotFound from pkg_resources import Requirement from pkg_resources import resource_filename # Setup environment os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'RestAuth.settings') sys.path.append(os.getcwd()) try: req = Requirement.parse("RestAuth") path = resource_filename(req, 'RestAuth') if os.path.exists(path): # pragma: no cover sys.path.insert(0, path) except DistributionNotFound: pass # we're run in a not-installed environment try: from django.utils import six from Services.models import Service from Users.cli.parsers import parser from backends import user_backend from backends import property_backend from backends import group_backend from common.errors import UserExists except ImportError as e: # pragma: no cover sys.stderr.write( 'Error: Cannot import RestAuth. Please make sure RestAuth is in your PYTHONPATH.\n') sys.exit(1) def main(args=None): # parse arguments args = parser.parse_args(args=args) if args.action == 'add': password = args.get_password(args) if args.password_generated: print(args.pwd) user_backend.set_password(args.user.username, password) elif args.action in ['ls', 'list']: for username in sorted(user_backend.list()): if six.PY3: # pragma: py3 print(username) else: # pragma: py2 print(username.encode('utf-8')) elif args.action == 'verify': if not args.pwd: # pragma: no cover args.pwd = getpass.getpass('password: ') if user_backend.check_password(args.user.username, args.pwd): print('Ok.') else: print('Failed.') sys.exit(1) elif args.action == 'set-password': password = args.get_password(args) if args.password_generated: print(args.pwd) user_backend.set_password(args.user.username, args.pwd) elif args.action == 'view': props = property_backend.list(args.user) if 'date joined' in props: print('Joined: %s' % props['date joined']) if 'last login' in props: print('Last login: %s' % props['last login']) if args.service: groups = group_backend.list(service=args.service, user=args.user) if groups: print('Groups: %s' % ', '.join(sorted(groups))) else: print('No groups.') else: groups = {} none_groups = group_backend.list(service=None, user=args.user) for service in Service.objects.all(): subgroups = group_backend.list(service=service, user=args.user) if subgroups: groups[service.username] = subgroups if groups or none_groups: print('Groups:') if none_groups: print('* no service: %s' % ', '.join(sorted(none_groups))) for service, groups in sorted(groups.items(), key=lambda t: t[0]): print('* %s: %s' % (service, ', '.join(sorted(groups)))) else: print('No groups.') elif args.action == 'rename': try: user_backend.rename(args.user.username, args.name) except UserExists as e: parser.error("%s: %s" % (args.name if six.PY3 else args.name.decode('utf-8'), e)) elif args.action in ['delete', 'rm', 'remove']: # pragma: no branch user_backend.remove(args.user.username) if __name__ == '__main__': # pragma: no cover main()
[ "ganapathiambore@gmail.com" ]
ganapathiambore@gmail.com
11c17b259d3788d26583fa112d9f1480f7a7ddc9
c16ea32a4cddb6b63ad3bacce3c6db0259d2bacd
/google/ads/googleads/v6/googleads-py/google/ads/googleads/v6/services/services/keyword_plan_campaign_service/transports/base.py
f3002492db3249e0f4e6c4c79ceb128094274fca
[ "Apache-2.0" ]
permissive
dizcology/googleapis-gen
74a72b655fba2565233e5a289cfaea6dc7b91e1a
478f36572d7bcf1dc66038d0e76b9b3fa2abae63
refs/heads/master
2023-06-04T15:51:18.380826
2021-06-16T20:42:38
2021-06-16T20:42:38
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,311
py
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # 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 abc import typing import pkg_resources import google.auth # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.ads.googleads.v6.resources.types import keyword_plan_campaign from google.ads.googleads.v6.services.types import keyword_plan_campaign_service try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( 'google-ads-googleads', ).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() class KeywordPlanCampaignServiceTransport(metaclass=abc.ABCMeta): """Abstract transport class for KeywordPlanCampaignService.""" AUTH_SCOPES = ( 'https://www.googleapis.com/auth/adwords', ) def __init__( self, *, host: str = 'googleads.googleapis.com', credentials: ga_credentials.Credentials = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ':' not in host: host += ':443' self._host = host # If no credentials are provided, then determine the appropriate # defaults. if credentials is None: credentials, _ = google.auth.default(scopes=self.AUTH_SCOPES) # Save the credentials. self._credentials = credentials # Lifted into its own function so it can be stubbed out during tests. self._prep_wrapped_messages(client_info) def _prep_wrapped_messages(self, client_info): # Precomputed wrapped methods self._wrapped_methods = { self.get_keyword_plan_campaign: gapic_v1.method.wrap_method( self.get_keyword_plan_campaign, default_timeout=None, client_info=client_info, ), self.mutate_keyword_plan_campaigns: gapic_v1.method.wrap_method( self.mutate_keyword_plan_campaigns, default_timeout=None, client_info=client_info, ), } @property def get_keyword_plan_campaign(self) -> typing.Callable[ [keyword_plan_campaign_service.GetKeywordPlanCampaignRequest], keyword_plan_campaign.KeywordPlanCampaign]: raise NotImplementedError @property def mutate_keyword_plan_campaigns(self) -> typing.Callable[ [keyword_plan_campaign_service.MutateKeywordPlanCampaignsRequest], keyword_plan_campaign_service.MutateKeywordPlanCampaignsResponse]: raise NotImplementedError __all__ = ( 'KeywordPlanCampaignServiceTransport', )
[ "bazel-bot-development[bot]@users.noreply.github.com" ]
bazel-bot-development[bot]@users.noreply.github.com
13aae462a5aafa015fb82c45d2a91d4661c6d84d
3312b5066954cbf96c79ef3e1f3d582b31ebc5ae
/colegend/academy/admin.py
33500be58723d3916ead15c076b6f986af5748b9
[]
no_license
Eraldo/colegend
d3f3c2c37f3bade7a3a1e10d307d49db225fe7f5
2e7b9d27887d7663b8d0d1930c2397c98e9fa1fc
refs/heads/master
2021-01-16T23:32:09.245967
2020-10-07T12:12:14
2020-10-07T12:12:14
21,119,074
4
2
null
null
null
null
UTF-8
Python
false
false
1,173
py
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from .models import Book, BookReview, BookTag class TaggedBookInline(admin.TabularInline): verbose_name = _('tagged book') verbose_name_plural = _('tagged books') model = Book.tags.through extra = 0 show_change_link = True class BookReviewInline(admin.TabularInline): fields = ['owner', 'rating', 'area_1', 'area_2', 'area_3', 'area_4', 'area_5', 'area_6', 'area_7'] model = BookReview extra = 0 show_change_link = True @admin.register(BookTag) class BookTagAdmin(admin.ModelAdmin): inlines = [TaggedBookInline] @admin.register(Book) class BookAdmin(admin.ModelAdmin): list_display = ['name', 'author', 'rating', 'public', 'featured'] list_filter = ['public', 'featured', 'tags'] list_editable = ['public'] filter_horizontal = ['tags'] readonly_fields = ['created'] search_fields = ['name', 'author'] inlines = [BookReviewInline] @admin.register(BookReview) class BookReviewAdmin(admin.ModelAdmin): list_display = ['book', 'owner'] list_filter = ['owner', 'book'] readonly_fields = ['created']
[ "eraldo@eraldo.org" ]
eraldo@eraldo.org
61eba779f71680917adcbb59e6fbd106e63422fa
481b7922a39c514e12087b8fde1e6595315ecaa3
/notifications/models.py
b9f022a3adbb347eea69bd15d618db4e150a04e3
[]
no_license
Zolo-2000/mape-1
3ad994b285229924f23a3a895a925b7551ba3ebd
87651ff08590ff5dd2685fa08956632493ee97c9
refs/heads/master
2021-01-19T22:21:46.884952
2017-08-31T16:23:57
2017-08-31T16:23:57
88,803,138
0
0
null
2017-04-20T00:27:07
2017-04-20T00:27:07
null
UTF-8
Python
false
false
517
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from social.models import Profile class Notification(models.Model): TYPE_CHOICES = ( (1, 'Like'), (2, 'Amistad'), (3, 'Invitacion'), ) from_profile = models.ForeignKey(Profile) to_profile = models.ForeignKey(Profile, related_name='notifications') message = models.TextField(blank=True, null=True) type = models.PositiveSmallIntegerField(choices=TYPE_CHOICES) date = models.DateTimeField(auto_now_add=True)
[ "dbsiavichay@gmail.com" ]
dbsiavichay@gmail.com
f211453dbbccbeb4172dfdc05ad63a35038e47f2
ddd7e91dae17664505ea4f9be675e125337347a2
/unused/2014/distributed/find_optimal_transformation_distributor_script.py
47787e7d5e351e7c76dd664da9c1f36153dabe6b
[]
no_license
akurnikova/MouseBrainAtlas
25c4134bae53827167e4b54ba83f215aec9f2d85
ed1b5858467febdaed0a58a1a742764d214cc38e
refs/heads/master
2021-07-15T17:17:19.881627
2019-02-22T06:00:17
2019-02-22T06:00:17
103,425,463
0
0
null
2018-04-27T19:08:02
2017-09-13T16:45:56
Jupyter Notebook
UTF-8
Python
false
false
299
py
import os import time from preprocess_utility import * t = time.time() script_root = os.environ['GORDON_REPO_DIR']+'/notebooks/' arg_tuples = [[i] for i in range(8)] run_distributed3(script_root+'/find_optimal_transformation_executable.py', arg_tuples) print 'total', time.time() - t, 'seconds'
[ "cyc3700@gmail.com" ]
cyc3700@gmail.com
2a8ef7d09dd39f175ff581175473aaecc29aa67b
c8a38e65e71de888fc5b22fbd027bbaa0f3f6ef1
/classic/MergeSort.py
e90a38bdccd7b2e70d6a29f8bfe43220a25d24fa
[]
no_license
skywhat/leetcode
e451a10cdab0026d884b8ed2b03e305b92a3ff0f
6aaf58b1e1170a994affd6330d90b89aaaf582d9
refs/heads/master
2023-03-30T15:54:27.062372
2023-03-30T06:51:20
2023-03-30T06:51:20
90,644,891
82
27
null
null
null
null
UTF-8
Python
false
false
681
py
def mergeSort(s, l, r): if l>=r: return mid = (l+r)/2 mergeSort(s, l, mid) mergeSort(s, mid+1, r) merge(s, l, mid, r) def merge(s, l, mid, r): t = [] i = l j = mid+1 while i<=mid and j<=r: if s[i] < s[j]: t.append(s[i]) i+=1 else: t.append(s[j]) j+=1 while i<=mid: t.append(s[i]) i+=1 while j<=r: t.append(s[j]) j+=1 for i, x in enumerate(t): s[l+i] = x if __name__=="__main__": s = [3,5,1,2,7,8,10,0] mergeSort(s, 0, len(s)-1) print s s = [9,8,7,6,5,4,3,2,1] mergeSort(s, 0, len(s)-1) print s
[ "gangzh@uber.com" ]
gangzh@uber.com
9b47587d53e94ef38b76436bc239d8c7de43f70f
20d8a89124008c96fa59225926ce39f113522daa
/UL_NanoAODv8/2018/step7_cfg.py
796ed2f73ea4ff4cc4240bf4fcdd4341af58cff3
[]
no_license
MiT-HEP/MCProduction
113a132a2ff440e13225be518ff8d52b0136e1eb
df019d7a15717a9eafd9502f2a310023dcd584f5
refs/heads/master
2022-05-06T20:25:34.372363
2022-04-12T11:55:15
2022-04-12T11:55:15
37,586,559
5
7
null
2015-08-24T11:13:58
2015-06-17T09:45:12
Python
UTF-8
Python
false
false
3,932
py
# Auto generated configuration file # using: # Revision: 1.19 # Source: /local/reps/CMSSW/CMSSW/Configuration/Applications/python/ConfigBuilder.py,v # with command line options: --python_filename step7_cfg.py --eventcontent NANOAODSIM --customise Configuration/DataProcessing/Utils.addMonitoring --datatier NANOAODSIM --fileout file:step7.root --conditions 106X_upgrade2018_realistic_v15_L1v1 --step NANO --filein file:step6.root --era Run2_2018,run2_nanoAOD_106Xv1 --no_exec --mc -n 500 import FWCore.ParameterSet.Config as cms from Configuration.Eras.Era_Run2_2018_cff import Run2_2018 from Configuration.Eras.Modifier_run2_nanoAOD_106Xv1_cff import run2_nanoAOD_106Xv1 process = cms.Process('NANO',Run2_2018,run2_nanoAOD_106Xv1) # import of standard configurations process.load('Configuration.StandardSequences.Services_cff') process.load('SimGeneral.HepPDTESSource.pythiapdt_cfi') process.load('FWCore.MessageService.MessageLogger_cfi') process.load('Configuration.EventContent.EventContent_cff') process.load('SimGeneral.MixingModule.mixNoPU_cfi') process.load('Configuration.StandardSequences.GeometryRecoDB_cff') process.load('Configuration.StandardSequences.MagneticField_cff') process.load('PhysicsTools.NanoAOD.nano_cff') process.load('Configuration.StandardSequences.EndOfProcess_cff') process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff') process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(500) ) # Input source process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring('file:step6.root'), secondaryFileNames = cms.untracked.vstring() ) process.options = cms.untracked.PSet( ) # Production Info process.configurationMetadata = cms.untracked.PSet( annotation = cms.untracked.string('--python_filename nevts:500'), name = cms.untracked.string('Applications'), version = cms.untracked.string('$Revision: 1.19 $') ) # Output definition process.NANOAODSIMoutput = cms.OutputModule("NanoAODOutputModule", compressionAlgorithm = cms.untracked.string('LZMA'), compressionLevel = cms.untracked.int32(9), dataset = cms.untracked.PSet( dataTier = cms.untracked.string('NANOAODSIM'), filterName = cms.untracked.string('') ), fileName = cms.untracked.string('file:step7.root'), outputCommands = process.NANOAODSIMEventContent.outputCommands ) # Additional output definition # Other statements from Configuration.AlCa.GlobalTag import GlobalTag process.GlobalTag = GlobalTag(process.GlobalTag, '106X_upgrade2018_realistic_v15_L1v1', '') # Path and EndPath definitions process.nanoAOD_step = cms.Path(process.nanoSequenceMC) process.endjob_step = cms.EndPath(process.endOfProcess) process.NANOAODSIMoutput_step = cms.EndPath(process.NANOAODSIMoutput) # Schedule definition process.schedule = cms.Schedule(process.nanoAOD_step,process.endjob_step,process.NANOAODSIMoutput_step) from PhysicsTools.PatAlgos.tools.helpers import associatePatAlgosToolsTask associatePatAlgosToolsTask(process) # customisation of the process. # Automatic addition of the customisation function from PhysicsTools.NanoAOD.nano_cff from PhysicsTools.NanoAOD.nano_cff import nanoAOD_customizeMC #call to customisation function nanoAOD_customizeMC imported from PhysicsTools.NanoAOD.nano_cff process = nanoAOD_customizeMC(process) # Automatic addition of the customisation function from Configuration.DataProcessing.Utils from Configuration.DataProcessing.Utils import addMonitoring #call to customisation function addMonitoring imported from Configuration.DataProcessing.Utils process = addMonitoring(process) # End of customisation functions # Customisation from command line # Add early deletion of temporary data products to reduce peak memory need from Configuration.StandardSequences.earlyDeleteSettings_cff import customiseEarlyDelete process = customiseEarlyDelete(process) # End adding early deletion
[ "andrea.marini@cern.ch" ]
andrea.marini@cern.ch
ed568aebf7ccfb7ab927a70bb4f56f29f3aadebe
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2908/61519/270339.py
01ee9a6039d0bea096c53e730e0059e37ea1e6bc
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
252
py
n=int(input()) a=[] b=[] for i in range(n): s=input() a.append(s) for i in range(len(a)): tem=list(a[i]) tem.sort() a[i]="".join(tem) b.append(a[0]) for i in range(len(a)): if a[i] not in b: b.append(a[i]) print(len(b))
[ "1069583789@qq.com" ]
1069583789@qq.com
e18d08fc75cb6a5c7e65786034508a5a6dfae2fb
ad4c2aa0398406ccb7e70562560e75fa283ffa1a
/prison-cells-after-n-days/prison-cells-after-n-days.py
5f5774ff8645fab995636b2a9afdbffacd5365cd
[ "Apache-2.0" ]
permissive
kmgowda/kmg-leetcode-python
427d58f1750735618dfd51936d33240df5ba9ace
4d32e110ac33563a8bde3fd3200d5804db354d95
refs/heads/main
2023-08-22T06:59:43.141131
2021-10-16T14:04:32
2021-10-16T14:04:32
417,841,590
0
1
null
null
null
null
UTF-8
Python
false
false
663
py
// https://leetcode.com/problems/prison-cells-after-n-days class Solution(object): def prisonAfterNDays(self, cells, N): """ :type cells: List[int] :type N: int :rtype: List[int] """ cells = [-1]+ cells+[-1] N -= max(N - 1, 0) / 14 * 14 for _ in range(N): newcells = cells[:] for i in range(1, len(cells)-1): if (cells[i-1] == 0 and cells[i+1] == 0) or (cells[i-1] == 1 and cells[i+1] == 1): newcells[i] = 1 else: newcells[i] = 0 cells = newcells return cells[1:-1]
[ "keshava.gowda@gmail.com" ]
keshava.gowda@gmail.com
31a9e2a3ce29989e3919b81f3ac99a0aa1d53099
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2806/59018/240055.py
407238dcea42d1b7be172e0c494ea3bb4c414b77
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
213
py
n=int(input()) a=[] p=[] for i in range(n): m,k=input().split(' ') a.appennd(int(m)) p.append(int(k)) count=0 for j in range(n): count=count+a[i]*min(p[0:i+1]) print(count)
[ "1069583789@qq.com" ]
1069583789@qq.com
56ebe08be3499a23b065f9b952dadc0a413e0d4d
93f47ba04fc18c4e537f0a48fe6232e2a89a4d30
/examples/adspygoogle/dfp/v201408/placement_service/update_placements.py
4a5f1ecff2f2c3ac09e479873dc7a7e90ef3069a
[ "Apache-2.0" ]
permissive
jasonshih/googleads-python-legacy-lib
c56dc52a1dab28b9de461fd5db0fcd6020b84a04
510fad41ecf986fe15258af64b90f99a96dc5548
refs/heads/master
2021-04-30T22:12:12.900275
2015-03-06T15:35:21
2015-03-06T15:35:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,538
py
#!/usr/bin/python # # Copyright 2013 Google Inc. 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 code example updates a single placement to allow for AdSense targeting. To determine which placements exist, run get_all_placements.py. """ __author__ = 'Nicholas Chen' # Locate the client library. If module was installed via "setup.py" script, then # the following two lines are not needed. import os import sys sys.path.insert(0, os.path.join('..', '..', '..', '..', '..')) # Import appropriate classes from the client library. from adspygoogle import DfpClient from adspygoogle.dfp import DfpUtils PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE' def main(client, placement_id): # Initialize appropriate service. placement_service = client.GetService('PlacementService', version='v201408') # Create query. values = [{ 'key': 'placementId', 'value': { 'xsi_type': 'NumberValue', 'value': placement_id } }] query = 'WHERE id = :placementId' statement = DfpUtils.FilterStatement(query, values, 1) # Get placements by statement. placements = placement_service.GetPlacementsByStatement( statement.ToStatement())[0] for placement in placements: if not placement['targetingDescription']: placement['targetingDescription'] = 'Generic description' placement['targetingAdLocation'] = 'All images on sports pages.' placement['targetingSiteName'] = 'http://code.google.com' placement['isAdSenseTargetingEnabled'] = 'true' # Update placements remotely. placements = placement_service.UpdatePlacements(placements) for placement in placements: print ('Placement with id \'%s\', name \'%s\', and AdSense targeting ' 'enabled \'%s\' was updated.' % (placement['id'], placement['name'], placement['isAdSenseTargetingEnabled'])) if __name__ == '__main__': # Initialize client object. dfp_client = DfpClient(path=os.path.join('..', '..', '..', '..', '..')) main(dfp_client, PLACEMENT_ID)
[ "nicholaschen@google.com" ]
nicholaschen@google.com
2b7ddd09aeac0d38f1ee11ee873acf5ee1e7cb06
8a52e36a792e3d22e9ae70a6b261e5fa26195c38
/wandoujia/spiders/qianliyanSpider.py
d3c9987b193664c9bc92e33fb6e31524d66f5f03
[]
no_license
beautifulmistake/Whole-app
77d55a3ced0d43fc5c670d2e86e0e22467df2ca4
cee208bd67fdddb87f4e58ee22466d722f7adc05
refs/heads/master
2020-05-31T07:25:28.080565
2019-06-04T08:56:44
2019-06-04T08:56:44
190,165,253
0
0
null
null
null
null
UTF-8
Python
false
false
3,126
py
from urllib.parse import urljoin import scrapy from wandoujia.items import QianLiYanItem class QianLiYanSpider(scrapy.Spider): name = "QianLiYan" def start_requests(self): """ 读取文件获取初始url :return: """ with open(r'G:\工作\APP\wandoujia\urls.txt', 'r', encoding='utf-8') as f: lines = f.readlines() for url in lines[:1]: # 发起请求 yield scrapy.Request(url=url.strip()) def parse(self, response): """ 解析页面获取详情页的看链接 :param response: :return: """ # 当前的url curr_url = response.url # 获取拼接前的url base = "/".join(curr_url.split("/")[:3]) # 获取详情页的列表 detail_urls = response.xpath('//div[@id="main"]/table[@id="category_table"]/' 'tbody/tr/td[2]/div/a/@href').extract() # 下一页 is_next = response.xpath('//table[@id="category_table"]/tfoot//a[last()]/text()').extract_first() # 请求详情页 for detail_url in detail_urls: url = urljoin(base, detail_url) print("查看获取的url:", url) yield scrapy.Request(url=url, callback=self.parse_detail) if is_next == "下一页": # 获得下一页的链接 next = response.xpath('//table[@id="category_table"]/tfoot//a[last()]/@href').extract_first() yield scrapy.Request(url=urljoin(base, next), callback=self.parse) def parse_detail(self, response): """ 解析详情页 :param response: :return: """ # 创建item item = QianLiYanItem() # 搜索标题 search_title = response.xpath('//div[@id="main"]/div/article/h1/text()').extract_first() # 服务区域,------>列表 service_area = response.xpath('//div[@id="main"]/div/article/section[1]' '/ul/li[1]/descendant-or-self::text()').extract() # 联系人,------>列表 contact = response.xpath('//div[@id="main"]/div/article/section[1]' '/ul/li[2]/descendant-or-self::text()').extract() # 联系人手机(图片) image_urls = response.xpath('//div[@id="main"]/div/article/section[1]' '/ul/li[3]/span[2]/img/@src').extract_first() # 联系人QQ contact_qq = response.xpath('//div[@id="main"]/div/article/section[1]' '/ul/li[4]/descendant-or-self::text()').extract() # 联系人邮箱 contact_email = response.xpath('//div[@id="main"]/div/article/section[1]' '/ul/li[5]/descendant-or-self::text()').extract() item['search_title'] = search_title item['service_area'] = service_area item['contact'] = contact item['image_urls'] = image_urls item['contact_qq'] = contact_qq item['contact_email'] = contact_email yield item
[ "17319296359@163.com" ]
17319296359@163.com
6edb3d2cddfae5ec7c09ce1b3da816f9fdc28865
7680dbfce22b31835107403514f1489a8afcf3df
/Teoria/teoria__lista_4.py
f7bb19bdeb60df58bd01289c6834859a4cb774a9
[]
no_license
EstephanoBartenski/Aprendendo_Python
c0022d545af00c14e6778f6a80f666de31a7659e
69b4c2e07511a0bd91ac19df59aa9dafdf28fda3
refs/heads/master
2022-11-27T17:14:00.949163
2020-08-03T22:11:19
2020-08-03T22:11:19
284,564,300
0
0
null
null
null
null
UTF-8
Python
false
false
417
py
teste = list() teste.append('Gustavo') teste.append(40) print(teste) galera = list() # galera.append(teste) ISSO AQUI NÃO PODE galera.append(teste[:]) teste[0] = 'Maria' teste[1] = 22 galera.append(teste[:]) print(galera) print() pessoal = [['Joana', 33], ['Marcelo', 45], ['Otávio', 50], ['Jorge', 12], ['Bárbara', 14]] for p in pessoal: print(f'O(a) {p[0]} tem {p[1]} anos de idade.')
[ "noreply@github.com" ]
EstephanoBartenski.noreply@github.com
2cd393130f9913c27560502518c7ea7a5860ccfe
5be29c3b055a335120186de58d8d08bab6a4de7a
/KFC_server/regist_Ui.py
6b85c7875fb7e61f010a51f1cb06a8cd93a92729
[]
no_license
wangredfei/projects
aabb68f45c661db4d60dc13e34d069c4fa77e423
3dfbf4467a10e43296a6397cebbfb2e6d78e684b
refs/heads/master
2022-12-09T07:19:07.538950
2019-03-18T06:57:12
2019-03-18T06:57:12
176,221,820
0
0
null
null
null
null
UTF-8
Python
false
false
2,481
py
from PyQt5.Qt import * import os class Regist_Ui(QDialog): '''这是管理员的注册''' def newWindowUI(self, dialog): dialog.resize(300,500) self.dialog = dialog self.button() self.lineEdit() self.background_show() def button(self): self.button1 = QPushButton(self.dialog) self.button1.setGeometry(QRect(270, 10, 20, 20)) self.button1.setText("×") self.button1.clicked.connect(self.dialog.close) self.button2 = QPushButton(self.dialog) self.button2.setGeometry(QRect(110, 400,80, 20)) self.button2.setText("注册") def lineEdit(self): self.lineEdit = QLineEdit(self.dialog) self.lineEdit.setGeometry(75, 235, 150, 30) self.lineEdit.setInputMask("") self.lineEdit.setText("") self.lineEdit.setMaxLength(17) self.lineEdit.setFrame(True) self.lineEdit.setEchoMode(QLineEdit.Normal) self.lineEdit.setAlignment(Qt.AlignCenter) self.lineEdit.setDragEnabled(False) self.lineEdit.setClearButtonEnabled(False) self.lineEdit.setObjectName("lineEdit") self.lineEdit.setPlaceholderText('姓名') self.lineEdit_1 = QLineEdit(self.dialog) self.lineEdit_1.setGeometry(75, 275, 150, 30) self.lineEdit_1.setInputMask("") self.lineEdit_1.setText("") self.lineEdit_1.setMaxLength(17) self.lineEdit_1.setFrame(True) self.lineEdit_1.setEchoMode(QLineEdit.Normal) self.lineEdit_1.setAlignment(Qt.AlignCenter) self.lineEdit_1.setDragEnabled(False) self.lineEdit_1.setClearButtonEnabled(False) self.lineEdit_1.setObjectName("lineEdit") self.lineEdit_1.setPlaceholderText('手机号') self.lineEdit_2 = QLineEdit(self.dialog) self.lineEdit_2.setGeometry(75, 315, 150, 30) self.lineEdit_2.setMaxLength(17) self.lineEdit_2.setEchoMode(QLineEdit.Password) self.lineEdit_2.setAlignment(Qt.AlignCenter) self.lineEdit_2.setObjectName("lineEdit_2") self.lineEdit_2.setPlaceholderText('密码') def background_show(self): self.path= (os.path.dirname(__file__)).replace('\\','/') #添加窗口背景图片 palette1 = QPalette() palette1.setBrush(self.dialog.backgroundRole(), QBrush(QPixmap('%s/Images/regist.jpg'%self.path))) self.dialog.setPalette(palette1)
[ "1538629795@qq.com" ]
1538629795@qq.com
5eb5f1b1e17df3c5a4a386f4ebd33e63991af2cd
255e19ddc1bcde0d3d4fe70e01cec9bb724979c9
/dockerized-gists/1324501/snippet.py
1c0cb3d7b8a1a399f9b0fbe7ad92bea55209c524
[ "MIT" ]
permissive
gistable/gistable
26c1e909928ec463026811f69b61619b62f14721
665d39a2bd82543d5196555f0801ef8fd4a3ee48
refs/heads/master
2023-02-17T21:33:55.558398
2023-02-11T18:20:10
2023-02-11T18:20:10
119,861,038
76
19
null
2020-07-26T03:14:55
2018-02-01T16:19:24
Python
UTF-8
Python
false
false
5,926
py
#!/usr/bin/env python # -*- coding: UTF-8 -*- from __future__ import print_function import os, sys import struct as st import time as tm uint32 = '>I' int32 = '>i' uint16 = '>H' int16 = '>h' uint8 = 'B' int8 = 'b' #file header file_version_number_fmt = uint32 app_version_number_fmt = uint32 idtag_length_fmt = uint16 length_length_fmt = uint16 #struct record header tag_id_fmt = uint8 #=1byte file header idtag_length length_fmt = uint16 #=2bytes file header length_length #records const recdomain = 0x01 recpath = 0x02 reccookie = 0x03 #msb flags msb = 0x80 enddomain = (msb | 0x04) endpath = (msb | 0x05) #indent size doind = 0 indent = 0 def readfmt(f, fmt): size = st.calcsize(fmt) data = f.read(size) if len(data) < size: raise EOFError('in readfmt, at pos:', f.tell()) return st.unpack(fmt, data)[0] def read(f, ln): data = f.read(ln) if len(data) < ln: raise EOFError('in read, at pos:', f.tell()) return data def getfhdr(f): fhdr = {} fhdr[1] = readfmt(f, file_version_number_fmt) fhdr[2] = readfmt(f, app_version_number_fmt) fhdr[3] = readfmt(f, idtag_length_fmt) fhdr[4] = readfmt(f, length_length_fmt) return fhdr def getrecid(f): return readfmt(f, tag_id_fmt) def getrechdr(f, hdr): global doind if (msb & hdr): if enddomain == hdr: doind = -1 return True, 'end of domain record', 0 elif endpath == hdr: return True, 'end of path record', 0 else: return True, 'end of unknown record', 0, else: datalen = readfmt(f, length_fmt) if recdomain == hdr: doind = 1 return False, 'domain record', datalen elif recpath == hdr: return False, 'path record', datalen elif reccookie == hdr: return False, 'cookie record', datalen else: return False, 'unknown record', datalen def getddidname(did): flag = True if msb & did else False if 0x1e == did: name = 'name of the domain part' elif 0x1f == did: name = 'how cookies are filtered for this domain.' elif 0x21 == did: name = 'handling of cookies that have explicit paths' elif 0x25 == did: name = 'filter third party cookies mode' else: name = 'unknown domain data id' return flag, name def getpdidname(did): flag = True if msb & did else False if 0x1d == did: name = 'the name of the path part' else: name = 'unknown path data id' return flag, name def getcdidname(did): flag = True if msb & did else False if 0x10 == did: name = 'name of the cookie' elif 0x11 == did: name = 'value of the cookie' elif 0x12 == did: name = 'expiry' elif 0x13 == did: name = 'last used' elif 0x14 == did: name = 'comment/description of use' elif 0x15 == did: name = 'URL for comment/description of use' elif 0x16 == did: name = 'domain received with version=1 cookies' elif 0x17 == did: name = 'path received with version=1 cookies' elif 0x18 == did: name = 'port limitations received with version=1 cookies' elif 0x1A == did: name = 'version number of cookie' elif (0x19 | msb) == did: name = 'will only be sent to https servers' elif (0x1b | msb) == did: name = 'will only be sent to the server that sent it' elif (0x1c | msb) == did: name = 'reserved for delete protection: not yet implemented' elif (0x20 | msb) == did: name = 'will not be sent if the path is a prefix of the url' elif (0x22 | msb) == did: name = 'was set as the result of a password login form' elif (0x23 | msb) == did: name = 'was set as the result of a http authentication login' elif (0x24 | msb) == did: name = 'was set by a third party server' else: name = 'unknown cookie data id' return flag, name def printt(*args): global indent if 0 > indent: print('indent:', indent) print('\t'*indent, *args, sep='') def prsdomaindata(f, d): end = f.tell() + d[2] data = [] while f.tell() < end: did = readfmt(f, tag_id_fmt) flag, dnam = getddidname(did) if not flag: dlen = readfmt(f, length_fmt) draw = read(f, dlen) else: dlen = 0 draw = '' data.append((hex(did), dnam, dlen, draw)) printt(data) return data def prspathdata(f, d): end = f.tell() + d[2] data = [] while f.tell() < end: did = readfmt(f, tag_id_fmt) flag, dnam = getpdidname(did) if not flag: dlen = readfmt(f, length_fmt) draw = read(f, dlen) else: dlen = 0 draw = '' data.append((hex(did), dnam, dlen, draw)) printt(data) return data def frmtm(t): unp = st.unpack('>Q', t)[0] return tm.strftime('%Y-%m-%d %H:%M:%S', tm.localtime(unp)) def prscookiedata(f, d): end = f.tell() + d[2] data = [] while f.tell() < end: did = readfmt(f, tag_id_fmt) flag, dnam = getcdidname(did) if not flag: dlen = readfmt(f, length_fmt) draw = read(f, dlen) if 0x12==did or 0x13==did: draw = frmtm(draw) else: dlen = 0 draw = '' data.append((hex(did), dnam, dlen, draw)) printt(data) return data def process(f): global indent global doind f.seek(0, os.SEEK_END) fend = f.tell() f.seek(0, os.SEEK_SET) fhdr = getfhdr(f) print('file_version_number', fhdr[1]) print('app_version_number', fhdr[2]) print('idtag_length', fhdr[3]) print('length_length', fhdr[4]) if (fhdr[3] != 1) and (fhdr[4] != 2): printt('Not compatible') return while(f.tell() < fend): try: rhdr = getrecid(f) rdat = getrechdr(f, rhdr) if True == rdat[0]: indent += doind doind = 0 printt(rdat[1]) elif False == rdat[0]: printt(rdat[1]) indent += doind doind = 0 if rhdr == recdomain: prsdomaindata(f, rdat) elif rhdr == recpath: prspathdata(f, rdat) elif rhdr == reccookie: prscookiedata(f, rdat) else: printt('parse unknown record') except EOFError as e: printt('EOFError', e) input() break def main(): if len(sys.argv) == 2 and os.path.exists(sys.argv[1]): file = open(sys.argv[1], 'rb') process(file) file.close() if __name__ == '__main__': try: main() except: import traceback print('Unhandled exception:\n') traceback.print_exc() input('\nPress any key...')
[ "gistshub@gmail.com" ]
gistshub@gmail.com
6e87b1af4210c206f1bb715e1b4a99fe7d50ad0a
093b9569be9d1c4e5daf92efbebc38f680917b2d
/.history/base/models_20210828170925.py
1ae5275cea498d2f694b609a8d77a0d76c347858
[]
no_license
Justin-Panagos/todoList
95b1e97ff71af1b0be58e7f8937d726a687cea4d
10539219b59fcea00f8b19a406db3d4c3f4d289e
refs/heads/master
2023-08-04T13:27:13.309769
2021-08-29T14:06:43
2021-08-29T14:06:43
400,827,602
0
0
null
null
null
null
UTF-8
Python
false
false
246
py
from django.db import models from django.contrib.auth.models import User # Create your models here. class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = description = complete = create =
[ "justpanagos@gmail.com" ]
justpanagos@gmail.com
1cfdc64b037a1a5b23091e1f5821332e1768d22a
32712c478ff9dff44de085cb50a1302bfc2eba67
/users/migrations/0003_auto_20200409_0846.py
6d5dd5bce835963096d9c8f9075a6418cf788858
[ "MIT" ]
permissive
vas3k/vas3k.club
158af17c329fe693178ca1bce36466922604df3b
b3ff2fd95ef1d6c593c57d3bcd501240f2705fbb
refs/heads/master
2023-09-03T07:10:10.859004
2023-09-01T09:08:32
2023-09-01T09:08:32
254,190,180
697
326
MIT
2023-09-04T09:02:12
2020-04-08T20:11:44
Python
UTF-8
Python
false
false
766
py
# Generated by Django 3.0.4 on 2020-04-09 08:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0002_auto_20200408_1516'), ] operations = [ migrations.AlterModelOptions( name='tag', options={'ordering': ['group', '?']}, ), migrations.AddField( model_name='tag', name='index', field=models.IntegerField(default=0), ), migrations.AlterField( model_name='tag', name='group', field=models.CharField(choices=[('hobbies', 'Хобби'), ('personal', 'Личное'), ('other', 'Остальное')], default='other', max_length=32), ), ]
[ "me@vas3k.ru" ]
me@vas3k.ru
6d77d52b9ef9e62676c4faa6684812efe2718167
770accfc4da8988db9b91d435623bc4f0860d6e8
/src/race/scripts/keyboard.py
79399f36cd172cbb9d8930627d46e9e51bff53a5
[ "MIT" ]
permissive
mgoli-cav/Platooning-F1Tenth
82eb4f79296b4e48b27b077ab68ce5d15a9281a0
f8b929f0669cd721d861333286995b2feef2641e
refs/heads/master
2022-11-12T00:21:46.348447
2020-06-19T22:26:56
2020-06-19T22:26:56
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,158
py
#!/usr/bin/env python import rospy from race.msg import drive_param import sys, select, termios, tty pub = rospy.Publisher('drive_parameters', drive_param, queue_size=10) keyBindings = { 'w':(1,0), 'd':(1,-1), 'a':(1,1), 's':(-1,0), } def getKey(): tty.setraw(sys.stdin.fileno()) select.select([sys.stdin], [], [], 0) key = sys.stdin.read(1) termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings) return key speed = 0.5 turn = 0.25 if __name__=="__main__": settings = termios.tcgetattr(sys.stdin) rospy.init_node('keyboard', anonymous=True) x = 0 th = 0 status = 0 try: while(1): key = getKey() if key in keyBindings.keys(): x = keyBindings[key][0] th = keyBindings[key][1] else: x = 0 th = 0 if (key == '\x03'): break msg = drive_param() msg.velocity = x*speed msg.angle = th*turn pub.publish(msg) except: print 'error' finally: msg = drive_param() msg.velocity = 0 msg.angle = 0 pub.publish(msg) termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings)
[ "pmusau13ster@gmail.com" ]
pmusau13ster@gmail.com
32944cfd8beb4be9ec3e8b9a0a5c40fbcdbc8659
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2530/60785/314884.py
6203abf12fc334b23c624843c641e54b233f7d1e
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
310
py
s=list(input()) t=list(input()) indic=[] others=[] res=[] dic=dict() for i in range(len(s)): dic.update({s[i]:i}) for i in range(len(t)): if t[i] not in s: others.append(t[i]) else: indic.append(dic[t[i]]) indic.sort() #or i in range(len(indic)): #es.append() print(dic.items())
[ "1069583789@qq.com" ]
1069583789@qq.com
072d0dba6c0ca264afdf8e312adc7a46a009aedc
c83e356d265a1d294733885c373d0a4c258c2d5e
/mayan/apps/mirroring/tests/literals.py
bf6b4866cd5651e325b438c1c41fa096b2780241
[ "Apache-2.0" ]
permissive
TrellixVulnTeam/fall-2021-hw2-451-unavailable-for-legal-reasons_6YX3
4160809d2c96707a196b8c94ea9e4df1a119d96a
0e4e919fd2e1ded6711354a0330135283e87f8c7
refs/heads/master
2023-08-21T23:36:41.230179
2021-10-02T03:51:12
2021-10-02T03:51:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
651
py
# -*- coding: utf-8 -*- TEST_CACHE_KEY_BAD_CHARACTERS = ' \r\n!@#$%^&*()+_{}|:"<>?-=[];\',./' TEST_DOCUMENT_PK = 99 TEST_KEY_UNICODE = 'áéíóúüäåéë¹²³¤' TEST_KEY_UNICODE_HASH = 'ba418878794230c3f4308e66c70db31dd83f1def4d9381f379c50f42eb88989c' TEST_NODE_EXPRESSION = 'level_1' TEST_NODE_EXPRESSION_INVALID = 'level/1' TEST_NODE_EXPRESSION_MULTILINE = 'first\r\nsecond\r\nthird' TEST_NODE_EXPRESSION_MULTILINE_EXPECTED = 'first second third' TEST_NODE_EXPRESSION_MULTILINE_2 = '\r\n\r\nfirst\r\nsecond\r\nthird\r\n' TEST_NODE_EXPRESSION_MULTILINE_2_EXPECTED = 'first second third' TEST_NODE_PK = 88 TEST_PATH = '/test/path'
[ "79801878+Meng87@users.noreply.github.com" ]
79801878+Meng87@users.noreply.github.com
4bbee182075a9344afaaa9db03b894910f5cdeda
db58ec54f85fd8d4ef6904529c5b17393ee041d8
/hacker-rank/30-days-of-code/3-intro-to-conditional-statements.py
a18e87e87351ccafc3ade2a2b6eb8288cf2008aa
[ "MIT" ]
permissive
washimimizuku/python-data-structures-and-algorithms
90ae934fc7d2bac5f50c18e7fbc463ba0c026fa4
537f4eabaf31888ae48004d153088fb28bb684ab
refs/heads/main
2023-08-28T07:45:19.603594
2021-11-08T07:53:52
2021-11-08T07:53:52
334,213,593
0
0
null
null
null
null
UTF-8
Python
false
false
658
py
#!/bin/python3 ''' https://www.hackerrank.com/challenges/30-conditional-statements Given an integer, n, perform the following conditional actions: 1. If n is odd, print Weird 2. If n is even and in the inclusive range of 2 to 5, print Not Weird 3. If n is even and in the inclusive range of 6 to 20, print Weird 4. If n is even and greater than 20, print Not Weird Complete the stub code provided in your editor to print whether or not n is weird. ''' if __name__ == '__main__': N = int(input()) if (N % 2): print('Weird') else: if (N >= 6 and N <= 20): print('Weird') else: print('Not Weird')
[ "nuno.barreto@inventsys.ch" ]
nuno.barreto@inventsys.ch
76ab20b11cb7917130d6313dd70fc7c2204486ac
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
/HvsBiHLGcsv2ex3gv_17.py
9eeb06382887e34dbf89828fd97e2c5c4b26d16d
[]
no_license
daniel-reich/ubiquitous-fiesta
26e80f0082f8589e51d359ce7953117a3da7d38c
9af2700dbe59284f5697e612491499841a6c126f
refs/heads/master
2023-04-05T06:40:37.328213
2021-04-06T20:17:44
2021-04-06T20:17:44
355,318,759
0
0
null
null
null
null
UTF-8
Python
false
false
146
py
import math def shortestDistance(txt): x1, y1, x2, y2 = list(map(float, txt.split(','))) return round(((x1 - x2)**2 + (y1 - y2)**2)**.5, 2)
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
8a6bdf502895e1b6a3423a37821464cc67432269
a1c20ec292350a4c8f2164ba21715414f8a77d19
/edx/5_Joynernacci.py
968c322ff5cda6dc679e9a0c92205cd2d9a9b575
[]
no_license
nowacki69/Python
2ae621b098241a614836a50cb1102094bf8e689f
e5325562801624e43b3975d9f246af25517be55b
refs/heads/master
2021-08-22T21:30:39.534186
2019-09-03T01:21:11
2019-09-03T01:21:11
168,528,687
0
0
null
null
null
null
UTF-8
Python
false
false
1,488
py
#Remember that Fibonacci's sequence is a sequence of numbers #where every number is the sum of the previous two numbers. # #Joynernacci numbers are similar to Fibonacci numbers, but #with two differences: # # - Fibonacci numbers are famous, Joynernacci numbers are # not (yet). # - In Joynernacci numbers, even-indexed numbers are the # sum of the previous two numbers, while odd-indexed # numbers are the absolute value of the difference # between the previous two numbers. # #For example: the Joynernacci sequence starts with 1 and 1 #as the numbers at index 1 and 2. 3 is an odd index, so #the third number would be 0 (1 - 1 = 0). 4 is an even #index, so the fourth number would be 1 (0 + 1). 5 is an #odd index, so the fifth number would be 1 (1 - 0). And #so on. # #The first several Joynernacci numbers (and their indices) #are thus: # # 1 1 0 1 1 2 1 3 2 5 3 8 5 13 8 21 13 34 21 # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 # #Write a function called joynernacci that returns the nth #Joynernacci number. For example: # # joynernacci(5) -> 1 # joynernacci(12) -> 8 # #We recommend implementing joynernacci recursively, but it #is not required. #Write your code here! #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. # #If your function works correctly, this will originally #print: 1, then 8 print(joynernacci(5)) print(joynernacci(12))
[ "nowacki69@gmail.com" ]
nowacki69@gmail.com
4b9b8076b1e6d35fef5e2416fbeac00933997a38
0ed9a8eef1d12587d596ec53842540063b58a7ec
/cloudrail/knowledge/context/environment_context/environment_context_defaults_merger.py
c0aa6175324c16da21d47dff9af6a602a4d700ef
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
cbc506/cloudrail-knowledge
8611faa10a3bf195f277b81622e2590dbcc60da4
7b5c9030575f512b9c230eed1a93f568d8663708
refs/heads/main
2023-08-02T08:36:22.051695
2021-09-13T15:23:33
2021-09-13T15:24:26
390,127,361
0
0
MIT
2021-07-27T21:08:06
2021-07-27T21:08:06
null
UTF-8
Python
false
false
308
py
from abc import abstractmethod from cloudrail.knowledge.context.base_environment_context import BaseEnvironmentContext class EnvironmentContextDefaultsMerger: @staticmethod @abstractmethod def merge_defaults(scanner_ctx: BaseEnvironmentContext, iac_ctx: BaseEnvironmentContext): pass
[ "ori.bar.emet@gmail.com" ]
ori.bar.emet@gmail.com
646ef078497ec966d63ba0eeb3fa364d0ebe238c
6aafb5d3e6204a442c0f1afad02c4ab6cbbc290f
/event/mention/models/rule_detectors.py
728234afa512dcd4677e2d15c7f148ad2ecf8106
[ "Apache-2.0" ]
permissive
Aditi138/DDSemantics
22ae526d91e41b728050b6adae8847c6106b7d91
c76010ea44b21810057c82a7ddbd1c6a3568f5f4
refs/heads/master
2020-03-21T11:21:48.622464
2018-06-24T15:39:31
2018-06-24T15:39:31
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,116
py
import math from event.io.ontology import OntologyLoader class MentionDetector: def __init__(self, **kwargs): super().__init__() self.unknown_type = "UNKNOWN" def predict(self, *input): pass class BaseRuleDetector(MentionDetector): def __init__(self, config, token_vocab): super().__init__() self.onto = OntologyLoader(config.ontology_path) self.token_vocab = token_vocab def predict(self, *input): words, _, l_feature, word_meta, sent_meta = input[0] center = math.floor(len(words) / 2) lemmas = [features[0] for features in l_feature] words = self.token_vocab.reveal_origin(words) return self.predict_by_word(words, lemmas, l_feature, center) def predict_by_word(self, words, lemmas, l_feature, center): raise NotImplementedError('Please implement the rule detector.') class MarkedDetector(BaseRuleDetector): """ Assume there is one field already marked with event type. """ def __init__(self, config, token_vocab, marked_field_index=-2): super().__init__(config, token_vocab) self.marked_field_index = marked_field_index def predict(self, *input): words, _, l_feature, word_meta, sent_meta = input[0] center = math.floor(len(words) / 2) return l_feature[center][self.marked_field_index] class FrameMappingDetector(BaseRuleDetector): def __init__(self, config, token_vocab): super().__init__(config, token_vocab) self.lex_mapping = self.load_frame_lex(config.frame_lexicon) self.entities, self.events, self.relations = self.load_wordlist( config.entity_list, config.event_list, config.relation_list ) self.temp_memory = set() def load_frame_lex(self, frame_path): import xml.etree.ElementTree as ET import os ns = {'berkeley': 'http://framenet.icsi.berkeley.edu'} lex_mapping = {} for file in os.listdir(frame_path): with open(os.path.join(frame_path, file)) as f: tree = ET.parse(f) frame = tree.getroot() frame_name = frame.get('name') lexemes = [] for lexUnit in frame.findall('berkeley:lexUnit', ns): lex = lexUnit.get('name') lexeme = lexUnit.findall( 'berkeley:lexeme', ns)[0].get('name') lexemes.append(lexeme) lex_text = ' '.join(lexemes) if lex_text not in lex_mapping: lex_mapping[lex_text] = [] lex_mapping[lex_text].append(frame_name) return lex_mapping def load_wordlist(self, entity_file, event_file, relation_file): events = {} entities = {} relations = {} with open(event_file) as fin: for line in fin: parts = line.strip().split() if len(parts) == 2: word, ontology = line.strip().split() events[word] = ontology with open(entity_file) as fin: for line in fin: parts = line.strip().split() if len(parts) == 2: word, ontology = line.strip().split() entities[word] = ontology with open(relation_file) as fin: for line in fin: parts = line.strip().split() if parts: event_type = parts[0] args = parts[1:] if event_type not in relations: relations[event_type] = {} for arg in args: arg_role, arg_types = arg.split(":") relations[event_type][arg_role] = arg_types.split(",") return entities, events, relations def predict_by_word(self, words, lemmas, l_feature, center): event_types = [] center_word = words[center] center_lemma = lemmas[center] # if center_lemma in self.lex_mapping: # for fname in self.lex_mapping[center_lemma]: # event_types.append(('FrameNet', fname)) # if center_word in self.events: # event_type = self.events[center_word] # # if center_lemma in self.events: # event_type = self.events[center_lemma] # pos_list = [features[1] for features in l_feature] # deps = [(features[2], features[3]) for features in l_feature] # if not event_type == self.unknown_type: # res = self.predict_args(center, event_type, lemmas, pos_list, # deps) # # for role, entity in res.items(): # if entity: # index, entity_type = entity # features = l_feature[index] # args[role] = index, entity_type return event_types def predict_args(self, center, event_type, context, pos_list, deps): if event_type not in self.relations: return {} expected_relations = self.relations[event_type] expected_relations["Location"] = ["Loc", "GPE"] expected_relations["Time"] = ["Time"] filled_relations = dict([(k, None) for k in expected_relations]) num_to_fill = len(filled_relations) relation_lookup = {} for role, types in expected_relations.items(): for t in types: relation_lookup[t] = role for distance in range(1, center + 1): left = center - distance right = center + distance left_lemma = context[left] right_lemma = context[right] if left_lemma in self.entities: arg_type = self.check_arg(context[center], event_type, left_lemma, deps) if arg_type in relation_lookup: possible_rel = relation_lookup[arg_type] if filled_relations[possible_rel] is None: filled_relations[possible_rel] = (left, arg_type) num_to_fill -= 1 if right_lemma in self.entities: arg_type = self.check_arg(context[center], event_type, right_lemma, deps) if arg_type in relation_lookup: possible_rel = relation_lookup[arg_type] if filled_relations[possible_rel] is None: filled_relations[possible_rel] = (right, arg_type) num_to_fill -= 1 if num_to_fill == 0: break return filled_relations def check_arg(self, predicate, event_type, arg_lemma, features): unknown_type = "O" entity_type = unknown_type if arg_lemma in self.entities: entity_type = self.entities[arg_lemma] if not entity_type == unknown_type: return entity_type return None
[ "hunterhector@gmail.com" ]
hunterhector@gmail.com
cead45ed6889c6bfe7441b3f734ec81df2680bf8
1ec4cd1417ae392deafd52b187cae61964efc8eb
/pheasant/main.py
098fb43f7e3ea78e4ada77ada1c8a29c771a699c
[ "MIT" ]
permissive
pkestene/pheasant
4cdfdfeb8a0529ef4ff589698871aea8ee2d2679
c9465f4fa1bacd7488c049882cb0663bad33feb9
refs/heads/master
2022-10-05T19:46:07.647962
2020-06-02T22:21:12
2020-06-02T22:21:12
269,784,793
0
0
MIT
2020-06-05T21:40:27
2020-06-05T21:40:26
null
UTF-8
Python
false
false
6,719
py
import os import sys import click import yaml from pheasant import __version__ from pheasant.core.page import Pages pgk_dir = os.path.dirname(os.path.abspath(__file__)) version_msg = f"{__version__} from {pgk_dir} (Python {sys.version[:3]})." @click.group(invoke_without_command=True) @click.pass_context @click.version_option(version_msg, "-V", "--version") def cli(ctx): if ctx.invoked_subcommand is None: prompt() ext_option = click.option( "-e", "--ext", default="md,py", show_default=True, help="File extension(s) separated by commas.", ) max_option = click.option( "--max", default=100, show_default=True, help="Maximum number of files." ) paths_argument = click.argument("paths", nargs=-1, type=click.Path(exists=True)) @cli.command(help="Run source files and save the caches.") @click.option("-r", "--restart", is_flag=True, help="Restart kernel after run.") @click.option("-s", "--shutdown", is_flag=True, help="Shutdown kernel after run.") @click.option("-f", "--force", is_flag=True, help="Delete cache and run.") @click.option( "-v", "--verbose", count=True, help="Print input codes and/or outputs from kernel." ) @ext_option @max_option @paths_argument def run(paths, ext, max, restart, shutdown, force, verbose): pages = Pages(paths, ext).collect() length = len(pages) click.secho(f"collected {length} files.", bold=True) if length > max: # pragma: no cover click.secho("Too many files. Aborted.", fg="yellow") sys.exit() if force: for page in pages: if page.has_cache: page.cache.delete() click.echo(page.cache.path + " was deleted.") from pheasant.core.pheasant import Pheasant converter = Pheasant(restart=restart, shutdown=shutdown, verbose=verbose) converter.jupyter.safe = True set_config(converter) converter.convert_from_files(page.path for page in pages) click.secho(f"{converter.log.info}", bold=True) def set_config(converter): if not os.path.exists("mkdocs.yml"): return with open("mkdocs.yml", "r") as f: config = yaml.safe_load(f) plugins = config.get("plugins", []) for plugin in plugins: if isinstance(plugin, dict) and 'pheasant' in plugin: config = plugin['pheasant'] break else: return cur_dir = config.get("cur_dir", 'page') confing_dir = os.getcwd() if cur_dir == "docs": cur_dir = os.path.join(confing_dir, 'docs') elif cur_dir == "config": cur_dir = confing_dir sys_paths = config.get("sys_paths", []) sys_paths = [os.path.join(confing_dir, path) for path in sys_paths] sys_paths = [os.path.normpath(path) for path in sys_paths] converter.jupyter.set_config( cur_dir=cur_dir, sys_paths=sys_paths ) @cli.command(help="Convert source files to rendered Markdown.") @click.option("-r", "--restart", is_flag=True, help="Restart kernel after run.") @click.option("-s", "--shutdown", is_flag=True, help="Shutdown kernel after run.") @click.option("-f", "--force", is_flag=True, help="Delete cache and run.") @click.option( "-v", "--verbose", count=True, help="Print input codes and/or outputs from kernel." ) @ext_option @max_option @paths_argument def convert(paths, ext, max, restart, shutdown, force, verbose): pages = Pages(paths, ext).collect() length = len(pages) click.secho(f"collected {length} files.", bold=True) if length > max: # pragma: no cover click.secho("Too many files. Aborted.", fg="yellow") sys.exit() if force: for page in pages: if page.has_cache: page.cache.delete() click.echo(page.cache.path + " was deleted.") from pheasant.core.pheasant import Pheasant converter = Pheasant(restart=restart, shutdown=shutdown, verbose=verbose) converter.jupyter.safe = True outputs = converter.convert_from_files(page.path for page in pages) for page, output in zip(pages, outputs): path = page.path.replace(".py", ".md").replace(".md", ".out.md") with open(path, "w", encoding="utf-8") as f: f.write(output) @cli.command(help="List source files.") @ext_option @paths_argument def list(paths, ext): pages = Pages(paths, ext).collect() def size(cache): size = cache.size / 1024 if size > 1024: size /= 1024 return f"{size:.01f}MB" else: return f"{size:.01f}KB" for page in pages: click.echo( ("* " if page.modified else " ") + page.path + (f" (cached, {size(page.cache)})" if page.has_cache else "") ) click.secho(f"collected {len(pages)} files.", bold=True) @cli.command(help="Delete caches for source files.") @click.option("-y", "--yes", is_flag=True, help="Do not ask for confirmation.") @ext_option @paths_argument def clean(paths, ext, yes): pages = Pages(paths, ext).collect() caches = [page.cache for page in pages if page.has_cache] if not caches: click.secho("No cache found. Aborted.", bold=True) sys.exit() for cache in caches: click.echo(cache.path) click.secho(f"collected {len(caches)} files.", bold=True) if not yes: click.confirm( "Are you sure you want to delete the caches for these files?", abort=True ) for cache in caches: cache.delete() click.echo(cache.path + " was deleted.") @cli.command(help="Python script prompt.") def python(): prompt(script=True) def prompt(script=False): click.echo("Enter double blank lines to exit.") lines = [] while True: line = click.prompt("", type=str, default="", show_default=False) if lines and lines[-1] == "" and line == "": break lines.append(line) source = "\n".join(lines).strip() + "\n" from markdown import Markdown from pheasant.core.pheasant import Pheasant converter = Pheasant() if script: source = converter.parse(source, "script") output = converter.parse(source, "main") output = converter.parse(output, "link") click.echo("[source]") click.echo(source.strip()) click.echo("[markdown]") click.echo(output.strip()) click.echo("[html]") markdown = Markdown() html = markdown.convert(output) click.echo(html.strip()) @cli.command(help="Serve web application.") @click.option("--port", default=8000, show_default=True, help="Port number.") @paths_argument @ext_option def serve(port, paths, ext): from pheasant.app.app import App app = App(paths, ext) app.run(port=port)
[ "daizutabi@gmail.com" ]
daizutabi@gmail.com
13873d164ca16400626328281f48e76f70139854
805a795ea81ca8b5cee1dec638585011da3aa12f
/MAIN/SC8/descriptionSetup8.py
a047dd05fd5ebd1065ff27bbb45d935885f0fc4f
[ "Apache-2.0" ]
permissive
josipamrsa/Interactive3DAnimation
5b3837382eb0cc2ebdee9ee69adcee632054c00a
a4b7be78514b38fb096ced5601f25486d2a1d3a4
refs/heads/master
2022-10-12T05:48:20.572061
2019-09-26T09:50:49
2019-09-26T09:50:49
210,919,746
0
1
Apache-2.0
2022-10-11T01:53:36
2019-09-25T19:03:51
Python
UTF-8
Python
false
false
1,328
py
import bge, bgl # Game engine i logika import blf # Upravljanje fontovima import math # Matematicke operacije # Kontrolerske varijable cont = bge.logic.getCurrentController() # Aktivni kontroler sc = bge.logic.getCurrentScene() # Aktivna scena own = cont.owner # Vlasnik # Rekalkulacija rotacije, translacije i skaliranja # opisa/obavijesti u sceni def recalculateRotation(obj,deg): rec = obj.localOrientation.to_euler() rec[1] = math.radians(deg) obj.localOrientation = rec.to_matrix() def rescaleObject(desc,frame): frameScale = desc.localScale[0] * (len(desc['Text']) / 7) frame.localScale[0] = frameScale def repositionObjects(desc,frame,posXYZ): frame.localPosition = posXYZ desc.localPosition = [posXYZ[0], posXYZ[1]*0.3, posXYZ[2]-0.8] # Objekti aktivne scene desc = sc.objects['Description4'] bubble = sc.objects['Bubble4'] msgNo = desc['msgProp'] # Broj poruke oznacava interaktivni objekt na sceni if msgNo == 0: repositionObjects(desc,bubble,[-1, 1.5, 3.0]) rescaleObject(desc,bubble) recalculateRotation(bubble,0) elif msgNo == 1: repositionObjects(desc,bubble,[-1, 1.5, 3.0]) rescaleObject(desc,bubble) recalculateRotation(bubble,0) # TODO - adaptirati skriptu za sve scene
[ "jmrsa21@gmail.com" ]
jmrsa21@gmail.com
f77cd4d3705f6836da20c19d301506a78fe19fc0
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2511/61132/300621.py
30fd96a4af0f3d26bfc73805f849f6008ed799d4
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
327
py
t,k = map(int,input().split()) l=[] ans=[] for j in range(t-1): l.append(int(input())) for i in range(len(l)): for le in range(len(l)-i,1,-1): if le%2==0 and sum(l[i:i+le//2])<=k and sum(l[i+le//2:i+le])<=k: ans.append(le) break else: ans.append(0) for i in ans: print(i)
[ "1069583789@qq.com" ]
1069583789@qq.com
e97fcd99d6872281fac7555bf69f72ad04b23bf8
aa64c62a3d246b87f3f1e5810a8f75b1d166aaf6
/paradrop/daemon/paradrop/lib/utils/addresses.py
39e033f7b0d50df4eacfe5692f24ffa180025536
[ "Apache-2.0" ]
permissive
ParadropLabs/Paradrop
ca40b3373c0732c781f9c10d38da9b6e9fbd3453
c910fd5ac1d1b5e234f40f9f5592cc981e9bb5db
refs/heads/master
2023-02-26T17:51:53.058300
2022-03-01T17:46:10
2022-03-01T17:46:10
37,789,450
88
31
Apache-2.0
2023-02-16T05:24:46
2015-06-20T23:18:38
Python
UTF-8
Python
false
false
4,947
py
################################################################### # Copyright 2013-2014 All Rights Reserved # Authors: The Paradrop Team ################################################################### import socket import struct from paradrop.lib.utils import pdos def isIpValid(ipaddr): """Return True if Valid, otherwise False.""" try: socket.inet_aton(ipaddr) return True except: return False def isIpAvailable(ipaddr, chuteStor, name): """ Make sure this IP address is available. Checks the IP addresses of all zones on all other chutes, makes sure subnets are not the same. """ chList = chuteStor.getChuteList() for ch in chList: # Only look at other chutes if (name != ch.name): otherIPs = ch.getChuteIPs() if ipaddr in otherIPs: return False return True def isWifiSSIDAvailable(ssid, chuteStor, name): """Make sure this SSID is available.""" chList = chuteStor.getChuteList() for ch in chList: # Only look at other chutes if (name != ch.name): otherSSIDs = ch.getChuteSSIDs() #print("chute: %s other SSIDs: %s" % (ch, otherSSIDs)) for o in otherSSIDs: if (o == ssid): return False return True def isStaticIpAvailable(ipaddr, chuteStor, name): """ Make sure this static IP address is available. Checks the IP addresses of all zones on all other chutes, makes sure not equal.""" chList = chuteStor.getChuteList() for ch in chList: # Only look at other chutes if (name != ch.name): otherStaticIPs = ch.getChuteStaticIPs() if ipaddr in otherStaticIPs: return False return True def checkPhyExists(radioid): """Check if this chute exists at all, a directory /sys/class/ieee80211/phyX must exist.""" #DFW: used to be this, but when netns runs this doesn't exist, so we switched to using the debug sysfs '/sys/class/ieee80211/phy%d' % radioid return pdos.exists('/sys/kernel/debug/ieee80211/phy%d' % radioid) def incIpaddr(ipaddr, inc=1): """ Takes a quad dot format IP address string and adds the @inc value to it by converting it to a number. Returns: Incremented quad dot IP string or None if error """ try: val = struct.unpack("!I", socket.inet_aton(ipaddr))[0] val += inc return socket.inet_ntoa(struct.pack('!I', val)) except Exception: return None def maxIpaddr(ipaddr, netmask): """ Takes a quad dot format IP address string and makes it the largest valid value still in the same subnet. Returns: Max quad dot IP string or None if error """ try: val = struct.unpack("!I", socket.inet_aton(ipaddr))[0] nm = struct.unpack("!I", socket.inet_aton(netmask))[0] inc = struct.unpack("!I", socket.inet_aton("0.0.0.254"))[0] val &= nm val |= inc return socket.inet_ntoa(struct.pack('!I', val)) except Exception: return None def getSubnet(ipaddr, netmask): try: val1 = struct.unpack("!I", socket.inet_aton(ipaddr))[0] nm = struct.unpack("!I", socket.inet_aton(netmask))[0] res = val1 & nm return socket.inet_ntoa(struct.pack('!I', res)) except Exception: return None def getInternalIntfList(ch): """ Takes a chute object and uses the key:networkInterfaces to return a list of the internal network interfaces that will exist in the chute (e.g., eth0, eth1, ...) Returns: A list of interface names None if networkInterfaces doesn't exist or there is an error """ intfs = ch.getCache('networkInterfaces') if(not intfs): return None l = [] for i in intfs: l.append(i['internalIntf']) return l def getGatewayIntf(ch): """ Looks at the key:networkInterfaces for the chute and determines what the gateway should be including the IP address and the internal interface name. Returns: A tuple (gatewayIP, gatewayInterface) None if networkInterfaces doesn't exist or there is an error """ intfs = ch.getCache('networkInterfaces') if(not intfs): return (None, None) for i in intfs: if(i['type'] == 'wan'): return (i['externalIpaddr'], i['internalIntf']) return (None, None) def getWANIntf(ch): """ Looks at the key:networkInterfaces for the chute and finds the WAN interface. Returns: The dict from networkInterfaces None """ intfs = ch.getCache('networkInterfaces') if(not intfs): return None for i in intfs: if(i['type'] == 'wan'): return i return None
[ "hartung@cs.wisc.edu" ]
hartung@cs.wisc.edu
57aff09534e2ac61bab36946cf7f415e0d943545
f24c35bb0919f9ad75f45e7906691c3189536b33
/chengbinWorkSpace/droneLanding/python/main1.py
006ebfa79f8a773cf8017786c92d08d5e4727681
[]
no_license
mfkiwl/supreme-xcb
9b941f49bab5a811d23a0cd75790d1e5722aa9f0
d1287657607bf86d4b1393acf285951760670925
refs/heads/main
2023-03-07T12:10:28.288282
2021-03-02T11:46:00
2021-03-02T11:46:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,158
py
''' brief: Version: Autor: shuike Date: 2020-12-31 17:36:47 LastEditors: shuike LastEditTime: 2020-12-31 17:39:59 FilePath: /droneLanding/python/main1.py ''' import numpy as np import time import cv2 import cv2.aruco as aruco #with np.load('webcam_calibration_output.npz') as X: # mtx, dist, _, _ = [X[i] for i in ('mtx','dist','rvecs','tvecs')] #mtx = #2946.48 0 1980.53 #0 2945.41 1129.25 #0 0 1 mtx = np.array([ [2946.48, 0, 1980.53], [ 0, 2945.41, 1129.25], [ 0, 0, 1], ]) #我的手机拍棋盘的时候图片大小是 4000 x 2250 #ip摄像头拍视频的时候设置的是 1920 x 1080,长宽比是一样的, #ip摄像头设置分辨率的时候注意一下 dist = np.array( [0.226317, -1.21478, 0.00170689, -0.000334551, 1.9892] ) # video = "http://admin:admin@192.168.1.2:8081/" # 手机ip摄像头 # 根据ip摄像头在你手机上生成的ip地址更改,右上角可修改图像分辨率 video = 0 cap = cv2.VideoCapture(video) font = cv2.FONT_HERSHEY_SIMPLEX #font for displaying text (below) #num = 0 while True: ret, frame = cap.read() # operations on the frame come here gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250) parameters = aruco.DetectorParameters_create() ''' detectMarkers(...) detectMarkers(image, dictionary[, corners[, ids[, parameters[, rejectedI mgPoints]]]]) -> corners, ids, rejectedImgPoints ''' #lists of ids and the corners beloning to each id corners, ids, rejectedImgPoints = aruco.detectMarkers(gray, aruco_dict, parameters=parameters) # if ids != None: if ids is not None: rvec, tvec, _ = aruco.estimatePoseSingleMarkers(corners, 0.05, mtx, dist) # Estimate pose of each marker and return the values rvet and tvec---different # from camera coeficcients (rvec-tvec).any() # get rid of that nasty numpy value array error # aruco.drawAxis(frame, mtx, dist, rvec, tvec, 0.1) #Draw Axis # aruco.drawDetectedMarkers(frame, corners) #Draw A square around the markers for i in range(rvec.shape[0]): aruco.drawAxis(frame, mtx, dist, rvec[i, :, :], tvec[i, :, :], 0.03) aruco.drawDetectedMarkers(frame, corners) ###### DRAW ID ##### # cv2.putText(frame, "Id: " + str(ids), (0,64), font, 1, (0,255,0),2,cv2.LINE_AA) else: ##### DRAW "NO IDS" ##### cv2.putText(frame, "No Ids", (0,64), font, 1, (0,255,0),2,cv2.LINE_AA) # Display the resulting frame cv2.imshow("frame",frame) key = cv2.waitKey(30) if key == 27: # 按esc键退出 print('esc break...') cap.release() cv2.destroyAllWindows() break if key == ord(' '): # 按空格键保存 # num = num + 1 # filename = "frames_%s.jpg" % num # 保存一张图像 filename = str(time.time())[:10] + ".jpg" cv2.imwrite(filename, frame)
[ "xiechengbinin@gmail.com" ]
xiechengbinin@gmail.com
1bba11a9a7d0dd0ee37d1de55d8acf5bf381a26f
8fcc27160f8700be46296568260fa0017a0b3004
/client/projectdiscovery/client/const.py
ad0cb4b6c30e1654050e4db0e6c4dbd6ccfdb876
[]
no_license
connoryang/dec-eve-serenity
5d867f4eedfa896a4ef60f92556356cafd632c96
b670aec7c8b4514fc47cd52e186d7ccf3aabb69e
refs/heads/master
2021-01-22T06:33:16.303760
2016-03-16T15:15:32
2016-03-16T15:15:32
56,389,750
1
0
null
2016-04-16T15:05:24
2016-04-16T15:05:24
null
UTF-8
Python
false
false
3,862
py
#Embedded file name: e:\jenkins\workspace\client_SERENITY\branches\release\SERENITY\packages\projectdiscovery\client\const.py import os RESROOT = os.path.dirname(__file__) + '\\res\\' class Texts: SelectionsLabel = 'Selections' TaskImageLabel = 'Jovian Tissue Sample' RankLabel = 'Rank: ' ScoreLabel = ' Discovery Credits' SubmitButtonLabel = 'Submit' PreviousGroupButtonLabel = 'Previous Group' NextGroupButtonLabel = 'Next Group' class Events: PlayTutorial = 'OnCitizenSciencePlayTutorial' NewTask = 'OnCitizenScienceNewTask' NewTrainingTask = 'OnCitizenScienceNewTrainingTask' CategoryChanged = 'OnCitizenScienceCategoryChanged' ExcludeCategories = 'OnCitizenScienceExcludeCategories' SubmitSolution = 'OnCitizenScienceSubmitSolution' ResultReceived = 'OnCitizenScienceResultReceived' TrainingResultReceived = 'OnCitizenScienceTrainingResultReceived' ContinueFromResult = 'OnCitizenScienceContinueFromResult' ContinueFromTrainingResult = 'OnCitizenScienceContinueFromTrainingResult' UpdateScoreBar = 'OnCitizenScienceUpdateScoreBar' ProjectDiscoveryStarted = 'OnProjectDiscoveryStarted' ContinueFromReward = 'OnProjectDiscoveryContinueFromReward' StartTutorial = 'OnProjectDiscoveryStartTutorial' QuitTutorial = 'OnProjectDiscoveryQuitTutorial' CloseResult = 'OnProjectDiscoveryResultClosed' HoverMainImage = 'OnHoverMainImage' ClickMainImage = 'OnClickMainImage' ProcessingViewFinished = 'OnProcessingViewFinished' MouseExitMainImage = 'OnMouseExitMainImage' MouseEnterMainImage = 'OnMouseEnterMainImage' TransmissionFinished = 'OnTransmissionFinished' RewardViewFadeOut = 'OnRewardViewFadeOut' MainImageLoaded = 'OnMainImageLoaded' EnableUI = 'OnUIEnabled' class Settings: ProjectDiscoveryTutorialPlayed = 'ProjectDiscoveryTutorialPlayed' ProjectDiscoveryIntroductionShown = 'ProjectDiscoveryIntroductionShown' class Sounds: CategorySelectPlay = 'wise:/project_discovery_category_select_play' MainImageLoadPlay = 'wise:/project_discovery_main_image_calculation_loop_play' MainImageLoadStop = 'wise:/project_discovery_main_image_calculation_loop_stop' MainImageLoopPlay = 'wise:/project_discovery_main_image_loop_play' MainImageLoopStop = 'wise:/project_discovery_main_image_loop_stop' MainImageOpenPlay = 'wise:/project_discovery_main_image_open_play' ColorSelectPlay = 'wise:/project_discovery_color_select_play' ProcessingPlay = 'wise:/project_discovery_analysis_calculation_loop_play' ProcessingStop = 'wise:/project_discovery_analysis_calculation_loop_stop' RewardsWindowOpenPlay = 'wise:/project_discovery_analysis_window_open_play' RewardsWindowClosePlay = 'wise:/project_discovery_analysis_window_close_play' RewardsWindowLoopPlay = 'wise:/project_discovery_analysis_window_loop_play' RewardsWindowLoopStop = 'wise:/project_discovery_analysis_window_loop_stop' AnalysisDonePlay = 'wise:/project_discovery_analysis_done_play' AnalysisWindowMovePlay = 'wise:/project_discovery_analysis_window_move_play' TrainingTasks = {'starter': {160000016: [102], 160000017: [211], 160000005: [303]}, 'levelOne': {160000009: [233], 160000001: [203], 160000011: [221]}, 'levelTwo': {160000014: [123], 160000003: [112], 160000007: [113]}, 'levelThree': {160000010: [102, 233], 160000006: [121, 203], 160000000: [102, 201]}, 'levelFour': {160000012: [303, 201]}, 'levelFive': {160000008: [102, 303, 302], 160000015: [102, 215]}, 'negative': {160000002: [901], 160000004: [101], 160000013: [201]}, 'unspecific': {}}
[ "masaho.shiro@gmail.com" ]
masaho.shiro@gmail.com
7e0ba785a515715cb0fc0bc4a2a9e33058df31f5
682581de9e3674d157877756d1a536f5b028c045
/script/Analysis3b_NW.py
581494f743f8299a4ad5ac878e03fb7d41090989
[]
no_license
wchnicholas/ProteinGFourMutants
3a81b9175e0e5bb864d5723fa59443a3ba07eda6
dbdd7639187e0b8f22359f404ce4d1d950fcc8a9
refs/heads/master
2023-08-16T19:53:02.475407
2023-08-03T12:24:44
2023-08-03T12:24:44
33,599,807
8
0
null
null
null
null
UTF-8
Python
false
false
4,443
py
#!/usr/bin/python import os import sys import operator import networkx as nx import numpy as np from itertools import imap def all_shortest_paths(G, source, target, weight=None): if weight is not None: pred,dist = nx.dijkstra_predecessor_and_distance(G,source,weight=weight) else: pred = nx.predecessor(G,source) if target not in pred: raise nx.NetworkXNoPath() stack = [[target,0]] top = 0 while top >= 0: node,i = stack[top] if node == source: yield [p for p,n in reversed(stack[:top+1])] if len(pred[node]) > i: top += 1 if top == len(stack): stack.append([pred[node][i],0]) else: stack[top] = [pred[node][i],0] else: stack[top-1][1] += 1 top -= 1 def hamming(str1, str2): assert len(str1) == len(str2) return sum(imap(operator.ne, str1, str2)) def TsvWithHeader2Hash(fitfile): H = {} infile = open(fitfile,'r') countline = 0 header = [] for line in infile.xreadlines(): countline += 1 line = line.rstrip().rsplit("\t") if countline == 1: header = line; continue mut = line[0] H[mut] = {} for i in range(1,len(line)): H[mut][header[i]] = line[i] infile.close() return H def filterfithash(fithash, condition): for mut in fithash.keys(): if fithash[mut][condition] == 'NA' or '_' in mut: del fithash[mut] return fithash def generatenodes(mut,WT,fithash): pathhash = {} nodes = [] for i in range(4): pathhash[i] = [WT[i],mut[i]] for i in range(16): index = str(bin(i)).rsplit('b')[1] index = ''.join(map(str,[0]*(4-len(index))))+index node = '' for p in range(len(index)): node+=pathhash[p][int(index[p])] if fithash.has_key(node): nodes.append(node) else: nodes.append('NA') return nodes def buildgraph(nodes): G = nx.Graph() [G.add_node(node) for node in nodes] for n1 in nodes: for n2 in nodes: if hamming(n1,n2) == 1: G.add_edge(n1,n2) return G def removenodes(nodes, fithash, cutoff, condition): cleannodes = [] for node in nodes: if float(fithash[node][condition]) >= cutoff: cleannodes.append(node) return cleannodes def stucking(path,fithash,condition,mut,WT): mutfit = float(fithash[mut][condition]) wtfit = float(fithash[WT][condition]) for step in path: stepfit = float(fithash[step][condition]) if step != WT and step != mut and stepfit > mutfit and stepfit > wtfit: return 1 return 0 def monoincr(path,fithash,condition,mut,WT): for n in range(1,len(path)): stepPrev = path[n-1] stepCurr = path[n] if float(fithash[stepPrev][condition]) > float(fithash[stepCurr][condition]): return 0 return 1 def localmaxing(G,WT,fithash,condition): localmaxs = [] for node in G.nodes(): fit = float(fithash[node][condition]) neighfits = [] [neighfits.append(float(fithash[neigh][condition])) for neigh in G.neighbors(node)] if max(neighfits) < fit: localmaxs.append(node) return localmaxs def pathwayanalysis(fithash,muts,WT,condition,outfile): print 'Pathway analysis started' for mut in muts: HD = int(fithash[mut]['HD']) mutfit = float(fithash[mut][condition]) if HD == 4 and mutfit < 1 and mutfit > 0.01: nodes = generatenodes(WT,mut,fithash) if 'NA' in nodes: continue G = buildgraph(nodes) localmaxs = localmaxing(G,WT,fithash,condition) if len(localmaxs) != 1 or localmaxs[0] != WT: continue assert(max([float(fithash[node][condition]) for node in nodes])==1) paths = all_shortest_paths(G,mut,WT) monoIpath = 0 for path in paths: assert(len(path)==5) #if float(fithash[path[1]][condition]) <= 0.01: continue #Filter first step fitness monoIpath+=monoincr(path,fithash,condition,mut,WT) outfile.write("\t".join(map(str,[condition, mut, mutfit, len(nodes), monoIpath]))+"\n") def main(): WT = 'VDGV' fitfile = 'result/Mutfit' outfile = 'analysis/ShortMonoPaths4ToWT' condition = 'I20fit' fithash = TsvWithHeader2Hash(fitfile) fithash = filterfithash(fithash, condition) muts = fithash.keys() outfile = open(outfile,'w') outfile.write("Condition\tMut\tMutfit\tNodes\tMonoIPath\n") pathwayanalysis(fithash,muts,WT,condition,outfile) outfile.close() if __name__ == '__main__': main()
[ "wchnicholas@Nicholass-MacBook-Pro.local" ]
wchnicholas@Nicholass-MacBook-Pro.local
f11e1e87cc797779c10501b1ba6580ef22410b8b
4f72e1235675562838c84dc7bfc7c97b9139dfd3
/src/tmdp/programs/pomdp_list/mdp_builder.py
2214c2518a806b47b79f8552b6517a072fe09599
[]
no_license
AndreaCensi/tmdp
dcc590cacd5f146b08c6dced132ca601554597f6
28d3103eedcc9370e56c96fff8004b8320b90c43
refs/heads/master
2021-01-12T19:24:46.987223
2014-06-10T01:39:39
2014-06-10T01:39:39
16,900,103
1
1
null
null
null
null
UTF-8
Python
false
false
3,565
py
from collections import defaultdict from contracts import contract from tmdp.sampled_mdp import SampledMDP __all__ = ['MDPBuilder'] class MDPBuilder(): @contract(start_dist='ddist') def __init__(self, start_dist): self._state2id = {} self._id2state = {} self._transitions = [] self.goals = set() self._start_dist = {} for state, p_state in start_dist.items(): self._start_dist[self._get_id(state)] = float(p_state) def _get_id(self, state): if state in self._state2id: return self._state2id[state] # print('not creating different IDs') # l = len(self._state2id) l = state self._state2id[state] = l self._id2state[l] = state return l def mark_goal(self, state): self.goals.add(self._get_id(state)) def add_state(self, state): pass def add_transition(self, state, action, state2, probability, reward): s1 = self._get_id(state) s2 = self._get_id(state2) t = (s1, action, s2, probability, reward) self._transitions.append(t) def get_sampled_mdp(self, goal_absorbing=True, stay=None): """ If goal_absorbing = True, all actions of the goal states give the same state. """ state2actions = defaultdict(lambda: set()) state2action2transition = defaultdict(lambda: defaultdict(lambda:{})) state2action2state2reward = \ defaultdict(lambda: defaultdict(lambda: defaultdict(lambda:{}))) # xXx: should be 0 # create states self.states = set() states = set() for s1 in self._id2state: states.add(s1) actions = set() for (s1, action, s2, p, reward) in self._transitions: actions.add(action) state2actions[s1].add(action) state2action2transition[s1][action][s2] = float(p) # += p state2action2state2reward[s1][action][s2] = reward # += p if goal_absorbing: if False: for g in self.goals: for a in actions: state2actions[g].add(a) # print('%10s %s' % (reward, (s1, action, s2))) state2action2transition[g][a][g] = 1.0 # print ('setting %s to 0 instead of %s' % # ((g, a, g), state2action2state2reward[g][a][g])) state2action2state2reward[g][a][g] = 0.0 else: # for each goal state, we reset to the start distribution assert isinstance(stay, float) for g in self.goals: for a in actions: state2actions[g].add(a) state2action2transition[g][a] = {} state2action2transition[g][a][g] = stay state2action2state2reward[g][a][g] = 0.0 for s0 in self._start_dist: x = self._start_dist[s0] * (1.0 - stay) state2action2transition[g][a][s0] = x state2action2state2reward[g][a][s0] = 0.0 mdp = SampledMDP(states=states, state2actions=state2actions, state2action2transition=state2action2transition, state2action2state2reward=state2action2state2reward, start_dist=self._start_dist, goals=self.goals) return mdp
[ "andrea@cds.caltech.edu" ]
andrea@cds.caltech.edu
f5d2df5f01ced18550aabed0aec4b75a5f07bb56
97f285b6f8016a8d1d2d675fffb771df3c9e37b9
/study/checkio/Electronic Station/largest_histogram.py
55dad59f2bd43ea949dc828d939a716654cfe3ff
[]
no_license
oskomorokhov/python
ef5408499840465d18852954aee9de460d0e7250
8909396c4200bd2fca19d3f216ed5f484fb2192a
refs/heads/master
2021-05-14T09:27:25.413163
2019-12-12T21:00:05
2019-12-12T21:00:05
116,327,306
0
0
null
null
null
null
UTF-8
Python
false
false
2,108
py
#!/usr/bin/env checkio --domain=py run largest-histogram # https://py.checkio.org/mission/largest-histogram/ # "Your power to choose can never be taken from you. # It can be neglected and it can be ignored. # But if used, it can make all the difference." # ― Steve Goodier # # You have a histogram. Try to find size of the biggest rectangle you can build out of the histogram bars. # # Input:List of all rectangles heights in histogram # # Output:Area of the biggest rectangle # # Example: # # # largest_histogram([5]) == 5 # largest_histogram([5, 3]) == 6 # largest_histogram([1, 1, 4, 1]) == 4 # largest_histogram([1, 1, 3, 1]) == 4 # largest_histogram([2, 1, 4, 5, 1, 3, 3]) == 8 # How it is used:There is no way the solution you come up with will be any useful in a real life. Just have some fun here. # # Precondition: # 0 < len(data) < 1000 # # # # END_DESC def largest_histogram(histogram): if len(histogram) == 1: return histogram[0] if len(set(histogram)) == 1: return sum(histogram) l = [] v_offset = 1 count = 0 while v_offset <= max(histogram): for i, b in enumerate(histogram): if b-v_offset >= 0: count += 1 else: l.append((v_offset, count)) count = 0 continue else: l.append((v_offset, count)) count = 0 v_offset += 1 return(max([x*i[n+1] for i in l for n, x in enumerate(i[:-1])])) if __name__ == "__main__": # These "asserts" using only for self-checking and not necessary for auto-testing #assert largest_histogram([5]) == 5, "one is always the biggest" #assert largest_histogram([5, 3]) == 6, "two are smallest X 2" #assert largest_histogram([1, 1, 4, 1]) == 4, "vertical" #assert largest_histogram([1, 1, 3, 1]) == 4, "horizontal" #assert largest_histogram([2, 1, 4, 5, 1, 3, 3]) == 8, "complex" #assert largest_histogram([0,1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1,0]) == False assert largest_histogram([2, 1, 4, 5, 1, 3, 3]) == 8 print("Done! Go check it!")
[ "oskom85@gmail.com" ]
oskom85@gmail.com
4016ca30ee6ed155a0c52f3a9303bb746026353c
4193a2c27d55bb9069680d624cbc223d9d2f5c0d
/gqlshop/gqlshop/wsgi.py
16f47a7aa220f67fe8b8ae6fb19e9844dca971a5
[]
no_license
r2d2-lex/graphql-example
fa517fb7daf9d6a9d779671a608be8980a5a8804
4405b70ccf171cb04e0cd4728c782be20b25e552
refs/heads/master
2022-12-23T23:44:28.325216
2020-10-07T19:14:03
2020-10-07T19:14:03
291,699,960
0
0
null
null
null
null
UTF-8
Python
false
false
391
py
""" WSGI config for gqlshop project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gqlshop.settings') application = get_wsgi_application()
[ "r2d2-lex@yandex.ru" ]
r2d2-lex@yandex.ru
3390e4dc6858eccf14bf91fb2b5b5710b7112ae2
8b23c09e4f0220a57273845a505c4f52a32c035f
/gallery/photogall/views.py
600419b8c721e57e67247ee696bbc5d2a3038c21
[]
no_license
MaryMbugua/PhotoGallery
ca89131211d55e1ad5cd5adb104605c76de2afc7
1c3a75c575d91a764c099092192f1c365a92899d
refs/heads/master
2020-03-15T12:32:48.993521
2018-05-10T09:57:14
2018-05-10T09:57:14
132,146,571
0
0
null
null
null
null
UTF-8
Python
false
false
290
py
from django.shortcuts import render from django.http import HttpResponse,Http404,HttpResponseRedirect from .models import Location,Category,Image # Create your views here. def landing(request): images = Image.get_image_by_id() return render(request,'index.html',{"images":images})
[ "marymbugua.nm@gmail.com" ]
marymbugua.nm@gmail.com
30fa2ca302469ae0002ea5b346973437ab8a20b7
b05b12abb6116440ded3862214c09d7ec7d007d7
/pin_is_touched.py
f71628c449def5e2bcf685a7f71810a97b9367ac
[]
no_license
cirosantilli/bbc-microbit-cheat
22713af05173757f0283316d53023f1db21e07cc
4e503a5e973851b8fe065fcb86f6be4731fee2cd
refs/heads/master
2021-07-16T04:42:39.000814
2016-10-24T21:44:09
2016-10-24T21:44:09
71,735,591
0
2
null
2021-02-24T16:33:55
2016-10-23T23:21:53
Python
UTF-8
Python
false
false
327
py
""" Check which electric connector pins are touched. You must also touch the GND pin at the same time to see anything. """ from microbit import * while True: val = 0 if pin0.is_touched(): val += 1 if pin1.is_touched(): val += 2 if pin2.is_touched(): val += 4 display.show(str(val))
[ "ciro.santilli@gmail.com" ]
ciro.santilli@gmail.com
6a240756c57303c77f96f2c2d6e05dec159770f6
f305f84ea6f721c2391300f0a60e21d2ce14f2a5
/6_tree/前缀树trie/好题/Ghost.py
2dc01dcb317b3e2726dc22fdb00ccba0a1a2dc4e
[]
no_license
981377660LMT/algorithm-study
f2ada3e6959338ae1bc21934a84f7314a8ecff82
7e79e26bb8f641868561b186e34c1127ed63c9e0
refs/heads/master
2023-09-01T18:26:16.525579
2023-09-01T12:21:58
2023-09-01T12:21:58
385,861,235
225
24
null
null
null
null
UTF-8
Python
false
false
1,153
py
from collections import defaultdict from typing import List # n ≤ 10,000 where n is the length of dictionary. # 两人轮流报的字符串必须是某个单词前缀,谁先报到整个单词谁输 # 问第一个玩家是否胜利,在两人都最好发挥下 class Solution: def solve(self, words: List[str]) -> int: def dfs(cur) -> bool: if "#" in cur: return False return not any(dfs(node) for node in cur.values()) # 队手报什么都不能赢 Trie = lambda: defaultdict(Trie) root = Trie() for w in words: cur = root for c in w: cur = cur[c] cur = cur["#"] return any(dfs(node) for node in root.values()) print(Solution().solve(words=["ghost", "ghostbuster", "gas"])) # Here is a sample game when dictionary is ["ghost", "ghostbuster", "gas"]: # Player 1: "g" # Player 2: "h" # Player 1: "o" # Player 2: "s" # Player 1: "t" [loses] # If player 2 had chosen "a" as the second letter, player 1 would still lose since they'd be forced to write the last letter "s".
[ "lmt2818088@gmail.com" ]
lmt2818088@gmail.com
13e1b504d533a70e45dfe026bb832bb026f4a5dd
38a028123c2b49590428f1369dae80c5f68d8f18
/pike/test_util.py
42609291af5f33efbf6b2f4ad1663dcceba09251
[ "MIT" ]
permissive
stevearc/python-pike
2412969768065b05fbde47abb68d281649382725
588fd5fae4da4a69f355279df10a3b4a41078ea2
refs/heads/master
2016-09-05T15:01:02.274490
2014-05-30T08:09:58
2014-05-30T08:09:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,128
py
""" Tests for pike.util """ import six import os from .test import BaseFileTest from pike import util, sqlitedict class TestFileMatch(BaseFileTest): """ Tests for recursive file glob matching """ def setUp(self): super(TestFileMatch, self).setUp() self.make_files( 'app.js', 'widget.js', 'common/util.js', 'common/api.js', 'shop/models.js', 'shop/util.js', ) def test_prefix(self): """ Can select files limited by directory prefix """ results = util.recursive_glob(self.tempdir, '*', 'common') self.assertItemsEqual(results, ['common/util.js', 'common/api.js']) def test_prefix_in_glob(self): """ Can embed a prefix inside the search glob """ results = util.recursive_glob(self.tempdir, 'common/*') self.assertItemsEqual(results, ['common/util.js', 'common/api.js']) def test_prefix_and_invert(self): """ Can both invert the match and provide a prefix """ results = util.recursive_glob(self.tempdir, '*.js:!common/*:!shop/*') self.assertItemsEqual(results, ['app.js', 'widget.js']) def test_match(self): """ Globs match filenames """ results = util.recursive_glob(self.tempdir, 'util.js') self.assertItemsEqual(results, ['common/util.js', 'shop/util.js']) def test_pathsep(self): """ Patterns can be separated by a ':' """ results = util.recursive_glob(self.tempdir, 'app.js:widget.js') self.assertEquals(results, ['app.js', 'widget.js']) def test_pattern_list(self): """ Patterns can be provided as a list """ results = util.recursive_glob(self.tempdir, ['app.js', 'widget.js']) self.assertEquals(results, ['app.js', 'widget.js']) def test_invert_match(self): """ Prefixing a glob with ! will remove matching elements """ results = util.recursive_glob(self.tempdir, 'app.js:!*.js') self.assertEquals(results, []) def test_dedupe(self): """ Results should not contain duplicates """ results = util.recursive_glob(self.tempdir, 'app.js:app.js') self.assertEquals(results, ['app.js']) class TestSqliteDict(BaseFileTest): """ Tests for sqlitedict """ def test_sqlitedict(self): """ Run a bunch of tests on sqlitedicts """ with sqlitedict.open() as d: self.assertEqual(list(d), []) self.assertEqual(len(d), 0) self.assertFalse(d) d['abc'] = 'rsvp' * 100 self.assertEqual(d['abc'], 'rsvp' * 100) self.assertEqual(len(d), 1) d['abc'] = 'lmno' self.assertEqual(d['abc'], 'lmno') self.assertEqual(len(d), 1) del d['abc'] self.assertFalse(d) self.assertEqual(len(d), 0) d['abc'] = 'lmno' d['xyz'] = 'pdq' self.assertEqual(len(d), 2) self.assertItemsEqual(list(six.iteritems(d)), [('abc', 'lmno'), ('xyz', 'pdq')]) self.assertItemsEqual(d.items(), [('abc', 'lmno'), ('xyz', 'pdq')]) self.assertItemsEqual(d.values(), ['lmno', 'pdq']) self.assertItemsEqual(d.keys(), ['abc', 'xyz']) self.assertItemsEqual(list(d), ['abc', 'xyz']) d.update(p='x', q='y', r='z') self.assertEqual(len(d), 5) self.assertItemsEqual(d.items(), [('abc', 'lmno'), ('xyz', 'pdq'), ('q', 'y'), ('p', 'x'), ('r', 'z')]) del d['abc'] try: d['abc'] except KeyError: pass else: assert False try: del d['abc'] except KeyError: pass else: assert False self.assertItemsEqual(list(d), ['xyz', 'q', 'p', 'r']) self.assertTrue(d) d.clear() self.assertFalse(d) self.assertEqual(list(d), []) d.update(p='x', q='y', r='z') self.assertItemsEqual(list(d), ['q', 'p', 'r']) d.clear() self.assertFalse(d) def test_file_persistence(self): """ Dict should be saved to a file """ with sqlitedict.open('test.db') as d: d['abc'] = 'def' with sqlitedict.open('test.db') as d: self.assertEqual(d['abc'], 'def') def test_flag_n(self): """ The 'n' flag will clear an existing database """ with sqlitedict.open('test.db', flag='n') as d: d['abc'] = 'def' with sqlitedict.open('test.db', flag='n') as d: self.assertFalse(d) def test_flag_w(self): """ The 'w' flag will clear existing table """ with sqlitedict.open('test.db', 'a') as d: d['abc'] = 'def' with sqlitedict.open('test.db', 'b') as d: d['abc'] = 'def' with sqlitedict.open('test.db', 'a', flag='w') as d: self.assertFalse(d) with sqlitedict.open('test.db', 'b') as d: self.assertEqual(d['abc'], 'def') def test_bad_flag(self): """ Passing a bad flag raises error """ with self.assertRaises(ValueError): sqlitedict.open(flag='g') def test_memory(self): """ in-memory databases do not create files """ with sqlitedict.open() as d: d['abc'] = 'def' self.assertEqual(os.listdir(os.curdir), []) self.assertEqual(os.listdir(os.curdir), []) def test_autocommit(self): """ When autocommit=True the db is automatically updated """ d1 = sqlitedict.open('test.db', autocommit=True) d2 = sqlitedict.open('test.db', autocommit=True) d1['abc'] = 'def' self.assertEqual(d2['abc'], 'def') def test_no_autocommit(self): """ When autocommit=False the db is updated when commit() is called """ d1 = sqlitedict.open('test.db', autocommit=False) d2 = sqlitedict.open('test.db', autocommit=False) d1['abc'] = 'def' self.assertFalse(d2) d1.commit() self.assertEqual(d2['abc'], 'def') def test_commit_after_close(self): """ Calling commit() after closing sqlitedict raises error """ d = sqlitedict.open() d.close() with self.assertRaises(IOError): d.commit() def test_close_calls_commit(self): """ If autocommit=False, closing sqlitedict automatically commits """ d1 = sqlitedict.open('test.db', autocommit=False) d2 = sqlitedict.open('test.db', autocommit=False) d1['abc'] = 'def' self.assertFalse(d2) d1.close() self.assertEqual(d2['abc'], 'def') def test_terminate(self): """ Calling terminate() removes database file """ with sqlitedict.open('test.db') as d: d['abc'] = 'def' d.terminate() self.assertFalse(os.path.exists('test.db'))
[ "stevearc@stevearc.com" ]
stevearc@stevearc.com
6dec4b41ccfe3eeec1c52bc3d20b4dd04b5ba518
1bf9f6b0ef85b6ccad8cb029703f89039f74cedc
/src/databox/azext_databox/_validators.py
a4339304141cb13037530ae3fa80a48739c595c6
[ "MIT", "LicenseRef-scancode-generic-cla" ]
permissive
VSChina/azure-cli-extensions
a1f4bf2ea4dc1b507618617e299263ad45213add
10b7bfef62cb080c74b1d59aadc4286bd9406841
refs/heads/master
2022-11-14T03:40:26.009692
2022-11-09T01:09:53
2022-11-09T01:09:53
199,810,654
4
2
MIT
2020-07-13T05:51:27
2019-07-31T08:10:50
Python
UTF-8
Python
false
false
3,935
py
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # pylint: disable=line-too-long from azure.cli.core.commands.client_factory import get_subscription_id from msrestazure.tools import resource_id def validate_create_input_parameters(cmd, namespace): _parse_storage_account_details(cmd, namespace) _parse_managed_disk_details(cmd, namespace) _validate_expected_data_size_for_databoxdisk(namespace) _validate_destination_account_details(namespace) def _parse_storage_account_details(cmd, namespace): """Parse storage account details for destination.""" from msrestazure.tools import is_valid_resource_id if not namespace.destination_account_details: namespace.destination_account_details = [] if namespace.storage_accounts: for storage_account in namespace.storage_accounts: if storage_account and not is_valid_resource_id(storage_account): storage_account = resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=namespace.resource_group_name, namespace='Microsoft.Storage', type='storageAccounts', name=storage_account ) if storage_account: storage_account_details = {'storage_account_id': storage_account, 'data_destination_type': 'StorageAccount'} namespace.destination_account_details.append(storage_account_details) del namespace.storage_accounts def _parse_managed_disk_details(cmd, namespace): """Parse managed disk details for destination.""" from msrestazure.tools import is_valid_resource_id if not namespace.destination_account_details: namespace.destination_account_details = [] subscription = get_subscription_id(cmd.cli_ctx) if namespace.staging_storage_account and not is_valid_resource_id(namespace.staging_storage_account): namespace.staging_storage_account = resource_id( subscription=subscription, resource_group=namespace.resource_group_name, namespace='Microsoft.Storage', type='storageAccounts', name=namespace.staging_storage_account ) if namespace.resource_group_for_managed_disk and not is_valid_resource_id( namespace.resource_group_for_managed_disk): namespace.resource_group_for_managed_disk = '/subscriptions/' + subscription + '/resourceGroups/' + namespace.resource_group_for_managed_disk if namespace.staging_storage_account and namespace.resource_group_for_managed_disk: managed_disk_details = {'staging_storage_account_id': namespace.staging_storage_account, 'resource_group_id': namespace.resource_group_for_managed_disk, 'data_destination_type': 'ManagedDisk'} namespace.destination_account_details.append(managed_disk_details) del namespace.staging_storage_account del namespace.resource_group_for_managed_disk def _validate_expected_data_size_for_databoxdisk(namespace): if namespace.sku == 'DataBoxDisk' and not namespace.expected_data_size: raise ValueError( "You must provide '--expected-data-size' when the 'sku' is 'DataBoxDisk'.") def _validate_destination_account_details(namespace): if not namespace.destination_account_details: raise ValueError( "You must provide at least one '--storage-account' or the combination of '--staging-storage-account' and " "'--resource-group-for-managed-disk'")
[ "noreply@github.com" ]
VSChina.noreply@github.com
4122aa86f674ce7e19064a2e472a1fb7a4326c1a
359f3d8a1a2b5524490c314a44d60cec1d06f658
/whoweb/campaigns/events.py
767989d855abd54f18cae6be04b6b6fcbe3b9002
[]
no_license
sivasuriyangithub/Merket_Intellect-s3.route
ec9d9aa7d4575d5ff8006e1454f69e4033193fc0
71a9ab642f9a31f4a318cebec7fe6a075870a83c
refs/heads/master
2023-08-25T13:51:02.116705
2021-10-19T01:06:49
2021-10-19T01:06:49
null
0
0
null
null
null
null
UTF-8
Python
false
false
323
py
PUBLISH_CAMPAIGN = 100, "Publishing Campaign." PUBLISH_DRIP_CAMPAIGN = 150, "Publishing Drip Campaign." PAUSE_CAMPAIGN = 300, "Pausing Campaign." RESUME_CAMPAIGN = 150, "Resuming Campaign." CAMPAIGN_SIGNATURES = 110, "Generated signatures for publishing campaign manager." ENQUEUED_FROM_ADMIN = 120, "Enqueued from Admin."
[ "zach@whoknows.com" ]
zach@whoknows.com
fad6d9954e6d45a6f1f6d6b53e441cbbf1dfdbd2
a6bb71f951c104ea9a3eb9d7a4ab413f45e84c5b
/aula48-ex01.py
af20f27cc7c9fed8872d8d98839f46245e52fe40
[]
no_license
romulorm/udemy-python
7e15621014c124190c18f3e67d6f6fa1f400e4d1
4a03ae860b9febad9f04bba0aabda211ccb0169d
refs/heads/master
2021-05-24T15:07:01.113977
2021-03-13T19:28:32
2021-03-13T19:28:32
253,619,683
0
0
null
null
null
null
UTF-8
Python
false
false
277
py
''' Crie uma função que exiba uma saudação com os parâmetros "saudação" e "nome". ''' def saudacao(msg='Olá', nome='usuário'): print(f'{msg}, {nome}.') # PROGRAMA PRINCIPAL saudacao('Boa noite', 'Leandro') saudacao('Boa tarde', 'Maria') saudacao('Hey', 'Joe')
[ "62728349+romulorm@users.noreply.github.com" ]
62728349+romulorm@users.noreply.github.com
2a697457b8a54b77ebffa2225054966f1aafc36f
62e58c051128baef9452e7e0eb0b5a83367add26
/x12/4041/434004041.py
58a9642917b1bb82347f7247422a5ead994c4d21
[]
no_license
dougvanhorn/bots-grammars
2eb6c0a6b5231c14a6faf194b932aa614809076c
09db18d9d9bd9d92cefbf00f1c0de1c590fe3d0d
refs/heads/master
2021-05-16T12:55:58.022904
2019-05-17T15:22:23
2019-05-17T15:22:23
105,274,633
0
0
null
2017-09-29T13:21:21
2017-09-29T13:21:21
null
UTF-8
Python
false
false
558
py
from bots.botsconfig import * from records004041 import recorddefs syntax = { 'version' : '00403', #version of ISA to send 'functionalgroup' : 'RJ', } structure = [ {ID: 'ST', MIN: 1, MAX: 1, LEVEL: [ {ID: 'BRR', MIN: 1, MAX: 1}, {ID: 'DTM', MIN: 1, MAX: 10}, {ID: 'N1', MIN: 1, MAX: 25, LEVEL: [ {ID: 'N2', MIN: 0, MAX: 1}, {ID: 'N3', MIN: 0, MAX: 2}, {ID: 'N4', MIN: 0, MAX: 1}, {ID: 'PER', MIN: 0, MAX: 1}, ]}, {ID: 'SE', MIN: 1, MAX: 1}, ]} ]
[ "jason.capriotti@gmail.com" ]
jason.capriotti@gmail.com
4628f1a901997ee1e00f6288b3b18bed3cca60c5
9172bc5c472a89e62444bfb164689d23fb8f1549
/zh_spider/spiders/example.py
60a25b86eb028eccfa6f54a893c9e692b7fe3b1e
[ "Apache-2.0" ]
permissive
szqh97/zspider
74bde989cb3b83384bbe6b4abaeafaac90f02946
204bf44fb6de74f122a8678c8141d2743ef9706e
refs/heads/master
2021-01-10T03:15:54.088548
2016-01-05T06:27:27
2016-01-05T06:27:27
48,946,129
0
0
null
null
null
null
UTF-8
Python
false
false
2,030
py
# -*- coding: utf-8 -*- """ TODO """ import scrapy from scrapy.http.request import Request class example(scrapy.Spider): """ This is a zhihu user crawler spider """ name = "example" allowed_domains = ["https://zhihu.com"] start_urls = ( 'https://www.zhihu.com/people/excited-vczh', #'https://www.zhihu.com/people/excited-vczh/followees', ) cookie = '_za=345605f6-eefa-4af6-a945-f2b790d12061; _ga=GA1.2.322499337.1436092356; q_c1=4b1955e3c8aa45ba930b1f40abe7c4ca|1449306839000|1436092370000; z_c0="QUFEQTVjMGVBQUFYQUFBQVlRSlZUVGl2clZieTl6NmN1Z19JX0oxczJubWh0QmIyRGoxRjRnPT0=|1451631160|c67789a061fac4d814e558bf5e0964e398efa6e4"; __utma=51854390.322499337.1436092356.1451631139.1451637264.14; __utmz=51854390.1451637264.14.8.utmcsr=zhihu.com|utmccn=(referral)|utmcmd=referral|utmcct=/people/excited-vczh/followees; __utmv=51854390.100-1|2=registration_date=20131007=1^3=entry_date=20131007=1; _xsrf=3130d2c61e1c6d68615d5046fa9d1714; cap_id="YThhNjgyNmUxYzYxNDJkM2JmNjk1MzU5OGVhNzA5NjE=|1451631135|c1a47afe58d0fdbcba7f0f524ca913809b709b79"; __utmc=51854390', headers = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8','Accept-Encoding': 'gzip, deflate", 'Accept-Language': 'en-US,en;q=0.5', 'Connection': 'keep-alive', 'Cookie': cookie, 'Host': 'www.zhihu.com', 'Referer': 'https://www.zhihu.com/people/szqh97/followees', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0' } def start_requests(self): for url in self.start_urls: yield Request(url, headers=self.headers, callback = self.parse_first_request) def parse(self, response): print response.body pass def parse_first_request(self, response): print response.body self._xsrf = response.xpath('//input[@name="_xsrf"]').xpath("@value").extract()[0] print 'kkkkkkkk', self._xsrf
[ "szqh97@163.com" ]
szqh97@163.com
debf561cc18693e3e094f31b1cb9df8a948b1a11
163fe2b466f3f2b5f3f9f218f3252f2cf78afa65
/begoodPlus/pages/context_processors.py
019c457fb3419b411ba317f3d83ac69ffcfaa6bf
[]
no_license
nhrnhr0/BeGoodPlus3
ec711952efcb267f4a9e72b0fb6e370ef5fea04c
8acead88ccba6d7427b945a7eb98562922d39cd9
refs/heads/master
2023-07-30T15:03:41.524737
2021-09-26T10:16:04
2021-09-26T10:16:04
349,965,663
0
0
null
2021-06-15T06:32:39
2021-03-21T10:34:15
JavaScript
UTF-8
Python
false
false
224
py
from catalogAlbum.models import CatalogAlbum from django.conf import settings def navbar_load(request): albums = CatalogAlbum.objects.all() return {'albums': albums, 'domain': settings.MY_DOMAIN, }
[ "ronionsegal@gmail.com" ]
ronionsegal@gmail.com
df0718ed19926840558ee2e12230c01ad56baf3d
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/otherforms/_repents.py
93675035cf55791d81d47ce5ead5081fe5e2a5b8
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
222
py
#calss header class _REPENTS(): def __init__(self,): self.name = "REPENTS" self.definitions = repent self.parents = [] self.childen = [] self.properties = [] self.jsondata = {} self.basic = ['repent']
[ "xingwang1991@gmail.com" ]
xingwang1991@gmail.com
cfbb894dced5120522fc3ed37442e6412c55cbb1
2a1ce1846dc4430f22c0f07c1d52ce8f0affde62
/mobi/wsgi.py
aa06d265a04f585da3cdf7e33a778c5f4de0f144
[]
no_license
Belie06Loryn/MobiCashChallenge
e8708cf475b39722f35540a850eac1adc20cfaac
58144494160e3dada66374131b317a11a0d5b0e1
refs/heads/master
2022-11-27T16:50:53.613486
2020-05-14T08:05:14
2020-05-14T08:05:14
236,824,658
0
0
null
2022-11-22T04:57:48
2020-01-28T19:41:51
Python
UTF-8
Python
false
false
386
py
""" WSGI config for mobi project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mobi.settings") application = get_wsgi_application()
[ "maniralexie@gmail.com" ]
maniralexie@gmail.com
f597058f292cdfbdc5b9f20f0197c632bca897be
487ce91881032c1de16e35ed8bc187d6034205f7
/codes/CodeJamCrawler/16_0_1_neat/16_0_1_mesksr_Counting Sheep.py
c3235f1be7a672b4553acacad7c7fb910a20c4d0
[]
no_license
DaHuO/Supergraph
9cd26d8c5a081803015d93cf5f2674009e92ef7e
c88059dc66297af577ad2b8afa4e0ac0ad622915
refs/heads/master
2021-06-14T16:07:52.405091
2016-08-21T13:39:13
2016-08-21T13:39:13
49,829,508
2
0
null
2021-03-19T21:55:46
2016-01-17T18:23:00
Python
UTF-8
Python
false
false
412
py
for t in xrange(int(raw_input())): print "Case #"+str(t+1)+":", n = int(raw_input()) if (n==0): print 'INSOMNIA' continue c = [False]*10 i = 1 while(i): temp = n*i #print temp, while(temp>0): c[temp%10]=True temp = temp/10 flag = 1 for j in range(10): if (c[j]==False): #print n*i, c i+=1 flag = 0 break if (flag==1): break print i*n
[ "[dhuo@tcd.ie]" ]
[dhuo@tcd.ie]
b4f1975b22f360941d3c806c66a92cd130121e85
6f4e925bf4538d104f1e3e9754d4297c5504ab80
/python/recall/app/core/filelib.py
4e63aad8618229b0a6bd6f71d4079d4b5bfecad2
[ "MIT" ]
permissive
kingreatwill/openself
7f02282da3e0b1f328c3627d83ba2b5ed4563dc8
8517d24e665b39371835ecd2ed0cd3509a5d9d62
refs/heads/master
2023-01-23T13:15:49.491402
2020-11-19T02:39:52
2020-11-19T02:39:52
null
0
0
null
null
null
null
UTF-8
Python
false
false
875
py
import hashlib import magic # pip install python-magic-bin # pip install python-magic def __sha1(f): sha1obj = hashlib.sha1() sha1obj.update(f.read()) return sha1obj.hexdigest() def __md5(f): md5obj = hashlib.md5() md5obj.update(f.read()) return md5obj.hexdigest() # 一定要是rb def sha1(file): if isinstance(file, str): with open(file, 'rb') as f: return __sha1(f) result = __sha1(file) file.seek(0) return result # 一定要是rb def md5(file): if isinstance(file, str): with open(file, 'rb') as f: return __md5(f) result = __md5(file) file.seek(0) return result f = magic.Magic(mime=True, uncompress=True) def mime(file): if isinstance(file, str): return f.from_file(file) buff = file.read(2048) file.seek(0) return f.from_buffer(buff)
[ "kingreatwill@qq.com" ]
kingreatwill@qq.com
20377d1afff2b99076cac037dae5436eae9bc44d
6a609bc67d6a271c1bd26885ce90b3332995143c
/exercises/binary-tree/lowest_common_ancester_of_a_binary_tree.py
a97468a75332c15acab7e46d66420ce78c3968f5
[]
no_license
nahgnaw/data-structure
1c38b3f7e4953462c5c46310b53912a6e3bced9b
18ed31a3edf20a3e5a0b7a0b56acca5b98939693
refs/heads/master
2020-04-05T18:33:46.321909
2016-07-29T21:14:12
2016-07-29T21:14:12
44,650,911
0
0
null
null
null
null
UTF-8
Python
false
false
2,239
py
# -*- coding: utf-8 -*- """ Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).” _______3______ / \ ___5__ ___1__ / \ / \ 6 _2 0 8 / \ 7 4 For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ if root in [None, p, q]: return root left, right = (self.lowestCommonAncestor(child, p, q) for child in (root.left, root.right)) return root if left and right else left or right def lowestCommonAncestor2(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ if root is None: return None # Find out all the parent-child pair above (including) p and q. stack = [root] parents = {root: None} while p not in parents or q not in parents: node = stack.pop() if node.left is not None: stack.append(node.left) parents[node.left] = node if node.right is not None: stack.append(node.right) parents[node.right] = node # Get all the ancestors of p. ancestors = set() while p: ancestors.add(p) p = parents[p] # Match q's ancestors. while q not in ancestors: q = parents[q] return q
[ "wanghan15@gmail.com" ]
wanghan15@gmail.com
5dcc87d0ce772cdb6f82fc8e7f36c35aeffb7ffe
062376f05b517606c0257d4855d8d93d482137c1
/tests/c/test_rand.py
0a2c3c11f7ed4dde5c6e0710061033828e451c38
[ "Apache-2.0" ]
permissive
exarkun/opentls
7047a68ce48c7d9c7aa67458693f7406a4ce60a9
cc651c597164b26a3dab2b9dd90dd375554ea74c
refs/heads/master
2021-01-15T21:09:49.086756
2013-05-28T12:14:11
2013-05-28T12:14:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,811
py
"""Test RAND API The objective is to test the API wrapper, not the underlying random number generators. The tests implemented were derived from John D Cook's chapter in 'Beautiful Testing' titled 'How to test a random number generator'. http://www.johndcook.com/blog/2010/12/06/how-to-test-a-random-number-generator-2/ """ from __future__ import absolute_import, division, print_function import ctypes import math import random try: import unittest2 as unittest except ImportError: import unittest from tls.c import api def cumulative_average(average=0.0, samples=0.0): """Generator to keep track of the current cummulative moving average. To use: >>> average = cumulative_average() >>> average.send(None) >>> for value in [1, 2, 3, 4]: ... mean = average.send(value) ... print mean 2.5 The function arguments `average` and `samples` can be used to set the cumulative average's initial state. http://en.wikipedia.org/wiki/Moving_average#Cumulative_moving_average """ cma = average cnt = samples while True: new = yield cma cnt += 1.0 cma = cma + (new - cma) / cnt class RandTests(object): def test_range(self): """Test extremes of valid range for random values has been generated. The probability of failure is less than 0.005e-17 for 10000 samples. """ low = min(self.data) high = max(self.data) self.assertEqual(high, 255) self.assertEqual(low, 0) def test_median(self): """Test that the median is "close" to the expected mean.""" sorted_ = sorted(self.data) median = sorted_[self.samples // 2] self.assertAlmostEqual(median, 127.5, delta=5.0) def test_mean(self): """Test the actual mean is "close" to the expected mean.""" average = cumulative_average() average.send(None) for value in self.data: mean = average.send(value) self.assertAlmostEqual(mean, 127.5, delta=3.0) def test_variance(self): """Test the variance is "close" to the expected mean.""" expected_mean = 255 // 2 average = cumulative_average() average.send(None) for value in self.data: deviation_squared = (value - expected_mean) ** 2 variance = average.send(deviation_squared) expected_variance = (expected_mean // 2) ** 2 self.assertAlmostEqual(variance, expected_variance, delta=expected_variance // 2) def test_buckets(self): """Test the distribution of values across the range.""" counts = {} for value in self.data: counts[value] = 1 + counts.get(value, 0) for value, count in counts.items(): self.assertGreater(count, 0) self.assertLess(count, 2.0 * (self.samples / 255.0)) def test_kolmogorov_smirnov(self): """Apply the Kolmogorov-Smirnov goodness-of-fit function. Range values for K+ sourced from 'Beautiful Testing' """ samples = 1e3 counts = {} for num, value in enumerate(self.data): if num >= samples: break for x in range(value + 1): counts[x] = 1 + counts.get(x, 0) empirical = [counts.get(i,0) / samples for i in range(256)] theoretical = [1.0 - (x / 255.0) for x in range(256)] kplus = math.sqrt(samples) * max(empirical[i] - theoretical[i] for i in range(256)) self.assertGreaterEqual(kplus, 0.07089) self.assertLessEqual(kplus, 1.5174) #kminus = math.sqrt(samples) * max(theoretical[i] - empirical[i] for i in range(256)) #self.assertGreaterEqual(kminus, 0.07089) #self.assertLessEqual(kminus, 1.5174) class TestPRNG(unittest.TestCase, RandTests): """Test OpenSSL's pseudo random number generator""" samples = int(1e4) data = api.new('unsigned char[]', samples) @classmethod def setUpClass(cls): if not api.RAND_status(): api.RAND_load_file(b"/dev/urandom", 1024) api.RAND_pseudo_bytes(api.cast('unsigned char*', cls.data), cls.samples) def setUp(self): self.assertTrue(api.RAND_status()) class TestCryptoRNG(unittest.TestCase, RandTests): """Test OpenSSL's crytographically valid random data""" samples = int(1e4) data = api.new('unsigned char[]', samples) @classmethod def setUpClass(cls): api.RAND_bytes(api.cast('unsigned char*', cls.data), cls.samples) class TestPyRandom(unittest.TestCase, RandTests): """Test Python's Mersenne Twister implementation""" samples = int(1e4) @classmethod def setUpClass(cls): cls.data = [random.randint(0, 255) for i in range(cls.samples)]
[ "aaron.iles@gmail.com" ]
aaron.iles@gmail.com
52bbc6eb71c3b869b7e93c49b39012fbc7bcf6d7
4dc31dd8bfd10945f7a5fee31f30c2e634b0534e
/clark_wright.py
6687d2af2ef4aac6506b4f9eb43d76d106c12b74
[]
no_license
cfld/clark_wright
9b89201e1bde33ca9a89cedaaa45bf123578d3ec
c67019c7fa72d3218c1d598968c3c5983277ffa7
refs/heads/master
2022-11-05T05:42:48.484236
2020-06-16T03:33:48
2020-06-16T03:33:48
245,242,814
1
0
null
null
null
null
UTF-8
Python
false
false
4,452
py
class CW: def __init__(self, edges, D_depot, demand, cap): self.edges = edges self.D_depot = D_depot self.demand = demand self.cap = cap self.visited = set([]) self.boundary = set([]) self.routes = {} self.node2route = {} self.route_idx = 0 def _new_route(self, src, dst): load = self.demand[src] + self.demand[dst] cost = self.D_depot[src] + self.edges[(src, dst)] + self.D_depot[dst] if load > self.cap: return self.visited.add(src) self.visited.add(dst) self.boundary.add(src) self.boundary.add(dst) self.node2route[src] = self.route_idx self.node2route[dst] = self.route_idx self.routes[self.route_idx] = { "idx" : self.route_idx, "nodes" : [src, dst], "load" : load, "cost" : cost, } self.route_idx += 1 def _extend_route(self, a, b): r = self.routes[self.node2route[a]] new_load = r['load'] + self.demand[b] new_cost = r['cost'] + self.edges[(a, b)] + self.D_depot[b] - self.D_depot[a] if new_load > self.cap: return self.visited.add(b) self.boundary.remove(a) self.boundary.add(b) if r['nodes'][0] == a: r['nodes'].insert(0, b) elif r['nodes'][-1] == a: r['nodes'].append(b) else: raise Exception('not in right position') r['load'] = new_load r['cost'] = new_cost self.node2route[b] = r['idx'] def _merge_route(self, src, dst): r_src = self.routes[self.node2route[src]] r_dst = self.routes[self.node2route[dst]] new_load = r_src['load'] + r_dst['load'] new_cost = r_src['cost'] + r_dst['cost'] + self.edges[(src, dst)] - self.D_depot[src] - self.D_depot[dst] if new_load > self.cap: return self.boundary.remove(src) self.boundary.remove(dst) # reverse direction to fit if r_src['nodes'][-1] != src: r_src['nodes'] = r_src['nodes'][::-1] if r_dst['nodes'][0] != dst: r_dst['nodes'] = r_dst['nodes'][::-1] del self.routes[self.node2route[src]] del self.routes[self.node2route[dst]] r = { "idx" : self.route_idx, "nodes" : r_src['nodes'] + r_dst['nodes'], "load" : new_load, "cost" : new_cost, } for n in r['nodes']: self.node2route[n] = self.route_idx self.routes[self.route_idx] = r self.route_idx += 1 def _fix_unvisited(self): # fix customers that haven't been visited for n in range(self.demand.shape[0]): if n not in self.visited: routes[self.route_idx] = { "idx" : self.route_idx, "nodes" : [n], "load" : self.demand[n], "cost" : 2 * self.D_depot[n], } self.route_idx += 1 def run(self): for (src, dst) in self.edges.keys(): src_visited = src in self.visited dst_visited = dst in self.visited src_boundary = src in self.boundary dst_boundary = dst in self.boundary if src > dst: pass if src_visited and not src_boundary: pass elif dst_visited and not dst_boundary: pass elif not src_visited and not dst_visited: self._new_route(src, dst) elif src_boundary and not dst_visited: self._extend_route(src, dst) elif dst_boundary and not src_visited: self._extend_route(dst, src) elif src_boundary and dst_boundary and (self.node2route[src] != self.node2route[dst]): self._merge_route(src, dst) else: pass self._fix_unvisited() return self.routes
[ "bkj.322@gmail.com" ]
bkj.322@gmail.com
8c9398d7e075b0b3b7ea6961cd9ea1db72ad4eb3
51f887286aa3bd2c3dbe4c616ad306ce08976441
/pybind/slxos/v17r_2_00/brocade_mpls_rpc/show_mpls_interface_detail/__init__.py
8d04b38e68d2ceaf5dd2047baec812b4a502c53c
[ "Apache-2.0" ]
permissive
b2220333/pybind
a8c06460fd66a97a78c243bf144488eb88d7732a
44c467e71b2b425be63867aba6e6fa28b2cfe7fb
refs/heads/master
2020-03-18T09:09:29.574226
2018-04-03T20:09:50
2018-04-03T20:09:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,377
py
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from decimal import Decimal from bitarray import bitarray import __builtin__ import output class show_mpls_interface_detail(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module brocade-mpls - based on the path /brocade_mpls_rpc/show-mpls-interface-detail. Each member element of the container is represented as a class variable - with a specific YANG type. """ __slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__output',) _yang_name = 'show-mpls-interface-detail' _rest_name = 'show-mpls-interface-detail' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): path_helper_ = kwargs.pop("path_helper", None) if path_helper_ is False: self._path_helper = False elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper): self._path_helper = path_helper_ elif hasattr(self, "_parent"): path_helper_ = getattr(self._parent, "_path_helper", False) self._path_helper = path_helper_ else: self._path_helper = False extmethods = kwargs.pop("extmethods", None) if extmethods is False: self._extmethods = False elif extmethods is not None and isinstance(extmethods, dict): self._extmethods = extmethods elif hasattr(self, "_parent"): extmethods = getattr(self._parent, "_extmethods", None) self._extmethods = extmethods else: self._extmethods = False self.__output = YANGDynClass(base=output.output, is_leaf=True, yang_name="output", rest_name="output", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions=None, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='output', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return [u'brocade_mpls_rpc', u'show-mpls-interface-detail'] def _rest_path(self): if hasattr(self, "_parent"): if self._rest_name: return self._parent._rest_path()+[self._rest_name] else: return self._parent._rest_path() else: return [u'show-mpls-interface-detail'] def _get_output(self): """ Getter method for output, mapped from YANG variable /brocade_mpls_rpc/show_mpls_interface_detail/output (output) """ return self.__output def _set_output(self, v, load=False): """ Setter method for output, mapped from YANG variable /brocade_mpls_rpc/show_mpls_interface_detail/output (output) If this variable is read-only (config: false) in the source YANG file, then _set_output is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_output() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=output.output, is_leaf=True, yang_name="output", rest_name="output", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions=None, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='output', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """output must be of a type compatible with output""", 'defined-type': "brocade-mpls:output", 'generated-type': """YANGDynClass(base=output.output, is_leaf=True, yang_name="output", rest_name="output", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions=None, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='output', is_config=True)""", }) self.__output = t if hasattr(self, '_set'): self._set() def _unset_output(self): self.__output = YANGDynClass(base=output.output, is_leaf=True, yang_name="output", rest_name="output", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions=None, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='output', is_config=True) output = __builtin__.property(_get_output, _set_output) _pyangbind_elements = {'output': output, }
[ "badaniya@brocade.com" ]
badaniya@brocade.com
83571e8f8f52a978baf403abc8e05e2ae13a9d0c
72983931fd4b2408399281e01f146e6cd8c38bc4
/tests/test_transducer.py
8a78c678aeaebb5b657621b10c589a3c417094ec
[ "Apache-2.0", "Python-2.0" ]
permissive
templeblock/TiramisuASR
3a356a4b72d22a9463f9a9ff8801c39a7d88f0ba
55b1789d956a6d1821b0ebb9ba53fc41e0fda9c2
refs/heads/master
2022-11-26T14:30:21.247362
2020-08-09T07:16:07
2020-08-09T07:16:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,845
py
# Copyright 2020 Huy Le Nguyen (@usimarit) # # 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 tensorflow as tf from tiramisu_asr.models.transducer import Transducer from tiramisu_asr.featurizers.text_featurizers import TextFeaturizer from tiramisu_asr.featurizers.speech_featurizers import TFSpeechFeaturizer, read_raw_audio from tiramisu_asr.utils.utils import merge_features_to_channels text_featurizer = TextFeaturizer({ "vocabulary": None, "blank_at_zero": True, "beam_width": 5, "norm_score": True }) speech_featurizer = TFSpeechFeaturizer({ "sample_rate": 16000, "frame_ms": 25, "stride_ms": 10, "num_feature_bins": 80, "feature_type": "logfbank", "preemphasis": 0.97, # "delta": True, # "delta_delta": True, "normalize_signal": True, "normalize_feature": True, "normalize_per_feature": False, # "pitch": False, }) inp = tf.keras.Input(shape=[None, 80, 1]) enc = merge_features_to_channels(inp) enc = tf.keras.layers.LSTM(350, return_sequences=True)(enc) enc_model = tf.keras.Model(inputs=inp, outputs=enc) model = Transducer( encoder=enc_model, blank=0, vocabulary_size=text_featurizer.num_classes, embed_dim=350, embed_dropout=0.0, num_lstms=1, lstm_units=320, joint_dim=1024 ) model._build([1, 50, 80, 1]) model.summary(line_length=100) model.save_weights("/tmp/transducer.h5") model.add_featurizers( speech_featurizer=speech_featurizer, text_featurizer=text_featurizer ) features = tf.random.normal(shape=[5, 50, 80, 1], stddev=127., mean=247.) hyps = model.recognize(features) print(hyps) signal = read_raw_audio("/home/nlhuy/Desktop/test/11003.wav", speech_featurizer.sample_rate) # hyps = model.recognize_tflite(signal) # # print(hyps) # hyps = model.recognize_beam(tf.expand_dims(speech_featurizer.tf_extract(signal), 0)) print(hyps) # hyps = model.recognize_beam_tflite(signal) # # print(hyps.numpy().decode("utf-8")) # concrete_func = model.recognize_tflite.get_concrete_function() converter = tf.lite.TFLiteConverter.from_concrete_functions( [concrete_func] ) converter.experimental_new_converter = True converter.optimizations = [tf.lite.Optimize.DEFAULT] converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS] converter.convert()
[ "nlhuy.cs.16@gmail.com" ]
nlhuy.cs.16@gmail.com
1de76da91028d525dbb288656b3b8acce8276384
b18b01b32e67433a6e749e2aae48fb69bcfc42f9
/titanic-kaggle-competition/pipeline-components/logisticregression/regression.py
727696deb98b29a16ba65e63a26725e66584d214
[ "Apache-2.0" ]
permissive
kubeflow/examples
f83c920cb94b32f0271103afb74b3efaaae35b41
40cba72b522ca6879672dca24398973c8f0ef32d
refs/heads/master
2023-09-01T20:39:26.577041
2023-08-05T16:51:33
2023-08-05T16:51:33
119,894,375
1,375
813
Apache-2.0
2023-08-30T14:40:56
2018-02-01T21:13:10
Jsonnet
UTF-8
Python
false
false
1,199
py
import numpy as np import pandas as pd # import seaborn as sns from matplotlib import pyplot as plt from matplotlib import style import argparse from sklearn import linear_model from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import Perceptron from sklearn.linear_model import SGDClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.naive_bayes import GaussianNB def regression(train_pickle, train_label): train_df = pd.read_pickle(train_pickle) train_labels = pd.read_pickle(train_label) logreg = LogisticRegression(solver='lbfgs', max_iter=110) logreg.fit(train_df, train_labels) acc_log = round(logreg.score(train_df, train_labels) * 100, 2) print('acc_log', acc_log) with open('regression_acc.txt', 'a') as f: f.write(str(acc_log)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--train_pickle') parser.add_argument('--train_label') args = parser.parse_args() regression(args.train_pickle, args.train_label)
[ "noreply@github.com" ]
kubeflow.noreply@github.com
14364c67317679c69633bfef740873388273e709
e74187c3ccb41042fe35953f081e90f671aca9a4
/src/103_train_lgbm1.py
4aac2c6c8e5f10f3353a47bdcdd42a5cccc70bed
[]
no_license
lockbro/KDD-Cup-2019
1d2bef17ecc4e164c26f4d18b5233889e559d18e
07bc25eb5a4d9ec33aa9b90fd1ef56de6da89f9d
refs/heads/master
2021-04-23T17:26:20.559648
2019-08-09T11:51:22
2019-08-09T11:51:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,061
py
import gc import json import lightgbm as lgb import matplotlib.pyplot as plt import numpy as np import os import pandas as pd import seaborn as sns import sys import time import warnings from contextlib import contextmanager from glob import glob from sklearn.metrics import f1_score from sklearn.model_selection import KFold, StratifiedKFold from tqdm import tqdm from utils import line_notify, loadpkl, eval_f, save2pkl from utils import NUM_FOLDS, FEATS_EXCLUDED, CAT_COLS #============================================================================== # Traing LightGBM (city 1) #============================================================================== warnings.filterwarnings('ignore') @contextmanager def timer(title): t0 = time.time() yield print("{} - done in {:.0f}s".format(title, time.time() - t0)) # Display/plot feature importance def display_importances(feature_importance_df_, outputpath, csv_outputpath): cols = feature_importance_df_[["feature", "importance"]].groupby("feature").mean().sort_values(by="importance", ascending=False)[:40].index best_features = feature_importance_df_.loc[feature_importance_df_.feature.isin(cols)] # for checking all importance _feature_importance_df_=feature_importance_df_.groupby('feature').sum() _feature_importance_df_.to_csv(csv_outputpath) plt.figure(figsize=(8, 10)) sns.barplot(x="importance", y="feature", data=best_features.sort_values(by="importance", ascending=False)) plt.title('LightGBM Features (avg over folds)') plt.tight_layout() plt.savefig(outputpath) # LightGBM GBDT with KFold or Stratified KFold def kfold_lightgbm(train_df,test_df,num_folds,stratified=False,debug=False): print("Starting LightGBM. Train shape: {}, test shape: {}".format(train_df.shape, test_df.shape)) # Cross validation model if stratified: folds = StratifiedKFold(n_splits= num_folds, shuffle=True, random_state=326) else: folds = KFold(n_splits= num_folds, shuffle=True, random_state=326) # Create arrays and dataframes to store results oof_preds = np.zeros((train_df.shape[0],12)) sub_preds = np.zeros((test_df.shape[0],12)) feature_importance_df = pd.DataFrame() feats = [f for f in train_df.columns if f not in FEATS_EXCLUDED] # k-fold for n_fold, (train_idx, valid_idx) in enumerate(folds.split(train_df[feats], train_df['click_mode'])): train_x, train_y = train_df[feats].iloc[train_idx], train_df['click_mode'].iloc[train_idx] valid_x, valid_y = train_df[feats].iloc[valid_idx], train_df['click_mode'].iloc[valid_idx] # set data structure lgb_train = lgb.Dataset(train_x, label=train_y, categorical_feature=CAT_COLS, free_raw_data=False) lgb_test = lgb.Dataset(valid_x, label=valid_y, categorical_feature=CAT_COLS, free_raw_data=False) # params params ={ 'device' : 'gpu', 'task': 'train', 'boosting': 'gbdt', 'objective': 'multiclass', 'metric': 'multiclass', 'learning_rate': 0.01, 'num_class': 12, 'num_leaves': 52, 'colsample_bytree': 0.3490457769968177, 'subsample': 0.543646263362097, 'max_depth': 11, 'reg_alpha': 4.762312990232561, 'reg_lambda': 9.98131082276387, 'min_split_gain': 0.19161156850826594, 'min_child_weight': 15.042054927368088, 'min_data_in_leaf': 17, 'verbose': -1, 'seed':int(2**n_fold), 'bagging_seed':int(2**n_fold), 'drop_seed':int(2**n_fold) } clf = lgb.train( params, lgb_train, valid_sets=[lgb_train, lgb_test], valid_names=['train', 'test'], # feval=eval_f, num_boost_round=10000, early_stopping_rounds= 200, verbose_eval=100 ) # save model clf.save_model('../output/lgbm_1_{}.txt'.format(n_fold)) oof_preds[valid_idx] = clf.predict(valid_x, num_iteration=clf.best_iteration) sub_preds += clf.predict(test_df[feats], num_iteration=clf.best_iteration) / folds.n_splits fold_importance_df = pd.DataFrame() fold_importance_df["feature"] = feats fold_importance_df["importance"] = np.log1p(clf.feature_importance(importance_type='gain', iteration=clf.best_iteration)) fold_importance_df["fold"] = n_fold + 1 feature_importance_df = pd.concat([feature_importance_df, fold_importance_df], axis=0) print('Fold %2d F1 Score : %.6f' % (n_fold + 1, f1_score(valid_y,np.argmax(oof_preds[valid_idx],axis=1),average='weighted'))) del clf, train_x, train_y, valid_x, valid_y gc.collect() # Full F1 Score & LINE Notify full_f1 = f1_score(train_df['click_mode'], np.argmax(oof_preds,axis=1),average='weighted') print('Full F1 Score %.6f' % full_f1) line_notify('Full F1 Score %.6f' % full_f1) # display importances display_importances(feature_importance_df, '../imp/lgbm_importances_1.png', '../imp/feature_importance_lgbm_1.csv') if not debug: # save prediction for submit test_df['recommend_mode'] = np.argmax(sub_preds, axis=1) test_df = test_df.reset_index() # post processing test_df['recommend_mode'][(test_df['plan_num_plans']==1)&(test_df['recommend_mode']!=0)] = test_df['plan_0_transport_mode'][(test_df['plan_num_plans']==1)&(test_df['recommend_mode']!=0)] # save csv test_df[['sid','recommend_mode']].to_csv(submission_file_name, index=False) # save out of fold prediction train_df.loc[:,'recommend_mode'] = np.argmax(oof_preds, axis=1) train_df = train_df.reset_index() train_df[['sid','click_mode','recommend_mode']].to_csv(oof_file_name, index=False) # save prediction for submit sub_preds = pd.DataFrame(sub_preds) sub_preds.columns = ['pred_lgbm_plans{}'.format(c) for c in sub_preds.columns] sub_preds['sid'] = test_df['sid'] sub_preds['click_mode'] = test_df['click_mode'] # save out of fold prediction oof_preds = pd.DataFrame(oof_preds) oof_preds.columns = ['pred_lgbm_plans{}'.format(c) for c in oof_preds.columns] oof_preds['sid'] = train_df['sid'] oof_preds['click_mode'] = train_df['click_mode'] # merge df = oof_preds.append(sub_preds) # save as pkl save2pkl('../features/lgbm_pred_1.pkl', df) line_notify('{} finished.'.format(sys.argv[0])) def main(debug=False): with timer("Load Datasets"): # load feathers files = sorted(glob('../features/feats1/*.feather')) df = pd.concat([pd.read_feather(f) for f in tqdm(files, mininterval=60)], axis=1) # use selected features df = df[configs['features']] # set card_id as index df.set_index('sid', inplace=True) # split train & test train_df = df[df['click_mode'].notnull()] test_df = df[df['click_mode'].isnull()] del df gc.collect() if debug: train_df=train_df.iloc[:1000] with timer("Run LightGBM with kfold"): kfold_lightgbm(train_df, test_df, num_folds=NUM_FOLDS, stratified=True, debug=debug) if __name__ == "__main__": submission_file_name = "../output/submission_lgbm_1.csv" oof_file_name = "../output/oof_lgbm_1.csv" configs = json.load(open('../configs/103_lgbm.json')) with timer("Full model run"): main(debug=False)
[ "fujiwara52jp@gmail.com" ]
fujiwara52jp@gmail.com
1b30a149581d0b5b8db7a100fe659f0611e29ef0
73d150e0b7de927948f89aa604537b312c69ef4d
/books/migrations/0006_set_start_end_page.py
3542211e8232b7d5b3b7eabc8f906c44f0d3e612
[]
no_license
nonZero/Hagadot
f7090f1348a1dac10e095c5d7bde9700b7241680
cd1735c1c1167c91efd8201ac84d863ada3373fc
refs/heads/master
2021-04-25T05:49:20.213406
2018-04-26T12:24:12
2018-04-26T12:24:12
113,889,523
0
2
null
2021-03-18T20:33:32
2017-12-11T17:41:47
Python
UTF-8
Python
false
false
566
py
# Generated by Django 2.0.4 on 2018-04-09 21:55 from django.db import migrations from django.db.models import F def forwards(apps, schema_editor): Book = apps.get_model("books", "Book") db_alias = schema_editor.connection.alias m = Book.objects.using(db_alias) m.filter(start_page=None).update(start_page=1) m.filter(end_page=None).update(end_page=F('num_pages')) class Migration(migrations.Migration): dependencies = [ ('books', '0005_auto_20180409_2147'), ] operations = [ migrations.RunPython(forwards) ]
[ "udioron@gmail.com" ]
udioron@gmail.com
33dc3dfc91acdf0546b4037e41f01b34a182023c
ffeacff13af906bf5e7a02018a2543902f5dc8ef
/01-Python核心编程/代码/01-Python基础入门/02-变量.py
7bc1c7bc22e85be68c5320b18334c3329a42044d
[ "MIT" ]
permissive
alikslee/Python-itheima-2019
457080ee83d0f5f7eaba426da0ea86405d2d5248
691035d5ff0e362139c7dbe82f730ec0e060fd2e
refs/heads/main
2023-01-01T16:27:20.062463
2020-10-22T16:20:29
2020-10-22T16:20:29
305,959,901
1
0
null
null
null
null
UTF-8
Python
false
false
275
py
""" 1. 定义变量 语法:变量名 = 值 2. 使用变量 3. 看变量的特点 """ # 定义变量:存储数据TOM my_name = 'TOM' print(my_name) # 定义变量:存储数据 黑马程序员 schoolName = '我是黑马程序员,我爱Python' print(schoolName)
[ "lee079074256@gmail.com" ]
lee079074256@gmail.com
9d0128dc70eb0120c6494ed71e98e88372a65f88
add5790098575fc81f774605944a682c7b301b2a
/scripts/chaos.py
4206aab19593cd518631462d0e19aadb3ba05638
[]
no_license
firemark/python-interpreters-benchmark
85135df95568866527a7cfadea3a26d62f6baad2
eb0c7ec3153579010c1e215f6030a0fc9f39dd91
refs/heads/master
2016-09-06T11:47:54.585586
2015-08-23T23:06:22
2015-08-23T23:06:22
35,060,200
0
0
null
null
null
null
UTF-8
Python
false
false
824
py
#from https://gist.github.com/aliles/1087520#file-chaos-py "Logistic map iteration timing" from itertools import islice import time def logistic_map(r, x): assert r > 0, 'R must be a positive number' assert 0 < x < 1, 'X must be a number between 0 and 1' while True: x = r * x * (1 - x) yield x if __name__ == '__main__': times = [] minimum = float("inf") maximum = float("-inf") iterator = logistic_map(3.65, 0.01) for loop in xrange(15): start = time.clock() for x in islice(iterator, 500): minimum = min(minimum, x) maximum = max(maximum, x) stop = time.clock() times.append(stop - start) print "Iteration times" print ",".join(str(i * 10**3) for i in times) print "X range" print minimum, maximum
[ "marpiechula@gmail.com" ]
marpiechula@gmail.com
9a88300c76be9816dc8f4201016a2df5e67a2647
fe5200ebd83028745f646643a086b144a54b5bbe
/source/chap7/files/graphdfs.py
a644ec6b83042855ab3813d3913ab69936d2979f
[]
no_license
kentdlee/CS2Plus
7561220fd43b611f62a9fdc25b86ae731aa35de9
2056f47a6c9e7c0d3f25a093011c3bb84c909a2f
refs/heads/master
2023-01-27T22:03:33.116038
2023-01-19T03:58:49
2023-01-19T03:58:49
228,526,240
3
4
null
2023-01-19T00:47:25
2019-12-17T03:36:30
HTML
UTF-8
Python
false
false
7,224
py
from xml.dom import minidom import turtle import math from xml.dom import minidom import turtle def drawArrow(turtle): x1 = turtle.xcor() y1 = turtle.ycor() turtle.right(180) turtle.forward(8) turtle.left(90) turtle.forward(3) x2 = turtle.xcor() y2 = turtle.ycor() turtle.backward(6) x3 = turtle.xcor() y3 = turtle.ycor() turtle.begin_fill() turtle.goto(x1,y1) turtle.goto(x2,y2) turtle.goto(x3,y3) turtle.end_fill() class Vertex: def __init__(self,vertexId,x,y,label): self.vertexId = vertexId self.x = x self.y = y self.label = int(label) self.edges = [] self.previous = None self.previousEdge = None def draw(self,turtle,color="white"): x = self.x y = self.y turtle.penup() turtle.goto(x,y-20) turtle.pendown() turtle.color("black") turtle.fillcolor(color) turtle.begin_fill() turtle.circle(20) turtle.end_fill() turtle.penup() turtle.goto(x+2,y+12) turtle.write(self.label,align="center",font=("Arial",12,"bold")) def __str__(self): return "Vertex: " + "\n label: " + str(self.label) + "\n id: " + str(self.vertexId) + "\n x: " + str(self.x) + "\n y: " + str(self.y) class Edge: def __init__(self,v1,v2,weight=0): self.v1 = v1 self.v2 = v2 self.weight = weight def __lt__(self,other): return self.weight < other.weight def __str__(self): return "Edge: " + "\n v1: " + str(self.v1) + "\n v2: " + str(self.v2) def draw(self,turtle,vertexDict,color="grey",width=1): turtle.color(color) turtle.width(width) x1 = float(vertexDict[self.v1].x) y1 = float(vertexDict[self.v1].y) x2 = float(vertexDict[self.v2].x) y2 = float(vertexDict[self.v2].y) x = x1-x2 y = y1-y2 d = math.sqrt(y**2 + x**2) angle = (math.acos(x/d)/math.pi)*180 if y1 < y2: angle = angle + 2 * (180-angle) turtle.penup() turtle.goto(x2,y2) turtle.pendown() turtle.color(color) turtle.setheading(angle) turtle.penup() turtle.forward(0) turtle.pendown() turtle.forward(d-20) drawArrow(turtle) turtle.width(1) if self.weight != 0: x = (x1 + x2) / 2 y = (y1 + y2) / 2 turtle.penup() turtle.goto(x+1,y+12) turtle.color("black") turtle.write(str(self.weight),align="center",font=("Arial",12,"bold")) turtle.setheading(0) def minCost(unvisited,vertexDict): minVal = infinity minId = -1 for ident in unvisited: if vertexDict[ident].cost < minVal: minId = ident minVal = vertexDict[ident].cost return minId def main(): xmldoc = minidom.parse("neiowagraph.xml") graph = xmldoc.getElementsByTagName("Graph")[0] vertices = graph.getElementsByTagName("Vertices")[0].getElementsByTagName("Vertex") edges = graph.getElementsByTagName("Edges")[0].getElementsByTagName("Edge") width = float(graph.attributes["width"].value) height = float(graph.attributes["height"].value) turtle.setup(0.65*width,0.65*height) t = turtle.Turtle() screen = t.getscreen() screen.setworldcoordinates(0,height,width,0) screen.title("A Weighted, Directed Graph") screen.tracer(0) t.speed(100) t.ht() vertexDict = {} vCount = 0 for vertex in vertices: vertexId = int(vertex.attributes["vertexId"].value) x = float(vertex.attributes["x"].value) y = float(vertex.attributes["y"].value) label = vertex.attributes["label"].value v = Vertex(vertexId, x, y, label) vertexDict[vertexId] = v vCount += 1 edgeList = [] for edgeNode in edges: edge = Edge(int(edgeNode.attributes["head"].value), int(edgeNode.attributes["tail"].value)) if "weight" in edgeNode.attributes: edge.weight = float(edgeNode.attributes["weight"].value) vertexDict[edge.v2].edges.append(edge) edgeList.append(edge) for edge in edgeList: edge.draw(t,vertexDict) for vertexId in vertexDict: vertex = vertexDict[vertexId] vertex.draw(t,(0.8,1,0.4)) # Run Depth First Search visited = [] stack = [] target = vertexDict[9] for ident in vertexDict: vertex = vertexDict[ident] if vertex.label == 0: source = vertex stack.append(source) found = False while (len(stack) > 0) and not found: current = stack.pop() print(current) visited.append(current.vertexId) if current.vertexId == target.vertexId: found = True else: for edge in current.edges: vId = edge.v1 vertex = vertexDict[vId] vertex.previous = current if not vId in visited: stack.append(vertex) if found: print("Found target") current = target while current.vertexId != source.vertexId: next = current current = current.previous print("Coloring edge:", current) for edge in current.edges: if edge.v1 == next.vertexId: print("found edge: ", edge) edge.draw(t,vertexDict,"blue",2) ## Run Dijkstra's Algorithm #previous = list(range(30)) #visited = [] #source.cost = 0 #unvisited = [source.vertexId] #while len(unvisited) > 0: #currentId = minCost(unvisited,vertexDict) #current = vertexDict[currentId] #print("Examining: ", current) #visited.append(currentId) #unvisited.remove(currentId) #for edge in current.edges: #if edge.v1 == currentId: #adjacentId = edge.v2 #else: #adjacentId = edge.v1 #if not adjacentId in visited: #adjacent = vertexDict[adjacentId] #if current.cost + edge.weight < adjacent.cost: #adjacent.cost = current.cost + edge.weight #adjacent.previous = currentId #adjacent.previousEdge = edge #if not adjacentId in unvisited: #unvisited.append(adjacentId) #for vertexId in vertexDict: #vertex = vertexDict[vertexId] #if vertex.previousEdge != None: #vertex.previousEdge.draw(t,vertexDict,"purple",2) for vertexId in vertexDict: vertex = vertexDict[vertexId] vertex.draw(t,(0.8,1,0.4)) #vertex.drawCost(t,"orange") screen.update() screen.exitonclick() if __name__ == "__main__": main()
[ "kentdlee@gmail.com" ]
kentdlee@gmail.com
cc44e29031cd48478c4008a214d3ab556eb48bc9
acff427a36d6340486ff747ae9e52f05a4b027f2
/main/multimedia/misc/gd/actions.py
042228023565d91f338fabc969069644018d6479
[]
no_license
jeremie1112/pisilinux
8f5a03212de0c1b2453132dd879d8c1556bb4ff7
d0643b537d78208174a4eeb5effeb9cb63c2ef4f
refs/heads/master
2020-03-31T10:12:21.253540
2018-10-08T18:53:50
2018-10-08T18:53:50
152,126,584
2
1
null
2018-10-08T18:24:17
2018-10-08T18:24:17
null
UTF-8
Python
false
false
790
py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Licensed under the GNU General Public License, version 3. # See the file http://www.gnu.org/licenses/gpl.txt from pisi.actionsapi import autotools from pisi.actionsapi import pisitools from pisi.actionsapi import shelltools from pisi.actionsapi import get def setup(): shelltools.system("./bootstrap.sh") autotools.configure("--disable-static \ --with-fontconfig \ --with-png \ --with-freetype \ --with-jpeg \ --without-xpm") def build(): autotools.make() def install(): autotools.rawInstall("DESTDIR=%s" % get.installDIR()) pisitools.dohtml(".") pisitools.dodoc("COPYING", "README*")
[ "erkanisik@yahoo.com" ]
erkanisik@yahoo.com
0b6fc9ada6e11aede244fdf4656ba71c235dc6d2
e1efc8e0b0e4629dea61504fbc816c0527691bd9
/19.操作系统/6-计算机组成.py
599824c990306f94405ce44162e609db550b9291
[]
no_license
xiongmengmeng/xmind-technology
2bb67a0bf92cfd660cac01f8ab3a2454423ccba5
e2fdb6987ef805a65f0a4feb52d84383853f4b77
refs/heads/main
2023-07-31T07:10:29.868120
2021-09-11T08:18:17
2021-09-11T08:18:17
307,636,242
3
1
null
null
null
null
UTF-8
Python
false
false
3,463
py
import os,sys parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0,parentdir) import xmind xmind_name="操作系统" w = xmind.load(os.path.dirname(os.path.abspath(__file__))+"\\"+xmind_name+".xmind") s2=w.createSheet() s2.setTitle("计算机组成") r2=s2.getRootTopic() r2.setTitle("计算机组成") content={ '操作系统提供了几种抽象模型':[ {'文件':[ '对I/O设备的抽象' ]}, {'虚拟内存':[ '对程序存储器的抽象' ]}, {'进程':[ '对一个正在运行程序的抽象' ]}, {'虚拟机':[ '对整个操作系统的抽象' ]} ], '计算机系统组成':[ {'硬件':[ '芯片、电路板、磁盘、键盘、显示器' ]}, {'操作系统':[ '为用户层和硬件提供各自的接口,屏蔽了不同应用和硬件之间的差异,达到统一标准的作用' ]}, '软件' ], '计算机的两种运行模式':[ {'内核态':[ '操作系统具有硬件的访问权,可以执行机器能够运行的任何指令', '软件中最基础的部分是操作系统,运行在内核态中' ]}, {'用户态':[ '软件的其余部分运行在用户态下' ]} ], '计算机硬件(五部分)':[ {'运算器':[ '功能:对数据和信息进行加工和运算' '组成:算数逻辑单元+寄存器', '基本运算包括加、减、乘、除、移位等操作' ]}, {'控制器':[ '功能:按照指定顺序改变主电路或控制电路的部件,控制命令执行', '组成:程序计数器、指令寄存器、解码译码器' ]}, {'存储器':[ '保存信息', {'两种':[ {'主存(内存):':[ '一个临时存储设备,CPU 主要交互对象', '物理组成上说:内存是由一系列 DRAM(dynamic random access memory) 动态随机存储构成的集合', '逻辑上说:内存是一个线性的字节数组,有它唯一的地址编号,从0开始' ]}, '外存:硬盘软盘' ]} ]}, {'输入设备':[ '给计算机获取外部信息的设备', '组成:键盘和鼠标' ]}, {'输出设备':[ '给用户呈现根据输入设备获取的信息经过一系列的计算后得到显示的设备', '组成:显示器、打印机' ]}, {'注':[ {'处理器(Processor)/CPU(central processing unit)':[ '运算器+控制器', '解释(并执行)存储在主存储器中的指令的引擎' ]}, {'I/O设备':[ '系统和外部世界的连接', {'四类':[ '用于用户输入的键盘', '用于用户输入的鼠标', '用于用户输出的显示器', '磁盘驱动:用来长时间的保存数据和程序,刚开始的时候,可执行程序就保存在磁盘上', ]} ]}, ]} ], '计算机硬件(其它)':[ {'总线(Buses)':[ '在组件之间来回传输字节信息,通常被设计成传送定长(4或8字节)的字节块' ]}, {'控制器(controller) /适配器(Adapter)':[ 'I/O设备连接I/O总线' ]} ] } #构建xmind xmind.build(content,r2) #保存xmind xmind.save(w,os.path.dirname(os.path.abspath(__file__))+"\\"+xmind_name+".xmind")
[ "xiongmengmeng@qipeipu.com" ]
xiongmengmeng@qipeipu.com
152a6146d2345f4c3caf0ae61e212e199ced1eb1
34f3cfeac7fd5a7bbbc5e362bef8bc316f81c1d0
/examples/hello_world.py
a949333bb699c9d60f65578b4953d65ee7b47ca1
[ "MIT" ]
permissive
eerimoq/asn1tools
860b3623955c12dfb9763ff4e20a805beb7436ba
de25657f7c79100d1ba5312dd7474ff3e0d0ad2e
refs/heads/master
2023-03-16T09:28:11.924274
2023-03-10T20:24:34
2023-03-10T20:24:34
99,156,277
272
98
MIT
2023-01-03T13:40:36
2017-08-02T20:05:05
Python
UTF-8
Python
false
false
758
py
#!/usr/bin/env python """The asn1tools hello world example. Example execution: $ ./hello_world.py Message: {'number': 2, 'text': 'Hi!'} Encoded: 010203486921 Decoded: {'number': 2, 'text': 'Hi!'} $ """ from __future__ import print_function from binascii import hexlify import asn1tools SPECIFICATION = ''' HelloWorld DEFINITIONS ::= BEGIN Message ::= SEQUENCE { number INTEGER, text UTF8String } END ''' hello_world = asn1tools.compile_string(SPECIFICATION, 'uper') message = {'number': 2, 'text': u'Hi!'} encoded = hello_world.encode('Message', message) decoded = hello_world.decode('Message', encoded) print('Message:', message) print('Encoded:', hexlify(encoded).decode('ascii')) print('Decoded:', decoded)
[ "erik.moqvist@gmail.com" ]
erik.moqvist@gmail.com
fc48e39bb0aee373153cef35813f955f5833f74f
1aa6e732645f4603c05a1c9262f6fbb1af76b056
/patchinfo/Sample.py
cf14f4943aea03a06512c40ef63dc666be04ea36
[]
no_license
nauddin257/DualBootPatcher
f2831bdc72d8f94787a1d3ad94d0d85103316dd5
024af7ecb38ba6b4e3f1ae16ab81e32cd213864f
refs/heads/master
2020-12-11T07:26:46.916515
2013-11-14T03:54:41
2013-11-14T03:54:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,179
py
# This file describes the ROM/Kernel/etc with the following information: # - Pattern in file name # - Patch to use # - Type of ramdisk (if any) # - Message to display to user # # Please copy this file to a new one before editing. from fileinfo import FileInfo import re file_info = FileInfo() # This is the regular expression for detecting a ROM using the filename. Here # are some basic rules for how regex's work: # Pattern | Meaning # ----------------------------------------------- # ^ | Beginning of filename # $ | End of filename # . | Any character # \. | Period # [a-z] | Lowercase English letters # [a-zA-Z] | All English letters # [0-9] | Numbers # * | 0 or more of previous pattern # + | 1 or more of previous pattern # We'll use the SuperSU zip as an example. # # Filename: UPDATE-SuperSU-v1.65.zip # Pattern: ^UPDATE-SuperSU-v[0-9\.]+\.zip$ # # So, when we go patch a file, if we see "UPDATE-SuperSU-v" at the beginning, # followed by 1 or more of either numbers or a period and then ".zip", then we # know it's a SuperSU zip. Of course, a simpler pattern like ^.*SuperSU.*\.zip$ # would work just as well. filename_regex = r"^.*SuperSU.*\.zip$" # This is the type of ramdisk. Run the 'list-ramdisks' file in the useful/ # folder to see what choices are available. (It's pretty obvious, you'll see) file_info.ramdisk = 'jflte/AOSP/AOSP.def' # If the zip file you're patching does not have a kernel, set this to false. file_info.has_boot_image = True # If the boot image has a different name or is in a subfolder, change this. file_info.bootimg = 'boot.img' # This is the patch file you generated. Just copy the patch into a subfolder in # patches/ and put the path here. file_info.patch = 'jflte/AOSP/YourROM.patch' def print_message(): # This is the message that is shown if the file to be patched is this one. print("Detected The Name of Some ROM") ### def matches(filename): if re.search(filename_regex, filename): return True else: return False def get_file_info(): return file_info
[ "chenxiaolong@cxl.epac.to" ]
chenxiaolong@cxl.epac.to
d513893828bbf80619ff10477ea3f18b0cdf6215
cc578cec7c485e2c1060fd075ccc08eb18124345
/cs15211/PerfectSquares.py
f097d8aa0569feaba85550e5a0ea219fa94bdfa0
[ "Apache-2.0" ]
permissive
JulyKikuAkita/PythonPrac
18e36bfad934a6112f727b4906a5e4b784182354
0ba027d9b8bc7c80bc89ce2da3543ce7a49a403c
refs/heads/master
2021-01-21T16:49:01.482561
2019-02-07T06:15:29
2019-02-07T06:15:29
91,907,704
1
1
Apache-2.0
2019-02-07T06:15:30
2017-05-20T18:12:53
Python
UTF-8
Python
false
false
6,693
py
__source__ = 'https://leetcode.com/problems/perfect-squares/' # https://github.com/kamyu104/LeetCode/blob/master/Python/perfect-squares.py # Time: O(n * sqrt(n)) # Space: O(n) # # Description: Leetcode # 279. Perfect Squares # # Given a positive integer n, find the least number of perfect # square numbers (for example, 1, 4, 9, 16, ...) which sum to n. # # For example, given n = 12, return 3 because 12 = 4 + 4 + 4; # given n = 13, return 2 because 13 = 4 + 9. # # Companies # Google # Related Topics # Math Dynamic Programming Breadth-first Search # Similar Questions # Count Primes Ugly Number II # #dp # http://bookshadow.com/weblog/2015/09/09/leetcode-perfect-squares/ # O(n * sqrt n) # @Not getting dp yet import unittest class Solution(object): _num = [0] def numSquares(self, n): """ :type n: int :rtype: int """ num = self._num while len(num) <= n: num += min(num[-i*i] for i in xrange(1, int(len(num)**0.5+1))) + 1, #print num return num[n] #Recursion class Solution2(object): def numSquares(self, n): """ :type n: int :rtype: in """ num, a, b, res = 2, 0, 0, n while num * num <= n: a = n / (num * num) b = n % (num * num) res = min(res, a + self.numSquares(b)) num += 1 return res # Lagrange's Four-Square Theorem # http://bookshadow.com/weblog/2015/09/09/leetcode-perfect-squares/ # O (sqrt n ) import math class Solution3(object): def numSquares(self, n): """ :type n: int :rtype: in """ while n % 4 == 0: n /= 4 if n % 8 == 7: return 4 a = 0 while a*a <= n: b = math.sqrt( n - a * a) if ( a*a + b*b == n): return ~~a + ~~b # no logical expression in python break a += 1 return 3 class SolutionDFS(object): def __init__(self): self.cnt = 0xF7777777 def numSquares(self, n): """ :type n: int :rtype: int """ if n <= 0: return 0 if n == 1: return 1 self.dfs(n, 0, [], 1) return self.cnt def dfs(self, n, sum, tmp, idx): if sum > n or idx * idx > n : return if sum == n: self.cnt = min(self.cnt, len(tmp)) return while idx * idx <= n: tmp.append(idx) self.dfs(n, sum + idx * idx, tmp, idx) tmp.pop() idx += 1 print tmp, idx, self.cnt, sum class SolutionDP(object): def numSquares(self, n): """ :type n: int :rtype: int """ if n <= 0: return 0 if n == 1: return 1 dp = [ 0xF7777777 for i in xrange(n+1)] for i in xrange(n): if i * i <= n: dp[i * i] = 1 for i in xrange(n+1): for j in xrange(1, n - i): if j * j + i <= n: dp[ j * j + i ] = min(dp[ j * j + i ], dp[i] + 1) return dp[n] class TestMethods(unittest.TestCase): def test_Local(self): self.assertEqual(1, 1) #print Solution().numSquares(12) #print Solution2().numSquares(12) print Solution3().numSquares(12) print SolutionDFS().numSquares(10) if __name__ == '__main__': unittest.main() Java = ''' # Thought: # dp[n] indicates that the perfect squares count of the given n, and we have: dp[0] = 0 dp[1] = dp[0]+1 = 1 dp[2] = dp[1]+1 = 2 dp[3] = dp[2]+1 = 3 dp[4] = Min{ dp[4-1*1]+1, dp[4-2*2]+1 } = Min{ dp[3]+1, dp[0]+1 } = 1 dp[5] = Min{ dp[5-1*1]+1, dp[5-2*2]+1 } = Min{ dp[4]+1, dp[1]+1 } = 2 . . . dp[13] = Min{ dp[13-1*1]+1, dp[13-2*2]+1, dp[13-3*3]+1 } = Min{ dp[12]+1, dp[9]+1, dp[4]+1 } = 2 . . . dp[n] = Min{ dp[n - i*i] + 1 }, n - i*i >=0 && i >= 1 # 15ms 97.04% class Solution { public int numSquares(int n) { int[] dp = new int[n + 1]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; int cur = 0; for (int j = 1; (cur = j * j) <= n; j++) { for (int i = cur; i <= n; i++) { dp[i] = Math.min(dp[i], dp[i - cur] + 1); } } return dp[n]; } } #Note dp arr for n = 5 will be: 0, MAX, MAX, MAX, MAX, MAX 0, 1 , MAX, MAX, MAX, MAX 0, 1, 2, MAX, MAX, MAX 0, 1, 2, 3, MAX, MAX 0, 1, 2, 3, 4, , MAX 0, 1, 2, 3, 4, 2 # Recurstion case: # dp[n] = Math.min(dp[n], dp[n - i*i] + 1 ), n - i*i >=0 && i >= 1 # 21ms 94.70% class Solution { public int numSquares(int n) { int[] dp = new int[n + 1]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; for (int i = 1; i * i <= n ;i++) { int cur = i * i; for (int j = cur; j <= n; j++) { dp[j] = Math.min(dp[j], dp[j - cur] + 1); } } return dp[n]; } } 3.Mathematical Solution # 1ms 100% class Solution { public int numSquares(int n) { //base case if(n < 4) return n; // If n is a perfect square, return 1. if (isSquare(n)) return 1; // The result is 4 if and only if n can be written in the // form of 4^k*(8*m + 7). Please refer to // Legendre's three-square theorem. while ((n & 3) == 0) { // n % 4 == 0 n >>= 2; } if ((n & 7) == 7) { // n % 8 == 7 return 4; } // Check whether 2 is the result. int sqrtN = (int)(Math.sqrt(n)); for(int i = 1; i <= sqrtN; i++) { if (isSquare(n - i * i)) return 2; } return 3; } public boolean isSquare(int n) { int sqrtN = (int)Math.sqrt(n); return sqrtN * sqrtN == n; } } //https://www.cnblogs.com/grandyang/p/4800552.html //there are only 4 possible result 1,2,3,4 //check if a * a + b * b == n # 98.70% 2ms class Solution { public int numSquares(int n) { //base case if (n < 4) return n; // The result is 4 if and only if n can be written in the // form of 4^k*(8*m + 7). // Legendre's three-square theorem. while (n % 4 == 0) n /= 4; //to make it smaller if (n % 8 == 7) return 4; int a, b; for (int i = 0; i < n; i++) { a = i; b = (int) Math.sqrt(n - a * a); if (a * a + b * b == n) //perfect square -> a or b == 0 return a == 0 || b == 0 ? 1 : 2; } return 3; } } '''
[ "b92701105@gmail.com" ]
b92701105@gmail.com
0b5ca29eaae9763b72fa05cf02e3700b7b140027
0912be54934d2ac5022c85151479a1460afcd570
/Ch02_Code/GUI_tabbed_two_mighty.py
96aa5a91f4e767b625a86a078a5ffa0a9a25fa21
[ "MIT" ]
permissive
actuarial-tools/Python-GUI-Programming-Cookbook-Third-Edition
6d9d155663dda4450d0b180f43bab46c24d18d09
8c9fc4b3bff8eeeda7f18381faf33c19e98a14fe
refs/heads/master
2023-01-31T13:11:34.315477
2020-12-15T08:21:06
2020-12-15T08:21:06
null
0
0
null
null
null
null
UTF-8
Python
false
false
989
py
''' Created on May 1, 2019 @author: Burkhard A. Meier ''' #====================== # imports #====================== import tkinter as tk from tkinter import ttk # Create instance win = tk.Tk() # Add a title win.title("Python GUI") tabControl = ttk.Notebook(win) # Create Tab Control tab1 = ttk.Frame(tabControl) # Create a tab tabControl.add(tab1, text='Tab 1') # Add the tab tab2 = ttk.Frame(tabControl) # Add a second tab tabControl.add(tab2, text='Tab 2') # Make second tab visible tabControl.pack(expand=1, fill="both") # Pack to make visible # LabelFrame using tab1 as the parent mighty = ttk.LabelFrame(tab1, text=' Mighty Python ') mighty.grid(column=0, row=0, padx=8, pady=4) # Label using mighty as the parent a_label = ttk.Label(mighty, text="Enter a name:") a_label.grid(column=0, row=0, sticky='W') #====================== # Start GUI #====================== win.mainloop()
[ "noreply@github.com" ]
actuarial-tools.noreply@github.com
509fcbdd523fa11e40a849845f97193b811db41c
8d2a124753905fb0455f624b7c76792c32fac070
/pytnon-month01/month01-shibw-notes/day15-shibw/project/student_system/usl.py
4ad416702de887a3725f0e5f9c0bd4ae8cdd8769
[]
no_license
Jeremy277/exercise
f38e4f19aae074c804d265f6a1c49709fd2cae15
a72dd82eb2424e4ae18e2f3e9cc66fc4762ec8fa
refs/heads/master
2020-07-27T09:14:00.286145
2019-09-17T11:31:44
2019-09-17T11:31:44
209,041,629
0
0
null
null
null
null
UTF-8
Python
false
false
2,952
py
from project.student_system.bll import StudentManagerController from project.student_system.model import StudentModel class StudentManagerView: def __init__(self): self.__manager = StudentManagerController() def __display_menu(self): print('+---------------------+') print('| 1)添加学生信息 |') print('| 2)显示学生信息 |') print('| 3)删除学生信息 |') print('| 4)修改学生信息 |') print('| 5)按照成绩升序排序 |') print('+---------------------+') def __select_menu(self): option = input('请输入:') if option == '1': self.__input_students() elif option == '2': self.__output_students(self.__manager.stu_list) elif option == '3': self.__delete_student() elif option == '4': self.__modify_student() elif option == '5': self.__output_student_by_socre() def main(self): ''' 界面入口 :return: ''' while True: self.__display_menu() self.__select_menu() # 输入学生__input_students def __input_students(self): #收集学生信息 #要求输入 姓名 年龄 成绩 #创建学生对象(姓名 年龄 成绩) #去控制器找add_student方法 name = input('请输入学生姓名:') age = int(input('请输入学生年龄:')) score = int(input('请输入学生成绩:')) stu = StudentModel(name,age,score) self.__manager.add_student(stu) # 输出学生__output_students def __output_students(self,list): for item in list: print(item.name,item.age,item.score,item.id) # 删除学生__delete_student def __delete_student(self): #需要用户输入学生id #调用管理器对象的删除学生方法 #如果结果为True 显示删除成功 #否则显示删除失败 id = int(input('请输入要删除学生的编号:')) if self.__manager.remove_student(id): print('删除成功') else: print('删除失败') #修改学生信息__modify_student def __modify_student(self): #收集用户输入的信息保存到对象 #调用管理器的修改学生的方法 id = int(input('请输入要修改学生的编号:')) name = input('请输入新的学生姓名:') age = int(input('请输入新的学生年龄:')) score = int(input('请输入新的学生成绩:')) stu = StudentModel(name,age,score,id) if self.__manager.update_student(stu): print('修改成功') else: print('修改失败') def __output_student_by_socre(self): self.__manager.order_by_score() self.__output_students(self.__manager.stu_list)
[ "13572093824@163.com" ]
13572093824@163.com
78d406860f54317f57d41d8f3bdb89b4bed931b9
a46d135ba8fd7bd40f0b7d7a96c72be446025719
/packages/python/plotly/plotly/validators/cone/colorbar/_thicknessmode.py
780825a965633045eb793b2aedd2476e4bbd835e
[ "MIT" ]
permissive
hugovk/plotly.py
5e763fe96f225d964c4fcd1dea79dbefa50b4692
cfad7862594b35965c0e000813bd7805e8494a5b
refs/heads/master
2022-05-10T12:17:38.797994
2021-12-21T03:49:19
2021-12-21T03:49:19
234,146,634
0
0
MIT
2020-01-15T18:33:43
2020-01-15T18:33:41
null
UTF-8
Python
false
false
508
py
import _plotly_utils.basevalidators class ThicknessmodeValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="thicknessmode", parent_name="cone.colorbar", **kwargs ): super(ThicknessmodeValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), values=kwargs.pop("values", ["fraction", "pixels"]), **kwargs )
[ "noreply@github.com" ]
hugovk.noreply@github.com
831330dcefafc3860800291775c941a2014c0554
f1cb02057956e12c352a8df4ad935d56cb2426d5
/LeetCode/1426. Counting Elements/Solution.py
d1562d8f530d1dc240ef0657eef54bb2fb1ca1c0
[]
no_license
nhatsmrt/AlgorithmPractice
191a6d816d98342d723e2ab740e9a7ac7beac4ac
f27ba208b97ed2d92b4c059848cc60f6b90ce75e
refs/heads/master
2023-06-10T18:28:45.876046
2023-05-26T07:46:42
2023-05-26T07:47:10
147,932,664
15
2
null
null
null
null
UTF-8
Python
false
false
310
py
from collections import Counter class Solution: def countElements(self, arr: List[int]) -> int: cnter = Counter() for num in arr: cnter[num] += 1 ret = 0 for num in cnter: if num + 1 in cnter: ret += cnter[num] return ret
[ "nhatsmrt@uw.edu" ]
nhatsmrt@uw.edu
4941db21d1801a4b32c8b425abfa53ba39a2daf7
0e7aed5eef2e1d132a7e75dd8f439ae76c87639c
/python/99_recovery_binary_search_tree.py
f33ff8d9a0ddc717ee9257ba29adfbe15bb56a73
[ "MIT" ]
permissive
liaison/LeetCode
2a93df3b3ca46b34f922acdbc612a3bba2d34307
bf03743a3676ca9a8c107f92cf3858b6887d0308
refs/heads/master
2022-09-05T15:04:19.661298
2022-08-19T19:29:19
2022-08-19T19:29:19
52,914,957
17
4
null
null
null
null
UTF-8
Python
false
false
2,097
py
# 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 recoverTree(self, root: Optional[TreeNode]) -> None: """ Do not return anything, modify root in-place instead. """ first_switch, second_switch = None, None prev_node = None def dfs(curr_node): nonlocal first_switch, second_switch, prev_node if not curr_node: return # inorder travesal dfs(curr_node.left) if prev_node: if curr_node.val < prev_node.val: second_switch = curr_node if not first_switch: first_switch = prev_node else: return # prev_node need to be global prev_node = curr_node dfs(curr_node.right) dfs(root) first_switch.val, second_switch.val = second_switch.val, first_switch.val # 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 SolutionIteration: def recoverTree(self, root: Optional[TreeNode]) -> None: """ Do not return anything, modify root in-place instead. """ first_switch, second_switch = None, None prev = None stack = [] curr = root while stack or curr: while curr: stack.append(curr) curr = curr.left curr = stack.pop() if prev and prev.val > curr.val: second_switch = curr if not first_switch: first_switch = prev else: break prev = curr curr = curr.right first_switch.val, second_switch.val = second_switch.val, first_switch.val
[ "lisong.guo@me.com" ]
lisong.guo@me.com
9e07b5398d27a117cd0715e83244ef70c8effa19
425db5a849281d333e68c26a26678e7c8ce11b66
/LeetCodeSolutions/LeetCode_0077.py
3acdf7b01e3c58d9d3ca83d70ec1fcf15e98ba77
[ "MIT" ]
permissive
lih627/python-algorithm-templates
e8092b327a02506086414df41bbfb2af5d6b06dc
a61fd583e33a769b44ab758990625d3381793768
refs/heads/master
2021-07-23T17:10:43.814639
2021-01-21T17:14:55
2021-01-21T17:14:55
238,456,498
29
8
null
null
null
null
UTF-8
Python
false
false
573
py
class Solution: def combine(self, n: int, k: int) -> List[List[int]]: if n < k or k == 0 or n < 1: return [] if n == k: return [list(range(1, n + 1))] elems = list(range(1, n + 1)) res = [] def helper(idx, cur_num, tmp): if cur_num == k: for _ in range(idx, n): res.append(tmp + [elems[_]]) return for _ in range(idx, n): helper(_ + 1, cur_num + 1, tmp + [elems[_]]) helper(0, 1, []) return res
[ "lih627@outlook.com" ]
lih627@outlook.com
9fc53681ad817b7fa251631d75071089db5d2263
3aafaa865594aa58d056a79fdae4d0658774d3ab
/lpot/policy/policy.py
7c0681ec514a8231ce3bcfe65665bfd8becfff2b
[ "Apache-2.0", "MIT", "Intel" ]
permissive
asamarah1/lpot
56aac0d46692e1864de2f06390ab435cd079e741
881bde402db387b04c2f33cc96fb817f47c4d623
refs/heads/master
2023-01-20T15:55:39.088923
2020-12-01T13:22:59
2020-12-01T14:25:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,827
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2020 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. POLICIES = {} def policy_registry(cls): """The class decorator used to register all PrunePolicy subclasses. Args: cls (class): The class of register. Returns: cls: The class of register. """ assert cls.__name__.endswith( 'PrunePolicy' ), "The name of subclass of PrunePolicy should end with \'PrunePolicy\' substring." if cls.__name__[:-len('PrunePolicy')].lower() in POLICIES: raise ValueError('Cannot have two policies with the same name') POLICIES[cls.__name__[:-len('PrunePolicy')].lower()] = cls return cls class PrunePolicy: def __init__(self, model, local_config, global_config, adaptor): """The base clase of Prune policies Args: model (object): The original model (currently torhc.nn.module instance). local_config (Conf): configs specific for this pruning instance global_config (Conf): global configs which may be overwritten by local_config adaptor (Adaptor): Correspond adaptor for current framework """ self.model = model self.adaptor = adaptor self.tensor_dims = [4] if local_config.method: self.method = local_config.method else: self.method = "per_tensor" if local_config.init_sparsity: self.init_sparsity = local_config["init_sparsity"] else: self.init_sparsity = global_config.pruning["init_sparsity"] if local_config.target_sparsity: self.target_sparsity = local_config.target_sparsity else: self.target_sparsity = global_config.pruning.target_sparsity self.start_epoch = global_config.pruning["start_epoch"] self.end_epoch = global_config.pruning["end_epoch"] self.freq = global_config.pruning["frequency"] if local_config.weights: self.weights = local_config.weights else: self.weights = self.adaptor.get_all_weight_names(self.model) self.is_last_epoch = False self.masks = {} def on_epoch_begin(self, epoch): raise NotImplementedError def on_batch_begin(self, batch_id): raise NotImplementedError def on_epoch_end(self): raise NotImplementedError def on_batch_end(self): raise NotImplementedError def update_sparsity(self, epoch): """ update sparsity goals according to epoch numbers Args: epoch (int): the epoch number Returns: sprsity (float): sparsity target in this epoch """ if self.start_epoch == self.end_epoch: return self.init_sparsity if epoch < self.start_epoch: return 0 if epoch > self.end_epoch: return self.target_sparsity return self.init_sparsity + (self.target_sparsity - self.init_sparsity) * ( (epoch - self.start_epoch) // self.freq) * self.freq / \ (self.end_epoch - self.start_epoch)
[ "feng.tian@intel.com" ]
feng.tian@intel.com
f54e17f1039b967e95884b5985520df3dfd65637
e71ecfe679dd8c800e8b0960d4ba68e19401a4fc
/stepik_lesson/course_512/24462_step_7/stepik_lesson_24462_step_7.py
63695a2af1d67f45221fa836de778932c8006dcf
[]
no_license
igizm0/SimplePyScripts
65740038d36aab50918ca5465e21c41c87713630
62c8039fbb92780c8a7fbb561ab4b86cc2185c3d
refs/heads/master
2021-04-12T10:48:17.769548
2017-06-15T18:53:04
2017-06-15T18:53:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,536
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' """ Вам дано описание наследования классов в следующем формате. <имя класса 1> : <имя класса 2> <имя класса 3> ... <имя класса k> Это означает, что класс 1 отнаследован от класса 2, класса 3, и т. д. Или эквивалентно записи: class Class1(Class2, Class3 ... ClassK): pass Класс A является прямым предком класса B, если B отнаследован от A: class B(A): pass Класс A является предком класса B, если A = B; A - прямой предок B существует такой класс C, что C - прямой предок B и A - предок C Например: class B(A): pass class C(B): pass # A -- предок С Вам необходимо отвечать на запросы, является ли один класс предком другого класса Важное примечание: Создавать классы не требуется. Мы просим вас промоделировать этот процесс, и понять существует ли путь от одного класса до другого. Формат входных данных В первой строке входных данных содержится целое число n - число классов. В следующих n строках содержится описание наследования классов. В i-й строке указано от каких классов наследуется i-й класс. Обратите внимание, что класс может ни от кого не наследоваться. Гарантируется, что класс не наследуется сам от себя (прямо или косвенно), что класс не наследуется явно от одного класса более одного раза. В следующей строке содержится число q - количество запросов. В следующих q строках содержится описание запросов в формате <имя класса 1> <имя класса 2>. Имя класса – строка, состоящая из символов латинского алфавита, длины не более 50. Формат выходных данных Для каждого запроса выведите в отдельной строке слово "Yes", если класс 1 является предком класса 2, и "No", если не является. Sample Input: 4 A B : A C : A D : B C 4 A B B D C D D A Sample Output: Yes Yes Yes No """ # Пример использования. В консоли: # > python stepik_lesson_24462_step_7.py < in # Yes # Yes # Yes # No if __name__ == '__main__': # A # B : A # C : A # D : B C # # A B # B D # C D # D A # TODO: по заданию необязательно через классы делать, # поэтому можно этот класс заменить словарем вида { 'name': '...', 'parents': [...] } # И, соответственно, функцию has_parent вынести из класса и поменять, чтобы она работала с словарем. class Class: def __init__(self, name): self.name = name self.list_parent_class = list() def has_parent(self, name): # Поиск предка в текущем классе for parent in self.list_parent_class: if parent.name == name: return True # Рекурсивный поиск предка у предков текущем классе for parent in self.list_parent_class: if parent.has_parent(name): return True return False def __str__(self): return 'Class <"{}": {}>'.format(self.name, [cls.name for cls in self.list_parent_class]) def __repr__(self): return self.__str__() from collections import OrderedDict, defaultdict class_dict = OrderedDict() # Словарь, в котором по ключу находится объект класса, а по # значению -- список названий (строка) классов, от которых от наследуется class_line_dict = defaultdict(list) # Алгоритм: # * Нахождение всех классов и добавление их в class_dict # * Если у класса указано наследование, добавление названия (строка) предков в class_line_dict # * После нахождения всех классов, выполняется перебор class_line_dict, чтобы заполнить список # предков найденных классов. К этому моменту всевозможные классы уже будут храниться в class_dict n = int(input()) for _ in range(n): s = input() # print(s) clsn = s.split(' : ') cls1_name = clsn[0] # Добавление класса в словарь cls = Class(cls1_name) class_dict[cls1_name] = cls # Попалось описание с наследованием if len(clsn) == 2: class_line_dict[cls] += clsn[1].split() for cls, names_cls_list in class_line_dict.items(): for name_cls in names_cls_list: cls.list_parent_class.append(class_dict[name_cls]) n = int(input()) for _ in range(n): # a -- предок, b -- класс, # т.е. проверяем, что у класса b есть предок a a, b = input().split() # Дурацкое у них условие: каждый класс является предком самого себя. # С второго теста есть такая проверка. if a == b: print('Yes') else: print('Yes' if class_dict[b].has_parent(a) else 'No')
[ "gil9red@gmail.com" ]
gil9red@gmail.com
bd9832d0c46aeb06f3e1be823cd8ddeeeff12f6b
658e2e3cb8a4d5343a125f7deed19c9ebf06fa68
/archived/Iris/predict_MLib.py
ad961a61d650da3d0598048dca22187b70f6101d
[]
no_license
yennanliu/analysis
3f0018809cdc2403f4fbfe4b245df1ad73fa08a5
643ad3fed41961cddd006fadceb0e927f1db1f23
refs/heads/master
2021-01-23T21:48:58.572269
2020-10-13T22:47:12
2020-10-13T22:47:12
57,648,676
11
9
null
null
null
null
UTF-8
Python
false
false
666
py
# python 2.7 # import pyspark library from pyspark import SparkConf, SparkContext # spark_sklearn provides the same API as sklearn but uses Spark MLLib # under the hood to perform the actual computations in a distributed way # (passed in via the SparkContext instance). from spark_sklearn import GridSearchCV # import ML library from sklearn import svm, grid_search, datasets sc =SparkContext() iris = datasets.load_iris() parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]} svr = svm.SVC() clf = GridSearchCV(sc, svr, parameters) clf.fit(iris.data, iris.target) print ("==================") print (clf.predict(iris.data)) print ("==================")
[ "f339339@gmail.com" ]
f339339@gmail.com
d24fae521ef6c2f8b0e3cf7b13a138e1f4046455
8dbb2a3e2286c97b1baa3ee54210189f8470eb4d
/kubernetes-stubs/client/models/v1_sysctl.pyi
e638c63d5d823971ab9ff9df1684ff0940b88d6c
[]
no_license
foodpairing/kubernetes-stubs
e4b0f687254316e6f2954bacaa69ff898a88bde4
f510dc3d350ec998787f543a280dd619449b5445
refs/heads/master
2023-08-21T21:00:54.485923
2021-08-25T03:53:07
2021-08-25T04:45:17
414,555,568
0
0
null
2021-10-07T10:26:08
2021-10-07T10:26:08
null
UTF-8
Python
false
false
288
pyi
import datetime import typing import kubernetes.client class V1Sysctl: name: str value: str def __init__(self, *, name: str, value: str) -> None: ... def to_dict(self) -> V1SysctlDict: ... class V1SysctlDict(typing.TypedDict, total=False): name: str value: str
[ "nikhil.benesch@gmail.com" ]
nikhil.benesch@gmail.com
673d91a849350b9e67aade6bec505c7dab3c0e0c
110044654f706e920380dad2779bb32a77f1f26f
/test/scons-time/run/option/prefix.py
df13cd03a7471c885ba2284a7fdb2d97f3999c1f
[ "MIT", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-unknown-license-reference" ]
permissive
SCons/scons
89327bb9635cee6e7cc59249edca9cd859d7d1ff
b2a7d7066a2b854460a334a5fe737ea389655e6e
refs/heads/master
2023-09-01T19:37:03.603772
2023-08-28T04:32:42
2023-08-28T04:32:42
104,670,160
1,827
342
MIT
2023-09-14T15:13:21
2017-09-24T19:23:46
Python
UTF-8
Python
false
false
1,756
py
#!/usr/bin/env python # # __COPYRIGHT__ # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" """ Verify specifying an alternate file prefix with the --prefix option. """ import TestSCons_time test = TestSCons_time.TestSCons_time() test.write_fake_scons_py() test.write_sample_project('foo.tar.gz') test.run(arguments = 'run --prefix bar foo.tar.gz') test.must_exist('bar-000-0.log', 'bar-000-0.prof', 'bar-000-1.log', 'bar-000-1.prof', 'bar-000-2.log', 'bar-000-2.prof') test.pass_test() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
[ "knight@baldmt.com" ]
knight@baldmt.com
03a9ddfa73884e7bfecba1c93affc417bf62874c
a1119965e2e3bdc40126fd92f4b4b8ee7016dfca
/trunk/geoip_server/geoip_server.py
694cfbf4361cb21ff3247af3076efb976476662d
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
SeattleTestbed/attic
0e33211ddf39efdbcf5573d4fc7fa5201aa7310d
f618a962ce2fd3c4838564e8c62c10924f5df45f
refs/heads/master
2021-06-10T23:10:47.792847
2017-05-15T12:05:43
2017-05-15T12:05:43
20,154,061
0
1
null
2014-10-16T17:21:06
2014-05-25T12:34:00
Python
UTF-8
Python
false
false
3,070
py
#!/usr/bin/env python """ <Author> Evan Meagher <Start Date> Nov 26, 2009 <Description> Starts an XML-RPC server that allows remote clients to execute geolocation queries using the pygeoip library. <Usage> python geoip_server.py /path/to/GeoIP.dat PORT Where /path/to/GeoIP.dat is the path to a legal GeoIP database and PORT is the port on which to host the server. Databases can be downloaded at http://www.maxmind.com/app/ip-location. More information on pygeoip at http://code.google.com/p/pygeoip/. More information on geoip_server.py at http://seattle.poly.edu/wiki/GeoIPServer """ import sys sys.path.append("./seattle/seattle_repy") import pygeoip import repyportability import xmlrpclib from SimpleXMLRPCServer import SimpleXMLRPCServer class SafeGeoIPServer(pygeoip.GeoIP): """ <Purpose> Provides safe wrappers around the GeoIP server method calls. This allows us to check that each request is well-formatted before executing them on pygeoip. This class does not introduce any new methods; it only overrides existing methods in pygeoip.GeoIP. """ def record_by_addr(self, addr): """ <Purpose> Returns the GeoIP record for the specified IP address. <Arguments> addr: A public IPv4 address. <Side Effects> None <Exceptions> None <Return> A dictionary containing GeoIP information for the address specified, if valid. Returns False on errors. """ if not _is_public_ipv4(addr): return xmlrpclib.Fault(xmlrpclib.INVALID_METHOD_PARAMS, "Not a public IP address") return super(SafeGeoIPServer, self).record_by_addr(addr) def _is_public_ipv4(addr): """ <Purpose> Determines if an IPv4 address is public or not. <Arguments> addr: An IPv4 address. <Side Effects> None <Exceptions> None, assuming that the provided value is a valid IPv4 address. <Returns> True if it is a public IP address, False otherwise. """ # We need to do some range comparisons for Class B and C addresses, # so preprocess them into ints. ip_int_tokens = [int(token) for token in addr.split('.')] if ip_int_tokens[0] == 10: # Class A private address is in the form 10.*.*.* return False # Class B private addresses are in the range 172.16.0.0/16 to # 172.31.255.255/16 elif ip_int_tokens[0] == 172: if 16 <= ip_int_tokens[1] and ip_int_tokens[1] < 32: return False # Class C private addresses are in the form 192.168.*.* elif ip_int_tokens[0:2] == [192, 168]: return False return True # Handle arguments if len(sys.argv) < 3: print "Usage: python geoip_server.py /path/to/GeoIP.dat PORT" raise RuntimeError geoipdb_filename = sys.argv[1] port = int(sys.argv[2]) # Get external IP ext_ip = repyportability.getmyip() # Create server server = SimpleXMLRPCServer((ext_ip, port), allow_none=True) # Initialize and register geoip object gic = SafeGeoIPServer(geoipdb_filename) server.register_instance(gic) # Run the server's main loop server.serve_forever()
[ "USER@DOMAIN" ]
USER@DOMAIN
f2d0bdcee3ce59d545e749c749eb9687f69c787a
e58f8258837fdf559cde6008ca46ecedb1735347
/scripts/extract_changelog.py
7cba17577c9a58cf1e5f59f53cb4544824cdc2a4
[ "MIT" ]
permissive
Dotnester/hyperqueue
5a4bbd4966dc5c79e48b0f2012576e418a2b8230
cf5227c2157ab431ee7018a40bbbf0558afe4f27
refs/heads/main
2023-07-08T22:22:15.992034
2021-08-08T09:38:06
2021-08-08T09:38:06
379,584,453
0
0
MIT
2021-06-23T11:47:10
2021-06-23T11:47:09
null
UTF-8
Python
false
false
1,033
py
import sys from os.path import dirname, abspath, join CURRENT_DIR = dirname(abspath(__file__)) CHANGELOG_PATH = join(dirname(CURRENT_DIR), "CHANGELOG.md") def normalize(version: str) -> str: return version.strip().lstrip("v").lower() def get_matching_lines(text: str, tag: str): lines = list(text.splitlines(keepends=False)) for (index, line) in enumerate(lines): if line.startswith("# "): version = normalize(line.lstrip("# ")) if version == tag: for matching_line in lines[index + 1:]: if matching_line.startswith("# "): return yield matching_line if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: python extract_changelog <tag>") exit(1) tag = normalize(sys.argv[1]) with open(CHANGELOG_PATH) as f: text = f.read() output = f"# HyperQueue {tag}\n" for line in get_matching_lines(text, tag): output += f"{line}\n" print(output)
[ "berykubik@gmail.com" ]
berykubik@gmail.com
839eed4612014b865c80342615cde0f6ddac614d
58afefdde86346760bea40690b1675c6639c8b84
/leetcode/minimum-moves-to-equal-array-elements/286144821.py
dc0c0055a3678c35f3e5333e2f8ffd941978ff97
[]
no_license
ausaki/data_structures_and_algorithms
aaa563f713cbab3c34a9465039d52b853f95548e
4f5f5124534bd4423356a5f5572b8a39b7828d80
refs/heads/master
2021-06-21T10:44:44.549601
2021-04-06T11:30:21
2021-04-06T11:30:21
201,942,771
1
0
null
null
null
null
UTF-8
Python
false
false
455
py
# title: minimum-moves-to-equal-array-elements # detail: https://leetcode.com/submissions/detail/286144821/ # datetime: Sun Dec 15 23:17:51 2019 # runtime: 300 ms # memory: 14 MB class Solution: def minMoves(self, nums: List[int]) -> int: m = nums[0] s0 = nums[0] for i in range(1, len(nums)): s0 += nums[i] if nums[i] < m: m = nums[i] return s0 - m * len(nums)
[ "ljm51689@gmail.com" ]
ljm51689@gmail.com
b809857ce9e48ae6ea3743c92b3a80ee7ad9cbd3
c886b04cdbe32e0997d9bc0259b90575ebb2d084
/system/vhost/zkeys_database_conf.py
351ec5b296da0e45d04398b1a40109dfa5125e71
[]
no_license
bmhxbai/AngelSword
3ce7b9f9f9e6114f8d4cff15e17d1fd8225a786c
a048dbfcbcf0097c6cf683ab9cd5ce975bddcf68
refs/heads/master
2020-06-25T07:23:15.505146
2017-07-01T17:57:34
2017-07-01T17:57:34
96,964,744
2
1
null
2017-07-12T04:20:20
2017-07-12T04:20:20
null
UTF-8
Python
false
false
1,256
py
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' name: 宏杰Zkeys虚拟主机默认数据库漏洞 referer: http://www.wooyun.org/bugs/wooyun-2014-048350 author: Lucifer description: 宏杰Zkeys虚拟主机默认开启999端口,默认数据库密码zkeys可连接root。 ''' import sys import pymysql import warnings from termcolor import cprint from urllib.parse import urlparse class zkeys_database_conf_BaseVerify: def __init__(self, url): self.url = url def run(self): if r"http" in self.url: #提取host host = urlparse(self.url)[1] flag = host.find(":") if flag != -1: host = host[:flag] else: host = self.url try: conn = pymysql.connect(host=host, user="root", passwd="zkeys", port=3306, connect_timeout=6) if conn.ping().server_status == 0: cprint("[+]存在宏杰Zkeys虚拟主机默认数据库漏洞...(高危)\tpayload: "+host+":3306"+" root:zkeys", "red") except: cprint("[-] "+__file__+"====>连接超时", "cyan") if __name__ == "__main__": warnings.filterwarnings("ignore") testVuln = zkeys_database_conf_BaseVerify(sys.argv[1]) testVuln.run()
[ "297954441@qq.com" ]
297954441@qq.com
0e02481e8375d280ec68fb8d4c16894dc62b6acb
0bf833b379210656214b4064d0a71850352e014e
/vsCode/DL_rawLevel/DL_rawLevel/4.ANN/test.py
3bf3a6f55736816652323c2826993e413b759991
[ "MIT" ]
permissive
pimier15/pyDLBasic
f10168e352b94b9d77fda3c1b89a294b66fd8e4e
80336cddbcb3ec1f70106b74ff0b3172510b769e
refs/heads/master
2021-07-20T00:37:15.363651
2017-10-28T02:32:47
2017-10-28T02:32:47
107,188,067
0
0
null
null
null
null
UTF-8
Python
false
false
496
py
import numpy as np ys = np.array([[1,2] , [3,4]]) #ys = np.array([1,2 , 3,4]) ts = np.array([[0,1] , [0,1]]) #ts = np.array([0,1 , 0,1]) IsOneHot = True res = None batch_size = ys.shape[0] #res = -np.sum(ts*np.log(ys + 1e-7) ) / batch_size #res = -np.sum(np.log(ys[np.arange(batch_size) , t]) ) / batch_size ly = np.log(ys + 1e-7) lymulti = ts * ly print(ly) print(lymulti) print() res1 = np.sum(lymulti , axis = 0) res2 =np.sum(lymulti , axis = 1) res2 =np.sum(lymulti ) print()
[ "pimier15@gmail.com" ]
pimier15@gmail.com
fc2fa0fbaa66103a9e382ebb8547fd0c14538125
dce4cfdae2d1e7285b92f657f2509143595f4cc3
/loadsbroker/client/base.py
faf44a100b06fc418c09f1db7c7545768e417185
[ "Apache-2.0" ]
permissive
loads/loads-broker
ed8a0c0b79b132a0b4e73da59a391193e9e99147
b6134690e1bd7b07e226bee16e6f779ef0f170d9
refs/heads/master
2021-01-17T13:46:16.539082
2017-03-29T22:06:20
2017-03-29T22:06:20
23,458,608
7
1
Apache-2.0
2021-04-27T19:20:00
2014-08-29T09:02:14
Python
UTF-8
Python
false
false
599
py
class BaseCommand(object): """Base Command Class""" arguments = {} def __init__(self, session, root): self.session = session self.root = root def __call__(self, args): return self.session.get(self.root).json() def args2options(self, args): options = {} for option in self.arguments: if option.startswith('--'): option = option[2:] normalized = option.replace('-', '_') if normalized in args: options[normalized] = getattr(args, normalized) return options
[ "tarek@ziade.org" ]
tarek@ziade.org
1900f05d4886154e7a4d78aa476492ce0db95e71
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02381/s946222912.py
98a2c0e51de4dd78dcdf7cf46b06bc31ed0bae32
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
220
py
import math while True: n = int(input()) if n == 0: break a = 0 st = list(map(int, input().split())) m = sum(st)/len(st) for x in st: a += (x-m)**2 print(math.sqrt(a/n))
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
fefc83938d27fd019badb525867387ffddc88103
47471b8424715c1a1bc9e6745f44b89bec3add5f
/apps/account/admin.py
536398f3e9367c65f9ffeb70845899b24cc3d01e
[]
no_license
Dimasuz/6.6_Ln_with_docker
5f34db291afe243e8e571067e17e7b3d92145437
d1fee864816174c0e03acc13a6849ee3277f6cec
refs/heads/master
2023-05-27T07:09:05.187935
2021-06-11T20:07:14
2021-06-11T20:07:14
null
0
0
null
null
null
null
UTF-8
Python
false
false
747
py
from django.contrib import admin from django.contrib.auth.admin import UserAdmin as DefaultUserAdmin from django.utils.translation import gettext_lazy as _ from apps.account.models import User @admin.register(User) class UserAdmin(DefaultUserAdmin): list_display = ( 'username', 'first_name', 'last_name', 'is_superuser', 'is_staff', 'is_active', ) fieldsets = ( (None, {'fields': ('username', 'password')}), (_('Personal info'), {'fields': ('first_name', 'last_name', 'email', 'avatar')}), (_('Permissions'), { 'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions'), }), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), )
[ "oz.sasha.ivanov@gmail.com" ]
oz.sasha.ivanov@gmail.com