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
00d0a14e123abd54a6e59a43184ae690361ef49d
acbb6e1e33cf2c5dae45c73e3d07723ce21f1cf9
/migrations/versions/ad4630b5d9d4_followers.py
6b6dd161cc165a486f3c1637ff7b444302d21143
[]
no_license
Tur-4000/microblog
24edde54599937bc97bf782861868fea0f57814e
24de02ed7c1d417b68171079dc366833f7d2e6c7
refs/heads/master
2022-05-25T22:16:10.609591
2018-08-02T20:34:40
2018-08-02T20:34:40
141,682,858
1
0
null
2022-05-25T00:20:33
2018-07-20T08:05:00
Python
UTF-8
Python
false
false
840
py
"""followers Revision ID: ad4630b5d9d4 Revises: 6f99f9ee47c0 Create Date: 2018-07-24 17:35:58.696784 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'ad4630b5d9d4' down_revision = '6f99f9ee47c0' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('followers', sa.Column('follower_id', sa.Integer(), nullable=True), sa.Column('followed_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['followed_id'], ['user.id'], ), sa.ForeignKeyConstraint(['follower_id'], ['user.id'], ) ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('followers') # ### end Alembic commands ###
[ "tur.4000@gmail.com" ]
tur.4000@gmail.com
b54dbcbba5b87d5e208a4286878095d159ab7260
4f75cc33b4d65d5e4b054fc35b831a388a46c896
/test_watchlist.py
395cd36afd93c199d6f54cfb098279bd0d6044b4
[]
no_license
Lr-2002/newpage
c3fe2acc451e24f6408996ea1271c61c321de702
c589ad974e7100aa9b1c2ccc095a959ff68069b6
refs/heads/main
2023-09-03T06:13:53.428236
2021-11-23T10:41:21
2021-11-23T10:41:21
402,606,000
0
0
null
null
null
null
UTF-8
Python
false
false
8,048
py
from os import name from re import A, T import unittest from app import app, db, Movie, User class WatchlistTestCase(unittest.TestCase): def setUp(self): app.config.update( TESTING = True, SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:' ) db.create_all() user = User(name = 'test', username = 'test') user.set_password('123') movie = Movie(title ='Test Movie Title', year = 2000) db.session.add_all([user,movie]) db.session.commit() self.client = app.test_client() # create client to test self.runner = app.test_cli_runner() # app.test_cli_runner app.test_client # both of them are built-in test function oin falsk def tearDown(self): """ close app and clean everything""" db.session.remove() db.drop_all() def test_app_exist(self): """ exist_testing by none (if app not exist then the object is nono)""" self.assertIsNotNone(app) def test_app_is_testing(self): """ test_app_is_testing by give app.config""" self.assertTrue(app.config['TESTING']) def test_404_page(self): response = self.client.get('/nothing') data = response.get_data(as_text=True) self.assertIn('Page Not Found - 404',data) # test the response of 404_page self.assertEqual(response.status_code, 404) def test_index_page(self): response = self.client.get('/') data = response.get_data(as_text=True) self.assertEqual(response.status_code, 200) def login(self): self.client.post('/login', data=dict( username = 'test', password = '123' ),follow_redirects = True) def test_create_item(self): print(1) self.login() print(4) response = self.client.post('/', data=dict( title='New Movie', year='2019' ), follow_redirects=True) print(2) data = response.get_data(as_text=True) self.assertIn('Item created.', data) self.assertIn('New Movie', data) print(3) # 测试创建条目操作,但电影标题为空 response = self.client.post('/', data=dict( title='', year='2019' ), follow_redirects=True) data = response.get_data(as_text=True) self.assertNotIn('Item created.', data) self.assertIn('Invalid input.', data) # 测试创建条目操作,但电影年份为空 response = self.client.post('/', data=dict( title='New Movie', year='' ), follow_redirects=True) data = response.get_data(as_text=True) self.assertNotIn('Item created.', data) self.assertIn('Invalid input.', data) def test_update_item(self): self.login() # 测试更新页面 response = self.client.get('/movie/edit/1') data = response.get_data(as_text=True) self.assertIn('Edit', data) self.assertIn('Test Movie Title', data) self.assertIn('2000', data) # 测试更新条目操作 response = self.client.post('/movie/edit/1', data=dict( title='New Movie Edited', year='2019' ), follow_redirects=True) data = response.get_data(as_text=True) self.assertIn('Item updated.', data) self.assertIn('New Movie Edited', data) # 测试更新条目操作,但电影标题为空 response = self.client.post('/movie/edit/1', data=dict( title='', year='2019' ), follow_redirects=True) data = response.get_data(as_text=True) self.assertNotIn('Item updated.', data) self.assertIn('Invalid input.', data) # 测试更新条目操作,但电影年份为空 response = self.client.post('/movie/edit/1', data=dict( title='New Movie Edited Again', year='' ), follow_redirects=True) data = response.get_data(as_text=True) self.assertNotIn('Item updated.', data) self.assertNotIn('New Movie Edited Again', data) self.assertIn('Invalid input.', data) # 测试删除条目 def test_delete_item(self): self.login() response = self.client.post('/movie/delete/1', follow_redirects=True) data = response.get_data(as_text=True) self.assertIn('Item Deleted', data) self.assertNotIn('Test Movie Title', data) def test_login_protect(self): response = self.client.get('/') data = response.get_data(as_text=True) self.assertNotIn('Logout', data) self.assertIn('Settings', data) self.assertIn("<form method='post'>", data) self.assertIn('Delete', data) self.assertIn('Edit', data) # 测试登录 def test_login(self): response = self.client.post('/login', data=dict( username='test', password='123' ), follow_redirects=True) data = response.get_data(as_text=True) self.assertIn('Successfully', data) self.assertIn('logout', data) self.assertIn('Settings', data) self.assertIn('Delete', data) self.assertIn('Edit', data) self.assertIn("<form method='post'>", data) # 测试使用错误的密码登录 response = self.client.post('/login', data=dict( username='test', password='456' ), follow_redirects=True) data = response.get_data(as_text=True) self.assertNotIn('Successfully', data) self.assertIn('Invalid username or password', data) # 测试使用错误的用户名登录 response = self.client.post('/login', data=dict( username='wrong', password='123' ), follow_redirects=True) data = response.get_data(as_text=True) self.assertNotIn('Successfully', data) self.assertIn('Invalid username or password', data) # 测试使用空用户名登录 response = self.client.post('/login', data=dict( username='', password='123' ), follow_redirects=True) data = response.get_data(as_text=True) self.assertNotIn('Successfully', data) self.assertIn('Invalid username or password', data) # 测试使用空密码登录 response = self.client.post('/login', data=dict( username='test', password='' ), follow_redirects=True) data = response.get_data(as_text=True) self.assertNotIn('Successfully', data) self.assertIn('Invalid username or password', data) # 测试登出 def test_logout(self): self.login() response = self.client.get('/logout', follow_redirects=True) data = response.get_data(as_text=True) self.assertIn('logged out', data) # self.assertIn('Logout', data) self.assertIn('Settings', data) self.assertIn('Delete', data) self.assertIn('Edit', data) self.assertIn("<form method='post'>", data) # 测试设置 def test_settings(self): self.login() # 测试设置页面 response = self.client.get('/settings') data = response.get_data(as_text=True) self.assertIn('Settings', data) self.assertIn('Your Name', data) # 测试更新设置 response = self.client.post('/settings', data=dict( name='Grey Li', ), follow_redirects=True) data = response.get_data(as_text=True) self.assertIn('changed', data) self.assertIn('Grey Li', data) # 测试更新设置,名称为空 response = self.client.post('/settings', data=dict( name='', ), follow_redirects=True) data = response.get_data(as_text=True) self.assertNotIn('changed', data) # self.assertIn('Invalid input.', data) if __name__ == '__main__': unittest.main()
[ "2629651228@qq.com" ]
2629651228@qq.com
9dedcdee6a2d68515c547bd4a1b13efe3b23bdce
3a891a79be468621aae43defd9a5516f9763f36e
/desktop/core/ext-py/dnspython-1.15.0/examples/ddns.py
f351524ee738290cfe64177208bb0df88bbff61f
[ "LicenseRef-scancode-warranty-disclaimer", "ISC", "Apache-2.0" ]
permissive
oyorooms/hue
b53eb87f805063a90f957fd2e1733f21406269aa
4082346ef8d5e6a8365b05752be41186840dc868
refs/heads/master
2020-04-15T20:31:56.931218
2019-01-09T19:02:21
2019-01-09T19:05:36
164,998,117
4
2
Apache-2.0
2019-01-10T05:47:36
2019-01-10T05:47:36
null
UTF-8
Python
false
false
1,204
py
#!/usr/bin/env python # # Use a TSIG-signed DDNS update to update our hostname-to-address # mapping. # # usage: ddns.py <ip-address> # # On linux systems, you can automatically update your DNS any time an # interface comes up by adding an ifup-local script that invokes this # python code. # # E.g. on my systems I have this # # #!/bin/sh # # DEVICE=$1 # # if [ "X${DEVICE}" == "Xeth0" ]; then # IPADDR=`LANG= LC_ALL= ifconfig ${DEVICE} | grep 'inet addr' | # awk -F: '{ print $2 } ' | awk '{ print $1 }'` # /usr/local/sbin/ddns.py $IPADDR # fi # # in /etc/ifup-local. # import sys import dns.update import dns.query import dns.tsigkeyring # # Replace the keyname and secret with appropriate values for your # configuration. # keyring = dns.tsigkeyring.from_text({ 'keyname.' : 'NjHwPsMKjdN++dOfE5iAiQ==' }) # # Replace "example." with your domain, and "host" with your hostname. # update = dns.update.Update('example.', keyring=keyring) update.replace('host', 300, 'A', sys.argv[1]) # # Replace "10.0.0.1" with the IP address of your master server. # response = dns.query.tcp(update, '10.0.0.1', timeout=10)
[ "yingchen@cloudera.com" ]
yingchen@cloudera.com
499388b2165572001dc1138029488a7777cf7e8c
45fdc51cf264bbd50e59655440eefc91451c50ea
/text/src/textwrap_dedent.py
5084ccaedb083bd8a9ae1878d3c3217339c0efd4
[]
no_license
blindij/python3_stl
2163043f3a9113eac21a48a35685a4a01987e926
ea138e25f8b5bbf7d8f78e4b1b7e2ae413de4735
refs/heads/master
2021-12-24T20:37:54.055116
2021-09-29T13:37:38
2021-09-29T13:37:38
191,508,648
0
0
null
2019-08-27T15:45:53
2019-06-12T06:10:30
Python
UTF-8
Python
false
false
142
py
import textwrap from textwrap_example import sample_text dedented_text = textwrap.dedent(sample_text) print('Dedented') print(dedented_text)
[ "blindij@users.noreply.github.com" ]
blindij@users.noreply.github.com
2eb81e6bc89d77f0ee7640edaec9543348a8f465
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/380/usersdata/315/101991/submittedfiles/minha_bib.py
37dfe39276605bb65b991985c20942c3898a1b93
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
3,182
py
# -*- coding: utf-8 -*- import random #Simbolo que o Jogador quer utilizar def solicitaSimbolodoHumano(a): a = input('\nQual símbolo você deseja utilizar no jogo? ') while a!='O' and a!='X' and a!='o' and a!='x': a = input('\nQual símbolo você deseja utilizar no jogo? ') if a == 'x' or a =='X': a = ' X ' else: a = ' O ' return a #Sorteio de quem ira começar jogando def sorteioPrimeiraJogada(jogador, nome): jogador = random.choice((0,1)) if jogador ==1: print('\nVencedor do sorteio para inicio do jogo : %s'%nome) else: print('\nVencedor do sorteio para inicio do jogo : Computador') return jogador #Printa o tabuleiro def mostraTabuleiro(tabuleiro): print ('') print (tabuleiro[0][0] + '|' + tabuleiro[0][1] + '|' + tabuleiro[0][2]) print (tabuleiro[1][0] + '|' + tabuleiro[1][1] + '|' + tabuleiro[1][2]) print (tabuleiro[2][0] + '|' + tabuleiro[2][1] + '|' + tabuleiro[2][2]) #Jogada do computador TA COM ERRO def JogadaComputador(smbPC,tabuleiro): while True: ti = random.choice((0,1,2)) tj = random.choice((0,1,2)) if tabuleiro[ti][tj] == ' ': break else: ti = random.choice((0,1,2)) tj = random.choice((0,1,2)) tabuleiro[ti][tj] = smbPC return tabuleiro #Verifica se a jogada é valida def validaJogada(a, tabuleiro, nome): while True: if tabuleiro[int(a[0])][int(a[2])] == (' '): break else: print('\nOPS!!! Essa jogada não está disponível. Tente novamente!') a = input('\nQual a sua jogada, %s? ' %nome) return a #sua jogada def JogadaHumana(smbH,tabuleiro, nome): mostraTabuleiro(tabuleiro) n = input('\nQual a sua jogada, %s? ' %nome) n = validaJogada(n, tabuleiro, nome) tabuleiro[int(n[0])][int(n[2])] = smbH return tabuleiro #Verifica se alguem ganhou def verificaVencedor(simbolo, tabuleiro): if tabuleiro[0][0] == simbolo and tabuleiro[0][1] == simbolo and tabuleiro[0][2] == simbolo: return True elif tabuleiro[1][0] == simbolo and tabuleiro[1][1] == simbolo and tabuleiro[1][2] == simbolo: return True elif tabuleiro[2][0] == simbolo and tabuleiro[2][1] == simbolo and tabuleiro[2][2] == simbolo: return True elif tabuleiro[0][0] == simbolo and tabuleiro[1][0] == simbolo and tabuleiro[2][0] == simbolo: return True elif tabuleiro[1][0] == simbolo and tabuleiro[1][1] == simbolo and tabuleiro[1][2] == simbolo: return True elif tabuleiro[2][0] == simbolo and tabuleiro[2][1] == simbolo and tabuleiro[2][2] == simbolo: return True elif tabuleiro[0][0] == simbolo and tabuleiro[1][1] == simbolo and tabuleiro[2][2] == simbolo: return True elif tabuleiro[0][2] == simbolo and tabuleiro[1][1] == simbolo and tabuleiro[2][0] == simbolo: return True elif (' ') not in tabuleiro: print('Velha')
[ "rafael.mota@ufca.edu.br" ]
rafael.mota@ufca.edu.br
80de93ce6ac31685b8012386a62622a1db6f1fc7
aa9297175621fcd499cad5a0373aaad15f33cde8
/impractical_py_projects/04/null_cipher_finder.py
217c00b8e15b8e5e7cc33e404b729d1f1166c3ca
[]
no_license
eflipe/python-exercises
a64e88affe8f9deb34e8aa29a23a68c25e7ba08a
b7a429f57a5e4c5dda7c77db5721ca66a401d0a3
refs/heads/master
2023-04-26T19:19:28.674350
2022-07-19T20:53:09
2022-07-19T20:53:09
192,589,885
0
0
null
2023-04-21T21:23:14
2019-06-18T18:06:14
HTML
UTF-8
Python
false
false
1,433
py
import sys import string def load_text(file): """Load a text file as a string""" with open(file) as f: file = f.read().strip() return file def sole_null_cipher(message, lookahead): for i in range(1, lookahead+1): plaintext = '' count = 0 found_first = False for char in message: if char in string.punctuation: count = 0 found_first = True elif found_first is True: count += 1 if count == i: plaintext += char print("Using offset of {} after punctuation = {}".format(i, plaintext)) print() def main(): filename = input("\nIngresa el mensaje: ") try: loaded_message = load_text(filename) except IOError as e: print(f'{e}. Error!') sys.exit(1) print("\nMensaje =") print("{}".format(loaded_message), "\n") print("\nList of punctuation marks to check = {}".format(string.punctuation)) message = ''.join(loaded_message.split()) while True: lookahead = input("\nLetras a checkear después de" \ "un signo de puntuación: ") if lookahead.isdigit(): lookahead = int(lookahead) break else: print("Pls, ingresa un número") print() sole_null_cipher(message, lookahead) if __name__ == '__main__': main()
[ "felipecabaleiro@gmail.com" ]
felipecabaleiro@gmail.com
14378df2d496adc2ab62a597cefb735979db3c8d
6219e6536774e8eeb4cadc4a84f6f2bea376c1b0
/scraper/storage_spiders/muahangtructuyencomvn.py
e3ab3bbbf0f13987eaeba9a31f3ed5a9bd875132
[ "MIT" ]
permissive
nguyenminhthai/choinho
109d354b410b92784a9737f020894d073bea1534
d2a216fe7a5064d73cdee3e928a7beef7f511fd1
refs/heads/master
2023-05-07T16:51:46.667755
2019-10-22T07:53:41
2019-10-22T07:53:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,134
py
# Auto generated by generator.py. Delete this line if you make modification. from scrapy.spiders import Rule from scrapy.linkextractors import LinkExtractor XPATH = { 'name' : "//div[@class='product-info']/h1[@class='mainbox-title']", 'price' : "//div[@class='product-info']/div[@class='clear']/p/span/span/span | //div[@class='product-info']/div[@class='prices-container clear']/div[@class='float-left product-prices']/p/span/span/span", 'category' : "//div[@class='breadcrumbs']/a", 'description' : "//div[@class='product-main-info']/div[@id='tabs_content']", 'images' : "//div[@class='product-main-info']/form/div/div/a/@href", 'canonical' : "", 'base_url' : "", 'brand' : "" } name = 'muahangtructuyen.com.vn' allowed_domains = ['muahangtructuyen.com.vn'] start_urls = ['http://muahangtructuyen.com.vn'] tracking_url = '' sitemap_urls = [''] sitemap_rules = [('', 'parse_item')] sitemap_follow = [] rules = [ Rule(LinkExtractor(allow=['/[a-zA-Z0-9-]+\.html']), 'parse_item'), Rule(LinkExtractor(allow=['/[a-zA-Z0-9-]+/+$']), 'parse'), #Rule(LinkExtractor(), 'parse_item_and_links'), ]
[ "nguyenchungthuy.hust@gmail.com" ]
nguyenchungthuy.hust@gmail.com
ee57f682e295cbfd9747da50306e7deadad5f554
b66e70a8bb3c53595acd01dceb23298694884b67
/cloudy/cloudy/models.py
92cd7f135177bdbc3b72c907c8741df29eb2c148
[]
no_license
flupke/cloudy-release
d7735a38d79f816c52da3d983c714512a32919b1
6b160188a7067f125b107eb68dc8db4bbb4bfdf4
refs/heads/master
2016-09-06T05:23:40.856287
2013-02-23T18:17:16
2013-02-23T18:17:16
8,377,854
0
0
null
null
null
null
UTF-8
Python
false
false
936
py
from django.db import models class SshIdentity(models.Model): name = models.CharField(max_length=256) public = models.TextField() private = models.TextField() class HostsGroup(models.Model): name = models.CharField(max_length=256) ssh_user = models.CharField(max_length=32, blank=True) ssh_identity = models.ForeignKey(SshIdentity, blank=True) class Host(models.Model): hostname = models.CharField(max_length=256) alias = models.CharField(max_length=256, blank=True) group = models.ForeignKey(HostsGroup) ssh_user = models.CharField(max_length=32, blank=True) ssh_identity = models.ForeignKey(SshIdentity, blank=True) class Project(models.Model): name = models.CharField(max_length=64) hosts = models.ForeignKey(HostsGroup) class Check(models.Model): project = models.ForeignKey(Project) name = models.CharField(max_length=64) command = models.TextField()
[ "luper.rouch@gmail.com" ]
luper.rouch@gmail.com
6adc753cf5c0b93e22a7d940f84597658076e3fa
cdb7bb6215cc2f362f2e93a040c7d8c5efe97fde
/F/FindResultantArrayAfterRemovingAnagrams.py
b380d59a74a054967ffe8ad6c2e2113609d1576b
[]
no_license
bssrdf/pyleet
8861bbac06dfe0f0f06f6ad1010d99f8def19b27
810575368ecffa97677bdb51744d1f716140bbb1
refs/heads/master
2023-08-20T05:44:30.130517
2023-08-19T21:54:34
2023-08-19T21:54:34
91,913,009
2
0
null
null
null
null
UTF-8
Python
false
false
1,973
py
''' -Easy- You are given a 0-indexed string array words, where words[i] consists of lowercase English letters. In one operation, select any index i such that 0 < i < words.length and words[i - 1] and words[i] are anagrams, and delete words[i] from words. Keep performing this operation as long as you can select an index that satisfies the conditions. Return words after performing all operations. It can be shown that selecting the indices for each operation in any arbitrary order will lead to the same result. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase using all the original letters exactly once. For example, "dacb" is an anagram of "abdc". Example 1: Input: words = ["abba","baba","bbaa","cd","cd"] Output: ["abba","cd"] Explanation: One of the ways we can obtain the resultant array is by using the following operations: - Since words[2] = "bbaa" and words[1] = "baba" are anagrams, we choose index 2 and delete words[2]. Now words = ["abba","baba","cd","cd"]. - Since words[1] = "baba" and words[0] = "abba" are anagrams, we choose index 1 and delete words[1]. Now words = ["abba","cd","cd"]. - Since words[2] = "cd" and words[1] = "cd" are anagrams, we choose index 2 and delete words[2]. Now words = ["abba","cd"]. We can no longer perform any operations, so ["abba","cd"] is the final answer. Example 2: Input: words = ["a","b","c","d","e"] Output: ["a","b","c","d","e"] Explanation: No two adjacent strings in words are anagrams of each other, so no operations are performed. Constraints: 1 <= words.length <= 100 1 <= words[i].length <= 10 words[i] consists of lowercase English letters. ''' from typing import List class Solution: def removeAnagrams(self, words: List[str]) -> List[str]: stack = [] for word in words: if stack and sorted(stack[-1]) == sorted(word): continue stack.append(word) return stack
[ "merlintiger@hotmail.com" ]
merlintiger@hotmail.com
ce2343c09e39f921202647e30c1bfea5cae7d3a8
463c053bcf3f4a7337b634890720ea9467f14c87
/rllib/examples/deterministic_training.py
3a0a9c725acda75ce6b9cd7557c4fb04fd59a650
[ "BSD-3-Clause", "MIT", "Apache-2.0" ]
permissive
pdames/ray
e8faddc4440976211a6bcead8f8b6e62c1dcda01
918d3601c6519d333f10910dc75eb549cbb82afa
refs/heads/master
2023-01-23T06:11:11.723212
2022-05-06T22:55:59
2022-05-06T22:55:59
245,515,407
1
1
Apache-2.0
2023-01-14T08:02:21
2020-03-06T20:59:04
Python
UTF-8
Python
false
false
2,464
py
""" Example of a fully deterministic, repeatable RLlib train run using the "seed" config key. """ import argparse import ray from ray import tune from ray.rllib.examples.env.env_using_remote_actor import ( CartPoleWithRemoteParamServer, ParameterStorage, ) from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID from ray.rllib.utils.metrics.learner_info import LEARNER_INFO from ray.rllib.utils.test_utils import check parser = argparse.ArgumentParser() parser.add_argument("--run", type=str, default="PPO") parser.add_argument("--framework", choices=["tf2", "tf", "tfe", "torch"], default="tf") parser.add_argument("--seed", type=int, default=42) parser.add_argument("--as-test", action="store_true") parser.add_argument("--stop-iters", type=int, default=2) parser.add_argument("--num-gpus-trainer", type=float, default=0) parser.add_argument("--num-gpus-per-worker", type=float, default=0) if __name__ == "__main__": args = parser.parse_args() param_storage = ParameterStorage.options(name="param-server").remote() config = { "env": CartPoleWithRemoteParamServer, "env_config": { "param_server": "param-server", }, # Use GPUs iff `RLLIB_NUM_GPUS` env var set to > 0. "num_gpus": args.num_gpus_trainer, "num_workers": 1, # parallelism "num_gpus_per_worker": args.num_gpus_per_worker, "num_envs_per_worker": 2, "framework": args.framework, # Make sure every environment gets a fixed seed. "seed": args.seed, # Simplify to run this example script faster. "train_batch_size": 100, "sgd_minibatch_size": 10, "num_sgd_iter": 5, "rollout_fragment_length": 50, } stop = { "training_iteration": args.stop_iters, } results1 = tune.run(args.run, config=config, stop=stop, verbose=1) results2 = tune.run(args.run, config=config, stop=stop, verbose=1) if args.as_test: results1 = list(results1.results.values())[0] results2 = list(results2.results.values())[0] # Test rollout behavior. check(results1["hist_stats"], results2["hist_stats"]) # As well as training behavior (minibatch sequence during SGD # iterations). check( results1["info"][LEARNER_INFO][DEFAULT_POLICY_ID]["learner_stats"], results2["info"][LEARNER_INFO][DEFAULT_POLICY_ID]["learner_stats"], ) ray.shutdown()
[ "noreply@github.com" ]
pdames.noreply@github.com
f9ac252177ad6e419233ca977c739c8b9a08c30c
4bf5a16c17f888d5e0a2b043a6b752a6111824fd
/src/biotite/structure/util.py
34495270dbcba6c8b3f79077462e59bc1fe60708
[ "BSD-3-Clause" ]
permissive
AAABioInfo/biotite
1b0e8c6d6fbc870ff894fc1ae91c32fe6568aed3
693f347534bcf2c8894bbcabf68c225c43190ec6
refs/heads/master
2022-07-06T01:15:25.373371
2020-05-18T13:27:01
2020-05-18T13:27:01
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,226
py
# This source code is part of the Biotite package and is distributed # under the 3-Clause BSD License. Please see 'LICENSE.rst' for further # information. """ Utility functions for in internal use in `Bio.Structure` package """ __name__ = "biotite.structure" __author__ = "Patrick Kunzmann" __all__ = ["vector_dot", "norm_vector", "distance", "matrix_rotate"] import numpy as np def vector_dot(v1,v2): """ Calculate vector dot product of two vectors. Parameters ---------- v1,v2 : ndarray The arrays to calculate the product from. The vectors are represented by the last axis. Returns ------- product : float or ndarray Scalar product over the last dimension of the arrays. """ return (v1*v2).sum(axis=-1) def norm_vector(v): """ Normalise a vector. Parameters ---------- v : ndarray The array containg the vector(s). The vectors are represented by the last axis. """ factor = np.linalg.norm(v, axis=-1) if isinstance(factor, np.ndarray): v /= factor[..., np.newaxis] else: v /= factor def distance(v1,v2): """ Calculate the distance between two position vectors. Parameters ---------- v1,v2 : ndarray The arrays to calculate the product from. The vectors are represented by the last axis. Returns ------- product : float or ndarray Vector distance over the last dimension of the array. """ dif = v1 - v2 return np.sqrt((dif*dif).sum(axis=-1)) def matrix_rotate(v, matrix): """ Perform a rotation using a rotation matrix. Parameters ---------- v : ndarray The coordinates to rotate. matrix : ndarray The rotation matrix. Returns ------- rotated : ndarray The rotated coordinates. """ # For proper rotation reshape into a maximum of 2 dimensions orig_ndim = v.ndim if orig_ndim > 2: orig_shape = v.shape v = v.reshape(-1, 3) # Apply rotation v = np.dot(matrix, v.T).T # Reshape back into original shape if orig_ndim > 2: v = v.reshape(*orig_shape) return v
[ "patrick.kunzm@gmail.com" ]
patrick.kunzm@gmail.com
742ed5a7da53469a0161d9225e9841a8d8cd06b4
90ec9a009d84dd7eebbd93de4f4b9de553326a39
/app/customer/views.py
f18aa6381cc21c8fb4bfde7ab8a60775f87a3157
[]
no_license
alexiuasse/NipponArDjango
18a86bb108b9d72b36c8adf7c4344398cc4ca6b2
ddc541a8d7e4428bde63c56f44354d6f82e0f40d
refs/heads/master
2023-08-03T12:16:56.431870
2021-07-15T23:43:33
2021-07-15T23:43:33
278,093,323
0
0
null
2021-09-22T20:04:15
2020-07-08T13:13:22
CSS
UTF-8
Python
false
false
7,674
py
# Created by Alex Matos Iuasse. # Copyright (c) 2020. All rights reserved. # Last modified 24/08/2020 17:44. from typing import Dict, Any from django.contrib.admin.utils import NestedObjects from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin from django.shortcuts import render from django.urls import reverse_lazy from django.views import View from django.views.generic.edit import DeleteView, CreateView, UpdateView from django_filters.views import FilterView from django_tables2.paginators import LazyPaginator from django_tables2.views import SingleTableMixin from .conf import * from .filters import * from .forms import * from .tables import * from frontend.icons import ICON_PERSON, ICON_NEW_PERSON class CustomerProfile(LoginRequiredMixin, View): template = 'customer/profile.html' def get(self, request, pk, tp): obj = IndividualCustomer.objects.get(pk=pk) if tp == 0 else JuridicalCustomer.objects.get(pk=pk) header = HEADER_CLASS_INDIVIDUAL_CUSTOMER if tp == 0 else HEADER_CLASS_JURIDICAL_CUSTOMER context = { 'config': { 'header': header }, 'obj': obj, } return render(request, self.template, context) class Customer(LoginRequiredMixin, View): template = 'customer/view.html' title = TITLE_VIEW_CUSTOMER subtitle = SUBTITLE_VIEW_CUSTOMER def get(self, request): links = { 'Pessoas Físicas': { 'Pessoa Física': { 'name': "Ver Todas Pessoas Físicas", 'link': reverse_lazy('customer:individualcustomer:view'), 'contextual': 'success', 'icon': ICON_PERSON, }, 'Novo Cadastro': { 'name': "Novo Cadastro", 'link': reverse_lazy('customer:individualcustomer:create'), 'contextual': 'primary', 'icon': ICON_NEW_PERSON, }, }, 'Pessoas Jurídicas': { 'Pessoa Jurídica': { 'name': "Ver Todas Pessoas Jurídicas", 'link': reverse_lazy('customer:juridicalcustomer:view'), 'contextual': 'success', 'icon': ICON_PERSON, }, 'Novo Cadastro': { 'name': "Novo Cadastro", 'link': reverse_lazy('customer:juridicalcustomer:create'), 'contextual': 'primary', 'icon': ICON_NEW_PERSON, }, }, } context = { 'title': self.title, 'subtitle': self.subtitle, 'links': links } return render(request, self.template, context) ######################################################################################################################## class IndividualCustomerView(LoginRequiredMixin, PermissionRequiredMixin, SingleTableMixin, FilterView): model = IndividualCustomer table_class = IndividualCustomerTable filterset_class = IndividualCustomerFilter paginator_class = LazyPaginator permission_required = 'customer.view_individualcustomer' template_name = 'base/view.html' title = TITLE_VIEW_INDIVIDUAL_CUSTOMER subtitle = SUBTITLE_INDIVIDUAL_CUSTOMER new = reverse_lazy('customer:individualcustomer:create') back_url = reverse_lazy('customer:index') header_class = HEADER_CLASS_INDIVIDUAL_CUSTOMER class IndividualCustomerCreate(LoginRequiredMixin, PermissionRequiredMixin, CreateView): model = IndividualCustomer form_class = IndividualCustomerForm template_name = 'customer/form.html' permission_required = 'customer.create_individualcustomer' title = TITLE_CREATE_INDIVIDUAL_CUSTOMER subtitle = SUBTITLE_INDIVIDUAL_CUSTOMER header_class = HEADER_CLASS_INDIVIDUAL_CUSTOMER @staticmethod def get_back_url(): return reverse_lazy('customer:individualcustomer:view') class IndividualCustomerEdit(LoginRequiredMixin, PermissionRequiredMixin, UpdateView): model = IndividualCustomer form_class = IndividualCustomerForm template_name = 'customer/form.html' permission_required = 'customer.edit_individualcustomer' title = TITLE_EDIT_INDIVIDUAL_CUSTOMER subtitle = SUBTITLE_INDIVIDUAL_CUSTOMER header_class = HEADER_CLASS_INDIVIDUAL_CUSTOMER # delete all services class IndividualCustomerDel(PermissionRequiredMixin, LoginRequiredMixin, DeleteView): model = IndividualCustomer template_name = "base/confirm_delete.html" permission_required = 'customer.del_individualcustomer' success_url = reverse_lazy('customer:individualcustomer:view') title = TITLE_DEL_INDIVIDUAL_CUSTOMER subtitle = SUBTITLE_INDIVIDUAL_CUSTOMER header_class = HEADER_CLASS_INDIVIDUAL_CUSTOMER def get_context_data(self, **kwargs): context: Dict[str, Any] = super().get_context_data(**kwargs) collector = NestedObjects(using='default') # or specific database collector.collect([context['object']]) to_delete = collector.nested() context['extra_object'] = to_delete return context ######################################################################################################################## class JuridicalCustomerView(LoginRequiredMixin, PermissionRequiredMixin, SingleTableMixin, FilterView): model = JuridicalCustomer table_class = JuridicalCustomerTable filterset_class = JuridicalCustomerFilter paginator_class = LazyPaginator permission_required = 'customer.view_juridicalcustomer' template_name = 'base/view.html' title = TITLE_VIEW_JURIDICAL_CUSTOMER subtitle = SUBTITLE_JURIDICAL_CUSTOMER new = reverse_lazy('customer:juridicalcustomer:create') back_url = reverse_lazy('customer:index') header_class = HEADER_CLASS_JURIDICAL_CUSTOMER class JuridicalCustomerCreate(LoginRequiredMixin, PermissionRequiredMixin, CreateView): model = JuridicalCustomer form_class = JuridicalCustomerForm template_name = 'base/form.html' permission_required = 'customer.create_juridicalcustomer' title = TITLE_CREATE_JURIDICAL_CUSTOMER subtitle = SUBTITLE_JURIDICAL_CUSTOMER header_class = HEADER_CLASS_JURIDICAL_CUSTOMER @staticmethod def get_back_url(): return reverse_lazy('customer:juridicalcustomer:view') class JuridicalCustomerEdit(LoginRequiredMixin, PermissionRequiredMixin, UpdateView): model = JuridicalCustomer form_class = JuridicalCustomerForm template_name = 'base/form.html' permission_required = 'customer.edit_juridicalcustomer' title = TITLE_EDIT_JURIDICAL_CUSTOMER subtitle = SUBTITLE_JURIDICAL_CUSTOMER header_class = HEADER_CLASS_JURIDICAL_CUSTOMER # delete all services class JuridicalCustomerDel(PermissionRequiredMixin, LoginRequiredMixin, DeleteView): model = JuridicalCustomer template_name = "base/confirm_delete.html" permission_required = 'customer.del_juridicalcustomer' success_url = reverse_lazy('customer:juridicalcustomer:view') title = TITLE_DEL_JURIDICAL_CUSTOMER subtitle = SUBTITLE_JURIDICAL_CUSTOMER header_class = HEADER_CLASS_JURIDICAL_CUSTOMER def get_context_data(self, **kwargs): context: Dict[str, Any] = super().get_context_data(**kwargs) collector = NestedObjects(using='default') # or specific database collector.collect([context['object']]) to_delete = collector.nested() context['extra_object'] = to_delete return context
[ "alexiuasse@gmail.com" ]
alexiuasse@gmail.com
a7c26984aed690a4bffc47db05dcfca2eaafb289
26f6313772161851b3b28b32a4f8d255499b3974
/Python/MaximumNestingDepthofTwoValidParenthesesStrings.py
67d4f477e9fa483c28fe2874e85607452ffd9d93
[]
no_license
here0009/LeetCode
693e634a3096d929e5c842c5c5b989fa388e0fcd
f96a2273c6831a8035e1adacfa452f73c599ae16
refs/heads/master
2023-06-30T19:07:23.645941
2021-07-31T03:38:51
2021-07-31T03:38:51
266,287,834
1
0
null
null
null
null
UTF-8
Python
false
false
1,751
py
""" A string is a valid parentheses string (denoted VPS) if and only if it consists of "(" and ")" characters only, and: It is the empty string, or It can be written as AB (A concatenated with B), where A and B are VPS's, or It can be written as (A), where A is a VPS. We can similarly define the nesting depth depth(S) of any VPS S as follows: depth("") = 0 depth(A + B) = max(depth(A), depth(B)), where A and B are VPS's depth("(" + A + ")") = 1 + depth(A), where A is a VPS. For example, "", "()()", and "()(()())" are VPS's (with nesting depths 0, 1, and 2), and ")(" and "(()" are not VPS's. Given a VPS seq, split it into two disjoint subsequences A and B, such that A and B are VPS's (and A.length + B.length = seq.length). Now choose any such A and B such that max(depth(A), depth(B)) is the minimum possible value. Return an answer array (of length seq.length) that encodes such a choice of A and B: answer[i] = 0 if seq[i] is part of A, else answer[i] = 1. Note that even though multiple answers may exist, you may return any of them. Example 1: Input: seq = "(()())" Output: [0,1,1,1,1,0] Example 2: Input: seq = "()(())()" Output: [0,0,0,1,1,0,1,1] Constraints: 1 <= seq.size <= 10000 """ class Solution: def maxDepthAfterSplit(self, seq: str): res = [0]*len(seq) stack = [] num = -1 for i,s in enumerate(seq): if s == '(': num += 1 stack.append(num) res[i] = num elif s == ')': num -= 1 res[i] = stack.pop() # print(res) return [i%2 for i in res] S = Solution() seq = "(()())" print(S.maxDepthAfterSplit(seq)) seq = "()(())()" print(S.maxDepthAfterSplit(seq))
[ "here0009@163.com" ]
here0009@163.com
f7dd8f55dc709f693b0211d8fcd73662147731f0
5574620c834f96d4baf50d6aa349242dae7c17af
/41.first-missing-positive.py
76b5ddd14a2ff4b66c5f2817265ba08c132b15ab
[]
no_license
Ming-H/leetcode
52dceba5f9a605afbdaa65e286a37205873e21bb
057cee4b830603ac12976ed7d5cea8d06a9b46a0
refs/heads/main
2023-09-02T21:30:48.796395
2023-09-01T01:59:48
2023-09-01T01:59:48
489,290,172
1
0
null
null
null
null
UTF-8
Python
false
false
870
py
# # @lc app=leetcode id=41 lang=python3 # # [41] First Missing Positive # class Solution: def firstMissingPositive(self, nums): """ 不能用额外空间,那就只有利用数组本身,跟Counting sort一样, 利用数组的index来作为数字本身的索引,把正数按照递增顺序依次放到数组中。 即让A[0]=1, A[1]=2, A[2]=3, ... , 这样一来,最后如果哪个数组元素 违反了A[i]=i+1即说明i+1就是我们要求的第一个缺失的正数。 """ for i in range(len(nums)): while 0 <= nums[i]-1 < len(nums) and nums[nums[i]-1] != nums[i]: tmp = nums[i]-1 nums[i], nums[tmp] = nums[tmp], nums[i] for i in range(len(nums)): if nums[i] != i+1: return i+1 return len(nums)+1
[ "1518246548@qq.com" ]
1518246548@qq.com
d28bf400e50f8c6d766ed1c1fb8dc15f1e4e723f
a3c662a5eda4e269a8c81c99e229879b946a76f6
/.venv/lib/python3.7/site-packages/pylint/test/functional/trailing_comma_tuple.py
a832ccc28973265a5df8150f54034ca8fc5a239a
[ "MIT" ]
permissive
ahmadreza-smdi/ms-shop
0c29da82c58b243507575672bbc94fb6e8068aeb
65ba3f3061e2ac5c63115b08dadfe7d67f645fb6
refs/heads/master
2023-04-27T19:51:34.858182
2019-11-24T20:57:59
2019-11-24T20:57:59
223,616,552
6
2
MIT
2023-04-21T20:51:21
2019-11-23T16:09:03
Python
UTF-8
Python
false
false
732
py
"""Check trailing comma one element tuples.""" # pylint: disable=bad-whitespace, missing-docstring AAA = 1, # [trailing-comma-tuple] BBB = "aaaa", # [trailing-comma-tuple] CCC="aaa", # [trailing-comma-tuple] FFF=['f'], # [trailing-comma-tuple] BBB = 1, 2 CCC = (1, 2, 3) DDD = ( 1, 2, 3, ) EEE = ( "aaa", ) def test(*args, **kwargs): return args, kwargs test(widget=1, label='test') test(widget=1, label='test') test(widget=1, \ label='test') def some_func(first, second): if first: return first, # [trailing-comma-tuple] if second: return (first, second,) return first, second, # [trailing-comma-tuple] def some_other_func(): yield 'hello', # [trailing-comma-tuple]
[ "ahmadreza.smdi@gmail.com" ]
ahmadreza.smdi@gmail.com
283575d0431210f70f269274660f9a4d6ba55839
667c324c7e8ac6a38cc91cd8ec4921a0dc9a0492
/backend/accounts/models.py
1340ee3158c537192b304432dd0f40f65bb50e5d
[]
no_license
litvaOo/elmy-clone
86fdf80fff91642c088fa3cee50bd4ad32518afd
eb30b5fd2eb8cfc177f3c6fec53d61722c7fe9cd
refs/heads/master
2021-05-08T02:33:48.277250
2017-10-23T16:11:21
2017-10-23T16:11:21
108,006,369
0
0
null
null
null
null
UTF-8
Python
false
false
1,013
py
from django.db import models from django.contrib.auth.models import AbstractUser class ServiceProvider(models.Model): rating = models.DecimalField(max_digits=2, decimal_places=1) description = models.CharField(max_length=1000) latitude = models.FloatField(default=0) longitude = models.FloatField(default=0) city = models.CharField(max_length=30, blank=True, null=True) class Client(models.Model): previous_buys = models.IntegerField(blank=True, null=True, default=0) class CustomUser(AbstractUser): phone = models.CharField(max_length=12, blank=True, null=True) bank_account = models.CharField(max_length=16, blank=True, null=True) customer = models.OneToOneField(Client, blank=True, null=True) provider = models.OneToOneField(ServiceProvider, blank=True, null=True) def __str__(self): try: return "Username: {0}, city: {1}".format(self.username, self.provider.city) except: return self.username # Create your models here.
[ "alexander.ksenzov@gmail.com" ]
alexander.ksenzov@gmail.com
8bac119f9df15d577d94fded7585b260efde9cc7
a563a95e0d5b46158ca10d6edb3ca5d127cdc11f
/tccli/services/captcha/captcha_client.py
8382673aac4f34d3d54b5528b41376e67b95efa9
[ "Apache-2.0" ]
permissive
SAIKARTHIGEYAN1512/tencentcloud-cli
e93221e0a7c70f392f79cda743a86d4ebbc9a222
d129f1b3a943504af93d3d31bd0ac62f9d56e056
refs/heads/master
2020-08-29T09:20:23.790112
2019-10-25T09:30:39
2019-10-25T09:30:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,063
py
# -*- coding: utf-8 -*- import os import json import tccli.options_define as OptionsDefine import tccli.format_output as FormatOutput from tccli.nice_command import NiceCommand import tccli.error_msg as ErrorMsg import tccli.help_template as HelpTemplate from tccli import __version__ from tccli.utils import Utils from tccli.configure import Configure from tencentcloud.common import credential from tencentcloud.common.profile.http_profile import HttpProfile from tencentcloud.common.profile.client_profile import ClientProfile from tencentcloud.captcha.v20190722 import captcha_client as captcha_client_v20190722 from tencentcloud.captcha.v20190722 import models as models_v20190722 from tccli.services.captcha import v20190722 from tccli.services.captcha.v20190722 import help as v20190722_help def doDescribeCaptchaResult(argv, arglist): g_param = parse_global_arg(argv) if "help" in argv: show_help("DescribeCaptchaResult", g_param[OptionsDefine.Version]) return param = { "CaptchaType": Utils.try_to_json(argv, "--CaptchaType"), "Ticket": argv.get("--Ticket"), "UserIp": argv.get("--UserIp"), "Randstr": argv.get("--Randstr"), "CaptchaAppId": Utils.try_to_json(argv, "--CaptchaAppId"), "AppSecretKey": argv.get("--AppSecretKey"), "BusinessId": Utils.try_to_json(argv, "--BusinessId"), "SceneId": Utils.try_to_json(argv, "--SceneId"), "MacAddress": argv.get("--MacAddress"), "Imei": argv.get("--Imei"), } cred = credential.Credential(g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey]) http_profile = HttpProfile( reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]), reqMethod="POST", endpoint=g_param[OptionsDefine.Endpoint] ) profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256") mod = CLIENT_MAP[g_param[OptionsDefine.Version]] client = mod.CaptchaClient(cred, g_param[OptionsDefine.Region], profile) client._sdkVersion += ("_CLI_" + __version__) models = MODELS_MAP[g_param[OptionsDefine.Version]] model = models.DescribeCaptchaResultRequest() model.from_json_string(json.dumps(param)) rsp = client.DescribeCaptchaResult(model) result = rsp.to_json_string() jsonobj = None try: jsonobj = json.loads(result) except TypeError as e: jsonobj = json.loads(result.decode('utf-8')) # python3.3 FormatOutput.output("action", jsonobj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter]) CLIENT_MAP = { "v20190722": captcha_client_v20190722, } MODELS_MAP = { "v20190722": models_v20190722, } ACTION_MAP = { "DescribeCaptchaResult": doDescribeCaptchaResult, } AVAILABLE_VERSION_LIST = [ v20190722.version, ] AVAILABLE_VERSIONS = { 'v' + v20190722.version.replace('-', ''): {"help": v20190722_help.INFO,"desc": v20190722_help.DESC}, } def captcha_action(argv, arglist): if "help" in argv: versions = sorted(AVAILABLE_VERSIONS.keys()) opt_v = "--" + OptionsDefine.Version version = versions[-1] if opt_v in argv: version = 'v' + argv[opt_v].replace('-', '') if version not in versions: print("available versions: %s" % " ".join(AVAILABLE_VERSION_LIST)) return action_str = "" docs = AVAILABLE_VERSIONS[version]["help"] desc = AVAILABLE_VERSIONS[version]["desc"] for action, info in docs.items(): action_str += " %s\n" % action action_str += Utils.split_str(" ", info["desc"], 120) helpstr = HelpTemplate.SERVICE % {"name": "captcha", "desc": desc, "actions": action_str} print(helpstr) else: print(ErrorMsg.FEW_ARG) def version_merge(): help_merge = {} for v in AVAILABLE_VERSIONS: for action in AVAILABLE_VERSIONS[v]["help"]: if action not in help_merge: help_merge[action] = {} help_merge[action]["cb"] = ACTION_MAP[action] help_merge[action]["params"] = [] for param in AVAILABLE_VERSIONS[v]["help"][action]["params"]: if param["name"] not in help_merge[action]["params"]: help_merge[action]["params"].append(param["name"]) return help_merge def register_arg(command): cmd = NiceCommand("captcha", captcha_action) command.reg_cmd(cmd) cmd.reg_opt("help", "bool") cmd.reg_opt(OptionsDefine.Version, "string") help_merge = version_merge() for actionName, action in help_merge.items(): c = NiceCommand(actionName, action["cb"]) cmd.reg_cmd(c) c.reg_opt("help", "bool") for param in action["params"]: c.reg_opt("--" + param, "string") for opt in OptionsDefine.ACTION_GLOBAL_OPT: stropt = "--" + opt c.reg_opt(stropt, "string") def parse_global_arg(argv): params = {} for opt in OptionsDefine.ACTION_GLOBAL_OPT: stropt = "--" + opt if stropt in argv: params[opt] = argv[stropt] else: params[opt] = None if params[OptionsDefine.Version]: params[OptionsDefine.Version] = "v" + params[OptionsDefine.Version].replace('-', '') config_handle = Configure() profile = config_handle.profile if ("--" + OptionsDefine.Profile) in argv: profile = argv[("--" + OptionsDefine.Profile)] is_conexist, conf_path = config_handle._profile_existed(profile + "." + config_handle.configure) is_creexist, cred_path = config_handle._profile_existed(profile + "." + config_handle.credential) config = {} cred = {} if is_conexist: config = config_handle._load_json_msg(conf_path) if is_creexist: cred = config_handle._load_json_msg(cred_path) for param in params.keys(): if param == OptionsDefine.Version: continue if params[param] is None: if param in [OptionsDefine.SecretKey, OptionsDefine.SecretId]: if param in cred: params[param] = cred[param] else: raise Exception("%s is invalid" % param) else: if param in config: params[param] = config[param] elif param == OptionsDefine.Region: raise Exception("%s is invalid" % OptionsDefine.Region) try: if params[OptionsDefine.Version] is None: version = config["captcha"][OptionsDefine.Version] params[OptionsDefine.Version] = "v" + version.replace('-', '') if params[OptionsDefine.Endpoint] is None: params[OptionsDefine.Endpoint] = config["captcha"][OptionsDefine.Endpoint] except Exception as err: raise Exception("config file:%s error, %s" % (conf_path, str(err))) versions = sorted(AVAILABLE_VERSIONS.keys()) if params[OptionsDefine.Version] not in versions: raise Exception("available versions: %s" % " ".join(AVAILABLE_VERSION_LIST)) return params def show_help(action, version): docs = AVAILABLE_VERSIONS[version]["help"][action] desc = AVAILABLE_VERSIONS[version]["desc"] docstr = "" for param in docs["params"]: docstr += " %s\n" % ("--" + param["name"]) docstr += Utils.split_str(" ", param["desc"], 120) helpmsg = HelpTemplate.ACTION % {"name": action, "service": "captcha", "desc": desc, "params": docstr} print(helpmsg) def get_actions_info(): config = Configure() new_version = max(AVAILABLE_VERSIONS.keys()) version = new_version try: profile = config._load_json_msg(os.path.join(config.cli_path, "default.configure")) version = profile["captcha"]["version"] version = "v" + version.replace('-', '') except Exception: pass if version not in AVAILABLE_VERSIONS.keys(): version = new_version return AVAILABLE_VERSIONS[version]["help"]
[ "tencentcloudapi@tencent.com" ]
tencentcloudapi@tencent.com
69e1dec6b346397c1857340caf4299600c26a600
2fe8194db578820629740e7022326355ef76632a
/instaladores/migrations/0004_merge_20201128_1647.py
52b65ade950c986c1f9bf531762ba99d0d9e0cfe
[]
no_license
Aleleonel/newloma
01213a14036aa7437b5951b8bb7ef202de6b86c2
7910c5b3170b953134240536b6e5376c96382266
refs/heads/master
2023-01-18T19:15:08.890658
2020-11-28T20:22:48
2020-11-28T20:22:48
312,459,505
0
0
null
null
null
null
UTF-8
Python
false
false
283
py
# Generated by Django 3.1.3 on 2020-11-28 19:47 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('instaladores', '0003_instaladores_email'), ('instaladores', '0002_auto_20201122_1232'), ] operations = [ ]
[ "you@example.com" ]
you@example.com
d90fb9bc6062203554935aaa9d2091c9aa8edcdb
72579db4299be6d512a766ce38ae50e3c7753368
/.history/Pythonlearning/day9_20200802091221.py
c5ab6ce577d7bd4429235686a4956391bbf742ca
[]
no_license
moteily/Python_Learning
f0d1abf360ad417112051ba52f32a141452adb2d
c294aa1e373254739fb372918507cd7dbe12c999
refs/heads/master
2022-11-26T11:09:48.145308
2020-08-04T08:47:15
2020-08-04T08:47:15
284,379,822
0
0
null
null
null
null
UTF-8
Python
false
false
230
py
#接上一天的第九章 # 静态方法和类方法: # 定义和表示:静态方法和类方法 class Myclass: def smeth(): print('This is a static method')\ smeth = staticmethod(smeth) def cmeth(cls)
[ "994283977@qq.com" ]
994283977@qq.com
5fba23b3bfb05e91ac578ebeb773c34c16a2d760
a5a99f646e371b45974a6fb6ccc06b0a674818f2
/RecoEgamma/EgammaIsolationAlgos/python/eleTrackExtractorBlocks_cff.py
a0465cbb16938dc958035bcbba12f0a0b49dbf37
[ "Apache-2.0" ]
permissive
cms-sw/cmssw
4ecd2c1105d59c66d385551230542c6615b9ab58
19c178740257eb48367778593da55dcad08b7a4f
refs/heads/master
2023-08-23T21:57:42.491143
2023-08-22T20:22:40
2023-08-22T20:22:40
10,969,551
1,006
3,696
Apache-2.0
2023-09-14T19:14:28
2013-06-26T14:09:07
C++
UTF-8
Python
false
false
643
py
import FWCore.ParameterSet.Config as cms EleIsoTrackExtractorBlock = cms.PSet( ComponentName = cms.string('EgammaTrackExtractor'), inputTrackCollection = cms.InputTag("generalTracks"), DepositLabel = cms.untracked.string(''), Diff_r = cms.double(9999.0), Diff_z = cms.double(0.2), DR_Max = cms.double(1.0), DR_Veto = cms.double(0.0), BeamlineOption = cms.string('BeamSpotFromEvent'), BeamSpotLabel = cms.InputTag("offlineBeamSpot"), NHits_Min = cms.uint32(0), Chi2Ndof_Max = cms.double(1e+64), Chi2Prob_Min = cms.double(-1.0), Pt_Min = cms.double(-1.0), dzOption = cms.string("vz") )
[ "giulio.eulisse@gmail.com" ]
giulio.eulisse@gmail.com
0f679e9becb942faabe154fdacf30c7f881b2d4f
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_201/671.py
42a2e415e2dafaa7888c38febad69fbcb7a3fdab
[]
no_license
dr-dos-ok/Code_Jam_Webscraper
c06fd59870842664cd79c41eb460a09553e1c80a
26a35bf114a3aa30fc4c677ef069d95f41665cc0
refs/heads/master
2020-04-06T08:17:40.938460
2018-10-14T10:12:47
2018-10-14T10:12:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,988
py
FILE_NAME = 'C-large'; INPUT_FILE = FILE_NAME+'.in'; OUTPUT_FILE = FILE_NAME+'.out'; def algorithm(N, K): segments = [N] while K > 0: segments.sort(reverse=True) biggest_segment = segments[0] del segments[0] if(biggest_segment % 2 == 0): left = biggest_segment / 2 - 1 right = biggest_segment / 2 else: left = right = biggest_segment / 2 segments.append(right) segments.append(left) K -= 1 result = segments[-2:] return str(result[0]) + " " + str(result[1]) def solve(data): N = int(data[0]) K = int(data[1]) log2 = K.bit_length() - 1 pow_log2 = 2**log2 Kscaled = K/pow_log2 Nscaled = N/pow_log2 if N%pow_log2 < K%pow_log2: Nscaled -= 1 return str(algorithm(Nscaled, Kscaled)); def run(): with open(INPUT_FILE) as in_file: lines = in_file.readlines() n_tests = int(lines[0]); out_file = open(OUTPUT_FILE,'w') count = 1 for i in range(1,len(lines)): result = solve(lines[i].split()) string_result = "Case #%d: %s\n" % (count,result) out_file.write(string_result); print string_result count += 1 # def debug(N, K): # print "-------" # L = K.bit_length() - 1 # print "division power 2: ", N/2**L, K/2**L # print "reminder: ", N%(2**L), K%(2**L) # print "correct: " , algorithm(N, K) # print N, K, 2**L # print "fast: ", algorithm(N/2**L , K/2**L) # print "-------" # def correct(N, K): # global TEST_COUNT # L = K.bit_length() - 1 # L2 = 2**L # Ntest = N/L2 # if N%L2 < K%L2: # Ntest -= 1 # Ktest = K/L2 # correct = algorithm(N, K) # test = algorithm(Ntest, Ktest) # if correct == test: # #print N, K, L2, "!", N/L2, Ktest, "!", N%L2, K%L2, correct == test, "!", N-K # print N%L2 < K%L2 # #print correct # #print algorithm(Ntest + 1 , Ktest) # #print algorithm(Ntest - 1 , Ktest) # #print "-----" run()
[ "miliar1732@gmail.com" ]
miliar1732@gmail.com
be370b1c9635cd0f42269dd7fcec37bb899a703c
f0ef364ed2d20390ff76bc7c5b9506cb41ba2e71
/widgets4py/websocket/examples/w2ui_toolbar_example.py
9f430804dd5066d43512e58a6ed47619c6c1eb7f
[]
no_license
singajeet/widgets4py
07c983e06d6101b6421bf96224fa1bcc3793f47a
e3ca6a459dee896af755278257a914efe04b1d11
refs/heads/master
2020-06-09T19:08:20.295781
2020-02-14T15:55:23
2020-02-14T15:55:23
193,489,543
1
0
null
null
null
null
UTF-8
Python
false
false
4,188
py
import os import webview from flask import Flask # , url_for from flask_socketio import SocketIO from widgets4py.base import Page from widgets4py.websocket.w2ui.ui import Toolbar, ToolbarButton, ToolbarCheck from widgets4py.websocket.w2ui.ui import ToolbarHTML, ToolbarMenu, ToolbarMenuCheck from widgets4py.websocket.w2ui.ui import ToolbarMenuRadio, ToolbarRadio, ToolbarSeparator from widgets4py.websocket.w2ui.ui import ToolbarDropDown, ToolbarSpacer from multiprocessing import Process app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app, async_mode=None) class W2UIPage: pg = None toolbar = None tool_btn = None tool_chk = None tool_html = None tool_menu = None tool_menu_chk = None tool_menu_rd = None tool_rd = None tool_sep = None tool_dd = None tool_spacer = None def show_layout(self): self.pg = Page('myPage', 'My Page') self.toolbar = Toolbar('toolbar', socketio, onclick_callback=self._toolbar_clicked) self.tool_btn = ToolbarButton('toolbtn', 'Button') self.tool_chk = ToolbarCheck('tool_chk', 'Check') self.tool_dd = ToolbarDropDown('tool_dd', 'My DropDown content', 'DropDown') self.tool_html = ToolbarHTML('tool_html', '<input type=text />', 'Html') self.tool_menu = ToolbarMenu('tool_menu', 'Actions') self.tool_menu.add_item('Add') self.tool_menu.add_item('Insert') self.tool_menu.add_item('Remove') self.tool_menu.add_item('Show') self.tool_menu.add_item('Hide') self.tool_menu.add_item('Enable') self.tool_menu.add_item('Disable') self.tool_menu_chk = ToolbarMenuCheck('tool_menu_chk', 'MenuCheck') self.tool_menu_chk.add_item('item1', 'Item1') self.tool_menu_chk.add_item('item2', 'Item2') self.tool_menu_rd = ToolbarMenuRadio('tool_menu_rd', 'MenuRadio') self.tool_menu_rd.add_item('item1', 'Item1') self.tool_menu_rd.add_item('item2', 'Item2') self.tool_rd = ToolbarRadio('tool_rd', 'Radio') self.tool_sep = ToolbarSeparator('tool_sep', 'Sep') self.tool_spacer = ToolbarSpacer('tool_spacer', 'Spac') self.toolbar.add(self.tool_btn) self.toolbar.add(self.tool_chk) self.toolbar.add(self.tool_dd) self.toolbar.add(self.tool_html) self.toolbar.add(self.tool_menu) self.toolbar.add(self.tool_menu_chk) self.toolbar.add(self.tool_menu_rd) self.toolbar.add(self.tool_rd) self.toolbar.add(self.tool_sep) self.toolbar.add(self.tool_spacer) self.pg.add(self.toolbar) content = self.pg.render() return content def _toolbar_clicked(self, name, props): menu = self.toolbar.clicked_item if str(menu).find(':') > 0: item = str(menu).split(':')[1] if item.upper() == 'ADD': new_btn = ToolbarButton('new_btn', 'New Button') self.toolbar.add_item(new_btn) if item.upper() == 'INSERT': new_ins_btn = ToolbarButton('new_ins_btn', 'New Insert Button') self.toolbar.insert_item(new_ins_btn, 'tool_btn') if item.upper() == 'REMOVE': self.toolbar.remove_item('new_ins_btn') if item.upper() == 'HIDE': self.toolbar.hide_item('toolbtn') if item.upper() == 'SHOW': self.toolbar.show_item('toolbtn') if item.upper() == 'ENABLE': self.toolbar.enable_item('toolbtn') if item.upper() == 'DISABLE': self.toolbar.disable_item('toolbtn') def start_app(): p = W2UIPage() app.add_url_rule('/', 'index', p.show_layout) socketio.run(app, debug=True) def start_web_view(): webview.create_window("My Application", "http://localhost:5000", resizable=True) if __name__ == "__main__": if os.uname().machine == 'aarch64': start_app() else: app_proc = Process(target=start_app) web_app = Process(target=start_web_view) app_proc.start() web_app.start() app_proc.join() web_app.join()
[ "singajeet@gmail.com" ]
singajeet@gmail.com
23ee2ea3fb54a9d1d459ca0edb986191ba823dca
3f7240da3dc81205a0a3bf3428ee4e7ae74fb3a2
/src/Week9/Efficiency/Sequencing.py
5cd59f4ad5c2b4f90a8180536091d1c58517304a
[]
no_license
theguyoverthere/CMU15-112-Spring17
b4ab8e29c31410b4c68d7b2c696a76b9d85ab4d8
b8287092b14e82d2a3aeac6c27bffbc95382eb34
refs/heads/master
2021-04-27T08:52:45.237631
2018-10-02T15:38:18
2018-10-02T15:38:18
107,882,442
0
0
null
null
null
null
UTF-8
Python
false
false
305
py
# what is the total cost here? L = [ 52, 83, 78, 9, 12, 4 ] # assume L is an arbitrary list of length N L.sort() # This is O(NlogN) L.sort(reverse=True) # This is O(NlogN) L[0] -= 5 # This is O(1) print(L.count(L[0]) + sum(L)) # This is O(N) + O(N)
[ "tariqueanwer@outlook.com" ]
tariqueanwer@outlook.com
ee1620b5cccb60aa52d2725d3e10e369eb226f0f
32eeb97dff5b1bf18cf5be2926b70bb322e5c1bd
/benchmark/suntimes/testcase/firstcases/testcase1_004.py
af83c435e940513a3fe6bb22542eaddd2ba85ec4
[]
no_license
Prefest2018/Prefest
c374d0441d714fb90fca40226fe2875b41cf37fc
ac236987512889e822ea6686c5d2e5b66b295648
refs/heads/master
2021-12-09T19:36:24.554864
2021-12-06T12:46:14
2021-12-06T12:46:14
173,225,161
5
0
null
null
null
null
UTF-8
Python
false
false
4,328
py
#coding=utf-8 import os import subprocess import time import traceback from appium import webdriver from appium.webdriver.common.touch_action import TouchAction from selenium.common.exceptions import NoSuchElementException, WebDriverException desired_caps = { 'platformName' : 'Android', 'deviceName' : 'Android Emulator', 'platformVersion' : '4.4', 'appPackage' : 'com.forrestguice.suntimeswidget', 'appActivity' : 'com.forrestguice.suntimeswidget.SuntimesActivity', 'resetKeyboard' : True, 'androidCoverage' : 'com.forrestguice.suntimeswidget/com.forrestguice.suntimeswidget.JacocoInstrumentation', 'noReset' : True } def command(cmd, timeout=5): p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True) time.sleep(timeout) p.terminate() return def getElememt(driver, str) : for i in range(0, 5, 1): try: element = driver.find_element_by_android_uiautomator(str) except NoSuchElementException: time.sleep(1) else: return element os.popen("adb shell input tap 50 50") element = driver.find_element_by_android_uiautomator(str) return element def getElememtBack(driver, str1, str2) : for i in range(0, 2, 1): try: element = driver.find_element_by_android_uiautomator(str1) except NoSuchElementException: time.sleep(1) else: return element for i in range(0, 5, 1): try: element = driver.find_element_by_android_uiautomator(str2) except NoSuchElementException: time.sleep(1) else: return element os.popen("adb shell input tap 50 50") element = driver.find_element_by_android_uiautomator(str2) return element def swipe(driver, startxper, startyper, endxper, endyper) : size = driver.get_window_size() width = size["width"] height = size["height"] try: driver.swipe(start_x=int(width * startxper), start_y=int(height * startyper), end_x=int(width * endxper), end_y=int(height * endyper), duration=2000) except WebDriverException: time.sleep(1) driver.swipe(start_x=int(width * startxper), start_y=int(height * startyper), end_x=int(width * endxper), end_y=int(height * endyper), duration=2000) return # testcase004 try : starttime = time.time() driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps) element = getElememtBack(driver, "new UiSelector().text(\"moonrise\")", "new UiSelector().className(\"android.widget.TextView\").instance(9)") TouchAction(driver).tap(element).perform() element = getElememtBack(driver, "new UiSelector().text(\"2:50\")", "new UiSelector().className(\"android.widget.TextView\").instance(4)") TouchAction(driver).tap(element).perform() element = getElememtBack(driver, "new UiSelector().text(\"sunrise\")", "new UiSelector().className(\"android.widget.TextView\").instance(2)") TouchAction(driver).tap(element).perform() driver.press_keycode(4) element = getElememtBack(driver, "new UiSelector().text(\"sunrise\")", "new UiSelector().className(\"android.widget.TextView\").instance(5)") TouchAction(driver).tap(element).perform() element = getElememtBack(driver, "new UiSelector().text(\"sunrise\")", "new UiSelector().className(\"android.widget.TextView\").instance(3)") TouchAction(driver).tap(element).perform() element = getElememtBack(driver, "new UiSelector().text(\"sunrise\")", "new UiSelector().className(\"android.widget.TextView\").instance(2)") TouchAction(driver).tap(element).perform() element = getElememt(driver, "new UiSelector().className(\"android.widget.TextView\").instance(2)") TouchAction(driver).long_press(element).release().perform() element = getElememtBack(driver, "new UiSelector().text(\"sunset\")", "new UiSelector().className(\"android.widget.TextView\").instance(1)") TouchAction(driver).tap(element).perform() swipe(driver, 0.5, 0.2, 0.5, 0.8) except Exception, e: print 'FAIL' print 'str(e):\t\t', str(e) print 'repr(e):\t', repr(e) print traceback.format_exc() else: print 'OK' finally: cpackage = driver.current_package endtime = time.time() print 'consumed time:', str(endtime - starttime), 's' command("adb shell am broadcast -a com.example.pkg.END_EMMA --es name \"1_004\"") jacocotime = time.time() print 'jacoco time:', str(jacocotime - endtime), 's' driver.quit() if (cpackage != 'com.forrestguice.suntimeswidget'): cpackage = "adb shell am force-stop " + cpackage os.popen(cpackage)
[ "prefest2018@gmail.com" ]
prefest2018@gmail.com
9dbc5aad569ad45d58831448aa34a51bc8258984
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02996/s612893539.py
7bab9fefb9759e4aca7500b4bfc54fe21ec5e098
[]
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
663
py
import sys import math import itertools import bisect from copy import copy from collections import deque,Counter from decimal import Decimal def s(): return input() def i(): return int(input()) def S(): return input().split() def I(): return map(int,input().split()) def L(): return list(input().split()) def l(): return list(map(int,input().split())) def lcm(a,b): return a*b//math.gcd(a,b) sys.setrecursionlimit(10 ** 9) mod = 10**9+7 S = i() time = [] for i in range(S): a = l() a.reverse() time.append(a) time.sort() pl = 0 for i in range(S): pl += time[i][1] if pl > time[i][0]: print("No") sys.exit() print("Yes")
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
2146132029e154c9162b74995f0cf34f0ef3342e
60654caf2633613021470d0285817343f76223e5
/daily_catch/public_update/config.py
566a37dc4796f6f4c390e00778aea0555a926b77
[]
no_license
whoiskx/com_code
79460ccee973d1dfe770af3780c273e4a0f466c9
388b5a055393ee7768cc8525c0484f19c3f97193
refs/heads/master
2020-04-09T23:14:28.228729
2018-12-06T07:10:25
2018-12-06T07:10:25
null
0
0
null
null
null
null
UTF-8
Python
false
false
641
py
# -*- coding: utf-8 -*- import os read_ver_url = 'http://dispatch.yunrunyuqing.com:38082/resources/sourceVersion/weixin/version.txt' download_url = 'http://dispatch.yunrunyuqing.com:38082/resources/sourceVersion/weixin/public_update.zip' base_path = os.path.dirname(os.path.abspath(__file__)) core_spider_path = os.path.join(base_path, 'public_update') core_zip_path = os.path.join(core_spider_path, 'public_update.zip') version_txt_path = os.path.join(core_spider_path, 'version.txt') spider_path = os.path.join(core_spider_path, 'daily_collect') run_path = os.path.join(spider_path, 'daily_collect.py') kill_path = 'daily_collect.py'
[ "574613576@qq.com" ]
574613576@qq.com
0b313513a4e40c31df181c98f2e15203095458e5
9bfd93b93531c7d66335fffded2d00db0c1f8935
/blog_censurfridns_dk/blog/translation.py
9e8157edd7537f26fe16f55c391113b0d9039730
[]
no_license
mortensteenrasmussen/blog.censurfridns.dk
7d5da3961b6abf4124fddba7b1fdf5a4fc014c2c
53939dee90ad5028256aace4c876d38695ec9e07
refs/heads/master
2021-01-14T14:23:17.443442
2016-08-29T20:11:22
2016-08-29T20:11:22
65,412,684
0
0
null
2016-08-10T20:03:31
2016-08-10T20:03:31
null
UTF-8
Python
false
false
412
py
from modeltranslation.translator import register, TranslationOptions from .models import BlogPost from taggit.models import Tag @register(BlogPost) class BlogPostTranslationOptions(TranslationOptions): fields = ('title', 'body', 'slug') required_languages = ('en', 'da') @register(Tag) class TaggitTranslations(TranslationOptions): fields = ('name','slug') required_languages = ('en', 'da')
[ "thomas@gibfest.dk" ]
thomas@gibfest.dk
60de944ffe3715da94961884dba29a2e0af82137
2937d60b7f5259b4899ba5af08146bd874529a67
/Assignment 5 q4.py
d9776a0e669e961e49153c7ebd3133b4fe52a833
[]
no_license
gourav47/Let-us-learn-python
9a2302265cb6c47e74863359c79eef5a3078358a
b324f2487de65b2f073b54c8379c1b9e9aa36298
refs/heads/master
2021-06-27T03:33:27.483992
2021-01-07T12:26:16
2021-01-07T12:26:16
204,323,390
1
1
null
2020-07-19T14:25:12
2019-08-25T16:53:56
Python
UTF-8
Python
false
false
212
py
'''python script to print square of numbers from a to b''' a=int(input("Enter the first number: ")) b=int(input("Enter second number: ")) if a>b: a,b=b,a for i in range(a,b+1): print(i**2,end=' ')
[ "noreply@github.com" ]
gourav47.noreply@github.com
d7c0d7693181b79f9f44abbeaedd2d8e7988f5ff
caa14cf78fe15affc96acc3de6f4fb1b54bcdf70
/sap/sap/saplib/tests/test_saputils.py
6eec437d874842f6cbed599b9adb923e141e3f69
[]
no_license
jesstherobot/Sycamore_FPGA
2e3f0dea21482de87ea444506ae2af3f58b5a344
d1096e15f07b17a8dcb2276e312c5ba3e0006632
refs/heads/master
2021-01-18T07:57:14.268157
2011-10-19T22:46:28
2011-10-19T22:46:28
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,689
py
import unittest import sys import os class Test (unittest.TestCase): """Unit test for saputils""" def setUp(self): os.environ["SAPLIB_BASE"] = sys.path[0] + "/saplib" #print "SAPLIB_BASE: " + os.getenv("SAPLIB_BASE") def test_create_dir(self): """create a directory""" import saputils result = saputils.create_dir("~/sandbox/projects") self.assertEqual(result, True) def test_remove_comments(self): """try and remove all comments from a buffer""" import saputils bufin = "not comment /*comment\n\n*/\n\n//comment\n\n/*\nabc\n*/soemthing//comment" #print "input buffer:\n" + bufin output_buffer = saputils.remove_comments(bufin) #print "output buffer:\n" + bufout self.assertEqual(len(output_buffer) > 0, True) def test_find_rtl_file_location(self): """give a filename that should be in the RTL""" import saputils result = saputils.find_rtl_file_location("simple_gpio.v") #print "file location: " + result try: testfile = open(result) result = True testfile.close() except: result = False self.assertEqual(result, True) def test_resolve_linux_path(self): """given a filename with or without the ~ return a filename with the ~ expanded""" import saputils filename1 = "/filename1" filename = saputils.resolve_linux_path(filename1) #print "first test: " + filename #if (filename == filename1): # print "test1: they are equal!" self.assertEqual(filename == "/filename1", True) filename2 = "~/filename2" filename = saputils.resolve_linux_path(filename2) correct_result = os.path.expanduser("~") + "/filename2" #print "second test: " + filename + " should equal to: " + correct_result #if (correct_result == filename): # print "test2: they are equal!" self.assertEqual(correct_result == filename, True) filename = filename.strip() def test_read_slave_tags(self): """try and extrapolate all info from the slave file""" import saputils base_dir = os.getenv("SAPLIB_BASE") filename = base_dir + "/hdl/rtl/wishbone/slave/simple_gpio/simple_gpio.v" drt_keywords = [ "DRT_ID", "DRT_FLAGS", "DRT_SIZE" ] tags = saputils.get_module_tags(filename, keywords = drt_keywords, debug = False) io_types = [ "input", "output", "inout" ] # #for io in io_types: # for port in tags["ports"][io].keys(): # print "Ports: " + port self.assertEqual(True, True) def test_read_slave_tags_with_params(self): """some verilog files have a paramter list""" import saputils base_dir = os.getenv("SAPLIB_BASE") filename = base_dir + "/hdl/rtl/wishbone/slave/ddr/wb_ddr.v" drt_keywords = [ "DRT_ID", "DRT_FLAGS", "DRT_SIZE" ] tags = saputils.get_module_tags(filename, keywords = drt_keywords, debug = True) io_types = [ "input", "output", "inout" ] # #for io in io_types: # for port in tags["ports"][io].keys(): # print "Ports: " + port print "\n\n\n\n\n\n" print "module name: " + tags["module"] print "\n\n\n\n\n\n" self.assertEqual(True, True) def test_read_hard_slave_tags(self): """try and extrapolate all info from the slave file""" import saputils base_dir = os.getenv("SAPLIB_BASE") filename = base_dir + "/hdl/rtl/wishbone/slave/ddr/wb_ddr.v" drt_keywords = [ "DRT_ID", "DRT_FLAGS", "DRT_SIZE" ] tags = saputils.get_module_tags(filename, keywords = drt_keywords, debug = True) io_types = [ "input", "output", "inout" ] # #for io in io_types: # for port in tags["ports"][io].keys(): # print "Ports: " + port self.assertEqual(True, True) if __name__ == "__main__": sys.path.append (sys.path[0] + "/../") import saputils unittest.main()
[ "cospan@gmail.com" ]
cospan@gmail.com
f7ecbb6e60d58f81414014d4eb23c770a0e6acd9
c4a8e44b171bbfcce4773fbd5820be40d991afab
/dispatcher_sample.fcgi
299c4ad0e1726445c0909f317429f2fd66a4824f
[ "MIT" ]
permissive
sveetch/DjangoSveetchies
a2462c29839d60736077f647b3014396ce700f42
0fd4f23d601287dbfb5a93b4f9baa33481466a25
refs/heads/master
2021-01-01T20:48:08.824288
2013-03-10T12:14:56
2013-03-10T12:14:56
null
0
0
null
null
null
null
UTF-8
Python
false
false
638
fcgi
#!/usr/bin/python # -*- coding: utf-8 -*- """ FastCGI dispatcher for development environment """ import sys, os sys.path.insert(0, '/home/django/py_libs') # An optionnal path where is installed some Python libs sys.path.insert(0, '/home/django/gits/') # Path to the directory which contains 'DjangoSveetchies' # Specify the temporary directory to use for Python Eggs os.environ['PYTHON_EGG_CACHE'] = "/tmp" # Set the DJANGO_SETTINGS_MODULE environment variable. os.environ['DJANGO_SETTINGS_MODULE'] = "DjangoSveetchies.prod_settings" from django.core.servers.fastcgi import runfastcgi runfastcgi(method="threaded", daemonize="false")
[ "sveetch@gmail.com" ]
sveetch@gmail.com
524a64d718c9a87331dcd95f4b5511761a102a97
3e397609ebd59d50ed0f9928e6bd039030e35f9a
/contract_api/lambda_handler.py
4757ef1411c05ce3dff3425d4a41156dd03276bb
[]
no_license
prashantramangupta/marketplace
d8f64462668f1bb15c37fd52c17236d7565e5ae5
acae91d90ec8626bc79ae46168c37a4d8bbab46a
refs/heads/master
2020-06-05T15:48:19.063615
2019-06-26T05:28:16
2019-06-26T05:28:16
159,120,771
0
0
null
null
null
null
UTF-8
Python
false
false
4,511
py
import json import logging import re import traceback from schema import Schema, And from common.constant import NETWORKS from common.repository import Repository from mpe import MPE from registry import Registry NETWORKS_NAME = dict((NETWORKS[netId]['name'], netId) for netId in NETWORKS.keys()) db = dict((netId, Repository(net_id=netId)) for netId in NETWORKS.keys()) def request_handler(event, context): print(event) if 'path' not in event: return get_response(400, "Bad Request") try: payload_dict = None resp_dta = None path = event['path'].lower() stage = event['requestContext']['stage'] net_id = NETWORKS_NAME[stage] if event['httpMethod'] == 'POST': body = event['body'] if body is not None and len(body) > 0: payload_dict = json.loads(body) elif event['httpMethod'] == 'GET': payload_dict = event.get('queryStringParameters') else: return get_response(400, "Bad Request") if path in ["/service", "/feedback"] or path[0:4] == "/org" or path[0:5] == "/user": obj_reg = Registry(obj_repo=db[net_id]) if "/org" == path: resp_dta = obj_reg.get_all_org() elif re.match("(\/service)[/]{0,1}$", path): if payload_dict is None: payload_dict = {} resp_dta = obj_reg.get_all_srvcs(qry_param=payload_dict) elif re.match("(\/org\/)[^\/]*(\/service\/)[^\/]*(\/group)[/]{0,1}$", path): params = path.split("/") org_id = params[2] service_id = params[4] resp_dta = obj_reg.get_group_info(org_id=org_id, service_id=service_id) elif "/channels" == path: obj_mpe = MPE(net_id=net_id, obj_repo=db[net_id]) resp_dta = obj_mpe.get_channels_by_user_address(payload_dict['user_address'], payload_dict.get('org_id', None), payload_dict.get('service_id', None)) elif re.match("(\/user\/)[^\/]*(\/feedback)[/]{0,1}$", path): params = path.split("/") user_address = params[2] resp_dta = get_user_feedback(user_address=user_address, obj_reg=obj_reg) elif "/feedback" == path: resp_dta = set_user_feedback(payload_dict['feedback'], obj_reg=obj_reg, net_id=net_id) else: return get_response(400, "Invalid URL path.") if resp_dta is None: err_msg = {'status': 'failed', 'error': 'Bad Request', 'api': event['path'], 'payload': payload_dict} response = get_response(500, err_msg) else: response = get_response(200, {"status": "success", "data": resp_dta}) except Exception as e: err_msg = {"status": "failed", "error": repr(e), 'api': event['path'], 'payload': payload_dict} response = get_response(500, err_msg) traceback.print_exc() return response def check_for_blank(field): if field is None or len(field) == 0: return True return False def get_user_feedback(user_address, obj_reg): if check_for_blank(user_address): return [] return obj_reg.get_usr_feedbk(user_address) def set_user_feedback(feedbk_info, obj_reg, net_id): feedbk_recorded = False schema = Schema([{'user_address': And(str), 'org_id': And(str), 'service_id': And(str), 'up_vote': bool, 'down_vote': bool, 'comment': And(str), 'signature': And(str) }]) try: feedback_data = schema.validate([feedbk_info]) feedbk_recorded = obj_reg.set_usr_feedbk(feedback_data[0], net_id=net_id) except Exception as err: print("Invalid Input ", err) return None if feedbk_recorded: return [] return None def get_response(status_code, message): return { 'statusCode': status_code, 'body': json.dumps(message), 'headers': { 'Content-Type': 'application/json', "X-Requested-With": '*', "Access-Control-Allow-Headers": 'Access-Control-Allow-Origin, Content-Type,X-Amz-Date,Authorization,X-Api-Key,x-requested-with', "Access-Control-Allow-Origin": '*', "Access-Control-Allow-Methods": 'GET,OPTIONS,POST' } }
[ "you@example.com" ]
you@example.com
ec204e589862d7db078962cf5fe0c41711f5cbcb
d2c4934325f5ddd567963e7bd2bdc0673f92bc40
/tests/artificial/transf_Logit/trend_Lag1Trend/cycle_30/ar_12/test_artificial_32_Logit_Lag1Trend_30_12_20.py
b308b4cbc07f69e3c5a3e07412703d09b5786f7b
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jmabry/pyaf
797acdd585842474ff4ae1d9db5606877252d9b8
afbc15a851a2445a7824bf255af612dc429265af
refs/heads/master
2020-03-20T02:14:12.597970
2018-12-17T22:08:11
2018-12-17T22:08:11
137,104,552
0
0
BSD-3-Clause
2018-12-17T22:08:12
2018-06-12T17:15:43
Python
UTF-8
Python
false
false
266
py
import pyaf.Bench.TS_datasets as tsds import pyaf.tests.artificial.process_artificial_dataset as art art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "Lag1Trend", cycle_length = 30, transform = "Logit", sigma = 0.0, exog_count = 20, ar_order = 12);
[ "antoine.carme@laposte.net" ]
antoine.carme@laposte.net
699bfc4d77e051f4b0b9b95cde59fbb62b5cf72d
4edbeb3e2d3263897810a358d8c95854a468c3ca
/python3/version/python_version.py
dec52afee6ab14dce005f6ae31bb0e544017de89
[ "MIT" ]
permissive
jtraver/dev
f505d15d45b67a59d11306cc7252114c265f388b
2197e3443c7619b856470558b737d85fe1f77a5a
refs/heads/master
2023-08-06T02:17:58.601861
2023-08-01T16:58:44
2023-08-01T16:58:44
14,509,952
0
1
MIT
2020-10-14T18:32:48
2013-11-19T00:51:19
Python
UTF-8
Python
false
false
672
py
#!/usr/bin/env python3 #!/usr/bin/python import os import platform import sys import aerospike def main(): print("\nos") print("os.name = %s" % str(os.name)) print("sys.platform = %s" % str(sys.platform)) print("platform.platform() = %s" % str(platform.platform())) print("\npython") print("sys.version = %s" % str(sys.version)) print("sys.version_info = %s" % str(sys.version_info)) print("sys.version_info[0] = %s" % str(sys.version_info[0])) print("\naerospike") try: print("aerospike client version is %s" % str(aerospike.__version__)) except Exception as e: print("e = %s" % str(e)) pass main()
[ "john@aeropsike.com" ]
john@aeropsike.com
bffc4998a73a001af96ff4d89986c7f07ba844b4
65f94b2fe3794b6fd682e52c7f4047a737cae6c7
/env/bin/symilar
f88c0874a96d9c0b5e2366b5b1482cc352a5092d
[]
no_license
udoyen/vgg-project-challenge
47e7e0c5352437f3df00aff9ac055dbadaadebb5
76a005edec6e77f9467b67bda20002c58abef7a9
refs/heads/master
2022-10-04T14:42:46.267458
2020-02-11T10:47:22
2020-02-11T10:47:22
238,899,753
0
1
null
2022-09-16T18:17:10
2020-02-07T10:45:53
Python
UTF-8
Python
false
false
276
#!/home/george/Documents/vgg-docs/vgg-project-challenge/env/bin/python3 # -*- coding: utf-8 -*- import re import sys from pylint import run_symilar if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(run_symilar())
[ "datameshprojects@gmail.com" ]
datameshprojects@gmail.com
19b0f1f8a7c09dc649e0cad037b8f1d8ebb8b242
81579ecd0678d652bbb57ff97529631fcfb74b12
/corehq/motech/openmrs/tests/test_repeater_helpers.py
83282f2a7427ec1fa865d3dd1356587c444939b9
[ "BSD-3-Clause" ]
permissive
dungeonmaster51/commcare-hq
64fece73671b03c1bca48cb9d1a58764d92796ea
1c70ce416564efa496fb4ef6e9130c188aea0f40
refs/heads/master
2022-12-03T21:50:26.035495
2020-08-11T07:34:59
2020-08-11T07:34:59
279,546,551
1
0
BSD-3-Clause
2020-07-31T06:13:03
2020-07-14T09:51:32
Python
UTF-8
Python
false
false
1,089
py
from unittest import skip from nose.tools import assert_regexp_matches from corehq.motech.auth import BasicAuthManager from corehq.motech.openmrs.repeater_helpers import generate_identifier from corehq.motech.requests import Requests DOMAIN = 'openmrs-test' BASE_URL = 'https://demo.mybahmni.org/openmrs/' USERNAME = 'superman' PASSWORD = 'Admin123' # Patient identifier type for use by the Bahmni Registration System # https://demo.mybahmni.org/openmrs/admin/patients/patientIdentifierType.form?patientIdentifierTypeId=3 IDENTIFIER_TYPE = '81433852-3f10-11e4-adec-0800271c1b75' @skip('Uses third-party web services') def test_generate_identifier(): auth_manager = BasicAuthManager(USERNAME, PASSWORD) requests = Requests( DOMAIN, BASE_URL, verify=False, # demo.mybahmni.org uses a self-issued cert auth_manager=auth_manager, logger=dummy_logger, ) identifier = generate_identifier(requests, IDENTIFIER_TYPE) assert_regexp_matches(identifier, r'^BAH\d{6}$') # e.g. BAH203001 def dummy_logger(*args, **kwargs): pass
[ "nhooper@dimagi.com" ]
nhooper@dimagi.com
dae9dc485e3fb180f377368fb642b0eeeb1004c6
1640189b5bf78114e2749a8ed1216e099bae9814
/src/xmlsec/rsa_x509_pem/pyasn1/debug.py
5aa42ced36ef65aadacddb629cebd74977b9d1a4
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
hfalcic/pyXMLSecurity
fb69cce12c1b417928d85b91a4c3dc87f46935ec
b29a68e6d21a0485b9190be45d532b9042fdc918
refs/heads/master
2020-04-03T13:19:13.016532
2014-07-08T17:57:55
2014-07-08T17:57:55
21,471,398
0
1
null
null
null
null
UTF-8
Python
false
false
1,512
py
import sys from .compat.octets import octs2ints from . import error from . import __version__ flagNone = 0x0000 flagEncoder = 0x0001 flagDecoder = 0x0002 flagAll = 0xffff flagMap = { 'encoder': flagEncoder, 'decoder': flagDecoder, 'all': flagAll } class Debug: defaultPrinter = sys.stderr.write def __init__(self, *flags): self._flags = flagNone self._printer = self.defaultPrinter self('running pyasn1 version %s' % __version__) for f in flags: if f not in flagMap: raise error.PyAsn1Error('bad debug flag %s' % (f,)) self._flags = self._flags | flagMap[f] self('debug category \'%s\' enabled' % f) def __str__(self): return 'logger %s, flags %x' % (self._printer, self._flags) def __call__(self, msg): self._printer('DBG: %s\n' % msg) def __and__(self, flag): return self._flags & flag def __rand__(self, flag): return flag & self._flags logger = 0 def setLogger(l): global logger logger = l def hexdump(octets): return ' '.join( [ '%s%.2X' % (n%16 == 0 and ('\n%.5d: ' % n) or '', x) for n,x in zip(range(len(octets)), octs2ints(octets)) ] ) class Scope: def __init__(self): self._list = [] def __str__(self): return '.'.join(self._list) def push(self, token): self._list.append(token) def pop(self): return self._list.pop() scope = Scope()
[ "harvey.falcic@gmail.com" ]
harvey.falcic@gmail.com
c9cbfca3f4c84cb5e219730e43194e7238cda653
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/358/usersdata/296/102792/submittedfiles/estatistica.py
79ada402f0ec9ec03a71780b75717f4fa32662f5
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
1,036
py
# -*- coding: utf-8 -*- def media(lista): soma = 0 for i in range(0,len(lista),1): soma = soma + lista[i] resultado = soma/len(lista) return resultado def media(lista): media = sum(lista)/len(lista) return media def desvio_padrao(lista): somatorio = 0 for i in range (0,len(lista),1): somatorio = ((media(lista)-lista[i])**2) + somatorio desvio = (somatorio/(n-1))**0.5 return desvio m = int(input("Digite o número da lista: ")) n = int(input("Digite o número de elementos de cada lista: ")) matriz=[] for i in range (0,m,1): matriz_linha=[] for j in range (0,n,1): matriz_linha.append(int(input("Digite o elemento (%d,%d): "%(i+1,j+1)))) matriz.append(matriz_linha) for i in range (0,m,1): print(media(matriz[i])) print("%.2f"%(desvio_padrao(matriz[i]))) #Baseado na função acima, escreva a função para calcular o desvio padrão de uma lista #Por último escreva o programa principal, que pede a entrada e chama as funções criadas.
[ "rafael.mota@ufca.edu.br" ]
rafael.mota@ufca.edu.br
9cab9dc37c46f3af6d44d688dd5c03fcf4425162
10c459a49cbc8ee2dc3bc2a8353c48b5a96f0c1d
/AI/nai_bayes.py
131804de264e30fc0df16076a4ac00543533cbaf
[]
no_license
alinzel/Demo
1a5d0e4596ab4c91d7b580da694b852495c4ddcc
cc22bbcdbd77190014e9c26e963abd7a9f4f0829
refs/heads/master
2020-03-10T22:26:30.247695
2018-04-15T15:37:28
2018-04-15T15:37:28
129,619,168
0
0
null
null
null
null
UTF-8
Python
false
false
3,994
py
import numpy as np from sklearn.naive_bayes import MultinomialNB, BernoulliNB from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import GridSearchCV from sklearn import metrics from time import time from pprint import pprint import matplotlib.pyplot as plt import matplotlib as mpl def make_test(classfier): print('分类器:', classfier) alpha_can = np.logspace(-3, 2, 10) model = GridSearchCV(classfier, param_grid={'alpha': alpha_can}, cv=5) model.set_params(param_grid={'alpha': alpha_can}) t_start = time() model.fit(x_train, y_train) t_end = time() t_train = (t_end - t_start) / (5 * alpha_can.size) print('5折交叉验证的训练时间为:%.3f秒/(5*%d)=%.3f秒' % ((t_end - t_start), alpha_can.size, t_train)) print('最优超参数为:', model.best_params_) t_start = time() y_hat = model.predict(x_test) t_end = time() t_test = t_end - t_start print('测试时间:%.3f秒' % t_test) acc = metrics.accuracy_score(y_test, y_hat) print('测试集准确率:%.2f%%' % (100 * acc)) name = str(classfier).split('(')[0] index = name.find('Classifier') if index != -1: name = name[:index] # 去掉末尾的Classifier return t_train, t_test, 1 - acc, name if __name__ == "__main__": remove = ('headers', 'footers', 'quotes') categories = 'alt.atheism', 'talk.religion.misc', 'comp.graphics', 'sci.space' # 选择四个类别进行分类 # 下载数据 data_train = fetch_20newsgroups(subset='train', categories=categories, shuffle=True, random_state=0, remove=remove) data_test = fetch_20newsgroups(subset='test', categories=categories, shuffle=True, random_state=0, remove=remove) print('训练集包含的文本数目:', len(data_train.data)) print('测试集包含的文本数目:', len(data_test.data)) print('训练集和测试集使用的%d个类别的名称:' % len(categories)) categories = data_train.target_names pprint(categories) y_train = data_train.target y_test = data_test.target print(' -- 前10个文本 -- ') for i in np.arange(10): print('文本%d(属于类别 - %s):' % (i + 1, categories[y_train[i]])) print(data_train.data[i]) print('\n\n') # tf-idf处理 vectorizer = TfidfVectorizer(input='content', stop_words='english', max_df=0.5, sublinear_tf=True) x_train = vectorizer.fit_transform(data_train.data) x_test = vectorizer.transform(data_test.data) print('训练集样本个数:%d,特征个数:%d' % x_train.shape) print('停止词:\n', end=' ') #pprint(vectorizer.get_stop_words()) feature_names = np.asarray(vectorizer.get_feature_names()) # 比较分类器结果 clfs = (MultinomialNB(), # 0.87(0.017), 0.002, 90.39% BernoulliNB(), # 1.592(0.032), 0.010, 88.54% ) result = [] for clf in clfs: r = make_test(clf) result.append(r) print('\n') result = np.array(result) time_train, time_test, err, names = result.T time_train = time_train.astype(np.float) time_test = time_test.astype(np.float) err = err.astype(np.float) x = np.arange(len(time_train)) mpl.rcParams['font.sans-serif'] = ['simHei'] mpl.rcParams['axes.unicode_minus'] = False plt.figure(figsize=(10, 7), facecolor='w') ax = plt.axes() b1 = ax.bar(x, err, width=0.25, color='#77E0A0') ax_t = ax.twinx() b2 = ax_t.bar(x + 0.25, time_train, width=0.25, color='#FFA0A0') b3 = ax_t.bar(x + 0.5, time_test, width=0.25, color='#FF8080') plt.xticks(x + 0.5, names) plt.legend([b1[0], b2[0], b3[0]], ('错误率', '训练时间', '测试时间'), loc='upper left', shadow=True) plt.title('新闻组文本数据不同分类器间的比较', fontsize=18) plt.xlabel('分类器名称') plt.grid(True) plt.tight_layout(2) plt.show()
[ "944951481@qq.com" ]
944951481@qq.com
080a6e7e8f5e0c897c92846f23df703ff1cf81f0
a8750439f200e4efc11715df797489f30e9828c6
/LeetCodeContests/87/845_longest_mountain.py
141d5018c884992b88f6afeddcd2fd5ae122f0db
[]
no_license
rajlath/rkl_codes
f657174305dc85c3fa07a6fff1c7c31cfe6e2f89
d4bcee3df2f501349feed7a26ef9828573aff873
refs/heads/master
2023-02-21T10:16:35.800612
2021-01-27T11:43:34
2021-01-27T11:43:34
110,989,354
0
0
null
null
null
null
UTF-8
Python
false
false
1,187
py
''' Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold: B.length >= 3 There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1] (Note that B could be any subarray of A, including the entire array A.) Given an array A of integers, return the length of the longest mountain. Return 0 if there is no mountain. Example 1: Input: [2,1,4,7,3,2,5] Output: 5 Explanation: The largest mountain is [1,4,7,3,2] which has length 5. Example 2: Input: [2,2,2] Output: 0 Explanation: There is no mountain. Note: 0 <= A.length <= 10000 0 <= A[i] <= 10000 ''' class Solution: def longestMountain(self, A): """ :type A: List[int] :rtype: int """ size = len(A) ans = 0 for i in range(1, size-1): if A[i] > A[i-1] and A[i] > A[i+1]: l = i - 1 r = i + 1 while l > 0 and A[l] > A[l-1]: l-= 1 while r < size-1 and A[r] > A[r+1]: r +=1 ans = max(ans, r - l + 1) return ans sol = Solution() print(sol.longestMountain([0,1,2,3,4,5,4,3,2,1,0]))
[ "raj.lath@gmail.com" ]
raj.lath@gmail.com
681440009127bf5750638d9a87a4155477b2fda3
43b34ed0be64771f236c086f716bc6a92ae3db32
/kt_ph_n.py
8073dcefb011746731594e8d83f99505915ad414
[]
no_license
elonca/LWB-benchmark-generator
ad5b6dc5e591941184056476db3ad13f01900879
7a7f28800f7574c98a3883f6edccad727dd509bc
refs/heads/main
2023-07-28T01:42:22.532324
2021-09-16T07:22:56
2021-09-16T07:22:56
407,061,367
0
0
null
2021-09-16T07:12:38
2021-09-16T07:12:37
null
UTF-8
Python
false
false
135
py
from k_ph_n import * def kt_ph_n(n): return str(kt_ph_n_f(n))[1:-1] def kt_ph_n_f(n): return left(n) |IMPLIES| Dia(right(n))
[ "u6427001@anu.edu.au" ]
u6427001@anu.edu.au
16b25ff5a3aed45017c060619a98e4dfce6a60d6
cbda89443b351bb2047180dad4e300c13dc3df7f
/Crystals/Morpurgo_sp_outer/Jobs/Pc/Pc_neut_neut_inner1_outer4/Pc_neut_neut_inner1_outer4.py
416385fcff412563b8446a40888f5125d9823323
[]
no_license
sheridanfew/pythonpolarisation
080f52979f98d26360a46412a10c8e3f51ee4549
178e2684e9a239a8e60af5f7b1eb414ac5f31e92
refs/heads/master
2021-07-10T01:07:40.978790
2021-03-11T16:56:37
2021-03-11T16:56:37
96,101,351
0
0
null
2017-07-03T13:37:06
2017-07-03T10:54:52
null
UTF-8
Python
false
false
5,279
py
import sys sys.path.append('../../../../../') from BasicElements import * from BasicElements.Register import GetRegister from BasicElements.MoleculeFactory import ReadMoleculeType from BasicElements.MoleculeFactory import GetMolecule from BasicElements.Crystal import * from Polarizability.GetDipoles import get_dipoles,split_dipoles_onto_atoms from Polarizability import * from Polarizability.GetEnergyFromDips import * from Polarizability.JMatrix import JMatrix import numpy as np from math import * from time import gmtime, strftime import os print strftime("%a, %d %b %Y %X +0000", gmtime()) name='Pc_neut_neut_inner1_outer4' #For crystals here, all cubic and centred at centre insize=1 #number of TVs in each dir central mol is from edge of inner region outsize=4 mols_cen=['Pc_mola_neut_aniso_cifstruct_chelpg.xyz','Pc_molb_neut_aniso_cifstruct_chelpg.xyz'] mols_sur=['Pc_mola_neut_aniso_cifstruct_chelpg.xyz','Pc_molb_neut_aniso_cifstruct_chelpg.xyz'] mols_outer=['sp_Pc_mola_neut.xyz','sp_Pc_molb_neut.xyz'] #From cif: ''' Pc _cell_length_a 7.900 _cell_length_b 6.060 _cell_length_c 16.010 _cell_angle_alpha 101.90 _cell_angle_beta 112.60 _cell_angle_gamma 85.80 _cell_volume 692.384 ''' #Get translation vectors: a=7.900/0.5291772109217 b=6.060/0.5291772109217 c=16.010/0.5291772109217 alpha=101.90*(pi/180) beta=112.60*(pi/180) gamma=90*(pi/180) cif_unit_cell_volume=692.384/(a*b*c*(0.5291772109217**3)) cell_volume=sqrt(1 - (cos(alpha)**2) - (cos(beta)**2) - (cos(gamma)**2) + (2*cos(alpha)*cos(beta)*cos(gamma))) #Converts frac coords to carts matrix_to_cartesian=np.matrix( [[a, b*cos(gamma), c*cos(beta)], [0, b*sin(gamma), c*(cos(alpha) - cos(beta)*cos(gamma))/sin(gamma)], [0, 0, c*cell_volume/sin(gamma)]]) #carts to frac matrix_to_fractional=matrix_to_cartesian.I #TVs, TV[0,1,2] are the three translation vectors. TV=matrix_to_cartesian.T cut=8.0 totsize=insize+outsize #number of TVs in each dir nearest c inner mol is from edge of outer region cenpos=[totsize,totsize,totsize] length=[2*totsize+1,2*totsize+1,2*totsize+1] maxTVs=insize outer_maxTVs=insize+outsize #for diamond outer, don't specify for cube and will fill to cube edges. print 'name: ',name,'mols_cen: ', mols_cen,' mols_sur: ',mols_sur,' TVs: ', TV # Place Molecules prot_neut_cry=Crystal(name=name,mols_cen=mols_cen,mols_sur=mols_sur,cenpos=cenpos,length=length,TVs=TV,maxTVs=maxTVs,mols_outer=mols_outer,outer_maxTVs=outer_maxTVs) #prot_neut_cry._mols contains all molecules. #mols[0] contains a list of all molecules in position a, mols[1] all mols in pos'n b, etc. #mols[0][x,y,z] contains molecule a in position x,y,z #mols may as such be iterated over in a number of ways to consider different molecules. prot_neut_cry().print_posns() #Calculate Properties: print strftime("%a, %d %b %Y %X +0000", gmtime()) E0 = np.matrix([0.,0.,0.]) print strftime("%a, %d %b %Y %X +0000", gmtime()) print 'Calc jm' jm = JMatrix(cutoff=cut) print strftime("%a, %d %b %Y %X +0000", gmtime()) print 'Calc dips:' d = get_dipoles(E0=E0,jm=jm._m,cutoff=cut) print strftime("%a, %d %b %Y %X +0000", gmtime()) Efield = get_electric_field(E0) potential = get_potential() print strftime("%a, %d %b %Y %X +0000", gmtime()) #print 'dips', d print 'splitting dips onto atoms' split_d = split_dipoles_onto_atoms(d) print strftime("%a, %d %b %Y %X +0000", gmtime()) print 'summing dips:' tot = np.matrix([0.,0.,0.]) for dd in split_d: tot += dd print strftime("%a, %d %b %Y %X +0000", gmtime()) print 'total dip moment', tot Uqq = np.multiply(get_U_qq(potential=potential),27.211) print strftime("%a, %d %b %Y %X +0000", gmtime()) print 'Uqq', Uqq Uqd = np.multiply(get_U_qdip(dips=d,Efield=Efield),27.211) print strftime("%a, %d %b %Y %X +0000", gmtime()) print 'Uqd', Uqd Udd = np.multiply(get_U_dipdip(jm=jm._m,dips=d.T),27.211) print strftime("%a, %d %b %Y %X +0000", gmtime()) print 'Udd', Udd energyev = Udd+Uqd+Uqq print 'energyev', energyev energy=energyev/27.211 print strftime("%a, %d %b %Y %X +0000", gmtime()) print 'Making .dat cross sections for gnuplot' # print TVs if not os.path.exists('Dips_Posns_TVs'): os.makedirs('Dips_Posns_TVs') f = open('Dips_Posns_TVs/%s_TVs.dat' % name, 'w') TVstr=str(str(TV[0,0]) + ' ' + str(TV[0,1]) + ' ' + str(TV[0,2]) + '\n' + str(TV[1,0]) + ' ' + str(TV[1,1]) + ' ' + str(TV[1,2]) + '\n' + str(TV[2,0]) + ' ' + str(TV[2,1]) + ' ' + str(TV[2,2])+ '\n') f.write(TVstr) f.flush() f.close() # print dipoles if not os.path.exists('Dips_Posns_TVs'): os.makedirs('Dips_Posns_TVs') f = open('Dips_Posns_TVs/%s_dipoles.dat' % name, 'w') for dd in split_d: dstr=str(dd) f.write(dstr) f.write('\n') f.flush() f.close() # print properties for charge in centrepos time=strftime("%a, %d %b %Y %X +0000", gmtime()) f = open('%s_properties.csv' % name, 'w') f.write ('time\tname\tmols_cen\tmols_sur\tmols_outer\tinsize\toutsize\tenergyev\tUqq\tUqd\tUdd\tTotdip_x\tTotdip_y\tTotdip_z') f.write ('\n%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s' % (time,name,mols_cen,mols_sur,mols_outer,insize,outsize,energyev,Uqq,Uqd,Udd,tot[0,0],tot[0,1],tot[0,2])) f.flush() f.close() print 'Job Completed Successfully.'
[ "sheridan.few@gmail.com" ]
sheridan.few@gmail.com
894482ee3334014d91285e7f29af8f4772c1e0bf
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/chromium_org/tools/cr/main.py
dced8cd4069ceea9d47ee5b9b17ca6fc164b8c81
[ "MIT", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only", "Apache-2.0", "LicenseRef-scancode-unknown" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
Python
false
false
3,092
py
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Chromium cr tool main module. Holds the main function and all it's support code. """ import os import sys import cr import cr.auto.user import cr.autocomplete import cr.loader _CONTACT = 'iancottrell@chromium.org' def Main(): """Chromium cr tool main function. This is the main entry point of the cr tool, it finds and loads all the plugins, creates the context and then activates and runs the specified command. """ # Add the users plugin dir to the cr.auto.user package scan user_path = os.path.expanduser(os.path.join('~', '.config', 'cr')) cr.auto.user.__path__.append(user_path) cr.loader.Scan() # Build the command context context = cr.Context( description='The chrome dev build tool.', epilog='Contact ' + _CONTACT + ' if you have issues with this tool.', ) # Install the sub-commands for command in cr.Command.Plugins(): context.AddSubParser(command) # test for the special autocomplete command if context.autocompleting: # After plugins are loaded so pylint: disable=g-import-not-at-top cr.autocomplete.Complete(context) return # Speculative argument processing to add config specific args context.ParseArgs(True) cr.plugin.Activate(context) # At this point we should know what command we are going to use command = cr.Command.GetActivePlugin(context) # Do some early processing, in case it changes the build dir if command: command.EarlyArgProcessing(context) # Update the activated set again, in case the early processing changed it cr.plugin.Activate(context) # Load the build specific configuration found_build_dir = cr.base.client.LoadConfig(context) # Final processing or arguments context.ParseArgs() cr.plugin.Activate(context) # If we did not get a command before, it might have been fixed. if command is None: command = cr.Command.GetActivePlugin(context) # If the verbosity level is 3 or greater, then print the environment here if context.verbose >= 3: context.DumpValues(context.verbose > 3) if command is None: print context.Substitute('No command specified.') exit(1) if command.requires_build_dir: if not found_build_dir: if not context.Find('CR_OUT_FULL'): print context.Substitute( 'No build directory specified. Please use cr init to make one.') else: print context.Substitute( 'Build {CR_BUILD_DIR} not a valid build directory') exit(1) if context.Find('CR_VERSION') != cr.base.client.VERSION: print context.Substitute( 'Build {CR_BUILD_DIR} is for the wrong version of cr') print 'Please run cr init to reset it' exit(1) cr.Platform.Prepare(context) if context.verbose >= 1: print context.Substitute( 'Running cr ' + command.name + ' for {CR_BUILD_DIR}') # Invoke the given command command.Run(context) if __name__ == '__main__': sys.exit(Main())
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
6d3560c2179b9703d5955c377a9989b5a7a236c0
34d88082307281333ef4aeeec012a3ff5f8ec06e
/w3resource/basic/Q098.py
c3ed4f05918371d4d44df3cbbb34edc91b0fb439
[]
no_license
JKChang2015/Python
a6f8b56fa3f9943682470ae57e5ad3266feb47a7
adf3173263418aee5d32f96b9ea3bf416c43cc7b
refs/heads/master
2022-12-12T12:24:48.682712
2021-07-30T22:27:41
2021-07-30T22:27:41
80,747,432
1
8
null
2022-12-08T04:32:06
2017-02-02T17:05:19
HTML
UTF-8
Python
false
false
148
py
# -*- coding: UTF-8 -*- # Q098 # Created by JKChang # Wed, 31/05/2017, 15:34 # Tag: # Description: Write a Python program to get the system time.
[ "jkchang2015@gmail.com" ]
jkchang2015@gmail.com
31ee5c556c25850ddd15704dede4c1ff0190e717
83e2824b060cea6290563a63dfc5a2caaddccc32
/problem019.py
3ab4e40b4de9a056bbdaac0afe9cb807e5089a42
[]
no_license
1tux/project_euler
b8f731155eb59c5cdb92efe68f0140695c5b6353
9a6c04d08a77d6e80eb15d203c8003870645415a
refs/heads/master
2021-01-09T20:17:35.502613
2016-10-03T16:19:50
2016-10-03T16:19:50
61,938,647
0
0
null
null
null
null
UTF-8
Python
false
false
137
py
import datetime c = 0 for x in xrange(1901, 2001): for y in xrange(1, 13): if datetime.date(x, y, 1).weekday() == 1: c+=1 print c
[ "root" ]
root
f040059ed129aa620990f466c803b2a2a026b103
00a3f91db1e0bd349a0a120d8980429363446d67
/api/migrations/0004_merge_20180805_1637.py
a0c874598dea406d580c4e4f2a4cf32728b0e65b
[]
no_license
junkluis/cenecu_web
59130894d0584479b352fcd7a119aa2c6185a5e5
078b59308a93e40514b63c130c4506f98f929be4
refs/heads/master
2020-03-25T09:08:02.327198
2018-08-05T21:42:21
2018-08-05T21:42:21
143,649,219
0
0
null
null
null
null
UTF-8
Python
false
false
330
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-08-05 21:37 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('api', '0003_auto_20180730_0141'), ('api', '0003_auto_20180729_2237'), ] operations = [ ]
[ "lufezuro@gmail.com" ]
lufezuro@gmail.com
d51f21fe04ab46c872361e77f688ddde25e6690d
1ba68429cd4a1654a66dd7b0a7b8e91f81798073
/cart/admin.py
25928702bc82acc30d13248cd482e57f5dc03454
[]
no_license
crowdbotics-apps/test-002-31939
097234cc8a8870e39ece59640ad66a14c641b708
d669523f2ed3681d487d4a1a65645a642c6413c1
refs/heads/master
2023-08-29T21:34:54.106718
2021-11-12T17:25:07
2021-11-12T17:25:07
427,392,814
0
0
null
null
null
null
UTF-8
Python
false
false
159
py
from django.contrib import admin from .models import Content, Product admin.site.register(Product) admin.site.register(Content) # Register your models here.
[ "team@crowdbotics.com" ]
team@crowdbotics.com
fb47a23ad30dfd0ef95a58c450969c5796386e1e
d83f50302702d6bf46c266b8117514c6d2e5d863
/wiggle-sort-ii.py
4e805ab4c2cb628a233a145c8732759446925784
[]
no_license
sfdye/leetcode
19764a6bdb82de114a2c82986864b1b2210c6d90
afc686acdda4168f4384e13fb730e17f4bdcd553
refs/heads/master
2020-03-20T07:58:52.128062
2019-05-05T08:10:41
2019-05-05T08:10:41
137,295,892
3
0
null
null
null
null
UTF-8
Python
false
false
285
py
class Solution: def wiggleSort(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ for i, num in enumerate(sorted(nums)[::-1]): nums[(i * 2 + 1) % (len(nums) | 1)] = num
[ "tsfdye@gmail.com" ]
tsfdye@gmail.com
fdc19d0a4f81488f5c242f4dfcda161c70c25497
a8d3471d8d2fa914a0f8bab0495b115e70538430
/handler.py
86e8d3670ac9432144feb56e01bd3d420ea7f28b
[]
no_license
davidbegin/morguebot
a03bbfa46cbfd6b916ace98a2f476e44d4843349
f62d75917d13b4a443c0f3c8e00f7dd82720d9f3
refs/heads/master
2022-12-22T14:52:20.398139
2020-01-17T15:56:04
2020-01-17T15:56:04
213,519,437
8
0
null
2022-12-08T06:49:48
2019-10-08T01:16:15
Python
UTF-8
Python
false
false
529
py
import json import os from glm.generic_lambda_handler import lambda_handler as generic_lambda_handler from flask_app import app import xl_bot import dungeon_gossiper def async_handler(messages, context): print(messages) def lambda_handler(event, context): result = generic_lambda_handler( event=event, context=context, flask_app=app, async_handler=async_handler ) print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") print(f"{result}") print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") return result
[ "davidmichaelbe@gmail.com" ]
davidmichaelbe@gmail.com
4ca726894e8a47f19d38fc009e00fb4aaa6896df
bf4be1f469b049dccf41807514a168400e48cdd1
/Related Topics/Bit Manipulation/201. Bitwise AND of Numbers Range.py
c38348cbfcb27e1311a88564532ee0347c21b603
[]
no_license
billgoo/LeetCode_Solution
8bde6844ecc44c61a914f9c88030d8d3e724c947
360d144cee86aae877b6187a07f1957e673c3592
refs/heads/master
2022-04-26T16:10:00.380910
2022-04-20T04:54:06
2022-04-20T04:54:06
155,243,219
0
0
null
null
null
null
UTF-8
Python
false
false
436
py
class Solution: def rangeBitwiseAnd(self, m: int, n: int) -> int: # bits shift """ e = 0 while m != n: m >>= 1 n >>= 1 e += 1 return m << e """ # Brian Kernighan's Algorithm # n & (n - 1) will remove the right most bits: 1100 & 1011 = 1000 while m < n: n &= (n - 1) return m & n
[ "billgoo0813@gmail.com" ]
billgoo0813@gmail.com
b9af3fae8856807e32bf2d31ce7e14ead62f9716
27010a7ad70bf69511858a91d42dc7a64e61b66d
/src/1763_longest_nice_substring.py
f1a96df1b1ba601c788359bfd79537a5f6d61f4a
[ "Apache-2.0" ]
permissive
hariharanragothaman/leetcode-solutions
fb7d967f2c6e3f4c936e3c7afe369415bc8d2dc6
44e759f80d3c9df382fdf8d694d6378881e3649d
refs/heads/master
2023-09-03T20:31:59.200701
2021-10-18T00:50:56
2021-10-18T00:50:56
267,927,538
1
1
null
null
null
null
UTF-8
Python
false
false
1,765
py
""" A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, "abABB" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, "abA" is not because 'b' appears, but 'B' does not. Given a string s, return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string. Example 1: Input: s = "YazaAay" Output: "aAa" Explanation: "aAa" is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear. "aAa" is the longest nice substring. Example 2: Input: s = "Bb" Output: "Bb" Explanation: "Bb" is a nice string because both 'B' and 'b' appear. The whole string is a substring. Example 3: Input: s = "c" Output: "" Explanation: There are no nice substrings. Example 4: Input: s = "dDzeE" Output: "dD" Explanation: Both "dD" and "eE" are the longest nice substrings. As there are multiple longest nice substrings, return "dD" since it occurs earlier. Constraints: 1 <= s.length <= 100 s consists of uppercase and lowercase English letters. """ class Solution: def longestNiceSubstring(self, s: str) -> str: max_length = 0 result = "" for i in range(len(s)): for j in range(i, len(s)): substr = s[i : j + 1] upper = "".join(c for c in substr if c.isupper()) lower = "".join(c for c in substr if c.islower()) upper = upper.lower() if set(upper) == set(lower) and (len(substr) > max_length): max_length = max(max_length, len(substr)) result = substr return result
[ "hariharanragothaman@gmail.com" ]
hariharanragothaman@gmail.com
e18acdf10dc10f22be785b412c98734ef4391a78
d190750d6cb34e9d86ae96724cf4b56a2f57a74a
/tests/r/test_morley.py
562dc425811ab5a69db86c60b1d186302756d5a8
[ "Apache-2.0" ]
permissive
ROAD2018/observations
a119f61a48213d791de0620804adb8d21c2ad9fb
2c8b1ac31025938cb17762e540f2f592e302d5de
refs/heads/master
2021-09-24T04:28:02.725245
2018-09-16T23:06:30
2018-09-16T23:06:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
510
py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.morley import morley def test_morley(): """Test module morley.py by downloading morley.csv and testing shape of extracted data has 100 rows and 3 columns """ test_path = tempfile.mkdtemp() x_train, metadata = morley(test_path) try: assert x_train.shape == (100, 3) except: shutil.rmtree(test_path) raise()
[ "dustinviettran@gmail.com" ]
dustinviettran@gmail.com
01e4a166b1a96c6ed40e515a79db2f4f05132979
83957f263305c8021add5f05327381263cc6fdad
/mongrey/server/protocols.py
92242373a487ab32a09578418932680ea295c321
[ "BSD-3-Clause" ]
permissive
srault95/mongrey
d011727bb003ec02dd9797876a2cc055554d0ed9
63a94efd33db04e4b361dd259bfda3e520c305c8
refs/heads/master
2020-05-15T19:50:40.992062
2018-03-11T09:11:46
2018-03-11T09:11:46
35,269,256
0
0
null
2018-03-11T09:11:47
2015-05-08T08:58:12
CSS
UTF-8
Python
false
false
4,686
py
# -*- coding: utf-8 -*- import uuid import logging import re from .. import constants from ..exceptions import InvalidProtocolError line_regex = re.compile(r'^\s*([^=\s]+)\s*=(.*)$') logger = logging.getLogger(__name__) def parse_protocol_line(request): """ example: client_name=123, client_address=1.1.1.1, sender=sender@example.net, recipient=rcpt@example.org """ try: fields = dict(constants.ALL_FIELDS).keys() protocol = dict([a.strip(',').split('=') for a in request.split()]) for key in fields: if not key in protocol: protocol[key] = None if not "instance" in protocol: protocol["instance"] = str(uuid.uuid1()) for key in protocol.copy().keys(): if not key in constants.POSTFIX_PROTOCOL['valid_fields'] + ['country']: protocol.pop(key) return protocol except Exception, err: logger.error(str(err)) def parse_policy_protocol(fileobj, debug=False): """ @see: http://www.postfix.org/SMTPD_POLICY_README.html """ protocol = {} while True: line = fileobj.readline() if line: line = line.strip() if debug: logger.debug(line) if not line: break else: m = line_regex.match(line) if not m: break key = m.group(1) value = m.group(2) if len(protocol) == 0: '''First line''' if key != 'request': raise InvalidProtocolError("Invalid Protocol") if not value or value != 'smtpd_access_policy': raise InvalidProtocolError("Invalid Protocol") elif key == 'request': '''request=smtpd_access_policy already parsing''' raise InvalidProtocolError("Invalid Protocol") if key in protocol: logger.warn("key is already in protocol : %s" % key) else: value = value.decode('utf-8', 'ignore') value = value.encode('us-ascii', 'ignore') protocol[key] = value.lower() request = protocol.get('request', None) if not request: raise InvalidProtocolError("Invalid Protocol") else: if request != 'smtpd_access_policy': raise InvalidProtocolError("Invalid Protocol") return protocol def verify_protocol(protocol): if not 'protocol_state' in protocol: raise InvalidProtocolError("protocol_state field not in protocol") protocol_state = protocol.get('protocol_state') if not protocol_state.lower() in constants.ACCEPT_PROTOCOL_STATES: raise InvalidProtocolError("this protocol_state is not supported: %s" % protocol_state) for key in protocol.keys(): if not key.lower() in constants.POSTFIX_PROTOCOL['valid_fields']: raise InvalidProtocolError("invalid field in protocol: %s" % key) def tcp_table_protocol(fileobj, debug=False): """ @see: http://www.postfix.org/tcp_table.5.html """ protocol = {} while True: line = fileobj.readline() if line: line = line.strip() if debug: logger.debug(line) if not line: break else: """ get SPACE key NEWLINE Look up data under the specified key. REPLY: 500 SPACE text NEWLINE 400 SPACE text NEWLINE 200 SPACE text NEWLINE """ return line return protocol def tcp_table_test(): """ postconf -e "smtpd_client_restrictions = check_client_access tcp:127.0.0.0:15005" postconf -e "smtpd_sender_restrictions = check_sender_access tcp:127.0.0.0:15005" postconf -e "smtpd_recipient_restrictions = check_recipient_access tcp:127.0.0.0:15005, reject" """ from gevent.server import StreamServer def handle(sock, address): fileobj = sock.makefile() key_search = tcp_table_protocol(fileobj, debug=True) print "key_search : ", key_search fileobj.write("200 TEST\n") fileobj.close() #sock.close() server = StreamServer(listener=('127.0.0.0', 15005), handle=handle) try: server.serve_forever() except KeyboardInterrupt: pass if __name__ == "__main__": tcp_table_test()
[ "stephane.rault@radicalspam.org" ]
stephane.rault@radicalspam.org
b429309f8e623409f989dca83d4ff8711914cc70
1b1546cafc9453c4fdb9406533f94ed56206541c
/tests/tutorials/tour/test_decoupled.py
1ca8a8aa8e194c9366c33e5da2f143cb4331d61d
[ "MIT" ]
permissive
pauleveritt/wired
bad7ecadae4f23874598031ae8d17e08ba34ec9b
629f950176a9682a7ccb68efbb27cb2e23b4e93e
refs/heads/master
2020-05-01T06:38:38.728436
2019-04-29T12:43:43
2019-04-29T12:43:43
177,335,238
1
1
MIT
2019-04-23T00:14:34
2019-03-23T20:08:57
Python
UTF-8
Python
false
false
1,029
py
import pytest from wired import ServiceRegistry @pytest.fixture def settings(): from tutorials.tour.decoupled import Settings settings = Settings(punctuation='!!') return settings @pytest.fixture def registry(settings): from tutorials.tour.decoupled import setup r: ServiceRegistry = setup(settings) return r @pytest.fixture def default_customer(): from tutorials.tour.decoupled import Customer return Customer(name='Mary') @pytest.fixture def french_customer(): from tutorials.tour.decoupled.custom import FrenchCustomer return FrenchCustomer(name='Henri') def test_greet_customer(registry, default_customer): from tutorials.tour.decoupled import greet_customer actual = greet_customer(registry, default_customer) assert 'Hello Mary !!' == actual def test_greet_french_customer(registry, french_customer): from tutorials.tour.decoupled import greet_customer actual = greet_customer(registry, french_customer) assert 'Bonjour Henri !!' == actual
[ "pauleveritt@me.com" ]
pauleveritt@me.com
2ee8380fc6a904aebb84b742cacca3669f9f7f0a
aea1d61c9a5d445f3a1c328a757dfa02d652f367
/dataset_04__eph_stim_vs_dist/fig9b/code/data/results/all_lfps.py
6880c9a242cd1df2c7015ad340675a073b8c6c85
[]
no_license
ModelDBRepository/263988
bb15ddf953a31ca44ac62ead919e3106389374f8
b1f4bd4931bb1ddcc323108c39e389b9fa4234a0
refs/heads/master
2022-11-21T22:38:24.738870
2020-07-30T00:38:17
2020-07-30T00:38:17
283,632,019
0
0
null
null
null
null
UTF-8
Python
false
false
6,650
py
""" Miguel Capllonch Juan 30 September 2018 Draw together all the LFPs computed with the different methods: - Results from the simulations (RN model) - Using the VC conductor theory """ import numpy as np import matplotlib.pyplot as plt import csv # Recording electrodes rec_els = { 'E': {'pos': (250, 0, 19000), 'lfp_indiv_ly1': {}, 'lfp_indiv_ly2': {}, 'lfp_total_ly1': None, 'lfp_total_ly2': None, 'color': 'r'}, 'S': {'pos': (0, -250, 19000), 'lfp_indiv_ly1': {}, 'lfp_indiv_ly2': {}, 'lfp_total_ly1': None, 'lfp_total_ly2': None, 'color': 'g'}, 'W': {'pos': (-250, 0, 19000), 'lfp_indiv_ly1': {}, 'lfp_indiv_ly2': {}, 'lfp_total_ly1': None, 'lfp_total_ly2': None, 'color': 'b'}, 'N': {'pos': (0, 250, 19000), 'lfp_indiv_ly1': {}, 'lfp_indiv_ly2': {}, 'lfp_total_ly1': None, 'lfp_total_ly2': None, 'color': 'k'} } # Stimulating electrode (amp in mA) delay = 0.1 dur = 0.2 amp = -15.e-3 stimcurrent = None stimelpos = (250, 0, 100) # Medium conductivity tensor (1/(Ohm*um)) sigma_x = 1. / (1.211e3 * 1.e-6) sigma_y = 1. / (1.211e3 * 1.e-6) sigma_z = 1. / (0.175e3 * 1.e-6) # Functions def compute_lfp(currents, elpos): """ Compute the LFP from a time series of currents as recorded by a point electrode situated at elpos The equation is taken from: Nicholson & Freeman (1975) The current sources are all the segments in the axon """ dx = x - elpos[0] dy = y - elpos[1] dz = z - elpos[2] denominator = 4. * np.pi * np.sqrt\ (\ sigma_y * sigma_z * dx ** 2 + \ sigma_z * sigma_x * dy ** 2 + \ sigma_x * sigma_y * dz ** 2\ ) # denominator = np.tile(denominator, nt).reshape(currents.shape) denominator = denominator.repeat(nt).reshape(currents.shape) # print dz.shape, (dz ** 2).shape, currents.shape return (currents / denominator).sum(axis=0) def compute_lfp_fromtimeseries(currents, srcpos, elpos): """ Compute the LFP from a time series of currents as recorded by a point electrode situated at elpos The equation is taken from: Nicholson & Freeman (1975) This time, there is only one current point source """ dx = srcpos[0] - elpos[0] dy = srcpos[1] - elpos[1] dz = srcpos[2] - elpos[2] denominator = 4. * np.pi * np.sqrt\ (\ sigma_y * sigma_z * dx ** 2 + \ sigma_z * sigma_x * dy ** 2 + \ sigma_x * sigma_y * dz ** 2\ ) # denominator = np.tile(denominator, nt).reshape(currents.shape) # denominator = denominator.repeat(nt).reshape(currents.shape) # denominator = denominator.repeat(nt) # print dz.shape, (dz ** 2).shape, currents.shape return currents / denominator # Declare arrays names = {} ily1 = {} ily2 = {} balancely1 = {} balancely2 = {} lfp_indiv_ly1 = {} lfp_indiv_ly2 = {} x = [] y = [] z = [] ii_fibs = [] # Other parameters dt = 0.005 # Get recordings from file recs = [] # with open('./recordings_R0P0_noartefacts.csv', 'r') as f: with open('./recordings_R0P0_withartefacts.csv', 'r') as f: frl = list(csv.reader(f)) for row in frl[1:]: recs.append(float(row[1])) recs = np.array(recs) # Get currents from file with open('./membranecurrents.csv', 'r') as f: frl = list(csv.reader(f)) for i, row in enumerate(frl[1:]): ifib = int(row[0]) ii_fibs.append(ifib) name = row[1] data = row[5:] ndata = len(data) / 2 dataly1 = np.array([float(item) for item in data[:ndata]]) dataly2 = np.array([float(item) for item in data[ndata:]]) try: ily1[ifib].append(dataly1.copy()) ily2[ifib].append(dataly2.copy()) names[ifib].append(name) except KeyError: names[ifib] = [name] ily1[ifib] = [dataly1] ily2[ifib] = [dataly2] x.append(float(row[2])) y.append(float(row[3])) z.append(float(row[4])) # Positions from lists to arrays x = np.array(x) y = np.array(y) z = np.array(z) # Finish setting parameters that depend on the data tarray = np.arange(0, dt * ndata, dt) nt = len(tarray) nsegstotal = len(z) stimcurrent = amp * np.ones_like(tarray) # stimcurrent[np.where(tarray < delay + dur)] = amp stimcurrent[np.where(tarray < delay)] = 0. stimcurrent[np.where(tarray > delay + dur)] = 0. # stimcurrent = stimcurrent() # stimcurrent[np.where(delay < tarray < delay + dur)] = amp # Positions of the nodes of Ranvier zRN = {} # and indices corresponding to them indsRN = {} for k, v in names.items(): zRN[k] = [] indsRN[k] = [] for i, vv in enumerate(v): if 'node' in vv: zRN[k].append(z[i]) indsRN[k].append(i) for ifib in ii_fibs: # Current balances ily1[ifib] = np.array(ily1[ifib]) ily2[ifib] = np.array(ily2[ifib]) balancely1[ifib] = np.zeros(nt) balancely2[ifib] = np.zeros(nt) for i_t, t in enumerate(tarray): balancely1[ifib][i_t] = ily1[ifib][:, i_t].sum() balancely2[ifib][i_t] = ily2[ifib][:, i_t].sum() # Individual LFPs for k, re in rec_els.items(): re['lfp_indiv_ly1'][ifib] = compute_lfp(ily1[ifib], re['pos']) re['lfp_indiv_ly2'][ifib] = compute_lfp(ily2[ifib], re['pos']) # Finally, sum up the individual LFPs of the fibers into a total LFP # for each electrode for k, re in rec_els.items(): re['lfp_total_ly1'] = np.zeros(nt) re['lfp_total_ly2'] = np.zeros(nt) for ifib in ii_fibs: re['lfp_total_ly1'] += re['lfp_indiv_ly1'][ifib] re['lfp_total_ly2'] += re['lfp_indiv_ly2'][ifib] # Add the contribution of the stimulating electrode re['lfp_total_ly1'] += compute_lfp_fromtimeseries(stimcurrent, stimelpos, re['pos']) re['lfp_total_ly2'] += compute_lfp_fromtimeseries(stimcurrent, stimelpos, re['pos']) # What if I sum them? resum = re['lfp_total_ly1'] + re['lfp_total_ly2'] # Now compare the two curves resum_norm = resum / np.abs(resum.max() - resum.min()) recs_norm = recs / np.abs(recs.max() - recs.min()) ############################################################################### # Figures # Time evolution at some point fig, ax = plt.subplots() ax.plot(tarray, recs, lw=3, label='RN model') for k, re in rec_els.items(): ax.plot(tarray, re['lfp_total_ly1'], c=re['color'] , ls='-', label=k + '. Layer 1') ax.plot(tarray, re['lfp_total_ly2'], c=re['color'] , ls='--', label=k + '. Layer 2') ax.plot(tarray, resum, 'r', lw=3, label='Sum VC model') ax.set_xlabel('Time (ms)') ax.set_ylabel('Extracellular recordings (mV)') ax.set_title('Extracellular recordings') ax.legend() fig.tight_layout() # plt.show() fig.savefig('recordings_all.png') fig, ax = plt.subplots() ax.plot(tarray, recs_norm, lw=3, label='RN model') ax.plot(tarray, resum_norm, 'r', lw=3, label='Sum VC model') ax.set_xlabel('Time (ms)') ax.set_ylabel('Extracellular recordings (mV)') ax.set_title('Extracellular recordings (normalised)') ax.legend() fig.tight_layout() # plt.show() fig.savefig('recordings_all_compare_RN_VC.png')
[ "tom.morse@yale.edu" ]
tom.morse@yale.edu
ed22cd98ccc5c3ab583769e5ced040437212592d
3f97f0ba5351aae879cae3c6c073d64077ee96bd
/ch99/photo/migrations/0001_initial.py
14effa898a4c93b21d9524971d9600907b03422d
[ "MIT" ]
permissive
dukuaris/django_web
7b8e63d82718afc2a7aedd97ceed97f8aeab4040
d6e8486999a8db8fc99c4b7dae0ddac402828c9d
refs/heads/master
2023-01-07T09:02:06.316075
2020-01-28T06:46:27
2020-01-28T06:46:27
232,438,676
0
0
MIT
2022-12-27T15:36:34
2020-01-07T23:45:17
HTML
UTF-8
Python
false
false
1,543
py
# Generated by Django 2.2.2 on 2020-01-16 09:54 from django.db import migrations, models import django.db.models.deletion import photo.fields class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Album', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=30, verbose_name='NAME')), ('description', models.CharField(blank=True, max_length=100, verbose_name='One Line Description')), ], options={ 'ordering': ('name',), }, ), migrations.CreateModel( name='Photo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=30, verbose_name='TITLE')), ('description', models.TextField(blank=True, verbose_name='Photo Description')), ('image', photo.fields.ThumbnailImageField(upload_to='photo/%Y/%m', verbose_name='IMAGE')), ('upload_dt', models.DateTimeField(auto_now_add=True, verbose_name='UPLOAD DATE')), ('album', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='photo.Album')), ], options={ 'ordering': ('title',), }, ), ]
[ "dukuaris@gmail.com" ]
dukuaris@gmail.com
a150f25eb027d1b21cf74cf109a18e85acada783
f576f0ea3725d54bd2551883901b25b863fe6688
/sdk/apimanagement/azure-mgmt-apimanagement/generated_samples/api_management_user_confirmation_password_send.py
793650579dac2e949735e69fe128bc5958cef7ad
[ "LicenseRef-scancode-generic-cla", "MIT", "LGPL-2.1-or-later" ]
permissive
Azure/azure-sdk-for-python
02e3838e53a33d8ba27e9bcc22bd84e790e4ca7c
c2ca191e736bb06bfbbbc9493e8325763ba990bb
refs/heads/main
2023-09-06T09:30:13.135012
2023-09-06T01:08:06
2023-09-06T01:08:06
4,127,088
4,046
2,755
MIT
2023-09-14T21:48:49
2012-04-24T16:46:12
Python
UTF-8
Python
false
false
1,638
py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential from azure.mgmt.apimanagement import ApiManagementClient """ # PREREQUISITES pip install azure-identity pip install azure-mgmt-apimanagement # USAGE python api_management_user_confirmation_password_send.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET. For more info about how to get the value, please see: https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal """ def main(): client = ApiManagementClient( credential=DefaultAzureCredential(), subscription_id="subid", ) response = client.user_confirmation_password.send( resource_group_name="rg1", service_name="apimService1", user_id="57127d485157a511ace86ae7", ) print(response) # x-ms-original-file: specification/apimanagement/resource-manager/Microsoft.ApiManagement/stable/2022-08-01/examples/ApiManagementUserConfirmationPasswordSend.json if __name__ == "__main__": main()
[ "noreply@github.com" ]
Azure.noreply@github.com
bb9907066005e577a1998be045ba95d25cf0401b
48bb4a0dbb361a67b88b7c7532deee24d70aa56a
/codekata/greatese.py
5bf5eea99317b8d7235f806cd8e0e600b1945704
[]
no_license
PRAMILARASI/GUVI
66080a80400888263d511138cb6ecd37540507c7
6a30a1d0a3f4a777db895f0b3adc8b0ac90fd25b
refs/heads/master
2022-01-28T08:54:07.719735
2019-06-24T15:57:05
2019-06-24T15:57:05
191,355,070
0
0
null
null
null
null
UTF-8
Python
false
false
167
py
x=int(input("")) y=int(input("")) z=int(input("")) if(x>y>z): largest=x print(largest) elif(y>z): largest=y print (largest) else: largest=z print(largest)
[ "noreply@github.com" ]
PRAMILARASI.noreply@github.com
b8c9672e42c3bf90c709b694832601d20977efac
14f455693213cae4506a01b7d0591e542c38de79
/apps/profile/urls.py
ae3b903bd2e0bbdeddb2002969555017bac9927d
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Cvalladares/Newsblur_Instrumented
f0b14d063759973330f202108a7eed3a29bcc033
4d6ee6aa9713879b1e2550ea5f2dbd819c73af12
refs/heads/master
2022-12-29T15:19:29.726455
2019-09-03T17:09:04
2019-09-03T17:09:04
206,130,022
0
0
MIT
2022-12-10T06:00:26
2019-09-03T17:07:04
Python
UTF-8
Python
false
false
2,248
py
from django.conf.urls import * from apps.profile import views urlpatterns = patterns('', url(r'^get_preferences?/?', views.get_preference), url(r'^set_preference/?', views.set_preference), url(r'^set_account_settings/?', views.set_account_settings), url(r'^get_view_setting/?', views.get_view_setting), url(r'^set_view_setting/?', views.set_view_setting), url(r'^clear_view_setting/?', views.clear_view_setting), url(r'^set_collapsed_folders/?', views.set_collapsed_folders), url(r'^paypal_form/?', views.paypal_form), url(r'^paypal_return/?', views.paypal_return, name='paypal-return'), url(r'^is_premium/?', views.profile_is_premium, name='profile-is-premium'), url(r'^paypal_ipn/?', include('paypal.standard.ipn.urls'), name='paypal-ipn'), url(r'^paypal_webhooks/?', include('paypal.standard.ipn.urls'), name='paypal-webhooks'), url(r'^stripe_form/?', views.stripe_form, name='stripe-form'), url(r'^activities/?', views.load_activities, name='profile-activities'), url(r'^payment_history/?', views.payment_history, name='profile-payment-history'), url(r'^cancel_premium/?', views.cancel_premium, name='profile-cancel-premium'), url(r'^refund_premium/?', views.refund_premium, name='profile-refund-premium'), url(r'^never_expire_premium/?', views.never_expire_premium, name='profile-never-expire-premium'), url(r'^upgrade_premium/?', views.upgrade_premium, name='profile-upgrade-premium'), url(r'^save_ios_receipt/?', views.save_ios_receipt, name='save-ios-receipt'), url(r'^update_payment_history/?', views.update_payment_history, name='profile-update-payment-history'), url(r'^delete_account/?', views.delete_account, name='profile-delete-account'), url(r'^forgot_password_return/?', views.forgot_password_return, name='profile-forgot-password-return'), url(r'^forgot_password/?', views.forgot_password, name='profile-forgot-password'), url(r'^delete_starred_stories/?', views.delete_starred_stories, name='profile-delete-starred-stories'), url(r'^delete_all_sites/?', views.delete_all_sites, name='profile-delete-all-sites'), url(r'^email_optout/?', views.email_optout, name='profile-email-optout'), )
[ "Cvalladares4837@gmail.com" ]
Cvalladares4837@gmail.com
d741cbbed408cd89eba80b859cd1b82ff07f0c56
5f364b328d0e7df6f292dbbec266995f495b2ed4
/src/python/txtai/vectors/words.py
1cac062ec92c54e5a3ac71630cd7282b202a50b2
[ "Apache-2.0" ]
permissive
binglinchengxiash/txtai
a17553f57ddd857ff39a7d0b38e24930f5c71596
1513eb8390f01848742e67690b6e4bc6452101ee
refs/heads/master
2023-04-03T18:59:35.845281
2021-04-05T22:05:15
2021-04-05T22:05:15
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,715
py
""" Word Vectors module """ import os import pickle import tempfile from errno import ENOENT from multiprocessing import Pool import fasttext import numpy as np from pymagnitude import converter, Magnitude from .base import Vectors from ..pipeline.tokenizer import Tokenizer # Multiprocessing helper methods # pylint: disable=W0603 VECTORS = None def create(config, scoring): """ Multiprocessing helper method. Creates a global embeddings object to be accessed in a new subprocess. Args: config: vector configuration scoring: scoring instance """ global VECTORS # Create a global embedding object using configuration and saved VECTORS = WordVectors(config, scoring) def transform(document): """ Multiprocessing helper method. Transforms document into an embeddings vector. Args: document: (id, text|tokens, tags) Returns: (id, embedding) """ global VECTORS return (document[0], VECTORS.transform(document)) class WordVectors(Vectors): """ Builds sentence embeddings/vectors using weighted word embeddings. """ def load(self, path): # Ensure that vector path exists if not path or not os.path.isfile(path): raise IOError(ENOENT, "Vector model file not found", path) # Load magnitude model. If this is a training run (uninitialized config), block until vectors are fully loaded return Magnitude(path, case_insensitive=True, blocking=not self.initialized) def index(self, documents): ids, dimensions, stream = [], None, None # Shared objects with Pool args = (self.config, self.scoring) # Convert all documents to embedding arrays, stream embeddings to disk to control memory usage with Pool(os.cpu_count(), initializer=create, initargs=args) as pool: with tempfile.NamedTemporaryFile(mode="wb", suffix=".npy", delete=False) as output: stream = output.name for uid, embedding in pool.imap(transform, documents): if not dimensions: # Set number of dimensions for embeddings dimensions = embedding.shape[0] ids.append(uid) pickle.dump(embedding, output) return (ids, dimensions, stream) def transform(self, document): # Convert to tokens if necessary if isinstance(document[1], str): document = (document[0], Tokenizer.tokenize(document[1]), document[2]) # Generate weights for each vector using a scoring method weights = self.scoring.weights(document) if self.scoring else None # pylint: disable=E1133 if weights and [x for x in weights if x > 0]: # Build weighted average embeddings vector. Create weights array os float32 to match embeddings precision. embedding = np.average(self.lookup(document[1]), weights=np.array(weights, dtype=np.float32), axis=0) else: # If no weights, use mean embedding = np.mean(self.lookup(document[1]), axis=0) return embedding def lookup(self, tokens): """ Queries word vectors for given list of input tokens. Args: tokens: list of tokens to query Returns: word vectors array """ return self.model.query(tokens) @staticmethod def build(data, size, mincount, path): """ Builds fastText vectors from a file. Args: data: path to input data file size: number of vector dimensions mincount: minimum number of occurrences required to register a token path: path to output file """ # Train on data file using largest dimension size model = fasttext.train_unsupervised(data, dim=size, minCount=mincount) # Output file path print("Building %d dimension model" % size) # Output vectors in vec/txt format with open(path + ".txt", "w") as output: words = model.get_words() output.write("%d %d\n" % (len(words), model.get_dimension())) for word in words: # Skip end of line token if word != "</s>": vector = model.get_word_vector(word) data = "" for v in vector: data += " " + str(v) output.write(word + data + "\n") # Build magnitude vectors database print("Converting vectors to magnitude format") converter.convert(path + ".txt", path + ".magnitude", subword=True)
[ "561939+davidmezzetti@users.noreply.github.com" ]
561939+davidmezzetti@users.noreply.github.com
31016d76561425d939332319e1c3c3f3630350a1
5808f74f1825919da58ae91829ff4516623eb79d
/2020/new_python_concepts/02_floats.py
00d580b96499450bff11db1b8e67cafef9cebf04
[ "MIT" ]
permissive
hygull/stkovrflw
e2d78c8614b8d9646e3458926d71d13dfa75e2d4
f341727c7e42b6e667345f12814ab1f2479f1b89
refs/heads/master
2023-07-19T11:56:45.818534
2022-03-19T18:13:47
2022-03-19T18:13:47
132,311,923
0
1
MIT
2023-07-16T21:27:08
2018-05-06T06:10:14
Python
UTF-8
Python
false
false
254
py
def func(p1: float, p2: float) -> float: print(p1 + p2) # return None """ floats.py:3: error: Incompatible return value type (got "None", expected "float") Found 1 error in 1 file (checked 2 source files) """ return p1 + p2
[ "rishikesh0014051992@gmail.com" ]
rishikesh0014051992@gmail.com
17d1e40c434aaf3fc57628e1fe5cf9356c36542a
97724145652ba49c5aacaf66d54a89f71c3f6426
/10-Testing-Exercise/mammal/test/test_mammal.py
f7874ed1536182fc6484460f09845535d717ac08
[]
no_license
l-damyanov/Python-OOP---February-2021
c0d729c99d6af44a55ee7f7a05cf66fb6d69876b
e92417ed38f1b24405973b2027c11201d09ddb83
refs/heads/main
2023-03-31T07:45:09.347412
2021-04-01T20:24:27
2021-04-01T20:24:27
341,599,115
1
0
null
null
null
null
UTF-8
Python
false
false
826
py
import unittest from mammal.project.mammal import Mammal class TestMammal(unittest.TestCase): def setUp(self): self.mammal = Mammal("Test mammal", "predator", "roar") def test_attr_set_up(self): self.assertEqual("Test mammal", self.mammal.name) self.assertEqual("predator", self.mammal.type) self.assertEqual("roar", self.mammal.sound) self.assertEqual(self.mammal._Mammal__kingdom, "animals") def test_make_sound_return(self): self.assertEqual("Test mammal makes roar", self.mammal.make_sound()) def test_get_kingdom_return(self): self.assertEqual("animals", self.mammal.get_kingdom()) def test_info_return(self): self.assertEqual("Test mammal is of type predator", self.mammal.info()) if __name__ == '__main__': unittest.main()
[ "l_l_damyanov@abv.bg" ]
l_l_damyanov@abv.bg
da12d3c31d5a691fa0565cbeff1fae9483d8d99b
93e9bbcdd981a6ec08644e76ee914e42709579af
/devide_and_conquer/315_Count_of_Smaller_Numbers_After_Self.py
e99b6ea88b209f2414fdefe3366889f075cf4bbd
[]
no_license
vsdrun/lc_public
57aa418a8349629494782f1a009c1a8751ffe81d
6350568d16b0f8c49a020f055bb6d72e2705ea56
refs/heads/master
2020-05-31T11:23:28.448602
2019-10-02T21:00:57
2019-10-02T21:00:57
190,259,739
6
0
null
null
null
null
UTF-8
Python
false
false
2,254
py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ https://leetcode.com/problems/count-of-smaller-numbers-after-self/description/ You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i]. Example: Input: [5,2,6,1] Output: [2,1,1,0] Explanation: To the right of 5 there are 2 smaller elements (2 and 1). To the right of 2 there is only 1 smaller element (1). To the right of 6 there is 1 smaller element (1). To the right of 1 there is 0 smaller element. """ class Solution(object): def countSmaller(self, nums): """ :type nums: List[int] :rtype: List[int] """ def sort(enum): half = len(enum) / 2 if half: left, right = sort(enum[:half]), sort(enum[half:]) for i in range(len(enum))[::-1]: if not right or left and left[-1][1] > right[-1][1]: smaller[left[-1][0]] += len(right) enum[i] = left.pop() else: enum[i] = right.pop() return enum smaller = [0] * len(nums) sort(list(enumerate(nums))) return smaller def rewrite(self, nums): """ :type nums: List[int] :rtype: List[int] """ """ 想法: 用merge sort """ result = [0] * len(nums) def msort(enum): half = len(enum) / 2 if half: left = msort(enum[:half]) right = msort(enum[half:]) for idx in range(len(enum))[::-1]: # (4,3,2,1,0) if (not right) or (left and left[-1][1] > right[-1][1]): result[left[-1][0]] += len(right) enum[idx] = left.pop() else: enum[idx] = right.pop() return enum msort(list(enumerate(nums))) # [(0, 3),(1,7),...] return result def build(): return [-1,-1] return [5,2,6,1] if __name__ == "__main__": s = Solution() print(s.countSmaller(build())) print(s.rewrite(build()))
[ "vsdmars@gmail.com" ]
vsdmars@gmail.com
7e8eed3e3e234e712b3ae2ebb9a56d9680629cb5
64a955664b82be8ed149d01149b36a8aac626f8e
/chapter5/p5.py
5ed71fd3dd2d87de56d123944936a15d519c8c03
[]
no_license
JoelDavisP/Python-Practice-Book-Solutions
b60371590d8aaecab9de6ccad2bf2efb7a2f90ae
ea298d35e50d3719d5b0b841748abfd0c852cc95
refs/heads/master
2021-07-14T04:52:40.678170
2017-10-18T13:26:50
2017-10-18T13:26:50
105,724,396
0
0
null
null
null
null
UTF-8
Python
false
false
652
py
import os import sys def lines_py(): """It compute the total number of lines of code in all python files (.py extension) in a specified directory recursively. """ dname = sys.argv[1] dpath = os.path.abspath(dname) line_count = 0 for fpath,dnames,fnames in os.walk(dpath): for i in fnames: j = os.path.join(fpath,i) if i.split('.')[1] == 'py': fn = open(j, 'r') for j in fn.readlines(): line_count += 1 yield line_count y = lines_py() while True: print y.next()
[ "joeldavisp17195@gmail.com" ]
joeldavisp17195@gmail.com
e4ca53294f3bb722d6cea8e2f23af4c97b3e01e8
cd781c114deb0ee56fcd8e35df038397ebf8dc09
/Mid Exams/Array Modifier.py
0beeaf038595a84c7b956ebade8230279bf00e54
[]
no_license
GBoshnakov/SoftUni-Fund
4549446c3bb355ff74c14d6071d968bde1886de5
de9318caaf072a82a9be8c3dd4e74212b8edd79e
refs/heads/master
2023-06-06T04:56:14.951452
2021-06-30T21:50:44
2021-06-30T21:50:44
381,817,178
0
0
null
null
null
null
UTF-8
Python
false
false
624
py
numbers = [int(n) for n in input().split()] command = input() while command != "end": command = command.split() action = command[0] if action == "swap": index_1 = int(command[1]) index_2 = int(command[2]) numbers[index_1], numbers[index_2] = numbers[index_2], numbers[index_1] elif action == "multiply": index_1 = int(command[1]) index_2 = int(command[2]) numbers[index_1] *= numbers[index_2] elif action == "decrease": for i in range(len(numbers)): numbers[i] -= 1 command = input() print(", ".join(list(map(str, numbers))))
[ "boshnakov.g@gmail.com" ]
boshnakov.g@gmail.com
ae794f51c213d3b803cc088b8c557a9b5dd56371
b7b7342a7369117cb98de55f697153e875eecbbc
/example.py
098d2dcfbcfa00aab247a6a943daee18f895b5ad
[ "MIT" ]
permissive
zzygyx9119/nglesspy
953a3ab084b7df72df522076b3cd094e4a02ba12
3cfa28ea8fe2fdc3c08ac80a5949844544489cc9
refs/heads/master
2022-11-18T20:38:45.927728
2020-07-16T19:56:42
2020-07-16T19:57:26
null
0
0
null
null
null
null
UTF-8
Python
false
false
444
py
from ngless import NGLess sc = NGLess.NGLess('0.0') sc.import_('mocat', '0.0') e = sc.env e.sample = sc.load_mocat_sample_('testing') @sc.preprocess_(e.sample, using='r') def proc(bk): bk.r = sc.substrim_(bk.r, min_quality=25) sc.if_(sc.len_(bk.r) < 45, sc.discard_) e.mapped = sc.map_(e.sample, reference='hg19') e.mapped = sc.select_(e.mapped, keep_if=['{mapped}']) sc.write_(e.mapped, ofile='ofile.sam') sc.run()
[ "luis@luispedro.org" ]
luis@luispedro.org
818ff902546aedaae8aaab629c81c725f1bf8b91
a94e8b83bb2a4ccc1fffbd28dd18f8783872daab
/Mock CCC/Mock CCC19S2 Pusheens Puzzle Present.py
aec48957b55fe819a6e6614885614ac56d2f56d4
[]
no_license
MowMowchow/Competitive-Programming
d679c1fe2d7d52940dc83a07dc8048922078704e
0ec81190f6322e103c2ae0ad8c3935bd4cdfff46
refs/heads/master
2022-03-03T03:01:03.383337
2022-02-17T07:27:45
2022-02-17T07:27:45
184,678,148
0
0
null
null
null
null
UTF-8
Python
false
false
329
py
import sys import math n = int(sys.stdin.readline()) grid = [[int(x) for x in sys.stdin.readline().split()] for x in range(n)] counter = 1 sublength = 0 for row in grid: for curr in range(n-1): if row[curr] != row[curr+1] - 1: sublength += 1 break #counter += 1 print(sublength)
[ "darkstar.hou2@gmail.com" ]
darkstar.hou2@gmail.com
4e9cf1128c2b20e84ccb9cb2a506b60bd1d92535
4d4899e54a8a97fad2039350f16c50245a4e0810
/source/todoapp/migrations/0003_task_full_description.py
09595c6bfdf9b7d031b76dd1d3c8ead3665d189d
[]
no_license
UuljanAitnazarova/python_homework_45_To_do_list
f7f4925bff987d5a13e52b48f745a4bddb72c440
592bd5ad8ac61f1147e7bf5ffe49f899a9a0c7cd
refs/heads/master
2023-03-12T12:28:24.234398
2021-03-04T08:52:25
2021-03-04T08:52:25
341,508,360
0
1
null
null
null
null
UTF-8
Python
false
false
469
py
# Generated by Django 3.1.7 on 2021-02-26 10:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('todoapp', '0002_auto_20210223_1242'), ] operations = [ migrations.AddField( model_name='task', name='full_description', field=models.TextField(default='полное описание задания'), preserve_default=False, ), ]
[ "u.aitnazarova@gmail.com" ]
u.aitnazarova@gmail.com
dbc6452150f8f06e22b66ac18298bc53ce7bdf3a
8bb4a472344fda15985ac322d14e8f4ad79c7553
/Python3-Core/src/main/prompto/runtime/WidgetField.py
66b4317c7bea2bed240b1d845097bc99cc1af084
[]
no_license
prompto/prompto-python3
c6b356f5af30c6826730ba7f2ad869f341983a2d
64bd3d97d4702cc912097d41d961f7ab3fd82bee
refs/heads/master
2022-12-24T12:33:16.251468
2022-11-27T17:37:56
2022-11-27T17:37:56
32,623,633
4
0
null
2019-05-04T11:06:05
2015-03-21T07:17:25
Python
UTF-8
Python
false
false
201
py
from prompto.runtime.Variable import Variable from prompto.type.IType import IType class WidgetField(Variable): def __init__(self, name: str, itype: IType): super().__init__(name, itype)
[ "eric.vergnaud@wanadoo.fr" ]
eric.vergnaud@wanadoo.fr
191484b45d9f5be8b3b00a8c2a6d15772c38782c
abc72a2f2072ab7a5a338e41d81c354324943b09
/tarefa11/sugestao.py
9c645d2ab609253931239f50b72395ec34a5b090
[]
no_license
gigennari/mc102
a3d39fd9a942c97ef477a9b59d7955f4269b202a
fce680d5188a8dfb0bc1832d6f430cbcaf68ef55
refs/heads/master
2023-04-05T01:40:58.839889
2020-07-27T20:33:56
2020-07-27T20:33:56
354,130,720
0
0
null
null
null
null
UTF-8
Python
false
false
3,420
py
""" Escreva um programa que, dadas duas palavras, sugere ao usuário qual será a próxima palavra, tal que essa escolha seja baseada na probabilidade de que essas três palavras apareçam nessa ordem em um determinado texto. Entrada: 1ª linha - o caminho do arquivo de texto 2ª linha - sequência de pares de palavras, um por linha Saída: frase sugerida com 3 palavras, um trio por linha Exemplo: E: testes/tetxto0.in buraco negro buracos negros campo gravitacional S: buraco negro é buracos negros não campo gravitacional pode Vamos criar uma classe com 3 palavras """ class Frase: #cria uma nova classe de abstração; coleção fixa de propriedades def __init__(self, p1, p2, p3): self.p1 = p1 self.p2 = p2 self.p3 = p3 def __repr__(self): return "% s % s % s" % (self.p1, self.p2, self.p3) def ler_entrada(): """lê caminho do texto e duas palavras do texto por linha, formando uma lista de Frase""" caminho = input() lista = [] while True: try: palavras = input().split() frase = Frase(palavras[0], palavras[1], "") lista.append(frase) except EOFError: break return caminho, lista def ler_arquivo_texto(nome_do_arquivo): """lê arquivo de texto, chama função para limpar pontuação e transforma em lista""" texto = open(nome_do_arquivo).read().lower() texto = limpar_pontuacao(texto) palavras = texto.split() return palavras def limpar_pontuacao(string): pontuacao = ".,;:?!''/*#@&" #sem hifen sem_pontucao = "" for letra in string: if letra not in pontuacao: sem_pontucao += letra return sem_pontucao def descobrir_frequencias(palavras): """ contar a frequencia de cada uma das palavras; devolve dict """ wordcount = {} #vamos usar um dict para armazenar a palavra e sua frequencia juntos for palavra in palavras: if palavra in wordcount: wordcount[palavra] += 1 else: wordcount[palavra] = 1 return wordcount def encontrar_proxima_palavra(texto, frase): """procura todas as próximas palavras, adiciona em uma lista, conta frequencia (dict), frase.p3 = palavra de maior frequencia; a mais frequente será a próxima""" proximas = [] for i, palavra in enumerate(texto): #procura próximas palavras if texto[i] == frase.p1: if texto[i+1] == frase.p2: seguinte = texto[i+2] proximas.append(seguinte) #adiciona todas as palavras que aparecem depois das duas primeiras #contar frequencia da lista --> dict --> dict.keys() proximas_dict = descobrir_frequencias(proximas) proximasordenadas = sorted(proximas_dict.items(), key=lambda a: a[0]) #devolve uma lista de tuplas (palavra, frequencia) em ordem alfabética proximasordenadas.sort(key=lambda f: f[1], reverse=True) #ordena a lista em ordem decrescente #frase.p3 = 1º elemento do dicionário frase.p3 = proximasordenadas[0][0] return frase def main(): caminho, frases = ler_entrada() texto = ler_arquivo_texto(caminho) trios = [] for frase in frases: frase_completa = encontrar_proxima_palavra(texto, frase) trios.append(frase_completa) for frase in trios: print(frase) main()
[ "g198010@dac.unicamp.br" ]
g198010@dac.unicamp.br
2a8baba7315e41a92db6cbdea5ef52408fcb9143
fd308ec9cb448c2b47ec4736b670ce452b70800d
/sdap/jobs/views.py
b66d02ed32f0fabf23b619815af97c5d649e5c8f
[ "MIT" ]
permissive
umr1085-irset/reproGenomicsViewer
d4d8c52fbe72a1824812d2f5a7574be7ce58f9b5
700bbe817596b27a05ed75a8761506c5004f340f
refs/heads/master
2023-05-25T01:55:42.333286
2023-05-15T10:02:54
2023-05-15T10:02:54
219,467,036
0
4
MIT
2022-02-11T09:44:32
2019-11-04T09:46:02
JavaScript
UTF-8
Python
false
false
3,463
py
import os from datetime import datetime from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from django.views import generic from django.utils import timezone from django.views import View from django.shortcuts import redirect from django.conf import settings from django.core.files.storage import FileSystemStorage from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib import messages from django.http import HttpResponse from mimetypes import guess_type from django.urls import reverse_lazy from sdap.jobs.models import Job from celery.result import AsyncResult # Create your views here. class IndexView(LoginRequiredMixin, generic.ListView): template_name = 'analyse/index.html' context_object_name = 'latest_analyse_list' def get_queryset(self): """ Return the last five published questions (not including those set to be published in the future). """ return Job.objects.filter( created_at__lte=timezone.now() ).order_by('-created_at')[:5] def DetailView(request, pk): job = get_object_or_404(Job, pk=pk) file_list = [] for file in os.listdir(job.output): table_content='' info = os.path.splitext(file) if info[1] == ".matrix" or info[1] == ".tsv" or info[1] == ".info" or info[1] == ".list" : df = pd.read_csv(os.path.join(job.output, file), sep="\t") df_head = df.head() table_content = df_head.to_html(classes=["table", "table-bordered", "table-striped", "table-hover"]) if info[1] == ".csv": df = pd.read_csv(os.path.join(job.output, file), sep=",") df_head = df.head() table_content = df_head.to_html(classes=["table", "table-bordered", "table-striped", "table-hover"]) file_list.append({'name':info[0],'ext':info[1], 'table':table_content, 'file':file, 'path':os.path.join(job.output, file)}) context = {'job':job, 'file_list':file_list} return render(request, 'jobs/results.html', context) def DownloadView(request, pk, file_name): job = get_object_or_404(Job, pk=pk) file_path = os.path.join(job.output, file_name) with open(file_path, 'rb') as f: response = HttpResponse(f, content_type=guess_type(file_path)[0]) response['Content-Length'] = len(response.content) return response class RunningJobsView(LoginRequiredMixin, generic.ListView): model = Job template_name = 'jobs/running_jobs.html' def get_context_data(self, **kwargs): context = super(RunningJobsView, self).get_context_data(**kwargs) context['jobs_list'] = Job.objects.filter(created_by__exact=self.request.user.id) for job in context['jobs_list']: if job.status != "SUCCESS": job.status = AsyncResult(job.celery_task_id).state job.save() return context def Delete_job(request, pk): job = get_object_or_404(Job, pk=pk) print(job) job.delete() context = {} context['jobs_list'] = Job.objects.filter(created_by__exact=request.user.id) for job in context['jobs_list']: if job.status != "SUCCESS": job.status = AsyncResult(job.celery_task_id).state job.save() return render(request, 'jobs/running_jobs.html', context)
[ "dardethomas@gmail.com" ]
dardethomas@gmail.com
f555c688d0fc632999966fdd07767c457fa0ab21
be12916ec075c76469946f6da2cdde4857141702
/771_2.py
3c283b6a4ace661e675538e93277637a7552e724
[]
no_license
goodsosbva/algorithm
7b2f9b1a899e43c7d120ab9d40e672be336a23d9
0bc44e9466d2d32a4b4e126e073badc60172da6e
refs/heads/main
2023-08-06T19:34:40.630006
2021-09-20T10:34:41
2021-09-20T10:34:41
334,918,056
3
0
null
null
null
null
UTF-8
Python
false
false
361
py
import collections def newJewelsInStones(J: str, S: str) -> int: freqs = collections.Counter(S) # 돌(S) 빈도 수 계산 count = 0 # 비교 없이 보석(j) 빈도 수 계산 for char in J: count += freqs[char] return count jew = "aA" stone = "aAAbbbb" jcount = newJewelsInStones(jew, stone) print(jcount)
[ "noreply@github.com" ]
goodsosbva.noreply@github.com
12e27a1ffb5b0c67c43f8b2c732fb638e6d2fa70
6b5431368cb046167d71c1f865506b8175127400
/challenges/n-primeiros-numeros-primos/tests.py
f921a7fcdf0065d0389c1479673886c2e732c226
[]
no_license
Insper/design-de-software-exercicios
e142f4824a57c80f063d617ace0caa0be746521e
3b77f0fb1bc3d76bb99ea318ac6a5a423df2d310
refs/heads/master
2023-07-03T12:21:36.088136
2021-08-04T16:18:03
2021-08-04T16:18:03
294,813,936
0
1
null
2021-08-04T16:18:04
2020-09-11T21:17:24
Python
UTF-8
Python
false
false
910
py
from strtest import str_test def eh_primo_gabarito(n): if n == 2: return True if n == 0 or n == 1 or n % 2 == 0: return False d = 3 while d < n: if n % d == 0: return False d += 2 return True def gabarito_dos_professores(n): encontrados = 0 i = 2 primos = [] while encontrados < n: if eh_primo_gabarito(i): primos.append(i) encontrados += 1 i += 1 return primos class TestCase(str_test.TestCaseWrapper): TIMEOUT = 2 def test_1(self): n = 100 primos = gabarito_dos_professores(n) retval = self.function(n) self.assertEqual(n, len(retval), 'Deveria ter exatamente n números primos') for primo, returned in zip(primos, retval): self.assertEqual(primo, returned, 'Não retornou os n primeiros primeos em ordem crescente')
[ "andrew.kurauchi@gmail.com" ]
andrew.kurauchi@gmail.com
92fa4c4cee9bfd46c826875c760c60269d31c06f
fcdbf22231739b61bbd4da531fcacf0c6f08c4bf
/services/lasso_regression/prod.config.py
0ba5c9b0f0b2531fae1cba7e4b5ac173809e1241
[]
no_license
revotechUET/wi-uservice
2a3f169a4a9735bb3167d8bef75baceab11b2a04
33f2ad2f0a329fc1f54153b0ebb775f2bd74d631
refs/heads/master
2023-04-15T14:58:36.183521
2023-04-07T09:39:48
2023-04-07T09:39:48
179,446,650
0
1
null
2022-12-08T01:51:59
2019-04-04T07:39:07
Python
UTF-8
Python
false
false
1,939
py
import os import multiprocessing bind = '0.0.0.0:80' backlog = 2048 workers = multiprocessing.cpu_count() worker_class = 'sync' or os.environ.get("WORKER_CLASS") worker_connections = 1000 timeout = 30 keepalive = 2 reload = False spew = False daemon = False raw_env = [ "DB_HOST="+os.environ.get("DB_HOST", "127.0.0.1"), "DB_PORT="+os.environ.get("DB_PORT", "27017"), "DB_NAME="+os.environ.get("DB_NAME", "wi_regression"), "MODEL_DIR="+os.path.join(os.getcwd(), "static"), ] if os.environ.get("DB_USER"): raw_env.append("DB_USER="+os.environ.get("DB_USER")) raw_env.append("DB_PASS="+os.environ.get("DB_PASS")) pidfile = "/tmp/lasso.pid" umask = 0 user = None group = None tmp_upload_dir = None errorlog = '-' loglevel = 'error' accesslog = '/var/log/wi_regression.access.log' access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"' proc_name = None def post_fork(server, worker): server.log.info("Worker spawned (pid: %s)", worker.pid) def pre_fork(server, worker): pass def pre_exec(server): server.log.info("Forked child, re-executing.") def when_ready(server): server.log.info("Server is ready. Spawning workers") def worker_int(worker): worker.log.info("worker received INT or QUIT signal") ## get traceback info import threading, sys, traceback id2name = {th.ident: th.name for th in threading.enumerate()} code = [] for threadId, stack in sys._current_frames().items(): code.append("\n# Thread: %s(%d)" % (id2name.get(threadId,""), threadId)) for filename, lineno, name, line in traceback.extract_stack(stack): code.append('File: "%s", line %d, in %s' % (filename, lineno, name)) if line: code.append(" %s" % (line.strip())) worker.log.debug("\n".join(code)) def worker_abort(worker): worker.log.info("Worker received SIGABRT signal")
[ "thinhlevan2015@gmail.com" ]
thinhlevan2015@gmail.com
c2d2b5d7a681a9da5144059d9d26d2b5fce68443
c4b7399a10b7f963f625d8d15e0a8215ea35ef7d
/225.用队列实现栈.py
30aed3284d9d2a250a13ade1686b9a592683c1e3
[]
no_license
kangkang59812/LeetCode-python
a29a9788aa36689d1f3ed0e8b668f79d9ca43d42
276d2137a929e41120c2e8a3a8e4d09023a2abd5
refs/heads/master
2022-12-05T02:49:14.554893
2020-08-30T08:22:16
2020-08-30T08:22:16
266,042,478
0
0
null
null
null
null
UTF-8
Python
false
false
1,823
py
# # @lc app=leetcode.cn id=225 lang=python3 # # [225] 用队列实现栈 # # https://leetcode-cn.com/problems/implement-stack-using-queues/description/ # # algorithms # Easy (64.30%) # Likes: 158 # Dislikes: 0 # Total Accepted: 45.7K # Total Submissions: 71.1K # Testcase Example: '["MyStack","push","push","top","pop","empty"]\n[[],[1],[2],[],[],[]]' # # 使用队列实现栈的下列操作: # # # push(x) -- 元素 x 入栈 # pop() -- 移除栈顶元素 # top() -- 获取栈顶元素 # empty() -- 返回栈是否为空 # # # 注意: # # # 你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty # 这些操作是合法的。 # 你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。 # 你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。 # # # # @lc code=start class MyStack: def __init__(self): """ Initialize your data structure here. """ self.res=[] def push(self, x: int) -> None: """ Push element x onto stack. """ self.res.append(x) def pop(self) -> int: """ Removes the element on top of the stack and returns that element. """ return self.res.pop() def top(self) -> int: """ Get the top element. """ return self.res[-1] def empty(self) -> bool: """ Returns whether the stack is empty. """ return len(self.res)==0 # Your MyStack object will be instantiated and called as such: # obj = MyStack() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.top() # param_4 = obj.empty() # @lc code=end
[ "596286458@qq.com" ]
596286458@qq.com
9b8c1f144c99095882b7063ecfbd996ea85ad76d
d2c4934325f5ddd567963e7bd2bdc0673f92bc40
/tests/model_control/detailed/transf_Anscombe/model_control_one_enabled_Anscombe_PolyTrend_Seasonal_Second_MLP.py
5f171286f0c82166bee8bda1463b423ed0a90ed9
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jmabry/pyaf
797acdd585842474ff4ae1d9db5606877252d9b8
afbc15a851a2445a7824bf255af612dc429265af
refs/heads/master
2020-03-20T02:14:12.597970
2018-12-17T22:08:11
2018-12-17T22:08:11
137,104,552
0
0
BSD-3-Clause
2018-12-17T22:08:12
2018-06-12T17:15:43
Python
UTF-8
Python
false
false
162
py
import pyaf.tests.model_control.test_ozone_custom_models_enabled as testmod testmod.build_model( ['Anscombe'] , ['PolyTrend'] , ['Seasonal_Second'] , ['MLP'] );
[ "antoine.carme@laposte.net" ]
antoine.carme@laposte.net
797fb5e4b44f2abe5c67ca7a0b9b2fba00dcd1e2
f305f84ea6f721c2391300f0a60e21d2ce14f2a5
/7_graph/经典题/置换环/amidakuji鬼脚图/1-最少的横线构造amidakuji.py
32ff9e00794f1b88811986c870be0e27ba2b7ac0
[]
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
889
py
# 冒泡排序邻位交换 构造amidakuji的横线 from typing import List def amidakuji(ends: List[int]) -> List[int]: """ 冒泡排序构造amidakuji的横线 Args: ends: 每个点最后的位置 (1-index) Returns: 鬼脚图的横线,一共m条,从上往下表示. lines[i] 表示第i条横线连接 line[i] 和 line[i]+1. (1-index) """ n = len(ends) res = [] for i in range(n - 1): isSorted = True for j in range(n - 1 - i): if ends[j] > ends[j + 1]: isSorted = False res.append(j + 1) ends[j], ends[j + 1] = ends[j + 1], ends[j] if isSorted: break return res[::-1] # 目标数组冒泡排序的逆序才是从上往下的横线顺序 assert amidakuji([5, 2, 4, 1, 3]) == [1, 3, 2, 4, 3, 2, 1]
[ "lmt2818088@gmail.com" ]
lmt2818088@gmail.com
5069b7fa589dea216ef97b476055fcf630474880
39dac505e0814d8f73d21576085b02e5e54d9b05
/67.py
4b3bbfabcd2eafad0676f05c08d42b459cf43d65
[]
no_license
gxmls/Python_Leetcode
4b2ce5efb0a88cf80ffe5e57a80185ca5df91af2
2a9bb36c5df0eaba026183a76deb677c5bd7fd2d
refs/heads/main
2023-06-08T03:45:43.548212
2021-06-22T09:46:44
2021-06-22T09:46:44
362,726,420
0
0
null
null
null
null
UTF-8
Python
false
false
773
py
''' 给你两个二进制字符串,返回它们的和(用二进制表示)。 输入为 非空 字符串且只包含数字 1 和 0。 示例 1: 输入: a = "11", b = "1" 输出: "100" 示例 2: 输入: a = "1010", b = "1011" 输出: "10101" 提示: 每个字符串仅由字符 '0' 或 '1' 组成。 1 <= a.length, b.length <= 10^4 字符串如果不是 "0" ,就都不含前导零。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/add-binary 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' class Solution: def addBinary(self, a: str, b: str) -> str: sa='0b'+a sb='0b'+b s=str(bin(eval(sa)+eval(sb))) return s[2:]
[ "noreply@github.com" ]
gxmls.noreply@github.com
94db114f318aa9b8d5bb675594da7ce584d26625
1f700dad5a6cae92d2f918098e5d6ffb92ead725
/tests/path/compressed_stream_path_spec.py
dd265d90b7bdc40125f173b57997c89a59e064a1
[ "Apache-2.0" ]
permissive
devgc/dfvfs
5cdf4fc8a984a4768877536128cee60d53e89834
a0196808f569e4c5f947c458945cd0a17d1abab5
refs/heads/master
2020-04-05T23:42:11.088128
2016-08-23T16:50:16
2016-08-23T16:50:16
66,384,661
1
0
null
2016-08-23T16:36:10
2016-08-23T16:36:07
Python
UTF-8
Python
false
false
1,618
py
#!/usr/bin/python # -*- coding: utf-8 -*- """Tests for the compressed stream path specification implementation.""" import unittest from dfvfs.path import compressed_stream_path_spec from tests.path import test_lib class CompressedStreamPathSpecTest(test_lib.PathSpecTestCase): """Tests for the compressed stream path specification implementation.""" def testInitialize(self): """Tests the path specification initialization.""" path_spec = compressed_stream_path_spec.CompressedStreamPathSpec( compression_method=u'test', parent=self._path_spec) self.assertIsNotNone(path_spec) with self.assertRaises(ValueError): _ = compressed_stream_path_spec.CompressedStreamPathSpec( compression_method=u'test', parent=None) with self.assertRaises(ValueError): _ = compressed_stream_path_spec.CompressedStreamPathSpec( compression_method=None, parent=self._path_spec) with self.assertRaises(ValueError): _ = compressed_stream_path_spec.CompressedStreamPathSpec( compression_method=u'test', parent=self._path_spec, bogus=u'BOGUS') def testComparable(self): """Tests the path specification comparable property.""" path_spec = compressed_stream_path_spec.CompressedStreamPathSpec( compression_method=u'test', parent=self._path_spec) self.assertIsNotNone(path_spec) expected_comparable = u'\n'.join([ u'type: TEST', u'type: COMPRESSED_STREAM, compression_method: test', u'']) self.assertEqual(path_spec.comparable, expected_comparable) if __name__ == '__main__': unittest.main()
[ "joachim.metz@gmail.com" ]
joachim.metz@gmail.com
6b2635ba044761b70c21a0615dfe7ff99392f967
1c6283303ceb883add8de4ee07c5ffcfc2e93fab
/Jinja2/lib/python3.7/site-packages/ixnetwork_restpy/testplatform/sessions/ixnetwork/traffic/trafficitem/configelement/stack/frameRelay_template.py
ec8c961f3acb1c4fdc24e612b525e265eee952f2
[]
no_license
pdobrinskiy/devcore
0f5b3dfc2f3bf1e44abd716f008a01c443e14f18
580c7df6f5db8c118990cf01bc2b986285b9718b
refs/heads/main
2023-07-29T20:28:49.035475
2021-09-14T10:02:16
2021-09-14T10:02:16
405,919,390
0
0
null
null
null
null
UTF-8
Python
false
false
5,002
py
from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class FrameRelay(Base): __slots__ = () _SDM_NAME = 'frameRelay' _SDM_ATT_MAP = { 'Address2ByteDlciHiOrderBits': 'frameRelay.header.frameRelayTag.frameRelay.address.address2Byte.dlciHiOrderBits-1', 'Address2ByteCrBit': 'frameRelay.header.frameRelayTag.frameRelay.address.address2Byte.crBit-2', 'Address2ByteEa0Bit': 'frameRelay.header.frameRelayTag.frameRelay.address.address2Byte.ea0Bit-3', 'Address2ByteDlciLoOrderBits': 'frameRelay.header.frameRelayTag.frameRelay.address.address2Byte.dlciLoOrderBits-4', 'Address2ByteFecnBit': 'frameRelay.header.frameRelayTag.frameRelay.address.address2Byte.fecnBit-5', 'Address2ByteBecnBit': 'frameRelay.header.frameRelayTag.frameRelay.address.address2Byte.becnBit-6', 'Address2ByteDeBit': 'frameRelay.header.frameRelayTag.frameRelay.address.address2Byte.deBit-7', 'Address2ByteEa1Bit': 'frameRelay.header.frameRelayTag.frameRelay.address.address2Byte.ea1Bit-8', 'HeaderControl': 'frameRelay.header.control-9', 'PaddingPad': 'frameRelay.header.padding.pad-10', 'HeaderNlpid': 'frameRelay.header.nlpid-11', } def __init__(self, parent, list_op=False): super(FrameRelay, self).__init__(parent, list_op) @property def Address2ByteDlciHiOrderBits(self): """ Display Name: DLCI High Order Bits Default Value: 0 Value Format: decimal """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['Address2ByteDlciHiOrderBits'])) @property def Address2ByteCrBit(self): """ Display Name: CR Bit Default Value: 0 Value Format: decimal """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['Address2ByteCrBit'])) @property def Address2ByteEa0Bit(self): """ Display Name: EA0 Bit Default Value: 0 Value Format: decimal """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['Address2ByteEa0Bit'])) @property def Address2ByteDlciLoOrderBits(self): """ Display Name: DLCI Low Order Bits Default Value: 0 Value Format: decimal """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['Address2ByteDlciLoOrderBits'])) @property def Address2ByteFecnBit(self): """ Display Name: FECN Bit Default Value: 0 Value Format: decimal """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['Address2ByteFecnBit'])) @property def Address2ByteBecnBit(self): """ Display Name: BECN Bit Default Value: 0 Value Format: decimal """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['Address2ByteBecnBit'])) @property def Address2ByteDeBit(self): """ Display Name: DE Bit Default Value: 0 Value Format: decimal """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['Address2ByteDeBit'])) @property def Address2ByteEa1Bit(self): """ Display Name: EA1 Bit Default Value: 1 Value Format: decimal """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['Address2ByteEa1Bit'])) @property def HeaderControl(self): """ Display Name: Control Default Value: 0x03 Value Format: hex """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['HeaderControl'])) @property def PaddingPad(self): """ Display Name: Pad Default Value: 0x00 Value Format: hex """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['PaddingPad'])) @property def HeaderNlpid(self): """ Display Name: NLPID Default Value: 0xCC Value Format: hex """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['HeaderNlpid'])) def add(self): return self._create(self._map_locals(self._SDM_ATT_MAP, locals()))
[ "pdobrinskiy@yahoo.com" ]
pdobrinskiy@yahoo.com
c575a9c2ea029a2616fb7aa34165dc2b935eb63a
3b863f7e7efea09f5a120eb8c323e5a3742b82b3
/LevelSelection_Page/LevelSelection_Page.pyde
23a2c39a016791744f8abcef5874cfa5058a187b
[]
no_license
TriceG/DNA_Project
b6096fbc91c35621b659dd5154a1972a9674d881
469df295120fbfe32070fd973c55f36b2af99341
refs/heads/master
2021-01-19T21:32:24.914550
2017-06-20T14:15:27
2017-06-20T14:15:27
88,661,601
0
0
null
null
null
null
UTF-8
Python
false
false
1,072
pyde
def setup(): background(37, 154, 247) size(800, 500) def draw(): fill(225) rectMode(CENTER) #beginerButton rect(400, 175, 150, 50) #intermediateButton rect(400, 275, 239, 50) #advancedButton rect(400, 375, 190, 50) textSize(30) #title text("Select a Level:", 300, 100) fill(0) #button text text("BEGINER", 337, 185) text("INTERMEDIATE", 292, 285) text("ADVANCED", 316, 385) def mouseClicked(): #BEGINER button clicked if mouseX > 325 and mouseX < 475 and mouseY > 150 and mouseY < 200: #go to easy mode #Import Easy Mode background(194, 247, 37) #INTERMEDIATE button clicked if mouseX > 280.5 and mouseX < 519.5 and mouseY > 250 and mouseY < 300: #go to medium mode #Import Medium mode background(47, 247, 37) #ADVANCED button clicked if mouseX > 305 and mouseX < 495 and mouseY > 350 and mouseY < 400: #go to hard mode #Import Hard Mode background(27, 167, 20)
[ "none@none" ]
none@none
8dbbb798fd7d365ab6925e56271b3e38fd9151e3
d229480fb037442bfc2d895e300fdab89d06e1f6
/examples/train_cornac.py
739d5ecca174fe68cffed861aa5a7481900cda49
[]
no_license
anonymcodes/t-vbr
939c8eebed4e6ecbe4e85b26b296b5e16bb0b445
c8d37aee05de5060a98fac74421a28db0a7eaa4c
refs/heads/master
2023-08-09T01:55:12.295567
2020-12-03T02:06:18
2020-12-03T02:06:18
264,423,776
2
0
null
2023-07-23T17:09:20
2020-05-16T11:40:02
Python
UTF-8
Python
false
false
6,934
py
import numpy as np import pandas as pd import pickle import argparse import json import torch.optim as optim from torch import Tensor from torch.utils.data import DataLoader import torch import torch.nn as nn import torch.optim as optim from tqdm import tqdm from livelossplot import PlotLosses import GPUtil import os import sys from datetime import datetime sys.path.append("../") import random import cornac from cornac.eval_methods.base_method import BaseMethod base_string = "abcdefghijklmnopqrstuvwxyz" from scipy.sparse import csr_matrix from beta_rec.utils.monitor import Monitor from beta_rec.utils.common_util import save_to_csv from beta_rec.utils import data_util from beta_rec.utils import logger import beta_rec.utils.constants as Constants from beta_rec.datasets import data_load import beta_rec.utils.evaluation as eval_model import beta_rec.utils.constants as Constants from scipy.sparse import csr_matrix import pandas as pd def parse_args(): parser = argparse.ArgumentParser(description="Run cornac model..") # If the following settings are specified with command line, # these settings will be updated. parser.add_argument( "--config_file", default="../configs/cornac_default.json", nargs="?", type=str, help="Options are: tafeng, dunnhunmby and instacart", ) parser.add_argument( "--dataset", nargs="?", type=str, help="Options are: tafeng, dunnhunmby and instacart", ) parser.add_argument( "--data_split", nargs="?", type=str, help="Options are: leave_one_out and temporal", ) parser.add_argument( "--test_percent", nargs="?", type=float, help="Options are: leave_one_out and temporal", ) parser.add_argument( "--root_dir", nargs="?", type=str, help="working directory", ) parser.add_argument( "--toy", nargs="?", type=int, help="working directory", ) return parser.parse_args() """ update hyperparameters from command line """ def update_args(config, args): # print(vars(args)) for k, v in vars(args).items(): if v != None: config[k] = v print("Received parameters form comand line:", k, v) def my_eval(eval_data_df, model): u_indices = eval_data_df[Constants.DEFAULT_USER_COL].to_numpy() i_indices = eval_data_df[Constants.DEFAULT_ITEM_COL].to_numpy() r_preds = np.fromiter( ( model.score(user_idx, item_idx).item() for user_idx, item_idx in zip(u_indices, i_indices) ), dtype=np.float, count=len(u_indices), ) pred_df = pd.DataFrame( { Constants.DEFAULT_USER_COL: u_indices, Constants.DEFAULT_ITEM_COL: i_indices, Constants.DEFAULT_PREDICTION_COL: r_preds, } ) result_dic = {} TOP_K = [5, 10, 20] if type(TOP_K) != list: TOP_K = [TOP_K] if 10 not in TOP_K: TOP_K.append(10) metrics = ["ndcg_at_k", "precision_at_k", "recall_at_k", "map_at_k"] for k in TOP_K: for metric in metrics: eval_metric = getattr(eval_model, metric) result = eval_metric(eval_data_df, pred_df, k=k) result_dic[metric + "@" + str(k)] = result result_dic.update(config) result_df = pd.DataFrame(result_dic, index=[0]) save_to_csv(result_df, config["result_file"]) if __name__ == "__main__": # load config file from json config = {} args = parse_args() update_args(config, args) with open(config["config_file"]) as config_params: print("loading config file", config["config_file"]) json_config = json.load(config_params) json_config.update(config) config = json_config root_dir = config["root_dir"] time_str = datetime.now().strftime("%Y%m%d_%H%M%S") log_file = ( root_dir + "logs/cornac" + "_" + config["dataset"] + "_" + config["data_split"] + time_str ) config["result_file"] = ( root_dir + "results/cornac" + "_" + config["dataset"] + "_" + config["data_split"] + ".csv" ) """ init logger """ logger.init_std_logger(log_file) # cornac.eval_methods.base_method.rating_eval = rating_eval # Load the built-in MovieLens 100K dataset (will be downloaded if not cached): # Here we are comparing Biased MF, PMF, and BPR: # pop = cornac.models.most_pop.recom_most_pop.MostPop(name="MostPop") # mf = cornac.models.MF( # k=10, max_iter=25, learning_rate=0.01, lambda_reg=0.02, use_bias=True, seed=123 # ) # pmf = cornac.models.PMF( # k=10, max_iter=100, learning_rate=0.001, lambda_reg=0.001, seed=123 # ) # bpr = cornac.models.BPR( # k=10, max_iter=200, learning_rate=0.001, lambda_reg=0.01, seed=123 # ) # vaecf = cornac.models.vaecf.recom_vaecf.VAECF( # name="VAECF", # k=10, # autoencoder_structure=[20], # act_fn="tanh", # likelihood="mult", # n_epochs=100, # batch_size=100, # learning_rate=0.001, # beta=1.0, # trainable=True, # verbose=False, # seed=None, # use_gpu=True, # ) # nmf = cornac.models.NMF( # k=15, # max_iter=50, # learning_rate=0.005, # lambda_u=0.06, # lambda_v=0.06, # lambda_bu=0.02, # lambda_bi=0.02, # use_bias=False, # verbose=True, # seed=123, # ) neumf = cornac.models.ncf.recom_neumf.NeuMF( name="NCF", num_factors=8, layers=(32, 16, 8), act_fn="relu", reg_mf=0.0, reg_layers=(0.0, 0.0, 0.0, 0.0), num_epochs=20, batch_size=256, num_neg=4, lr=0.001, learner="adam", early_stopping=None, trainable=True, verbose=True, seed=None, ) # models = [pop, mf, pmf, bpr, vaecf, nmf, neumf] models = [neumf] # add our own eval data = data_util.Dataset(config) num_users = data.n_users num_items = data.n_items uid_map = data.user2id iid_map = data.item2id train_uir_tuple = [ data.train["col_user"].to_numpy(), data.train["col_item"].to_numpy(), data.train["col_rating"].to_numpy(), ] train_data = cornac.data.Dataset( num_users, num_items, uid_map, iid_map, train_uir_tuple, timestamps=None, seed=None, ) test_df_li = data.test for model in models: config["model"] = str(model.__class__).split(".")[-1].replace(">", "").strip( "'\"" ) + datetime.now().strftime("_%Y%m%d_%H%M%S") model.fit(train_data) my_eval(test_df_li[0], model)
[ "your@email.com" ]
your@email.com
24bd01eef13ac27c129556df9c4bdd7e0d6ad861
44b869c9ddcfd8afa429a6a4758c6acdac62f9c1
/users/admin.py
c13af5a0c2a73efaf7790a0cc239c9c99a1fafdc
[]
no_license
paulitstep/blog-api
7507394eb008c6c1bd30e5699bb33e9e37cfac52
5ce6d84495fa9b6d32b38d7d99412858ff3bc077
refs/heads/main
2023-04-06T12:56:00.364861
2021-04-16T09:28:09
2021-04-16T09:28:09
357,801,983
0
0
null
null
null
null
UTF-8
Python
false
false
805
py
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from users.models import NewUser class UserAdminConfig(UserAdmin): model = NewUser search_fields = ('email', 'user_name',) list_filter = ('email', 'user_name', 'is_staff', 'is_active') list_display = ('email', 'id', 'user_name', 'is_staff', 'is_active') ordering = ('-start_date',) fieldsets = ( (None, {'fields': ('email', 'user_name',)}), ('Permissions', {'fields': ('is_staff', 'is_active',)}), ('Personal', {'fields': ('about',)}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'user_name', 'password1', 'password2', 'is_staff', 'is_active'), }), ) admin.site.register(NewUser, UserAdminConfig)
[ "pasha-mo1@rambler.ru" ]
pasha-mo1@rambler.ru
17c45d94efa8018ba6165c376fcf4a8981629f48
c5bc44b4bb7aa0b8e6df81c198e9803eb0f060ce
/pro_tracker/issue/views.py
7a365ad081af225db4a559345972d6c6de5b7ae1
[]
no_license
hyperloop11/Progress-tracking-website
4821b1c17b04b223b1a20610b1612b11b0a54ce3
7c3bd77a0b0605994b001544fc809c1e52a18f82
refs/heads/master
2023-06-21T12:06:26.531345
2021-08-05T07:21:37
2021-08-05T07:21:37
298,636,249
0
0
null
null
null
null
UTF-8
Python
false
false
5,218
py
from django.shortcuts import render, get_object_or_404 from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, ) from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from .models import Issue from django.contrib.auth.models import User, Permission from .forms import IssueUpdateForm, CommentForm from django.views.generic.edit import FormMixin from django.urls import reverse from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from notifications.signals import notify def home(request): context = { 'posts': Issue.objects.all() } return render(request, 'issue/home.html', context) class IssueListView(ListView): model = Issue template_name='issue/home.html' context_object_name='posts' paginate_by=6 #ORDERING def get_queryset(self): return Issue.objects.filter(completed=False).order_by('-id') class OldIssueListView(ListView): model = Issue template_name='issue/home.html' context_object_name='posts' paginate_by=6 #ORDERING def get_queryset(self): return Issue.objects.filter(completed=True).order_by('-id') class IssueDetailView(FormMixin, DetailView): model = Issue form_class=CommentForm def get_success_url(self): return reverse('issue-detail', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): context = super(IssueDetailView, self).get_context_data(**kwargs) context['form'] = CommentForm(initial={'issue': self.object.id, 'author': self.request.user}) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): curr_issue = Issue.objects.get(pk=self.object.id) for user in curr_issue.author.all() : if self.request.user != user: notify.send( request.user, recipient=user, verb = 'commented on your issue', target=curr_issue, ) return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.save() return super(IssueDetailView, self).form_valid(form) class IssueCreateView(LoginRequiredMixin, CreateView): model = Issue fields= ['title', 'content', 'priority'] def form_valid(self, form): form.save() form.instance.author.add(self.request.user) return super().form_valid(form) def view_type(self): return "Create" class IssueUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Issue form_class = IssueUpdateForm # leader =self.get_object().author.first() # #author = forms.ModelChoiceField(queryset=User.objects.exclude(leader)) # form_class.fields['author'].queryset=User.objects.exclude(leader) #form_class=UserForm # def __init__(self, *args): # super(IssueUpdateView, self).__init__(*args) # leader =self.get_object().author.first() # self.fields['author'].queryset = User.objects.exclude(leader) def form_valid(self, form): form.save() form.instance.author.add(self.request.user) return super().form_valid(form) def test_func(self): post= self.get_object() if self.request.user in post.author.all() or self.request.user.has_perm('issue.change_issue'): return True else: return False def view_type(self): return "Update" #to fix kwargs in issue list view, better not inherit from listView and make a function. def UserIssue(request,username): #user = get_object_or_404( User,User.objects.get(username=username)) this_user = get_object_or_404(User, username=username) posts = this_user.issue_set.filter(completed=False).order_by('-id') paginator = Paginator(posts, 2) # Show 4 blogs per page. page_number = request.GET.get('page', 1) try: page_obj = paginator.page(page_number) except PageNotAnInteger: page_obj = paginator.page(1) except EmptyPage: page_obj = paginator.page(paginator.num_pages) context = { 'this_user': this_user, #'posts': this_user.issue_set.all().order_by('-id'), 'posts': page_obj, } return render(request, 'issue/user_issues.html', context) def UserIssueArchives(request,username): this_user = get_object_or_404(User, username=username) posts = this_user.issue_set.filter(completed=True).order_by('-id') paginator = Paginator(posts, 2) # Show 4 blogs per page. page_number = request.GET.get('page', 1) try: page_obj = paginator.page(page_number) except PageNotAnInteger: page_obj = paginator.page(1) except EmptyPage: page_obj = paginator.page(paginator.num_pages) context = { 'this_user': this_user, #'posts': this_user.issue_set.all().order_by('-id'), 'posts': page_obj, } return render(request, 'issue/user_issues.html', context)
[ "=" ]
=
7ea31f1d5cee13bb05992a54895bdc6027e86ed4
5deca81ecb729fdb1e14511b7fdb65e5f3b277de
/2_sentiment/submission_v3.py
867249d65f4d33c72710ac1ca021d7e5f65d622c
[]
no_license
anatu/CS221-Fall2018
6a0e170ada7ba8794d9e93dee875fc1a072e4692
03dbcf7cb7da953877171b311be9d0e2aacec30c
refs/heads/master
2021-03-20T06:01:52.122056
2020-03-14T00:22:10
2020-03-14T00:22:10
247,183,322
1
0
null
null
null
null
UTF-8
Python
false
false
7,968
py
#!/usr/bin/python import random import collections import math import sys from util import * ############################################################ # Problem 3: binary classification ############################################################ ############################################################ # Problem 3a: feature extraction def extractWordFeatures(x): """ Extract word features for a string x. Words are delimited by whitespace characters only. @param string x: @return dict: feature vector representation of x. Example: "I am what I am" --> {'I': 2, 'am': 2, 'what': 1} """ # BEGIN_YOUR_CODE (our solution is 4 lines of code, but don't worry if you deviate from this) features = dict() for word in set(x.split(" ")): features[word] = x.split(" ").count(word) return features # END_YOUR_CODE ############################################################ # Problem 3b: stochastic gradient descent def learnPredictor(trainExamples, testExamples, featureExtractor, numIters, eta): ''' Given |trainExamples| and |testExamples| (each one is a list of (x,y) pairs), a |featureExtractor| to apply to x, and the number of iterations to train |numIters|, the step size |eta|, return the weight vector (sparse feature vector) learned. You should implement stochastic gradient descent. Note: only use the trainExamples for training! You should call evaluatePredictor() on both trainExamples and testExamples to see how you're doing as you learn after each iteration. ''' weights = {} # feature => weight # BEGIN_YOUR_CODE (our solution is 12 lines of code, but don't worry if you deviate from this) for iteration in range(numIters): # print("BEGINNING RUN NUMBER %i" % (iteration)) for example in trainExamples: # Extract the features from the input x = example[0] y = example[1] features = featureExtractor(x) # Calculate the hinge loss score_product = (sum(weights[key]*features.get(key, 0) for key in weights))*y hingeLoss = max(0,1-score_product) # print("Example: %s , Error: %i " % (x, hingeLoss)) # Compute gradient vector based on value of the hinge loss if score_product < 1: # Equals phi*y if less than 1 hingeGrad = features hingeGrad.update((a, b*-1*y) for a, b in features.items()) else: # Zero otherwise hingeGrad = 0 # Update only if the gradient is nonzero, otherwise # gradient descent cannot proceed if hingeGrad != 0: for feature in hingeGrad.keys(): weights[feature] = weights.get(feature,0) - eta*hingeGrad.get(feature, 0) # END_YOUR_CODE return weights ############################################################ # Problem 3c: generate test case def generateDataset(numExamples, weights): ''' Return a set of examples (phi(x), y) randomly which are classified correctly by |weights|. ''' random.seed(42) # Return a single example (phi(x), y). # phi(x) should be a dict whose keys are a subset of the keys in weights # and values can be anything (randomize!) with a nonzero score under the given weight vector. # y should be 1 or -1 as classified by the weight vector. def generateExample(): # BEGIN_YOUR_CODE (our solution is 2 lines of code, but don't worry if you deviate from this) phi = {} # END_YOUR_CODE return (phi, y) return [generateExample() for _ in range(numExamples)] ############################################################ # Problem 3e: character features def extractCharacterFeatures(n): ''' Return a function that takes a string |x| and returns a sparse feature vector consisting of all n-grams of |x| without spaces. EXAMPLE: (n = 3) "I like tacos" --> {'Ili': 1, 'lik': 1, 'ike': 1, ... You may assume that n >= 1. ''' def extract(x): # BEGIN_YOUR_CODE (our solution is 6 lines of code, but don't worry if you deviate from this) # Preprocessing - ignore whitespace x = x.replace(" ","") # Pull all ngrams in a zipped form and turn into a list of string grams ngram_tuple = zip(*[x[i:] for i in range(n)]) ngram_list = ["".join(elem) for elem in ngram_tuple] features = dict() # Develop feature vector from grams for gram in ngram_list: features[gram] = x.count(gram) return features # END_YOUR_CODE return extract ############################################################ # Problem 4: k-means ############################################################ def kmeans(examples, K, maxIters): ''' examples: list of examples, each example is a string-to-double dict representing a sparse vector. K: number of desired clusters. Assume that 0 < K <= |examples|. maxIters: maximum number of iterations to run (you should terminate early if the algorithm converges). Return: (length K list of cluster centroids, list of assignments (i.e. if examples[i] belongs to centers[j], then assignments[i] = j) final reconstruction loss) ''' # BEGIN_YOUR_CODE (our solution is 32 lines of code, but don't worry if you deviate from this) # Initialize the centroids, each one being a random selection # from the input list examples random.seed(42) centroids = [] for k in range(K): centroids.append(random.choice(examples)) # LOSS - Precalculate the L2-norm squared of featureset loss_example_norm = 0 for example in examples: loss_example_norm += sum((example.get(d))**2 for d in example) # Initialize assignments list and loss storage loss_centroid_norm = 0 loss_cross_term = 0 assignments = [0 for elem in examples] assmts_lookup = {k: [] for k in range(len(centroids))} losses = dict() num_iters = 0 while num_iters < maxIters: # Step 1 - Perform the initial assignment of examples to centroids for i in range(len(examples)): distances = dict() for j in range(len(centroids)): # LOSS - Calculate cross term loss_cross_term += 2*sum((examples[i].get(d) + centroids[j].get(d)) for d in set(examples[i]) | set(centroids[j])) distances[j] = sum((examples[i].get(d,0) - centroids[j].get(d,0))**2 for d in set(examples[i]) | set(centroids[j])) min_centroid = min(distances, key=distances.get) assignments[i] = min_centroid # Add the example into the lookup table to speed up the update step assmts_lookup[min_centroid].append(example) # Step 2 - Update the centroids using the mean of assigned points centroids = [dict() for k in range(K)] for j in range(len(centroids)): assigned_examples = assmts_lookup[centroids[j]] # Add up all the dimensions of all the assigned points into the centroid for assignee in assigned_examples: for key in assignee.keys(): centroids[j][key] = centroids[j].get(key,0) + assignee[key] # Make the cluster the centroid of the points by dividing by the number of points centroids[j].update((a, b/len(assigned_examples)) for a, b in centroids[j].items()) # LOSS - Precalculate L2-norm squared of the centroids squared loss_centroid_norm += sum((example.get(d))**2 for d in centroids[j]) # LOSS - Combine to form total reconstruction loss for the run num_iters +=1 losses[num_iters] = loss_example_norm + loss_centroid_norm + loss_cross_term return centroids, assignments, losses[max(losses)] # END_YOUR_CODE
[ "natu.anand@gmail.com" ]
natu.anand@gmail.com
ee3997b39a5d30d9f9dd95a3f9021ff2a495f82f
19919c7c7f4ccfc4842e016c8ece818cd144de14
/Yaml/Read_Yaml.py
c8430249f60c60a6bf80499260dc9591569fc42c
[]
no_license
Cz1660/GitTestSetting_0225
b9e08e74dc0eb27aa39f204763140f0d772e5796
ba59ca5b16d1e9784a19b2c70d7ca27e923289f4
refs/heads/master
2020-04-25T02:52:49.869443
2019-02-25T08:08:21
2019-02-25T08:08:21
172,456,529
0
0
null
null
null
null
UTF-8
Python
false
false
290
py
import os,yaml class Read_Yaml: def __init__(self,file_name): self.path = os.getcwd() + os.sep + 'Yaml' + os.sep + file_name def read_yaml(self): with open(self.path,'r',encoding='utf-8') as f: self.yaml_data = yaml.load(f) return self.yaml_data
[ "you@example.com" ]
you@example.com
29508b8c62c4dfc7ece26c6ae621b64c84e7d5da
1368e2beda67052140a51fd53eb7a12941124320
/Python 3/1541.py
72fe04dada81de5994973cd36cbc76aecd070127
[]
no_license
matheuskolln/URI
ac540fd4ea18c9b3ba853492dc60157c165145cf
b9091ed1c5b75af79cb25827aff8aab99d2e4b65
refs/heads/master
2023-03-09T23:17:17.865447
2021-02-25T16:47:24
2021-02-25T16:47:24
272,043,082
0
0
null
null
null
null
UTF-8
Python
false
false
194
py
while True: n = [int(x) for x in input().split(' ')] if n[0] == 0: break a = n[0] * n[1] i = 0 while i * i * n[2] / 100 <= a: i += 1 print(i - 1)
[ "matheuzhenrik@gmail.com" ]
matheuzhenrik@gmail.com
de86bd936a9bc7afa59da85369c6a2c0b220a168
f8ffa8ff257266df3de9d20d95b291e393f88434
/Python from scratch/Zadania/zadania podczas zajęć/zajęcia11/zadanie01/zadanie01+a.py
ac892bb38f756545548af1328c3d3f7cef2f15c5
[]
no_license
janiszewskibartlomiej/Python_Code_Me_Gda
c0583c068ef08b6130398ddf93c3a3d1a843b487
7568de2a9acf80bab1429bb55bafd89daad9b729
refs/heads/master
2020-03-30T05:06:26.757033
2020-03-02T08:53:28
2020-03-02T08:53:28
150,781,356
0
0
null
null
null
null
UTF-8
Python
false
false
393
py
from datetime import datetime data_urodzenia = input('Wprowadź datę urodzin celebryty w formacie [RRRR-MM-DD]:') try: konwertowanie_daty = datetime.strptime(data_urodzenia, '%Y-%m-%d') except ValueError: print('Wprowadzono nie prawiłowe dane!') exit() teraz = datetime.now() wiek_celebryty = teraz - konwertowanie_daty print('Wiek celebryty to:', wiek_celebryty.days // 365)
[ "janiszewski.bartlomiej@gmail.com" ]
janiszewski.bartlomiej@gmail.com
288832b4e21767a5fe146fc0d0ad0218ce3730fc
be55991401aef504c42625c5201c8a9f14ca7c3b
/python全栈3期/面向对象/继承顺序.py
dcb0234f6de6831c86a781efdb3753c1b0f99ed8
[ "Apache-2.0" ]
permissive
BillionsRichard/pycharmWorkspace
adc1f8bb15b58ded489fc8dec0df397601823d2c
709e2681fc6d85ff52fb25717215a365f51073aa
refs/heads/master
2021-09-14T21:12:59.839963
2021-08-08T09:05:37
2021-08-08T09:05:37
143,610,481
0
0
null
null
null
null
UTF-8
Python
false
false
619
py
""" 广度优先: 新式类(Python3) F->D->B->E->C->A 深度优先: 经典类(python2,不继承自object类)F->D->B->A->E->C A | \ B C | \ D E \ / \/ F """ from pprint import pprint as pp class A: def test(self): print('A') class B(A): def test(self): print('B') pass class C(A): def test(self): print('C') class D(B): pass # def test(self): # print('D') class E(C): def test(self): print('E') pass class F(D, E): pass # def test(self): # print('F') f1 = F() f1.test() pp(F.__mro__)
[ "295292802@qq.com" ]
295292802@qq.com
f297dde3e24a29cede6a18efcb18439969ce8aba
7e0e22e31aafc7eecda9d62ae4329f8697e23d40
/scripts/average
90f6be281641d653f9fe748d36aef7067a7f810b
[ "MIT" ]
permissive
Sandy4321/cli_stats
feec6e6b234e40062f0fe5b6519fdca0fc93f31b
d8a75cf81904a0565c9de6839ee4711355e26b70
refs/heads/master
2023-02-10T11:06:46.602325
2021-01-01T22:50:31
2021-01-01T22:50:31
null
0
0
null
null
null
null
UTF-8
Python
false
false
476
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Compute the average of a number stream on stdin Author: Gertjan van den Burg License: See LICENSE file Copyright (c) 2020, G.J.J. van den Burg """ import sys def main(): total = 0.0 count = 0 for line in sys.stdin: if not line.strip(): continue total += float(line.strip()) count += 1 average = total / count print(average) if __name__ == "__main__": main()
[ "gertjanvandenburg@gmail.com" ]
gertjanvandenburg@gmail.com
942a6a475150a440d2d71c36555b3b9649d6eb26
ad0857eaba945c75e705594a53c40dbdd40467fe
/baekjoon/python/dial_5622.py
2f52057085043af2b8abff6075f383071902aa85
[ "MIT" ]
permissive
yskang/AlgorithmPractice
c9964d463fbd0d61edce5ba8b45767785b0b5e17
3efa96710e97c8740d6fef69e4afe7a23bfca05f
refs/heads/master
2023-05-25T13:51:11.165687
2023-05-19T07:42:56
2023-05-19T07:42:56
67,045,852
0
0
null
2021-06-20T02:42:27
2016-08-31T14:40:10
Python
UTF-8
Python
false
false
494
py
# https://www.acmicpc.net/problem/5622 def dial_time(digit_string): digit_dict = {"A": 2, "B": 2, "C": 2, "D": 3, "E": 3, "F": 3, "G": 4, "H": 4, "I": 4, "J": 5, "K": 5, "L": 5, "M": 6, "N": 6, "O": 6, "P": 7, "Q": 7, "R": 7, "S": 7, "T": 8, "U": 8, "V": 8, "W": 9, "X": 9, "Y": 9, "Z": 9} time = 0 for d in digit_string: time += (digit_dict[d] + 1) return time if __name__ == "__main__": print(dial_time(input()))
[ "yongsung.kang@gmail.com" ]
yongsung.kang@gmail.com
7519b3756f10f14a5efbed78d21cd03b01e3570b
0a85e9ecb51c89110794aeb399fc3ccc0bff8c43
/Udacity/1. Data Structures/2. Linked List/detecting_loops.py
7dde5625ea99184e444c23e219dd8ab70ca841bc
[]
no_license
jordan-carson/Data_Structures_Algos
6d246cd187e3c3e36763f1eedc535ae1b95c0b18
452bb766607963e5ab9e39a354a24ebb26ebaaf5
refs/heads/master
2020-12-02T23:19:11.315890
2020-09-15T01:23:29
2020-09-15T01:23:29
231,147,094
1
0
null
null
null
null
UTF-8
Python
false
false
1,569
py
class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self, init_list=None): self.head = None if init_list: for value in init_list: self.append(value) def append(self, value): if self.head is None: self.head = Node(value) return # Move to the tail (the last node) node = self.head while node.next: node = node.next node.next = Node(value) return def iscircular(linked_list): if linked_list.head is None: return False slow = linked_list.head fast = linked_list.head while slow and fast and fast.next: fast = fast.next.next slow = slow.next if fast == slow: return True return False if __name__ == '__main__': list_with_loop = LinkedList([2, -1, 3, 0, 5]) # Creating a loop where the last node points back to the second node loop_start = list_with_loop.head.next node = list_with_loop.head while node.next: node = node.next node.next = loop_start small_loop = LinkedList([0]) small_loop.head.next = small_loop.head print ("Pass" if iscircular(list_with_loop) else "Fail") print ("Pass" if not iscircular(LinkedList([-4, 7, 2, 5, -1])) else "Fail") print ("Pass" if not iscircular(LinkedList([1])) else "Fail") print ("Pass" if iscircular(small_loop) else "Fail") print ("Pass" if not iscircular(LinkedList([])) else "Fail")
[ "jordanlouiscarson@gmail.com" ]
jordanlouiscarson@gmail.com
35af21c694adef7b09cbc80926fda010c74caf6e
7a6aca7d300c0752f2a73730b743a1a7361e941b
/tensorflow_graphics/nn/metric/fscore.py
8bb696c3919b2925c77ede8d7b9ae9e1851fd458
[ "Apache-2.0" ]
permissive
tensorflow/graphics
ef0abe102398a58eb7c41b709393df3d0b0a2811
1b0203eb538f2b6a1013ec7736d0d548416f059a
refs/heads/master
2023-09-03T20:41:25.992578
2023-08-08T21:16:36
2023-08-08T21:17:31
164,626,274
2,920
413
Apache-2.0
2023-08-27T14:26:47
2019-01-08T10:39:44
Python
UTF-8
Python
false
false
3,437
py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://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 module implements the fscore metric.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from typing import Any, Callable import tensorflow as tf from tensorflow_graphics.nn.metric import precision as precision_module from tensorflow_graphics.nn.metric import recall as recall_module from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape from tensorflow_graphics.util import type_alias def evaluate(ground_truth: type_alias.TensorLike, prediction: type_alias.TensorLike, precision_function: Callable[..., Any] = precision_module.evaluate, recall_function: Callable[..., Any] = recall_module.evaluate, name: str = "fscore_evaluate") -> tf.Tensor: """Computes the fscore metric for the given ground truth and predicted labels. The fscore is calculated as 2 * (precision * recall) / (precision + recall) where the precision and recall are evaluated by the given function parameters. The precision and recall functions default to their definition for boolean labels (see https://en.wikipedia.org/wiki/Precision_and_recall for more details). Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: ground_truth: A tensor of shape `[A1, ..., An, N]`, where the last axis represents the ground truth values. prediction: A tensor of shape `[A1, ..., An, N]`, where the last axis represents the predicted values. precision_function: The function to use for evaluating the precision. Defaults to the precision evaluation for binary ground-truth and predictions. recall_function: The function to use for evaluating the recall. Defaults to the recall evaluation for binary ground-truth and prediction. name: A name for this op. Defaults to "fscore_evaluate". Returns: A tensor of shape `[A1, ..., An]` that stores the fscore metric for the given ground truth labels and predictions. Raises: ValueError: if the shape of `ground_truth`, `prediction` is not supported. """ with tf.name_scope(name): ground_truth = tf.convert_to_tensor(value=ground_truth) prediction = tf.convert_to_tensor(value=prediction) shape.compare_batch_dimensions( tensors=(ground_truth, prediction), tensor_names=("ground_truth", "prediction"), last_axes=-1, broadcast_compatible=True) recall = recall_function(ground_truth, prediction) precision = precision_function(ground_truth, prediction) return safe_ops.safe_signed_div(2 * precision * recall, precision + recall) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
[ "copybara-worker@google.com" ]
copybara-worker@google.com
b513f222fdaffe800eb13434b6c68a58cf123706
94becda0e99eb1bf23f2649d63a6a2af0f631e33
/brats/bak/loop_finetune_v100_bak.py
fc472ca5384a7149a43deaf323fcf73f85ea7cfd
[ "MIT" ]
permissive
guusgrimbergen/3DUnetCNN_BRATS
d560a878dfbe7dfe95ca5a37c8b066199300d276
1c4ad386b66c550770adc8c9e7371c1ce476db94
refs/heads/master
2022-01-08T13:37:05.253386
2019-06-17T13:10:59
2019-06-17T13:10:59
185,376,310
0
0
null
2019-05-07T10:07:33
2019-05-07T10:07:32
null
UTF-8
Python
false
false
3,151
py
from brats.config import config, config_unet, config_dict import datetime import logging import threading import subprocess import os import sys from subprocess import Popen, PIPE, STDOUT from unet3d.utils.path_utils import make_dir from unet3d.utils.path_utils import get_model_h5_filename from unet3d.utils.path_utils import get_filename_without_extension config.update(config_unet) # pp = pprint.PrettyPrinter(indent=4) # # pp.pprint(config) config.update(config_unet) def run(model_filename, out_file, cmd): print("="*120) print(">> processing:", cmd) print("log to:", out_file) print(cmd) os.system(cmd) task = "finetune" is_test = "0" model_list = list() cmd_list = list() out_file_list = list() for model_name in ["unet", "isensee"]: for is_denoise in config_dict["is_denoise"]: for is_normalize in config_dict["is_normalize"]: for is_hist_match in ["0", "1"]: for loss in ["minh", "weighted"]: patch_shape = "160-192-128" log_folder = "log" make_dir(log_folder) d = datetime.date.today() year_current = d.year month_current = '{:02d}'.format(d.month) date_current = '{:02d}'.format(d.day) model_filename = get_filename_without_extension(get_model_h5_filename( datatype="model", is_bias_correction="1", is_denoise=is_denoise, is_normalize=is_normalize, is_hist_match=is_hist_match, depth_unet=4, n_base_filters_unet=16, model_name=model_name, patch_shape=patch_shape, is_crf="0", is_test=is_test, loss=loss, model_dim=2)) out_file = "{}/{}{}{}_{}_out.log".format( log_folder, year_current, month_current, date_current, model_filename) cmd = "python brats/{}.py -t \"{}\" -o \"0\" -n \"{}\" -de \"{}\" -hi \"{}\" -ps \"{}\" -l \"{}\" -m \"{}\" -ba 1 -dim 3".format( task, is_test, is_normalize, is_denoise, is_hist_match, patch_shape, "minh", model_name ) model_list.append(model_filename) out_file_list.append(out_file) cmd_list.append(cmd) import random combined = list(zip(model_list, out_file_list, cmd_list)) random.shuffle(combined) model_list[:], out_file_list[:], cmd_list = zip(*combined) for i in range(len(model_list)): model_filename = model_list[i] out_file = out_file_list[i] cmd = cmd_list[i] run(model_filename, out_file, cmd)
[ "minhmanutd@gmail.com" ]
minhmanutd@gmail.com
a52b455dc705da8f9fc3724685f6ef38c3740ff4
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
/5pYkwf948KBQ3pNwz_13.py
f195abcf98ede33050c2a8f2b103f9ced9d8120e
[]
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
480
py
from collections import Counter ​ def most_common_words(text, n): words = ''.join([c if c.isalpha() else ' ' for c in text.lower()]).split() seq = {} idx = 0 for word in words: if word not in seq: idx += 1 seq[word] = idx C = Counter(words) L = [[k, v, seq[k]] for k, v in C.items()] L.sort(key=lambda x: (-x[1], x[2])) ans = {} for i in range(min(n, len(L))): ans[L[i][0]] = L[i][1] return ans
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
961e76ad1d6a22225b91b5f9e9b5a45cc59f4df6
f8095636248bac9e2b018ed3b06f36502edffb0b
/frontend_issuu_autotest_replica/tests_pro_account/TestQuickTourPRO.py
ede810b50de37975ec611870bca9add110124b14
[]
no_license
slashsorin/auto-fe-test
deb1c696767b1c31125970679aa8ce4364fa956a
266f3d7badb14c388edc63139bf659f60e09ac64
refs/heads/master
2016-08-04T10:22:18.123109
2013-11-22T09:16:57
2013-11-22T09:16:57
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,575
py
import sys, time, os #sys.path.append('/Users/Sorin/Issuu/new_eclipse_ws/frontend-issuu-autotest/autotest_framework/') sys.path.append('../autotest_framework') import SeleniumTestCase, make_platform_classes import SetTestStatus as sts import unittest, xmlrunner class TestQuickTourPRO(SeleniumTestCase.SeleniumTestCase): def test_quick_tour(self): try: sel = self.selenium sel.set_speed("500") sel.open("/signup/quicktour") sel.wait_for_page_to_load("60000") self.assertEqual("Issuu - Signup - A quick tour", sel.get_title()) self.failUnless(sel.is_element_present("xpath=//div[2]/div[4]/img")) self.failUnless(sel.is_element_present("link=issuu")) self.failUnless(sel.is_element_present("id=t3BodyTop")) self.failUnless(sel.is_element_present("xpath=//div[2]/div[1]/div")) self.failUnless(sel.is_element_present("xpath=//span[@class='system-blue-shade-fat-btn-text']/strong")) sel.click("id=loginLink") sel.wait_for_page_to_load("60000") sel.type("id=username", "PROaccount") sel.type("id=password", "autotest") sel.click("xpath=//span[@class='system-blue-shade-fat-btn-text']//strong[.='Log in']") sel.wait_for_page_to_load("60000") self.assertEqual("Issuu - Signup - A quick tour", sel.get_title()) self.failUnless(sel.is_element_present("xpath=//div[2]/div[4]/img")) self.failUnless(sel.is_element_present("link=issuu")) self.failUnless(sel.is_element_present("id=t3BodyTop")) self.failUnless(sel.is_element_present("xpath=//div[2]/div[1]/div")) self.failUnless(sel.is_element_present("xpath=//span[@class='system-blue-shade-fat-btn-text']/strong")) sel.click("link=Log out") sel.wait_for_page_to_load("60000") #print self.__class__.__name__ + " passed!" #sts.set_test_status(self.selenium.get_eval("selenium.sessionId"), passed=True) except AttributeError: pass #except: # catch *all* exceptions #if sys.exc_info()[1]: #sts.set_test_status(self.selenium.get_eval("selenium.sessionId"), passed=False) #print self.__class__.__name__ + " failed!" globals().update(make_platform_classes.make_platform_classes(TestQuickTourPRO)) if __name__ == '__main__': unittest.main(testRunner=xmlrunner.XMLTestRunner(output='../test_reports'))
[ "sorin.dimo@yahoo.com" ]
sorin.dimo@yahoo.com
e2553bf31614edf3ef91cdd52439d0a0721bc8d2
e3fd35a8443aaf2f293ae03a5f6c819046a4dd21
/leetcode-python/medium/_503_next_greater_element_2/test_solution.py
68da2b92260a0e9bd3dc14ea7131a1cb31787adc
[]
no_license
hieutran106/leetcode-ht
2223ea6bcd459c2cdbc33344c0ff69df7f8a3c7f
8332eb20e613f82cda2e326218154c7803a32403
refs/heads/main
2023-08-09T02:52:41.360360
2023-07-27T10:12:28
2023-07-27T10:12:28
234,890,448
0
0
null
null
null
null
UTF-8
Python
false
false
585
py
import unittest from .solution import Solution class MyTestCase(unittest.TestCase): def setUp(self) -> None: self.s = Solution() def test_case1(self): actual = self.s.nextGreaterElements([1, 2, 1]) self.assertEqual(actual, [2, -1, 2]) def test_case2(self): actual = self.s.nextGreaterElements([3, 1, 2, 4]) self.assertEqual(actual, [4, 2, 4, -1]) def test_case3(self): actual = self.s.nextGreaterElements([3, 5, 2, 1]) self.assertEqual(actual, [5, -1, 3, 3]) if __name__ == '__main__': unittest.main()
[ "hieutran106@gmail.com" ]
hieutran106@gmail.com
c42af3a2ce14d0a7a69408abef1650a90e836b3a
8afb5afd38548c631f6f9536846039ef6cb297b9
/MY_REPOS/INTERVIEW-PREP-COMPLETE/Practice/BSTFromArray/model_solution/model_solution.py
f9d67e0ad74527a0da094829f9bcf5cb690108cf
[ "MIT" ]
permissive
bgoonz/UsefulResourceRepo2.0
d87588ffd668bb498f7787b896cc7b20d83ce0ad
2cb4b45dd14a230aa0e800042e893f8dfb23beda
refs/heads/master
2023-03-17T01:22:05.254751
2022-08-11T03:18:22
2022-08-11T03:18:22
382,628,698
10
12
MIT
2022-10-10T14:13:54
2021-07-03T13:58:52
null
UTF-8
Python
false
false
2,162
py
import math def create_min_height_bst(sorted_array): left = 0 right = len(sorted_array) - 1 return rec_helper(sorted_array, left, right) def rec_helper(sorted_array, left, right): if left > right: return None midpoint = ((right - left) // 2) + left root = BinaryTreeNode(sorted_array[midpoint]) root.left = rec_helper(sorted_array, left, midpoint - 1) root.right = rec_helper(sorted_array, midpoint + 1, right) return root class BinaryTreeNode: def __init__(self, value): self.value = value self.left = None self.right = None # Helper function to validate that the created tree is a valid BST def is_BST(root, min_bound, max_bound): if root is None: return True if root.value < min_bound or root.value > max_bound: return False left = is_BST(root.left, min_bound, root.value - 1) right = is_BST(root.right, root.value + 1, max_bound) return left and right # Helper function to check the max height of a BST def find_bst_max_height(node): if node is None: return 0 return 1 + max(find_bst_max_height(node.left), find_bst_max_height(node.right)) # Helper function to validate that the given BST exhibits the min height def is_bst_min_height(root, N): bst_max_height = find_bst_max_height(root) should_equal = math.floor(math.log2(N)) + 1 return bst_max_height == should_equal # Helper function to count the number of nodes for a given BST def count_bst_nodes(root, count): if root is None: return count count_bst_nodes(root.left, count) count += 1 count_bst_nodes(root.right, count) # Some tests sorted_array = [1, 2, 3, 4, 5, 6, 7] bst = create_min_height_bst(sorted_array) print(is_BST(bst, float("-inf"), float("inf"))) # should print true print(is_bst_min_height(bst, len(sorted_array))) # should print true sorted_array = [4, 10, 11, 18, 42, 43, 47, 49, 55, 67, 79, 89, 90, 95, 98, 100] bst = create_min_height_bst(sorted_array) print(is_BST(bst, float("-inf"), float("inf"))) # should print true print(is_bst_min_height(bst, len(sorted_array))) # should print true
[ "bryan.guner@gmail.com" ]
bryan.guner@gmail.com
bdceae09f3f12e2c784454982314c598267c7550
d1d626e557cc3ec2068734c464afdde6d0b44a92
/bot/models.py
70d55805aa7993b986707e1145d34e9f2b759e43
[]
no_license
akhad97/Telegram-Bot
d279899f1cacebdb3317f2084047beaa4507c0fb
fd999c03b7b1abd2d433efcd67d9047430c66e4a
refs/heads/master
2023-07-02T06:53:41.697269
2021-08-03T17:41:07
2021-08-03T17:41:07
352,558,410
1
0
null
null
null
null
UTF-8
Python
false
false
1,104
py
from django.db import models class TelegramUser(models.Model): user_id = models.CharField(max_length=30) full_name = models.CharField(max_length=100) phone_number = models.CharField(max_length=15, null=True) resume = models.CharField(max_length=100, null=True) # resume = models.FileField(upload_to="resume/%Y/%m", null=True) class Meta: verbose_name = 'TelegramUser' verbose_name_plural = 'TelegramUsers' def __str__(self): return self.full_name class Vacancy(models.Model): name = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.name # class Language(models.Model): # vacancy = models.ForeignKey(Vacancy, on_delete=models.CASCADE) # name = models.CharField(max_length=50) # code = models.CharField(max_length=30) class Post(models.Model): user = models.ForeignKey(TelegramUser, on_delete=models.CASCADE, null = True) vacancy = models.ForeignKey(Vacancy, on_delete=models.CASCADE, null = True) def __str__(self): return self.user.full_name
[ "ahadjon.abdullaev1997@gmail.com" ]
ahadjon.abdullaev1997@gmail.com
3d0676ba2f791a63793876a7f9cac6d72829b2f7
f845225329fa9750c838bf511fed3beb48cc86af
/accounts/migrations/0024_auto_20190104_1910.py
548b1c2d5d7579453106f5fb740c98f2b35c2c4a
[]
no_license
Fabricourt/btre_project-
ac8c2b84cc8b7f4f5368a204dc23b378d488b356
13defd495ba309ac31550d22ad7d6306638f91eb
refs/heads/master
2020-04-15T11:03:05.980170
2019-01-08T11:16:56
2019-01-08T11:16:56
164,611,152
0
0
null
null
null
null
UTF-8
Python
false
false
413
py
# Generated by Django 2.1.4 on 2019-01-04 16:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0023_dashboard_title'), ] operations = [ migrations.AlterField( model_name='dashboard', name='title', field=models.CharField(blank=True, default=None, max_length=200), ), ]
[ "mfalme2030@gmail.com" ]
mfalme2030@gmail.com
1960f27aab4a6e04b44d42cae1957586f552c1e4
244ecfc2017a48c70b74556be8c188e7a4815848
/res/scripts/client/gui/battle_control/requests/__init__.py
cb82e19a0f4681639e117250b900737bead761e8
[]
no_license
webiumsk/WOT-0.9.12
c1e1259411ba1e6c7b02cd6408b731419d3174e5
5be5fd9186f335e7bae88c9761c378ff5fbf5351
refs/heads/master
2021-01-10T01:38:36.523788
2015-11-18T11:33:37
2015-11-18T11:33:37
46,414,438
1
0
null
null
null
null
WINDOWS-1250
Python
false
false
491
py
# 2015.11.18 11:52:01 Střední Evropa (běžný čas) # Embedded file name: scripts/client/gui/battle_control/requests/__init__.py from gui.battle_control.requests.AvatarRequestsController import AvatarRequestsController __all__ = ['AvatarRequestsController'] # okay decompyling c:\Users\PC\wotsources\files\originals\res\scripts\client\gui\battle_control\requests\__init__.pyc # decompiled 1 files: 1 okay, 0 failed, 0 verify failed # 2015.11.18 11:52:01 Střední Evropa (běžný čas)
[ "info@webium.sk" ]
info@webium.sk