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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
29040bbe393c5645cee310429de8117d60756676
|
19b82e3a7610696a70d2d3fac70cf5425e61853d
|
/python_learning_liaoxuefeng/function_arguments.py
|
432646b83e51e0d5ccf25a6b96f4f5ece8a3fc25
|
[] |
no_license
|
xieyipeng/python
|
9ef5c3e3865e78aa4948c7a89aa7d2c6713122c6
|
1f4e23369e76fc0739d4c2213b6470bba9fa288c
|
refs/heads/master
| 2021-04-15T13:09:30.338025
| 2020-03-11T03:36:03
| 2020-03-11T03:36:03
| 126,497,745
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,047
|
py
|
# 函数参数:
# 位置参数:
# def power(x):
# return x * x
# print(power(5))
def power(x, n=2): # 上面的power函数就没用了,修改为带有默认参数的函数
s = 1
while n > 0:
n = n - 1
s = s * x
return s
print(power(5, 4))
# 默认参数:
print(power(5)) # 必选参数在前,默认参数在后
def enroll(name, gender, age=6, city='beijing'):
print('name:', name)
print('gender:', gender)
print('age:', age)
print('city:', city)
enroll('Sarach', 'F')
enroll('Sarach', 'F', city='Tianjin') # 默认参数的调用
# def add_end(L=[]): # 默认参数的坑
# L.append('end')
# return L
#
#
# print(add_end())
# print(add_end())
# print(add_end()) # 所以默认参数的定义必须是只想不可变对象
def add_end(L=None): # 修改的
if L is None:
L = []
L.append('end')
return L
print(add_end())
print(add_end())
print(add_end())
# 可变参数:参数个数可变
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
print(calc(1, 2, 3, 4))
nums = [1, 2, 3]
print(calc(*nums))
# 关键字参数:扩展函数的功能
# def person(name, age, **kw): # 命名关键字参数:
# if 'city' in kw:
# pass
# if 'job' in kw:
# pass
# print('name:', name, 'age:', age, 'other:', kw)
#
#
# print(person('Michael', 30))
# print(person('Bob', 35, city='Beijing')) # 可以组装一个dict,person('Jack',24,**extra)
# 命名关键字参数:
# def person(name, age, *, city, job): # 命名关键字参数:在*之后的参数都是命名关键字参数
# print(name, age, city, job)
#
#
# print(person('Jack', 24, city='Beijing', job='English')) # 参数必须传入参数名
def person(name, age, *, city='Beijing', job): # 有默认参数
print(name, age, city, job)
print(person('Jack', 24, job='English'))
# 参数组合-顺序:必选参数->默认参数->可变参数->命名参数/命名关键字参数->关键字参数
|
[
"3239202719@qq.com"
] |
3239202719@qq.com
|
d0011a7ba2c397fd29dfb45dc2ba6c8850c56dfa
|
fd994f57661fc7960a2a47cb70283db0a4f0145f
|
/lampost/gameops/display.py
|
dded84469844a7faca54b223e24a586173763318
|
[
"MIT"
] |
permissive
|
NancyR/Lampost-Mud
|
24d6ad979e99b27dd05546646694f1727af73bc1
|
7d313c34af0eadb2707242ca351013c97c720f51
|
refs/heads/master
| 2021-01-14T12:57:32.719005
| 2013-05-05T22:14:37
| 2013-05-05T22:14:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 658
|
py
|
DEFAULT_COLOR = 'default'
SYSTEM_COLOR = 'system'
ROOM_TITLE_COLOR = 'room_title'
ROOM_COLOR = 'room'
EXIT_COLOR = 'exit'
TELL_FROM_COLOR = 'tell_from'
TELL_TO_COLOR = 'tell_to'
SAY_COLOR = 'say'
COLOR_DATA = {DEFAULT_COLOR: ("Default", 0x00000),
SYSTEM_COLOR: ("System messages", 0x002288),
ROOM_TITLE_COLOR: ("Room titles", 0x6b306b),
ROOM_COLOR: ("Rooms", 0xAD419A),
EXIT_COLOR: ("Exit descriptions", 0x808000),
TELL_FROM_COLOR: ("Tells from other players", 0x00a2e8),
TELL_TO_COLOR: ("Tells to other players", 0x0033f8),
SAY_COLOR: ("Say", 0xe15a00)}
|
[
"genzgd@gmail.com"
] |
genzgd@gmail.com
|
987cbeb106b713ef40e6d165b790ddb7ead12987
|
5327317139867617bf9faff600b07e9404d68126
|
/data_generate_single.py
|
853f78603a9082b74101b86b581f3a9b27753c9b
|
[] |
no_license
|
Doreenruirui/BCI
|
9091b9b4ceb021387d199a90ed001c9f8258761a
|
a8c5e7e3c0ed9cbef16ddc0c5b534b210f32d400
|
refs/heads/master
| 2021-07-14T07:19:07.715054
| 2018-12-04T10:54:52
| 2018-12-04T10:54:52
| 131,056,144
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,971
|
py
|
import random
from os.path import join as pjoin
from data_simulate import *
import datetime
def tokenize(string):
return [int(s) for s in string.split()]
def load_vocabulary(path_data):
vocab = {}
rev_vocab = {}
line_id = 0
with open(pjoin(path_data, 'vocab')) as f_in:
for line in f_in:
word = line.strip('\n')
vocab[word] = line_id
rev_vocab[line_id] = word
line_id += 1
return vocab, rev_vocab
def refill(batches, fx, batch_size, start=0, end=-1, max_seq_len=300, sort_and_shuffle=True):
line_pairs = []
linex = fx.readline()
line_id = 0
while linex:
if line_id >= start:
newline = linex.strip()
tokens = tokenize(newline)
if len(tokens) >= 1:
tok_x = [char2id['<sos>']] + tokens[:max_seq_len][:-1]
tok_y = tokens[:max_seq_len]
line_pairs.append((tok_x, tok_y))
linex = fx.readline()
line_id += 1
if line_id == end:
break
if sort_and_shuffle:
random.shuffle(line_pairs)
line_pairs = sorted(line_pairs, key=lambda e:len(e[0]))
for batch_start in range(0, len(line_pairs), batch_size):
x_batch = [ele[0] for ele in line_pairs[batch_start:batch_start + batch_size]]
y_batch = [ele[1] for ele in line_pairs[batch_start:batch_start + batch_size]]
batches.append((x_batch, y_batch))
if sort_and_shuffle:
random.shuffle(batches)
return
def refill_noisy(batches, fx, fy, batch_size, start=0, end=-1, max_seq_len=300, sort_and_shuffle=True):
line_pairs = []
linex = fx.readline()
liney = fy.readline()
line_id = 0
while linex:
if line_id >= start:
newline_x = linex.strip()
newline_y = liney.strip()
tokens_x = tokenize(newline_x)
tokens_y = tokenize(newline_y)
if len(tokens_x) >= 1:
tok_x = [char2id['<sos>']] + tokens_x[:max_seq_len][:-1]
tok_y = tokens_y[:max_seq_len]
line_pairs.append((tok_x, tok_y))
linex = fx.readline()
liney = fy.readline()
line_id += 1
if line_id == end:
break
if sort_and_shuffle:
random.shuffle(line_pairs)
line_pairs = sorted(line_pairs, key=lambda e:len(e[0]))
for batch_start in range(0, len(line_pairs), batch_size):
x_batch = [ele[0] for ele in line_pairs[batch_start:batch_start + batch_size]]
y_batch = [ele[1] for ele in line_pairs[batch_start:batch_start + batch_size]]
batches.append((x_batch, y_batch))
if sort_and_shuffle:
random.shuffle(batches)
return
def padded(tokens, pad_v=char2id['<pad>']):
len_x = list(map(lambda x: len(x), tokens))
maxlen = max(len_x)
return list(map(lambda token_list: token_list + [pad_v] * (maxlen - len(token_list)), tokens))
def load_data(batches, file_data, dev, batch_size=128, max_seq_len=300,
prob_high=1.0, start=0, end=-1, sort_and_shuffle=False):
if prob_high == 1.0:
fx = open(pjoin(file_data, '0.0', dev + '.ids'))
refill(batches, fx, batch_size, max_seq_len=max_seq_len,
sort_and_shuffle=sort_and_shuffle, start=start, end=end)
else:
fy = open(pjoin(file_data, '0.0', dev + '.ids'))
fx = open(pjoin(file_data, '%.1f' % (1 - prob_high), dev + '.ids'))
refill_noisy(batches, fx, fy, batch_size, max_seq_len=max_seq_len,
sort_and_shuffle=sort_and_shuffle, start=start, end=end)
fy.close()
fx.close()
def iter_data(batch):
x_tokens, y_tokens = batch
x_pad = padded(x_tokens, 0)
y_pad = padded(y_tokens, 0)
source_tokens = np.transpose(np.array(x_pad), (1, 0))
source_mask = (source_tokens > 0).astype(np.int32)
target_tokens = np.array(y_pad).T
return (source_tokens, source_mask, target_tokens)
|
[
"ruiruidong1989@gmail.com"
] |
ruiruidong1989@gmail.com
|
2387e28c6307a5777130aedd6c83a0115cb3b4e6
|
0e7cdded06b219e20382edc8b855e4902c16bd1b
|
/task/download.py
|
dcacda001148129c45fb8111d59eebe14cc6e073
|
[
"MIT"
] |
permissive
|
cpausmit/FiBS
|
71828b9fce4025a548bbeb8647ecfe5c37719f41
|
2a49bb3bea53201f1933dcf5a8d43e4774bcf9b8
|
refs/heads/master
| 2022-09-13T06:43:53.736788
| 2022-08-30T21:43:38
| 2022-08-30T21:43:38
| 55,325,041
| 0
| 1
|
MIT
| 2022-08-30T21:43:39
| 2016-04-03T01:57:53
|
Python
|
UTF-8
|
Python
| false
| false
| 5,111
|
py
|
#!/usr/bin/env python
#---------------------------------------------------------------------------------------------------
# Download exactly one file from a given xrootd location to another xrootd location.
#
# Ch.Paus (Mar 25, 2021)
#---------------------------------------------------------------------------------------------------
import os,sys,re,socket,datetime,time
OVERWRITE = True
# define source and target
SOURCE_SERVER = "t3serv017.mit.edu"
TARGET_SERVER = "xrootd18.cmsaf.mit.edu"
#---
SOURCE = "/data/submit/cms"
#SOURCE = "root://%s/"%(SOURCE_SERVER)
TARGET = "root://%s/"%(TARGET_SERVER)
#---------------------------------------------------------------------------------------------------
# H E L P E R S
#---------------------------------------------------------------------------------------------------
def showSetup(status):
if status == 'start':
print("\n=-=-=-= Show who and where we are =-=-=-=\n")
print(" Script: %s"%(os.path.basename(__file__)))
print(" Arguments: %s"%(" ".join(sys.argv[1:])))
print(" ")
print(" user executing: " + os.getenv('USER','unknown user'))
print(" running on : %s"%(socket.gethostname()))
print(" running in : %s"%(os.getcwd()))
print(" start time : %s"%(str(datetime.datetime.now())))
elif status == 'end':
print(" end time : %s"%(str(datetime.datetime.now())))
else:
print(" now time : %s (%s)"%(str(datetime.datetime.now()),str(status)))
print(" ")
return
def exeCmd(cmd,debug=0):
# execute a given command and show what is going on
rc = 0
if debug>1:
print(' =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=')
if debug>0:
print(' =Execute: %s'%(cmd))
rc = os.system(cmd) ##print(' !! DISABLED EXECUTION !! ')
if debug>1:
print(' =E=N=D=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n')
return rc
def extractLfn(fullFile,debug=0):
# extract the lfn rom the given file name
if debug>1:
print(" File: %s"%(fullFile))
lfn = fullFile[fullFile.index('/store'):]
#lfn = lfn.replace("wangz","paus") # for files from Qier
return lfn
def downloadFile(file_xrootd,lfn,debug=0):
# execute the file download
# peer-to-peer copy fails for now with redirector limit reached?!
#cmd = "xrdcp -T first %s%s %s%s"%(SOURCE,lfn,TARGET,lfn)
cmd = "xrdcp --path %s%s %s%s"%(SOURCE,lfn,TARGET,lfn)
print("CMD: %s"%(cmd))
rc = exeCmd(cmd,debug)
if rc == 0:
print(" download worked (%s)."%(lfn))
else:
print(" download FAILED with %d (%s)."%(rc,lfn))
return rc
def removeRemainder(lfn,debug=0):
# remove remainder from failed download
cmd = "xrdfs %s rm %s"%(TARGET_SERVER,lfn)
# cmd = "rm %s%s >& /dev/null"%(TARGET,lfn)
rc = exeCmd(cmd,debug)
if rc == 0:
print(" removed remainder: %s%s."%(TARGET,lfn))
else:
print(" removing remainder FAILED (rc=%s): %s."%(rc,lfn))
return rc
def existFile(lfn,debug=0):
# check if file exists already
if OVERWRITE: # force overwrite
return 1
cmd = "xrdfs %s ls %s >& /dev/null"%(TARGET_SERVER,lfn)
# cmd = "ls -l %s%s >& /dev/null"%(TARGET,lfn)
rc = exeCmd(cmd,debug)
if rc == 0:
print(" file listed successfully: %s."%(lfn))
else:
print(" file listing FAILED (rc=%s) so we need to download: %s."%(rc,lfn))
dir = "/".join(lfn.split("/")[:-1])
print("DIR: %s%s"%(TARGET,dir))
cmd = "ls -l %s%s >& /dev/null"%(TARGET,dir)
tmprc = exeCmd(cmd,debug)
if tmprc == 0:
print(" directory exists: %s."%(lfn))
else:
cmd = "mkdir -p %s%s >& /dev/null"%(TARGET,dir)
tmprc = exeCmd(cmd,debug)
print(" directory created (RC=%d): %s."%(int(tmprc),lfn))
return rc
#---------------------------------------------------------------------------------------------------
# M A I N
#---------------------------------------------------------------------------------------------------
debug = 2
# make announcement
showSetup('start')
# make sure we have at least one parameter
if len(sys.argv)<2:
print('\n ERROR - Missing file name as parameter.\n')
showExit(1)
# read command line parameters
fullFile = " ".join(sys.argv[1:])
# make sure to trim the input file if needed (want to go back to lfn = /store/...)
lfn = extractLfn(fullFile,debug)
# show the certificate
exeCmd("voms-proxy-init --valid 168:00 -voms cms",debug)
exeCmd("voms-proxy-info -all",debug)
# does the file exist already?
rc = existFile(lfn,debug)
if rc == 0:
print("\n Our work is done, file exists already.\nEXIT\n")
showSetup(rc)
sys.exit(rc)
# download the file to local
rc = downloadFile(fullFile,lfn,debug)
if rc != 0:
print("\n File download failed. EXIT!\n Cleanup potential remainders.")
removeRemainder(lfn,debug)
showSetup(rc)
sys.exit(rc)
# make announcement
showSetup('end')
sys.exit(0)
|
[
"paus@mit.edu"
] |
paus@mit.edu
|
7295512a52631127cac7a9bac633c1f3e19e03f8
|
6e423cddd8698bc662bcc3208eb7a8fdb2eb0d72
|
/mlcomp/parallelm/model/constants.py
|
5e8296f20d50f1acfb3eaec9e0c114645176ed6f
|
[
"Apache-2.0"
] |
permissive
|
theromis/mlpiper
|
7d435343af7b739767f662b97a988c2ccc7665ed
|
738356ce6d5e691a5d813acafa3f0ff730e76136
|
refs/heads/master
| 2020-05-05T04:44:00.494105
| 2019-04-03T19:53:01
| 2019-04-03T22:02:53
| 179,722,926
| 0
| 0
|
Apache-2.0
| 2019-04-05T17:06:02
| 2019-04-05T17:06:01
| null |
UTF-8
|
Python
| false
| false
| 394
|
py
|
# Provides information about the model file path that should be fetched and used by the pipeline
METADATA_FILENAME = 'metadata.json'
# A helper file that is used to signal the uWSGI workers about new models
SYNC_FILENAME = 'sync'
# A dedicated extension that is used to avoid model file paths collisions between the
# pipeline model fetch and the agent
PIPELINE_MODEL_EXT = '.last_approved'
|
[
"lior.amar@parallelmachines.com"
] |
lior.amar@parallelmachines.com
|
8fa5731878c882842bf2a145cc3010af0d34ccae
|
fe9e19372790f3f79f134b008852c028d497c7fb
|
/blog/migrations/0001_initial.py
|
55c531ce6369adcbed4ab5de943b193fff831878
|
[] |
no_license
|
Mohamed-awad/django_blog
|
9f73cbb598c4e71670f7546150fa257d494d3041
|
40b198b53dd023ee63112189863e49f2e28d19dc
|
refs/heads/master
| 2021-05-03T16:32:04.262701
| 2018-03-24T16:06:58
| 2018-03-24T16:06:58
| 120,438,080
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,707
|
py
|
# Generated by Django 2.0.1 on 2018-02-06 07:26
import datetime
from django.conf import settings
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Comment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('author', models.CharField(max_length=100)),
('text', models.TextField()),
('create_date', models.DateTimeField(default=datetime.datetime(2018, 2, 6, 7, 26, 23, 225451, tzinfo=utc))),
('approved_comment', models.BooleanField(default=False)),
],
),
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
('text', models.TextField()),
('create_date', models.DateTimeField(default=datetime.datetime(2018, 2, 6, 7, 26, 23, 224974, tzinfo=utc))),
('published_date', models.DateTimeField(default=True, null=True)),
('author', models.ForeignKey(on_delete=True, to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddField(
model_name='comment',
name='post',
field=models.ForeignKey(on_delete=True, related_name='comments', to='blog.Post'),
),
]
|
[
"awadmohamed233@gmail.com"
] |
awadmohamed233@gmail.com
|
6d58b6cfcfe5f6bdddc5b38f1fa6e583aebad983
|
f281d0d6431c1b45c6e5ebfff5856c374af4b130
|
/DAY001~099/DAY87-BOJ2217-로프/smlee.py
|
5bab04654a25b085dadf331133df46f33e52a89b
|
[] |
no_license
|
tachyon83/code-rhino
|
ec802dc91dce20980fac401b26165a487494adb4
|
b1af000f5798cd12ecdab36aeb9c7a36f91c1101
|
refs/heads/master
| 2022-08-13T09:10:16.369287
| 2022-07-30T11:27:34
| 2022-07-30T11:27:34
| 292,142,812
| 5
| 6
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 170
|
py
|
n = int(input())
arr = [int(input()) for _ in range(n)]
arr.sort(reverse=True)
result=[]
for i in range(len(arr)):
result.append(arr[i] * (i+1))
print(max(result))
|
[
"noreply@github.com"
] |
tachyon83.noreply@github.com
|
77f992b5ee77c422b6c3b1c8bd56c87d95f7d6c4
|
c6053ad14e9a9161128ab43ced5604d801ba616d
|
/Lemon/Python_Base/api_auto_4/__init__.py
|
591e89f6ae29685aa744ea28b9493c1bb8296095
|
[] |
no_license
|
HesterXu/Home
|
0f6bdace39f15e8be26031f88248f2febf33954d
|
ef8fa0becb687b7b6f73a7167bdde562b8c539be
|
refs/heads/master
| 2020-04-04T00:56:35.183580
| 2018-12-25T02:48:51
| 2018-12-25T02:49:05
| 155,662,403
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 296
|
py
|
# -*- coding: utf-8 -*-
# @Time : 2018/12/10/19:49
# @Author : Hester Xu
# Email : xuruizhu@yeah.net
# @File : __init__.py.py
# @Software : PyCharm
"""
代码--放在package里 数据--放在文件夹里
1.package:
common
2.directory:
datas
test_result: log report
configs
"""
|
[
"xuruizhu@yeah.net"
] |
xuruizhu@yeah.net
|
7e1f7eb16d48fbf502259148e251576c19aa8f53
|
d35813d7e9ef6c606591ae1eb4ed3b2d5156633b
|
/python-daily/list_extend.py
|
3e1ee4598d757d52be70a3c5d44b0daa750289cc
|
[] |
no_license
|
JeremiahZhang/gopython
|
eb6f598c16c8a00c86245e6526261b1b2d1321f1
|
ef13f16d2330849b19ec5daa9f239bf1558fa78c
|
refs/heads/master
| 2022-08-13T22:38:12.416404
| 2022-05-16T02:32:04
| 2022-05-16T02:32:04
| 42,239,933
| 13
| 6
| null | 2022-08-01T08:13:54
| 2015-09-10T11:14:43
|
Jupyter Notebook
|
UTF-8
|
Python
| false
| false
| 128
|
py
|
animals = ['Python', 'Viper', 'Cobra']
def add_snake(snake_type):
animals.extend(snake_type)
print(animals)
add_snake('Boa')
|
[
"zhangleisuda@gmail.com"
] |
zhangleisuda@gmail.com
|
6fc6c184d8c93782a2b1661cc99dcafccc772bb1
|
a89dbc6d2d9c44b7c4a19f297b0885e8127a3cdb
|
/tests/test_xvnc.py
|
cf04b338505f7b2d82a17bbbe6d3134bc5ccefd4
|
[
"BSD-2-Clause"
] |
permissive
|
ponty/PyVirtualDisplay
|
79a6e53eaaa146665409aaa144a67faf12c38d72
|
8368c4138a09efb5bba45cc7c3ff95f602d21881
|
refs/heads/master
| 2023-07-05T00:33:21.167789
| 2023-03-12T07:54:41
| 2023-03-12T07:54:41
| 1,354,580
| 554
| 82
|
BSD-2-Clause
| 2021-04-02T20:56:40
| 2011-02-11T10:41:09
|
Python
|
UTF-8
|
Python
| false
| false
| 1,917
|
py
|
import tempfile
from pathlib import Path
from tutil import has_xvnc, rfbport, worker
from vncdotool import api
from pyvirtualdisplay import Display
from pyvirtualdisplay.xvnc import XvncDisplay
if has_xvnc():
def test_xvnc():
with tempfile.TemporaryDirectory() as temp_dir:
vnc_png = Path(temp_dir) / "vnc.png"
password = "123456"
passwd_file = Path(temp_dir) / "pwd.txt"
vncpasswd_generated = b"\x49\x40\x15\xf9\xa3\x5e\x8b\x22"
passwd_file.write_bytes(vncpasswd_generated)
if worker() == 0:
with Display(backend="xvnc"):
with api.connect("localhost:0") as client:
client.timeout = 1
client.captureScreen(vnc_png)
with XvncDisplay():
with api.connect("localhost:0") as client:
client.timeout = 1
client.captureScreen(vnc_png)
sconnect = "localhost:%s" % (rfbport() - 5900)
with Display(backend="xvnc", rfbport=rfbport()):
with api.connect(sconnect) as client:
client.timeout = 1
client.captureScreen(vnc_png)
with XvncDisplay(rfbport=rfbport()):
with api.connect(sconnect) as client:
client.timeout = 1
client.captureScreen(vnc_png)
with Display(backend="xvnc", rfbport=rfbport(), rfbauth=passwd_file):
with api.connect(sconnect, password=password) as client:
client.timeout = 1
client.captureScreen(vnc_png)
with XvncDisplay(rfbport=rfbport(), rfbauth=passwd_file):
with api.connect(sconnect, password=password) as client:
client.timeout = 1
client.captureScreen(vnc_png)
|
[
"ponty@home"
] |
ponty@home
|
22ee0ba721abb697347257b1a5d2542edcf4c1e9
|
797e83cd492c22c8b7e456b76ae9efb45e102e30
|
/chapter3_ScriptExectionContext/redirect.py
|
def595d1368afa8dfb1bf48215eba992e256569d
|
[] |
no_license
|
skyaiolos/ProgrammingPython4th
|
013e2c831a6e7836826369d55aa9435fe91c2026
|
a6a98077440f5818fb0bd430a8f9a5d8bf0ce6d7
|
refs/heads/master
| 2021-01-23T11:20:38.292728
| 2017-07-20T03:22:59
| 2017-07-20T03:22:59
| 93,130,254
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,316
|
py
|
"""
file-like objects that save standard output text in a string and provide
standard input text from a string; redirect runs a passed-in function
with its output and input streams reset to these file-like class objects;
"""
import sys # get built-in modules
class Output: # simulated output file
def __init__(self):
self.text = '' # empty string when created
def write(self, string): # add a string of bytes
self.text += string
def writelines(self, lines): # add each line in a list
for line in lines: self.write(line)
class Input: # simulated input file
def __init__(self, input=''): # default argument
self.text = input # save string when created
def read(self, size=None): # optional argument
if size == None: # read N bytes, or all
res, self.text = self.text, ''
else:
res, self.text = self.text[:size], self.text[size:]
return res
def readline(self):
eoln = self.text.find('\n') # find offset of next eoln
if eoln == -1: # slice off through eoln
res, self.text = self.text, ''
else:
res, self.text = self.text[:eoln+1], self.text[eoln+1:]
return res
def redirect(function, pargs, kargs, input): # redirect stdin/out
savestreams = sys.stdin, sys.stdout # run a function object
sys.stdin = Input(input) # return stdout text
sys.stdout = Output()
try:
result = function(*pargs, **kargs) # run function with args
output = sys.stdout.text
finally:
sys.stdin, sys.stdout = savestreams # restore if exc or not
return (result, output) # return result if no exc
# Output
# Provides the write method interface (a.k.a. protocol) expected of output files but
# saves all output in an in-memory string as it is written.
# Input
# Provides the interface expected of input files, but provides input on demand from
# an in-memory string passed in at object construction time.
|
[
"skyaiolos@aliyun.com"
] |
skyaiolos@aliyun.com
|
dbbeccc73dc6022533c406f9b0cb7b945674c7d3
|
21e177a4d828f4e0a003e9424c4952dbc0b47d29
|
/testlints/test_lint_subject_locality_name_max_length.py
|
43b55f38acbf73df4543e4b07ebccf054dd11684
|
[] |
no_license
|
846468230/Plint
|
1071277a55144bb3185347a58dd9787562fc0538
|
c7e7ca27e5d04bbaa4e7ad71d8e86ec5c9388987
|
refs/heads/master
| 2020-05-15T12:11:22.358000
| 2019-04-19T11:46:05
| 2019-04-19T11:46:05
| 182,255,941
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,257
|
py
|
import sys
sys.path.append("..")
from lints import base
from lints import lint_subject_locality_name_max_length
import unittest
import os
from cryptography import x509
from cryptography.hazmat.backends import default_backend
class TestSubjectLocalityNameLengthGood(unittest.TestCase):
'''test lint_subject_locality_name_max_length.py'''
def test_SubjectLocalityNameLengthGood(self):
certPath ='..\\testCerts\\subjectLocalityNameLengthGood.pem'
lint_subject_locality_name_max_length.init()
with open(certPath, "rb") as f:
cert = x509.load_pem_x509_certificate(f.read(), default_backend())
out = base.Lints["e_subject_locality_name_max_length"].Execute(cert)
self.assertEqual(base.LintStatus.Pass,out.Status)
def test_SubjectLocalityNameLong(self):
certPath ='..\\testCerts\\subjectLocalityNameLong.pem'
lint_subject_locality_name_max_length.init()
with open(certPath, "rb") as f:
cert = x509.load_pem_x509_certificate(f.read(), default_backend())
out = base.Lints["e_subject_locality_name_max_length"].Execute(cert)
self.assertEqual(base.LintStatus.Error,out.Status)
if __name__=="__main__":
unittest.main(verbosity=2)
|
[
"846468230@qq.com"
] |
846468230@qq.com
|
3e6b65965404c9a88926cd2f245c924f11869101
|
56f5b2ea36a2258b8ca21e2a3af9a5c7a9df3c6e
|
/CMGTools/H2TauTau/prod/25aug_corrMC/up/mc/VBF_HToTauTau_M-120_8TeV-powheg-pythia6/Summer12_DR53X-PU_S10_START53_V7A-v1/AODSIM/V5_B/PAT_CMG_V5_16_0_1377467448/HTT_24Jul_newTES_manzoni_Up_Jobs/Job_66/run_cfg.py
|
09d33bfcf02f1d13dc3723c60dd660d9b368a10a
|
[] |
no_license
|
rmanzoni/HTT
|
18e6b583f04c0a6ca10142d9da3dd4c850cddabc
|
a03b227073b2d4d8a2abe95367c014694588bf98
|
refs/heads/master
| 2016-09-06T05:55:52.602604
| 2014-02-20T16:35:34
| 2014-02-20T16:35:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,483
|
py
|
import FWCore.ParameterSet.Config as cms
import os,sys
sys.path.append('/afs/cern.ch/user/m/manzoni/summer13/CMGTools/CMSSW_5_3_9/src/CMGTools/H2TauTau/prod/25aug_corrMC/up/mc/VBF_HToTauTau_M-120_8TeV-powheg-pythia6/Summer12_DR53X-PU_S10_START53_V7A-v1/AODSIM/V5_B/PAT_CMG_V5_16_0_1377467448/HTT_24Jul_newTES_manzoni_Up_Jobs')
from base_cfg import *
process.source = cms.Source("PoolSource",
noEventSort = cms.untracked.bool(True),
inputCommands = cms.untracked.vstring('keep *',
'drop cmgStructuredPFJets_cmgStructuredPFJetSel__PAT'),
duplicateCheckMode = cms.untracked.string('noDuplicateCheck'),
fileNames = cms.untracked.vstring('/store/cmst3/user/cmgtools/CMG/VBF_HToTauTau_M-120_8TeV-powheg-pythia6/Summer12_DR53X-PU_S10_START53_V7A-v1/AODSIM/V5_B/PAT_CMG_V5_16_0/cmgTuple_392.root',
'/store/cmst3/user/cmgtools/CMG/VBF_HToTauTau_M-120_8TeV-powheg-pythia6/Summer12_DR53X-PU_S10_START53_V7A-v1/AODSIM/V5_B/PAT_CMG_V5_16_0/cmgTuple_393.root',
'/store/cmst3/user/cmgtools/CMG/VBF_HToTauTau_M-120_8TeV-powheg-pythia6/Summer12_DR53X-PU_S10_START53_V7A-v1/AODSIM/V5_B/PAT_CMG_V5_16_0/cmgTuple_394.root',
'/store/cmst3/user/cmgtools/CMG/VBF_HToTauTau_M-120_8TeV-powheg-pythia6/Summer12_DR53X-PU_S10_START53_V7A-v1/AODSIM/V5_B/PAT_CMG_V5_16_0/cmgTuple_395.root',
'/store/cmst3/user/cmgtools/CMG/VBF_HToTauTau_M-120_8TeV-powheg-pythia6/Summer12_DR53X-PU_S10_START53_V7A-v1/AODSIM/V5_B/PAT_CMG_V5_16_0/cmgTuple_396.root')
)
|
[
"riccardo.manzoni@cern.ch"
] |
riccardo.manzoni@cern.ch
|
29a9940ae1963530c38cc81ee7feb8f6627c38e0
|
f1d49f5155d63172e58547e706a4f11a2dcd2cbc
|
/lib/crypto/receipt.py
|
5b563ba67b2fd1aee5396523b8a817bfa46ca171
|
[] |
no_license
|
rtnpro/zamboni
|
a831f308c994025b38616fcd039ceb856d2cafaf
|
6a8cb8b5e81ed0ad72200a1586af54d9c3865d17
|
refs/heads/master
| 2021-01-16T19:09:07.937849
| 2012-11-06T17:19:49
| 2012-11-08T18:49:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,163
|
py
|
import json
import urllib2
from django.conf import settings
from django_statsd.clients import statsd
import commonware.log
import jwt
log = commonware.log.getLogger('z.crypto')
class SigningError(Exception):
pass
def sign(receipt):
"""
Send the receipt to the signing service.
This could possibly be made async via celery.
"""
destination = settings.SIGNING_SERVER
# If no destination is set. Just ignore this request.
if not destination:
return
destination += '/1.0/sign'
timeout = settings.SIGNING_SERVER_TIMEOUT
receipt_json = json.dumps(receipt)
log.info('Calling service: %s' % destination)
log.info('Receipt contents: %s' % receipt_json)
headers = {'Content-Type': 'application/json'}
data = receipt if isinstance(receipt, basestring) else receipt_json
request = urllib2.Request(destination, data, headers)
try:
with statsd.timer('services.sign.receipt'):
response = urllib2.urlopen(request, timeout=timeout)
except urllib2.HTTPError, error:
# Will occur when a 3xx or greater code is returned
log.error('Posting to signing failed: %s, %s'
% (error.code, error.read().strip()))
raise SigningError
except:
# Will occur when some other error occurs.
log.error('Posting to signing failed', exc_info=True)
raise SigningError
if response.getcode() != 200:
log.error('Posting to signing failed: %s'
% (response.getcode()))
raise SigningError
return json.loads(response.read())['receipt']
def decode(receipt):
"""
Decode and verify that the receipt is sound from a crypto point of view.
Will raise errors if the receipt is not valid, returns receipt contents
if it is valid.
"""
raise NotImplementedError
def crack(receipt):
"""
Crack open the receipt, without checking that the crypto is valid.
Returns a list of all the elements of a receipt, which by default is
cert, receipt.
"""
return map(lambda x: jwt.decode(x.encode('ascii'), verify=False),
receipt.split('~'))
|
[
"amckay@mozilla.com"
] |
amckay@mozilla.com
|
172982b7a6506280c67c338a2ed05e734620f7ea
|
cc4424bcbc6ca3d04c1be2effa043076816b3a12
|
/Spider/VideoDownloading/shipin.py
|
ea67b404f6573e189a7fa5ca9ae0d133ef2b47f7
|
[] |
no_license
|
IronmanJay/Python_Project
|
a65a47c64b7121993be1ef38a678ffd4771ffaf1
|
91293b05eb28697f5dec7f99a0f608904f6a0b1f
|
refs/heads/master
| 2023-06-11T07:56:18.121706
| 2023-06-07T02:31:06
| 2023-06-07T02:31:06
| 253,717,731
| 15
| 4
| null | 2022-11-21T20:51:58
| 2020-04-07T07:22:35
|
Python
|
UTF-8
|
Python
| false
| false
| 621
|
py
|
import requests
url = 'http://v3-default.ixigua.com/dd48e529360eaf527c9a929e8622e8d8/5d4d0a65/video/m/220c097cb8f27af496eaddb07c5d42edc601162e796e0000acb22a2eb570/?rc=M2psOGZoZ3NrbzMzZTczM0ApdSk6OjUzNTg0NDgzNTw7PDNAKTk8OTU8OzY8PDdnODM6NzNnKXUpQGczdSlAZjN1KTk0ZHIwajItcnIuMF8tLTQtMHNzOmkvNDIvNS0yLS0tMi4tLS4vaS1gY2BgLzFjYl8zLjQyMDA6YzpiMHAjOmEtcCM6YDU0Og%3D%3D'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763',
}
r = requests.get(url=url,headers=headers)
with open('1.mp4','wb') as fp:
fp.write(r.content)
|
[
"1975686676@qq.com"
] |
1975686676@qq.com
|
9c5a9a552daa857baa5ab25b8dea7fccee69eada
|
372c618e3abf56f59027ba1cbfce8102a6ea2903
|
/sugargame/canvas.py
|
82992b3e5d2e511ef049fe38d9e16e7d2546c7d8
|
[] |
no_license
|
sugar-activities/4259-activity
|
0bb728d1f49fcc01ba91c4c07a15eca3b267868e
|
db87efad848f073b1c45d2a5debb2d4ca8eab729
|
refs/heads/master
| 2021-01-19T23:15:31.307314
| 2017-04-21T05:09:21
| 2017-04-21T05:09:21
| 88,938,120
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,039
|
py
|
import os
from gi.repository import Gtk
from gi.repository import GLib
import pygame
import event
CANVAS = None
class PygameCanvas(Gtk.EventBox):
"""
mainwindow is the activity intself.
"""
def __init__(self, mainwindow, pointer_hint = True):
Gtk.EventBox.__init__(self)
global CANVAS
assert CANVAS == None, "Only one PygameCanvas can be created, ever."
CANVAS = self
# Initialize Events translator before widget gets "realized".
self.translator = event.Translator(mainwindow, self)
self._mainwindow = mainwindow
self.set_can_focus(True)
self._socket = Gtk.Socket()
self.add(self._socket)
self.show_all()
def run_pygame(self, main_fn):
# Run the main loop after a short delay. The reason for the delay is that the
# Sugar activity is not properly created until after its constructor returns.
# If the Pygame main loop is called from the activity constructor, the
# constructor never returns and the activity freezes.
GLib.idle_add(self._run_pygame_cb, main_fn)
def _run_pygame_cb(self, main_fn):
assert pygame.display.get_surface() is None, "PygameCanvas.run_pygame can only be called once."
# Preinitialize Pygame with the X window ID.
assert pygame.display.get_init() == False, "Pygame must not be initialized before calling PygameCanvas.run_pygame."
os.environ['SDL_WINDOWID'] = str(self._socket.get_id())
pygame.init()
# Restore the default cursor.
self._socket.get_window().set_cursor(None)
# Initialize the Pygame window.
r = self.get_allocation()
pygame.display.set_mode((r.width, r.height), pygame.RESIZABLE)
# Hook certain Pygame functions with GTK equivalents.
self.translator.hook_pygame()
# Run the Pygame main loop.
main_fn()
return False
def get_pygame_widget(self):
return self._socket
|
[
"ignacio@sugarlabs.org"
] |
ignacio@sugarlabs.org
|
c1baadb28696c7b692331bd49fd54779350c9199
|
ea0928f988c87c4ac04bf7dc4e9fe0b25495d22c
|
/append.py
|
22dfbaf3ece8ee4b802feff98a716ac58f3fe026
|
[] |
no_license
|
opasha/Python
|
8c7c9aa7c363d27a7628714543e674a4edc8ae13
|
b3559e92c6c06753717cec5181868d0cecc9a2ac
|
refs/heads/master
| 2021-01-19T23:54:01.438772
| 2017-05-05T04:07:56
| 2017-05-05T04:07:56
| 89,051,109
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 322
|
py
|
numbers = [1, 2, 3, 4, 5] # .append means to add something to the end of the list
print numbers
numbers.append(6)
print numbers
numbers.append(7)
print numbers
print list(range(10))
print range(10)
for number in range (8, 21): # for i in range (): statement
numbers.append(number)
print numbers
print numbers[::-1]
|
[
"username@users.noreply.github.com"
] |
username@users.noreply.github.com
|
07491e39d8215bad8fc61f2dfe20894595808718
|
bc25195db1151a867343b5991fe51096ce2d57a8
|
/tmp/portmidi/i.py
|
cff73824a778636fcd9c351feb4b491d5cb7f67c
|
[
"MIT"
] |
permissive
|
ptone/protomidi
|
04b78139c499518440afe5faecba9664ca068226
|
3dd169e66359ab17319880581771172a5867b261
|
refs/heads/master
| 2020-04-18T06:22:15.835383
| 2012-11-19T05:40:40
| 2012-11-19T05:40:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 166
|
py
|
import time
import pprint
import protomidi.portmidi as io
input = io.Input('SH-201 MIDI 1')
while 1:
for msg in input:
print(msg)
time.sleep(0.001)
|
[
"ombdalen@gmail.com"
] |
ombdalen@gmail.com
|
4568bdca6024375029e24fe57f3dd21cc996b16d
|
0d560495d4e5be2004a5a08d696a1b4cb2b91742
|
/backend/folk_games_25344/urls.py
|
8d4f66d6cd8dc7ef11318eb019a291a2b54ca1f2
|
[] |
no_license
|
crowdbotics-apps/folk-games-25344
|
54fa818b69c50867425814ff5133c1bf87d3d2d4
|
a00bf5a15f184fcfe138e84c9e386688e5121cd8
|
refs/heads/master
| 2023-03-29T14:24:41.695249
| 2021-03-29T15:12:24
| 2021-03-29T15:12:24
| 352,686,992
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,223
|
py
|
"""folk_games_25344 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include, re_path
from django.views.generic.base import TemplateView
from allauth.account.views import confirm_email
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
urlpatterns = [
path("", include("home.urls")),
path("accounts/", include("allauth.urls")),
path("modules/", include("modules.urls")),
path("api/v1/", include("home.api.v1.urls")),
path("admin/", admin.site.urls),
path("users/", include("users.urls", namespace="users")),
path("rest-auth/", include("rest_auth.urls")),
# Override email confirm to use allauth's HTML view instead of rest_auth's API view
path("rest-auth/registration/account-confirm-email/<str:key>/", confirm_email),
path("rest-auth/registration/", include("rest_auth.registration.urls")),
]
admin.site.site_header = "Folk games"
admin.site.site_title = "Folk games Admin Portal"
admin.site.index_title = "Folk games Admin"
# swagger
api_info = openapi.Info(
title="Folk games API",
default_version="v1",
description="API documentation for Folk games App",
)
schema_view = get_schema_view(
api_info,
public=True,
permission_classes=(permissions.IsAuthenticated,),
)
urlpatterns += [
path("api-docs/", schema_view.with_ui("swagger", cache_timeout=0), name="api_docs")
]
urlpatterns += [path("", TemplateView.as_view(template_name='index.html'))]
urlpatterns += [re_path(r"^(?:.*)/?$",
TemplateView.as_view(template_name='index.html'))]
|
[
"team@crowdbotics.com"
] |
team@crowdbotics.com
|
d13de3fc39daba7cccce1b46249e9f50ee05cfda
|
5b771c11e8967038025376c6ec31962ca90748dd
|
/django_by_example_book/01_building_blog/blog/models.py
|
f61f39b725aead3d787f5b675f2d303f20eee4b3
|
[] |
no_license
|
AsemAntar/Django_Projects
|
7135eca3b4bcb656fc88e0838483c97d7f1746e1
|
4141c2c7e91845eec307f6dd6c69199302eabb16
|
refs/heads/master
| 2022-12-10T06:32:35.787504
| 2020-05-26T14:43:01
| 2020-05-26T14:43:01
| 216,863,494
| 0
| 0
| null | 2022-12-05T13:31:53
| 2019-10-22T16:47:28
|
Python
|
UTF-8
|
Python
| false
| false
| 2,066
|
py
|
from django.db import models
from django.utils import timezone
from django.urls import reverse
from django.contrib.auth.models import User
from taggit.managers import TaggableManager
# create custom manager
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager, self).get_queryset().filter(status='published')
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title = models.CharField(max_length=250, verbose_name='Post Title')
slug = models.SlugField(max_length=250, unique_for_date='publish')
author = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='blog_posts')
body = models.TextField(verbose_name='Post Body')
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(
max_length=10, choices=STATUS_CHOICES, default='draft')
objects = models.Manager() # The default manager
published = PublishedManager() # Custom manager
tags = TaggableManager()
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
# create a url linked to each post with the help of post_detail view to be used in templates
def get_absolute_url(self):
return reverse(
'blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]
)
class Comment(models.Model):
post = models.ForeignKey(
Post, on_delete=models.CASCADE, related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=True)
class Meta:
ordering = ('-created',)
def __str__(self):
return 'Comment by {} on {}'.format(self.name, self.post)
|
[
"asemantar@gmail.com"
] |
asemantar@gmail.com
|
08b738fec65ee11ea20d6fb76dbae3a4d57f27dc
|
01932366dd322ec3459db9dd85a2fd8d22a82fcb
|
/keras/keras41_cnn2_diabet.py
|
8cfb63b0328f7edc365337ec0a562d64604f6de0
|
[] |
no_license
|
Jeong-Kyu/A_study
|
653f5fd695109639badfa9e99fd5643d2e9ff1ac
|
6866c88fcc25841ceae2cd278dcb5ad5654c2a69
|
refs/heads/master
| 2023-06-11T02:44:20.574147
| 2021-07-05T08:59:43
| 2021-07-05T08:59:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,007
|
py
|
#실습 : 19_1, 2, 3, 4, 5, EarlyStopping까지 총 6개의 파일을 완성하시오.
import numpy as np
from sklearn.datasets import load_diabetes
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Dense, Input, Conv2D,MaxPool2D, Flatten
#1. 데이터
dataset = load_diabetes()
x = dataset.data
y = dataset.target
#print(dataset.DESCR)
#x = x / np.max(x)
#print(np.max(x), np.min(x)) # 정규화
#1_2. 데이터 전처리
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, train_size = 0.8, shuffle = True, random_state = 66 )
x_train, x_val, y_train, y_val = train_test_split(x_train, y_train, train_size= 0.8, shuffle = True, random_state = 66, )
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
scaler.fit(x_train)
x_train = scaler.transform(x_train)
x_test = scaler.transform(x_test)
x_val = scaler.transform(x_val)
'''
print(x_train.shape)
print(x_test.shape)
print(x_val.shape)
'''
x_train = x_train.reshape(282,10,1,1)
x_test = x_test.reshape(89,10,1,1)
x_val = x_val.reshape(71,10,1,1)
#2. 모델링
model = Sequential()
model.add(Conv2D(filters = 10,kernel_size=(1,1), strides=1, padding='same', input_shape = (10,1,1))) # (input_dim * kernel_size + bias)*filter
#strides = 얼마나 건너서 자를건지 2 / (2,3)
model.add(MaxPool2D(pool_size=(1,1))) # 2 / 3 / (2,3)
# model.add(Conv2D(9,(2,3)))
# model.add(Conv2D(8,2))
model.add(Flatten())
model.add(Dense(1))
#3. 컴파일, 훈련
model.compile(loss = 'mse', optimizer = 'adam', metrics = ['mae'])
'''
EarlyStopping
'''
from tensorflow.keras.callbacks import EarlyStopping
early_stopping = EarlyStopping(monitor='loss', patience=20, mode='auto')
model.fit(x_train, y_train, epochs=1000, batch_size=7, validation_data= (x_val, y_val), callbacks = [early_stopping])
#4. 평가, 예측
loss, mae = model.evaluate(x_test, y_test)
print("loss : ", loss)
print("mae : ", mae)
y_predict = model.predict(x_test)
#RMSE
from sklearn.metrics import mean_squared_error
def RMSE(y_test, y_predict) :
return np.sqrt(mean_squared_error(y_test, y_predict))
print("RMSE : ", RMSE(y_test, y_predict))
from sklearn.metrics import r2_score
r2 = r2_score(y_test, y_predict)
print("R2 : ", r2)
"""
**Data Set Characteristics:**
:Number of Instances: 442
:Number of Attributes: First 10 columns are numeric predictive values
:Target: Column 11 is a quantitative measure of disease progression one year after baseline
:Attribute Information:
- age age in years
- sex
- bmi body mass index
- bp average blood pressure
- s1 tc, T-Cells (a type of white blood cells)
- s2 ldl, low-density lipoproteins
- s3 hdl, high-density lipoproteins
- s4 tch, thyroid stimulating hormone
- s5 ltg, lamotrigine
- s6 glu, blood sugar level
"""
#데이터 전처리 전
# loss : 3317.64599609375
# mae : 47.06387710571289
# RMSE : 57.59901189718801
# R2 : 0.488809627121195
#데이터 엉망 처리 후
# loss : 3379.458984375
# mae : 47.35618591308594
# RMSE : 58.13311275393621
# R2 : 0.47928539874511966
#데이터 x를 전처리한 후
# loss : 3291.452880859375
# mae : 46.496116638183594
# RMSE : 57.37118551454562
# R2 : 0.49284554101046385
#데이터 x_train잡아서 전처리한 후....
# loss : 3421.5537109375
# mae : 47.82155227661133
# RMSE : 58.49405010020266
# R2 : 0.47279929140593635
#발리데이션 test분리
# loss : 3369.262451171875
# mae : 48.33604431152344
# RMSE : 58.04534944194592
# R2 : 0.5128401315682825
#Earlystopping 적용
# loss : 57.708213806152344
# mae : 5.144794464111328
# RMSE : 7.596591897809446
# R2 : 0.991656001135139
# loss : 6162.50048828125
# mae : 62.28391647338867
# RMSE : 78.50159664503691
# R2 : 0.05046805612688887'''
# cnn
# loss : 3194.252197265625
# mae : 46.7601318359375
# RMSE : 56.517714046839565
# R2 : 0.507822478023054
|
[
"jare92n@gmail.com"
] |
jare92n@gmail.com
|
71510ac89df23b353d808a6ad31c17a177af9447
|
52d324c6c0d0eb43ca4f3edc425a86cdc1e27d78
|
/scripts/current/stage4_today_total.py
|
494801c0c903240ab3698afb779c3c93ce742f6b
|
[
"MIT"
] |
permissive
|
deenacse/iem
|
992befd6d95accfdadc34fb7928d6b69d661d399
|
150512e857ca6dca1d47363a29cc67775b731760
|
refs/heads/master
| 2021-02-04T04:20:14.330527
| 2020-02-26T21:11:32
| 2020-02-26T21:11:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,997
|
py
|
"""
Sum up the hourly precipitation from NCEP stage IV and produce maps
"""
from __future__ import print_function
import datetime
import os
import sys
import pygrib
from pyiem.datatypes import distance
from pyiem.plot import MapPlot, nwsprecip
import pytz
def doday(ts, realtime):
"""
Create a plot of precipitation stage4 estimates for some day
We should total files from 1 AM to midnight local time
"""
sts = ts.replace(hour=1)
ets = sts + datetime.timedelta(hours=24)
interval = datetime.timedelta(hours=1)
now = sts
total = None
lts = None
while now < ets:
gmt = now.astimezone(pytz.utc)
fn = gmt.strftime(
("/mesonet/ARCHIVE/data/%Y/%m/%d/" "stage4/ST4.%Y%m%d%H.01h.grib")
)
if os.path.isfile(fn):
lts = now
grbs = pygrib.open(fn)
if total is None:
total = grbs[1]["values"]
lats, lons = grbs[1].latlons()
else:
total += grbs[1]["values"]
grbs.close()
now += interval
if lts is None:
if ts.hour > 1:
print(("stage4_today_total.py found no data for date: %s") % (ts,))
return
lts = lts - datetime.timedelta(minutes=1)
subtitle = "Total between 12:00 AM and %s" % (lts.strftime("%I:%M %p %Z"),)
routes = "ac"
if not realtime:
routes = "a"
for sector in ["iowa", "midwest", "conus"]:
pqstr = ("plot %s %s00 %s_stage4_1d.png %s_stage4_1d.png png") % (
routes,
ts.strftime("%Y%m%d%H"),
sector,
sector,
)
mp = MapPlot(
sector=sector,
title=("%s NCEP Stage IV Today's Precipitation")
% (ts.strftime("%-d %b %Y"),),
subtitle=subtitle,
)
clevs = [0.01, 0.1, 0.3, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 5, 6, 8, 10]
mp.pcolormesh(
lons,
lats,
distance(total, "MM").value("IN"),
clevs,
cmap=nwsprecip(),
units="inch",
)
# map.drawstates(zorder=2)
if sector == "iowa":
mp.drawcounties()
mp.postprocess(pqstr=pqstr)
mp.close()
def main(argv):
""" Go Main Go
So the past hour's stage IV is available by about 50 after, so we should
run for a day that is 90 minutes in the past by default
"""
if len(argv) == 4:
date = datetime.datetime(
int(argv[1]), int(argv[2]), int(argv[3]), 12, 0
)
realtime = False
else:
date = datetime.datetime.now()
date = date - datetime.timedelta(minutes=90)
date = date.replace(hour=12, minute=0, second=0, microsecond=0)
realtime = True
# Stupid pytz timezone dance
date = date.replace(tzinfo=pytz.utc)
date = date.astimezone(pytz.timezone("America/Chicago"))
doday(date, realtime)
if __name__ == "__main__":
main(sys.argv)
|
[
"akrherz@iastate.edu"
] |
akrherz@iastate.edu
|
723c6f7bef028baa67703a89851fee5669b1e438
|
1a2bf34d7fc1d227ceebf05edf00287de74259c5
|
/Django/Day09/AXF/APP/views.py
|
410ab6a0ae6c42ec968dfac9b50b15f473ffb049
|
[] |
no_license
|
lzn9423362/Django-
|
de69fee75160236e397b3bbc165281eadbe898f0
|
8c1656d20dcc4dfc29fb942b2db54ec07077e3ae
|
refs/heads/master
| 2020-03-29T18:03:47.323734
| 2018-11-28T12:07:12
| 2018-11-28T12:07:12
| 150,192,771
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,795
|
py
|
from django.shortcuts import render
from .models import *
# Create your views here.
def home(request):
#获取首页数据
#轮播数据u
wheel = MainWheel.objects.all()
nav = MainNav.objects.all()
mustbuy = MainMustbuy.objects.all()
shop = MainShop.objects.all()
shop1 = MainShop.objects.get(id=1)
mainlist = MainShow.objects.all()
data = {
'wheels': wheel,
'navs': nav,
'mustbuys': mustbuy,
'shop1': shop1,
'shop2': shop[1:3],
'shop3': shop[3:7],
'shop4': shop[7:11],
'main_list': mainlist,
}
return render(request, 'home/home.html', data)
def cart(request):
return render(request, 'cart/cart.html')
def mine(request):
return render(request, 'mine/mine.html')
def market(request, categoryid, cid, sortid):
leftSlider = MainFoodTpye.objects.all()
if cid == '0':
productList = Goods.objects.filter(categoryid=categoryid)
else:
productList = Goods.objects.filter(categoryid=categoryid, childcid=cid)
if sortid == '1':
productList = productList.order_by('-productnum')
elif sortid == '2':
productList = productList.order_by('-price')
elif sortid == '3':
productList = productList.order_by('price')
group = leftSlider.get(typeid=categoryid)
childList = []
childnames = group.childtypenames
arr1 =childnames.split('#')
for str in arr1:
arr2 = str.split(':')
obj = {'childName': arr2[0], 'childId': arr2[1]}
childList.append(obj)
data = {
'leftSlider': leftSlider,
'productList': productList,
'childList': childList,
'categoryid': categoryid,
'cid': cid,
}
return render(request, 'market/market.html', data)
|
[
"411121080@qq.com"
] |
411121080@qq.com
|
31ecf624d4ad0a53984e4da6628073af9caec17b
|
476415b07a8ab773ac240989b481464961119b6a
|
/Funcionalidades/Diseño Clases/orden.py
|
7406d7ba1af43e7054866541d4af804d132f09ac
|
[] |
no_license
|
rtejada/Universidad-Python
|
c4d46a91eee2a15d3c72035aced9d28f1527fb69
|
a2c8035f57f5ae269b1b968ef187180879d14163
|
refs/heads/master
| 2022-12-16T21:32:47.181638
| 2020-09-17T17:42:49
| 2020-09-17T17:42:49
| 284,633,477
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 528
|
py
|
class Order:
count_order = 0
def __init__(self):
Order.count_order += 1
self.__id_order = Order.count_order
self.product_list = []
def add_product(self, product):
self.product_list.append(product)
def calc_total(self):
total = 0
for i in range(len(self.product_list)):
total += self.product_list[i].price
return total
def get_products(self):
return self.product_list
|
[
"rtejadasilva@gmail.com"
] |
rtejadasilva@gmail.com
|
676934452bd736024c690192d1c1131a2e64e5b2
|
98c6ea9c884152e8340605a706efefbea6170be5
|
/examples/data/Assignment_7/knnoth001/question1.py
|
3099688c159642da489155736d68fff2d6c0ea97
|
[] |
no_license
|
MrHamdulay/csc3-capstone
|
479d659e1dcd28040e83ebd9e3374d0ccc0c6817
|
6f0fa0fa1555ceb1b0fb33f25e9694e68b6a53d2
|
refs/heads/master
| 2021-03-12T21:55:57.781339
| 2014-09-22T02:22:22
| 2014-09-22T02:22:22
| 22,372,174
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 536
|
py
|
'''Program that prints list of unique string of a string in the same order
Othniel KONAN
KNNOTH001
2014/04/27
'''
#VARIABLES
unik_list = []
#PROMPT THE USER TO ENTER A STRING
st = input('Enter strings (end with DONE):\n')
while st != 'DONE':
if not st in unik_list: #If it's a new string
unik_list.append(st) #Add it to the unique list
st = input() #Ask the user again
print('\nUnique list:')
#PRINT THE LIST
for l in unik_list:
print(l)
|
[
"jarr2000@gmail.com"
] |
jarr2000@gmail.com
|
ffe39281999c87161f8b9dfbad8a984c251fd2be
|
3199331cede4a22b782f945c6a71150a10c61afc
|
/20210519PythonAdvacned/02-metaclass/hook03/user.py
|
b3f9c6d008e28f42933539ae1b06a6dd3ab8d1dd
|
[] |
no_license
|
AuroraBoreas/language-review
|
6957a3cde2ef1b6b996716addaee077e70351de8
|
2cb0c491db7d179c283dba205b4d124a8b9a52a3
|
refs/heads/main
| 2023-08-19T23:14:24.981111
| 2021-10-11T12:01:47
| 2021-10-11T12:01:47
| 343,345,371
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 285
|
py
|
"#Python is a protocol orientated lang; every top-level function or syntax has a corresponding dunder method implemented;"
from library import Base
class Derived(Base):
def bar(self):
return self.foo()
class A(Base):
def a(self):
return self.foo()
|
[
"noreply@github.com"
] |
AuroraBoreas.noreply@github.com
|
00f71d34637a4cb4036d4283d721b653b33e0aae
|
0725ed7ab6be91dfc0b16fef12a8871c08917465
|
/dp/binomial_cof.py
|
abe4fe8f6815852764ae85642a87766712dd4896
|
[] |
no_license
|
siddhism/leetcode
|
8cb194156893fd6e9681ef50c84f0355d09e9026
|
877933424e6d2c590d6ac53db18bee951a3d9de4
|
refs/heads/master
| 2023-03-28T08:14:12.927995
| 2021-03-24T10:46:20
| 2021-03-24T10:46:20
| 212,151,205
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 622
|
py
|
def binomial_cof(n, k):
if cache[n][k]:
print ('returning from cache')
return cache[n][k]
print ('Calling binomial for n: ', n, ' k : ', k)
if k ==0 or n ==0 or k > n:
return 1
numerator = 1
for i in range(0, k):
# have to do n. n-1. n-2
numerator = numerator * (n-i)
denominator = 1
for i in range(1, k+1):
denominator = denominator * i
answer = numerator / denominator
cache[n][k] = answer
return cache[n][k]
n = 10
k = 10
cache = [[0 for i in range(k+1)] for j in range(n+1)]
for k in range(0, 10):
print binomial_cof(5, k)
|
[
"siddhesh@hackerearth.com"
] |
siddhesh@hackerearth.com
|
6bd6130c6ed40039761f0f71d944d545d53d6817
|
63e3e22fd46c07dbd18b74952b460cb7dc347466
|
/peripteras/kiosks/migrations/0003_brand_category_item.py
|
da8d3e4017a041b0f37e0b99d2806d30435f2c9b
|
[
"MIT"
] |
permissive
|
sm2x/e-peripteras
|
0104dad6a4a0e2765c403c0b81dd34b2fefa847b
|
39634ca07de535c6a1188af636e394a8966672ca
|
refs/heads/master
| 2021-10-24T01:28:21.987338
| 2019-03-21T10:45:30
| 2019-03-21T10:45:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,812
|
py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kiosks', '0002_auto_20160905_1531'),
]
operations = [
migrations.CreateModel(
name='Brand',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('title', models.CharField(default=b'', max_length=255, verbose_name='Brand name')),
],
),
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('title', models.CharField(default=b'', max_length=255, verbose_name='Category title')),
('slug', models.SlugField(unique=True, max_length=255, blank=True)),
],
options={
'verbose_name_plural': 'Categories',
},
),
migrations.CreateModel(
name='Item',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('price', models.DecimalField(max_digits=6, decimal_places=2)),
('slug', models.SlugField(unique=True, max_length=255, blank=True)),
('created_on', models.DateTimeField(auto_now_add=True)),
('last_updated', models.DateTimeField(auto_now=True, null=True)),
('brand', models.ForeignKey(to='kiosks.Brand')),
('category', models.ForeignKey(to='kiosks.Category')),
('kiosk', models.ForeignKey(to='kiosks.Kiosk')),
],
),
]
|
[
"ctefanos.t@gmail.com"
] |
ctefanos.t@gmail.com
|
6709fd566ee0ff20b661b59581d20d4021135340
|
942ee5e8d54e8ebe9c5c841fbfdd1da652946944
|
/1001-1500/1268.Search Suggestions System.py
|
decc52676b284d49aeebcc99154207205fe08d97
|
[] |
no_license
|
kaiwensun/leetcode
|
0129c174457f32887fbca078fb448adce46dd89d
|
6b607f4aae3a4603e61f2e2b7480fdfba1d9b947
|
refs/heads/master
| 2023-08-31T07:30:50.459062
| 2023-08-27T07:59:16
| 2023-08-27T07:59:16
| 57,526,914
| 69
| 9
| null | 2023-08-20T06:34:41
| 2016-05-01T05:37:29
|
Python
|
UTF-8
|
Python
| false
| false
| 1,033
|
py
|
import collections
class Solution(object):
def suggestedProducts(self, products, searchWord):
"""
:type products: List[str]
:type searchWord: str
:rtype: List[List[str]]
"""
def dfs(p, res):
if '#' in p:
for _ in xrange (p['#'][1]):
if len(res) == 3:
break
res.append(p['#'][0])
if len(res) == 3:
return res
for key in sorted(p.keys()):
if key != "#" and len(dfs(p[key], res)) == 3:
return res
return res
T = lambda: collections.defaultdict(T)
trie = T()
for product in products:
p = trie
for c in product:
p = p[c]
p["#"] = (product, p["#"][1] + 1 if "#" in p else 1)
res = []
p = trie
for c in searchWord:
p = p[c]
res.append(dfs(p, []))
return res
|
[
"noreply@github.com"
] |
kaiwensun.noreply@github.com
|
8955a3578716804771d062c9949cb5bf9b88be34
|
e51c261f76ecb86d85c1f7f93c0c3e4953284233
|
/setup.py
|
c49e76f060f460899c14fea338caf86f58519c53
|
[
"MIT"
] |
permissive
|
adodo1/pyminitouch
|
6f0194f3c25ab78abc89fabe9e8cd6bc19b20f54
|
cefeab762277626b5a8167454467971a4c376e31
|
refs/heads/master
| 2020-05-20T09:48:45.430918
| 2019-03-25T06:39:26
| 2019-03-25T06:39:26
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 383
|
py
|
from setuptools import setup, find_packages
setup(
name='pyminitouch',
version='0.2.5',
description='python wrapper of minitouch, for better experience',
author='williamfzc',
author_email='fengzc@vip.qq.com',
url='https://github.com/williamfzc/pyminitouch',
packages=find_packages(),
install_requires=[
'loguru',
'requests',
]
)
|
[
"178894043@qq.com"
] |
178894043@qq.com
|
eb57c92acb99b68b2959e86a7d6a967376b975be
|
e23a4f57ce5474d468258e5e63b9e23fb6011188
|
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/beginner/254/scoping.py
|
34decf08d03878474c2328fa00d3a32c654a37e8
|
[] |
no_license
|
syurskyi/Python_Topics
|
52851ecce000cb751a3b986408efe32f0b4c0835
|
be331826b490b73f0a176e6abed86ef68ff2dd2b
|
refs/heads/master
| 2023-06-08T19:29:16.214395
| 2023-05-29T17:09:11
| 2023-05-29T17:09:11
| 220,583,118
| 3
| 2
| null | 2023-02-16T03:08:10
| 2019-11-09T02:58:47
|
Python
|
UTF-8
|
Python
| false
| false
| 502
|
py
|
# num_hundreds -1
#
#
# ___ sum_numbers numbers l.. __ i..
# """Sums passed in numbers returning the total, also
# update the global variable num_hundreds with the amount
# of times 100 fits in total"""
# sumlist s.. ?
# gl.. 'num_hundreds' +_ ? //100
# r.. ?
#
#
# """ numlists = [[],[1, 2, 3],[40, 50, 60],[140, 50, 60],[140, 150, 160],[1140, 150, 160]]
#
# for numlist in numlists:
# print(numlist)
# print(sum_numbers(numlist))
# print(num_hundreds) """
|
[
"sergejyurskyj@yahoo.com"
] |
sergejyurskyj@yahoo.com
|
ea2a8410b431daa5b5ae063281210a409f3e2dc2
|
931ae36e876b474a5343d0608ef41da6b33f1048
|
/python100_sourceCode/089.py
|
c81f732407e3b1cf928528d280322cf2dcc05199
|
[] |
no_license
|
mucollabo/py100
|
07fc10164b1335ad45a55b6af4767948cf18ee28
|
6361398e61cb5b014d2996099c3acfe604ee457c
|
refs/heads/master
| 2023-01-27T13:48:57.807514
| 2020-12-10T12:49:10
| 2020-12-10T12:49:10
| 267,203,606
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 443
|
py
|
import sqlite3
# DB 연결
conn = sqlite3.connect('./output/sample.db')
cur = conn.cursor()
# Product 테이블의 id=1인 행 레코드의 가격을 7000원으로 수정
cur.execute('UPDATE Product set title="새 제품", price=7000 where id=1')
conn.commit()
# 변경 내용 확인
cur.execute('SELECT * from Product where id=1')
rows = cur.fetchall()
for row in rows:
print(row)
# DB 연결 종료
conn.close()
|
[
"mucollabo@gmail.com"
] |
mucollabo@gmail.com
|
e525cb78a6ad0651eeef1a726b80d42425cb8a17
|
fe6b6d2253a9efc50571e1d1339ba5134306e978
|
/AOJ/1611.py
|
4a3e9abfc835b6997ea05081a0d81b344a4dbbd5
|
[] |
no_license
|
tehhuu/Atcoder
|
d6642dea8e92c9d721a914c9bbc208ca4fb484d0
|
3ff8b9890ac5a2b235ec0fbc9e1ef5f9653d956e
|
refs/heads/master
| 2020-12-07T09:02:22.422854
| 2020-08-15T16:20:16
| 2020-08-15T16:20:16
| 232,689,873
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,435
|
py
|
import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def ti(): return tuple(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
def dp2(ini, i, j): return [[ini]*i for _ in range(j)]
def dp3(ini, i, j, k): return [[[ini]*i for _ in range(j)] for _ in range(k)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value
#from itertools import accumulate #list(accumulate(A))
## DP
def solve(N):
A = ti()
dp = dp2(0, N, N)
for i in range(N-1):
if abs(A[i]-A[i+1]) < 2:
dp[i][i+1] = 2
for h in range(2, N): #hは(区間の長さ)-1
for i in range(N):
if i+h >= N:
break
j = i+h
# 区間の長さが偶数の場合
if h % 2:
if abs(A[i]-A[j]) < 2 and dp[i+1][j-1] == h-1:
dp[i][j] = h + 1
continue
else:
dp[i][j] = max(tuple(dp[i][k]+dp[k+1][j] for k in range(i, j)))
# 区間の長さが奇数の場合
else:
dp[i][j] = max(dp[i+1][j], dp[i][j-1])
else:
continue
print(dp[0][N-1])
while True:
N = ii()
if N == 0:
exit()
solve(N)
|
[
"volley_neverlose_exile@yahoo.co.jp"
] |
volley_neverlose_exile@yahoo.co.jp
|
e60a211880a23654d745ef6116f44ceb0a6b2b21
|
bf7ceda28eacc4e68dadff5d35224a13e7467d4d
|
/save_pages_as_pickle_from_db.py
|
7da88716bcfdb8ba5e8e88cc411a951fa68dcdf0
|
[] |
no_license
|
katryo/task_search
|
83983d61618d7755c474a9ed9c39ec6ca5621641
|
20c1985ca27253f64f4f9c124b36166c86bcf2d0
|
refs/heads/master
| 2020-05-09T10:04:11.155557
| 2014-03-25T04:10:25
| 2014-03-25T04:10:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 935
|
py
|
# -*- coding: utf-8 -*-
import constants
import pdb
from pickle_file_saver_for_original import PickleFileSaverForOriginal
from page_data_loader import PageDataLoader
from web_page import WebPage
if __name__ == '__main__':
queries = constants.QUERIES_4
saver = PickleFileSaverForOriginal()
with PageDataLoader() as page_loader:
for query in queries:
pages = []
page_ids = page_loader.page_ids_with_query(query)
for page_id in page_ids:
pagedata = page_loader.pagedata_with_id(page_id) # (id, url, snippet, body, rank)
page = WebPage(id=page_id,
url=pagedata[0],
query=pagedata[1],
snippet=pagedata[2],
rank=pagedata[3])
pages.append(page)
saver.save_pages_with_query(pages=pages, query=query)
|
[
"katoryo55@gmail.com"
] |
katoryo55@gmail.com
|
979b67f9de6aee4f55cd9ac3f8fa6994dfbe7fbe
|
d5ad13232e3f1ced55f6956bc4cbda87925c8085
|
/cc_mcc_seq/20sViruses/6.heatmap.py
|
52b1d01453d24e84bc8ab093eb29173973a0ce4b
|
[] |
no_license
|
arvin580/SIBS
|
c0ba9a8a41f59cb333517c286f7d80300b9501a2
|
0cc2378bf62359ec068336ea4de16d081d0f58a4
|
refs/heads/master
| 2021-01-23T21:57:35.658443
| 2015-04-09T23:11:34
| 2015-04-09T23:11:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,232
|
py
|
from PyPlot.PyPlotClass import *
import sys
import math
import numpy
V = {}
V['NC_001669.1']='Simian virus'
V['NC_006273.2']='Human herpesvirus 5'
V['NC_003287.2']='Enterobacteria phage M13'
V['NC_000898.1']='Human herpesvirus 6B'
V['NC_007605.1']='Human herpesvirus 4 type 1'
V['NC_009334.1']='Human herpesvirus 4'
V['NC_003977.1']='Hepatitis B virus'
Score = 20
def foo(x):
if x >= Score:
return 1
else:
return 0
def gene_heatmap(sampleNameList, ouF, figsize=0, rowList=[]):
D = dict()
D2 = dict()
for i,inF in enumerate(sampleNameList):
inFile = open(inF + '.unmapped.sam.mapped.fa.fa.blasted.top.num')
for line in inFile:
line = line.strip()
fields =line.split('\t')
D.setdefault(fields[0],[0]*20)
D2.setdefault(fields[0],[0]*20)
#D[fields[0]][i] = int(math.log(int(fields[1])+1,2))
D[fields[0]][i] = int(fields[1])
D2[fields[0]][i] = int(fields[1])
inFile.close()
D3 = {}
D4 = {}
D3['Human herpesvirus']=[foo(x) for x in (numpy.array(D['NC_006273.2'])+numpy.array(D['NC_000898.1'])+numpy.array(D['NC_007605.1'])+numpy.array(D['NC_009334.1']))]
D3['Hepatitis B virus']=[foo(x) for x in D['NC_003977.1']]
D3['Enterobacteria phage M13']=[foo(x) for x in D['NC_003287.2']]
D4['Human herpesvirus']=numpy.array(D['NC_006273.2'])+numpy.array(D['NC_000898.1'])+numpy.array(D['NC_007605.1'])+numpy.array(D['NC_009334.1'])
D4['Hepatitis B virus']=D['NC_003977.1']
D4['Enterobacteria phage M13']=D['NC_003287.2']
ouFile = open(ouF+'.data','w')
for k in D4 :
ouFile.write(k+'\t'+'\t'.join([str(x)for x in D4[k]])+'\n')
LD = []
geneList = []
for key in D3 :
if max(D3[key])>0:
LD.append(D3[key])
geneList.append(key)
print(LD)
pp=PyPlot(ouF)
pp.heatmap(LD,col=False,xLabel=sampleNameList,yLabel=geneList,xLabelVertical=True,grid=True,figsize=figsize,colorTickets=True)
gene_heatmap(['ICC1A','ICC2A','ICC3A','ICC4A','ICC5A','ICC6A','ICC7A','ICC8A','ICC9A','ICC10A','CHC1A','CHC2A','CHC3A','CHC4A','CHC5A','CHC6A','CHC7A','CHC8A','CHC9A','CHC10A'],'viruses.heatmap3.pdf')
|
[
"sunhanice@gmail.com"
] |
sunhanice@gmail.com
|
d83aba75ffff502d1e1d4ac11c23a729564cdd4c
|
26c5f6bb53331f19e2a0ef0797b752aca9a89b19
|
/caffe2/python/operator_test/elementwise_logical_ops_test.py
|
fb886a1845571f85cf8624a289fb54f3ae7c6bc2
|
[
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] |
permissive
|
Maratyszcza/caffe2
|
4c68baedbdaf5378f9da0ebf58b232478f689ae4
|
f4794ac7629e6825b2c8be99950ea130b69c4840
|
refs/heads/master
| 2023-06-20T18:23:06.774651
| 2018-03-26T07:41:33
| 2018-03-26T18:22:53
| 122,715,434
| 1
| 0
|
Apache-2.0
| 2018-02-24T07:28:21
| 2018-02-24T07:28:21
| null |
UTF-8
|
Python
| false
| false
| 5,258
|
py
|
# Copyright (c) 2016-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##############################################################################
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
from hypothesis import given
import hypothesis.strategies as st
import caffe2.python.hypothesis_test_util as hu
import numpy as np
import unittest
def mux(select, left, right):
return [np.vectorize(lambda c, x, y: x if c else y)(select, left, right)]
def rowmux(select_vec, left, right):
select = [[s] * len(left) for s in select_vec]
return mux(select, left, right)
class TestWhere(hu.HypothesisTestCase):
def test_reference(self):
self.assertTrue((
np.array([1, 4]) == mux([True, False],
[1, 2],
[3, 4])[0]
).all())
self.assertTrue((
np.array([[1], [4]]) == mux([[True], [False]],
[[1], [2]],
[[3], [4]])[0]
).all())
@given(N=st.integers(min_value=1, max_value=10),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs_cpu_only)
def test_where(self, N, gc, dc, engine):
C = np.random.rand(N).astype(bool)
X = np.random.rand(N).astype(np.float32)
Y = np.random.rand(N).astype(np.float32)
op = core.CreateOperator("Where", ["C", "X", "Y"], ["Z"], engine=engine)
self.assertDeviceChecks(dc, op, [C, X, Y], [0])
self.assertReferenceChecks(gc, op, [C, X, Y], mux)
@given(N=st.integers(min_value=1, max_value=10),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs_cpu_only)
def test_where_dim2(self, N, gc, dc, engine):
C = np.random.rand(N, N).astype(bool)
X = np.random.rand(N, N).astype(np.float32)
Y = np.random.rand(N, N).astype(np.float32)
op = core.CreateOperator("Where", ["C", "X", "Y"], ["Z"], engine=engine)
self.assertDeviceChecks(dc, op, [C, X, Y], [0])
self.assertReferenceChecks(gc, op, [C, X, Y], mux)
class TestRowWhere(hu.HypothesisTestCase):
def test_reference(self):
self.assertTrue((
np.array([1, 2]) == rowmux([True],
[1, 2],
[3, 4])[0]
).all())
self.assertTrue((
np.array([[1, 2], [7, 8]]) == rowmux([True, False],
[[1, 2], [3, 4]],
[[5, 6], [7, 8]])[0]
).all())
@given(N=st.integers(min_value=1, max_value=10),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs_cpu_only)
def test_rowwhere(self, N, gc, dc, engine):
C = np.random.rand(N).astype(bool)
X = np.random.rand(N).astype(np.float32)
Y = np.random.rand(N).astype(np.float32)
op = core.CreateOperator(
"Where",
["C", "X", "Y"],
["Z"],
broadcast_on_rows=True,
engine=engine,
)
self.assertDeviceChecks(dc, op, [C, X, Y], [0])
self.assertReferenceChecks(gc, op, [C, X, Y], mux)
@given(N=st.integers(min_value=1, max_value=10),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs_cpu_only)
def test_rowwhere_dim2(self, N, gc, dc, engine):
C = np.random.rand(N).astype(bool)
X = np.random.rand(N, N).astype(np.float32)
Y = np.random.rand(N, N).astype(np.float32)
op = core.CreateOperator(
"Where",
["C", "X", "Y"],
["Z"],
broadcast_on_rows=True,
engine=engine,
)
self.assertDeviceChecks(dc, op, [C, X, Y], [0])
self.assertReferenceChecks(gc, op, [C, X, Y], rowmux)
class TestIsMemberOf(hu.HypothesisTestCase):
@given(N=st.integers(min_value=1, max_value=10),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs_cpu_only)
def test_is_member_of(self, N, gc, dc, engine):
X = np.random.randint(10, size=N).astype(np.int64)
values = [0, 3, 4, 6, 8]
op = core.CreateOperator(
"IsMemberOf",
["X"],
["Y"],
value=np.array(values),
engine=engine,
)
self.assertDeviceChecks(dc, op, [X], [0])
values = set(values)
def test(x):
return [np.vectorize(lambda x: x in values)(x)]
self.assertReferenceChecks(gc, op, [X], test)
if __name__ == "__main__":
unittest.main()
|
[
"facebook-github-bot@users.noreply.github.com"
] |
facebook-github-bot@users.noreply.github.com
|
2da8e86c83b20b30243df47ef601477d5c095ae6
|
de24f83a5e3768a2638ebcf13cbe717e75740168
|
/moodledata/vpl_data/428/usersdata/281/102513/submittedfiles/jogoDaVelha.py
|
f0e243249430cf1433ee1d4ee186ce27cbbfc621
|
[] |
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
| 469
|
py
|
# -*- coding: utf-8 -*-
from jogoDaVelha_BIB import *
import random
# COLOQUE SEU PROGRAMA A PARTIR DAQUI
print('Bem vindo ao Jogo da Velha da equipe ESSI')
nome=str(input('Qual o seu nome (ou apelido)? '))
simb ()
sorteio ()
if sorteio==1:
print('Vencedor do sorteio para inicio do jogo: Computador' )
elif sorteio==0:
print('Vencedor do sorteio para inicio do jogo: ' +nome)
|
[
"rafael.mota@ufca.edu.br"
] |
rafael.mota@ufca.edu.br
|
d3b35b564dfbdedf90d2e01ce3eef7f3c2366590
|
d2b42c7a82229b02498ec9ba3bb49bb78857beca
|
/common.py
|
c0b5f07acc611a74bb0135b56d8cdd884e802e8b
|
[] |
no_license
|
flyingbird93/NIMA
|
8dd41d0bb10a21b7b9afeca59f26f70c626e9dec
|
4c75458d31762d6236b931f0bc66d1784a2ea003
|
refs/heads/master
| 2022-11-06T10:47:30.404174
| 2018-12-14T07:05:57
| 2018-12-14T12:28:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,488
|
py
|
import os
import numpy as np
import requests
from torchvision import transforms
IMAGE_NET_MEAN = [0.485, 0.456, 0.406]
IMAGE_NET_STD = [0.229, 0.224, 0.225]
class Transform:
def __init__(self):
normalize = transforms.Normalize(
mean=IMAGE_NET_MEAN,
std=IMAGE_NET_STD)
self._train_transform = transforms.Compose([
transforms.Resize((256, 256)),
transforms.RandomHorizontalFlip(),
transforms.RandomCrop((224, 224)),
transforms.ToTensor(),
normalize])
self._val_transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
normalize])
@property
def train_transform(self):
return self._train_transform
@property
def val_transform(self):
return self._val_transform
def get_mean_score(score):
buckets = np.arange(1, 11)
mu = (buckets * score).sum()
return mu
def get_std_score(scores):
si = np.arange(1, 11)
mean = get_mean_score(scores)
std = np.sqrt(np.sum(((si - mean) ** 2) * scores))
return std
def download_file(url, local_filename, chunk_size=1024):
if os.path.exists(local_filename):
return local_filename
r = requests.get(url, stream=True)
with open(local_filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=chunk_size):
if chunk:
f.write(chunk)
return local_filename
|
[
"wangxin19930411@163.com"
] |
wangxin19930411@163.com
|
07e8edc00895d0ef29ad6acd8dcaad2abc9c07cb
|
6fc5882ad4c38f32162ed30e60c3423ef8da5b7b
|
/fake_faces/models/baseline_batchnorm.py
|
e364734eb462c9da412e3e12f9385e20b72190ee
|
[
"MIT"
] |
permissive
|
alexkyllo/fake-faces
|
f7334c798fc90eab94657dc18df88c19ec8c052c
|
95d7467598bc1275e6c6c0bea331e036da4e625e
|
refs/heads/main
| 2023-01-31T15:43:53.212202
| 2020-12-17T02:11:15
| 2020-12-17T02:11:15
| 304,217,528
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,931
|
py
|
"""baseline.py
A baseline CNN with 3 Conv2D layers"""
import os
from tensorflow.keras import Sequential
from tensorflow.keras.layers import (
Conv2D,
MaxPool2D,
Flatten,
Dense,
Dropout,
BatchNormalization,
)
from tensorflow.keras.optimizers import Adam
from fake_faces.models.model import Model
from fake_faces import SHAPE, BATCH_SIZE, CLASS_MODE
class BaselineBatchNorm(Model):
"""A simple 3-layer CNN with batch normalization."""
def build(self, shape=SHAPE, color_channels=1, momentum=0.99, normalize_fc=False, optimizer=Adam()):
"""Build the model with the given hyperparameter values."""
model = Sequential()
model.add(
Conv2D(
filters=32,
kernel_size=(3, 3),
input_shape=(*SHAPE, color_channels),
activation="relu",
padding="same",
)
)
model.add(BatchNormalization(momentum=momentum))
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(
Conv2D(filters=64, kernel_size=(3, 3), activation="relu", padding="same")
)
model.add(BatchNormalization(momentum=momentum))
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(
Conv2D(filters=128, kernel_size=(3, 3), activation="relu", padding="same")
)
model.add(BatchNormalization(momentum=momentum))
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(Flatten())
if normalize_fc:
model.add(BatchNormalization(momentum=momentum))
model.add(Dense(units=128, activation="relu"))
if normalize_fc:
model.add(BatchNormalization(momentum=momentum))
model.add(Dense(units=1, activation="sigmoid"))
model.compile(
optimizer=optimizer, loss="binary_crossentropy", metrics=["accuracy"]
)
self.model = model
return self
|
[
"alex.kyllo@gmail.com"
] |
alex.kyllo@gmail.com
|
57affb3c8abbefac1bd893146ceb7506392bad76
|
d35813d7e9ef6c606591ae1eb4ed3b2d5156633b
|
/python4everybody/ch12_network_programming/socket1.py
|
3e7484b486f0d5399dec90354d6b926489059e4a
|
[] |
no_license
|
JeremiahZhang/gopython
|
eb6f598c16c8a00c86245e6526261b1b2d1321f1
|
ef13f16d2330849b19ec5daa9f239bf1558fa78c
|
refs/heads/master
| 2022-08-13T22:38:12.416404
| 2022-05-16T02:32:04
| 2022-05-16T02:32:04
| 42,239,933
| 13
| 6
| null | 2022-08-01T08:13:54
| 2015-09-10T11:14:43
|
Jupyter Notebook
|
UTF-8
|
Python
| false
| false
| 333
|
py
|
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('data.pr4e.org', 80))
cmd = 'GET http://data.pr4e.org/intro-short.txt HTTP/1.0\r\n\r\n'.encode()
mysock.send(cmd)
while True:
data = mysock.recv(512)
if (len(data) < 1):
break
print(data.decode(), end='')
mysock.close()
|
[
"zhangleisuda@gmail.com"
] |
zhangleisuda@gmail.com
|
cdf1db92901c592528e93cf76a2b6650207ac886
|
311578520b84f1649124cdfa335028ee66e9d88d
|
/scapy_python2/bridge/scapy_bridge_ThreadPoolExecutor.py
|
b6adcf9046fa57b1f12222f453747858c4178415
|
[
"Unlicense"
] |
permissive
|
thinkAmi-sandbox/syakyo-router_jisaku
|
b8070494a5fc62b576200cae96eb9c09599f4f41
|
295e4df3cf65ce0275f40884027ff8aaff381dd4
|
refs/heads/master
| 2021-09-03T07:32:08.995618
| 2018-01-07T03:19:15
| 2018-01-07T03:19:15
| 115,960,241
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 930
|
py
|
# -*- coding: utf-8 -*-
from scapy.all import conf
import concurrent.futures
def bridge_from_eth0_to_eth1():
eth0_socket = conf.L2socket(iface='eth0')
eth1_socket = conf.L2socket(iface='eth1')
while True:
p = eth0_socket.recv()
if p:
eth1_socket.send(p.original)
def bridge_from_eth1_to_eth0():
eth0_socket = conf.L2socket(iface='eth0')
eth1_socket = conf.L2socket(iface='eth1')
while True:
p = eth1_socket.recv()
if p:
eth0_socket.send(p.original)
def bridge():
try:
# スレッドを用意
executor = concurrent.futures.ThreadPoolExecutor(max_workers=3)
executor.submit(bridge_from_eth0_to_eth1)
executor.submit(bridge_from_eth1_to_eth0)
except KeyboardInterrupt:
# threadingと異なり、特に何もしなくてもCtrl + C が可能
pass
if __name__ == '__main__':
bridge()
|
[
"dev.thinkami@gmail.com"
] |
dev.thinkami@gmail.com
|
61576ee9ff5f75ea088469328816acfcc2fd48b8
|
f0d583a064cc53510d8b00b42ac869832e70bf41
|
/nearl/convolutions.py
|
8904603be480f804d66ed61426d0d836ea09e435
|
[] |
no_license
|
PaulZoni/nn
|
918d543b4b2d955ff991da70ce4e88d4d94d13c8
|
25a81579499c893584b040f536ddbef254197f4e
|
refs/heads/master
| 2020-04-27T19:05:10.968050
| 2019-06-27T12:22:16
| 2019-06-27T12:22:16
| 174,564,933
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,153
|
py
|
from skimage.exposure import rescale_intensity
import numpy as np
import argparse
import cv2
def convolve(image, K):
(iH, iW) = image.shape[:2]
(kH, kW) = K.shape[:2]
pad = (kW - 1) // 2
image = cv2.copyMakeBorder(image, pad, pad, pad, pad,
cv2.BORDER_REPLICATE)
output = np.zeros((iH, iW), dtype="float")
for y in np.arange(pad, iH + pad):
for x in np.arange(pad, iW + pad):
roi = image[y - pad:y + pad + 1, x - pad:x + pad + 1]
k = (roi * K).sum()
output[y - pad, x - pad] = k
output = rescale_intensity(output, in_range=(0, 255))
output = (output * 255).astype("uint8")
return output
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=False, help="path to the input image",
default="/home/pavel/Изображения/dog.jpg")
args = vars(ap.parse_args())
smallBlur = np.ones((7, 7), dtype="float") * (1.0 / (7 * 7))
largeBlur = np.ones((21, 21), dtype="float") * (1.0 / (21 * 21))
sharpen = np.array((
[0, -1, 0],
[-1, 5, -1],
[0, -1, 0]), dtype="int")
laplacian = np.array((
[0, 1, 0],
[1, -4, 1],
[0, 1, 0]), dtype="int")
sobelX = np.array((
[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]), dtype="int")
sobelY = np.array((
[-1, -2, -1],
[0, 0, 0],
[1, 2, 1]), dtype="int")
emboss = np.array((
[-2, -1, 0],
[-1, 1, 1],
[0, 1, 2]), dtype="int")
kernelBank = (
("small_blur", smallBlur),
("large_blur", largeBlur),
("sharpen", sharpen),
("laplacian", laplacian),
("sobel_x", sobelX),
("sobel_y", sobelY),
("emboss", emboss))
image = cv2.imread(args["image"])
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
for (kernelName, K) in kernelBank:
print("[INFO] applying {} kernel".format(kernelName))
convolveOutput = convolve(gray, K)
opencvOutput = cv2.filter2D(gray, -1, K)
cv2.imshow("Original", gray)
cv2.imshow("{} - convole".format(kernelName), convolveOutput)
cv2.imshow("{} - opencv".format(kernelName), opencvOutput)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
[
"polykovpavel23@gmail.com"
] |
polykovpavel23@gmail.com
|
3f0f1dcc0fbb8c2b8add0c757387a982bca2cbaf
|
f0d713996eb095bcdc701f3fab0a8110b8541cbb
|
/iBL3eDRWzpxgfQyHx_3.py
|
e27280148842b79a6e873bc4c39cde8d6161a12a
|
[] |
no_license
|
daniel-reich/turbo-robot
|
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
|
a7a25c63097674c0a81675eed7e6b763785f1c41
|
refs/heads/main
| 2023-03-26T01:55:14.210264
| 2021-03-23T16:08:01
| 2021-03-23T16:08:01
| 350,773,815
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 363
|
py
|
"""
Fix the code in the **Code** tab so the function returns `true` _if and only
if_ `x` is equal to `7`. Try to debug code and pass all the tests.
### Examples
is_seven(4) ➞ False
is_seven(9) ➞ False
is_seven(7) ➞ True
### Notes
The bug can be subtle, so look closely!
"""
def is_seven(x):
return False if x!=7 else True
|
[
"daniel.reich@danielreichs-MacBook-Pro.local"
] |
daniel.reich@danielreichs-MacBook-Pro.local
|
fa17aaf115da2b9fef1951a840b2557fca760856
|
9645bdfbb15742e0d94e3327f94471663f32061a
|
/Python/844 - Backspace String Compare/844_backspace-string-compare.py
|
e1471d752b7544301a87dd7b7b8a38438f4cdf93
|
[] |
no_license
|
aptend/leetcode-rua
|
f81c080b2260adb2da677612e5c437eda256781d
|
80e44f4e9d3a5b592fdebe0bf16d1df54e99991e
|
refs/heads/master
| 2023-06-22T00:40:05.533424
| 2021-03-17T13:51:28
| 2021-03-17T13:51:28
| 186,434,133
| 2
| 0
| null | 2023-06-21T22:12:51
| 2019-05-13T14:17:27
|
HTML
|
UTF-8
|
Python
| false
| false
| 1,715
|
py
|
from leezy import Solution, solution
class Q844(Solution):
@solution
def backspaceCompare(self, S, T):
# 8ms 99.44%
def print_s(s):
stack = []
for ch in s:
if ch == '#':
if stack:
stack.pop()
else:
stack.append(ch)
# str comp is somehow faster
return ''.join(stack)
return print_s(S) == print_s(T)
@solution
def backspace_compare(self, S, T):
# 12ms 95.69%
# every '#' only affects previous positions, so we think to handle from back
i, j = len(S)-1, len(T)-1
sback = tback = 0
while True:
# find the char that will REALLY be printed on the paper
while i >= 0 and S[i] == '#':
i -= 1
sback += 1
while i >= 0 and sback:
sback += 1 if S[i] == '#' else -1
i -= 1
while j >= 0 and T[j] == '#':
j -= 1
tback += 1
while j >= 0 and tback:
tback += 1 if T[j] == '#' else -1
j -= 1
if i >= 0 and j >= 0:
if S[i] == T[j]:
i -= 1
j -= 1
else:
return False
elif i < 0 and j < 0:
return True
else:
return False
def main():
q = Q844()
q.add_args('ab#c', 'ad#c')
q.add_args('ab##', 'c#d##')
q.add_args('z#ab###c', 'ad#c')
q.add_args('z####c##', 'ad#c')
q.run()
if __name__ == "__main__":
main()
|
[
"crescentwhale@hotmail.com"
] |
crescentwhale@hotmail.com
|
c76d6d2e9cca7e7d52dfb5b95ee5a097aa6b684e
|
70aa3b9b80a42930234315f335ca7ab06e87c15d
|
/chapter6/code/vgg.py
|
82c411216bb94b89000d79007c91b9a3edd8525e
|
[
"Apache-2.0"
] |
permissive
|
gvenus/BookSource
|
c0e6c4fbbf5bc69d3dd2bf437f3fdfa734b83234
|
f18fd11f64ac5b400175a0d80a6dd4a393476673
|
refs/heads/master
| 2020-05-27T06:14:46.789134
| 2018-10-08T11:26:46
| 2018-10-08T11:26:46
| 188,516,561
| 1
| 0
| null | 2019-05-25T03:37:08
| 2019-05-25T03:37:08
| null |
UTF-8
|
Python
| false
| false
| 1,691
|
py
|
# coding:utf-8
import paddle.v2 as paddle
# ***********************定义VGG卷积神经网络模型***************************************
def vgg_bn_drop(datadim, type_size):
image = paddle.layer.data(name="image",
type=paddle.data_type.dense_vector(datadim))
def conv_block(ipt, num_filter, groups, dropouts, num_channels=None):
return paddle.networks.img_conv_group(
input=ipt,
num_channels=num_channels,
pool_size=2,
pool_stride=2,
conv_num_filter=[num_filter] * groups,
conv_filter_size=3,
conv_act=paddle.activation.Relu(),
conv_with_batchnorm=True,
conv_batchnorm_drop_rate=dropouts,
pool_type=paddle.pooling.Max())
# 最后一个参数是图像的通道数
conv1 = conv_block(image, 64, 2, [0.0, 0], 1)
conv2 = conv_block(conv1, 128, 2, [0.0, 0])
conv3 = conv_block(conv2, 256, 3, [0.0, 0.0, 0])
conv4 = conv_block(conv3, 512, 3, [0.0, 0.0, 0])
conv5 = conv_block(conv4, 512, 3, [0.0, 0.0, 0])
drop = paddle.layer.dropout(input=conv5, dropout_rate=0.5)
fc1 = paddle.layer.fc(input=drop, size=512, act=paddle.activation.Linear())
bn = paddle.layer.batch_norm(input=fc1,
act=paddle.activation.Relu(),
layer_attr=paddle.attr.Extra(drop_rate=0.0))
fc2 = paddle.layer.fc(input=bn, size=512, act=paddle.activation.Linear())
# 通过Softmax获得分类器
out = paddle.layer.fc(input=fc2,
size=type_size,
act=paddle.activation.Softmax())
return out
|
[
"yeyupiaoling@foxmail.com"
] |
yeyupiaoling@foxmail.com
|
1be3f37b927eb931b4e39d39885b1e9c66cc025f
|
d9a45783aa0dc1fd7528b57fbe73bfd3f1a277cd
|
/08. Exams/Mid Exam - 2 November 2019 Group 2/venv/Scripts/pip-script.py
|
6e6f746c1433b351df37825d7f2fb3e2f75ed566
|
[] |
no_license
|
miaviles/Python-Fundamentals
|
630b9553cbe768b344e199f890e91a5a41d5e141
|
9d6ab06fe9fbdc181bc7871f18447708cb8a33fe
|
refs/heads/master
| 2022-08-22T19:15:18.423296
| 2020-05-25T17:53:16
| 2020-05-25T17:53:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 446
|
py
|
#!"D:\User\Desktop\PythonProjects\Exams\Mid Exam - 2 November 2019 Group 2\venv\Scripts\python.exe"
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip'
__requires__ = 'pip==19.0.3'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('pip==19.0.3', 'console_scripts', 'pip')()
)
|
[
"rossavelrs@yahoo.com"
] |
rossavelrs@yahoo.com
|
ac5de98114ba10d946ab377a66b11b5ea13312d7
|
6e1c0e2e6713af19d5d3c05b432c908137b62a7a
|
/riboviria/mqtt-ping.py
|
ebf838f1ad9e9912ee6284847c868b1074b0a737
|
[
"Apache-2.0"
] |
permissive
|
craigderington/westnile
|
75e81158b2e6494c2717edb1c9046a9461885297
|
0dbc496dfda816cf85b50ea590fa5e693b735c7e
|
refs/heads/master
| 2022-12-13T01:06:57.751396
| 2021-04-08T22:37:28
| 2021-04-08T22:37:28
| 205,703,695
| 0
| 0
|
Apache-2.0
| 2022-12-08T06:06:07
| 2019-09-01T16:34:02
|
Python
|
UTF-8
|
Python
| false
| false
| 5,948
|
py
|
#! c:\python34\python.exe
#!/usr/bin/env python
##demo code provided by Steve Cope at www.steves-internet-guide.com
##email steve@steves-internet-guide.com
##Free to use for any purpose
##If you like and use this code you can
##buy me a drink here https://www.paypal.me/StepenCope
"""
mqtt pinger
"""
import paho.mqtt.client as mqtt
import time
import json
##user can edit this data
mqttclient_log=True
max_connection_time=6 # if not connected after this time assume failure
cname="pinger"
msg="ping test:" +cname
topic="pingtest"
broker="loopback"
port=1883
inputs={"broker":broker,"port":port,"topic":"pingtest","loops":\
4,"loop_delay":1,"silent_flag":False,"username":"",\
"password":""}
mqttclient_log=False
##end user editable data
responses=[]
sent=[]
####
def on_connect(client, userdata, flags, rc):
if rc==0:
client.connected_flag=True
print("connected sending ",inputs["loops"]," messages ",\
inputs["loop_delay"]," second Intervals")
else:
client.bad_connection_flag=True
if rc==5:
print("broker requires authentication")
def on_disconnect(client, userdata, rc):
m="disconnecting reason " ,str(rc)
client.connect_flag=False
client.disconnect_flag=True
def on_subscribe(client, userdata, mid, granted_qos):
#print("subscribed ok ")
client.suback_flag=True
def on_publish(client, userdata, mid):
client.puback_flag=True
def on_message(client, userdata, message):
topic=message.topic
msgr=str(message.payload.decode("utf-8"))
responses.append(json.loads(msgr))
client.rmsg_count+=1
client.rmsg_flagset=True
def on_log(client, userdata, level, buf):
print("log: ",buf)
def Initialise_client_object():
mqtt.Client.bad_connection_flag=False
mqtt.Client.suback_flag=False
mqtt.Client.connected_flag=False
mqtt.Client.disconnect_flag=False
mqtt.Client.disconnect_time=0.0
mqtt.Client.disconnect_flagset=False
mqtt.Client.rmsg_flagset=False
mqtt.Client.rmsg_count=0
mqtt.Client.display_msg_count=0
def Initialise_clients(cname):
#flags set
client= mqtt.Client(cname)
if mqttclient_log: #enable mqqt client logging
client.on_log=on_log
client.on_connect= on_connect #attach function to callback
client.on_message=on_message #attach function to callback
client.on_disconnect=on_disconnect
client.on_subscribe=on_subscribe
client.on_publish=on_publish
return client
def get_input(argv):
broker_in=""
port_in=0
topics_in=""
try:
opts, args = getopt.getopt(argv,"h:p:t:c:d:su:P:")
except getopt.GetoptError:
print (sys.argv[0]," -h <broker> -p <port> -t <topic> -c <count> \
-d <delay> -u <username> -P <pasword>-s <silent True>" )
sys.exit(2)
for opt, arg in opts:
if opt == '--help':
print (sys.argv[0]," -h <broker> -p <port> -t <topic> -c <count> \
-d <delay> -u <username> -P <pasword>-s <silent True>" )
sys.exit()
elif opt == "-h":
inputs["broker"] = str(arg)
elif opt =="-t":
inputs["topic"] = str(arg)
elif opt =="-p":
inputs["port"] = int(arg)
elif opt =="-c":
inputs["loops"] = int(arg)
elif opt =="-u":
inputs["username"] = str(arg)
elif opt =="-P":
inputs["password"] = str(arg)
elif opt =="-d":
inputs["loop_delay"] =int(arg)
elif opt == "-s":
inputs["silent_flag"] =True
return((broker_in,port_in,topics_in))
#start
if __name__ == "__main__":
import sys, getopt
if len(sys.argv)>=2:
get_input(sys.argv[1:])
###
Initialise_client_object()#create object flags
client=Initialise_clients(cname)#create client object and set callbacks
if inputs["username"]!="": #set username/password
client.username_pw_set(username=inputs["username"],password=inputs["password"])
print("connecting to broker ",inputs["broker"],"on port ",inputs["port"],\
" topic",inputs["topic"])
try:
res=client.connect(inputs["broker"],inputs["port"]) #establish connection
except:
print("can't connect to broker",inputs["broker"])
sys.exit()
client.loop_start()
tstart=time.time()
while not client.connected_flag and not client.bad_connection_flag:
time.sleep(.25)
if client.bad_connection_flag:
print("connection failure to broker ",inputs["broker"])
client.loop_stop()
sys.exit()
if inputs["silent_flag"]:
print ("Silent Mode is on")
client.subscribe(inputs["topic"])
while not client.suback_flag: #wait for subscribe to be acknowledged
time.sleep(.25)
count=0
tbegin=time.time()
try:
while count<inputs["loops"]:
wait_response_flag=True
client.rmsg_flagset=False
count+=1
m_out=json.dumps((msg,count))
sent.append(m_out)
if not inputs["silent_flag"]:
print("sending:",m_out)
client.publish(inputs["topic"],m_out) #publish
tstart=time.time()
#print("flags " ,wait_response_flag,client.rmsg_flagset)
while wait_response_flag:
if responses and client.rmsg_flagset:
ttrip=time.time()-tstart
if not inputs["silent_flag"]:
print("received:",responses.pop(0),"time= %2.3f"%ttrip)
wait_response_flag=False
time.sleep(inputs["loop_delay"])
except KeyboardInterrupt:
print("interrrupted by keyboard")
tt=time.time()-tbegin
print("Total time= %2.2f" %tt)
print("Total sent=",count)
print("Total received=",client.rmsg_count)
time.sleep(2)
client.disconnect()
client.loop_stop()
time.sleep(2)
|
[
"craig@craigderington.me"
] |
craig@craigderington.me
|
6a6fbc3b7e6a3a9760a73b117d20d87c3e9de4df
|
f445450ac693b466ca20b42f1ac82071d32dd991
|
/generated_tempdir_2019_09_15_163300/generated_part000147.py
|
e8bd4521a04948dde809492ba35369e65d1ee11b
|
[] |
no_license
|
Upabjojr/rubi_generated
|
76e43cbafe70b4e1516fb761cabd9e5257691374
|
cd35e9e51722b04fb159ada3d5811d62a423e429
|
refs/heads/master
| 2020-07-25T17:26:19.227918
| 2019-09-15T15:41:48
| 2019-09-15T15:41:48
| 208,357,412
| 4
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,530
|
py
|
from sympy.abc import *
from matchpy.matching.many_to_one import CommutativeMatcher
from matchpy import *
from matchpy.utils import VariableWithCount
from collections import deque
from multiset import Multiset
from sympy.integrals.rubi.constraints import *
from sympy.integrals.rubi.utility_function import *
from sympy.integrals.rubi.rules.miscellaneous_integration import *
from sympy import *
class CommutativeMatcher40837(CommutativeMatcher):
_instance = None
patterns = {
0: (0, Multiset({0: 1}), [
(VariableWithCount('i2.2.1.2.2.2.1.0', 1, 1, S(1)), Mul)
]),
1: (1, Multiset({}), [
(VariableWithCount('i2.2.1.2.2.2.1.0_1', 1, 1, S(1)), Mul),
(VariableWithCount('i2.2.1.2.2.2.1.1', 1, 1, None), Mul)
])
}
subjects = {}
subjects_by_id = {}
bipartite = BipartiteGraph()
associative = Mul
max_optional_count = 1
anonymous_patterns = set()
def __init__(self):
self.add_subject(None)
@staticmethod
def get():
if CommutativeMatcher40837._instance is None:
CommutativeMatcher40837._instance = CommutativeMatcher40837()
return CommutativeMatcher40837._instance
@staticmethod
def get_match_iter(subject):
subjects = deque([subject]) if subject is not None else deque()
subst0 = Substitution()
# State 40836
if len(subjects) >= 1 and isinstance(subjects[0], Pow):
tmp1 = subjects.popleft()
subjects2 = deque(tmp1._args)
# State 40838
if len(subjects2) >= 1:
tmp3 = subjects2.popleft()
subst1 = Substitution(subst0)
try:
subst1.try_add_variable('i2.2.1.2.2.2.1.1', tmp3)
except ValueError:
pass
else:
pass
# State 40839
if len(subjects2) >= 1 and subjects2[0] == Integer(2):
tmp5 = subjects2.popleft()
# State 40840
if len(subjects2) == 0:
pass
# State 40841
if len(subjects) == 0:
pass
# 0: x**2
yield 0, subst1
subjects2.appendleft(tmp5)
subjects2.appendleft(tmp3)
subjects.appendleft(tmp1)
return
yield
from collections import deque
|
[
"franz.bonazzi@gmail.com"
] |
franz.bonazzi@gmail.com
|
401203770cc2f93e7faaa29cf9e1fd36cbbaa32f
|
6e373b40393fb56be4437c37b9bfd218841333a8
|
/Level_18/Level_3/Level_3/asgi.py
|
f8742930a072809c0359d740818761b659f2518a
|
[] |
no_license
|
mahto4you/Django-Framework
|
6e56ac21fc76b6d0352f004a5969f9d4331defe4
|
ee38453d9eceea93e2c5f3cb6895eb0dce24dc2b
|
refs/heads/master
| 2023-01-22T01:39:21.734613
| 2020-12-04T03:01:17
| 2020-12-04T03:01:17
| 318,383,854
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 391
|
py
|
"""
ASGI config for Level_3 project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Level_3.settings')
application = get_asgi_application()
|
[
"mahto4you@gmail.com"
] |
mahto4you@gmail.com
|
136d4440722f6be8b2f774e356379319276d55fb
|
91d1a6968b90d9d461e9a2ece12b465486e3ccc2
|
/ds_read/trust_list.py
|
d26d454ed09c7e02a796d81fb15423168bae8639
|
[] |
no_license
|
lxtxl/aws_cli
|
c31fc994c9a4296d6bac851e680d5adbf7e93481
|
aaf35df1b7509abf5601d3f09ff1fece482facda
|
refs/heads/master
| 2023-02-06T09:00:33.088379
| 2020-12-27T13:38:45
| 2020-12-27T13:38:45
| 318,686,394
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,243
|
py
|
#!/usr/bin/python
# -*- codding: utf-8 -*-
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from common.execute_command import read_no_parameter
# url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ds/describe-trusts.html
if __name__ == '__main__':
"""
create-trust : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ds/create-trust.html
delete-trust : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ds/delete-trust.html
update-trust : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ds/update-trust.html
verify-trust : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ds/verify-trust.html
"""
add_option_dict = {}
#######################################################################
# setting option use
# ex: add_option_dict["setting_matching_parameter"] = "--owners"
# ex: add_option_dict["setting_key"] = "owner_id"
#######################################################################
# single parameter
# ex: add_option_dict["no_value_parameter_list"] = "--single-parameter"
read_no_parameter("ds", "describe-trusts", add_option_dict)
|
[
"hcseo77@gmail.com"
] |
hcseo77@gmail.com
|
4f39da7e6a56aec71dd90546a3eaa8dd922c328a
|
3d76e2e4e1abc66ab0d55e9fe878da12fd6255ab
|
/rhinoscripts/GetMap.py
|
f117e93c148239aaf8b3e56a99d7409bc6443b1c
|
[] |
no_license
|
localcode/localcode
|
f863aaefa3e0ef25862be05c8ec2bd935805775e
|
3089aee227d257adc856021a4e1eb678d9527f50
|
refs/heads/master
| 2021-01-22T11:38:36.801103
| 2011-12-07T20:52:09
| 2011-12-07T20:52:09
| 2,935,478
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,081
|
py
|
# Written by Lorenz Lachauer, 28.6.2011
# License: CC-BY-NC-SA
# eat-a-bug.blogspot.com
# This script imports a static map form OpenStreetMaps,
# based on an adress entered by the user
import urllib,urllib2,time
import os, Rhino, scriptcontext
import rhinoscriptsyntax as rs
import re, socket, math
def GetMap():
socket.setdefaulttimeout(10)
filename='c:\\map.jpg' # you migth hve to change this path
street = rs.GetString('Street')
city = rs.GetString('City')
country = rs.GetString('Country')
zoom = rs.GetInteger('Zoom', 17, 1, 19)
rs.UnitSystem(4, True)
url='http://nominatim.openstreetmap.org/search?q='+street+','+city+','+country+'&format=xml'
rs.CurrentView('Top')
try:
xml = urllib.urlopen(url).read()
except:
print 'http://nominatim.openstreetmap.org produced an error'
return
temp = xml[xml.find("lat=")+5:-1]
lat= temp[0:temp.find("'")]
temp = xml[xml.find("lon=")+5:-1]
lng= temp[0:temp.find("'")]
print 'Latitude, Longitude: '+lat+", "+lng
picture_page = 'http://osm-tah-cache.firefishy.com/MapOf/?lat='+lat+'&long='+lng+'&z='+str(zoom)+'&w=1000&h=1000&format=jpeg'
opener1 = urllib2.build_opener()
try:
page1 = opener1.open(picture_page)
my_picture = page1.read()
except:
print 'http://osm-tah-cache.firefishy.com produced an error'
return
try:
fout = open(filename, 'wb')
fout.write(my_picture)
fout.close()
except:
print 'writing of '+path+' produced an error'
return
res = 40075017 * math.cos(float(lat)/180*math.pi) / (256 * 2 ** zoom) *1000
rs.Command('_-BackgroundBitmap Remove _Enter',False)
rs.Command('_-BackgroundBitmap '+filename+' '+str(-res/2)+','+str(-res/2)+',0 '+str(res/2)+','+str(res/2)+',0 _Enter',True)
rs.Command('_-BackgroundBitmap Grayscale=No _Enter', False)
rs.Command('_-EarthAnchorPoint Latitude '+lat+' Longitude '+lng+' _Enter _Enter _Enter _Enter _Enter', False)
GetMap()
|
[
"benjamin.j.golder@gmail.com"
] |
benjamin.j.golder@gmail.com
|
acf3731d1ba76d907697201fbe3d10aef30551e5
|
255e19ddc1bcde0d3d4fe70e01cec9bb724979c9
|
/all-gists/9d7288f70414cd170901/snippet.py
|
4ef0297206b75218d8477b5d7156f3ab7eb75bde
|
[
"MIT"
] |
permissive
|
gistable/gistable
|
26c1e909928ec463026811f69b61619b62f14721
|
665d39a2bd82543d5196555f0801ef8fd4a3ee48
|
refs/heads/master
| 2023-02-17T21:33:55.558398
| 2023-02-11T18:20:10
| 2023-02-11T18:20:10
| 119,861,038
| 76
| 19
| null | 2020-07-26T03:14:55
| 2018-02-01T16:19:24
|
Python
|
UTF-8
|
Python
| false
| false
| 777
|
py
|
#! /usr/bin/env python3
'''(1.196 x STE at 60 ms after the J-point in V3 in mm) + (0.059 x computerized QTc) - (0.326 x R-wave Amplitude in V4 in mm).
Use the calculator below. A value greater than 23.4 is quite sensitive and specific for LAD occlusion.
http://hqmeded-ecg.blogspot.com/2013/06/here-is-link-to-full-text-of-article-in.html'''
import sys
try:
import console
ios = True
except ImportError:
ios = False
ste, qtc, rwave = [float(each) for each in sys.argv[1:]]
score = (1.196 * ste + 0.059 * qtc - 0.326 * rwave) - 23.4
score_string = 'Score: {}'.format(score)
score_message = 'Positive scores are sensitive and specific for LAD occlusion.'
if ios:
console.alert(score_string, score_message)
else:
print(score_string, '\n', score_message)
|
[
"gistshub@gmail.com"
] |
gistshub@gmail.com
|
8bdcc4f7cfa967553a81250d695dd32e60f6eb07
|
9e27f91194541eb36da07420efa53c5c417e8999
|
/twilio/rest/pricing/v2/__init__.py
|
e41e349328afb7633a4ea4c2ed3e2fbcbf2f2b60
|
[] |
no_license
|
iosmichael/flask-admin-dashboard
|
0eeab96add99430828306b691e012ac9beb957ea
|
396d687fd9144d3b0ac04d8047ecf726f7c18fbd
|
refs/heads/master
| 2020-03-24T05:55:42.200377
| 2018-09-17T20:33:42
| 2018-09-17T20:33:42
| 142,508,888
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 943
|
py
|
# coding=utf-8
"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from admin.twilio.base.version import Version
from admin.twilio.rest.pricing.v2.voice import VoiceList
class V2(Version):
def __init__(self, domain):
"""
Initialize the V2 version of Pricing
:returns: V2 version of Pricing
:rtype: twilio.rest.pricing.v2.V2.V2
"""
super(V2, self).__init__(domain)
self.version = 'v2'
self._voice = None
@property
def voice(self):
"""
:rtype: twilio.rest.pricing.v2.voice.VoiceList
"""
if self._voice is None:
self._voice = VoiceList(self)
return self._voice
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Pricing.V2>'
|
[
"michaelliu@iresearch.com.cn"
] |
michaelliu@iresearch.com.cn
|
b3de952ebfad9a2dcddea113de5570690cb125ff
|
28ed6f9c587b8efd27182116ee39984e3856ea6a
|
/pythonBasic/2列表和元组/2.2通用序列操作/2.2.4乘法/乘法.py
|
fccc547755e3ae088e1ec4cbed7bd726f549b691
|
[] |
no_license
|
Fangziqiang/PythonInterfaceTest
|
758c62a0599a9d98179b6e3b402016e0972f2415
|
def37ed36258dfa9790032b0165e35c6278057f0
|
refs/heads/master
| 2020-04-30T07:55:32.725421
| 2019-09-19T08:33:42
| 2019-09-19T08:33:42
| 176,699,735
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 353
|
py
|
#coding=utf-8
# 用数字x乘以一个序列会生成新的序列,而在新的序列中,原来的序列将被重复x次
print "python"*5
# 输出:pythonpythonpythonpythonpython
print [42]*5
# 输出:[42, 42, 42, 42, 42]
# 如果想初始化一个长度为10的列表,可以按照下面的例子来实现:
sequence=[None]*10
print sequence
|
[
"286330540@qq.com"
] |
286330540@qq.com
|
e64b66ecb488c6aef2c7591335ccc40c08f08013
|
3b239e588f2ca6e49a28a63d906dd8dd26173f88
|
/code/run_gtp.py
|
22a8710cdc6285439eca3628c9aee2ea342dd378
|
[] |
no_license
|
Angi16/deep_learning_and_the_game_of_go
|
3bbf4f075f41359b87cb06fe01b4c7af85837c18
|
ba63d5e3f60ec42fa1088921ecf93bdec641fd04
|
refs/heads/master
| 2020-03-23T16:02:47.431241
| 2018-07-21T02:57:16
| 2018-07-21T02:57:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 359
|
py
|
#!/usr/local/bin/python2
from dlgo.gtp import GTPFrontend
from dlgo.agent.predict import load_prediction_agent
from dlgo.agent import termination
import h5py
model_file = h5py.File("agents/betago.hdf5", "r")
agent = load_prediction_agent(model_file)
termination = termination.get("opponent_passes")
frontend = GTPFrontend(agent, termination)
frontend.run()
|
[
"max.pumperla@googlemail.com"
] |
max.pumperla@googlemail.com
|
f99eb4d682177ed04151f93cefcb7d9041dccddd
|
6a4bfed49f65ff74b5c076d19ce8b9a6209754e5
|
/quicksort3.py
|
cb79716efee99c68337998c9753914e989a1cf13
|
[] |
no_license
|
Styfjion/-offer
|
ef4f2f44722ad221e39afa67dd70b3c1453c8b01
|
1f9c311b7775138d8096bf41adbef8a02a129397
|
refs/heads/master
| 2020-05-23T12:04:46.833239
| 2019-05-15T12:21:42
| 2019-05-15T12:21:42
| 186,750,197
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 647
|
py
|
def quick_sort(alist,first,last):
'''快速排序'''
if first >= last:
return
mid_value = alist[first]
low = first
high = last
while low < high :
# high左移
while low < high and alist[high]>= mid_value:
high-=1
alist[low] = alist[high]
while high > low and alist[low]<mid_value:
low+=1
alist[high] = alist[low]
alist[low]=mid_value
quick_sort(alist,first,low-1)
quick_sort(alist,low+1,last)
if __name__=='__main__':
li = [54,26,93,17,77,31,44,55,20]
print(li)
quick_sort(li,0,len(li)-1)
print(li)
|
[
"noreply@github.com"
] |
Styfjion.noreply@github.com
|
0c0d009cc5b976759c50e86d94edf401b1be0d39
|
e1eeec4c9e84f52a14e0c29a1384dfbd60d9f2b4
|
/apps/paintapp.py
|
a9c5c27f02c14ca25b47625410dd904964741044
|
[] |
no_license
|
Yobmod/dmlgames
|
f88583523b6631fa4b1f71e2a98555f1e655b97f
|
952f6416e2f7e9cd268d6a62b3a771839c99f1b0
|
refs/heads/master
| 2022-07-16T23:56:32.449207
| 2020-05-21T14:45:29
| 2020-05-21T14:45:29
| 265,620,729
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,507
|
py
|
from __future__ import annotations
# import kivy
from kivy.app import App
from kivy.graphics import Line, Color, Ellipse
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.widget import Widget
import dotenv
import os
from random import random
from kivy.input import MotionEvent
env = dotenv.load_dotenv('../.env')
KIVY_DATA_DIR = os.environ.get('KIVY_DATA_DIR') or './data'
# KIVY_MODULES_DIR = os.environ['KIVY_DATA_DIR'] or './modules'
class LoginScreen(GridLayout):
""""""
def __init__(self, **kwargs: object) -> None:
super(LoginScreen, self).__init__(**kwargs)
self.cols = 2
self.add_widget(Label(text="Username: "))
self.username = TextInput(multiline=False)
self.add_widget(self.username)
self.add_widget(Label(text="Password: "))
self.password = TextInput(multiline=False, password=True)
self.add_widget(self.password)
self.add_widget(Label(text="Two Factor Auth: "))
self.tfa = TextInput(multiline=False)
self.add_widget(self.tfa)
class PaintWidget(Widget):
def on_touch_down(self, touch: MotionEvent) -> None:
# print(touch)
with self.canvas:
color = (random(), 1.0, 1.0)
Color(*color, mode='hsv') # default mode='rgb'
# color = (random(), random(), random())
# Color(*color, mode='rgb') # default mode='rgb'
d = 30.0
Ellipse(pos=(touch.x - d / 2, touch.y - d / 2), size=(d, d))
touch.ud['line'] = Line(points=(touch.x, touch.y))
def on_touch_move(self, touch: MotionEvent) -> None:
# print(touch)
touch.ud["line"].points += (touch.x, touch.y)
def on_touch_up(self, touch: MotionEvent) -> None:
# print("Released", touch)
with self.canvas:
d = 30.0
Ellipse(pos=(touch.x - d / 2, touch.y - d / 2), size=(d, d))
class PaintApp(App):
""""""
def build(self) -> Widget:
# return LoginScreen()
parent: Widget = Widget()
self.painter = PaintWidget()
clearbtn = Button(text='Clear')
clearbtn.bind(on_release=self.clear_canvas)
parent.add_widget(self.painter)
parent.add_widget(clearbtn)
return parent
def clear_canvas(self, obj: Button) -> None:
self.painter.canvas.clear()
if __name__ == "__main__":
PaintApp().run()
|
[
"yobmod@gmail.com"
] |
yobmod@gmail.com
|
1970df72902b0a82e5c6714a75f174d5dc12f140
|
300cb04e51274541611efec5cb8e06d9994f7f66
|
/Bai4.py
|
22c15634333a611bab3d437c56890a831f99ee97
|
[] |
no_license
|
thuongtran1210/Buoi1
|
b77c2a40d0107506cbd4bff12336e006942e9ff6
|
d1c6240e60c10606bc430cd86ec473e3f11027f4
|
refs/heads/master
| 2022-12-16T19:49:40.028110
| 2020-09-24T17:16:13
| 2020-09-24T17:16:13
| 295,476,239
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 203
|
py
|
pi=3.14
print("Nhập chiều dài bán kính hình tròn: ",end='')
r=float(input())
cv=r*2*pi
dt=r*r*pi
print("Hình tròn có chu vi là: "+str(cv))
print("Hình tròn có diện tích là: "+str(dt))
|
[
"you@example.com"
] |
you@example.com
|
01fa7e142fd2ebb49b922ab2250b16e3ae2a44bd
|
dce0807fa8587e676d56bd36871cfcc98550619c
|
/python/docs/conf.py
|
591636a9a861622b80bd49ae3b38df0d4fbbd06e
|
[
"BSD-3-Clause"
] |
permissive
|
ZigmundRat/spidriver
|
ca45993342ac2f3b134dbb37b686550318383846
|
9f3a7e75d55eea425eae03529680e6f7302cc042
|
refs/heads/master
| 2023-03-02T17:17:56.127183
| 2023-02-07T22:59:32
| 2023-02-07T22:59:32
| 153,183,836
| 0
| 0
|
BSD-3-Clause
| 2021-02-12T21:48:19
| 2018-10-15T21:25:51
|
Python
|
UTF-8
|
Python
| false
| false
| 2,023
|
py
|
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import sys
import os
sys.path.insert(0, os.path.abspath('..'))
# -- Project information -----------------------------------------------------
project = 'spidriver'
copyright = '2021, Excamera Labs'
author = 'James Bowman'
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
"sphinx_rtd_theme",
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx"
]
intersphinx_mapping = {'https://docs.python.org/3/': None}
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
master_doc = 'index'
|
[
"jamesb@excamera.com"
] |
jamesb@excamera.com
|
19573ae17cac9b95b5c1c8e0d9dfc26b363993a8
|
0ceaad883368e250a8cc9d54dd3df6c82f550983
|
/826/test.py
|
98e8cfce3fb41c391831dd25293c29056c6d2719
|
[] |
no_license
|
tarp20/LeetCode
|
ae6b5a3838308156ea24a678c63992acb0528fa9
|
551a76714306d4ae9663718b5ce0769c7356e152
|
refs/heads/main
| 2023-03-06T03:48:54.924494
| 2021-02-16T14:38:00
| 2021-02-16T14:38:00
| 337,395,859
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 603
|
py
|
import collections
difficulty = [3, 5, 9, 2, 3]
workers = [3, 9, 5]
profit = [6, 10, 18, 4, 6]
a = collections.defaultdict(int)
def maxProfitAssignment(difficulty, profit, worker):
diffPro = collections.defaultdict(int)
for diff, pro in zip(difficulty, profit):
diffPro[diff] = max(diffPro[diff], pro)
maxVal = 0
for x in range(min(difficulty + worker), max(difficulty + worker) + 1):
diffPro[x] = max(diffPro[x], maxVal)
maxVal = max(diffPro[x], maxVal)
return sum(diffPro[w] for w in worker)
print(maxProfitAssignment(difficulty, profit, workers))
|
[
"taras.piont@gmail.com"
] |
taras.piont@gmail.com
|
bb1484bc3df7792baec606d0259c65f2711a1bb6
|
a8c0867109974ff7586597fe2c58521277ab9d4d
|
/LC90.py
|
9d8341d685661f5f3d24ef3401b4bcb15fa0cba8
|
[] |
no_license
|
Qiao-Liang/LeetCode
|
1491b01d2ddf11495fbc23a65bb6ecb74ac1cee2
|
dbdb227e12f329e4ca064b338f1fbdca42f3a848
|
refs/heads/master
| 2023-05-06T15:00:58.939626
| 2021-04-21T06:30:33
| 2021-04-21T06:30:33
| 82,885,950
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 628
|
py
|
class Solution(object):
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
result = [[], [nums[0]]]
add_len = 1
for idx in range(1, len(nums)):
if nums[idx] == nums[idx - 1]:
result.extend([elem + [nums[idx]] for elem in result[-add_len:]])
else:
add_len = len(result)
result.extend([elem + [nums[idx]] for elem in result])
return result
sol = Solution()
# nums = [1, 2, 2, 3, 3]
nums = [1, 1, 2]
print(sol.subsetsWithDup(nums))
|
[
"qiaoliang@Qiaos-MacBook-Pro.local"
] |
qiaoliang@Qiaos-MacBook-Pro.local
|
99cff29f8d6ff23f00550202608b54f8610bd70c
|
aa9a0acc85a7328969a81527f3ed7c155a245727
|
/chapter_13/Alien_Invasion/bullet.py
|
26d4391e22fdf97246f3cabb1eb2a814f1b590b8
|
[] |
no_license
|
mwnickerson/python-crash-course
|
7035e21e1ee60c05d1d475ebcf04bd6a93c5967a
|
18784c7e3abfb74f85f8c96cb0f8e606cab6dccc
|
refs/heads/main
| 2023-08-03T20:14:49.883626
| 2021-09-25T05:31:12
| 2021-09-25T05:31:12
| 400,644,375
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,048
|
py
|
# bullet class
import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
"""class to manage bullets fired from the ship"""
def __init__(self, ai_game):
"""create a bullet object at the ship's current position"""
super().__init__()
self.screen = ai_game.screen
self.settings = ai_game.settings
self.color = self.settings.bullet_color
# create a bullet rect at (0,0) and then set correct position
self.rect = pygame.Rect(0, 0, self.settings.bullet_width,
self.settings.bullet_height)
self.rect.midtop = ai_game.ship.rect.midtop
# store the bullet's position as a decimal value
self.y = float(self.rect.y)
def update(self):
"""move the bullet up the screen"""
self.y -= self.settings.bullet_speed
# update the rect position
self.rect.y = self.y
def draw_bullet(self):
"""draw the bullet to the screen"""
pygame.draw.rect(self.screen, self.color, self.rect)
|
[
"82531659+mwnickerson@users.noreply.github.com"
] |
82531659+mwnickerson@users.noreply.github.com
|
a11d1ec99d2df46d06b650b72e04650e59b214ac
|
a3d3fc52912e7a15ef03bda17acfc191a4536a07
|
/arcade/examples/isometric_example.py
|
3a25b2406c1cd8e8a58a921a2fb752fe6ea007ed
|
[
"MIT"
] |
permissive
|
yasoob/arcade
|
533a41ce3153ef711005ab02d3501b41a83e50aa
|
5ef4858e09cf239f2808492ead8c1dd8fd6d47eb
|
refs/heads/master
| 2020-08-21T19:23:25.886055
| 2019-10-18T21:36:36
| 2019-10-18T21:36:36
| 216,228,521
| 0
| 0
|
NOASSERTION
| 2019-10-19T15:33:19
| 2019-10-19T15:33:19
| null |
UTF-8
|
Python
| false
| false
| 6,600
|
py
|
"""
Example of displaying an isometric map.
Isometric map created with Tiled Map Editor: https://www.mapeditor.org/
Tiles by Kenney: http://kenney.nl/assets/isometric-dungeon-tiles
If Python and Arcade are installed, this example can be run from the command line with:
python -m arcade.examples.isometric_example
"""
import arcade
import os
SPRITE_SCALING = 0.5
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_TITLE = "Isometric Example"
# How many pixels to keep as a minimum margin between the character
# and the edge of the screen.
VIEWPORT_MARGIN = 200
MOVEMENT_SPEED = 5
def read_sprite_list(grid, sprite_list):
for row in grid:
for grid_location in row:
if grid_location.tile is not None:
tile_sprite = arcade.Sprite(grid_location.tile.source, SPRITE_SCALING)
tile_sprite.center_x = grid_location.center_x * SPRITE_SCALING
tile_sprite.center_y = grid_location.center_y * SPRITE_SCALING
# print(f"{grid_location.tile.source} -- ({tile_sprite.center_x:4}, {tile_sprite.center_y:4})")
sprite_list.append(tile_sprite)
class MyGame(arcade.Window):
""" Main application class. """
def __init__(self, width, height, title):
"""
Initializer
"""
super().__init__(width, height, title)
# Set the working directory (where we expect to find files) to the same
# directory this .py file is in. You can leave this out of your own
# code, but it is needed to easily run the examples using "python -m"
# as mentioned at the top of this program.
file_path = os.path.dirname(os.path.abspath(__file__))
os.chdir(file_path)
# Sprite lists
self.all_sprites_list = None
# Set up the player
self.player_sprite = None
self.wall_list = None
self.floor_list = None
self.objects_list = None
self.player_list = None
self.view_bottom = 0
self.view_left = 0
self.my_map = None
def setup(self):
""" Set up the game and initialize the variables. """
# Sprite lists
self.player_list = arcade.SpriteList()
self.wall_list = arcade.SpriteList()
self.floor_list = arcade.SpriteList()
self.objects_list = arcade.SpriteList()
# noinspection PyDeprecation
self.my_map = arcade.read_tiled_map('dungeon.tmx', SPRITE_SCALING)
# Set up the player
self.player_sprite = arcade.Sprite("images/character.png", 0.4)
px, py = arcade.isometric_grid_to_screen(self.my_map.width // 2,
self.my_map.height // 2,
self.my_map.width,
self.my_map.height,
self.my_map.tilewidth,
self.my_map.tileheight)
self.player_sprite.center_x = px * SPRITE_SCALING
self.player_sprite.center_y = py * SPRITE_SCALING
self.player_list.append(self.player_sprite)
read_sprite_list(self.my_map.layers["Floor"], self.floor_list)
read_sprite_list(self.my_map.layers["Walls"], self.wall_list)
read_sprite_list(self.my_map.layers["Furniture"], self.wall_list)
# Set the background color
if self.my_map.backgroundcolor is None:
arcade.set_background_color(arcade.color.BLACK)
else:
arcade.set_background_color(self.my_map.backgroundcolor)
# Set the viewport boundaries
# These numbers set where we have 'scrolled' to.
self.view_left = 0
self.view_bottom = 0
def on_draw(self):
"""
Render the screen.
"""
# This command has to happen before we start drawing
arcade.start_render()
# Draw all the sprites.
self.floor_list.draw()
self.player_list.draw()
self.wall_list.draw()
def on_key_press(self, key, modifiers):
"""Called whenever a key is pressed. """
if key == arcade.key.UP:
self.player_sprite.change_y = MOVEMENT_SPEED
elif key == arcade.key.DOWN:
self.player_sprite.change_y = -MOVEMENT_SPEED
elif key == arcade.key.LEFT:
self.player_sprite.change_x = -MOVEMENT_SPEED
elif key == arcade.key.RIGHT:
self.player_sprite.change_x = MOVEMENT_SPEED
def on_key_release(self, key, modifiers):
"""Called when the user releases a key. """
if key == arcade.key.UP or key == arcade.key.DOWN:
self.player_sprite.change_y = 0
elif key == arcade.key.LEFT or key == arcade.key.RIGHT:
self.player_sprite.change_x = 0
def update(self, delta_time):
""" Movement and game logic """
# Call update on all sprites (The sprites don't do much in this
# example though.)
self.player_sprite.update()
# --- Manage Scrolling ---
# Track if we need to change the viewport
changed = False
# Scroll left
left_bndry = self.view_left + VIEWPORT_MARGIN
if self.player_sprite.left < left_bndry:
self.view_left -= left_bndry - self.player_sprite.left
changed = True
# Scroll right
right_bndry = self.view_left + SCREEN_WIDTH - VIEWPORT_MARGIN
if self.player_sprite.right > right_bndry:
self.view_left += self.player_sprite.right - right_bndry
changed = True
# Scroll up
top_bndry = self.view_bottom + SCREEN_HEIGHT - VIEWPORT_MARGIN
if self.player_sprite.top > top_bndry:
self.view_bottom += self.player_sprite.top - top_bndry
changed = True
# Scroll down
bottom_bndry = self.view_bottom + VIEWPORT_MARGIN
if self.player_sprite.bottom < bottom_bndry:
self.view_bottom -= bottom_bndry - self.player_sprite.bottom
changed = True
if changed:
self.view_left = int(self.view_left)
self.view_bottom = int(self.view_bottom)
arcade.set_viewport(self.view_left,
SCREEN_WIDTH + self.view_left,
self.view_bottom,
SCREEN_HEIGHT + self.view_bottom)
def main():
""" Main method """
window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
window.setup()
arcade.run()
if __name__ == "__main__":
main()
|
[
"paul@cravenfamily.com"
] |
paul@cravenfamily.com
|
71b070ebe37d27a064ccb16f22272cca112b34c1
|
b3b1bdd2daffd372c97d9d11dc6b100bd688c9b1
|
/src/criterion/divergence.py
|
0b13074345617cecadd3115e367637df3d6eb60f
|
[] |
no_license
|
jasonZhang892/audio_source_separation
|
edc9dffb9a82c45d6fd46372a634b8ea6573f0f3
|
1c29f49349d81962532bfaac29c189208e77e18a
|
refs/heads/main
| 2023-06-06T07:34:59.716291
| 2021-05-25T07:19:14
| 2021-05-25T07:19:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,196
|
py
|
import numpy as np
EPS=1e-12
def kl_divergence(input, target, eps=EPS):
"""
Args:
input (C, *)
Returns:
loss (*)
"""
_input = input + eps
_target = target + eps
ratio = _target / _input
loss = _target * np.log(ratio)
loss = loss.sum(dim=0)
return loss
def is_divergence(input, target, eps=EPS):
"""
Args:
input (*)
"""
_input = input + eps
_target = target + eps
ratio = _target / _input
loss = ratio - np.log(ratio) - 1
return loss
def generalized_kl_divergence(input, target, eps=EPS):
"""
Args:
input (*)
"""
_input = input + eps
_target = target + eps
ratio = _target / _input
loss = _target * np.log(ratio) + _input - _target
return loss
def beta_divergence(input, target, beta=2):
"""
Beta divergence
Args:
input (batch_size, *)
"""
beta_minus1 = beta - 1
assert beta != 0, "Use is_divergence instead."
assert beta_minus1 != 0, "Use generalized_kl_divergence instead."
loss = target * (target**beta_minus1 - input**beta_minus1) / beta_minus1 - (target**beta - input**beta) / beta
return loss
|
[
"40362510+tky823@users.noreply.github.com"
] |
40362510+tky823@users.noreply.github.com
|
5a1d1526babe1aa52c0f2b0fc433efd22a8a5080
|
9b527131c291b735a163226d1daac2397c25b712
|
/Lecture5/activity_sort.py
|
0b3de48ee6555fdc9145628f7045924bdcce0a1e
|
[] |
no_license
|
arnabs542/BigO-Coding-material
|
dbc8895ec6370933069b2e40e0610d4b05dddcf2
|
3b31bddb1240a407aa22f8eec78956d06b42efbc
|
refs/heads/master
| 2022-03-19T18:32:53.667852
| 2019-11-27T23:55:04
| 2019-11-27T23:55:04
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 596
|
py
|
class Activity:
def __init__(self, start, finish):
self.start = start
self.finish = finish
def activity_selection(a):
a.sort(key=lambda activity: activity.finish)
i = 0
res.append(a[0])
for j in range(1, len(a)):
if a[j].start >= a[i].finish:
res.append(a[j])
i = j
def print_activities(result):
for activity in result:
print('{} - {}'.format(activity.start, activity.finish))
if __name__ == '__main__':
a = []
res = []
n = int(input())
for i in range(n):
s, f = map(int, input().split())
a.append(Activity(s, f))
activity_selection(a)
print_activities(res)
|
[
"tranhoangkhuongvn@gmail.com"
] |
tranhoangkhuongvn@gmail.com
|
6aeb485e5f218bf264cd0085a6de182171b62a9e
|
5e8d86f6ddfd516b9768e8617ced0baca8112f4c
|
/core-python/Core_Python/csvfile/FinalAssessment_CSV.py
|
14c8146f4b97477600694bda120bf1e7ee0c9dcd
|
[
"MIT"
] |
permissive
|
bharat-kadchha/tutorials
|
0a96ce5a3da1a0ceb39a0d464c8f3e2ff397da7c
|
cd77b0373c270eab923a6db5b9f34c52543b8664
|
refs/heads/master
| 2022-12-23T11:49:34.042820
| 2020-10-06T03:51:20
| 2020-10-06T03:51:20
| 272,891,375
| 1
| 0
|
MIT
| 2020-06-17T06:04:33
| 2020-06-17T06:04:33
| null |
UTF-8
|
Python
| false
| false
| 1,195
|
py
|
import csv, os
# change your parent dir accordingly
parent_dir = "E:/GitHub/1) Git_Tutorials_Repo_Projects/core-python/Core_Python/ExCsvFiles"
def read_employees(csv_file_location):
csv.register_dialect('empDialect', skipinitialspace=True, strict=True)
employee_file = csv.DictReader(open(csv_file_location), dialect='empDialect')
employee_list = []
for data in employee_file:
employee_list.append(data)
return employee_list
def process_data(employee_list):
department_list = []
for employee_data in employee_list:
department_list.append(employee_data['Department'])
department_data = {}
for department_name in set(department_list):
department_data[department_name] = department_list.count(department_name)
return department_data
def write_report(dictionary, report_file):
with open(report_file, "w+") as f:
for k in sorted(dictionary):
f.write(str(k) + ':' + str(dictionary[k]) + '\n')
employee_list = read_employees(os.path.join(parent_dir,'Employees.csv'))
dictionary = process_data(employee_list)
write_report(dictionary, os.path.join(parent_dir,'Report.txt'))
print("Report Generated Suuccesfully")
|
[
"deeppatel.dd@gmail.com"
] |
deeppatel.dd@gmail.com
|
5b918c1178365622b9af53d1dba706c1fe65ecc0
|
41cd1bcff0166ed3aab28a183a2837adaa2d9a07
|
/allauth/socialaccount/providers/openid/models.py
|
9103b37e93f41b94d02b6bbbb938e9389ebdf298
|
[
"MIT"
] |
permissive
|
thomaspurchas/django-allauth
|
694dde8615b90cd4768e7f9eda79fdcf6fe3cdb6
|
d7a8b9e13456180648450431057a206afa689373
|
refs/heads/master
| 2022-02-04T03:18:25.851391
| 2013-05-20T11:26:55
| 2013-05-20T11:26:55
| 7,754,028
| 1
| 0
|
MIT
| 2022-02-01T23:04:02
| 2013-01-22T14:44:56
|
Python
|
UTF-8
|
Python
| false
| false
| 755
|
py
|
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class OpenIDStore(models.Model):
server_url = models.CharField(max_length=255)
handle = models.CharField(max_length=255)
secret = models.TextField()
issued = models.IntegerField()
lifetime = models.IntegerField()
assoc_type = models.TextField()
def __str__(self):
return self.server_url
@python_2_unicode_compatible
class OpenIDNonce(models.Model):
server_url = models.CharField(max_length=255)
timestamp = models.IntegerField()
salt = models.CharField(max_length=255)
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.server_url
|
[
"raymond.penners@intenct.nl"
] |
raymond.penners@intenct.nl
|
fbae567a999df749f8ce0f277919dae770888389
|
55c250525bd7198ac905b1f2f86d16a44f73e03a
|
/Python/Detectron/tools/generate_testdev_from_test.py
|
1613d2313d82d50ece48e2e046b19b7f79711bdd
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
NateWeiler/Resources
|
213d18ba86f7cc9d845741b8571b9e2c2c6be916
|
bd4a8a82a3e83a381c97d19e5df42cbababfc66c
|
refs/heads/master
| 2023-09-03T17:50:31.937137
| 2023-08-28T23:50:57
| 2023-08-28T23:50:57
| 267,368,545
| 2
| 1
| null | 2022-09-08T15:20:18
| 2020-05-27T16:18:17
| null |
UTF-8
|
Python
| false
| false
| 129
|
py
|
version https://git-lfs.github.com/spec/v1
oid sha256:9683898a2074bbd67574a333a6c8d61a3e5cb1ab42b6e728fab7477d6670f1ce
size 3243
|
[
"nateweiler84@gmail.com"
] |
nateweiler84@gmail.com
|
4c144aed67166564a3d15f170ade14626dc5a098
|
46d8a9446d9f52136736cdeb54f7fc7a23639f10
|
/ppasr/model_utils/deepspeech2/model.py
|
30ae326f08d9c7597c22f54bb040653bd172fa2b
|
[
"Apache-2.0"
] |
permissive
|
buyersystem/PPASR
|
19b23ff490cdab79fdaa43c0eea4af8ca9b4787d
|
73edad5e136bf606b0a9b429a09a41716079afd1
|
refs/heads/master
| 2023-08-28T06:15:50.724115
| 2021-10-27T09:57:20
| 2021-10-27T09:57:20
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,847
|
py
|
from paddle import nn
from ppasr.model_utils.deepspeech2.conv import ConvStack
from ppasr.model_utils.deepspeech2.rnn import RNNStack
__all__ = ['DeepSpeech2Model']
class DeepSpeech2Model(nn.Layer):
"""DeepSpeech2模型结构
:param feat_size: 输入的特征大小
:type feat_size: int
:param vocab_size: 字典的大小,用来分类输出
:type vocab_size: int
:param num_conv_layers: 堆叠卷积层数
:type num_conv_layers: int
:param num_rnn_layers: 堆叠RNN层数
:type num_rnn_layers: int
:param rnn_size: RNN层大小
:type rnn_size: int
:return: DeepSpeech2模型
:rtype: nn.Layer
"""
def __init__(self, feat_size, vocab_size, num_conv_layers=3, num_rnn_layers=3, rnn_size=1024):
super().__init__()
# 卷积层堆
self.conv = ConvStack(feat_size, num_conv_layers)
# RNN层堆
i_size = self.conv.output_height
self.rnn = RNNStack(i_size=i_size, h_size=rnn_size, num_stacks=num_rnn_layers)
# 分类输入层
self.bn = nn.BatchNorm1D(rnn_size * 2, data_format='NLC')
self.fc = nn.Linear(rnn_size * 2, vocab_size)
def forward(self, audio, audio_len):
"""
Args:
audio (Tensor): [B, D, Tmax]
audio_len (Tensor): [B, Umax]
Returns:
logits (Tensor): [B, T, D]
x_lens (Tensor): [B]
"""
# [B, D, T] -> [B, C=1, D, T]
x = audio.unsqueeze(1)
x, x_lens = self.conv(x, audio_len)
# 将数据从卷积特征映射转换为向量序列
x = x.transpose([0, 3, 1, 2]) # [B, T, C, D]
x = x.reshape([0, 0, -1]) # [B, T, C*D]
# 删除填充部分
x = self.rnn(x, x_lens) # [B, T, D]
x = self.bn(x)
logits = self.fc(x)
return logits, x_lens
|
[
"yeyupiaoling@foxmail.com"
] |
yeyupiaoling@foxmail.com
|
496e630dfed3f36556a00508c7fe6aacb46501f0
|
ba895ee2765b60ddf2da15307f038c6a884da4ec
|
/month02/day15/ftp/tcp_client.py
|
751a0c6cd45e84de2df6f55247a2d865a3c382a1
|
[] |
no_license
|
jay0613/2020-0720-note
|
dc53831b829f7e7437fc57937eef38ab9e3942e9
|
7b2babd30a4dd9897b7853527a07e8a8fe2ba3ea
|
refs/heads/master
| 2022-12-06T17:01:19.542832
| 2020-08-22T10:39:06
| 2020-08-22T10:39:06
| 281,112,932
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,350
|
py
|
from socket import *
from time import sleep
ADDR = ("124.70.187.114",8888)
dir = "/home/tarena/month02/day15/ftp/"
class FTPClient():
def __init__(self,s):
super().__init__()
self.s = s
def do_list(self):
self.s.send("LIST".encode())
data = self.s.recv(128).decode()
if data =="OK":
file = self.s.recv(1024).decode()
print(file)
else:
print("文件库为空!")
def do_get(self,filename):
data = "RETR "+filename
self.s.send(data.encode())
result = self.s.recv(128)
if result.decode() == "OK":
f = open(dir + filename, "wb")
while True:
data = self.s.recv(1024)
if data == b"##":
break
f.write(data)
f.close()
else:
print("文件不存在!")
def do_put(self, filename):
data = "STOR "+filename
self.s.send(data.encode())
result = self.s.recv(1024)
if result == b"OK":
try:
f = open(dir+filename,"rb")
except:
print("该文件不存在!")
self.s.send(b"NO")
return
else:
while True:
data = f.read(1024)
if not data:
sleep(0.1)
self.s.send(b"##")
break
self.s.send(data)
f.close()
else:
print("文件已存在!")
def main():
s = socket(AF_INET,SOCK_STREAM)
s.connect(ADDR)
t = FTPClient(s)
while True:
print("============ 命令选项==============")
print("*** list ***")
print("*** get file ***")
print("*** put file ***")
print("*** exit ***")
print("==================================")
cmd = input("请输入命令:")
if cmd == "list":
t.do_list()
elif cmd[:3] == "get":
filename = cmd.split(" ")[-1]
t.do_get(filename)
elif cmd[:3] == "put":
filename = cmd.split(" ")[-1]
t.do_put(filename)
if __name__ == '__main__':
main()
|
[
"240110075@qq.com"
] |
240110075@qq.com
|
273de56721095e1a544df0c7125213c4ee89326c
|
d043a51ff0ca2f9fb3943c3f0ea21c61055358e9
|
/python3网络爬虫开发实战/Xpath/xpath1.py
|
2cfe82c6a2a22b29961311f089129e8ab0fdd732
|
[] |
no_license
|
lj1064201288/dell_python
|
2f7fd9dbcd91174d66a2107c7b7f7a47dff4a4d5
|
529985e0e04b9bde2c9e0873ea7593e338b0a295
|
refs/heads/master
| 2020-03-30T03:51:51.263975
| 2018-12-11T13:21:13
| 2018-12-11T13:21:13
| 150,707,725
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 841
|
py
|
# 导入lxml库的etree模块
from lxml import etree
# 声明一段HTML文本
text = '''
<div>
<ul>
<li class="item-0"><a href="link1.html">first item</a></li>
<li class="item-1"><a href="link2.html">second item</a></li>
<li class="item-inactve"><a href="link3.html">third item</a></li>
<li class="item-1"><a href="link4.html">fourth item</a></li>
<li class="item-0"><a href="link5.html">fifth item</a></li>
<ul>
</div>
'''
# 调用HTML类进行初始化,这样就成功构造了一个XPath解析对象
html = etree.HTML(text)
# 调用tostring()方法即可输出修正后的HTML代码,但是结果是butes类型
result = etree.tostring(html)
# 这里利用decode()方法将其装成str类型
print(result.decode('utf-8'))
html = etree.parse('./text.html', etree.HTMLParser())
result = etree.tostring(html)
print(result.decode('utf-8'))
|
[
"1064201288@qq.com"
] |
1064201288@qq.com
|
e15e7dfe43813e6f6539b4794a7a1eaa7fd966cd
|
7c45efb5a5c66305d7c4ba8994d3b077612df109
|
/friday/apps/users/views.py
|
57b0f5d3deb51bc1e94b7cf72bd56f04d2f251a1
|
[] |
no_license
|
globedasher/django-dojo
|
c245f35b276402b6df6205a8612deb0089d34612
|
dc27d289b8986b4fb910ef42f7bf483c385a3b4e
|
refs/heads/master
| 2020-07-30T04:04:02.054414
| 2018-05-01T04:32:05
| 2018-05-01T04:32:05
| 73,635,951
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,858
|
py
|
from django.shortcuts import render, redirect, HttpResponse
from django.core.urlresolvers import reverse
from django.contrib import messages
import bcrypt
from .models import User
def index(request):
try:
all_users = User.objects.all()
context = { 'all_users': all_users }
return render(request, 'users/index.html', context)
except:
return render(request, 'users/index.html')
"""
The tuple_return in the login and register functions return a true if the email
is cleared by regex match and and User object. If the email is not cleared by
regex, the tuple comes back as false at [0] and an error message at [1].
"""
def login(request):
if request.method == 'POST':
tuple_return = User.objects.login(request.POST['email'],
request.POST['password'])
# tuple_return[0] is false if email didn't pass regex
if tuple_return[0] == False:
messages.error(request, "Login errors:")
# Here, tuple_retun[1] is a list of error messages to flash to user
for item in tuple_return[1]:
messages.error(request, item)
return redirect(reverse('login:index'))
# tuple_return[0] is false if email didn't pass regex
elif tuple_return[0] == True:
request.session['id'] = tuple_return[1].id
request.session['alias'] = tuple_return[1].alias
request.session['name'] = tuple_return[1].name
messages.success(request, "Successful login!")
return redirect(reverse('poke:index'))
else:
messages.error(request, "Incorrect Http request.")
return redirect(reverse('login:index'))
def logout(request):
del request.session['id']
del request.session['alias']
del request.session['name']
return redirect(reverse('login:index'))
def register(request):
if request.method == 'POST':
tuple_return = User.objects.register(request.POST)
# tuple_return[0] is false if email didn't pass regex
if tuple_return[0] == False:
messages.error(request, "Registration errors:")
# Here, tuple_retun[1] is a list of error messages to flash to user
for item in tuple_return[1]:
messages.error(request, item)
return redirect(reverse('login:index'))
# tuple_return[0] is false if email didn't pass regex
elif tuple_return[0] == True:
request.session['id'] = tuple_return[1].id
request.session['alias'] = tuple_return[1].alias
request.session['name'] = tuple_return[1].name
messages.success(request, "Successful registration!")
return redirect(reverse('poke:index'))
else:
messages.error(request, "Incorrect Http request.")
return redirect(reverse('login:index'))
|
[
"globe.dasher@gmail.com"
] |
globe.dasher@gmail.com
|
73fb490420320edf221354588547c2a78de90043
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p03222/s439293787.py
|
607583db9ccf522b5a6afe3b8aea692cb031ffb6
|
[] |
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
| 1,510
|
py
|
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
sys.setrecursionlimit(2147483647)
INF = float('inf')
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007
def fib(n):
a, b = 1, 1
fib_list = [1] * n
for i in range(n - 2):
a, b = a + b, a
fib_list[i + 2] = a
return fib_list
h, w, k = LI()
L = [0] + fib(w + 1)
dp = [[0] * w for _ in range(h + 1)]
dp[0][0] = 1
for i in range(h):
for j in range(w):
dp[i + 1][j - 1] = (dp[i + 1][j - 1] + dp[i][j] * L[j] * L[w - j]) % mod
if j + 1 < w:
dp[i + 1][j + 1] = (dp[i + 1][j + 1] + dp[i][j] * L[j + 1] * L[w - j - 1]) % mod
dp[i + 1][j] = (dp[i + 1][j] + dp[i][j] * L[j + 1] * L[w - j]) % mod
print(dp[-1][k - 1])
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
9bebcc1eb78e239d67cbec9156fcd58d8bda1048
|
bb11350c9f600d0021d81f7f6ee8c2cc5961a5f0
|
/ZKDEMO/01_dule_color_led.py
|
213c3601343a8b57ed3d9346195e481f1dea9bf8
|
[] |
no_license
|
atiger808/raspberry-tutorial
|
045178877a456908aa8ce764aad62159d674ae79
|
e877939fd1c72e09ce20497f08d854872588e1ef
|
refs/heads/master
| 2022-12-25T19:35:08.378370
| 2020-10-14T09:56:15
| 2020-10-14T09:56:15
| 303,970,623
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,306
|
py
|
import RPi.GPIO as GPIO
import time
color = [0xff00, 0x00ff, 0x0ff0, 0xf00f]
Rpin = 12
Gpin = 13
def setup():
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(Rpin, GPIO.OUT)
GPIO.setup(Gpin, GPIO.OUT)
GPIO.output(Rpin,GPIO.LOW)
GPIO.output(Gpin, GPIO.LOW)
global p_R, p_G
p_R = GPIO.PWM(Rpin, 2000)
p_G = GPIO.PWM(Gpin, 2000)
p_R.start(0)
p_G.start(0)
def map(x, in_min, in_max, out_min, out_max):
return (x - in_min)*(out_max - out_min)/(in_max - in_min) + out_min
def setColor(col):
R_val = col >> 8
G_val = col & 0x00ff
R_val = map(R_val, 0, 255, 0, 100)
G_val = map(G_val, 0, 255, 0, 100)
p_R.ChangeDutyCycle(R_val)
p_G.ChangeDutyCycle(G_val)
def bright(x):
GPIO.output(Rpin, 1)
GPIO.output(Gpin, 1)
p_R.ChangeDutyCycle(100)
p_G.ChangeDutyCycle(100)
time.sleep(x)
GPIO.output(Rpin, GPIO.LOW)
GPIO.output(Gpin, GPIO.LOW)
time.sleep(x)
def loop():
while True:
for col in color:
setColor(col)
time.sleep(0.5)
def destroy():
p_R.stop()
p_G.stop()
GPIO.output(Rpin, GPIO.LOW)
GPIO.cleanup()
if __name__ == '__main__':
setup()
time.sleep(5)
try:
loop()
except KeyboardInterrupt:
destroy()
|
[
"atiger0614@163.com"
] |
atiger0614@163.com
|
f47296e7b93017d932670a09a376cf7d21d82114
|
856f43a69bf77e02803cf5ea8723fe5d7c044ae9
|
/pasarkita/urls.py
|
e68645318fa1c599e32d5172f5155cda451d0bf0
|
[] |
no_license
|
yeremiaChris/pasarkitaapp
|
15cf6e21bbe262ac9360f38ab4bc0cd92f563708
|
76d190e2f6bdbf60e07575051f17fc8213cf01c4
|
refs/heads/master
| 2022-11-30T10:39:57.655765
| 2020-07-22T07:58:14
| 2020-07-22T07:58:14
| 279,835,842
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 278
|
py
|
from django.urls import path
from django.contrib.auth import views as view
from . import views
urlpatterns = [
path('', views.index,name='index'),
path('register', views.register,name='register'),
path('tambah-barang', views.tambahBarang,name='tambah-barang'),
]
|
[
"yeremia997@gmail.com"
] |
yeremia997@gmail.com
|
e9f7910d9c8ada08ccb51e63663df4796f5e7d92
|
1857aaf614cba134941b45880f30da8482b7d7b2
|
/api/urls.py
|
2d9524a315813aa4f71505c7983077fa8d2bf1ec
|
[] |
no_license
|
HavingNoFuture/pd-diplom
|
ec92a372a26182d893364dbd16e51ff55208d269
|
849f139d21c2fcd35e0a9f0b4512d09276b73dc5
|
refs/heads/master
| 2020-06-16T18:49:28.804376
| 2019-11-22T15:47:41
| 2019-11-22T15:47:41
| 195,668,884
| 0
| 1
| null | 2019-07-07T15:42:24
| 2019-07-07T15:42:24
| null |
UTF-8
|
Python
| false
| false
| 1,675
|
py
|
"""orders URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from rest_framework import routers
from rest_framework.schemas import get_schema_view
from django.urls import path, include
from api import views
state_detail = views.StateViewSet.as_view({
'get': 'retrieve',
'post': 'update_state_detail',
})
state_list = views.StateViewSet.as_view({
'get': 'list',
'post': 'update_state_list',
})
price_update = views.PriceUpdateViewSet.as_view({
'post': 'update_price',
})
urlpatterns = [
path('', include('djoser.urls')),
path('', include('djoser.urls.authtoken')),
path('partner/state/<int:pk>/', state_detail, name='state-detail'),
path('partner/state/', state_list, name='state-list'),
path('partner/update/', price_update, name='price-update'),
path('openapi', get_schema_view(
title="Shop API",
description="API for all things …",
# version="1.0.0",
urlconf='api.urls'
), name='openapi-schema'),
]
router = routers.SimpleRouter()
router.register(r'partner/order', views.OrderViewSet)
urlpatterns += router.urls
|
[
"alex.erm@yandex.ru"
] |
alex.erm@yandex.ru
|
6fb534f40527aab8cac971d8f3b32dd73637e3d7
|
f0becfb4c3622099ce3af2fad5b831b602c29d47
|
/django/myvenv/bin/epylint
|
803f74f6fb86daa6e4d5a0f62e132c49186b0875
|
[
"MIT"
] |
permissive
|
boostcamp-2020/relay_06
|
9fe7c1c722405d0916b70bb7b734b7c47afff217
|
a2ecfff55572c3dc9262dca5b4b2fc83f9417774
|
refs/heads/master
| 2022-12-02T05:51:04.937920
| 2020-08-21T09:22:44
| 2020-08-21T09:22:44
| 282,153,031
| 4
| 12
|
MIT
| 2022-11-27T01:13:40
| 2020-07-24T07:29:18
|
Python
|
UTF-8
|
Python
| false
| false
| 255
|
#!/Users/kobyunghwa/relay_06/django/myvenv/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from pylint import run_epylint
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(run_epylint())
|
[
"bhko0524@naver.com"
] |
bhko0524@naver.com
|
|
8e8c3eb0849e2651e56d2c0ba0c6382c180a3c9a
|
50ea2988e1c0dd20bee544d9185608446c681c7b
|
/app/snippets/urls/drf_generic_cbv.py
|
4eadb91373042a452e86ad15eb65d3af793d685c
|
[] |
no_license
|
wps9th-mongkyo/drf-tutorial
|
b725c3de77d4bc9c7ce12fa742b967ef6736369d
|
18bd3cede77254a8893c8f429aa4f24afe765ccb
|
refs/heads/master
| 2020-04-06T10:06:18.759284
| 2018-11-14T16:49:07
| 2018-11-14T16:49:07
| 157,368,423
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 312
|
py
|
from django.urls import path
from ..views.drf_generic_cbv import *
from ..views.user import *
urlpatterns = [
path('snippets/', SnippetList.as_view()),
path('snippets/<int:pk>', SnippetDetail.as_view()),
path('users/', UserListView.as_view()),
path('users/<int:pk>', UserDetailView.as_view()),
]
|
[
"dreamong91@gmail.com"
] |
dreamong91@gmail.com
|
8994a33fe39373b23b98f5bffcc40a7cbe8c40bf
|
7f3205f78ae92a5b3341d458449789e38c9e7ede
|
/packages/fetchai/protocols/http/serialization.py
|
533320118e37d64fae8803351f0958a63a256a12
|
[
"Apache-2.0"
] |
permissive
|
greencultureai/agents-aea
|
d9537cf440387cd8e9c29b2451f9f67a4b5c35f2
|
bc4f65fc749e9cd628f3d0f91bba3d522bce82e4
|
refs/heads/master
| 2021-03-07T03:55:31.340188
| 2020-03-09T14:18:13
| 2020-03-09T14:18:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,143
|
py
|
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2020 fetchai
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ------------------------------------------------------------------------------
"""Serialization module for http protocol."""
from typing import cast
from aea.protocols.base import Message
from aea.protocols.base import Serializer
from packages.fetchai.protocols.http import http_pb2
from packages.fetchai.protocols.http.message import HttpMessage
class HttpSerializer(Serializer):
"""Serialization for the 'http' protocol."""
def encode(self, msg: Message) -> bytes:
"""
Encode a 'Http' message into bytes.
:param msg: the message object.
:return: the bytes.
"""
msg = cast(HttpMessage, msg)
http_msg = http_pb2.HttpMessage()
http_msg.message_id = msg.message_id
dialogue_reference = msg.dialogue_reference
http_msg.dialogue_starter_reference = dialogue_reference[0]
http_msg.dialogue_responder_reference = dialogue_reference[1]
http_msg.target = msg.target
performative_id = msg.performative
if performative_id == HttpMessage.Performative.REQUEST:
performative = http_pb2.HttpMessage.Request() # type: ignore
method = msg.method
performative.method = method
url = msg.url
performative.url = url
version = msg.version
performative.version = version
headers = msg.headers
performative.headers = headers
bodyy = msg.bodyy
performative.bodyy = bodyy
http_msg.request.CopyFrom(performative)
elif performative_id == HttpMessage.Performative.RESPONSE:
performative = http_pb2.HttpMessage.Response() # type: ignore
version = msg.version
performative.version = version
status_code = msg.status_code
performative.status_code = status_code
status_text = msg.status_text
performative.status_text = status_text
headers = msg.headers
performative.headers = headers
bodyy = msg.bodyy
performative.bodyy = bodyy
http_msg.response.CopyFrom(performative)
else:
raise ValueError("Performative not valid: {}".format(performative_id))
http_bytes = http_msg.SerializeToString()
return http_bytes
def decode(self, obj: bytes) -> Message:
"""
Decode bytes into a 'Http' message.
:param obj: the bytes object.
:return: the 'Http' message.
"""
http_pb = http_pb2.HttpMessage()
http_pb.ParseFromString(obj)
message_id = http_pb.message_id
dialogue_reference = (
http_pb.dialogue_starter_reference,
http_pb.dialogue_responder_reference,
)
target = http_pb.target
performative = http_pb.WhichOneof("performative")
performative_id = HttpMessage.Performative(str(performative))
performative_content = dict()
if performative_id == HttpMessage.Performative.REQUEST:
method = http_pb.request.method
performative_content["method"] = method
url = http_pb.request.url
performative_content["url"] = url
version = http_pb.request.version
performative_content["version"] = version
headers = http_pb.request.headers
performative_content["headers"] = headers
bodyy = http_pb.request.bodyy
performative_content["bodyy"] = bodyy
elif performative_id == HttpMessage.Performative.RESPONSE:
version = http_pb.response.version
performative_content["version"] = version
status_code = http_pb.response.status_code
performative_content["status_code"] = status_code
status_text = http_pb.response.status_text
performative_content["status_text"] = status_text
headers = http_pb.response.headers
performative_content["headers"] = headers
bodyy = http_pb.response.bodyy
performative_content["bodyy"] = bodyy
else:
raise ValueError("Performative not valid: {}.".format(performative_id))
return HttpMessage(
message_id=message_id,
dialogue_reference=dialogue_reference,
target=target,
performative=performative,
**performative_content
)
|
[
"david.minarsch@googlemail.com"
] |
david.minarsch@googlemail.com
|
dc0d540c206b2cbbf1c166e46318470ac644409b
|
316c473d020f514ae81b7485b10f6556cf914fc0
|
/urllib/parse/demo4.py
|
2b21849b6000934339e662c8417960f368438b53
|
[
"Apache-2.0"
] |
permissive
|
silianpan/seal-spider-demo
|
ca96b12d4b6fff8fe57f8e7822b7c0eb616fc7f3
|
7bdb77465a10a146c4cea8ad5d9ac589c16edd53
|
refs/heads/master
| 2023-06-20T03:47:04.572721
| 2023-05-24T06:27:13
| 2023-05-24T06:27:13
| 189,963,452
| 1
| 1
|
Apache-2.0
| 2022-12-08T03:24:54
| 2019-06-03T08:15:56
|
Python
|
UTF-8
|
Python
| false
| false
| 132
|
py
|
from urllib.parse import urlparse
result = urlparse('http://www.baidu.com/index.html#comment', allow_fragments=False)
print(result)
|
[
"1206284818@qq.com"
] |
1206284818@qq.com
|
2e5487930aa047da633bb9abe095cf99646b32ad
|
53fab060fa262e5d5026e0807d93c75fb81e67b9
|
/backup/user_392/ch24_2019_09_11_13_10_29_212592.py
|
7d5dbd4fe3971f1941fce8860d74aef5c4a84a36
|
[] |
no_license
|
gabriellaec/desoft-analise-exercicios
|
b77c6999424c5ce7e44086a12589a0ad43d6adca
|
01940ab0897aa6005764fc220b900e4d6161d36b
|
refs/heads/main
| 2023-01-31T17:19:42.050628
| 2020-12-16T05:21:31
| 2020-12-16T05:21:31
| 306,735,108
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 212
|
py
|
def classifica_triangulo(a,b,c):
if a==b and a==c:
return 'equilátero'
elif a==b and b==c and a!=c or a==c and b==c and b!=a:
return 'isósceles'
else:
return 'escaleno'
|
[
"you@example.com"
] |
you@example.com
|
0d93dd2e7128c469c539a4bbc00ad886d5180dcb
|
0366bccae8841bbf6ecaad70660aae89bb0f6394
|
/8_Tuples/1_tuple_types.py
|
8bfd986aaff001145630fdba8e0cc3a6ac27ce50
|
[] |
no_license
|
KobiShashs/Python
|
8a5bdddcaef84b455795c5393cbacee5967493f7
|
e748973ad0b3e12c5fb87648783531783282832a
|
refs/heads/master
| 2021-04-05T20:18:57.715805
| 2020-04-02T21:51:44
| 2020-04-02T21:51:44
| 248,597,057
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 151
|
py
|
one_value_tuple = (20)
print(one_value_tuple)
print(type(one_value_tuple))
one_value_tuple = (20,)
print(one_value_tuple)
print(type(one_value_tuple))
|
[
"kobi.shasha@gmail.com"
] |
kobi.shasha@gmail.com
|
d4d21cfed010e88eb85bf3c40848a3fb92c8625b
|
9d278285f2bc899ac93ec887b1c31880ed39bf56
|
/ondoc/cart/migrations/0007_auto_20190326_1349.py
|
34d1c28b4f17a8472690bb6cee2e9a32d2efd8bc
|
[] |
no_license
|
ronit29/docprime
|
945c21f8787387b99e4916cb3ba1618bc2a85034
|
60d4caf6c52a8b70174a1f654bc792d825ba1054
|
refs/heads/master
| 2023-04-01T14:54:10.811765
| 2020-04-07T18:57:34
| 2020-04-07T18:57:34
| 353,953,576
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 500
|
py
|
# Generated by Django 2.0.5 on 2019-03-26 08:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cart', '0006_merge_20190326_1307'),
]
operations = [
migrations.AlterField(
model_name='cart',
name='product_id',
field=models.IntegerField(choices=[(1, 'Doctor Appointment'), (2, 'LAB_PRODUCT_ID'), (3, 'INSURANCE_PRODUCT_ID'), (4, 'SUBSCRIPTION_PLAN_PRODUCT_ID')]),
),
]
|
[
"sonamsinha@policybazaar.com"
] |
sonamsinha@policybazaar.com
|
bc0b53d1af3b5f30447b9706d33fd91793b72d47
|
ce76b3ef70b885d7c354b6ddb8447d111548e0f1
|
/see_day/little_eye_and_fact/government/government_and_day/work_time.py
|
7733864285181ed2b0aca7b41229ba4587d52094
|
[] |
no_license
|
JingkaiTang/github-play
|
9bdca4115eee94a7b5e4ae9d3d6052514729ff21
|
51b550425a91a97480714fe9bc63cb5112f6f729
|
refs/heads/master
| 2021-01-20T20:18:21.249162
| 2016-08-19T07:20:12
| 2016-08-19T07:20:12
| 60,834,519
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 273
|
py
|
#! /usr/bin/env python
def same_point(str_arg):
feel_public_problem_from_few_problem(str_arg)
print('want_last_life')
def feel_public_problem_from_few_problem(str_arg):
print(str_arg)
if __name__ == '__main__':
same_point('know_different_hand_of_time')
|
[
"jingkaitang@gmail.com"
] |
jingkaitang@gmail.com
|
00e165ed69dc9db91fe96614fa3c7a6ff23bd55e
|
6d25434ca8ce03f8fef3247fd4fc3a1707f380fc
|
/[0140][Hard][Word_Break_II]/Word_Break_II.py
|
2abe1aaa6de1356b8dd434ee82f875c245a499e5
|
[] |
no_license
|
sky-dream/LeetCodeProblemsStudy
|
145f620e217f54b5b124de09624c87821a5bea1b
|
e0fde671cdc9e53b83a66632935f98931d729de9
|
refs/heads/master
| 2020-09-13T08:58:30.712604
| 2020-09-09T15:54:06
| 2020-09-09T15:54:06
| 222,716,337
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,529
|
py
|
# -*- coding: utf-8 -*-
# leetcode time cost : 50 ms
# leetcode memory cost : 15 MB
# Time Complexity: O(N*N)
# Space Complexity: O(N)
#solution 1, DFS and memorize
class Solution:
def wordBreak(self, s: str, wordDict: list) -> list:
if not s:
return []
_len, wordDict = len(s), set(wordDict) # 转换成字典用于O(1)判断in
_min, _max = 2147483647, -2147483648 # 记录字典中的单词的最长和最短长度,用于剪枝
for word in wordDict:
_min = min(_min, len(word))
_max = max(_max, len(word))
def dfs(start): # 返回s[start:]能由字典构成的所有句子
if start not in memo:
res = []
for i in range(_min, min(_max, _len-start)+1): # 剪枝,只考虑从最小长度到最大长度查找字典
if s[start: start+i] in wordDict: # 找到了
res.extend(list(map(lambda x: s[start: start+i]+' '+x, dfs(start+i)))) # 添加
memo[start] = res # 加入记忆
return memo[start]
memo = {_len: ['']} # 初始化记忆化存储
return list(map(lambda x: x[:-1], dfs(0))) # 去掉末尾多出的一个空格
def main():
s, wordDict = "catsanddog",["cat","cats","and","sand","dog"] #expect is ["cat sand dog","cats and dog"]
obj = Solution()
result = obj.wordBreak(s, wordDict)
print("return result is :",result)
if __name__ =='__main__':
main()
|
[
"xxm1263476788@126.com"
] |
xxm1263476788@126.com
|
0ffa84d97f57d7a639d5357bce6f193502cc93a4
|
e1787e6b167ffe1e7b03b926422437839f2e0921
|
/permutation.py
|
13ba44ec3745ce092bda40c385ef8aad6ad9ac6b
|
[] |
no_license
|
Kennedy-Njeri/python-Algorithms
|
c86ec3dec0faa02c676200fcad65b2860c4e64b0
|
4e65b6c652ca09beeb4cdde706d14fbfd399eea0
|
refs/heads/master
| 2020-11-29T09:06:35.255011
| 2020-01-17T20:18:14
| 2020-01-17T20:18:14
| 230,075,701
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 445
|
py
|
""""Given two strings write a function to decide if one is a permutation of the other string"""
str_1 = "driving"
str_2 = "drviign"
def is_permutation(str_1, str_2):
str_1 = str_1.replace(" ", "")
str_2 = str_2.replace(" ", "")
if len(str_1) != len(str_2):
return False
for c in str_1:
if c in str_2:
str_2 = str_2.replace(c, "")
return len(str_2) == 0
print (is_permutation(str_1, str_2))
|
[
"mistakenz123@gmail.com"
] |
mistakenz123@gmail.com
|
81a753ffd8cb5baca58b8a2daa8a6d8cc329da19
|
a7b2be4d98565280b9e5bccb62aa26dfe8d780c8
|
/env/bin/django-admin.py
|
62949e376acde185f24655c3dd6df13920323d00
|
[] |
no_license
|
argen87/Shop_market
|
bb354d78ccbaefcbc78eddd9821b392a850ba100
|
07142b1274b707e48842a02f9a95edb603604a2f
|
refs/heads/main
| 2023-05-09T05:36:08.429109
| 2021-06-10T14:46:47
| 2021-06-10T14:46:47
| 375,729,325
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 692
|
py
|
#!/home/argen/PycharmProjects/shop_market/env/bin/python3
# When the django-admin.py deprecation ends, remove this script.
import warnings
from django.core import management
try:
from django.utils.deprecation import RemovedInDjango40Warning
except ImportError:
raise ImportError(
'django-admin.py was deprecated in Django 3.1 and removed in Django '
'4.0. Please manually remove this script from your virtual environment '
'and use django-admin instead.'
)
if __name__ == "__main__":
warnings.warn(
'django-admin.py is deprecated in favor of django-admin.',
RemovedInDjango40Warning,
)
management.execute_from_command_line()
|
[
"you@example.com"
] |
you@example.com
|
c50c6c1e5fec1a82e31eadbc1cc3276ebfb96d9b
|
deefd01b60fb0cfbeb8e8ae483f1d852f897c5f8
|
/listkeeper/devices/migrations/0001_initial.py
|
24af4f2cdc476b212d301d3c324e2886d895361b
|
[] |
no_license
|
andrewgodwin/rfid-inventory
|
c0bb6f9ebe6ba53c3ec19e7ebe38ad4c1b9128c1
|
fdb8b919bc4228049545f8b05773617c7d6690c9
|
refs/heads/master
| 2020-09-22T07:20:18.463709
| 2020-07-05T03:43:02
| 2020-07-05T03:43:02
| 225,102,557
| 30
| 4
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,767
|
py
|
# Generated by Django 3.0 on 2019-12-08 06:30
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [("directory", "0001_initial")]
operations = [
migrations.CreateModel(
name="Device",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"name",
models.CharField(
help_text="Unique-ish device name", max_length=200
),
),
(
"type",
models.CharField(
blank=True, help_text="Device type", max_length=200
),
),
("notes", models.TextField(blank=True)),
("token", models.TextField(blank=True, help_text="Device API token")),
(
"mode",
models.CharField(
choices=[
("passive", "Passive tracking"),
("assigning", "Assigning locations"),
],
default="passive",
help_text="Current device mode",
max_length=32,
),
),
("created", models.DateTimeField(auto_now_add=True)),
("updated", models.DateTimeField(auto_now=True)),
("last_seen", models.DateTimeField(blank=True, null=True)),
(
"location",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
to="directory.Location",
),
),
],
),
migrations.CreateModel(
name="DeviceRead",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"tag",
models.CharField(
help_text="Type prefix, colon, hex value of tag (e.g. epc:f376ce13434a2b)",
max_length=255,
),
),
("created", models.DateTimeField(auto_now_add=True)),
("last_seen", models.DateTimeField()),
("present", models.BooleanField(default=False)),
(
"device",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="reads",
to="devices.Device",
),
),
(
"item",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="device_reads",
to="directory.Item",
),
),
],
options={"unique_together": {("device", "tag")}},
),
]
|
[
"andrew@aeracode.org"
] |
andrew@aeracode.org
|
3fe4b27047341c4a9fcea2e0da355659b238ff8b
|
95d1dd5758076c0a9740d545a6ef2b5e5bb8c120
|
/PY/basic/str_op.py
|
7cec952522cfb4159b5a939c5083c84c679c3d6d
|
[] |
no_license
|
icoding2016/study
|
639cb0ad2fe80f43b6c93c4415dc6e8a11390c85
|
11618c34156544f26b3b27886b55c771305b2328
|
refs/heads/master
| 2023-08-31T14:15:42.796754
| 2023-08-31T05:28:38
| 2023-08-31T05:28:38
| 117,061,872
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,647
|
py
|
longstr1 = ('This is an example of a long string '
'which is devided into multiple lines in the code '
'and use bracket to group into one string (which is required to avoid compiler error)'
'but actually should display in one line.\n')
longstr_in_obj = ('a tuple', 1, 'a long string in a tuple '
'while is splitted into multiple lines in the code, but'
' should display as one line. '
'In this case, the bracket is not required.\n'
)
mlstr = """This is an example of
a multi line string.
This line has 2 space in the lead.
The last line.\n"""
mlstr2 = ('This is another example of a multi line string.\n'
'Which does\'t use triple-quatation,but the \'\\n\' '
'expression to change lines.\n'
' This line has 2 space in the lead.\n'
'The last line.\n')
s='abcd'
# str join
l = [x for x in s]
print(l)
s1=''
print(s1.join(l))
print(s+'x') # >> abcx
print(s.join('x')) # >> x , that's a wrong way to use join
print(''.join(l)) # >> abc, that's a right way to use join,
print('-'.join(l)) # >> a-b-c, that's a right way to use join,
ipsection = ['10','20','1','1']
print('.'.join(ipsection))
# cut a piece off the str
s1 = s[:3] + s[4:] # >> abce
print(s1)
# str format
for i in range(1,11):
for j in range(1,11):
print("{:<6}".format(i*j), end='')
print('')
print('{:b}'.format(10))
for i in range(1,10, 2):
print(i)
# sub string -- in
def subString(s1,s2):
if s1 in s2:
return True
return False
print(subString('abc', 'fullabcd'))
print(subString('abc', 'fullabd'))
s = 'abcdefghijk'
if 'a' in s:
print('a in ',s)
# sub string -- find
def findSubString(s1,s2):
return s2.find(s1)
print(findSubString('abc', 'fullabcd'))
# remove substring from a string
s1='ababcab'
s2='ab'
print('remove ',s2, ' from ',s1, ': ', s1.replace(s2,''))
# convert str to int
s = '123'
print('int for for {} is {}'.format(s, int(s)))
# The better way to format a str
# f'python 3 f format has the best performance'
# e.g.
# var1 = 'v1'
# var2 = 10
# f' some vars: {var1}, {var2} '
#
# >>> import timeit
# >>> timeit.timeit("""name = "Eric"
# ... age = 74
# ... '%s is %s.' % (name, age)""", number = 10000)
# 0.003324444866599663
# >>> timeit.timeit("""name = "Eric"
# ... age = 74
# ... '{} is {}.'.format(name, age)""", number = 10000)
# 0.004242089427570761
# >>> timeit.timeit("""name = "Eric"
# ... age = 74
# ... f'{name} is {age}.'""", number = 10000)
# 0.0024820892040722242
print(longstr1)
print(longstr_in_obj[2])
print(mlstr)
print(mlstr2)
print()
|
[
"icoding2016@gmail.com"
] |
icoding2016@gmail.com
|
fbc5a3e9710da3cffc431b9a658319fa0d4b4578
|
6c860b5a89fcba3dad4e4d8dea9c570262fab901
|
/luggage_calculator_2.py
|
90e5822ff0cb6cb4469581665832e51ede3d9014
|
[] |
no_license
|
momentum-cohort-2019-05/examples
|
e011b0907dce22d1b58612a5e2df2030be98bdd5
|
277a213c2ef8d5499b9eb69e2c4287faac8e6f4e
|
refs/heads/master
| 2022-09-07T21:14:29.409749
| 2019-07-11T20:18:43
| 2019-07-11T20:18:43
| 189,416,951
| 0
| 4
| null | 2022-08-23T17:52:24
| 2019-05-30T13:15:52
|
PLpgSQL
|
UTF-8
|
Python
| false
| false
| 697
|
py
|
# Description
# Ask the user for the weight of the current bag.
# - If the user has no more bags, stop
# - Otherwise, ask again
# Add up the weight of all bags
# If > limit (100 lbs), warn the user
total_weight = 0
weight_limit = 100
while True:
bag_weight_as_str = input(
"How much does your bag weigh in pounds? (Hit Enter if you are done) ")
if bag_weight_as_str == "":
break
bag_weight = int(bag_weight_as_str)
total_weight += bag_weight
print("Your total weight so far is " + str(total_weight) + ".")
if total_weight > weight_limit:
print("Warning! You are over the weight limit by " +
str(total_weight - weight_limit) + " pounds.")
|
[
"clinton@dreisbach.us"
] |
clinton@dreisbach.us
|
26899bb618ab25ea80fd07b6b93e9ea23828318c
|
ef1bf421aca35681574c03014e0c2b92da1e7dca
|
/test/test_modes/test_occurrences.py
|
f9d0d8e717d9872d33f126775173dc825cf599b5
|
[
"MIT"
] |
permissive
|
pyQode/pyqode.core
|
74e67f038455ea8cde2bbc5bd628652c35aff6eb
|
0ffabebe4f0397d53429024f6f44db3fe97b0828
|
refs/heads/master
| 2020-04-12T06:36:33.483459
| 2020-01-18T14:16:08
| 2020-01-18T14:16:08
| 7,739,074
| 24
| 25
|
MIT
| 2020-01-18T14:16:10
| 2013-01-21T19:46:41
|
Python
|
UTF-8
|
Python
| false
| false
| 1,555
|
py
|
import pytest
from pyqode.qt import QtGui
from pyqode.qt.QtTest import QTest
from pyqode.core.api import TextHelper
from pyqode.core import modes
from ..helpers import ensure_visible, ensure_connected
def get_mode(editor):
return editor.modes.get(modes.OccurrencesHighlighterMode)
def test_enabled(editor):
mode = get_mode(editor)
assert mode.enabled
mode.enabled = False
mode.enabled = True
@ensure_connected
@ensure_visible
def test_delay(editor):
mode = get_mode(editor)
assert mode.delay == 1000
mode.delay = 3000
assert mode.delay == 3000
mode.delay = 1000
assert mode.delay == 1000
@ensure_connected
@ensure_visible
def test_background(editor):
mode = get_mode(editor)
assert mode.background.name() == '#ccffcc'
mode.background = QtGui.QColor('#404040')
assert mode.background.name() == '#404040'
@ensure_connected
@ensure_visible
def test_foreground(editor):
mode = get_mode(editor)
assert mode.foreground is None
mode.foreground = QtGui.QColor('#202020')
assert mode.foreground.name() == '#202020'
@ensure_connected
@ensure_visible
@pytest.mark.xfail
def test_occurrences(editor):
for underlined in [True, False]:
editor.file.open(__file__)
assert editor.backend.running is True
mode = get_mode(editor)
mode.underlined = underlined
assert len(mode._decorations) == 0
assert mode.delay == 1000
TextHelper(editor).goto_line(16, 7)
QTest.qWait(2000)
assert len(mode._decorations) > 0
|
[
"colin.duquesnoy@gmail.com"
] |
colin.duquesnoy@gmail.com
|
1abaebbe2a53ac8c55b73c8692edd187e8ac1ca3
|
3a85089c2498ff04d1b9bce17a4b8bf6cf2380c9
|
/DQM/SiStripCommissioningSources/python/__init__.py
|
5cb176520939c3fb3b64280306e6166224512036
|
[] |
no_license
|
sextonkennedy/cmssw-ib
|
c2e85b5ffa1269505597025e55db4ffee896a6c3
|
e04f4c26752e0775bd3cffd3a936b288ee7b0268
|
HEAD
| 2016-09-01T20:09:33.163593
| 2013-04-26T12:05:17
| 2013-04-29T16:40:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 214
|
py
|
#Automatically created by SCRAM
import os
__path__.append(os.path.dirname(os.path.abspath(__file__).rsplit('/DQM/SiStripCommissioningSources/',1)[0])+'/cfipython/slc6_amd64_gcc480/DQM/SiStripCommissioningSources')
|
[
"giulio.eulisse@cern.ch"
] |
giulio.eulisse@cern.ch
|
c824b387f7e69b52f2aea7ee95f05bb9fe654c45
|
c46260c40054c0499e0a6871e4d3fe2d6d8aa9c0
|
/LISTING.py
|
281621f7fb0be0311058b69ce8761221ebea4feb
|
[] |
no_license
|
iiot-tbb/learngit
|
1d6f5c234f1c36016be5489c7ec605f666bbba16
|
dfa3106d05bcbb0da39b9bf71f7a0698322130f7
|
refs/heads/master
| 2020-08-30T01:30:07.632602
| 2019-12-07T13:09:59
| 2019-12-07T13:09:59
| 218,225,081
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 731
|
py
|
#!/usr/bin/env python
# coding=utf-8
from timeit import Timer
def test1():
l =[]
for i in range(1000):
l = l+ [i]
def test2():
l =[]
for i in range(1000):
l.append(i)
def test3():
l =[ i for i in range(1000) ]
def test4():
l = list(range(1000))
t1 =Timer("test1()","from __main__ import test1")
print("concat ",t1.timeit(number=1000), "milliseconds")
t2 = Timer("test2()","from __main__ import test2")
print("append ",t2.timeit(number=1000),"milliseconds")
t3 = Timer("test3()", "from __main__ import test3")
print("comprehension ",t3.timeit(number=1000), "milliseconds")
t4 = Timer("test4()", "from __main__ import test4")
print("list range ",t4.timeit(number=1000), "milliseconds")
|
[
"247687157@qq.com"
] |
247687157@qq.com
|
226d7c640175f5819037705b351840787fd615ac
|
6188f8ef474da80c9e407e8040de877273f6ce20
|
/examples/assets_pandas_type_metadata/assets_pandas_type_metadata/resources/csv_io_manager.py
|
68dc75f91b9b2b658c50091745e997fba2f106e1
|
[
"Apache-2.0"
] |
permissive
|
iKintosh/dagster
|
99f2a1211de1f3b52f8bcf895dafaf832b999de2
|
932a5ba35263deb7d223750f211c2ddfa71e6f48
|
refs/heads/master
| 2023-01-24T15:58:28.497042
| 2023-01-20T21:51:35
| 2023-01-20T21:51:35
| 276,410,978
| 1
| 0
|
Apache-2.0
| 2020-07-01T15:19:47
| 2020-07-01T15:13:56
| null |
UTF-8
|
Python
| false
| false
| 2,782
|
py
|
import os
import textwrap
import pandas as pd
from dagster import (
AssetKey,
MemoizableIOManager,
MetadataEntry,
TableSchemaMetadataValue,
io_manager,
)
class LocalCsvIOManager(MemoizableIOManager):
"""Translates between Pandas DataFrames and CSVs on the local filesystem."""
def __init__(self, base_dir):
self._base_dir = base_dir
def _get_fs_path(self, asset_key: AssetKey) -> str:
rpath = os.path.join(self._base_dir, *asset_key.path) + ".csv"
return os.path.abspath(rpath)
def handle_output(self, context, obj: pd.DataFrame):
"""This saves the dataframe as a CSV."""
fpath = self._get_fs_path(context.asset_key)
os.makedirs(os.path.dirname(fpath), exist_ok=True)
obj.to_csv(fpath)
with open(fpath + ".version", "w", encoding="utf8") as f:
f.write(context.version if context.version else "None")
yield MetadataEntry.int(obj.shape[0], "Rows")
yield MetadataEntry.path(fpath, "Path")
yield MetadataEntry.md(obj.head(5).to_markdown(), "Sample")
yield MetadataEntry.text(context.version, "Resolved version")
yield MetadataEntry.table_schema(
self.get_schema(context.dagster_type),
"Schema",
)
def get_schema(self, dagster_type):
schema_entry = next(
(
x
for x in dagster_type.metadata_entries
if isinstance(x.entry_data, TableSchemaMetadataValue)
),
None,
)
assert schema_entry
return schema_entry.entry_data.schema
def load_input(self, context):
"""This reads a dataframe from a CSV."""
fpath = self._get_fs_path(context.asset_key)
date_col_names = [
table_col.name
for table_col in self.get_schema(context.upstream_output.dagster_type).columns
if table_col.type == "datetime64[ns]"
]
return pd.read_csv(fpath, parse_dates=date_col_names)
def has_output(self, context) -> bool:
fpath = self._get_fs_path(context.asset_key)
version_fpath = fpath + ".version"
if not os.path.exists(version_fpath):
return False
with open(version_fpath, "r", encoding="utf8") as f:
version = f.read()
return version == context.version
@io_manager
def local_csv_io_manager(context):
return LocalCsvIOManager(context.instance.storage_directory())
def pandas_columns_to_markdown(dataframe: pd.DataFrame) -> str:
return (
textwrap.dedent(
"""
| Name | Type |
| ---- | ---- |
"""
)
+ "\n".join([f"| {name} | {dtype} |" for name, dtype in dataframe.dtypes.iteritems()])
)
|
[
"noreply@github.com"
] |
iKintosh.noreply@github.com
|
34007746b1f587a5fbfc161816d0df49bbeda33c
|
163bbb4e0920dedd5941e3edfb2d8706ba75627d
|
/Code/CodeRecords/2176/60898/304593.py
|
dd9b9604eea880c2c36c822e8be0863c455da893
|
[] |
no_license
|
AdamZhouSE/pythonHomework
|
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
|
ffc5606817a666aa6241cfab27364326f5c066ff
|
refs/heads/master
| 2022-11-24T08:05:22.122011
| 2020-07-28T16:21:24
| 2020-07-28T16:21:24
| 259,576,640
| 2
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 220
|
py
|
s1 = input()
l1 = len(s1)
s2 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
a =""
for i in range(52):
for j in range(l1):
if s1[l1-j-1]==s2[i]:
b=str(l1-j)
a=a+b+" "
print(a)
|
[
"1069583789@qq.com"
] |
1069583789@qq.com
|
f8b8200530e6ac229ce51345487daaf93aa19c13
|
6b14d9a64a578239e5612e6098320b61b45c08d9
|
/SEP27/03.py
|
da54b196d586a25bb2a7fc1b0f68d526ccca9bd1
|
[
"MIT"
] |
permissive
|
Razdeep/PythonSnippets
|
498c403140fec33ee2f0dd84801738f1256ee9dd
|
76f9313894f511c487a99bc38bdf0fe5e594caf5
|
refs/heads/master
| 2020-03-26T08:56:23.067022
| 2018-11-26T05:36:36
| 2018-11-26T05:36:36
| 144,726,845
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 321
|
py
|
# Using sqlite3
import sqlite3
conn=sqlite3.connect('Example.db')
# conn.execute('Create table student(name,address,age,mob)')
print('Table created')
conn.execute('insert into student values("Raj","ssd","sdf","adgg")')
print('Row has been inserted')
student=conn.execute('select * from student').fetchall()
print(student)
|
[
"rrajdeeproychowdhury@gmail.com"
] |
rrajdeeproychowdhury@gmail.com
|
194d7c03a55bf69115a1a87ec700ccc939cc4a70
|
ef9a1edc55a8dc13c7dc0081334d9b0e5b5643ed
|
/explorer/migrations/0004_auto_20170815_1500.py
|
1b277b7d3a2988b7195fc9606bca3d45696ee5ae
|
[
"MIT"
] |
permissive
|
LCOGT/serol
|
450a7650a4ad70d2f1402d58e3098d6cdfc8cda7
|
b4698dc90cc59587068e352e1e523025087cca62
|
refs/heads/master
| 2023-09-04T08:08:01.557747
| 2023-08-14T12:24:06
| 2023-08-14T12:24:06
| 98,443,901
| 0
| 0
|
MIT
| 2023-05-23T03:39:31
| 2017-07-26T16:29:55
|
Python
|
UTF-8
|
Python
| false
| false
| 1,086
|
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-15 15:00
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('explorer', '0003_challenge_category'),
]
operations = [
migrations.DeleteModel(
name='Target',
),
migrations.AddField(
model_name='challenge',
name='active',
field=models.BooleanField(default=True),
),
migrations.AddField(
model_name='challenge',
name='avm_code',
field=models.CharField(blank=True, max_length=50, null=True),
),
migrations.AlterField(
model_name='challenge',
name='category',
field=models.TextField(blank=True, help_text='Astronomical object type', null=True),
),
migrations.AlterField(
model_name='challenge',
name='description',
field=models.TextField(help_text='Research page info'),
),
]
|
[
"edward@gomez.me.uk"
] |
edward@gomez.me.uk
|
7e7d78b5c7010025c138d03323e04d0ec123e87a
|
e1c5b001b7031d1ff204d4b7931a85366dd0ce9c
|
/EMu/2017/data_reskim/script/Batch_reskim_all.py
|
c2503d17c492d171b32fbe7503db4a8bf1b7a58b
|
[] |
no_license
|
fdzyffff/IIHE_code
|
b9ff96b5ee854215e88aec43934368af11a1f45d
|
e93a84777afad69a7e63a694393dca59b01c070b
|
refs/heads/master
| 2020-12-30T16:03:39.237693
| 2020-07-13T03:06:53
| 2020-07-13T03:06:53
| 90,961,889
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,833
|
py
|
import os
import sys
MYDIR=os.getcwd()
file_root_dir_dic={
#[isData,isZToTT,isTTbin,isWWbin,
"../Data/rB_1" :[[True,False,False,False],[0]],
"../Data/rC_1" :[[True,False,False,False],[0]],
"../Data/rD_1" :[[True,False,False,False],[0]],
"../Data/rE_1" :[[True,False,False,False],[0]],
"../Data/rF_1" :[[True,False,False,False],[0]],
}
reskim_dic={
}
def my_walk_dir(my_dir,my_list):
for tmp_file in os.listdir(my_dir):
tmp_file_name = my_dir+'/'+tmp_file
if os.path.isfile(tmp_file_name):
if 'failed' in tmp_file_name:continue
if not '.root' in tmp_file_name:continue
my_list.append(tmp_file_name[3:])
else:
my_walk_dir(tmp_file_name,my_list)
return my_list
def make_dic(check_dir = ""):
print "%s making file list %s"%("#"*15,"#"*15)
n_total = 0
for file_dir in file_root_dir_dic:
tmp_name = ""
for i in file_dir.split("/"):
if (not i == ".") and (not i == ".."):
tmp_name += "%s_"%(i)
file_list = my_walk_dir(file_dir,[])
file_list.sort()
if check_dir == "":
reskim_dic[tmp_name] = [file_root_dir_dic[file_dir][0],file_list,file_root_dir_dic[file_dir][1],[]]
else:
reskim_dic[tmp_name] = [file_root_dir_dic[file_dir][0],file_list,file_root_dir_dic[file_dir][1],my_walk_dir(check_dir,[])]
print " %s : %d"%(file_dir,len(reskim_dic[tmp_name][1]))
n_total += len(reskim_dic[tmp_name][1])
print " Total root files : %d"%(n_total)
def make_sub(label,n_file_per_job):
print "%s making jobs script, %d root files/job %s"%("#"*15,n_file_per_job,"#"*15)
try:
if isCheck:
tmp_dir='check_sub_%s'%(label)
else:
tmp_dir='sub_%s'%(label)
os.mkdir(tmp_dir)
except:
pass
try:
os.system('mkdir %s/sub_err'%tmp_dir)
os.system('mkdir %s/sub_out'%tmp_dir)
os.system('mkdir %s/sub_job'%tmp_dir)
os.system('mkdir %s/BigSub'%tmp_dir)
except:
print "err!"
pass
i=0
tmp_bigsubname = "BigSubmit_%s.jobb"%(label)
BigSub_job = open(MYDIR+'/'+tmp_dir+'/'+tmp_bigsubname,'w')
sub_log_name = "sub_log_%s.log"%(label)
sub_log = open(MYDIR+'/'+tmp_dir+'/'+sub_log_name,'w')
n_total_job = 0
for reskim in reskim_dic:
isData = reskim_dic[reskim][0][0]
isDYbin = reskim_dic[reskim][0][1]
isTTbin = reskim_dic[reskim][0][2]
isWWbin = reskim_dic[reskim][0][3]
triggerVersion = reskim_dic[reskim][2][0]
n_job = 0
sub_n_total_job = 0
n_start = True
job_text = ""
i = 0
for root_file in reskim_dic[reskim][1]:
sample_name = root_file.split("/")[-3]
subdir_name = root_file.split("/")[-2]
file_name = root_file.split("/")[-1]
output_name = "ntuples/batchdata_loop_2/data_%s_%s_%s_%s"%(label,sample_name,subdir_name,file_name)
tmp_label = reskim
if n_start:
n_start=False
job_text = ""
job_text+=("curr_dir=%s\n"%(MYDIR))
job_text+=("cd %s\n"%(MYDIR))
job_text+=("source env2.sh\n")
job_text+=("cd ../\n")
if (not isCheck) or (not output_name in reskim_dic[reskim][3]):
job_text+=("python reskim_all.py -r %s -o %s --isData %s --isDYbin %s --isTTbin %s --isWWbin %s -t %s\n"%(root_file, output_name, isData, isDYbin, isTTbin, isWWbin, triggerVersion))
n_job+=1
i+=1
if (n_job%n_file_per_job==0 and n_job>0) or (i >= len(reskim_dic[reskim][1])):
n_job=0
n_start=True
n_total_job += 1
sub_n_total_job += 1
tmp_label = "%s%s"%(reskim,sub_n_total_job)
tmp_jobname="sub_%s.jobb"%(tmp_label)
tmp_job=open(MYDIR+'/'+tmp_dir+'/sub_job/'+tmp_jobname,'w')
tmp_job.write(job_text)
tmp_job.close()
os.system("chmod +x %s"%(MYDIR+'/'+tmp_dir+'/'+"sub_job/"+tmp_jobname))
sub_log_command = "qsub -q localgrid -e %s/sub_err/err_%s_%s.dat -o %s/sub_out/out_%s_%s.dat %s"%(tmp_dir,label,tmp_label,tmp_dir,label,tmp_label,MYDIR+'/'+tmp_dir+'/sub_job/'+tmp_jobname)
#os.system(sub_log_command)
sub_log.write("%s\n"%(sub_log_command))
BigSub_job.write("qsub -q localgrid %s\n"%(MYDIR+'/'+tmp_dir+'/sub_job/'+tmp_jobname))
os.system("chmod +x %s"%(MYDIR+'/'+tmp_dir+'/'+tmp_bigsubname))
print "%d jobs created"%(n_total_job)
isCheck = True
isCheck = False
make_dic()
#make_dic("../ntuples/batchdata_loop_2")
make_sub("2017_SingleMuon",200)
|
[
"1069379433@qq.com"
] |
1069379433@qq.com
|
5ea0cc825f93fc42950aba4b149681a669002a5c
|
8f64d50494507fd51c0a51010b84d34c667bd438
|
/BeautyForMe/myvenv/Lib/site-packages/phonenumbers/shortdata/region_AF.py
|
840519d2de85f67d5d2e0916a6bd49c9e9b2a04f
|
[
"MIT"
] |
permissive
|
YooInKeun/CAU_CSE_Capstone_3
|
5a4a61a916dc13c8635d25a04d59c21279678477
|
51405c4bed2b55661aa0708c8acea17fe72aa701
|
refs/heads/master
| 2022-12-11T15:39:09.721019
| 2021-07-27T08:26:04
| 2021-07-27T08:26:04
| 207,294,862
| 6
| 1
|
MIT
| 2022-11-22T04:52:11
| 2019-09-09T11:37:13
|
Python
|
UTF-8
|
Python
| false
| false
| 937
|
py
|
"""Auto-generated file, do not edit by hand. AF metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_AF = PhoneMetadata(id='AF', country_code=None, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='[14]\\d\\d(?:\\d{2})?', possible_length=(3, 5)),
toll_free=PhoneNumberDesc(national_number_pattern='1(?:02|19)', example_number='102', possible_length=(3,)),
emergency=PhoneNumberDesc(national_number_pattern='1(?:02|19)', example_number='102', possible_length=(3,)),
short_code=PhoneNumberDesc(national_number_pattern='1(?:02|19)|40404', example_number='102', possible_length=(3, 5)),
carrier_specific=PhoneNumberDesc(national_number_pattern='404\\d\\d', example_number='40400', possible_length=(5,)),
sms_services=PhoneNumberDesc(national_number_pattern='404\\d\\d', example_number='40400', possible_length=(5,)),
short_data=True)
|
[
"keun0390@naver.com"
] |
keun0390@naver.com
|
10f907d3baaaa51c57acbf31d33adc0870fafb74
|
25ebc03b92df764ff0a6c70c14c2848a49fe1b0b
|
/daily/20191121/example_jinja2/01inherit/main.py
|
f6a2a6121ddb3ef66ab19e547bff0ea2c8a5a968
|
[] |
no_license
|
podhmo/individual-sandbox
|
18db414fafd061568d0d5e993b8f8069867dfcfb
|
cafee43b4cf51a321f4e2c3f9949ac53eece4b15
|
refs/heads/master
| 2023-07-23T07:06:57.944539
| 2023-07-09T11:45:53
| 2023-07-09T11:45:53
| 61,940,197
| 6
| 0
| null | 2022-10-19T05:01:17
| 2016-06-25T11:27:04
|
Python
|
UTF-8
|
Python
| false
| false
| 249
|
py
|
import os.path
from jinja2 import Environment, FileSystemLoader
here = os.path.dirname(__file__)
e = Environment(loader=FileSystemLoader(here))
t = e.get_template("main.j2")
print(t.render())
e.compile_templates(here, zip=None, log_function=print)
|
[
"ababjam61+github@gmail.com"
] |
ababjam61+github@gmail.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.