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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
81514d43a8d83c10edcfafd29865f09868f39d2f | f47fe8a7d8cd87b3bfa2e172b4a9fc93e3a4abc2 | /2015/AST1/vezbovni/Ivan/drugi.py | 2b511e0abfef1e8c327b2cdf308726281e5c262f | [] | no_license | ispastlibrary/Titan | a4a7e4bb56544d28b884a336db488488e81402e0 | f60e5c6dc43876415b36ad76ab0322a1f709b14d | refs/heads/master | 2021-01-17T19:23:32.839966 | 2016-06-03T13:47:44 | 2016-06-03T13:47:44 | 60,350,752 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 144 | py | def obim(a, b):
O = 2*a+2*b
print("obim pravougaonika stranica", a "i" b, "je", O)
return O
prvi = obim(1, 2)
drugi = obim(25, 36)
| [
"ispast.library@gmail.com"
] | ispast.library@gmail.com |
48cc96d967e3c3242cbb6e49bf663103aaea450c | 9ecf55bf2601e0d4f74e71f4903d2fd9e0871fd6 | /my_seg_tf/v10_segcap_128_128/config/config_res_segcap_3L_v3.py | 01c05a130a8d00c0547dfd1a8595652e1a11e9fd | [] | no_license | qq191513/mySeg | 02bc9803cde43907fc5d96dc6a6a6371f2bef6fe | 4337e6a0ca50b8ccbf6ed9b6254f2aec814b24db | refs/heads/master | 2020-04-10T09:57:37.811133 | 2019-06-26T08:21:23 | 2019-06-26T08:21:23 | 160,951,962 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,331 | py | import os
########################## 训练集 #######################################
project_root ='/home/mo/work/seg_caps/my_seg_tf/v9_segcap_128_128'
mask=True
train_data_number = 57
num_classes = 1
batch_size = 2
input_shape =[batch_size,128,128,3]
labels_shape =[batch_size,128,128,1]
labels_shape_vec =[batch_size,128*128*1]
epoch = 150 #共多少个epoch
save_epoch_n = 5 #每多少epoch保存一次
lr_range=(1e-3,1e-7,0.96)
test_data_number =9
choose_loss = 'margin_focus'
######################## end ########################################
########################## 输出路径 #######################################
output_path = '/home/mo/work/output'
branch_name = 'v9_segcap_128_128'
model_name = 'res_segcap_my_final'
dataset_name = 'my_128'
######################## end ########################################
#固定写法
ckpt =os.path.join(output_path,branch_name,model_name + '_' + dataset_name)
save_mean_csv = os.path.join(ckpt,'eval_result_mean.csv')
save_list_csv = os.path.join(ckpt,'eval_result.csv')
save_plot_curve_dir = os.path.join(ckpt,'plot_curve')
train_print_log = os.path.join(ckpt)
logdir = os.path.join(ckpt,'logdir')
predict_pics_save = os.path.join(ckpt,'predict_pics')
predict_tensor_feature_map = os.path.join(ckpt,'predict_tensor_feature_map') | [
"1915138054@qq.com"
] | 1915138054@qq.com |
0ad48321b180ab40c03d0c360ae53bd96eb13d58 | 87cacb90676e5e7d1d8f0e643f1ad6ed9e35acbf | /need to clean/codes_dl_old/split_train_test_bu.py | 99a5c178bbdbfdef7b08c55a8d37704e0befe3c4 | [] | no_license | vuhoangminh/Kaggle-TalkingData-AdTracking-Fraud-Detection-Challenge | 3b75d4a7c60574a4875c62e8843a01d945d792d3 | 56045f446f1a0c538d91ac65e536edc4b7b5a417 | refs/heads/master | 2020-03-13T12:56:42.309722 | 2018-05-08T10:50:35 | 2018-05-08T10:50:35 | 131,129,397 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,884 | py | """
Adding improvements inspired from:
Ravi Teja's fe script: https://www.kaggle.com/rteja1113/lightgbm-with-count-features?scriptVersionId=2815638
"""
import pandas as pd
import time
import numpy as np
from sklearn.cross_validation import train_test_split
import lightgbm as lgb
import gc
import pickle
from sklearn.preprocessing import LabelEncoder
path = '../input/'
dtypes = {
'ip' : 'uint32',
'app' : 'uint16',
'device' : 'uint16',
'os' : 'uint16',
'channel' : 'uint16',
'is_attributed' : 'uint8',
'click_id' : 'uint32'
}
TRAINSAMPLE = 180000000
# TRAINSAMPLE = 1000
NROWS = 30000000
TRAINROWS = 90000000
# NROWS = 300
num_split = int(TRAINSAMPLE/NROWS)
print (num_split)
def load_write(iSplit):
print('loading train data...')
for iDivide in range(3):
skip_rows = iDivide*NROWS
print('loading train data...', iDivide)
if iDivide==0:
train_df = pd.read_csv(path+"train.csv", nrows=NROWS, dtype=dtypes, usecols=['ip','app','device','os', 'channel', 'click_time', 'is_attributed'])
train_df = train_df.sample(frac=TRAINROWS/NROWS/num_split)
print ("len of train_df: ", len(train_df))
else:
train_df_temp = pd.read_csv(path+"train.csv", skiprows=range(1,skip_rows), nrows=NROWS, dtype=dtypes, usecols=['ip','app','device','os', 'channel', 'click_time', 'is_attributed'])
train_df_temp = train_df_temp.sample(frac=TRAINROWS/NROWS/num_split)
train_df = train_df.append(train_df_temp)
print ("len of train_df: ", len(train_df))
del train_df_temp
gc.collect()
# train_df_full = pd.read_csv(path+"train.csv", dtype=dtypes, usecols=['ip','app','device','os', 'channel', 'click_time', 'is_attributed'])
# print ("len of full: ", len(train_df_full))
# train_df, train_df_delete = train_test_split(train_df_full, test_size=NROWS/TRAINSAMPLE)
# del train_df_delete, train_df_full
# gc.collect()
# print ("len of sampling: ", len(train_df_full))
print('loading test data...')
test_df = pd.read_csv(path+"test.csv", dtype=dtypes, usecols=['ip','app','device','os', 'channel', 'click_time', 'click_id'])
print ("len of test: ", len(test_df))
gc.collect()
len_train = len(train_df)
train_df=train_df.append(test_df)
del test_df
gc.collect()
# if iSplit>0:
# train_df = pd.read_csv(path+"train.csv", skiprows=range(1,skip_rows), nrows=NROWS, dtype=dtypes, usecols=['ip','app','device','os', 'channel', 'click_time', 'is_attributed'])
# else:
# train_df = pd.read_csv(path+"train.csv", nrows=NROWS, dtype=dtypes, usecols=['ip','app','device','os', 'channel', 'click_time', 'is_attributed'])
gc.collect()
print('Extracting new features...')
train_df['min'] = pd.to_datetime(train_df.click_time).dt.minute.astype('uint8')
train_df['hour'] = pd.to_datetime(train_df.click_time).dt.hour.astype('uint8')
train_df['day'] = pd.to_datetime(train_df.click_time).dt.day.astype('uint8')
train_df['wday'] = pd.to_datetime(train_df.click_time).dt.dayofweek.astype('uint8')
print(train_df.head())
print('grouping by ip alone....')
gp = train_df[['ip','channel']].groupby(by=['ip'])[['channel']].count().reset_index().rename(index=str, columns={'channel': 'ipcount'})
train_df = train_df.merge(gp, on=['ip'], how='left')
del gp; gc.collect()
print('grouping by ip-day-hour combination....')
gp = train_df[['ip','day','hour','channel']].groupby(by=['ip','day','hour'])[['channel']].count().reset_index().rename(index=str, columns={'channel': 'qty'})
train_df = train_df.merge(gp, on=['ip','day','hour'], how='left')
del gp; gc.collect()
print('group by ip-app combination....')
gp = train_df[['ip','app', 'channel']].groupby(by=['ip', 'app'])[['channel']].count().reset_index().rename(index=str, columns={'channel': 'ip_app_count'})
train_df = train_df.merge(gp, on=['ip','app'], how='left')
del gp; gc.collect()
print('group by ip-app-os combination....')
gp = train_df[['ip','app', 'os', 'channel']].groupby(by=['ip', 'app', 'os'])[['channel']].count().reset_index().rename(index=str, columns={'channel': 'ip_app_os_count'})
train_df = train_df.merge(gp, on=['ip','app', 'os'], how='left')
del gp; gc.collect()
print("vars and data type....")
train_df['ipcount'] = train_df['qty'].astype('uint32')
train_df['qty'] = train_df['qty'].astype('uint16')
train_df['ip_app_count'] = train_df['ip_app_count'].astype('uint16')
train_df['ip_app_os_count'] = train_df['ip_app_os_count'].astype('uint16')
print("label encoding....")
train_df[['app','device','os', 'channel', 'hour', 'day', 'wday']].apply(LabelEncoder().fit_transform)
# train_df[['app','device','os', 'channel', 'hour', 'day']].apply(LabelEncoder().fit_transform)
print ('final part of preparation....')
# train_df = train_df.drop(['click_time', 'wday', 'day'], axis=1)
# train_df = train_df.drop(['click_time', 'day'], axis=1)
train_df = train_df.drop(['click_time'], axis=1)
print(train_df.head())
print("train size: ", len(train_df))
test_df = train_df[len_train:]
print ("len of test: ", len(test_df))
train_df = train_df[:len_train]
print ("len of train: ", len(train_df))
save_name = 'train_' + str(iSplit)
print("save to: ", save_name)
train_df.to_pickle(save_name)
del train_df
gc.collect()
save_name = 'test_' + str(iSplit)
print("save to: ", save_name)
test_df.to_pickle(save_name)
del test_df
gc.collect()
for iSplit in range(3):
print('Processing split', iSplit+1)
skip_rows = iSplit*NROWS
print (skip_rows)
load_write(iSplit) | [
"minhmanutd@gmail.com"
] | minhmanutd@gmail.com |
5c87709e79b598bd4b214aead30ccb6efaa34278 | 018a1d8d59c00f69b0489ce05567a2972c335ff7 | /2017_May23/threads/job_queue.py | f5a021c0ba152893e936037dcb4ee78ae934f673 | [] | no_license | singhujjwal/python | f0127b604e2204a02836c95d89ee4903f760d48c | 4fb4b34a318f093bd944cd70d7f0d69dd7dfef6e | refs/heads/master | 2021-09-20T15:35:13.389400 | 2021-09-03T06:39:58 | 2021-09-03T06:39:58 | 92,157,309 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,401 | py | from time import sleep
def square(x):
sleep(5)
return x*x
def factorial(x):
sleep(3)
from functools import reduce
return reduce(lambda x,y: x*y, range(1, x+1))
def sum_all(x):
sleep(2)
return sum(range(x))
class MyJobQueue:
def __init__(self, capacity):
from queue import Queue
from threading import Lock, Thread
self.capacity = capacity
self.jobq = Queue(capacity)
self.workers = {}
self.result = {}
self.job_id = 0
self.job_id_mtx = Lock()
for i in range(capacity):
self.workers[i] = Thread(target=self.work)
self.workers[i].start()
def work(self):
while True:
job_id, fn, args, kwargs = self.jobq.get()
self.result[job_id] = fn(*args, **kwargs)
self.jobq.task_done()
def submit(self, fn, *args, **kwargs):
with self.job_id_mtx: self.job_id += 1
self.jobq.put((self.job_id, fn, args, kwargs))
def join(self):
self.jobq.join()
return self.result
if __name__ == "__main__":
jobs = MyJobQueue(10) # Upto 10 workers can run concurrently!
jobs.submit(square, 10)
jobs.submit(factorial, 5)
jobs.submit(sum_all, 10)
jobs.submit(square, 2)
result = jobs.join() # Wait for all submitted jobs to complete...
print("Result = {}".format(str(result)))
| [
"ujjsingh@cisco.com"
] | ujjsingh@cisco.com |
de6558aa3fa726a49caaa8cdd14339487414a1c5 | a46d135ba8fd7bd40f0b7d7a96c72be446025719 | /packages/python/plotly/plotly/validators/box/unselected/marker/_opacity.py | d86095f213c385378e349c836d4e4410faab53eb | [
"MIT"
] | permissive | hugovk/plotly.py | 5e763fe96f225d964c4fcd1dea79dbefa50b4692 | cfad7862594b35965c0e000813bd7805e8494a5b | refs/heads/master | 2022-05-10T12:17:38.797994 | 2021-12-21T03:49:19 | 2021-12-21T03:49:19 | 234,146,634 | 0 | 0 | MIT | 2020-01-15T18:33:43 | 2020-01-15T18:33:41 | null | UTF-8 | Python | false | false | 501 | py | import _plotly_utils.basevalidators
class OpacityValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="opacity", parent_name="box.unselected.marker", **kwargs
):
super(OpacityValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "style"),
max=kwargs.pop("max", 1),
min=kwargs.pop("min", 0),
**kwargs
)
| [
"noreply@github.com"
] | hugovk.noreply@github.com |
1af686590d178711452f4ed5b201e9029756d6e5 | f445450ac693b466ca20b42f1ac82071d32dd991 | /generated_tempdir_2019_09_15_163300/generated_part004559.py | 2ab65e23a64dd1382972f44fd77b836d6ac16441 | [] | 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 | 1,456 | 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 CommutativeMatcher14982(CommutativeMatcher):
_instance = None
patterns = {
0: (0, Multiset({}), [
(VariableWithCount('i2.2.1.4.1.1.0', 1, 1, None), Mul),
(VariableWithCount('i2.2.1.4.1.1.0_1', 1, 1, S(1)), Mul)
]),
1: (1, Multiset({}), [
(VariableWithCount('i2.2.1.4.1.1.0', 1, 1, S(1)), Mul),
(VariableWithCount('i2.2.3.1.1.0', 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 CommutativeMatcher14982._instance is None:
CommutativeMatcher14982._instance = CommutativeMatcher14982()
return CommutativeMatcher14982._instance
@staticmethod
def get_match_iter(subject):
subjects = deque([subject]) if subject is not None else deque()
subst0 = Substitution()
# State 14981
return
yield
from collections import deque | [
"franz.bonazzi@gmail.com"
] | franz.bonazzi@gmail.com |
332448d7ef58c005a849960379afc675efeb75c3 | eeda8f12876b4193b8b32642b663c865f4ade39a | /player/migrations/0007_auto_20161210_2247.py | cf0accaf6c90db284a7cec3816fc1a10a76722e3 | [] | no_license | TheAvinashSingh/DirectMe | b893a29757ec0c147cc57d0d1fbd5917ce069958 | dc957d19c08666ae27adb5c25321a32ad5316a7b | refs/heads/master | 2021-01-20T05:26:49.504025 | 2016-12-11T00:28:53 | 2016-12-11T00:28:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 426 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2016-12-10 22:47
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('player', '0006_auto_20161210_2117'),
]
operations = [
migrations.AlterModelOptions(
name='inventory',
options={'verbose_name_plural': 'Inventory'},
),
]
| [
"bansalutkarsh3@gmail.com"
] | bansalutkarsh3@gmail.com |
bbc3043cb67e1318cd74d7424783ed50f9e0f638 | dc95dfb24f3cd12b823dfad2cca8607ab12e757b | /13-Built-in-Functions/lambda-functions.py | 290a032db496cccdb44a90abc4b42ebe13a6a8b5 | [] | no_license | RandyG3/Python | 06213a361deac2d653d4cd4734728838ed34e733 | 86068d81ae037beb6fd6114d93074a92c2f3108e | refs/heads/master | 2023-01-06T15:18:43.173886 | 2020-11-08T03:03:34 | 2020-11-08T03:03:34 | 236,549,506 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 554 | py | # Lambda Function
# An anonymous function
# (a function without a name)
#
# use once, then discard
metals = ["gold", "silver", "platinum", "palladium"]
# get words more than 5 char
print(filter(lambda metal: len(metal) > 5, metals))
print(list(filter(lambda metal: len(metal) > 5, metals)))
print(list(filter(lambda metal: "p" in metal, metals)))
# count the number of "l"s
print(list(map(lambda word: word.count("l"), metals)))
# return new list where lower "s" is replaced with a $
print(list(map(lambda val: val.replace("s", "$"), metals)))
| [
"40631249+RandyG3@users.noreply.github.com"
] | 40631249+RandyG3@users.noreply.github.com |
da8f240c44afe29c7e5b234fa6b40b2e38fa1cbd | 87a26f06a60b98f7a0191e59e4111d3ba338aeeb | /biLSTM/Common.py | 7b3d38f45022ee7d9f20d5833d178ba1d5f6be93 | [] | no_license | zenRRan/Stance-Detection | be0c03d3cafe0c4390e39c931cb836f6eca1f156 | 62b6d6a092a956ccd31a7d47a9de9fbf72260f98 | refs/heads/master | 2021-09-08T01:18:51.392615 | 2018-03-05T02:14:51 | 2018-03-05T02:14:51 | 115,618,231 | 8 | 2 | null | null | null | null | UTF-8 | Python | false | false | 512 | py | # Version python3.6
# -*- coding: utf-8 -*-
# @Time : 2018/2/9 下午9:22
# @Author : zenRRan
# @Email : zenrran@qq.com
# @File : Common.py
# @Software: PyCharm Community Edition
unk_key = '-unk-'
padding_key = '-padding-'
English_topics = ['atheism', 'feminist movement', 'hillary clinton',
'legalization of abortion', 'climate change is a real concern']
Chinese_topics = ['春节 放鞭炮', 'iphonese', '俄罗斯 在 叙利亚 的 反恐 行动', '开放 二胎', '深圳 禁摩 限电'] | [
"824203828@qq.com"
] | 824203828@qq.com |
2fa77c854e55396aad6687738cfc4adb903b8084 | 694d57c3e512ce916269411b51adef23532420cd | /leetcode_review/378kth_smallest_element_in_a_sorted_matrix.py | ea3b9532ad401931b61c1c7752f4a37732851542 | [] | no_license | clovery410/mycode | 5541c3a99962d7949832a0859f18819f118edfba | e12025e754547d18d5bb50a9dbe5e725fd03fd9c | refs/heads/master | 2021-05-16T02:46:47.996748 | 2017-05-10T23:43:50 | 2017-05-10T23:43:50 | 39,235,141 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 983 | py | from heapq import *
class Solution(object):
# solution1, using heap
def kthSmallest(self, matrix, k):
m, n = len(matrix), len(matrix[0]) if len(matrix) else 0
heap = []
for i in xrange(m):
heappush(heap, (matrix[i][0], i, 0))
for x in xrange(k):
cur_num, cur_i, cur_j = heappop(heap)
if cur_j + 1 < n:
heappush(heap, (matrix[cur_i][cur_j+1], cur_i, cur_j + 1))
return cur_num
# solution2, using binary search, faster than solution1
def kthSmallest2(self, matrix, k):
lo, hi = matrix[0][0], matrix[-1][-1]
while lo < hi:
mid = (hi - lo) / 2 + lo
if sum(bisect.bisect(row, mid) for row in matrix) >= k:
hi = mid
else:
lo = mid + 1
return lo
if __name__ == "__main__":
sol = Solution()
matrix = [[1,5,9],[10,11,13],[12,13,15]]
k = 9
print sol.kthSmallest(matrix, k)
| [
"seasoul410@gmail.com"
] | seasoul410@gmail.com |
69e6cab54865678d41fd6a8b033cb45b0e9a27a2 | d4c83df812c0c182bf444cc432deba03b79fb810 | /bin/gifmaker.py | 4150f99bbb22a423f9f1994f854015fa3f3fbb1e | [
"MIT"
] | permissive | webbyfox/suade | 2c06bb3d59762bbc9c41bde7b062a9575b3ea9e2 | 52a93df0f4cb1f6442b6c7dd259c8350a7687082 | refs/heads/master | 2021-01-21T20:16:58.674107 | 2017-05-23T21:23:26 | 2017-05-23T21:23:26 | 92,213,858 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 662 | py | #!/Users/Rizwan/www/suade/bin/python3.6
#
# The Python Imaging Library
# $Id$
#
# convert sequence format to GIF animation
#
# history:
# 97-01-03 fl created
#
# Copyright (c) Secret Labs AB 1997. All rights reserved.
# Copyright (c) Fredrik Lundh 1997.
#
# See the README file for information on usage and redistribution.
#
from __future__ import print_function
from PIL import Image
if __name__ == "__main__":
import sys
if len(sys.argv) < 3:
print("GIFMAKER -- create GIF animations")
print("Usage: gifmaker infile outfile")
sys.exit(1)
im = Image.open(sys.argv[1])
im.save(sys.argv[2], save_all=True)
| [
"mr.mansuri@gmail.com"
] | mr.mansuri@gmail.com |
7b212255dd798268635f44caac329f228d0e7cdb | 5c443eb3556d6d52717227008c29426ed7ca6a24 | /todo/test_views.py | 8242761704991a0157f03efcc6fbe053dc7aa31f | [] | no_license | ashur-k/ci_django_to_do_app | ef4dcfd1b6df529265f8ee4c9b1e4d5b05c27573 | f829d962a2e482830bc7c631230d2a30bef0245f | refs/heads/master | 2023-02-26T11:48:48.306451 | 2021-02-01T11:19:02 | 2021-02-01T11:19:02 | 286,980,518 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,861 | py | from django.test import TestCase
from .models import Item
# Create your tests here.
class TestViews(TestCase):
def test__get_todo_list(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'todo/todo_list.html')
def test_get_add_item_page(self):
response = self.client.get('/add')
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'todo/add_item.html')
def test_get_edit_item_page(self):
item = Item.objects.create(name='Test Todo Item')
response = self.client.get(f'/edit/{item.id}')
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'todo/edit_item.html')
def test_can_add_item(self):
response = self.client.post('/add', {'name': 'Test Added Item'})
self.assertRedirects(response, '/')
def test_can_delete_item(self):
item = Item.objects.create(name='Test Todo Item')
response = self.client.get(f'/delete/{item.id}')
self.assertRedirects(response, '/')
existing_items = Item.objects.filter(id=item.id)
self.assertEqual(len(existing_items), 0)
def test_can_toggle_item(self):
item = Item.objects.create(name='Test Todo Item', done=True)
response = self.client.get(f'/toggle/{item.id}')
self.assertRedirects(response, '/')
updated_item = Item.objects.get(id=item.id)
self.assertFalse(updated_item.done)
def test_can_edit_item(self):
item = Item.objects.create(name='Test Todo Item')
response = self.client.post(f'/edit/{item.id}', {'name': 'Updated Name'})
self.assertRedirects(response, '/')
updated_item = Item.objects.get(id=item.id)
self.assertEqual(updated_item.name, 'Updated Name')
| [
"ashurkanwal@yahoo.com"
] | ashurkanwal@yahoo.com |
d75e31c9ad75f7bcd75a6edb6e64dcb2f734a9f8 | 5b93930ce8280b3cbc7d6b955df0bfc5504ee99c | /nodes/Geron17Hands/C_PartII/A_Chapter9/C_ManagingGraphs/index.py | c0a3c947cdad986f3ad78522ec72a8e696105d0b | [] | no_license | nimra/module_gen | 8749c8d29beb700cac57132232861eba4eb82331 | 2e0a4452548af4fefd4cb30ab9d08d7662122cf4 | refs/heads/master | 2022-03-04T09:35:12.443651 | 2019-10-26T04:40:49 | 2019-10-26T04:40:49 | 213,980,247 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 5,823 | py | # Lawrence McAfee
# ~~~~~~~~ import ~~~~~~~~
from modules.node.HierNode import HierNode
from modules.node.LeafNode import LeafNode
from modules.node.Stage import Stage
from modules.node.block.CodeBlock import CodeBlock as cbk
from modules.node.block.HierBlock import HierBlock as hbk
from modules.node.block.ImageBlock import ImageBlock as ibk
from modules.node.block.ListBlock import ListBlock as lbk
from modules.node.block.MarkdownBlock import MarkdownBlock as mbk
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
blocks = [
# Download from finelybook www.finelybook.com
# with block (but you do need to close the session manually when you are done with
# it):
# >>> sess = tf.InteractiveSession()
# >>> init.run()
# >>> result = f.eval()
# >>> print(result)
# 42
# >>> sess.close()
# A TensorFlow program is typically split into two parts: the first part builds a compu‐
# tation graph (this is called the construction phase), and the second part runs it (this is
# the execution phase). The construction phase typically builds a computation graph
# representing the ML model and the computations required to train it. The execution
# phase generally runs a loop that evaluates a training step repeatedly (for example, one
# step per mini-batch), gradually improving the model parameters. We will go through
# an example shortly.
#
# Managing Graphs
# Any node you create is automatically added to the default graph:
# >>> x1 = tf.Variable(1)
# >>> x1.graph is tf.get_default_graph()
# True
# In most cases this is fine, but sometimes you may want to manage multiple independ‐
# ent graphs. You can do this by creating a new Graph and temporarily making it the
# default graph inside a with block, like so:
# >>> graph = tf.Graph()
# >>> with graph.as_default():
# ... x2 = tf.Variable(2)
# ...
# >>> x2.graph is graph
# True
# >>> x2.graph is tf.get_default_graph()
# False
#
# In Jupyter (or in a Python shell), it is common to run the same
# commands more than once while you are experimenting. As a
# result, you may end up with a default graph containing many
# duplicate nodes. One solution is to restart the Jupyter kernel (or
# the Python shell), but a more convenient solution is to just reset the
# default graph by running tf.reset_default_graph().
#
#
#
#
# 234 | Chapter 9: Up and Running with TensorFlow
#
# Download from finelybook www.finelybook.com
# Lifecycle of a Node Value
# When you evaluate a node, TensorFlow automatically determines the set of nodes
# that it depends on and it evaluates these nodes first. For example, consider the follow‐
# ing code:
# w = tf.constant(3)
# x = w + 2
# y = x + 5
# z = x * 3
#
# with tf.Session() as sess:
# print(y.eval()) # 10
# print(z.eval()) # 15
# First, this code defines a very simple graph. Then it starts a session and runs the
# graph to evaluate y: TensorFlow automatically detects that y depends on w, which
# depends on x, so it first evaluates w, then x, then y, and returns the value of y. Finally,
# the code runs the graph to evaluate z. Once again, TensorFlow detects that it must
# first evaluate w and x. It is important to note that it will not reuse the result of the
# previous evaluation of w and x. In short, the preceding code evaluates w and x twice.
# All node values are dropped between graph runs, except variable values, which are
# maintained by the session across graph runs (queues and readers also maintain some
# state, as we will see in Chapter 12). A variable starts its life when its initializer is run,
# and it ends when the session is closed.
# If you want to evaluate y and z efficiently, without evaluating w and x twice as in the
# previous code, you must ask TensorFlow to evaluate both y and z in just one graph
# run, as shown in the following code:
# with tf.Session() as sess:
# y_val, z_val = sess.run([y, z])
# print(y_val) # 10
# print(z_val) # 15
#
# In single-process TensorFlow, multiple sessions do not share any
# state, even if they reuse the same graph (each session would have its
# own copy of every variable). In distributed TensorFlow (see Chap‐
# ter 12), variable state is stored on the servers, not in the sessions, so
# multiple sessions can share the same variables.
#
#
# Linear Regression with TensorFlow
# TensorFlow operations (also called ops for short) can take any number of inputs and
# produce any number of outputs. For example, the addition and multiplication ops
# each take two inputs and produce one output. Constants and variables take no input
#
#
# Lifecycle of a Node Value | 235
#
]
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class Content(LeafNode):
def __init__(self):
super().__init__(
"Managing Graphs",
# Stage.REMOVE_EXTRANEOUS,
# Stage.ORIG_BLOCKS,
# Stage.CUSTOM_BLOCKS,
# Stage.ORIG_FIGURES,
# Stage.CUSTOM_FIGURES,
# Stage.CUSTOM_EXERCISES,
)
[self.add(a) for a in blocks]
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class ManagingGraphs(HierNode):
def __init__(self):
super().__init__("Managing Graphs")
self.add(Content(), "content")
# eof
| [
"lawrence.mcafee@gmail.com"
] | lawrence.mcafee@gmail.com |
7dc8acbac6368137168cd3244cb6acd73d01644b | 358dd2e27935215304ef5640b715de260d16aa2b | /lextract/keyed_db/repl.py | 90230021411875594959910e7f1981de5ea88e4d | [] | no_license | frankier/lextract | 7495c2053493eb50623b1cae4a8594cca6c8247e | ba38eb23188e074f7724e2ec08e5993fe98dcb6f | refs/heads/master | 2023-03-08T22:03:33.095959 | 2020-11-23T11:27:22 | 2020-11-23T11:27:22 | 188,093,991 | 1 | 0 | null | 2023-02-22T23:29:47 | 2019-05-22T18:35:44 | Python | UTF-8 | Python | false | false | 592 | py | import sys
import click
from pprint import pprint
from finntk import get_omorfi
from wikiparse.utils.db import get_session
from .extract import extract_toks
@click.command("extract-toks")
def extract_toks_cmd():
paragraph = sys.stdin.read()
omorfi = get_omorfi()
tokenised = omorfi.tokenise(paragraph)
starts = []
start = 0
for token in tokenised:
start = paragraph.index(token["surf"], start)
starts.append(start)
surfs = [tok["surf"] for tok in tokenised]
session = get_session().get_bind()
pprint(list(extract_toks(session, surfs)))
| [
"frankie@robertson.name"
] | frankie@robertson.name |
317e95c65c566b23be221e71ce486bf6889f931e | 86e8f0a13269d01bd3f9020dc2dc32e77fc7e30f | /tests/integration/test_misc.py | dd9e414a01d2216759622644551555ef39b9518d | [
"Apache-2.0"
] | permissive | stardude900/stratis-cli | 92bae614f8998cf30727a3eb0899906fe2a67df6 | bf0beb60c7bc64b8762247da983436be7ec59d32 | refs/heads/master | 2021-01-19T06:15:37.907429 | 2017-08-07T21:46:04 | 2017-08-07T21:46:04 | 100,633,518 | 0 | 0 | null | 2017-08-17T18:28:51 | 2017-08-17T18:28:51 | null | UTF-8 | Python | false | false | 5,528 | py | # Copyright 2016 Red Hat, 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.
"""
Test miscellaneous methods.
"""
import time
import unittest
from stratisd_client_dbus import get_object
from stratis_cli._actions._misc import GetObjectPath
from stratis_cli._constants import TOP_OBJECT
from stratis_cli._errors import StratisCliDbusLookupError
from ._misc import _device_list
from ._misc import RUNNER
from ._misc import Service
_DEVICE_STRATEGY = _device_list(1)
class GetPoolTestCase(unittest.TestCase):
"""
Test get_pool method when there is no pool.
It should raise an exception.
"""
def setUp(self):
"""
Start the stratisd daemon with the simulator.
"""
self._service = Service()
self._service.setUp()
time.sleep(1)
def tearDown(self):
"""
Stop the stratisd simulator and daemon.
"""
self._service.tearDown()
def testNonExistingPool(self):
"""
An exception is raised if the pool does not exist.
"""
with self.assertRaises(StratisCliDbusLookupError):
GetObjectPath.get_pool(get_object(TOP_OBJECT), {'Name': 'notapool'})
class GetPool1TestCase(unittest.TestCase):
"""
Test get_pool method when there is a pool.
"""
_POOLNAME = 'deadpool'
def setUp(self):
"""
Start the stratisd daemon with the simulator.
"""
self._service = Service()
self._service.setUp()
time.sleep(1)
command_line = \
['pool', 'create', self._POOLNAME] + \
_DEVICE_STRATEGY.example()
RUNNER(command_line)
def tearDown(self):
"""
Stop the stratisd simulator and daemon.
"""
self._service.tearDown()
def testExistingPool(self):
"""
The pool should be gotten.
"""
self.assertIsNotNone(
GetObjectPath.get_pool(
get_object(TOP_OBJECT),
spec={'Name': self._POOLNAME}
)
)
def testNonExistingPool(self):
"""
An exception is raised if the pool does not exist.
"""
with self.assertRaises(StratisCliDbusLookupError):
GetObjectPath.get_pool(get_object(TOP_OBJECT), {'Name': 'notapool'})
class GetVolume1TestCase(unittest.TestCase):
"""
Test get_filesystem method when there is a pool but no volume.
"""
_POOLNAME = 'deadpool'
def setUp(self):
"""
Start the stratisd daemon with the simulator.
"""
self._service = Service()
self._service.setUp()
time.sleep(1)
command_line = \
['pool', 'create', self._POOLNAME] + \
_DEVICE_STRATEGY.example()
RUNNER(command_line)
def tearDown(self):
"""
Stop the stratisd simulator and daemon.
"""
self._service.tearDown()
def testNonExistingVolume(self):
"""
An exception is raised if the volume does not exist.
"""
proxy = get_object(TOP_OBJECT)
pool_object_path = \
GetObjectPath.get_pool(proxy, spec={'Name': self._POOLNAME})
with self.assertRaises(StratisCliDbusLookupError):
GetObjectPath.get_filesystem(
proxy,
{'Name': 'noname', 'Pool': pool_object_path}
)
class GetVolume2TestCase(unittest.TestCase):
"""
Test get_filesystem method when there is a pool and the volume is there.
"""
_POOLNAME = 'deadpool'
_VOLNAME = 'vol'
def setUp(self):
"""
Start the stratisd daemon with the simulator.
"""
self._service = Service()
self._service.setUp()
time.sleep(1)
command_line = \
['pool', 'create', self._POOLNAME] + \
_DEVICE_STRATEGY.example()
RUNNER(command_line)
command_line = \
['filesystem', 'create', self._POOLNAME, self._VOLNAME]
RUNNER(command_line)
def tearDown(self):
"""
Stop the stratisd simulator and daemon.
"""
self._service.tearDown()
def testExistingVolume(self):
"""
The volume should be discovered.
"""
proxy = get_object(TOP_OBJECT)
pool_object_path = \
GetObjectPath.get_pool(proxy, spec={'Name': self._POOLNAME})
self.assertIsNotNone(
GetObjectPath.get_filesystem(
proxy,
{'Name': self._VOLNAME, 'Pool': pool_object_path}
)
)
def testNonExistingVolume(self):
"""
An exception is raised if the volume does not exist.
"""
proxy = get_object(TOP_OBJECT)
pool_object_path = \
GetObjectPath.get_pool(proxy, spec={'Name': self._POOLNAME})
with self.assertRaises(StratisCliDbusLookupError):
GetObjectPath.get_filesystem(
proxy,
{'Name': 'noname', 'Pool': pool_object_path}
)
| [
"amulhern@redhat.com"
] | amulhern@redhat.com |
c2b66c7a38983f935b08a2197ce9cdb85019fda6 | 9bb16f8fbf9f562f1171a3bbff8318a47113823b | /abc132/abc132_d/main.py | 6b825f6fef88b9fcc0c84f1d7a6cd6ad0aa3c805 | [] | no_license | kyamashiro/atcoder | 83ab0a880e014c167b6e9fe9457e6972901353fc | 999a7852b70b0a022a4d64ba40d4048ee4cc0c9c | refs/heads/master | 2022-06-01T03:01:39.143632 | 2022-05-22T05:38:42 | 2022-05-22T05:38:42 | 464,391,209 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 400 | py | #!/usr/bin/env python3
# from typing import *
MOD = 1000000007
# def solve(N: int, K: int) -> List[str]:
def solve(N, K):
pass # TODO: edit here
# generated by oj-template v4.8.1 (https://github.com/online-judge-tools/template-generator)
def main():
N, K = map(int, input().split())
a = solve(N, K)
for i in range(K):
print(a[i])
if __name__ == '__main__':
main()
| [
"kyamashiro73@gmail.com"
] | kyamashiro73@gmail.com |
015dde9f3d18d2234d142749e7b2fdbe911482af | 7882860350c714e6c08368288dab721288b8d9db | /백트래킹/1182_부분수열의 합.py | bc2b31a9f2df3eabfb77b6ce66c3a3e67deac17a | [] | no_license | park-seonju/Algorithm | 682fca984813a54b92a3f2ab174e4f05a95921a8 | 30e5bcb756e9388693624e8880e57bc92bfda969 | refs/heads/master | 2023-08-11T18:23:49.644259 | 2021-09-27T10:07:49 | 2021-09-27T10:07:49 | 388,741,922 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 303 | py | n,s=map(int,input().split())
arr=list(map(int,input().split()))
ans=0
def func(idx,total):
global ans
if idx>=n:
if s==total:
ans+=1
return
else:
func(idx+1,total+arr[idx])
func(idx+1,total)
func(0,0)
if s==0:
print(ans-1)
else:
print(ans) | [
"cucu9823@naver.com"
] | cucu9823@naver.com |
161708e25ea49fb32dcaf50a3134a77915485ee0 | 67ffddfd7e0ace7490c5d52325838b82644eb458 | /leetcode/greedy/lc_134.py | 5480eaf182de37f45b734ea31103412665b90700 | [] | no_license | ckdrjs96/algorithm | 326f353c5aa89a85ec86ce1aabb06cde341193ce | d5d09b047808b6fc2eeaabdbe7f32c83446b4a1b | refs/heads/main | 2023-08-20T05:12:50.671798 | 2021-10-23T04:20:05 | 2021-10-23T04:20:05 | 324,481,888 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,133 | py | # greedy o(N)
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
if sum(gas) < sum(cost):
return -1
# 성립이 안되는 지점이 있다면 그앞은 모두 정답이 될수없다. 따라서 start=i+1
start, fuel = 0, 0
for i in range(len(gas)):
if gas[i] + fuel < cost[i]:
start = i + 1
fuel = 0
else:
fuel += gas[i] - cost[i]
# print(start,fuel)
return start
#brute force o(N^2) 통과는되지만 매우느리다
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
n = len(gas)
for start in range(n):
fuel = 0
for i in range(n):
idx = (start + i) % n
fuel += gas[idx] - cost[idx]
# print(fuel)
if fuel < 0:
ans = -1
break
# 정답이 반드시 하나라했으므로 찾으면 바로종료
else:
return start
return ans | [
"ckdrjs96@gmail.com"
] | ckdrjs96@gmail.com |
76815cea1685820cd7c163aadc790a8960d954e4 | 753a70bc416e8dced2853f278b08ef60cdb3c768 | /include/tensorflow/lite/testing/op_tests/cos.py | 20b831dce9a7a16df7890f821473a43f2ad57af6 | [
"MIT"
] | permissive | finnickniu/tensorflow_object_detection_tflite | ef94158e5350613590641880cb3c1062f7dd0efb | a115d918f6894a69586174653172be0b5d1de952 | refs/heads/master | 2023-04-06T04:59:24.985923 | 2022-09-20T16:29:08 | 2022-09-20T16:29:08 | 230,891,552 | 60 | 19 | MIT | 2023-03-25T00:31:18 | 2019-12-30T09:58:41 | C++ | UTF-8 | Python | false | false | 2,002 | py | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Test configs for cos."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
from tensorflow.lite.testing.zip_test_utils import create_tensor_data
from tensorflow.lite.testing.zip_test_utils import make_zip_of_tests
from tensorflow.lite.testing.zip_test_utils import register_make_test_function
@register_make_test_function()
def make_cos_tests(options):
"""Make a set of tests to do cos."""
test_parameters = [{
"input_dtype": [tf.float32],
"input_shape": [[], [3], [1, 100], [4, 2, 3], [5, 224, 224, 3]],
}]
def build_graph(parameters):
"""Build the cos op testing graph."""
input_tensor = tf.compat.v1.placeholder(
dtype=parameters["input_dtype"],
name="input",
shape=parameters["input_shape"])
out = tf.cos(input_tensor)
return [input_tensor], [out]
def build_inputs(parameters, sess, inputs, outputs):
values = [
create_tensor_data(
parameters["input_dtype"],
parameters["input_shape"],
min_value=-np.pi,
max_value=np.pi)
]
return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))
make_zip_of_tests(options, test_parameters, build_graph, build_inputs)
| [
"finn.niu@apptech.com.hk"
] | finn.niu@apptech.com.hk |
2e15ac5d08dfab344b92280d6c14efe4945dc1f4 | bc6492a9a30ac7228caad91643d58653b49ab9e3 | /sympy/utilities/matchpy_connector.py | 1d12f13a8f09bbb88826a622781a13072f484722 | [] | no_license | cosmosZhou/sagemath | 2c54ea04868882340c7ef981b7f499fb205095c9 | 0608b946174e86182c6d35d126cd89d819d1d0b8 | refs/heads/master | 2023-01-06T07:31:37.546716 | 2020-11-12T06:39:22 | 2020-11-12T06:39:22 | 311,177,322 | 1 | 0 | null | 2020-11-12T06:09:11 | 2020-11-08T23:42:40 | Python | UTF-8 | Python | false | false | 4,168 | py | from sympy.external import import_module
from sympy.utilities.decorator import doctest_depends_on
from sympy.functions.elementary.integers import floor, frac
from sympy.functions import (log, sin, cos, tan, cot, csc, sec, sqrt, erf, gamma, uppergamma, polygamma, digamma,
loggamma, factorial, zeta, LambertW)
from sympy.functions.elementary.hyperbolic import acosh, asinh, atanh, acoth, acsch, asech, cosh, sinh, tanh, coth, sech, csch
from sympy.functions.elementary.trigonometric import atan, acsc, asin, acot, acos, asec, atan2
from sympy.polys.polytools import Poly, quo, rem, total_degree, degree
from sympy.simplify.simplify import fraction, simplify, cancel, powsimp
from sympy.core.sympify import sympify
from sympy.utilities.iterables import postorder_traversal
from sympy.functions.special.error_functions import fresnelc, fresnels, erfc, erfi, Ei, expint, li, Si, Ci, Shi, Chi
from sympy.functions.elementary.complexes import im, re, Abs
from sympy.core.exprtools import factor_terms
from sympy import (Basic, E, polylog, N, Wild, WildFunction, factor, gcd, Sum, S, I, Mul, Integer, Float, Dict, Symbol, Rational,
Add, hyper, symbols, sqf_list, sqf, Max, factorint, factorrat, Min, sign, E, Function, collect, FiniteSet, nsimplify,
expand_trig, expand, poly, apart, lcm, And, Pow, pi, zoo, oo, Integral, UnevaluatedExpr, PolynomialError, Dummy, exp,
powdenest, PolynomialDivisionFailed, discriminant, UnificationFailed, appellf1)
from sympy.functions.special.hyper import TupleArg
from sympy.functions.special.elliptic_integrals import elliptic_f, elliptic_e, elliptic_pi
from sympy.utilities.iterables import flatten
from random import randint
from sympy.logic.boolalg import Or
matchpy = import_module("matchpy")
if matchpy:
from matchpy import Arity, Operation, CommutativeOperation, AssociativeOperation, OneIdentityOperation, CustomConstraint, Pattern, ReplacementRule, ManyToOneReplacer
from matchpy.expressions.functions import op_iter, create_operation_expression, op_len
from sympy.integrals.rubi.symbol import WC
from matchpy import is_match, replace_all
Operation.register(Integral)
Operation.register(Pow)
OneIdentityOperation.register(Pow)
Operation.register(Add)
OneIdentityOperation.register(Add)
CommutativeOperation.register(Add)
AssociativeOperation.register(Add)
Operation.register(Mul)
OneIdentityOperation.register(Mul)
CommutativeOperation.register(Mul)
AssociativeOperation.register(Mul)
Operation.register(exp)
Operation.register(log)
Operation.register(gamma)
Operation.register(uppergamma)
Operation.register(fresnels)
Operation.register(fresnelc)
Operation.register(erf)
Operation.register(Ei)
Operation.register(erfc)
Operation.register(erfi)
Operation.register(sin)
Operation.register(cos)
Operation.register(tan)
Operation.register(cot)
Operation.register(csc)
Operation.register(sec)
Operation.register(sinh)
Operation.register(cosh)
Operation.register(tanh)
Operation.register(coth)
Operation.register(csch)
Operation.register(sech)
Operation.register(asin)
Operation.register(acos)
Operation.register(atan)
Operation.register(acot)
Operation.register(acsc)
Operation.register(asec)
Operation.register(asinh)
Operation.register(acosh)
Operation.register(atanh)
Operation.register(acoth)
Operation.register(acsch)
Operation.register(asech)
@op_iter.register(Integral)
def _(operation):
return iter((operation._args[0],) + operation._args[1])
@op_iter.register(Basic)
def _(operation):
return iter(operation._args)
@op_len.register(Integral)
def _(operation):
return 1 + len(operation._args[1])
@op_len.register(Basic)
def _(operation):
return len(operation._args)
@create_operation_expression.register(Basic)
def sympy_op_factory(old_operation, new_operands, variable_name=True):
return type(old_operation)(*new_operands)
| [
"74498494@qq.com"
] | 74498494@qq.com |
5161e0559dc3a3fd010c60d8374844d07214aba5 | 543e4a93fd94a1ebcadb7ba9bd8b1f3afd3a12b8 | /maza/modules/creds/routers/mikrotik/telnet_default_creds.py | 540d36ba30ae985f5d22df9eb468af7ebc98ea40 | [
"MIT"
] | permissive | ArturSpirin/maza | e3127f07b90034f08ff294cc4afcad239bb6a6c3 | 56ae6325c08bcedd22c57b9fe11b58f1b38314ca | refs/heads/master | 2020-04-10T16:24:47.245172 | 2018-12-11T07:13:15 | 2018-12-11T07:13:15 | 161,144,181 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 856 | py | from maza.core.exploit import *
from maza.modules.creds.generic.telnet_default import Exploit as TelnetDefault
class Exploit(TelnetDefault):
__info__ = {
"name": "Mikrotik Router Default Telnet Creds",
"description": "Module performs dictionary attack against Mikrotik Router Telnet service."
"If valid credentials are found they are displayed to the user.",
"authors": (
"Marcin Bury <marcin[at]threat9.com>", # routersploit module
),
"devices": (
"Mikrotik Router",
),
}
target = OptIP("", "Target IPv4, IPv6 address or file with ip:port (file://)")
port = OptPort(23, "Target Telnet port")
threads = OptInteger(1, "Number of threads")
defaults = OptWordlist("admin:admin", "User:Pass or file with default credentials (file://)")
| [
"a.spirin@hotmail.com"
] | a.spirin@hotmail.com |
1e461f00ab09e4de26a84fd68a6fd672c1864ff8 | 261ff2a577650185ff00f5d26dee3189283f28ad | /problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/solution_2.py | 4910e5585f6a7b750a56f850a1b51e46193f26b5 | [
"MIT"
] | permissive | YunYouJun/LeetCode | a60dd3e719a199f09f47656ba21af66bb5c02641 | 9dbd55acc82cafd7b1eb3cc81b20563f9bb1ce04 | refs/heads/master | 2023-08-25T05:58:28.444830 | 2023-07-21T17:24:45 | 2023-07-21T17:24:45 | 146,094,429 | 5 | 2 | MIT | 2021-08-28T17:49:40 | 2018-08-25T12:43:30 | Python | UTF-8 | Python | false | false | 597 | py | from typing import List
class Solution:
def verifyPostorder(self, postorder: List[int]) -> bool:
stack, root = [], float('+inf')
for i in range(len(postorder) - 1, -1, -1):
if postorder[i] > root:
return False
while stack and postorder[i] < stack[-1]:
root = stack.pop()
stack.append(postorder[i])
return True
if __name__ == '__main__':
test_cases = [[1, 6, 3, 2, 5], [1, 3, 2, 6, 5], [1, 3, 2, 5]]
for case in test_cases:
ans = Solution().verifyPostorder(case)
print(ans)
| [
"me@yunyoujun.cn"
] | me@yunyoujun.cn |
f5e547d3d457bb61682b752e448c9ac190e7749f | 9b87a520e85566a66f729d2b4cafd00c67ea5db0 | /Builder/build_utils.py | b71a2e74f1b31500fe22c85e188b543577ea5471 | [
"Apache-2.0"
] | permissive | barry-scott/scm-workbench | c694720acd316789821b7f8ebf32f7b941913d94 | 6ae79141ae54424d81a94a76690b2ab12df9d901 | refs/heads/master | 2023-03-15T21:13:28.394412 | 2022-07-10T11:47:30 | 2022-07-10T11:47:30 | 50,042,812 | 28 | 12 | null | null | null | null | UTF-8 | Python | false | false | 2,725 | py | #
# Needs to run under python2 or python3
#
from __future__ import print_function
import sys
import os
import subprocess
import shutil
log = None
if sys.version_info[0] == 2:
unicode_type = unicode
else:
unicode_type = str
class BuildError(Exception):
def __init__( self, msg ):
super(BuildError, self).__init__( msg )
# use a python3 compatible subprocess.run() function
class CompletedProcess(object):
def __init__(self, returncode, stdout=None, stderr=None):
self.returncode = returncode
if stdout is not None:
self.stdout = stdout.decode( 'utf-8' )
else:
self.stdout = stdout
if stderr is not None:
self.stderr = stderr.decode( 'utf-8' )
else:
self.stderr = stderr
class Popen(subprocess.Popen):
def __init__( self, *args, **kwargs ):
super(Popen, self).__init__( *args, **kwargs )
def __enter__(self):
return self
def __exit__(self, exc_type, value, traceback):
if self.stdout:
self.stdout.close()
if self.stderr:
self.stderr.close()
# Wait for the process to terminate, to avoid zombies.
self.wait()
def run( cmd, check=True, output=False, cwd=None ):
kwargs = {}
if cwd is None:
cwd = os.getcwd()
kwargs['cwd'] = cwd
if type(cmd) is unicode_type:
log.info( 'Running %s in %s' % (cmd, cwd) )
kwargs['shell'] = True
else:
log.info( 'Running %s in %s' % (' '.join( cmd ), cwd) )
if output:
kwargs['stdout'] = subprocess.PIPE
kwargs['stderr'] = subprocess.PIPE
with Popen(cmd, **kwargs) as process:
try:
stdout, stderr = process.communicate( input=None )
except: # Including KeyboardInterrupt, communicate handled that.
process.kill()
# We don't call process.wait() as .__exit__ does that for us.
raise
retcode = process.poll()
r = CompletedProcess( retcode, stdout, stderr )
if check and retcode != 0:
raise BuildError( 'Cmd failed %s - %r' % (retcode, cmd) )
return r
def rmdirAndContents( folder ):
if os.path.exists( folder ):
shutil.rmtree( folder )
def mkdirAndParents( folder ):
if not os.path.exists( folder ):
os.makedirs( folder, 0o755 )
def copyFile( src, dst, mode ):
if os.path.isdir( dst ):
dst = os.path.join( dst, os.path.basename( src ) )
if os.path.exists( dst ):
os.chmod( dst, 0o600 )
os.remove( dst )
shutil.copyfile( src, dst )
os.chmod( dst, mode )
def numCpus():
return os.sysconf( os.sysconf_names['SC_NPROCESSORS_ONLN'] )
| [
"barry@barrys-emacs.org"
] | barry@barrys-emacs.org |
168e9a9c6acb9bf3b4a1fbaac845daddd794d7b0 | a46fc5187245f7ac79758ae475d4d865e24f482b | /permutation_in_string/str_permutation.py | 02a895fffa3bf8acdd261aea5803250d08ef67fd | [] | no_license | narnat/leetcode | ae31f9321ac9a087244dddd64706780ea57ded91 | 20a48021be5e5348d681e910c843e734df98b596 | refs/heads/master | 2022-12-08T00:58:12.547227 | 2020-08-26T21:04:53 | 2020-08-26T21:04:53 | 257,167,879 | 0 | 2 | null | null | null | null | UTF-8 | Python | false | false | 1,696 | py | #!/usr/bin/env python3
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
if len(s1) > len(s2):
return False
pattern = [0] * 26
s = [0] * 26
for i in range(len(s1)):
pattern[ord(s1[i]) - ord('a')] += 1
s[ord(s2[i]) - ord('a')] += 1
window = len(s1) - 1
if s == pattern:
return True
i = 1
while i + window < len(s2):
s[ord(s2[i - 1]) - ord('a')] -= 1
s[ord(s2[i + window]) - ord('a')] += 1
if s == pattern:
return True
i += 1
return False
def checkInclusion_2(self, s1: str, s2: str) -> bool:
''' Optimized count checking'''
if len(s1) > len(s2):
return False
pattern = [0] * 26
s = [0] * 26
for i in range(len(s1)):
pattern[ord(s1[i]) - ord('a')] += 1
s[ord(s2[i]) - ord('a')] += 1
matches = 0
window = len(s1)
for i in range(len(pattern)):
if pattern[i] == s[i]:
matches += 1
for i in range(len(s2) - len(s1)):
if matches == 26:
return True
left = ord(s2[i]) - ord('a')
right = ord(s2[i + window]) - ord('a')
s[left] -= 1
if s[left] == pattern[left]:
matches += 1
elif s[left] == pattern[left] - 1:
matches -= 1
s[right] += 1
if s[right] == pattern[right]:
matches += 1
elif s[right] == pattern[right] + 1:
matches -= 1
return matches == 26
| [
"farruh1996@gmail.com"
] | farruh1996@gmail.com |
046d95f1bdeabff8b72c1d0183cafd768c0b0544 | 15581a76b36eab6062e71d4e5641cdfaf768b697 | /Topics/Binary Search/Sqrt(x).py | 1021b5b6f1d4524ae476e8448226947f4e415112 | [] | no_license | MarianDanaila/Competitive-Programming | dd61298cc02ca3556ebc3394e8d635b57f58b4d2 | 3c5a662e931a5aa1934fba74b249bce65a5d75e2 | refs/heads/master | 2023-05-25T20:03:18.468713 | 2023-05-16T21:45:08 | 2023-05-16T21:45:08 | 254,296,597 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 373 | py | class Solution:
def mySqrt(self, x: int) -> int:
low = 0
high = x + 1
while low <= high:
mid = low + (high - low) // 2
if mid * mid == x:
return mid
elif mid * mid < x:
ans = mid
low = mid + 1
else:
high = mid - 1
return ans
| [
"mariandanaila01@gmail.com"
] | mariandanaila01@gmail.com |
425aa18798c9113ad41a1766ea7429d70cc9bebe | a7058080e41af37eb77c146fc09a5e4db57f7ec6 | /Solved/05361/05361.py | e15000503140aedadcd13f71e1a12b36e94d0d31 | [] | no_license | Jinmin-Goh/BOJ_PS | bec0922c01fbf6e440589cc684d0cd736e775066 | 09a285bd1369bd0d73f86386b343d271dc08a67d | refs/heads/master | 2022-09-24T02:24:50.823834 | 2022-09-21T02:16:22 | 2022-09-21T02:16:22 | 223,768,547 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 383 | py | # Problem No.: 5361
# Solver: Jinmin Goh
# Date: 20220710
# URL: https://www.acmicpc.net/problem/5361
import sys
def main():
t = int(input())
for _ in range(t):
a, b, c, d, e = map(int, sys.stdin.readline().split())
print(f'${a * 350.34 + b * 230.90 + c * 190.55 + d * 125.30 + e * 180.90:.2f}')
return
if __name__ == "__main__":
main() | [
"eric970901@gmail.com"
] | eric970901@gmail.com |
f052899444f57fe22175d48f07fc1b910f3d54f6 | 5f8487a7efb97d90ec0393b0db046b7ca908378b | /wk2/examples/albert.py | 2077581b5d51754c3eded2211afbcb38ee8bacc3 | [] | no_license | sphilmoon/karel | 444fe686c083b3a6b101141c3b16e807ef54a4ba | f6e8a1801509d49d188cf579856cec5d7033bbde | refs/heads/main | 2023-08-25T10:23:19.010270 | 2021-10-20T12:26:35 | 2021-10-20T12:26:35 | 359,027,046 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 277 | py | C = 299792458
E = "e = m * C^2.."
def main():
mass = float(input("Enter kilos of mass: "))
print(E)
print("m =", mass, "kg")
print("C =", f"{C:,d}", "m/s")
energy = mass * (C**2)
print(energy, "joules of energy!")
if __name__ == "__main__":
main() | [
"sphilmoon@gmail.com"
] | sphilmoon@gmail.com |
c038f897a86b44cea4235b3a9c3b0b1234e25ddd | 20c20938e201a0834ccf8b5f2eb5d570d407ad15 | /abc112/abc112_c/8543451.py | 9e0a5e189ca893892719e48af7fabf0ab05acb17 | [] | no_license | kouhei-k/atcoder_submissions | 8e1a1fb30c38e0d443b585a27c6d134bf1af610a | 584b4fd842ccfabb16200998fe6652f018edbfc5 | refs/heads/master | 2021-07-02T21:20:05.379886 | 2021-03-01T12:52:26 | 2021-03-01T12:52:26 | 227,364,764 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 618 | py | N=int(input())
xyh=[list(map(int,input().split()))for i in range(N)]
xyh.sort(reverse=True,key=lambda x:x[2])
for cx in range(101):
for cy in range(101):
H=0
flag=False
for i,tmp in enumerate(xyh):
x,y,h=tmp
if h != 0:
tmp= h+abs(x-cx)+abs(y-cy)
else:
if H-abs(x-cx)-abs(y-cy) <=0:
if i == N-1:
flag=True
continue
if H!=0:
if H==tmp:
if i==N-1:
flag=True
continue
else:
break
else:
H=tmp
if flag:
print(cx,cy,H)
exit(0)
| [
"kouhei.k.0116@gmail.com"
] | kouhei.k.0116@gmail.com |
e82a60a7a6247bc2fab33bf2628b009d9ac38eaa | 141b42d9d72636c869ff2ce7a2a9f7b9b24f508b | /myvenv/Lib/site-packages/phonenumbers/data/region_GH.py | d654cc750d3bbb37816ed1112c6c777b6334e675 | [
"BSD-3-Clause"
] | permissive | Fa67/saleor-shop | 105e1147e60396ddab6f006337436dcbf18e8fe1 | 76110349162c54c8bfcae61983bb59ba8fb0f778 | refs/heads/master | 2021-06-08T23:51:12.251457 | 2018-07-24T08:14:33 | 2018-07-24T08:14:33 | 168,561,915 | 1 | 0 | BSD-3-Clause | 2021-04-18T07:59:12 | 2019-01-31T17:00:39 | Python | UTF-8 | Python | false | false | 1,483 | py | """Auto-generated file, do not edit by hand. GH metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_GH = PhoneMetadata(id='GH', country_code=233, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='[235]\\d{8}|8\\d{7}', possible_length=(8, 9), possible_length_local_only=(7,)),
fixed_line=PhoneNumberDesc(national_number_pattern='3(?:0(?:[237]\\d|80)|[167](?:2[0-6]|7\\d|80)|2(?:2[0-5]|7\\d|80)|3(?:2[0-3]|7\\d|80)|4(?:2[013-9]|3[01]|7\\d|80)|5(?:2[0-7]|7\\d|80)|8(?:2[0-2]|7\\d|80)|9(?:[28]0|7\\d))\\d{5}', example_number='302345678', possible_length=(9,), possible_length_local_only=(7,)),
mobile=PhoneNumberDesc(national_number_pattern='(?:2[034678]\\d|5(?:[0457]\\d|6[01]))\\d{6}', example_number='231234567', possible_length=(9,)),
toll_free=PhoneNumberDesc(national_number_pattern='800\\d{5}', example_number='80012345', possible_length=(8,)),
no_international_dialling=PhoneNumberDesc(national_number_pattern='800\\d{5}', example_number='80012345', possible_length=(8,)),
national_prefix='0',
national_prefix_for_parsing='0',
number_format=[NumberFormat(pattern='(\\d{2})(\\d{3})(\\d{4})', format='\\1 \\2 \\3', leading_digits_pattern=['[235]'], national_prefix_formatting_rule='0\\1'),
NumberFormat(pattern='(\\d{3})(\\d{5})', format='\\1 \\2', leading_digits_pattern=['8'], national_prefix_formatting_rule='0\\1')],
mobile_number_portable_region=True)
| [
"gruzdevasch@gmail.com"
] | gruzdevasch@gmail.com |
e4ad0a1cd2b6f6d8ae19810a9781b6eb59e564d0 | 882c865cf0a4b94fdd117affbb5748bdf4e056d0 | /python/SWexpert/level1/2068_최대수 구하기.py | 6908a815bc4146840b9367f8be966728a03e0f3a | [] | no_license | minhee0327/Algorithm | ebae861e90069e2d9cf0680159e14c833b2f0da3 | fb0d3763b1b75d310de4c19c77014e8fb86dad0d | refs/heads/master | 2023-08-15T14:55:49.769179 | 2021-09-14T04:05:11 | 2021-09-14T04:05:11 | 331,007,037 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 137 | py | import sys
for t in range(int(sys.stdin.readline())):
lst = list(map(int, input().split()))
print("#{} {}".format(t, max(lst)))
| [
"queen.minhee@gmail.com"
] | queen.minhee@gmail.com |
0a78e495b80ab9f88ed61331eaa680936024d356 | 1a6c2be5ff1a8364c97a1ede23c824b2579ecf79 | /tfx/dsl/components/base/executor_spec.py | 502c4c21c1cc3f66f1766c0916cf2b2132a0d303 | [
"Apache-2.0"
] | permissive | 418sec/tfx | fa1a4690df2178e9c6bd24f97df0bbde7436df95 | df1529c91e52d442443eca5968ff33cf0a38dffa | refs/heads/master | 2023-04-18T12:25:38.098958 | 2021-04-28T16:11:00 | 2021-04-28T16:11:00 | 333,769,030 | 2 | 1 | Apache-2.0 | 2021-04-28T16:11:01 | 2021-01-28T13:35:14 | null | UTF-8 | Python | false | false | 6,429 | py | # Lint as: python2, python3
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Executor specifications for defining what to to execute."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import copy
from typing import cast, Iterable, List, Optional, Text, Type
from six import with_metaclass
from tfx import types
from tfx.dsl.components.base import base_executor
from tfx.proto.orchestration import executable_spec_pb2
from tfx.utils import import_utils
from tfx.utils import json_utils
from google.protobuf import message
class ExecutorSpec(with_metaclass(abc.ABCMeta, json_utils.Jsonable)):
"""A specification for a component executor.
An instance of ExecutorSpec describes the implementation of a component.
"""
def encode(
self,
component_spec: Optional[types.ComponentSpec] = None) -> message.Message:
"""Encodes ExecutorSpec into an IR proto for compiling.
This method will be used by DSL compiler to generate the corresponding IR.
Args:
component_spec: Optional. The ComponentSpec to help with the encoding.
Returns:
An executor spec proto.
"""
# TODO(b/158712976, b/161286496): Serialize executor specs for different
# platforms.
raise NotImplementedError('{}.{} does not support encoding into IR.'.format(
self.__module__, self.__class__.__name__))
def copy(self) -> 'ExecutorSpec':
"""Makes a copy of the ExecutorSpec.
An abstract method to implement to make a copy of the ExecutorSpec instance.
Deepcopy is preferred in the implementation. But if for any reason a
deepcopy is not able to be made because of some fields are not deepcopyable,
it is OK to make a shallow copy as long as the subfield is consider
globally immutable.
Returns:
A copy of ExecutorSpec.
"""
return cast('ExecutorSpec', copy.deepcopy(self))
class ExecutorClassSpec(ExecutorSpec):
"""A specification of executor class.
Attributes:
executor_class: a subclass of base_executor.BaseExecutor used to execute
this component (required).
extra_flags: extra flags to be set in the Python base executor.
"""
def __init__(self, executor_class: Type[base_executor.BaseExecutor]):
if not executor_class:
raise ValueError('executor_class is required')
self.executor_class = executor_class
self.extra_flags = []
super(ExecutorClassSpec, self).__init__()
def __reduce__(self):
# When executing on the Beam DAG runner, the ExecutorClassSpec instance
# is pickled using the "dill" library. To make sure that the executor code
# itself is not pickled, we save the class path which will be reimported
# by the worker in this custom __reduce__ function.
#
# See https://docs.python.org/3/library/pickle.html#object.__reduce__ for
# more details.
return (ExecutorClassSpec._reconstruct_from_executor_class_path,
(self.class_path,))
@property
def class_path(self):
"""Fully qualified class name for the executor class.
<executor_class_module>.<executor_class_name>
Returns:
Fully qualified class name for the executor class.
"""
return '{}.{}'.format(self.executor_class.__module__,
self.executor_class.__name__)
@staticmethod
def _reconstruct_from_executor_class_path(executor_class_path):
executor_class = import_utils.import_class_by_path(executor_class_path)
return ExecutorClassSpec(executor_class)
def encode(
self,
component_spec: Optional[types.ComponentSpec] = None) -> message.Message:
result = executable_spec_pb2.PythonClassExecutableSpec()
result.class_path = self.class_path
result.extra_flags.extend(self.extra_flags)
return result
def add_extra_flags(self, extra_flags: Iterable[str]) -> None:
self.extra_flags.extend(extra_flags)
def copy(self) -> 'ExecutorClassSpec':
# The __reduce__() method is customized and the function
# import_class_by_path() is used in it. import_class_by_path() doesn't work
# with nested class which is very common in tests. copy.deepcopy(self)
# desn't work.
# So in this implementation, a new
# ExecutorClassSpec is created and every field in the old instance is
# deepcopied to the new instance.
cls = self.__class__
result = cls.__new__(cls)
for k, v in self.__dict__.items():
setattr(result, k, copy.deepcopy(v))
return result
class ExecutorContainerSpec(ExecutorSpec):
"""A specification of a container.
The spec includes image, command line entrypoint and arguments for a
container. For example:
spec = ExecutorContainerSpec(
image='docker/whalesay',
command=['cowsay'],
args=['hello wolrd'])
Attributes:
image: Container image that has executor application. Assumption is that
this container image is separately release-managed, and tagged/versioned
accordingly.
command: Container entrypoint array. Not executed within a shell. The docker
image's ENTRYPOINT is used if this is not provided. The Jinja templating
mechanism is used for constructing a user-specified command-line
invocation based on input and output metadata at runtime.
args: Arguments to the container entrypoint. The docker image's CMD is used
if this is not provided. The Jinja templating mechanism is used for
constructing a user-specified command-line invocation based on input and
output metadata at runtime.
"""
def __init__(self,
image: Text,
command: List[Text] = None,
args: List[Text] = None):
if not image:
raise ValueError('image cannot be None or empty.')
self.image = image
self.command = command
self.args = args
super(ExecutorContainerSpec, self).__init__()
| [
"tensorflow-extended-nonhuman@googlegroups.com"
] | tensorflow-extended-nonhuman@googlegroups.com |
4c5707cd2ba9d17efea44451ba77c6004b84104a | ac4b9385b7ad2063ea51237fbd8d1b74baffd016 | /.history/google/drive_files_download_prepare_20210214184811.py | 86688cc510192a730867099d50d8918aaacbc36e | [] | no_license | preethanpa/ssoemprep | 76297ef21b1d4893f1ac2f307f60ec72fc3e7c6f | ce37127845253c768d01aeae85e5d0d1ade64516 | refs/heads/main | 2023-03-09T00:15:55.130818 | 2021-02-20T06:54:58 | 2021-02-20T06:54:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,610 | py | from __future__ import print_function
import pickle
import os.path
import io
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.http import MediaIoBaseDownload
from oauth2client.service_account import ServiceAccountCredentials
from google.oauth2 import service_account
import googleapiclient.discovery
import inspect
import sys
import json
SCOPES = ['https://www.googleapis.com/auth/documents',
'https://www.googleapis.com/auth/documents.readonly',
'https://www.googleapis.com/auth/documents.readonly',
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/drive.metadata.readonly',
'https://www.googleapis.com/auth/drive.readonly',
]
# The ID of a sample document.
# DOCUMENT_ID = '1bQkFcQrWFHGlte8oTVtq_zyKGIgpFlWAS5_5fi8OzjY'
DOCUMENT_ID = '1sXQie19gQBRHODebxBZv4xUCJy-9rGpnlpM7_SUFor4'
# SERVICE_ACCOUNT_FILE = '/home/dsie/Developer/sandbox/3ray/3rml/kbc_process/google/domain-wide-credentials-gdrive.json'
SERVICE_ACCOUNT_FILE = '/home/dsie/Developer/sandbox/3ray/3rml/kbc_process/google/app-automation-service-account-thirdrayai-1612747564720-415d6ebd6001.json'
UPLOAD_FILE_LOCATION = '/home/dsie/Developer/sandbox/3ray/3rml/kbc_process/documents/pdf/'
doc_types = {
"application/vnd.google-apps.document": "gdoc",
# "application/vnd.google-apps.folder": "folder",
"application/vnd.google-apps.spreadsheet": "gsheet",
"application/vnd.google-apps.presentation": "gslide"
}
drive_files_list = [] if (sys.argv is None or sys.argv[1] is None) else json.loads(sys.argv[1])
# google_file_type = 'gdoc' if (sys.argv is None or sys.argv[1] is None or sys.argv[1].google_file_type is None) else sys.argv[1].google_file_type
# target_file_type = 'pdf' if (sys.argv is None or sys.argv[1] is None or sys.argv[1].target_file_type is None) else sys.argv[1].target_file_type
# location = '/home/dsie/Developer/sandbox/3ray/3rml/kbc_process/drive_documents/'+drive_files_list.get('job_id')+'/pdf/'
# document_id = None if (sys.argv[1] is None or sys.argv[1].file_location is None) else sys.argv[1].document_id
document_id = ''
def get_resource(domain_wide_delegate=False, user_to_impersonate=None):
"""Prepare a Google Drive resource object based on credentials.
"""
credentials = None
# use subject in case of domain-wide delegation
if domain_wide_delegate:
if user_to_impersonate is not None:
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES, subject=user_to_impersonate)
else:
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
if credentials is None:
return credentials
else:
drive_service = build('drive', 'v3', credentials=credentials)
return drive_service
def download_drive_file(resource=None, document_id=None, google_file_type='gdoc', target_type=None, target_location=None):
"""Downloads a Google Drive file using the provided resource.
If google_file_type is passed as None, then 'gdoc' / Google Doc is default.
If target_type is passed as None, then 'application/pdf' is default.
If location is none, then use environment variable UPLOAD_FILE_LOCATION as default
"""
# print(dir(resource.files())) #Get resource methods with dir.
if resource is None:
raise Exception('Invalid credentials. Provide subject email addredd for Drive-wide delegation')
else:
extension, mimeType = extension_mime_type(google_file_type, target_type)
t
content = resource.files().export(fileId=document_id, mimeType=mimeType).execute()
with open(target_location+target_type+'-'+document_id+extension, "wb") as file:
file.write(content)
return {"status": "OK", "message": target_type+'-'+document_id+extension+" has been added to data lake."}
def extension_mime_type(google_file_ext=None, format=None):
export_type = None
if google_file_ext is not None:
if google_file_ext == 'gdoc':
if format == 'docx':
export_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
elif format == 'epub':
export_type = 'application/epub+zip'
elif format == 'html':
export_type = 'text/html'
elif format == 'odt':
export_type = 'application/vnd.oasis.opendocument.text'
elif format == 'pdf':
export_type = 'application/pdf'
elif format == 'rtf':
export_type = 'application/rtf'
elif format == 'tex':
export_type = 'application/zip'
elif format == 'txt':
export_type = 'text/plain'
elif format == 'html.zip':
export_type = 'application/zip'
else:
raise Exception('Unknown format "{}"'.format(format))
elif google_file_ext == 'gsheet':
if format == 'csv':
export_type = 'text/csv'
elif format == 'html.zip':
export_type = 'application/zip'
elif format == 'ods':
export_type = 'application/x-vnd.oasis.opendocument.spreadsheet'
elif format == 'pdf':
export_type = 'application/pdf'
elif format == 'tsv':
export_type = 'text/tab-separated-values'
elif format == 'xlsx':
export_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
else:
raise Exception('Unknown format "{}"'.format(format))
elif google_file_ext == 'gslide':
if format == 'odp':
export_type = 'application/vnd.oasis.opendocument.presentation'
elif format == 'pdf':
export_type = 'application/pdf'
elif format == 'pptx':
export_type = 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
elif format == 'txt':
export_type = 'text/plain'
else:
raise Exception('Unknown format "{}"'.format(format))
else:
raise Exception('Unknown Google document extension "{}"'.format(google_file_ext))
return '.'+format, export_type
if drive_files_list == []:
print(json.dumps(drive_files_list))
else:
location = os.path.join('/home/dsie/Developer/sandbox/3ray/3rml/kbc_process/drive_documents/', drive_files_list.get('job_id')+'/pdf/')
os.makedirs(location)
response_message = {
"status": "OK",
"processed_files": []
}
for index, item in enumerate(drive_files_list.get('files')):
try:
google_file_type = doc_types[item.get('mimeType')]
drive_document_id = item.get('id')
target_file_type = "pdf"
dl_response = download_drive_file(resource=get_resource(domain_wide_delegate=False), document_id=drive_document_id, google_file_type=google_file_type, target_type=target_file_type, target_location=location)
response_message["processed_files"].append(dl_response)
except KeyError as ke:
pass
print(json.dumps(response_message))
# print(download_drive_file(resource=get_resource(domain_wide_delegate=False)), google_file_type=google_file_type, target_type=target_file_type, target_location=location) | [
"{abhi@third-ray.com}"
] | {abhi@third-ray.com} |
7391c196678a5851d5df375ccb31973f5f4308d5 | faa390890e17219fd763bd66e66bb6753c692b14 | /jacinle/comm/__init__.py | 31090e96df5a3363aa5d28bc73146df1406c9cf6 | [
"MIT"
] | permissive | vacancy/Jacinle | 7170b1c798e4a903186abe74d28e4a7e034ec766 | 20021790fd32ef1ad40c67fba7582c6db54235da | refs/heads/master | 2023-07-20T03:54:46.693649 | 2023-07-12T21:00:10 | 2023-07-12T21:00:10 | 117,910,172 | 135 | 275 | MIT | 2023-01-18T17:41:33 | 2018-01-18T00:35:55 | Python | UTF-8 | Python | false | false | 228 | py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File : __init__.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 01/22/2018
#
# This file is part of Jacinle.
# Distributed under terms of the MIT license.
| [
"maojiayuan@gmail.com"
] | maojiayuan@gmail.com |
bc044afaa2aa7c550a0e4c305793d3073561ab60 | 444a9480bce2035565332d4d4654244c0b5cd47b | /official/cv/OCRNet/convert_from_torch.py | 4d18c05e48df3f7270f9673f7922b6241774d711 | [
"LicenseRef-scancode-proprietary-license",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | mindspore-ai/models | 7ede9c6454e77e995e674628204e1c6e76bd7b27 | eab643f51336dbf7d711f02d27e6516e5affee59 | refs/heads/master | 2023-07-20T01:49:34.614616 | 2023-07-17T11:43:18 | 2023-07-17T11:43:18 | 417,393,380 | 301 | 92 | Apache-2.0 | 2023-05-17T11:22:28 | 2021-10-15T06:38:37 | Python | UTF-8 | Python | false | false | 4,078 | py | # Copyright 2022 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""HRNet conversion from torch."""
import argparse
import pickle
import torch
from mindspore import Parameter, load_param_into_net, save_checkpoint
from src.config import config_hrnetv2_w48 as config
from src.seg_hrnet import HighResolutionNet
def parse_args():
"""Get arguments from command-line."""
parser = argparse.ArgumentParser(description="Convert HRNetW48_seg weights from torch to mindspore.")
parser.add_argument("--torch_path", type=str, default=None, help="Path to input torch model.")
parser.add_argument("--numpy_path", type=str, default=None,
help="Path to save/load intermediate numpy representation.")
parser.add_argument("--mindspore_path", type=str, default=None, help="Path to save result mindspore model.")
return parser.parse_args()
def torch2numpy(input_torch, out_numpy=None):
"""
Convert torch model to numpy
Args:
input_torch: path to .pth model
out_numpy: path to save .npy model (if None will not save)
Returns:
dict of numpy weights
"""
weights = torch.load(input_torch)
weights_numpy = {k: v.detach().cpu().numpy() for k, v in weights.items()}
if out_numpy:
with open(out_numpy, 'wb') as fp:
pickle.dump(weights_numpy, fp)
return weights_numpy
def numpy2mindspore(input_numpy, out_mindspore):
"""
Convert numpy model weights to mindspore
Args:
input_numpy: path to .npy weights or dict of numpy arrays
out_mindspore: path to output mindspore model
"""
if isinstance(input_numpy, str):
with open(input_numpy, 'rb') as fp:
weights_numpy = pickle.load(fp)
else:
weights_numpy = input_numpy
net = HighResolutionNet(config.model, 19)
sample_ms = net.parameters_dict()
weights_ms = {}
miss_in_ms = set()
for k in weights_numpy.keys():
if k.endswith('.num_batches_tracked'):
continue
new_k = k
if k.rsplit('.', 1)[0] + '.running_mean' in weights_numpy.keys():
new_k = new_k.replace('weight', 'gamma').replace('bias', 'beta')
new_k = new_k.replace('running_mean', 'moving_mean').replace('running_var', 'moving_variance')
if new_k not in sample_ms.keys():
miss_in_ms.add(k)
continue
weights_ms[new_k] = Parameter(weights_numpy[k], name=new_k)
print('Missed in mindspore:\n', miss_in_ms)
print('Missed from mindspore:\n', set(sample_ms.keys()) - set(weights_ms.keys()))
load_param_into_net(net, weights_ms)
save_checkpoint(net, out_mindspore)
def convert():
""" Full convert pipeline """
args = parse_args()
if not args.torch_path and not args.numpy_path:
raise ValueError('torch_path or numpy_path must be defined as input')
if not args.mindspore_path and not args.numpy_path:
raise ValueError('mindspore_path or numpy_path must be defined as output')
numpy_weights = None
if args.torch_path:
numpy_weights = torch2numpy(input_torch=args.torch_path, out_numpy=args.numpy_path)
print('Converted to numpy!')
if args.mindspore_path:
if not numpy_weights:
numpy_weights = args.numpy_path
numpy2mindspore(input_numpy=numpy_weights, out_mindspore=args.mindspore_path)
print('Converted to mindspore!')
if __name__ == '__main__':
convert()
| [
"a.denisov@expasoft.tech"
] | a.denisov@expasoft.tech |
8374d54bebd6681df61f6a480be5b6a013cc4aaa | 1b34447fff2b0c08d5b43257b441b82f3faa263a | /bloogle-bot/blooglebot/spiders/theverge_spider.py | 050967b104b0a3840bb4caf49601b88b3c68bd97 | [] | no_license | Folch/bloogle | ded7a4986139e50ffc1b372e1c6a348b9524f58c | fd573c5948fd14945411e75c22f71ce45e9747b9 | refs/heads/master | 2020-05-03T16:55:11.349542 | 2019-03-31T19:42:43 | 2019-03-31T19:42:43 | 178,734,386 | 1 | 0 | null | 2019-03-31T19:45:28 | 2019-03-31T19:45:28 | null | UTF-8 | Python | false | false | 180 | py | from .simple_base_spider import SimpleBaseSpider
class TheVergeSpider(SimpleBaseSpider):
name = 'theverge'
def get_domain(self):
return 'https://www.theverge.com' | [
"xaviml.93@gmail.com"
] | xaviml.93@gmail.com |
2f058e998fff357b00f55662b8586e74272472e7 | 2fb8fa04d520a0b6fde6f737467e4ff5f8b1c8d2 | /add.py | bedba07af9cfb067b2441297e4063ea8f7741216 | [] | no_license | Dhiraj4016/batch89 | 3bd11ae67d39cc43cd816d3c1ccca425833b2e3d | 8cdc01853c00eaf009b20024b9e25ddcc29b7bda | refs/heads/master | 2020-06-07T12:57:11.581541 | 2019-06-21T03:56:06 | 2019-06-21T03:56:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 312 | py | '''a=int(input("enter Any number"))
b=int (input("enter Any number"))
c = a + b
print("sum=",c)'''
name = input("enter your name")
print(name)
data= input("Are you a student if yes press y else n")
print(data[0])
print(data)
data1= input("Are you a student if yes press y else n")[0]
print(data1)
print(data1)
| [
"aswanibtech@gmail.com"
] | aswanibtech@gmail.com |
68fd786f367e1dd95ac1d5c0cf2a28069117e1e6 | 276dd5dd778adefd039e6f6a71dc574386729401 | /demo2/webapp/app.py | dbe50b9132d718d8d8a8d8ec04892046463991de | [
"MIT"
] | permissive | amitsaha/python-grpc-demo | 4880e64b4b993df4b7eb96f2946b6607fb2dfa82 | 48546bfda83062a3fcb015d352fecb46346e8c92 | refs/heads/master | 2023-01-12T10:01:36.396783 | 2022-10-08T05:10:39 | 2022-10-08T05:10:39 | 101,063,881 | 145 | 52 | MIT | 2022-12-27T17:26:21 | 2017-08-22T13:07:17 | Python | UTF-8 | Python | false | false | 757 | py | from flask import Flask, Response
import sys
from google.protobuf.json_format import MessageToJson
from client_wrapper import ServiceClient
import users_pb2_grpc as users_service
import users_types_pb2 as users_messages
app = Flask(__name__)
app.config['users'] = ServiceClient(users_service, 'UsersStub', 'users', 50051)
@app.route('/users/')
def users_get():
request = users_messages.GetUsersRequest(
user=[users_messages.User(username="alexa", user_id=1),
users_messages.User(username="christie", user_id=1)]
)
def get_user():
response = app.config['users'].GetUsers(request)
for resp in response:
yield MessageToJson(resp)
return Response(get_user(), content_type='application/json') | [
"amitsaha.in@gmail.com"
] | amitsaha.in@gmail.com |
e6b276124f6f834603cf0301a93b00fed97d9445 | 275b16af98827504d4de75c5d45afa09d0a84b8c | /tests/messages/server/test_result_message_parser.py | fb0346ed890136b496c853af3c2b95768ec9b05d | [
"Apache-2.0"
] | permissive | foxdog-studios/pyddp | e63bec12fffc5f87e9a44b0bf9de7bedae71d517 | a4ac0bd5d8a2f350e012fd65d79e0034a89d8e67 | refs/heads/dev | 2021-01-02T08:45:41.081693 | 2015-05-31T15:10:29 | 2015-05-31T15:10:29 | 13,887,437 | 10 | 5 | Apache-2.0 | 2018-03-05T17:42:18 | 2013-10-26T17:12:39 | Python | UTF-8 | Python | false | false | 1,968 | py | # -*- coding: utf-8 -*-
# Copyright 2014 Foxdog Studios
#
# 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
import unittest
from ddp.messages.server.result_message import ResultMessage
from ddp.messages.server.result_message_parser import ResultMessageParser
class ResultMessageParserTestCase(unittest.TestCase):
def setUp(self):
self.parser = ResultMessageParser()
self.id = 'id'
self.error = 'error'
self.result = {'result': [True, 1.0]}
def test_with_error(self):
message = self.parser.parse({'msg': 'result', 'id': self.id,
'error': self.error})
self.assertEqual(message, ResultMessage(self.id, error=self.error))
def test_with_result(self):
message = self.parser.parse({'msg': 'result', 'id': self.id,
'result': self.result})
self.assertEqual(message, ResultMessage(self.id, result=self.result))
def test_with_error_with_result(self):
with self.assertRaises(ValueError):
self.parser.parse({'msg': 'result', 'id': self.id,
'error': self.error, 'result': self.result})
def test_without_error_without_reuslt(self):
message = self.parser.parse({'msg': 'result', 'id': self.id})
self.assertEqual(message, ResultMessage(self.id))
| [
"foxxy@foxdogstudios.com"
] | foxxy@foxdogstudios.com |
6324c47b3a02c8328fa9a73edda997ad76230713 | 518bf342bc4138982af3e2724e75f1d9ca3ba56c | /solutions/2370. Longest Ideal Subsequence/2370.py | 1b387f7c2ce92430d9791134800f76c0ce754e38 | [
"MIT"
] | permissive | walkccc/LeetCode | dae85af7cc689882a84ee5011f0a13a19ad97f18 | a27be41c174565d365cbfe785f0633f634a01b2a | refs/heads/main | 2023-08-28T01:32:43.384999 | 2023-08-20T19:00:45 | 2023-08-20T19:00:45 | 172,231,974 | 692 | 302 | MIT | 2023-08-13T14:48:42 | 2019-02-23T15:46:23 | C++ | UTF-8 | Python | false | false | 506 | py | class Solution:
def longestIdealString(self, s: str, k: int) -> int:
# dp[i] := longest subseq that ends at ('a' + i)
dp = [0] * 26
for c in s:
i = ord(c) - ord('a')
dp[i] = 1 + self._getMaxReachable(dp, i, k)
return max(dp)
def _getMaxReachable(self, dp: List[int], i: int, k: int) -> int:
first = max(0, i - k)
last = min(25, i + k)
maxReachable = 0
for j in range(first, last + 1):
maxReachable = max(maxReachable, dp[j])
return maxReachable
| [
"me@pengyuc.com"
] | me@pengyuc.com |
9a4edd570cf19c80e4d21640897a0de5b4bfc863 | d214b72b3ae340d288c683afe356de6846a9b09d | /括号类/使括号有效的最少添加_921.py | d19e8d350a25ab41893dfe2a1a6db26563fa58bb | [] | no_license | Xiaoctw/LeetCode1_python | 540af6402e82b3221dad8648bbdcce44954a9832 | b2228230c90d7c91b0a40399fa631520c290b61d | refs/heads/master | 2021-08-29T15:02:37.786181 | 2021-08-22T11:12:07 | 2021-08-22T11:12:07 | 168,444,276 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 447 | py | from typing import *
class Solution:
def minAddToMakeValid(self, S: str) -> int:
stack=[]
cnt=0
for c in S:
if c=='(':
stack.append(c)
else:
if not stack:
cnt+=1
else:
stack.pop()
return cnt+len(stack)
if __name__ == '__main__':
sol=Solution()
s='()))(('
print(sol.minAddToMakeValid(s)) | [
"m18846183092@163.com"
] | m18846183092@163.com |
e19f03b66bd26f3d7fc8dd5e3735dd2b75cd2ef8 | 702f22704e5485aff356b4d1b6f1dea51bd95fa4 | /grd_web_edit/tools/handler/modify_handler.py | 6dab3c01e736e30f972f6e3ed148329bbdf56ef1 | [] | no_license | 510908220/chromium_grd_tool | 9b20986e6c5a825eeff4447a9ec91416b3188087 | 4b649c74f49d8515a5bf362828b48cae2f8ce6d0 | refs/heads/master | 2021-03-12T23:56:51.201622 | 2015-08-21T06:06:45 | 2015-08-21T06:06:45 | 41,099,166 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,320 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#encoding:utf-8
__author__ = 'Administrator'
import xml_node
import conf
import util
import history_handler
import innerdb
def get_message_info(message_name):
"""
return:
message_string
message_text
"""
grd = xml_node.Grd(conf.grd_path)
message_info = grd.get_message_node_string(message_name)
return message_info
def get_translation_text(id_):
xtb = xml_node.XTB(conf.xtb_path)
translation_node = xtb.get_translation_node(id_)
if translation_node is not None:
return translation_node.text
def search(message_name):
message_info = get_message_info(message_name)
if message_info is not None:
id_ = util.generate_message_id(message_info[1].strip())
print id_
translation_text = get_translation_text(id_)
print "translation_text:", translation_text, type(translation_text)
message_str = message_info[0]
if translation_text is not None:
return {"translation_text":translation_text.encode("utf-8"),"message_str":message_str}
else:
return {"message_str":message_str}
return {}
def delete(message_name):
message_info = get_message_info(message_name)
ret_info = {"ret":'false', "info":"no such message node"}
if message_info is not None:
id_ = util.generate_message_id(message_info[1])
grd = xml_node.Grd(conf.grd_path)
message_flag = grd.remove(message_name)
xtb = xml_node.XTB(conf.xtb_path)
xtb_flag = xtb.delete(id_)
if message_flag and xtb_flag:#删除成功才保存使生效
grd.save()
xtb.save()
ret_info["ret"] = 'true'
ret_info["info"] = ""
history_handler.delete_history(message_name)
else:
ret_info["ret"] = 'false'
ret_info["info"] = grd.error_info + "/" + xtb.error_info
return ret_info
def update(message_name, translation_desc):
message_info = get_message_info(message_name)
ret_info = {"ret":'false', "info":"update faile"}
if message_info is not None:
id_ = util.generate_message_id(message_info[1])
xtb = xml_node.XTB(conf.xtb_path)
xtb_flag = xtb.update(id_, translation_desc)
if xtb_flag:
xtb.save()
ret_info["ret"] = "true"
ret_info["info"] = ""
with innerdb.InnerDb() as db:
db.write(str(message_name),{"id":id_,"translation_desc":translation_desc})
else:
ret_info["ret"] = "false"
ret_info["info"] = xtb.error_info
return ret_info
| [
"510908220@qq.com"
] | 510908220@qq.com |
58b5c70bbc6fd1570d661922bbc81850e967a9d4 | e2f400d159ca0abb82e35af7eeedc4eebc3333e7 | /desktop/core/src/desktop/lib/rest/http_client.py | e0b90f9979300b77e4e731021e47046aecbc5742 | [
"Apache-2.0"
] | permissive | optimistdk/hue | a40ad47b33fc395fadc02840c5f707d8890e5bdc | 417d7e18b87faae1157c60f949da61cd3075ed98 | refs/heads/master | 2021-01-17T21:43:52.399457 | 2012-07-30T17:17:07 | 2012-07-30T17:17:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,954 | py | # Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import cookielib
import logging
import posixpath
import types
import urllib
import urllib2
from urllib2_kerberos import HTTPKerberosAuthHandler
__docformat__ = "epytext"
LOG = logging.getLogger(__name__)
class RestException(Exception):
"""
Any error result from the Rest API is converted into this exception type.
"""
def __init__(self, error):
Exception.__init__(self, error)
self._error = error
self._code = None
self._message = str(error)
# See if there is a code or a message. (For urllib2.HTTPError.)
try:
self._code = error.code
self._message = error.read()
except AttributeError:
pass
def __str__(self):
res = self._message or ""
if self._code is not None:
res += " (error %s)" % (self._code,)
return res
def get_parent_ex(self):
if isinstance(self._error, Exception):
return self._error
return None
@property
def code(self):
return self._code
@property
def message(self):
return self._message
class HttpClient(object):
"""
Basic HTTP client tailored for rest APIs.
"""
def __init__(self, base_url, exc_class=None, logger=None):
"""
@param base_url: The base url to the API.
@param exc_class: An exception class to handle non-200 results.
Creates an HTTP(S) client to connect to the Cloudera Manager API.
"""
self._base_url = base_url.rstrip('/')
self._exc_class = exc_class or RestException
self._logger = logger or LOG
self._headers = { }
# Make a cookie processor
cookiejar = cookielib.CookieJar()
self._opener = urllib2.build_opener(
HTTPErrorProcessor(),
urllib2.HTTPCookieProcessor(cookiejar))
def set_basic_auth(self, username, password, realm):
"""
Set up basic auth for the client
@param username: Login name.
@param password: Login password.
@param realm: The authentication realm.
@return: The current object
"""
# Make a basic auth handler that does nothing. Set credentials later.
passmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
passmgr.add_password(realm, self._base_url, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passmgr)
self._opener.add_handler(authhandler)
return self
def set_kerberos_auth(self):
"""Set up kerberos auth for the client, based on the current ticket."""
authhandler = HTTPKerberosAuthHandler()
self._opener.add_handler(authhandler)
return self
def set_headers(self, headers):
"""
Add headers to the request
@param headers: A dictionary with the key value pairs for the headers
@return: The current object
"""
self._headers = headers
return self
@property
def base_url(self):
return self._base_url
@property
def logger(self):
return self._logger
def _get_headers(self, headers):
res = self._headers.copy()
if headers:
res.update(headers)
return res
def execute(self, http_method, path, params=None, data=None, headers=None):
"""
Submit an HTTP request.
@param http_method: GET, POST, PUT, DELETE
@param path: The path of the resource. Unsafe characters will be quoted.
@param params: Key-value parameter data.
@param data: The data to attach to the body of the request.
@param headers: The headers to set for this request.
@return: The result of urllib2.urlopen()
"""
# Prepare URL and params
path = urllib.quote(smart_str(path))
url = self._make_url(path, params)
if http_method in ("GET", "DELETE"):
if data is not None:
self.logger.warn(
"GET method does not pass any data. Path '%s'" % (path,))
data = None
# Setup the request
request = urllib2.Request(url, data)
# Hack/workaround because urllib2 only does GET and POST
request.get_method = lambda: http_method
headers = self._get_headers(headers)
for k, v in headers.items():
request.add_header(k, v)
# Call it
self.logger.debug("%s %s" % (http_method, url))
try:
return self._opener.open(request)
except (urllib2.HTTPError, urllib2.URLError), ex:
raise self._exc_class(ex)
def _make_url(self, path, params):
res = self._base_url
if path:
res += posixpath.normpath('/' + path.lstrip('/'))
if params:
param_str = urllib.urlencode(params)
res += '?' + param_str
return iri_to_uri(res)
class HTTPErrorProcessor(urllib2.HTTPErrorProcessor):
"""
Python 2.4 only recognize 200 and 206 as success. It's broken. So we install
the following processor to catch the bug.
"""
def http_response(self, request, response):
if 200 <= response.code < 300:
return response
return urllib2.HTTPErrorProcessor.http_response(self, request, response)
https_response = http_response
#
# Method copied from Django
#
def iri_to_uri(iri):
"""
Convert an Internationalized Resource Identifier (IRI) portion to a URI
portion that is suitable for inclusion in a URL.
This is the algorithm from section 3.1 of RFC 3987. However, since we are
assuming input is either UTF-8 or unicode already, we can simplify things a
little from the full method.
Returns an ASCII string containing the encoded result.
"""
# The list of safe characters here is constructed from the "reserved" and
# "unreserved" characters specified in sections 2.2 and 2.3 of RFC 3986:
# reserved = gen-delims / sub-delims
# gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
# sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
# / "*" / "+" / "," / ";" / "="
# unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
# Of the unreserved characters, urllib.quote already considers all but
# the ~ safe.
# The % character is also added to the list of safe characters here, as the
# end of section 3.1 of RFC 3987 specifically mentions that % must not be
# converted.
if iri is None:
return iri
return urllib.quote(smart_str(iri), safe="/#%[]=:;$&()+,!?*@'~")
#
# Method copied from Django
#
def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Returns a bytestring version of 's', encoded as specified in 'encoding'.
If strings_only is True, don't convert (some) non-string-like objects.
"""
if strings_only and isinstance(s, (types.NoneType, int)):
return s
elif not isinstance(s, basestring):
try:
return str(s)
except UnicodeEncodeError:
if isinstance(s, Exception):
# An Exception subclass containing non-ASCII data that doesn't
# know how to print itself properly. We shouldn't raise a
# further exception.
return ' '.join([smart_str(arg, encoding, strings_only,
errors) for arg in s])
return unicode(s).encode(encoding, errors)
elif isinstance(s, unicode):
return s.encode(encoding, errors)
elif s and encoding != 'utf-8':
return s.decode('utf-8', errors).encode(encoding, errors)
else:
return s
| [
"bcwalrus@cloudera.com"
] | bcwalrus@cloudera.com |
ec8fab1581b91290cbc80f32f5189bf5668fbae2 | 2b7efe276d1dfdc70a4b5cd59ae863b7b7a1bd58 | /euler121.py | 596e9fa74a1af624297a392aad4c6bdc67a2e48c | [] | no_license | mckkcm001/euler | 550bbd126e8d9bb5bc7cb854147399060f865cfc | 8cf1db345b05867d47921b01e8c7e4c2df4ee98d | refs/heads/master | 2021-01-01T17:43:28.799946 | 2017-11-07T02:17:34 | 2017-11-07T02:17:34 | 18,375,089 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 280 | py | from fractions import Fraction
rounds = 1
odds = Fraction(blue,blue+red)
def chances(rounds):
red = 0
blue = 0
bag_red = 1
bag_blue = 1
for i in range(rounds):
for i in range(rounds):
red += 1
odds *= Fraction(blue,blue+red)
print(odds)
| [
"noreply@github.com"
] | mckkcm001.noreply@github.com |
daf5e135c93d1a2cd279020eb00f833972745212 | d7d53826ab804a3d0f229b0a189f2626d4ebe99b | /payment/models.py | a029297c35becab4fbd5c326718b5fa46a280bd2 | [] | no_license | zbcbcbc/xiaomaifeng | 6e299e7f1d13dbca95af7a1e46d66dd0d1c86b08 | 91b7da9404678227d3c2c4a446777be6dacdedb7 | refs/heads/master | 2020-12-02T16:58:26.661967 | 2016-09-04T17:53:51 | 2016-09-04T17:53:51 | 67,359,821 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,254 | py | # -*- coding: utf-8 -*-
#
# Copyright 2013 XiaoMaiFeng
__author__ = "Bicheng Zhang"
__copyright__ = "Copyright 2013, XiaoMaiFeng"
from django.db import models
__all__ = ['PartnerTradeBaseModel','DirectPayBaseModel', 'PartnerTradeBaseManager', 'DirectPayBaseManager']
class PaymentBaseManager(models.Manager):
def verify_payment(self, params):
raise NotImplementedError
def update_payment(self, params):
raise NotImplementedError
class PaymentBaseModel(models.Model):
"""
"""
xmf_order = models.OneToOneField('orders.Order', primary_key=True, null=False, on_delete=models.CASCADE,
blank=False,
related_name="%(class)s",
editable=False, )
is_verified = models.BooleanField(null=False, default=False, editable=True)
class Meta:
abstract = True
def __repr__(self):
return u"%s:(%s)" % (self, self.pk)
def _verify_success(self, **kwargs):
"""
交易认证成功逻辑:
如果认证成功,发送认证成功信号
"""
raise NotImplementedError
def _verify_fail(self, reason, re_verify=True, **kwargs):
"""
交易认证成功逻辑:
如果认证成功,发送认证失败信号
"""
raise NotImplementedError
def build_verify_url(self, write_to_db=False, **kwargs):
"""
建立支付认证url
"""
raise NotImplementedError
class PartnerTradeBaseManager(PaymentBaseManager):
def create_payment(self, payer, receiver, comment, social_platform, body, item, quantity):
raise NotImplementedError
class PartnerTradeBaseModel(PaymentBaseModel):
class Meta(PaymentBaseModel.Meta):
abstract = True
def shippment_confirm_success(self, **kwargs):
"""
交易货物寄送成功:
如果认证成功,发送寄送货物成功信号
"""
raise NotImplementedError
def shippment_confirm_fail(self, reason, re_verify=True, **kwargs):
"""
交易货物寄送成功:
如果认证成功,发送寄送货物成功信号
"""
raise NotImplementedError
class DirectPayBaseManager(PaymentBaseManager):
def create_payment(self, payer, receiver, comment, social_platform, body, fund):
raise NotImplementedError
class DirectPayBaseModel(PaymentBaseModel):
class Meta(PaymentBaseModel.Meta):
abstract = True
| [
"viczhang1990@gmail.com"
] | viczhang1990@gmail.com |
293b781a84a06c23dcb33282f1187f182d64d46e | 853d4cec42071b76a80be38c58ffe0fbf9b9dc34 | /venv/Lib/site-packages/pip/_internal/operations/build/wheel.py | 5a43e43f72d487fc34b5e42c4afc6f2d625df89e | [] | no_license | msainTesting/TwitterAnalysis | 5e1646dbf40badf887a86e125ef30a9edaa622a4 | b1204346508ba3e3922a52380ead5a8f7079726b | refs/heads/main | 2023-08-28T08:29:28.924620 | 2021-11-04T12:36:30 | 2021-11-04T12:36:30 | 424,242,582 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,100 | py | import logging
import os
from typing import Optional
from pip._vendor.pep517.wrappers import Pep517HookCaller
from pip._internal.utils.subprocess import runner_with_spinner_message
logger = logging.getLogger(__name__)
def build_wheel_pep517(
name: str,
backend: Pep517HookCaller,
metadata_directory: str,
tempd: str,
) -> Optional[str]:
"""Build one InstallRequirement using the PEP 517 build process.
Returns path to wheel if successfully built. Otherwise, returns None.
"""
assert metadata_directory is not None
try:
logger.debug("Destination directory: %s", tempd)
runner = runner_with_spinner_message(
f"Building wheel for {name} (pyproject.toml)"
)
with backend.subprocess_runner(runner):
wheel_name = backend.build_wheel(
tempd,
metadata_directory=metadata_directory,
)
except Exception:
logger.error("Failed building wheel for %s", name)
return None
return os.path.join(tempd, wheel_name)
| [
"msaineti@icloud.com"
] | msaineti@icloud.com |
9182965cf5743dc890b618905174e89ec27a0f10 | 534e9eb7da6450a58876b284272d515ff8595730 | /base/factories.py | bee9c8e09ec3c02bf5ab2d091d098737a64a1bd8 | [] | no_license | Asingjr2/todos_dj | a188946c45e435faf7e57f912676af23f03356f6 | a1e08f27a81f9bfa3336dfcee036cbb325f7b63e | refs/heads/master | 2020-03-24T09:57:34.460300 | 2018-09-13T00:57:09 | 2018-09-13T00:57:09 | 142,643,266 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 173 | py | import factory
from .models import BaseModel
class BaseModelFactory(factory.django.DjangoModelFactory):
class Meta:
model = BaseModel
abstract = True | [
"asingjr2@gmail.com"
] | asingjr2@gmail.com |
6f28abf08eb082e5601825a559cb2c2981c18ca4 | 71764665e27f4b96bab44f38a4a591ffc2171c24 | /hhplt/productsuite/OBU_tc56/mock_suite_3.py | 2e1584d638d34317a197e435489c2eba9d8dd1cb | [] | no_license | kingdomjc/RSU_production_VAT | 693f8c504acc0cc88af92942734ccb85f7e7d7c0 | 9a3d6d3f5a5edfaf30afdff725661630aafe434c | refs/heads/master | 2020-07-31T05:03:46.699606 | 2019-09-24T02:09:53 | 2019-09-24T02:09:53 | 210,491,514 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,981 | py | #encoding:utf-8
u'''这项测试又是虚拟测试项,用于调试'''
import time
from threading import RLock
suiteName = u'''并行虚拟测试项3'''
version = "1.0"
failWeightSum = 10 #整体不通过权值,当失败权值和超过此,判定测试不通过
from hhplt.testengine.exceptions import TestItemFailException,AbortTestException
from hhplt.parameters import SESSION
from hhplt.testengine.parallelTestSynAnnotation import syntest,serialSuite
def finalFun(product):
pass
def setup(product):
pass
serialIdCode = 1000
def T_01_initFactorySetting_A(product):
u'''出厂信息写入-出厂信息写入(包括MAC地址,唤醒灵敏度参数)'''
global serialIdCode
serialIdCode += 1
product.setTestingProductIdCode("%.5d"%serialIdCode)
# raise AbortTestException(message=u"终止了啊")
time.sleep(0.5)
#@syntest
def T_03_soundLight_M(product):
u'''声光指示测试-指示灯显示正常,蜂鸣器响声正常。人工确认后才停止显示和响'''
global serialIdCode
product.addBindingCode(u"PID","%.5d"%(serialIdCode+10))
product.addBindingCode(u"中文","%.5d"%(serialIdCode+10))
time.sleep(0.5)
def T_04_BatteryVoltage_A(product):
u'''电池电路电压测试-返回电池电路电压值,后台根据配置判定'''
global serialIdCode
product.addBindingCode(u"EPC","%.5d"%(serialIdCode+100))
time.sleep(0.5)
return {u"槽思密达":product.productSlot}
@syntest
def T_05_anotherSoundLight_M(product):
u'''又一个声光指示测试-指示灯显示正常,蜂鸣器响声正常。人工确认后才停止显示和响'''
time.sleep(1)
from hhplt.testengine.manul import manulCheck
if manulCheck(u"声光指示测试", u"请确认槽位【%s】破玩意是正常亮了吗?"%product.productSlot):
return {"随便写的返回值":300}
else:
raise TestItemFailException(failWeight = 10,message = u'声光测试失败')
| [
"929593844@qq.com"
] | 929593844@qq.com |
05c4564a86b21d10499757b085d1b233d309d25b | 4e60e8a46354bef6e851e77d8df4964d35f5e53f | /share/Tornado/databases_share.py | 62c25ddacece769d8b5b612f0a4203f260ca0128 | [] | no_license | cq146637/DockerManagerPlatform | cbae4154ad66eac01772ddd902d7f70b62a2d856 | 9c509fb8dca6633ed3afdc92d4e6491b5d13e322 | refs/heads/master | 2021-04-09T13:58:14.117752 | 2018-03-19T13:41:04 | 2018-03-19T13:41:04 | 125,712,276 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,764 | py | # -*- coding: utf-8 -*-
__author__ = 'CQ'
import pymysql
import logging
logger = logging.getLogger(__name__)
class MysqlServer(object):
"""
Tornado通用连接数据库类
用pymysql替代tornado使得操作数据库更加灵活,定制化
"""
def __init__(self, db_config):
try:
self._db_config = db_config
self._conn = self.__get_conn()
self._cursor = self._conn.curson()
except Exception:
self.close()
logger.exception(u"数据库连接失败")
def __get_conn(self):
connection = pymysql.connect(host=self._db_config['HOST'],
port=self._db_config['PORT'],
user=self._db_config['USERNAME'],
password=self._db_config['PASSWORD'],
db=self._db_config['DB_NAME'],
charset=self._db_config['CHAR_SET'],
)
connection.ping(True)
return connection
def ensure_cursor(self):
if not self._cursor:
if not self._conn:
self._conn = self.__get_conn()
self._cursor = self._conn.cursor()
def run_sql(self, sql):
"""
执行完SQL语句需要返回结果
:param sql:
:return:
"""
self.ensure_cursor()
self._cursor.execute(sql)
# commit只对innodb生效,不加commit的话,修改数据库记录的操作不会生效。
# 如果是myisam引擎的话,不需要commit即可生效
self._conn.commit()
return self._cursor.fetchall()
def execute_sql(self, sql):
"""
执行SQL语句无返回值
:param sql:
:return:
"""
self.ensure_cursor()
self._cursor.execute(sql)
self._conn.commit()
def run_sql_fetchone(self, sql):
"""
执行SQL返回一条结果
:param sql:
:return:
"""
self.ensure_cursor()
self._cursor.execute(sql)
return self._cursor.fetchone()
def close(self):
if self._cursor:
self._cursor.close()
if self._conn:
self._conn.close()
logger.info(u"关闭数据库连接")
def test():
settings = {
'HOST': "127.0.0.1",
'PORT': "3306",
'USERNAME': "root",
'PASSWORD': "123456",
'DB_NAME': "test",
'CHAR_SET': "utf8",
}
db = MysqlServer(settings)
sql = "select distinct `node_name` from tb_node"
ret = db.run_sql(sql)
db.close()
return ret
if __name__ == "__main__":
print(test())
| [
"1016025625@qq.com"
] | 1016025625@qq.com |
8a6e89aefd0aab863690b3f259ff2bcd29002021 | 9b54e3d58447e917a238b85891020c392c4ac601 | /acmicpc/14470/14470.py | 67e4bb02871ebb7925dcbc02a4a5f31a47ccf24e | [
"MIT"
] | permissive | love-adela/algorithm-ps | ea0ebcd641a4c309348b389b8618daa83973f4b2 | c92d105d8ad344def001160367115ecf99d81c0d | refs/heads/master | 2023-05-11T03:37:11.750692 | 2023-04-30T17:31:30 | 2023-04-30T17:31:30 | 174,651,672 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 162 | py | a = int(input())
b = int(input())
c = int(input())
d = int(input())
e = int(input())
if a < 0:
time = -a* c + d +b *e
else:
time = (b-a) * e
print(time)
| [
"love.adelar@gmail.com"
] | love.adelar@gmail.com |
95d4af7b8cfb565d8293b6691bd035ddde66ad43 | f0d713996eb095bcdc701f3fab0a8110b8541cbb | /Z8REdTE5P57f4q7dK_19.py | 9bdc112052430aebd5d4e5509f2a4327f341d3b4 | [] | 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 | 1,271 | py | """
A Collatz sequence is generated like this. Start with a positive number. If
it's even, halve it. If it's odd, multiply it by three and add one. Repeat the
process with the resulting number. The Collatz Conjecture is that every
sequence eventually reaches 1 (continuing past 1 just results in an endless
repeat of the sequence `4, 2, 1`).
The length of the sequence from starting number to 1 varies widely.
Create a function that takes a number as an argument and returns a tuple of
two elements — the number of steps in the Collatz sequence of the number, and
the highest number reached.
### Examples
collatz(2) ➞ (2, 2)
# seq = [2, 1]
collatz(3) ➞ (8, 16)
# seq = [3, 10, 5, 16, 8, 4, 2, 1]
collatz(7) ➞ (17, 52)
# seq = [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
collatz(8) ➞ (4, 8)
# seq = [8, 4, 2, 1]
### Notes
(Improbable) Bonus: Find a positive starting number that doesn't reach 1, and
score a place in Math history plus a cash prize.
"""
def collatz(n):
seq = [n]
k = n
while True:
if k % 2 == 0:
k /= 2
else:
k = k*3+1
seq.append(k)
if k == 1:
break
return len(seq), round(max(seq))
| [
"daniel.reich@danielreichs-MacBook-Pro.local"
] | daniel.reich@danielreichs-MacBook-Pro.local |
2c7378d5804ce5a23049db468925321034b3b0f8 | c23b4c6253ca5a0d42822dd0d28ffa752c11ebf5 | /exercises/55ad104b-7e6b-4f79-85f7-99ab6d43946e/skeletons/6376fb9a-a7ba-4f6b-b910-33ae0f34729e/skeleton.py3 | 1dc8678357cebc450bba6ab2504ef1e7caf277c6 | [] | no_license | josepaiva94/e57d8867-6234-41a6-b239-2cd978ad1e70 | 803e2eb1e2db23c64409bc72ff00c4463875a82f | aa270941dd8cf7b2e1ec8ac89445b1ab3a47f89d | refs/heads/master | 2023-01-07T10:49:56.871378 | 2020-11-16T11:28:14 | 2020-11-16T11:28:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 243 | py3 | mac = input()
def checkMAC(mac):
mac_split = {{gap_1}}
hex_arr = "ABCDEF0123456789"
if {{gap_2}} is 6:
for x in {{gap_2}}:
if not({{gap_3}}) or not({{gap_4}}:
return False
return True
else:
return False
print(checkMAC(mac)) | [
"56930760+jcpaiva-fgpe@users.noreply.github.com"
] | 56930760+jcpaiva-fgpe@users.noreply.github.com |
cb9a9d19afb8978fb0f05ed8e8cc82e86052e9ce | 469325b1fd3a6b88710bbbb4f5baa0a26404b37a | /Proj/.history/trafficapp/aicv/imgshandle_20201030055426.py | 31fb8f916d0bfda891c0927036e367ce80096960 | [] | no_license | axiat/IRCRA | 7f0f8ef1a41b8b58d6bc836f960b9d5a29dcec0f | b55bfdd794bd8200fd6f74f57016effebdd9d3e6 | refs/heads/master | 2023-03-13T03:03:33.385625 | 2021-02-21T17:27:52 | 2021-02-21T17:27:52 | 305,881,747 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,852 | py | import cv2
import numpy as np
import time
from PyQt5.QtGui import QImage
# def QImageToCvMat(self,incomingImage):
# ''' Converts a QImage into an opencv MAT format '''
# incomingImage = incomingImage.convertToFormat(QtGui.QImage.Format_RGB888)
# width = incomingImage.width()
# height = incomingImage.height()
# ptr = incomingImage.constBits()
# arr = np.array(ptr).reshape(height, width, 4) # Copies the data
# return arr
def QImageToCvMat(incomingImage):
''' Converts a QImage into an opencv MAT format '''
incomingImage = incomingImage.convertToFormat(QImage.Format_RGB888)
width = incomingImage.width()
height = incomingImage.height()
ptr = incomingImage.bits()
ptr.setsize(height * width * 4)
arr = np.frombuffer(ptr, np.uint8).reshape((height, width, 4))
return arr
def getTime():
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
def timeImg(img):
# img1=np.asarray(img)
# img1 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# cv2.putText(img, getTime(), (5, 30),
# cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
# img = np.expand_dims(img1, axis=2).repeat(3, axis=2)
return img1
def toGray(img):
# 灰度处理
img1 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 把灰度的2为图像转换为3为灰度图像(彩色)
# img = img1[:, :, np.newaxis].repeat(dim=2)
# cv2.putText(img1, getTime(), (5, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
img = np.expand_dims(img1, axis=2).repeat(3, axis=2)
# print("图像的维度", img.shape)
return img
def toClear(img):
return img
def toBright(img, brightness=127):
return img
def toLine(img):
return img
| [
"m13521259272@163.com"
] | m13521259272@163.com |
ae089e7b09c6e18966e93cccf8067efcbfd52338 | 017fc2259e09ec8760bc473d436ad45e464044f4 | /pennylane/templates/subroutines/grover.py | 46f2d83ab8c0c452e0b5ed4121e61a5b35107d51 | [
"Apache-2.0"
] | permissive | thomascherickal/pennylane | f1e8ef5b8ffa0c00601da30c39ff89318791e08f | 20dcbbc2f86c3fbd3f6fe2a416300e2d2fc172d0 | refs/heads/master | 2021-10-09T16:15:44.500819 | 2021-09-28T19:18:23 | 2021-09-28T19:18:23 | 199,557,166 | 2 | 1 | Apache-2.0 | 2021-09-28T19:18:23 | 2019-07-30T02:11:54 | Python | UTF-8 | Python | false | false | 5,426 | py | # Copyright 2018-2021 Xanadu Quantum Technologies 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.
"""
Contains the Grover Operation template.
"""
import itertools
import functools
import numpy as np
import pennylane as qml
from pennylane.operation import AnyWires, Operation
from pennylane.ops import Hadamard, PauliZ, MultiControlledX
class GroverOperator(Operation):
r"""Performs the Grover Diffusion Operator.
.. math::
G = 2 |s \rangle \langle s | - I
= H^{\bigotimes n} \left( 2 |0\rangle \langle 0| - I \right) H^{\bigotimes n}
where :math:`n` is the number of wires, and :math:`|s\rangle` is the uniform superposition:
.. math::
|s\rangle = H^{\bigotimes n} |0\rangle = \frac{1}{\sqrt{2^n}} \sum_{i=0}^{2^n-1} | i \rangle.
For this template, the operator is implemented with a layer of Hadamards, a layer of :math:`X`,
followed by a multi-controlled :math:`Z` gate, then another layer of :math:`X` and Hadamards.
This is expressed in a compact form by the circuit below:
.. figure:: ../../_static/templates/subroutines/grover.svg
:align: center
:width: 60%
:target: javascript:void(0);
The open circles on the controlled gate indicate control on 0 instead of 1.
The ``Z`` gates on the last wire result from leveraging the circuit identity :math:`HXH = Z`,
where the last ``H`` gate converts the multi-controlled :math:`Z` gate into a
multi-controlled :math:`X` gate.
Args:
wires (Union[Wires, Sequence[int], or int]): the wires to apply to
work_wires (Union[Wires, Sequence[int], or int]): optional auxiliary wires to assist
in the decomposition of :class:`~.MultiControlledX`.
**Example**
The Grover Diffusion Operator amplifies the magnitude of the basis state with
a negative phase. For example, if the solution to the search problem is the :math:`|111\rangle`
state, we require an oracle that flips its phase; this could be implemented using a `CCZ` gate:
.. code-block:: python
n_wires = 3
wires = list(range(n_wires))
def oracle():
qml.Hadamard(wires[-1])
qml.Toffoli(wires=wires)
qml.Hadamard(wires[-1])
We can then implement the entire Grover Search Algorithm for ``num_iterations`` iterations by alternating calls to the oracle and the diffusion operator:
.. code-block:: python
dev = qml.device('default.qubit', wires=wires)
@qml.qnode(dev)
def GroverSearch(num_iterations=1):
for wire in wires:
qml.Hadamard(wire)
for _ in range(num_iterations):
oracle()
qml.templates.GroverOperator(wires=wires)
return qml.probs(wires)
>>> GroverSearch(num_iterations=1)
tensor([0.03125, 0.03125, 0.03125, 0.03125, 0.03125, 0.03125, 0.03125,
0.78125], requires_grad=True)
>>> GroverSearch(num_iterations=2)
tensor([0.0078125, 0.0078125, 0.0078125, 0.0078125, 0.0078125, 0.0078125,
0.0078125, 0.9453125], requires_grad=True)
We can see that the marked :math:`|111\rangle` state has the greatest probability amplitude.
Optimally, the oracle-operator pairing should be repeated :math:`\lceil \frac{\pi}{4}\sqrt{2^{n}} \rceil` times.
"""
num_params = 0
num_wires = AnyWires
par_domain = None
grad_method = None
def __init__(self, wires=None, work_wires=None, do_queue=True, id=None):
if (not hasattr(wires, "__len__")) or (len(wires) < 2):
raise ValueError("GroverOperator must have at least two wires provided.")
self.work_wires = work_wires
super().__init__(wires=wires, do_queue=do_queue, id=id)
def expand(self):
ctrl_str = "0" * (len(self.wires) - 1)
with qml.tape.QuantumTape() as tape:
for wire in self.wires[:-1]:
Hadamard(wire)
PauliZ(self.wires[-1])
MultiControlledX(
control_values=ctrl_str,
control_wires=self.wires[:-1],
wires=self.wires[-1],
work_wires=self.work_wires,
)
PauliZ(self.wires[-1])
for wire in self.wires[:-1]:
Hadamard(wire)
return tape
@property
def matrix(self):
# Redefine the property here to allow for a custom _matrix signature
mat = self._matrix(len(self.wires))
return mat
@classmethod
def _matrix(cls, *params):
num_wires = params[0]
# s1 = H|0>, Hadamard on a single qubit in the ground state
s1 = np.array([1, 1]) / np.sqrt(2)
# uniform superposition state |s>
s = functools.reduce(np.kron, list(itertools.repeat(s1, num_wires)))
# Grover diffusion operator
G = 2 * np.outer(s, s) - np.identity(2 ** num_wires)
return G
| [
"noreply@github.com"
] | thomascherickal.noreply@github.com |
c783408703830e9ce5af701f85c93ff834e2edcd | 325fde42058b2b82f8a4020048ff910cfdf737d7 | /src/automation/azext_automation/vendored_sdks/automation/aio/operations/_key_operations.py | 681d8e496bb3177248fc58d79101828166f94822 | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | permissive | ebencarek/azure-cli-extensions | 46b0d18fe536fe5884b00d7ffa30f54c7d6887d1 | 42491b284e38f8853712a5af01836f83b04a1aa8 | refs/heads/master | 2023-04-12T00:28:44.828652 | 2021-03-30T22:34:13 | 2021-03-30T22:34:13 | 261,621,934 | 2 | 5 | MIT | 2020-10-09T18:21:52 | 2020-05-06T01:25:58 | Python | UTF-8 | Python | false | false | 4,781 | py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import Any, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class KeyOperations:
"""KeyOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~automation_client.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
async def list_by_automation_account(
self,
resource_group_name: str,
automation_account_name: str,
**kwargs
) -> "models.KeyListResult":
"""Retrieve the automation keys for an account.
:param resource_group_name: Name of an Azure Resource group.
:type resource_group_name: str
:param automation_account_name: The name of the automation account.
:type automation_account_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: KeyListResult, or the result of cls(response)
:rtype: ~automation_client.models.KeyListResult
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["models.KeyListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2015-10-31"
accept = "application/json"
# Construct URL
url = self.list_by_automation_account.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._]+$'),
'automationAccountName': self._serialize.url("automation_account_name", automation_account_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.post(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize(models.ErrorResponse, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('KeyListResult', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
list_by_automation_account.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/listKeys'} # type: ignore
| [
"noreply@github.com"
] | ebencarek.noreply@github.com |
9e9f504f0fb585777d13b480599377adfccab439 | 4a28e3e3afb28c0455ea21cfb983c3a8284dc5dd | /I E4.py | ee1a12a4cf658e738806f55aa474029ddec31781 | [] | no_license | omdeshmukh20/Python-3-Programming | 60f6bc4e627de9d643a429e64878a636f3875cae | 9fb4c7fa54bc26d18b69141493c7a72e0f68f7d0 | refs/heads/main | 2023-08-28T04:37:27.001888 | 2021-10-29T17:03:34 | 2021-10-29T17:03:34 | 370,008,995 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 274 | py | #Discription: List of pets using if else
#Date: 06/09/21
#Author : Om Deshmukh
myPets = ['Zophie', 'Pooka', 'Fat-tail']
print('Enter a pet name:')
name = input()
if name not in myPets:
print('I do not have a pet named ' + name)
else:
print(name + ' is my pet.')
| [
"noreply@github.com"
] | omdeshmukh20.noreply@github.com |
60ad984973c35369bf1cb81993e908362db04f80 | a31c54cb9b27e315567ed865e07cb720fc1e5c8e | /revenge/engines/frida/memory/__init__.py | 822cf4949f39526faed7b7372b6be6f31b0ee14f | [] | no_license | bannsec/revenge | 212bc15e09f7d864c837a1829b3dc96410e369d3 | 2073b8fad76ff2ba21a5114be54e959297aa0cf9 | refs/heads/master | 2021-06-25T12:26:02.609076 | 2020-05-29T15:46:45 | 2020-05-29T15:46:45 | 188,461,358 | 51 | 6 | null | null | null | null | UTF-8 | Python | false | false | 305 | py |
import logging
logger = logging.getLogger(__name__)
from .memory_range import FridaMemoryRange as MemoryRange
from .map import FridaMemoryMap as MemoryMap
from .find import FridaMemoryFind as MemoryFind
from .memory_bytes import FridaMemoryBytes as MemoryBytes
from .memory import FridaMemory as Memory
| [
"whootandahalf@gmail.com"
] | whootandahalf@gmail.com |
0ff9d5df07821b0ccf07676e580cb14b38ecf5a9 | bb33e6be8316f35decbb2b81badf2b6dcf7df515 | /source/res/scripts/client/gui/scaleform/daapi/view/meta/browsermeta.py | 03baa92387d38a7e9c7d66f787f593bbf42db740 | [] | no_license | StranikS-Scan/WorldOfTanks-Decompiled | 999c9567de38c32c760ab72c21c00ea7bc20990c | d2fe9c195825ececc728e87a02983908b7ea9199 | refs/heads/1.18 | 2023-08-25T17:39:27.718097 | 2022-09-22T06:49:44 | 2022-09-22T06:49:44 | 148,696,315 | 103 | 39 | null | 2022-09-14T17:50:03 | 2018-09-13T20:49:11 | Python | UTF-8 | Python | false | false | 1,992 | py | # Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: scripts/client/gui/Scaleform/daapi/view/meta/BrowserMeta.py
from gui.Scaleform.framework.entities.BaseDAAPIComponent import BaseDAAPIComponent
class BrowserMeta(BaseDAAPIComponent):
def browserAction(self, action):
self._printOverrideError('browserAction')
def browserMove(self, x, y, z):
self._printOverrideError('browserMove')
def browserDown(self, x, y, z):
self._printOverrideError('browserDown')
def browserUp(self, x, y, z):
self._printOverrideError('browserUp')
def browserFocusOut(self):
self._printOverrideError('browserFocusOut')
def onBrowserShow(self, needRefresh):
self._printOverrideError('onBrowserShow')
def onBrowserHide(self):
self._printOverrideError('onBrowserHide')
def invalidateView(self):
self._printOverrideError('invalidateView')
def setBrowserSize(self, width, height, scale):
self._printOverrideError('setBrowserSize')
def as_loadBitmapS(self, url):
return self.flashObject.as_loadBitmap(url) if self._isDAAPIInited() else None
def as_resizeS(self, width, height):
return self.flashObject.as_resize(width, height) if self._isDAAPIInited() else None
def as_loadingStartS(self, showContentUnderWaiting):
return self.flashObject.as_loadingStart(showContentUnderWaiting) if self._isDAAPIInited() else None
def as_loadingStopS(self):
return self.flashObject.as_loadingStop() if self._isDAAPIInited() else None
def as_showServiceViewS(self, header, description):
return self.flashObject.as_showServiceView(header, description) if self._isDAAPIInited() else None
def as_hideServiceViewS(self):
return self.flashObject.as_hideServiceView() if self._isDAAPIInited() else None
def as_changeTitleS(self, title):
return self.flashObject.as_changeTitle(title) if self._isDAAPIInited() else None
| [
"StranikS_Scan@mail.ru"
] | StranikS_Scan@mail.ru |
aa3bf61bfc07d94f00d6817e70534ec9f50a0ba4 | 0eaf0d3f0e96a839f2ef37b92d4db5eddf4b5e02 | /past12/k.py | a9705a280a1da017a04972e470fa5eb408fb0a6b | [] | no_license | silphire/atcoder | b7b02798a87048757745d99e8564397d1ca20169 | f214ef92f13bc5d6b290746d5a94e2faad20d8b0 | refs/heads/master | 2023-09-03T17:56:30.885166 | 2023-09-02T14:16:24 | 2023-09-02T14:16:24 | 245,110,029 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,904 | py | from collections import defaultdict
class UnionFind(object):
"""
Union-Find (Disjoint Set Union)
"""
def __init__(self, n: int):
assert n > 0
self.parent = [x for x in range(n)]
self.size = [1] * n
def root(self, x: int) -> int:
if self.parent[x] != x:
self.parent[x] = self.root(self.parent[x])
return self.parent[x]
def is_same(self, x: int, y: int) -> bool:
return self.root(x) == self.root(y)
def unite(self, x:int, y: int) -> None:
rx = self.root(x)
ry = self.root(y)
if rx == ry:
return
if self.size[rx] < self.size[ry]:
rx, ry = ry, rx
self.parent[ry] = rx
self.size[rx] += self.size[ry]
def get_size(self, x: int) -> int:
return self.size[self.root(x)]
g = defaultdict(set)
n, m = map(int, input().split())
aa = [0] * m
bb = [0] * m
for i in range(m):
aa[i], bb[i] = map(int, input().split())
g[aa[i]].add(bb[i])
g[bb[i]].add(aa[i])
q = int(input())
tt = [0] * q
xx = [0] * q
yy = [0] * q
for i in range(q):
tt[i], xx[i], yy[i] = map(int, input().split())
if tt[i] == 1:
g[xx[i]].add(yy[i])
g[yy[i]].add(xx[i])
elif tt[i] == 2:
g[xx[i]].remove(yy[i])
g[yy[i]].remove(xx[i])
uf = UnionFind(n + 1)
for k, v in g.items():
for x in v:
uf.unite(k, x)
ans = []
for i in range(q - 1, -1, -1):
if tt[i] == 1:
g[xx[i]].remove(yy[i])
g[yy[i]].remove(xx[i])
uf = UnionFind(n + 1)
for k, v in g.items():
for x in v:
uf.unite(k, x)
elif tt[i] == 2:
g[xx[i]].add(yy[i])
g[yy[i]].add(xx[i])
uf.unite(xx[i], yy[i])
else:
ans.append(uf.is_same(xx[i], yy[i]))
for a in reversed(ans):
if a:
print('Yes')
else:
print('No') | [
"silphire@gmail.com"
] | silphire@gmail.com |
21cc95eced5ffb9542d47d29cc4edd83e4b704eb | 3339d4a79ff8670b5cf81dcbfd9ff4d477adad46 | /setup.py | 6872dd60dbbc2cb1391205b9f9bccfda4a3b5955 | [
"MIT"
] | permissive | djm/elasticsearch-django | a83314854a2c0b7e1dfcecf9190734e47eb5b752 | 2e607846ed4cc716aff9ac2b65182f45c21b6fd8 | refs/heads/master | 2020-05-23T10:19:43.984729 | 2017-01-13T16:23:59 | 2017-01-13T17:24:49 | 80,419,713 | 0 | 0 | null | 2017-01-30T12:31:47 | 2017-01-30T12:31:46 | null | UTF-8 | Python | false | false | 1,452 | py | # -*- coding: utf-8 -*-
from os import path, chdir, pardir
from setuptools import setup, find_packages
README = open(path.join(path.dirname(__file__), 'README.rst')).read()
# requirements.txt must be included in MANIFEST.in and include_package_data must be True
# in order for this to work; ensures that tox can use the setup to enforce requirements
REQUIREMENTS = '\n'.join(open(path.join(path.dirname(__file__), 'requirements.txt')).readlines()) # noqa
# allow setup.py to be run from any path
chdir(path.normpath(path.join(path.abspath(__file__), pardir)))
setup(
name="elasticsearch-django",
version="0.5.2",
packages=find_packages(),
install_requires=REQUIREMENTS,
include_package_data=True,
license='MIT',
description='Elasticsearch Django app',
long_description=README,
url='https://github.com/yunojuno/elasticsearch-django',
author='Hugo Rodger-Brown',
author_email='code@yunojuno.com',
maintainer='Hugo Rodger-Brown',
maintainer_email='hugo@yunojuno.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| [
"hugo@yunojuno.com"
] | hugo@yunojuno.com |
986af905818ae3d5de425d83b122f62b130e2ab9 | 163bbb4e0920dedd5941e3edfb2d8706ba75627d | /Code/CodeRecords/2205/60696/263490.py | 8c63e98e28ee66ededfef13e5763a6545d7bb62a | [] | 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 | 386 | py | class Solution:
def numberOfWays(self, n: int) -> int:
res = 1
for i in range(1, n // 2 + 1):
res *= n - i + 1
res //= i
return res // (n // 2 + 1) % (10**9 + 7)
if __name__ == '__main__':
n = int(input())
for i in range(n):
num = int(input())
num = int(num/2) * 2
print(Solution().numberOfWays(num)) | [
"1069583789@qq.com"
] | 1069583789@qq.com |
73d320126cdceeed526c2541becb2e67e6003c88 | 033095b33abcef8ac34638a277de11ab734cf642 | /Chapter04/Refactoring/point_v3.py | 929c6d925f187b40c1dc7872edeb211b1229dadc | [
"MIT"
] | permissive | PacktPublishing/Hands-On-Application-Development-with-PyCharm | fa2df6bfbe06272a4314a83f03cd90030ed2d466 | 9998906b754a44ced6789e850e8eed139bec0a97 | refs/heads/master | 2023-04-27T23:49:31.779700 | 2023-01-18T09:11:50 | 2023-01-18T09:11:50 | 175,549,552 | 40 | 45 | MIT | 2023-04-21T20:31:21 | 2019-03-14T04:43:12 | Python | UTF-8 | Python | false | false | 1,455 | py | from math import sqrt
from matplotlib import pyplot as plt
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f'Point ({self.x}, {self.y})'
def __add__(self, p):
return Point(self.x + p.x, self.y + p.y)
def __sub__(self, p):
return Point(self.x - p.x, self.y - p.y)
def distance(self, p):
diff = self - p
distance = sqrt(diff.x**2 + diff.y**2)
return distance
@staticmethod
def draw(x, y):
# set up range of the plot
limit = max(x, y) + 1
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_aspect('equal')
# lines corresponding to x- and y-coordinates
plt.plot([x, x], [0, y], '-', c='blue', linewidth=3)
plt.plot([0, x], [y, y], '-', c='blue', linewidth=3)
plt.scatter(x, y, s=100, marker='o', c='red') # actual point
ax.set_xlim((-limit, limit))
ax.set_ylim((-limit, limit))
# axis arrows
left, right = ax.get_xlim()
bottom, top = ax.get_ylim()
plt.arrow(left, 0, right - left, 0, length_includes_head=True,
head_width=0.15)
plt.arrow(0, bottom, 0, top - bottom, length_includes_head=True,
head_width=0.15)
plt.grid()
plt.show()
if __name__ == '__main__':
p1 = Point(1, 0)
p2 = Point(5, 3)
Point.draw(p2.x, p2.y)
| [
"nguyenminhquan135@gmail.com"
] | nguyenminhquan135@gmail.com |
5c1049545c0c2a10a0f9a258fb0b91f1efd85336 | 09122d8d733d17f5c7fa79c1f167b63ef83d6838 | /LeetCode_Algorithm_I/binary_search.py | d9c336c0ef5bf9bc398707f400382081fdfb60bb | [] | no_license | vipulsingh24/DSA | e294ec4aa1b6db2e0ab658f0c7d8389c42563fe2 | bcad07d073b064428bcb1bfe7c53f1e785ecc4eb | refs/heads/main | 2023-08-17T00:57:44.232545 | 2021-10-10T17:53:59 | 2021-10-10T17:53:59 | 391,599,514 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 988 | py | """
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
"""
class Solution:
def search(self, nums: List[int], target: int) -> int:
if len(nums) == 1 and nums[0] == target:
return 0
else:
low = 0
high = len(nums)-1
counter = 0
while low <= high:
# mid = (low + high)//2
mid = low + (high-low)//2
if nums[mid] == target:
return mid ## Success, Found
elif nums[mid] > target:
high = mid - 1
elif nums[mid] < target:
low = mid + 1
counter += 1
if counter > len(nums):
break
return -1 #
| [
"letsmailvipul@gmail.com"
] | letsmailvipul@gmail.com |
ba918c9a370632727defbf27b9f61360d89b1d1e | 391a40002b63daff8bb056b2f0b2ae3f7ee52bb3 | /项目/4组_基于MTCNN与FaceNet的人脸识别/4组_基于MTCNN与FaceNet的人脸识别/src/face.py | 5c903bc4586d85543ca2a0df1e690a7e91cf937e | [] | no_license | realllcandy/USTC_SSE_Python | 7b40f0e4ae3531fc41683fd19f71a58ce3815cdb | 3ac15a95e8a99491c322481a70c14b6ab830082f | refs/heads/master | 2023-03-17T21:30:19.068695 | 2020-10-10T06:15:28 | 2020-10-10T06:15:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,374 | py | import pickle
import os
import cv2
import numpy as np
import tensorflow as tf
from scipy import misc
import align.detect_face
import facenet
gpu_memory_fraction = 0.3
facenet_model_checkpoint = os.path.dirname(__file__) + "/../src/models/20180402-114759"
classifier_model = os.path.dirname(__file__) + "/../src/models/classifier.pkl"
debug = False
class Face:
def __init__(self):
self.name = None
self.bounding_box = None
self.image = None
self.container_image = None
self.embedding = None
class Recognition:
def __init__(self):
self.detect = Detection()
self.encoder = Encoder()
self.identifier = Identifier()
def add_identity(self, image, person_name):
faces = self.detect.find_faces(image)
if len(faces) == 1:
face = faces[0]
face.name = person_name
face.embedding = self.encoder.generate_embedding(face)
return faces
def identify(self, image):
faces = self.detect.find_faces(image)
for i, face in enumerate(faces):
if debug:
cv2.imshow("Face: " + str(i), face.image)
face.embedding = self.encoder.generate_embedding(face)
face.name = self.identifier.identify(face)
return faces
class Identifier:
def __init__(self):
with open(classifier_model, 'rb') as infile:
self.model, self.class_names = pickle.load(infile)
def identify(self, face):
if face.embedding is not None:
predictions = self.model.predict_proba([face.embedding])
best_class_indices = np.argmax(predictions, axis=1)
return self.class_names[best_class_indices[0]]
class Encoder:
def __init__(self):
self.sess = tf.Session()
with self.sess.as_default():
facenet.load_model(facenet_model_checkpoint)
def generate_embedding(self, face):
images_placeholder = tf.get_default_graph().get_tensor_by_name("input:0")
embeddings = tf.get_default_graph().get_tensor_by_name("embeddings:0")
phase_train_placeholder = tf.get_default_graph().get_tensor_by_name("phase_train:0")
prewhiten_face = facenet.prewhiten(face.image)
# Run forward pass to calculate embeddings
feed_dict = {images_placeholder: [prewhiten_face], phase_train_placeholder: False}
return self.sess.run(embeddings, feed_dict=feed_dict)[0]
class Detection:
minsize = 20 # minimum size of face
threshold = [0.6, 0.7, 0.7] # three steps's threshold
factor = 0.709 # scale factor
def __init__(self, face_crop_size=160, face_crop_margin=32):
self.pnet, self.rnet, self.onet = self._setup_mtcnn()
self.face_crop_size = face_crop_size
self.face_crop_margin = face_crop_margin
def _setup_mtcnn(self):
with tf.Graph().as_default():
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
with sess.as_default():
return align.detect_face.create_mtcnn(sess, None)
def find_faces(self, image):
faces = []
bounding_boxes, _ = align.detect_face.detect_face(image, self.minsize,
self.pnet, self.rnet, self.onet,
self.threshold, self.factor)
for bb in bounding_boxes:
face = Face()
face.container_image = image
face.bounding_box = np.zeros(4, dtype=np.int32)
img_size = np.asarray(image.shape)[0:2]
face.bounding_box[0] = np.maximum(bb[0] - self.face_crop_margin / 2, 0)
face.bounding_box[1] = np.maximum(bb[1] - self.face_crop_margin / 2, 0)
face.bounding_box[2] = np.minimum(bb[2] + self.face_crop_margin / 2, img_size[1])
face.bounding_box[3] = np.minimum(bb[3] + self.face_crop_margin / 2, img_size[0])
cropped = image[face.bounding_box[1]:face.bounding_box[3], face.bounding_box[0]:face.bounding_box[2], :]
face.image = misc.imresize(cropped, (self.face_crop_size, self.face_crop_size), interp='bilinear')
faces.append(face)
return faces
| [
"321699849@qq.com"
] | 321699849@qq.com |
f97edd5d3b27d38201267d468279199221e65350 | 275f3a3dce44f35a5dc1a626e2052c006bdb71bf | /python3/hackerrank_leetcode/longest_common_prefix/test.py | 72dd75f74c79b1a194638843eaa41b43c1a81fa7 | [
"MIT"
] | permissive | seLain/codesnippets | 79b7655950b160af7f2b9fa94712594f95a4794d | ae9a1fa05b67f4b3ac1703cc962fcf5f6de1e289 | refs/heads/master | 2018-10-08T10:29:53.982156 | 2018-07-23T13:32:26 | 2018-07-23T13:32:26 | 114,009,746 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 574 | py | import unittest
from main import Solution
class TestSolutionMethods(unittest.TestCase):
solution = Solution()
def test_longestCommonPrefix(self):
# leetcode test
self.assertEqual(self.solution.longestCommonPrefix([]), "")
# customized test
self.assertEqual(self.solution.longestCommonPrefix(["b", "c", "abc"]), "")
self.assertEqual(self.solution.longestCommonPrefix(["ac", "ab", "abc"]), "a")
self.assertEqual(self.solution.longestCommonPrefix(["abc", "abc"]), "abc")
if __name__ == '__main__':
unittest.main() | [
"selain@nature.ee.ncku.edu.tw"
] | selain@nature.ee.ncku.edu.tw |
4a462bf150a9a56a7a27908dbbbfb4f65c656ad2 | 3325f16c04ca8e641cbd58e396f983542b793091 | /Seção 07 - Coleções Python/Exercícios da Seção/Exercício_44.py | e74cdc81ca838e39ebaaefe45c5c38d333e4831a | [] | no_license | romulovieira777/Programacao_em_Python_Essencial | ac929fbbd6a002bcc689b8d6e54d46177632c169 | e81d219db773d562841203ea370bf4f098c4bd21 | refs/heads/master | 2023-06-11T16:06:36.971113 | 2021-07-06T20:57:25 | 2021-07-06T20:57:25 | 269,442,342 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 666 | py | """
44) Leia uma matriz 5 x 5. Leia também um valor X. O programa
deverá fazer uma busca desse valor na matriz e, ao final, escrever a localização
(linha e coluna) ou mensagem de "não encontrado".
"""
lista1 = []
for i in range(5):
lista2 = []
for j in range(5):
num = int(input("Enter a number: "))
lista2.append(num)
lista1.append(lista2)
x = int(input("\nEnter a number x: "))
print(f'\n{lista1}')
cont = 0
for i in range(5):
for j in range(5):
if x == lista1[i][j]:
cont += 1
print(f"\nThe value {x} is found in line {i} and in the column {j}")
if cont == 0:
print("\nNot found")
| [
"romulo.vieira777@gmail.com"
] | romulo.vieira777@gmail.com |
a15cc26b1d7917df84ed6039e6ad915c5581b902 | 517d461257edd1d6b239200b931c6c001b99f6da | /HalloWing/CircuitPython/testing_transistors_w_motor.py | 025c05429c16510fc22b9c3cc91a10e59c07db35 | [] | no_license | cmontalvo251/Microcontrollers | 7911e173badff93fc29e52fbdce287aab1314608 | 09ff976f2ee042b9182fb5a732978225561d151a | refs/heads/master | 2023-06-23T16:35:51.940859 | 2023-06-16T19:29:30 | 2023-06-16T19:29:30 | 229,314,291 | 5 | 3 | null | null | null | null | UTF-8 | Python | false | false | 686 | py | import board
import digitalio
import time
import touchio
import audioio
from analogio import AnalogIn,AnalogOut
#Set up Touch Buttons
touch1 = touchio.TouchIn(board.TOUCH1)
touch2 = touchio.TouchIn(board.TOUCH2)
touch3 = touchio.TouchIn(board.TOUCH3)
touch4 = touchio.TouchIn(board.TOUCH4)
#print(dir(board))
#analog_button = AnalogOut(board.A6)
transistor = digitalio.DigitalInOut(board.D4)
transistor.direction = digitalio.Direction.OUTPUT
transistor.value = False
while True:
if touch1.value or touch2.value or touch3.value or touch4.value:
print("Touched")
transistor.value = 65535
time.sleep(2)
transistor.value = 0
time.sleep(0.05)
| [
"cmontalvo251@gmail.com"
] | cmontalvo251@gmail.com |
830acf70ecae7fd6e2f7dc1714aff73773a35e2c | 7efee8fb6eb0fa0c3474eeee6344f0c3a5842ff1 | /discourse/__init__.py | 8cda3bd93fb73ad81fb65a473bed545b69e8a8f8 | [] | no_license | nyddle/Discourse | ca0f4eaec039b859a607423c81d97367442c2d3a | 031b5bbe7520bfd00addce291661f3e0d8d1e204 | refs/heads/master | 2021-01-15T21:20:39.699191 | 2014-05-16T01:55:06 | 2014-05-16T01:55:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 886 | py | from notice import subscribe, unsubscribe, is_subscribed, send_event, render_mail, send_mail
from models import (model_sig,
get_instance_from_sig,
comment_manipulate,
attachment_manipulate,
document_manipulate,
library_view,
document_view,
attachment_view,
comment_vote,
event)
from notice import send_event
### Helpers ###
def template_repr(var):
r = repr(var)
if r.startswith('u"') or r.startswith("u'"):
return r[1:]
return r
def tag_repr(name, *args, **kwargs):
parts = [name]
if args:
parts.extend(args)
if kwargs:
parts.extend(["%s=%s" % (k, template_repr(v)) for k, v in kwargs.items() if v is not None])
return "{%% %s %%}" % " ".join(parts) | [
"deadwisdom@gmail.com"
] | deadwisdom@gmail.com |
09cdd6da39ecd793c55b596eeafdfec3a03a092e | 6daa3815511b1eb1f4ff3a40b7e9332fab38b8ef | /tastesavant/taste/tests/steps.py | 1de3767d55e2ec324a42e1607c1b534641af88ed | [] | no_license | kaizensoze/archived-projects | 76db01309453606e6b7dd9d2ff926cfee42bcb05 | d39ac099cb40131bac5de66bde7d0e2db5f74189 | refs/heads/master | 2021-05-31T12:16:17.800730 | 2016-02-23T00:27:56 | 2016-02-23T00:27:56 | 14,407,212 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,601 | py | # -*- coding: utf-8 -*-
from urlparse import urlparse
from django.contrib.auth import login, authenticate
from django.contrib.auth.models import User
from django.http import HttpRequest
from lettuce import step, world
from lettuce.django import django_url
from lettuce_webdriver.util import AssertContextManager
from taste.apps.restaurants.models import Restaurant
from taste.apps.reviews.models import Review
# @todo: not very DRY; what's a better way?
MODELS = {
'Restaurant': Restaurant,
'User': User,
}
@step(r'I go to "(.*)"')
def go_to_url(step, url):
with AssertContextManager(step):
full_url = django_url(url)
world.browser.visit(full_url)
@step(u'there is a "(.*?)"')
def there_is_a_model(step, model):
with AssertContextManager(step):
try:
model = MODELS[model]
except KeyError:
raise AssertionError("No such model: %s" % model)
assert model.objects.count > 0
@step(u'I am logged in')
def i_am_logged_in(step):
with AssertContextManager(step):
# We assume a certain user present in the fixtures.
full_url = django_url('/accounts/login/')
world.browser.visit(full_url)
world.browser.fill('username', 'test')
world.browser.fill('password', 'foobar')
world.browser.find_by_css('.button').last.click()
@step(u'my profile is complete')
def my_profile_is_complete(step):
with AssertContextManager(step):
user = User.objects.get(username='test')
assert user.get_profile().is_valid
## Search steps
# ---------------------------------------------------------------------------
@step(u'a user named "([^"]*)" exists')
def a_user_named_name_exists(step, name):
with AssertContextManager(step):
try:
User.objects.get(username=name)
assert True
except User.DoesNotExist:
assert False
@step(u'I search for a user named "([^"]*)"')
def i_search_for_a_user_named_name(step, name):
with AssertContextManager(step):
full_url = django_url('/search/users/')
world.browser.visit(full_url)
# We're using the .last ones here, because apparently Zope Testbrowser
# doesn't get IDs with dashes in them well.
world.browser.find_by_id('friend-input').last.fill(name)
world.browser.find_by_id('friend-input-submit').last.click()
@step(u'I should see a results page showing "([^"]*)"')
def i_should_see_a_results_page_showing_name(step, name):
with AssertContextManager(step):
elts = world.browser.find_by_css('.follow-suggestions-name')
assert any(map(lambda x: x.value == name, elts))
@step(u'a restaurant named "([^"]*)" exists')
def a_restaurant_named_name_exists(step, name):
with AssertContextManager(step):
try:
Restaurant.objects.get(name=name)
assert True
except User.DoesNotExist:
assert False
@step(u'I search for a restaurant named "([^"]*)"')
def i_search_for_a_restaurant_named_name(step, name):
with AssertContextManager(step):
full_url = django_url('/')
world.browser.visit(full_url)
world.browser.find_by_id('id_query').last.fill(name)
world.browser.find_by_id('search-submit').first.click()
@step(u'I should see a results page showing a restaurant named "([^"]*)"')
def i_should_see_a_results_page_showing_a_restaurant_named_name(step, name):
with AssertContextManager(step):
# Wait for the AJAX call
world.browser.is_element_present_by_css('.result-link', wait_time=10)
elts = world.browser.find_by_css('.restaurant-name')
assert any(map(lambda x: x.value == name, elts))
## Review steps
# ---------------------------------------------------------------------------
@step(u'I create a review for "([^""]*)"')
def i_create_a_review_for_name(step, name):
with AssertContextManager(step):
restaurant = Restaurant.objects.get(name=name)
full_url = django_url('/restaurant/%s/review/create_edit/' % restaurant.slug)
world.browser.visit(full_url)
@step(u'a review should exist for "([^""]*)"')
def that_review_should_exist_for_name(step, name):
with AssertContextManager(step):
user = User.objects.get(username='test')
restaurant = Restaurant.objects.get(name=name)
try:
Review.objects.get(user=user, restaurant=restaurant)
assert True
except Review.DoesNotExist:
assert False, "The review does not exist."
@step(u'I should see it on the restaurant page for "([^""]*)"')
def i_should_see_it_on_the_restaurant_page_for_name(step, name):
with AssertContextManager(step):
restaurant = Restaurant.objects.get(name=name)
full_url = django_url('/restaurant/%s/review/savants/' % restaurant.slug)
world.browser.visit(full_url)
elts = world.browser.find_by_css('.review h2')
assert any(map(lambda x: x.value == 'Test E.', elts))
@step(u'I should see a review for "([^""]*)" on my profile')
def i_should_see_a_review_for_name_on_my_profile(step, name):
with AssertContextManager(step):
restaurant = Restaurant.objects.get(name=name)
full_url = django_url('/profiles/%s/' % 'test')
world.browser.visit(full_url)
elts = world.browser.find_by_css('#my-reviews .review h2')
assert any(map(lambda x: x.value == restaurant.name, elts))
## Review steps
# ---------------------------------------------------------------------------
# @todo: parse the path element of the links, since the href is fully specified
@step(u'I should see critic reviews')
def i_should_see_critic_reviews(step):
with AssertContextManager(step):
elts = world.browser.find_by_css('#reviews h2 a')
assert len(elts) > 0
assert all(map(lambda x: urlparse(x['href']).path.startswith('/critic/'), elts))
@step(u'I should see user reviews')
def i_should_see_user_reviews(step):
with AssertContextManager(step):
elts = world.browser.find_by_css('#reviews h2 a')
assert len(elts) > 0
assert all(map(lambda x: urlparse(x['href']).path.startswith('/profiles/'), elts))
@step(u'I should see friend reviews')
def i_should_see_friend_reviews(step):
with AssertContextManager(step):
elts = world.browser.find_by_css('#reviews h2 a')
if len(elts) > 0:
assert all(map(lambda x: urlparse(x['href']).path.startswith('/critic/'), elts))
else:
assert "Want to ask your friends about this Restaurant?" in world.browser.html
| [
"gallo.j@gmail.com"
] | gallo.j@gmail.com |
281e26ea1ec3a66c875c9fcbfcddf7bea0ab7124 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02735/s901108588.py | f6b1a85f048bbee1370c201a20c65c14f71472da | [] | 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 | 157 | py | _,*s=open(0);t="."
b=t*101;q=range(101);i=0
for s in s:
a=[i];i+=1
for x,y,z,c in zip(b,t+s,s,q):a+=min(c+(t>z<x),a[-1]+(t>z<y)),
b,q=s,a[1:]
print(a[-2]) | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
877aeeda55babf2eddf7c6b3e99bbcd34aa7de6b | 163bbb4e0920dedd5941e3edfb2d8706ba75627d | /Code/CodeRecords/2065/60581/238639.py | 0b6140cd9552c6b8e6249ceccb99bf5ca41994cc | [] | 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 | 1,160 | py | str = list(input())
number = ''
i = 0
judge = False
while i < len(str):
if not judge:
if str[i]==' ' or str[i]=='"':
i += 1
elif str[i]=='-':
judge = True
number += str[i]
i += 1
elif str[i]>='0' and str[i]<='9':
judge = True
number += str[i]
i += 1
else:
print(0)
break
else:
if str[i]>='0' and str[i]<='9':
number += str[i]
i += 1
if i == len(str):
number = int(number)
if number <= pow(2, 31) - 1 and number >= -pow(2, 31):
print(number)
elif number > pow(2, 31) - 1:
print(pow(2, 31) - 1)
elif number < -pow(2, 31):
print(-pow(2, 31))
else:
number = int(number)
if number <= pow(2,31)-1 and number >= -pow(2,31):
print(number)
elif number > pow(2,31)-1:
print(pow(2,31)-1)
elif number < -pow(2,31):
print(-pow(2,31))
break | [
"1069583789@qq.com"
] | 1069583789@qq.com |
0ac9b7d50b3f82f281b0d8fbcb21e8b9c3ef7b46 | 6329ece221f3b2295cb3791168c876d260ed0c31 | /test_learn/chapter4基本窗口控件/对话框类控件/QFileDialog.py | ab66856621d3dd3617c5317bdf95c2ce59f1a629 | [] | no_license | dxcv/PythonGUI | 4908e049dde5e569a3ad916c6bac385c7953a243 | a39beef0006e3e4057e3a9bcb3e0e64ea790427e | refs/heads/master | 2020-05-17T17:14:58.250549 | 2019-04-11T09:32:52 | 2019-04-11T09:32:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,655 | py | # -*- coding:UTF-8 -*-
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys
class fileDialogDemo(QWidget):
def __init__(self,parent=None):
super(fileDialogDemo,self).__init__(parent)
self.setWindowTitle("Demo")
self.resize(500,500)
self.move(200,200)
layout=QVBoxLayout()
self.btn=QPushButton("加载图片")
self.btn.clicked.connect(self.getfile)
layout.addWidget(self.btn)
#这下面三行就是用来后面放图片的
self.le=QLabel("")
self.le.setAlignment(Qt.AlignCenter)
layout.addWidget(self.le)
self.btn1=QPushButton("加载文本文件")
self.btn1.clicked.connect(self.getfiles)
layout.addWidget(self.btn1)
self.contents=QTextEdit()
layout.addWidget(self.contents)
self.setLayout(layout)
def getfile(self):
fname,_=QFileDialog.getOpenFileName(self,'Open file',"../","Image files(*.jpg *.gif)")
self.le.setPixmap(QPixmap(fname))
def getfiles(self):
dig=QFileDialog()
dig.setFileMode(QFileDialog.AnyFile)
dig.setFilter(QDir.Files)
#下面这部分代码不是很熟悉,不太了解怎么回事,只知道是把文件中的东西拿出来放在self.content里面
if dig.exec_():
filenames=dig.selectedFiles()
f=open(filenames[0],'r')
with f:
data=f.read()
self.contents.setText(data)
if __name__=='__main__':
app=QApplication(sys.argv)
form=fileDialogDemo()
form.show()
sys.exit(app.exec_())
| [
"834819108@qq.com"
] | 834819108@qq.com |
cbfb0a7ceefd20b47c2632746185783e57fbe556 | 6ef3b1919e7acbc72e5706b2dc6d716f8929e3d2 | /pytorch_lightning/trainer/optimizers.py | 663871d98b419c6f3037dcb83eff927bbacd78ae | [
"MIT"
] | permissive | linshaoxin-maker/taas | 04f7dcc7c0d2818718e6b245531e017ca5370231 | 34e11fab167a7beb78fbe6991ff8721dc9208793 | refs/heads/main | 2023-01-19T20:58:04.459980 | 2020-11-27T02:28:36 | 2020-11-27T02:28:36 | 329,522,465 | 6 | 0 | MIT | 2021-01-14T06:02:08 | 2021-01-14T06:02:07 | null | UTF-8 | Python | false | false | 6,897 | py | from abc import ABC
from typing import List, Tuple
import torch
from torch import optim
from torch.optim.optimizer import Optimizer
from pytorch_lightning.core.lightning import LightningModule
from pytorch_lightning.utilities import rank_zero_warn
class TrainerOptimizersMixin(ABC):
def init_optimizers(
self,
model: LightningModule
) -> Tuple[List, List, List]:
optim_conf = model.configure_optimizers()
if optim_conf is None:
rank_zero_warn('`LightningModule.configure_optimizers` returned `None`, '
'this fit will run with no optimizer', UserWarning)
optim_conf = _MockOptimizer()
# single output, single optimizer
if isinstance(optim_conf, Optimizer):
return [optim_conf], [], []
# two lists, optimizer + lr schedulers
elif isinstance(optim_conf, (list, tuple)) and len(optim_conf) == 2 \
and isinstance(optim_conf[0], list):
optimizers, lr_schedulers = optim_conf
lr_schedulers = self.configure_schedulers(lr_schedulers)
return optimizers, lr_schedulers, []
# single dictionary
elif isinstance(optim_conf, dict):
optimizer = optim_conf["optimizer"]
lr_scheduler = optim_conf.get("lr_scheduler", [])
if lr_scheduler:
lr_schedulers = self.configure_schedulers([lr_scheduler])
else:
lr_schedulers = []
return [optimizer], lr_schedulers, []
# multiple dictionaries
elif isinstance(optim_conf, (list, tuple)) and isinstance(optim_conf[0], dict):
optimizers = [opt_dict["optimizer"] for opt_dict in optim_conf]
# take only lr wif exists and ot they are defined - not None
lr_schedulers = [
opt_dict["lr_scheduler"] for opt_dict in optim_conf if opt_dict.get("lr_scheduler")
]
# take only freq wif exists and ot they are defined - not None
optimizer_frequencies = [
opt_dict["frequency"] for opt_dict in optim_conf if opt_dict.get("frequency") is not None
]
# clean scheduler list
if lr_schedulers:
lr_schedulers = self.configure_schedulers(lr_schedulers)
# assert that if frequencies are present, they are given for all optimizers
if optimizer_frequencies and len(optimizer_frequencies) != len(optimizers):
raise ValueError("A frequency must be given to each optimizer.")
return optimizers, lr_schedulers, optimizer_frequencies
# single list or tuple, multiple optimizer
elif isinstance(optim_conf, (list, tuple)):
return list(optim_conf), [], []
# unknown configuration
else:
raise ValueError(
'Unknown configuration for model optimizers.'
' Output from `model.configure_optimizers()` should either be:'
' * single output, single `torch.optim.Optimizer`'
' * single output, list of `torch.optim.Optimizer`'
' * single output, a dictionary with `optimizer` key (`torch.optim.Optimizer`)'
' and an optional `lr_scheduler` key (`torch.optim.lr_scheduler`)'
' * two outputs, first being a list of `torch.optim.Optimizer` second being'
' a list of `torch.optim.lr_scheduler`'
' * multiple outputs, dictionaries as described with an optional `frequency` key (int)')
def configure_schedulers(self, schedulers: list):
# Convert each scheduler into dict structure with relevant information
lr_schedulers = []
default_config = {'interval': 'epoch', # default every epoch
'frequency': 1, # default every epoch/batch
'reduce_on_plateau': False, # most often not ReduceLROnPlateau scheduler
'monitor': 'val_loss'} # default value to monitor for ReduceLROnPlateau
for scheduler in schedulers:
if isinstance(scheduler, dict):
if 'scheduler' not in scheduler:
raise ValueError('Lr scheduler should have key `scheduler`',
' with item being a lr scheduler')
scheduler['reduce_on_plateau'] = isinstance(
scheduler['scheduler'], optim.lr_scheduler.ReduceLROnPlateau)
lr_schedulers.append({**default_config, **scheduler})
elif isinstance(scheduler, optim.lr_scheduler.ReduceLROnPlateau):
lr_schedulers.append({**default_config, 'scheduler': scheduler,
'reduce_on_plateau': True})
elif isinstance(scheduler, optim.lr_scheduler._LRScheduler):
lr_schedulers.append({**default_config, 'scheduler': scheduler})
else:
raise ValueError(f'Input {scheduler} to lr schedulers '
'is a invalid input.')
return lr_schedulers
def reinit_scheduler_properties(self, optimizers: list, schedulers: list):
# Reinitialize optimizer.step properties added by schedulers
for scheduler in schedulers:
scheduler = scheduler['scheduler']
for optimizer in optimizers:
# check that we dont mix users optimizers and schedulers
if scheduler.optimizer == optimizer:
# Find the mro belonging to the base lr scheduler class
for i, mro in enumerate(scheduler.__class__.__mro__):
if (
mro == optim.lr_scheduler._LRScheduler
or mro == optim.lr_scheduler.ReduceLROnPlateau
):
idx = i
state = scheduler.state_dict()
else:
state = None
scheduler.__class__.__mro__[idx].__init__(scheduler, optimizer)
if state is not None:
scheduler.load_state_dict(state)
class _MockOptimizer(Optimizer):
"""The `_MockOptimizer` will be used inplace of an optimizer in the event that `None`
is returned from `configure_optimizers`.
"""
def __init__(self):
super().__init__([torch.zeros(1)], {})
def add_param_group(self, param_group):
pass # Do Nothing
def load_state_dict(self, state_dict):
pass # Do Nothing
def state_dict(self):
return {} # Return Empty
def step(self, closure=None):
if closure is not None:
closure()
def zero_grad(self):
pass # Do Nothing
def __repr__(self):
return 'No Optimizer'
| [
"czh097@gmail.com"
] | czh097@gmail.com |
cd62d851128b56dfad4c05a46bf175597a5648dd | ef7eabdd5f9573050ef11d8c68055ab6cdb5da44 | /topCoder/srms/500s/srm501/div2/fox_progression.py | 7d232b6426e31efc69bb07c2a286459f0cdd6a0f | [
"WTFPL"
] | permissive | gauravsingh58/algo | cdbf68e28019ba7c3e4832e373d32c71902c9c0d | 397859a53429e7a585e5f6964ad24146c6261326 | refs/heads/master | 2022-12-28T01:08:32.333111 | 2020-09-30T19:37:53 | 2020-09-30T19:37:53 | 300,037,652 | 1 | 1 | WTFPL | 2020-10-15T09:26:32 | 2020-09-30T19:29:29 | Java | UTF-8 | Python | false | false | 570 | py | class FoxProgression:
def theCount(self, seq):
if len(seq) == 1:
return -1
a, m = seq[1]-seq[0], seq[1]/float(seq[0])
af, mf = True, m == int(m)
c = sum((af, mf))
for i, j in zip(seq[1:], seq[2:]):
if af and j-i != a:
af = False
c -= 1
if mf and j/float(i) != m:
mf = False
c -= 1
if not af and not mf:
break
if af and mf and seq[-1] + a == seq[-1] * m:
c -= 1
return c
| [
"elmas.ferhat@gmail.com"
] | elmas.ferhat@gmail.com |
a1eca980f1e7db4ea2bb2c1345ea2b21ac48c02d | edfdc0d3a2fdeed95ba7aa3d0e198eb9dafe4064 | /operator_api/auditor/serializers/wallet_state.py | 1112734b67db81e9f2b2170501516b8880cfed53 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | xiaobai900/nocust-hub | 880e72ba4e1d324ae36adea6c03c9761a7d91621 | 76f49f9b8a6c264fcbe9e0c110e98031d463c0a8 | refs/heads/master | 2023-05-28T08:18:17.402228 | 2020-11-01T19:48:17 | 2020-11-01T19:48:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,988 | py | from rest_framework import serializers
from ledger.models import Transfer, Deposit, WithdrawalRequest, Withdrawal
from django.db.models import Q
from .admission import AdmissionSerializer
from .proof import ProofSerializer
from .transfer import TransactionSerializer
from .deposit import DepositSerializer
from .withdrawal import WithdrawalSerializer
from .withdrawal_request import WithdrawalRequestSerializer
class WalletStateSerializer(serializers.Serializer):
registration = AdmissionSerializer(read_only=True)
merkle_proof = ProofSerializer(read_only=True)
transactions = TransactionSerializer(many=True, read_only=True)
deposits = DepositSerializer(many=True, read_only=True)
withdrawal_requests = WithdrawalRequestSerializer(
many=True, read_only=True)
withdrawals = WithdrawalSerializer(many=True, read_only=True)
def to_representation(self, wallet_data_request):
balance = wallet_data_request.wallet\
.exclusivebalanceallotment_set\
.filter(eon_number=wallet_data_request.eon_number).last()
transactions = Transfer.objects\
.filter(eon_number=wallet_data_request.eon_number, id__gte=wallet_data_request.transfer_id)\
.filter(Q(wallet=wallet_data_request.wallet) | Q(recipient=wallet_data_request.wallet))\
.select_related('recipient')\
.select_related('wallet')\
.select_related('recipient__token')\
.select_related('wallet__token')\
.order_by('id')
deposits = Deposit.objects \
.filter(wallet=wallet_data_request.wallet)\
.filter(eon_number=wallet_data_request.eon_number) \
.order_by('id')
withdrawal_requests = WithdrawalRequest.objects \
.filter(wallet=wallet_data_request.wallet)\
.filter(eon_number=wallet_data_request.eon_number) \
.order_by('id')
withdrawals = Withdrawal.objects \
.filter(wallet=wallet_data_request.wallet)\
.filter(eon_number=wallet_data_request.eon_number) \
.order_by('id')
return {
'registration':
AdmissionSerializer(
wallet_data_request.wallet, read_only=True).data,
'merkle_proof':
ProofSerializer(
balance, read_only=True).data if balance is not None else None,
'transactions':
TransactionSerializer(transactions, context={
'wallet_id': wallet_data_request.wallet.id}, many=True, read_only=True).data,
'deposits':
DepositSerializer(deposits, many=True, read_only=True).data,
'withdrawal_requests':
WithdrawalRequestSerializer(
withdrawal_requests, many=True, read_only=True).data,
'withdrawals':
WithdrawalSerializer(
withdrawals, many=True, read_only=True).data
}
| [
"guillaume@felley.io"
] | guillaume@felley.io |
0d1b22f3e6aacb8bee17e5edebb65a999f43f842 | 612325535126eaddebc230d8c27af095c8e5cc2f | /depot_tools/external_bin/gsutil/gsutil_4.15/gsutil/third_party/boto/boto/codedeploy/__init__.py | f48c2dae9e305a94834d5aaafbadc02808f60652 | [
"Apache-2.0",
"MIT",
"BSD-3-Clause"
] | permissive | TrellixVulnTeam/proto-quic_1V94 | 1a3a03ac7a08a494b3d4e9857b24bb8f2c2cd673 | feee14d96ee95313f236e0f0e3ff7719246c84f7 | refs/heads/master | 2023-04-01T14:36:53.888576 | 2019-10-17T02:23:04 | 2019-10-17T02:23:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,703 | py | # Copyright (c) 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
from boto.regioninfo import RegionInfo, get_regions
def regions():
"""
Get all available regions for the AWS CodeDeploy service.
:rtype: list
:return: A list of :class:`boto.regioninfo.RegionInfo`
"""
from boto.codedeploy.layer1 import CodeDeployConnection
return get_regions('codedeploy', connection_cls=CodeDeployConnection)
def connect_to_region(region_name, **kw_params):
for region in regions():
if region.name == region_name:
return region.connect(**kw_params)
return None
| [
"2100639007@qq.com"
] | 2100639007@qq.com |
b13acb7fc13d6d4bd873a484ebf7f63ace15afc0 | 9eaa2c64a777bd24a3cccd0230da5f81231ef612 | /study/1905/month01/code/Stage4/day10/02_renrenlogin2.py | 31c6c8f20308f336b60ec8fed5843bcce90c5158 | [
"MIT"
] | permissive | Dython-sky/AID1908 | 4528932f2ca66b844d8a3fcab5ed8bf84d20eb0c | 46cd54a7b36b5f009974f2bbb7005a4ad440ca1a | refs/heads/master | 2022-04-14T12:23:30.426270 | 2020-04-01T18:05:19 | 2020-04-01T18:05:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,801 | py | import requests
from lxml import etree
class RenrenLogin(object):
def __init__(self):
# 抓取的url地址
self.url = 'http://www.renren.com/973116780/profile'
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'
}
def get_cookies(self):
cookies = {}
cookies_str = 'anonymid=k4c0r1yz-pzvxkf; depovince=GW; _r01_=1; JSESSIONID=abcDAiw02y0mU64ddRB8w; ick_login=83f80a9a-2b55-40f3-8685-88a6144f0626; t=f41b47d87ea76c271cb60f84bd6706660; societyguester=f41b47d87ea76c271cb60f84bd6706660; id=973116780; xnsid=e4530f4b; ver=7.0; loginfrom=null; jebe_key=77eabbe7-277c-4414-ab89-64253f69f03f%7Cccea8a8b81a47ac4b3a5c48154653dfb%7C1576717335984%7C1%7C1576717341787; jebe_key=77eabbe7-277c-4414-ab89-64253f69f03f%7Cccea8a8b81a47ac4b3a5c48154653dfb%7C1576717335984%7C1%7C1576717341792; wp_fold=0; jebecookies=cd8b6928-eee7-4bde-a161-7933a4f284d8|||||; XNESSESSIONID=ead277ab8d81'
for kv in cookies_str.split('; '):
key = kv.split('=')[0]
value = kv.split('=')[1]
cookies[key] = value
return cookies
def get_parse_html(self):
cookies = self.get_cookies()
html = requests.get(
url=self.url,
headers=self.headers,
# cookies参数,类型为字典
cookies=cookies,
).text
parse_obj = etree.HTML(html)
xpath_bds = '//*[@id="operate_area"]/div[1]/ul/li[1]/span/text()'
r_list = parse_obj.xpath(xpath_bds)
# r_list['就读于国家检察官学院']
print(r_list)
def run(self):
self.get_parse_html()
if __name__ == '__main__':
spider = RenrenLogin()
spider.run() | [
"dong_1998_dream@163.com"
] | dong_1998_dream@163.com |
57d19a3a065a491b3910d9971156d10e1ef56fb4 | ce5362e8871b53b02c0a95f82fba8df98ccccad1 | /Service/debug.py | f62461eaaf82a35cabf20b378a19acb411186ea5 | [] | no_license | git-hacker/TeamA_NOISES | d7c810ed44d6694b5e6933e87ac3ac221f806e24 | def359e752b84aab0b16cfb2cecf3412f684bfab | refs/heads/master | 2020-03-28T08:57:45.337321 | 2018-09-10T15:45:08 | 2018-09-10T15:45:08 | 148,002,844 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 707 | py | import librosa
import numpy as np
def read_wav(path, fs=16000):
data, _ = librosa.load(path, sr=fs)
return np.trim_zeros(data)
def play(array, fs=16000):
import sounddevice as sd
print("Playing audio...")
sd.play(array, fs, blocking=True)
print("Stop playing.\n")
def denoise(wave, sr=16000):
from oct2py import octave
x = octave.feval('api/logmmse', wave, sr)
x = np.float32(x)
return np.squeeze(x)
def draw_wave(*wave):
from matplotlib import pyplot as plt
plt.figure()
for w in wave:
plt.plot(w, linewidth=.2)
plt.show()
wave = read_wav('media/noise_2jts5xo.wav')
clean = denoise(wave)
print()
# play(wave)
# play(clean)
print(clean) | [
"gradschool.hchen13@gmail.com"
] | gradschool.hchen13@gmail.com |
e102783efdf5acc7145bb6ca5f1590a771086b2d | 32eeb97dff5b1bf18cf5be2926b70bb322e5c1bd | /benchmark/KISS/testcase/firstcases/testcase3_003.py | 15f1fa5f77c982ba7400d547ef607b57ab7e9616 | [] | no_license | Prefest2018/Prefest | c374d0441d714fb90fca40226fe2875b41cf37fc | ac236987512889e822ea6686c5d2e5b66b295648 | refs/heads/master | 2021-12-09T19:36:24.554864 | 2021-12-06T12:46:14 | 2021-12-06T12:46:14 | 173,225,161 | 5 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,016 | py | #coding=utf-8
import os
import subprocess
import time
import traceback
from appium import webdriver
from appium.webdriver.common.touch_action import TouchAction
from selenium.common.exceptions import NoSuchElementException, WebDriverException
desired_caps = {
'platformName' : 'Android',
'deviceName' : 'Android Emulator',
'platformVersion' : '4.4',
'appPackage' : 'fr.neamar.kiss',
'appActivity' : 'fr.neamar.kiss.MainActivity',
'resetKeyboard' : True,
'androidCoverage' : 'fr.neamar.kiss/fr.neamar.kiss.JacocoInstrumentation',
'noReset' : True
}
def command(cmd, timeout=5):
p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True)
time.sleep(timeout)
p.terminate()
return
def getElememt(driver, str) :
for i in range(0, 5, 1):
try:
element = driver.find_element_by_android_uiautomator(str)
except NoSuchElementException:
time.sleep(1)
else:
return element
os.popen("adb shell input tap 50 50")
element = driver.find_element_by_android_uiautomator(str)
return element
def getElememtBack(driver, str1, str2) :
for i in range(0, 2, 1):
try:
element = driver.find_element_by_android_uiautomator(str1)
except NoSuchElementException:
time.sleep(1)
else:
return element
for i in range(0, 5, 1):
try:
element = driver.find_element_by_android_uiautomator(str2)
except NoSuchElementException:
time.sleep(1)
else:
return element
os.popen("adb shell input tap 50 50")
element = driver.find_element_by_android_uiautomator(str2)
return element
def swipe(driver, startxper, startyper, endxper, endyper) :
size = driver.get_window_size()
width = size["width"]
height = size["height"]
try:
driver.swipe(start_x=int(width * startxper), start_y=int(height * startyper), end_x=int(width * endxper),
end_y=int(height * endyper), duration=2000)
except WebDriverException:
time.sleep(1)
driver.swipe(start_x=int(width * startxper), start_y=int(height * startyper), end_x=int(width * endxper),
end_y=int(height * endyper), duration=2000)
return
# testcase003
try :
starttime = time.time()
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
element = getElememt(driver, "new UiSelector().resourceId(\"fr.neamar.kiss:id/searchEditText\").className(\"android.widget.EditText\")")
element.clear()
element.send_keys("Search apps, contacts, .");
element = getElememt(driver, "new UiSelector().resourceId(\"fr.neamar.kiss:id/searchEditText\").className(\"android.widget.EditText\")")
element.clear()
element.send_keys("1test");
element = getElememtBack(driver, "new UiSelector().text(\"clock alarm timer stopwatch\")", "new UiSelector().className(\"android.widget.TextView\").instance(2)")
TouchAction(driver).long_press(element).release().perform()
element = getElememt(driver, "new UiSelector().resourceId(\"fr.neamar.kiss:id/item_app_icon\").className(\"android.widget.ImageView\")")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().resourceId(\"fr.neamar.kiss:id/searchEditText\").className(\"android.widget.EditText\")")
element.clear()
element.send_keys("testt");
element = getElememtBack(driver, "new UiSelector().text(\"Clock\")", "new UiSelector().className(\"android.widget.TextView\").instance(1)")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().resourceId(\"fr.neamar.kiss:id/searchEditText\").className(\"android.widget.EditText\")")
element.clear()
element.send_keys("testt");
element = getElememt(driver, "new UiSelector().resourceId(\"fr.neamar.kiss:id/clearButton\").className(\"android.widget.ImageView\")")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().resourceId(\"fr.neamar.kiss:id/searchEditText\").className(\"android.widget.EditText\")")
element.clear()
element.send_keys("Search apps, contacts, .");
element = getElememtBack(driver, "new UiSelector().text(\"Search Google for “12st”\")", "new UiSelector().className(\"android.widget.TextView\")")
TouchAction(driver).long_press(element).release().perform()
element = getElememt(driver, "new UiSelector().resourceId(\"fr.neamar.kiss:id/searchEditText\").className(\"android.widget.EditText\")")
element.clear()
element.send_keys("1test");
element = getElememt(driver, "new UiSelector().resourceId(\"fr.neamar.kiss:id/clearButton\").className(\"android.widget.ImageView\")")
TouchAction(driver).tap(element).perform()
except Exception, e:
print 'FAIL'
print 'str(e):\t\t', str(e)
print 'repr(e):\t', repr(e)
print traceback.format_exc()
else:
print 'OK'
finally:
cpackage = driver.current_package
endtime = time.time()
print 'consumed time:', str(endtime - starttime), 's'
command("adb shell am broadcast -a com.example.pkg.END_EMMA --es name \"3_003\"")
jacocotime = time.time()
print 'jacoco time:', str(jacocotime - endtime), 's'
driver.quit()
if (cpackage != 'fr.neamar.kiss'):
cpackage = "adb shell am force-stop " + cpackage
os.popen(cpackage) | [
"prefest2018@gmail.com"
] | prefest2018@gmail.com |
a01bf4fdb740165c86936ed2d5025cd058dd3f36 | 96d284595c07bf3eb135f88a1a1e5fd2692293dc | /labml_db/serializer/yaml.py | f0afb684e1e52fd58864477a7b5da669068d9e55 | [
"MIT"
] | permissive | actuarial-tools/db | cfc3be5b027fe8127032ccecf64a295a83601eba | f6be48f8c724bf76fc6dc966cb4e13bd6501e911 | refs/heads/master | 2023-01-13T19:21:49.783395 | 2020-11-24T03:26:13 | 2020-11-24T03:26:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 444 | py |
from . import Serializer
from .utils import encode_keys, decode_keys
from ..types import ModelDict
class YamlSerializer(Serializer):
file_extension = 'yaml'
def to_string(self, data: ModelDict) -> str:
import yaml
return yaml.dump(encode_keys(data), default_flow_style=False)
def from_string(self, data: str) -> ModelDict:
import yaml
return decode_keys(yaml.load(data, Loader=yaml.FullLoader))
| [
"vpjayasiri@gmail.com"
] | vpjayasiri@gmail.com |
b6540baaefcf2ad5c0dc65ec15d031a6d31b70a0 | ec1059f4ccea10deb2cb8fd7f9458700a5e6ca4c | /venv/Lib/site-packages/qiskit/test/mock/backends/cambridge/fake_cambridge.py | 9391cbac2bdaa8760fd1c54ad790775b685e29f5 | [
"Apache-2.0",
"MIT"
] | permissive | shivam675/Quantum-CERN | b60c697a3a7ad836b3653ee9ce3875a6eafae3ba | ce02d9198d9f5a1aa828482fea9b213a725b56bb | refs/heads/main | 2023-01-06T20:07:15.994294 | 2020-11-13T10:01:38 | 2020-11-13T10:01:38 | 330,435,191 | 1 | 0 | MIT | 2021-01-17T16:29:26 | 2021-01-17T16:29:25 | null | UTF-8 | Python | false | false | 2,107 | py | # This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Fake Cambridge device (20 qubit).
"""
import os
import json
from qiskit.providers.models import QasmBackendConfiguration, BackendProperties
from qiskit.test.mock.fake_backend import FakeBackend
class FakeCambridge(FakeBackend):
"""A fake Cambridge backend."""
def __init__(self):
"""
00 ↔ 01 ↔ 02 ↔ 03 ↔ 04
↕ ↕
05 06
↕ ↕
07 ↔ 08 ↔ 09 ↔ 10 ↔ 11 ↔ 12 ↔ 13 ↔ 14 ↔ 15
↕ ↕ ↕
16 17 18
↕ ↕ ↕
19 ↔ 20 ↔ 21 ↔ 22 ↔ 23 ↔ 24 ↔ 25 ↔ 26 ↔ 27
"""
dirname = os.path.dirname(__file__)
filename = "conf_cambridge.json"
with open(os.path.join(dirname, filename)) as f_conf:
conf = json.load(f_conf)
configuration = QasmBackendConfiguration.from_dict(conf)
configuration.backend_name = 'fake_cambridge'
self._defaults = None
self._properties = None
super().__init__(configuration)
def properties(self):
"""Returns a snapshot of device properties"""
if not self._properties:
dirname = os.path.dirname(__file__)
filename = "props_cambridge.json"
with open(os.path.join(dirname, filename)) as f_prop:
props = json.load(f_prop)
self._properties = BackendProperties.from_dict(props)
return self._properties
| [
"vinfinitysailor@gmail.com"
] | vinfinitysailor@gmail.com |
3484100f82f3f01cf5341d95128ee9886dc4357f | 15f321878face2af9317363c5f6de1e5ddd9b749 | /solutions_python/Problem_199/3642.py | 933226fea834fae98b48a12ad1623499f69186ae | [] | no_license | dr-dos-ok/Code_Jam_Webscraper | c06fd59870842664cd79c41eb460a09553e1c80a | 26a35bf114a3aa30fc4c677ef069d95f41665cc0 | refs/heads/master | 2020-04-06T08:17:40.938460 | 2018-10-14T10:12:47 | 2018-10-14T10:12:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 731 | py | import sys
def func(arr, w):
s = [0]*len(arr)
sum = ans = 0
for i in range(len(arr)):
s[i] += (arr[i]+sum)%2 != 1
sum += s[i]- (s[i-w+1] if (i>= w-1) else 0)
ans += s[i]
if(i > len(arr)-w and s[i] != 0):
return 'IMPOSSIBLE'
return str(ans)
fname = 'input2.txt'
with open(fname) as f:
content = f.readlines()
lines = content[1:]
orig_stdout = sys.stdout
fout = open('out1.txt', 'w')
sys.stdout = fout
for j,line in enumerate(lines):
st, w = line.split()
arr = [(1 if i =='+' else 0) for i in st]
print 'Case #'+str(j+1)+': '+func(arr, int(w))
sys.stdout = orig_stdout
f.close()
fout.close()
| [
"miliar1732@gmail.com"
] | miliar1732@gmail.com |
547a53c86ba8b4cd0d676928ceea1cd8c29a5eb4 | 157d46852ea5788f1c7153b3ce10afb71d5a34c5 | /setup.py | d80136964004e5a4fc17965a395deeebde568d6d | [] | no_license | rctk/rctk.qx | 4475e0e0918df16a1d961a591d5d5d403a59ec23 | c1d510b2cd4404b5b9897e18b33c3d5b80813608 | refs/heads/master | 2020-05-19T13:50:17.871325 | 2011-09-13T20:16:51 | 2011-09-13T20:16:51 | 2,898,626 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 881 | py | from setuptools import setup, find_packages
import os
version = '1.0'
setup(name='rctk.qx',
version=version,
description="Qooxdoo frontend for RCTK",
long_description=open("README.txt").read() + "\n" +
open(os.path.join("docs", "HISTORY.txt")).read(),
# Get more strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
"Programming Language :: Python",
],
keywords='',
author='Ivo van der Wijk',
author_email='ivo@rctk.org',
url='http://rctk.org/',
license='BSD',
packages=find_packages(exclude=['ez_setup']),
namespace_packages=['rctk'],
include_package_data=True,
zip_safe=False,
install_requires=[
'setuptools',
'rctk',
],
entry_points="""
# -*- Entry points: -*-
""",
)
| [
"github@in.m3r.nl"
] | github@in.m3r.nl |
a4ab3dfa2ec84f7f290cefd5efc56c798f2baf7b | 5fd4707876cac0a4ca3b14af9a936301c45b5599 | /03_字典和集合/fp_07_StrKeyDict0在查询的时候把非字符串的键转换为字符串.py | 0f65f3920a1e86a92cadfe6eba73b40dbd5364f7 | [] | no_license | xuelang201201/FluentPython | 5b0d89bfc6ee1238ad77db9955ec7e8417b418b8 | 7cbedf7c780c2a9e0edac60484f2ad4c385e1dbd | refs/heads/master | 2022-04-26T21:49:16.923214 | 2020-04-27T01:27:50 | 2020-04-27T01:27:50 | 258,290,957 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,297 | py | class StrKeyDict0(dict): # StrKeyDict0 继承了 dict。
def __missing__(self, key):
if isinstance(key, str): # 如果找不到的键本身就是字符串,那就抛出 KeyError 异常。
raise KeyError(key)
return self[str(key)] # 如果找不到的键不是字符串,那么把它转换成字符串再进行查找。
def get(self, key, default=None):
try:
# get 方法把查找工作用 self[key] 的形式委托给 __getitem__,
# 这样在宣布查找失败之前,还能通过 __missing__ 再给某个键一个机会。
return self[key]
except KeyError:
# 如果抛出 KeyError,那么说明 __missing__ 也失败了,于是返回 default。
return default
def __contains__(self, key):
# 先按照传入键的原本的值来查找(我们的映射类型中可能含有非字符串的键),
# 如果没找到,再用 str() 方法把键转换成字符串再查找一次。
return key in self.keys() or str(key) in self.keys()
d = StrKeyDict0([('2', 'two'), ('4', 'four')])
print(d['2'])
print(d[4])
# print(d[1])
print(d.get('2'))
print(d.get('4'))
print(d.get(1, 'N/A'))
print(2 in d)
print(1 in d)
| [
"xuelang201201@gmail.com"
] | xuelang201201@gmail.com |
91840a9b9599ca25ad5162852ade91602d46b6a3 | 9740b4cfc46b924c2e430472ce0522fa35813465 | /django_lender/settings.py | 87c2c6eaeeae5c3144315c44ebe1535b2a0dd0dd | [
"MIT"
] | permissive | madelinepet/django_lender | d99f176b76d245ebcc0032f3304d677cd7a4fcfe | 5c6c342e8306e848e93db31a02efe9ef1299a401 | refs/heads/master | 2020-03-28T21:48:08.933512 | 2018-10-03T23:03:01 | 2018-10-03T23:03:01 | 149,183,702 | 0 | 0 | MIT | 2018-10-03T23:02:57 | 2018-09-17T20:26:20 | JavaScript | UTF-8 | Python | false | false | 4,217 | py | """
Django settings for django_lender project.
Generated by 'django-admin startproject' using Django 2.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# If no secret key, do not run app.
SECRET_KEY = os.environ.get('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
# Defaults to False
DEBUG = os.environ.get('DEBUG', False)
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '').split()
# Application definition
INSTALLED_APPS = [
'django_lender',
'lender_books',
'django.contrib.admin',
'django.contrib.auth',
'django_registration',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'django_lender.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'django_lender.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ.get('DB_NAME', 'test_books'),
'USER': os.environ.get('DB_USER'),
'PASSWORD': os.environ.get('DB_PASSWORD'),
'HOST': os.environ.get('DB_HOST', 'localhost'),
'PORT': os.environ.get('DB_PORT', 5432),
'TEST': {
'NAME': 'lender_test'
}
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
# CUSTOM SETTINGS GO DOWN HERE
# os.path business gets you to the root of your directory. For production!
# (While debug = True, django doesn't use static root)
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# Image Upload settings
MEDIA_ROOT = '/static-assets/'
MEDIA_URL = '/static-assets/'
# Django Registration settings
ACCOUNT_ACTIVATION_DAYS = 1
LOGIN_REDIRECT_URL = '/'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER', '')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD', '')
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
| [
"madelinepet@hotmail.com"
] | madelinepet@hotmail.com |
ab7516a56c5ad7146d01832178bc747e367073e6 | d6acd0cdfeba9d4777ae897e9edd225e5317d254 | /donate_anything/item/migrations/0001_initial.py | 03277750c0f3544c629f4322043237e2706ebdaf | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | fossabot/Donate-Anything | 680be213d90888bdf565e22214c1267fa5a8b84c | 335ef00f3d8bf76b8827d337b68c5ba0fc99bc64 | refs/heads/master | 2022-12-06T18:37:01.398381 | 2020-08-23T02:01:26 | 2020-08-23T02:01:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,315 | py | # Generated by Django 3.0.8 on 2020-07-17 23:12
import django.contrib.postgres.fields
import django.contrib.postgres.indexes
import django.db.models.deletion
from django.conf import settings
from django.contrib.postgres.operations import TrigramExtension
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
("charity", "0001_initial"),
]
operations = [
TrigramExtension(),
migrations.CreateModel(
name="Item",
fields=[
("id", models.BigAutoField(primary_key=True, serialize=False)),
("name", models.CharField(max_length=100, unique=True, db_index=True)),
("image", models.ImageField(blank=True, null=True, upload_to="")),
("is_appropriate", models.BooleanField(default=True)),
],
),
migrations.CreateModel(
name="WantedItem",
fields=[
("id", models.BigAutoField(primary_key=True, serialize=False)),
(
"charity",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="charity.Charity",
),
),
(
"item",
models.ForeignKey(
db_index=False,
on_delete=django.db.models.deletion.CASCADE,
to="item.Item",
),
),
],
),
migrations.CreateModel(
name="ProposedItem",
fields=[
("id", models.BigAutoField(primary_key=True, serialize=False)),
(
"item",
django.contrib.postgres.fields.ArrayField(
base_field=models.BigIntegerField(), size=10000, default=list
),
),
(
"names",
django.contrib.postgres.fields.ArrayField(
base_field=models.CharField(max_length=100),
size=1000,
default=list,
),
),
("closed", models.BooleanField(default=False)),
(
"entity",
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
to="charity.Charity",
),
),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
],
),
migrations.CreateModel(
name="Category",
fields=[
("id", models.BigAutoField(primary_key=True, serialize=False)),
(
"category",
models.PositiveSmallIntegerField(
choices=[
(0, "Financial"),
(1, "Clothing"),
(2, "Kitchenware"),
(3, "Books and Media"),
(4, "Toys and Games"),
(5, "Art"),
(6, "Hygiene"),
(7, "Sports"),
(8, "Furniture"),
(9, "Electronics"),
(10, "Internal Health"),
(11, "School Supplies"),
(12, "Linen"),
(13, "Recyclables"),
(14, "Compost"),
(15, "Food and Liquids"),
(16, "Miscellaneous"),
]
),
),
(
"charity",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="charity.Charity",
),
),
],
),
migrations.AddIndex(
model_name="item",
index=django.contrib.postgres.indexes.GinIndex(
fields=["name"],
name="item_name_sim_gin_index",
opclasses=("gin_trgm_ops",),
),
),
migrations.AddIndex(
model_name="wanteditem",
index=django.contrib.postgres.indexes.BrinIndex(
fields=["item"], name="item_wanted_item_id_b5f5d9_brin"
),
),
migrations.AddConstraint(
model_name="category",
constraint=models.UniqueConstraint(
fields=("charity", "category"), name="charity_supports_category"
),
),
migrations.AddConstraint(
model_name="wanteditem",
constraint=models.UniqueConstraint(
fields=("charity", "item"), name="charity_need_item"
),
),
]
| [
"acwangpython@gmail.com"
] | acwangpython@gmail.com |
65024f94ef36f76cc69ae7f6045e4016d5ab2984 | 71b8b60c5627ace1bbda39f679f93f60b55543ca | /tensorflow_federated/python/common_libs/golden.py | c9ac9996e2e44a95a545046401cfb6d448d6ab15 | [
"Apache-2.0"
] | permissive | tensorflow/federated | ff94b63e9f4af448795bae77cee5b627dcae9051 | ad4bca66f4b483e09d8396e9948630813a343d27 | refs/heads/main | 2023-08-31T11:46:28.559047 | 2023-08-31T02:04:38 | 2023-08-31T02:09:59 | 161,556,784 | 2,297 | 631 | Apache-2.0 | 2023-09-13T22:54:14 | 2018-12-12T23:15:35 | Python | UTF-8 | Python | false | false | 5,056 | py | ## Copyright 2020, The TensorFlow Federated Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for asserting against golden files."""
import contextlib
import difflib
import io
import os.path
import re
import traceback
from typing import Optional
from absl import flags
_GOLDEN = flags.DEFINE_multi_string(
'golden', [], 'List of golden files available.'
)
_UPDATE_GOLDENS = flags.DEFINE_bool(
'update_goldens', False, 'Set true to update golden files.'
)
_VERBOSE = flags.DEFINE_bool(
'verbose', False, 'Set true to show golden diff output.'
)
FLAGS = flags.FLAGS
class MismatchedGoldenError(RuntimeError):
pass
_filename_to_golden_map: Optional[dict[str, str]] = None
def _filename_to_golden_path(filename: str) -> str:
"""Retrieve the `--golden` path flag for a golden file named `filename`."""
# Parse out all of the golden files once
global _filename_to_golden_map
if _filename_to_golden_map is None:
_filename_to_golden_map = {}
for golden_path in _GOLDEN.value:
name = os.path.basename(golden_path)
old_path = _filename_to_golden_map.get(name)
if old_path is not None and old_path != golden_path:
raise RuntimeError(
f'Multiple golden files provided for filename {name}:\n'
f'{old_path} and\n'
f'{golden_path}\n'
'Golden file names in the same test target must be unique.'
)
_filename_to_golden_map[name] = golden_path
if filename not in _filename_to_golden_map:
raise RuntimeError(f'No `--golden` files found with filename {filename}')
return _filename_to_golden_map[filename]
def check_string(filename: str, value: str):
"""Check that `value` matches the contents of the golden file `filename`."""
# Append a newline to the end of `value` to work around lint against
# text files with no trailing newline.
if not value.endswith('\n'):
value = value + '\n'
golden_path = _filename_to_golden_path(filename)
if _UPDATE_GOLDENS.value:
with open(golden_path, 'w') as f:
f.write(value)
return
with open(golden_path, 'r') as f:
golden_contents = f.read()
if value == golden_contents:
return
message = (
f'The contents of golden file {filename} '
'no longer match the current value.\n'
'To update the golden file, rerun this target with:\n'
'`--test_arg=--update_goldens --test_strategy=local`\n'
)
if _VERBOSE.value:
message += 'Full diff:\n'
split_value = value.split('\n')
split_golden = golden_contents.split('\n')
message += '\n'.join(difflib.unified_diff(split_golden, split_value))
else:
message += 'To see the full diff, rerun this target with:\n'
message += '`--test_arg=--verbose\n'
raise MismatchedGoldenError(message)
def traceback_string(exc_type, exc_value, tb) -> str:
"""Generates a standardized stringified version of an exception traceback."""
exception_string_io = io.StringIO()
traceback.print_exception(exc_type, exc_value, tb, file=exception_string_io)
exception_string = exception_string_io.getvalue()
# Strip path to TFF to normalize error messages
# First in filepaths.
without_filepath = re.sub(
r'\/\S*\/tensorflow_federated\/', '', exception_string
)
# Then also in class paths.
without_classpath = re.sub(
r'(\S*\.)+?(?=tensorflow_federated)', '', without_filepath
)
# Strip line numbers to avoid churn
without_linenumber = re.sub(r', line \d*', '', without_classpath)
return without_linenumber
def check_raises_traceback(
filename: str, exception: Exception
) -> contextlib.AbstractContextManager[None]:
"""Check for `exception` to be raised, generating a golden traceback."""
# Note: does not use `@contextlib.contextmanager` because that adds
# this function to the traceback.
return _TracebackManager(filename, exception)
class _TracebackManager:
"""Context manager for collecting tracebacks and comparing them to goldens."""
def __init__(self, filename, exception):
self._filename = filename
self._exception = exception
def __enter__(self):
pass
def __exit__(self, exc_type, exc_value, tb):
if not issubclass(exc_type, self._exception):
message = f'Exception `{self._exception.__name__}` was not thrown.'
if exc_value is not None:
message += f' A different exception was thrown: {exc_type.__name__}'
raise RuntimeError(message)
traceback_str = traceback_string(exc_type, exc_value, tb)
check_string(self._filename, traceback_str)
return True
| [
"tensorflow.copybara@gmail.com"
] | tensorflow.copybara@gmail.com |
b168f4b1683a0a19436abc505deb186004b85a6c | 94dcccac732db506a1066a83961554842ca50d0b | /weather/urls.py | 55c116563a1e827708236748f015e45215bbb1d8 | [] | no_license | PickertJoe/personal_website | 69e7d2d6c1065686fe917c7af0e836b193cab612 | 3c61e2847fd375eb99fcb23b2c9ad69ca73b1cf3 | refs/heads/master | 2022-12-13T08:10:53.177963 | 2022-03-05T01:59:43 | 2022-03-05T01:59:43 | 191,227,416 | 0 | 0 | null | 2022-11-22T04:45:56 | 2019-06-10T18:51:07 | Python | UTF-8 | Python | false | false | 201 | py | from django.urls import path
from . import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('', views.weather_index, name='weather_index'),
]
| [
"pickertjoe@gmail.com"
] | pickertjoe@gmail.com |
c8843c93853bb44731b78258d1617cea61e2fa91 | d998c5fbbd02c1666862b8996639b8f34604a6eb | /dirigible/sheet/importer.py | 49899c0fae53173c5b9e16e783f59ea4e2ecb81a | [
"MIT"
] | permissive | randfb/dirigible-spreadsheet | 668f8f341fd48add69937d9dc41353360ed4f08c | c771e9a391708f3b219248bf9974e05b1582fdd0 | refs/heads/master | 2020-04-14T02:49:44.123713 | 2017-04-13T06:51:44 | 2017-04-13T06:51:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,619 | py | # Copyright (c) 2010 Resolver Systems Ltd, PythonAnywhere LLP
# See LICENSE.md
#
from chardet.universaldetector import UniversalDetector
from codecs import getreader
import csv
from xlrd import (
error_text_from_code, xldate_as_tuple, XL_CELL_DATE, XL_CELL_ERROR,
)
from worksheet import Worksheet
class DirigibleImportError(Exception):
pass
def worksheet_from_csv(
worksheet, csv_file, start_column, start_row, excel_encoding
):
def autodetect_encoding(csv_file):
detector = UniversalDetector()
for line in csv_file.readlines():
detector.feed(line)
if detector.done: break
detector.close()
csv_file.seek(0)
encoding = detector.result['encoding']
if not encoding:
raise DirigibleImportError('could not recognise encoding')
return encoding
def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
# csv.py doesn't do Unicode; encode temporarily as UTF-8:
csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
dialect=dialect, **kwargs)
for row in csv_reader:
# decode UTF-8 back to Unicode, cell by cell:
yield [unicode(cell, 'utf-8') for cell in row]
def utf_8_encoder(unicode_csv_data):
for line in unicode_csv_data:
yield line.encode('utf-8')
if excel_encoding:
encoding = 'windows-1252'
else:
encoding = autodetect_encoding(csv_file)
unicode_translated_csv_file = getreader(encoding)(csv_file)
row = start_row
try:
for csv_row in unicode_csv_reader(unicode_translated_csv_file):
column = start_column
for csv_cell in csv_row:
worksheet[column, row].formula = unicode(csv_cell)
column += 1
row += 1
except Exception, e:
raise DirigibleImportError(unicode(e))
return worksheet
def worksheet_from_excel(excel_sheet):
worksheet = Worksheet()
for col in range(excel_sheet.ncols):
for row in range(excel_sheet.nrows):
cell = excel_sheet.cell(row, col)
if cell.ctype == XL_CELL_ERROR:
formula = '=%s' % (error_text_from_code[cell.value], )
elif cell.ctype == XL_CELL_DATE:
formula = '=DateTime(%s, %s, %s, %s, %s, %s)' % xldate_as_tuple(
cell.value, excel_sheet.book.datemode)
else:
formula = unicode(excel_sheet.cell(row, col).value)
worksheet[col + 1, row + 1].formula = formula
return worksheet
| [
"hjwp2@cantab.net"
] | hjwp2@cantab.net |
553dfa692cedff65a719f24eedf7b1caa123174e | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02780/s249015131.py | df3ee8200242ba2c41976713fe7df8440c0aa10b | [] | 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 | 339 | py | n,k = map(int, input().split())
p = [int(x) for x in input().split()]
p_kitaiti=[float((x+1)/2) for x in p]
ruisekiwa=[p_kitaiti[0]]
for i in range(1,len(p_kitaiti)):
ruisekiwa.append(ruisekiwa[-1]+p_kitaiti[i])
ans=ruisekiwa[k-1]
for i in range(1,len(ruisekiwa)-k+1):
ans=max(ans,ruisekiwa[i+k-1]-ruisekiwa[i-1])
print(ans) | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
58ec6e180cfe9269f7d7743814d631827370228b | 15f321878face2af9317363c5f6de1e5ddd9b749 | /solutions_python/Problem_200/5463.py | 9161570ab3d441e8b67d8aabb2838ba513463229 | [] | no_license | dr-dos-ok/Code_Jam_Webscraper | c06fd59870842664cd79c41eb460a09553e1c80a | 26a35bf114a3aa30fc4c677ef069d95f41665cc0 | refs/heads/master | 2020-04-06T08:17:40.938460 | 2018-10-14T10:12:47 | 2018-10-14T10:12:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 522 | py | test = int(input())
def isTidy(num):
last = 10 ** 19
while(num > 0):
currD = num % 10
if currD > last:
return False
else:
last = currD
num /= 10
num = int(num)
return True
def lastTidy(max):
lastT = -1
for i in range(1, max + 1):
if isTidy(i):
lastT = i
return lastT
case = 1
while(test > 0):
currN = int(input())
print("Case #{}: {}".format(case, lastTidy(currN)))
case += 1
test -= 1
| [
"miliar1732@gmail.com"
] | miliar1732@gmail.com |
fd7393b541b9bb5f909a07532784680f760067d5 | c88a3a539d32a8c0c3426508d85bcead51e28273 | /average_solve_cartpole_v1_DQN.py | cc1d11dbc7d2b3b7893c0d1df3d81686249ce6c8 | [] | no_license | afcarl/DQN_Experiments | f6f4e35190eafa5add1ccb4b6487994af49368cd | 667e072a76bf3702556ae44fe6b4a9ebec143fbd | refs/heads/master | 2020-03-22T08:06:39.490033 | 2017-02-22T03:49:22 | 2017-02-22T03:49:22 | 139,745,429 | 1 | 0 | null | 2018-07-04T16:31:59 | 2018-07-04T16:31:59 | null | UTF-8 | Python | false | false | 6,214 | py | import copy
import gym
from gym import wrappers
import matplotlib.pyplot as plt
import time
from utils import *
from ReplayMemory import ReplayMemory
from agents import AgentEpsGreedy
from valuefunctions import ValueFunctionDQN
# Inspired by necnec's algorithm at:
# https://gym.openai.com/evaluations/eval_89nQ59Y4SbmrlQ0P9pufiA
# And inspired by David Silver's Deep RL tutorial:
# http://www0.cs.ucl.ac.uk/staff/d.silver/web/Resources_files/deep_rl.pdf
# results_dir_prefix = '###'
# upload = False
discount = 0.99
decay_eps = 0.9
batch_size = 64
max_n_ep = 1000
#USING A LARGE CUMULATIVE MINIMUM AVERAGE REWARD FOR THE CART POLE HERE
min_avg_Rwd = 1000000 # Minimum average reward to consider the problem as solved
n_avg_ep = 100 # Number of consecutive episodes to calculate the average reward
# t = get_last_folder_id(results_dir_prefix) + 1 # Calculate next test id
# results_dir = results_dir_prefix + '\\' + str(t).zfill(4)
# os.makedirs(results_dir)
def run_episode(env,
agent,
state_normalizer,
memory,
batch_size,
discount,
max_step=10000):
state = env.reset()
if state_normalizer is not None:
state = state_normalizer.transform(state)[0]
done = False
total_reward = 0
step_durations_s = np.zeros(shape=max_step, dtype=float)
train_duration_s = np.zeros(shape=max_step-batch_size, dtype=float)
progress_msg = "Step {:5d}/{:5d}. Avg step duration: {:3.1f} ms. Avg train duration: {:3.1f} ms. Loss = {:2.10f}."
loss_v = 0
w1_m = 0
w2_m = 0
w3_m = 0
i = 0
action = 0
for i in range(max_step):
t = time.time()
if i > 0 and i % 200 == 0:
print(progress_msg.format(i, max_step,
np.mean(step_durations_s[0:i])*1000,
np.mean(train_duration_s[0:i-batch_size])*1000,
loss_v))
if done:
break
action = agent.act(state)
state_next, reward, done, info = env.step(action)
total_reward += reward
if state_normalizer is not None:
state_next = state_normalizer.transform(state_next)[0]
memory.add((state, action, reward, state_next, done))
if len(memory.memory) > batch_size: # DQN Experience Replay
states_b, actions_b, rewards_b, states_n_b, done_b = zip(*memory.sample(batch_size))
states_b = np.array(states_b)
actions_b = np.array(actions_b)
rewards_b = np.array(rewards_b)
states_n_b = np.array(states_n_b)
done_b = np.array(done_b).astype(int)
q_n_b = agent.predict_q_values(states_n_b) # Action values on the arriving state
targets_b = rewards_b + (1. - done_b) * discount * np.amax(q_n_b, axis=1)
targets = agent.predict_q_values(states_b)
for j, action in enumerate(actions_b):
targets[j, action] = targets_b[j]
t_train = time.time()
loss_v, w1_m, w2_m, w3_m = agent.train(states_b, targets)
train_duration_s[i - batch_size] = time.time() - t_train
state = copy.copy(state_next)
step_durations_s[i] = time.time() - t # Time elapsed during this step
return loss_v, w1_m, w2_m, w3_m, total_reward
env = gym.make("CartPole-v1")
n_actions = env.action_space.n
state_dim = env.observation_space.high.shape[0]
value_function = ValueFunctionDQN(state_dim=state_dim, n_actions=n_actions, batch_size=batch_size)
agent = AgentEpsGreedy(n_actions=n_actions, value_function_model=value_function, eps=0.9)
memory = ReplayMemory(max_size=100000)
Experiments = 3
Experiments_All_Rewards = np.zeros(shape=(max_n_ep))
for e in range(Experiments):
print('Experiment Number ', e)
loss_per_ep = []
w1_m_per_ep = []
w2_m_per_ep = []
w3_m_per_ep = []
total_reward = []
ep = 0
avg_Rwd = -np.inf
episode_end_msg = 'loss={:2.10f}, w1_m={:3.1f}, w2_m={:3.1f}, w3_m={:3.1f}, total reward={}'
while avg_Rwd < min_avg_Rwd and ep < max_n_ep:
if ep >= n_avg_ep:
avg_Rwd = np.mean(total_reward[ep-n_avg_ep:ep])
print("EPISODE {}. Average reward over the last {} episodes: {}.".format(ep, n_avg_ep, avg_Rwd))
else:
print("EPISODE {}.".format(ep))
loss_v, w1_m, w2_m, w3_m, cum_R = run_episode(env, agent, None, memory, batch_size=batch_size, discount=discount,
max_step=15000)
print(episode_end_msg.format(loss_v, w1_m, w2_m, w3_m, cum_R))
if agent.eps > 0.0001:
agent.eps *= decay_eps
# Collect episode results
loss_per_ep.append(loss_v)
w1_m_per_ep.append(w1_m)
w2_m_per_ep.append(w2_m)
w3_m_per_ep.append(w3_m)
total_reward.append(cum_R)
ep += 1
Experiments_All_Rewards = Experiments_All_Rewards + total_reward
np.save('/Users/Riashat/Documents/PhD_Research/BASIC_ALGORITHMS/My_Implementations/gym_examples/DQN_Experiments/Average_DQN_CartPole_V1_Results/' + 'CartPole_V1_cumulative_reward' + 'Experiment_' + str(e) + '.npy', total_reward)
np.save('/Users/Riashat/Documents/PhD_Research/BASIC_ALGORITHMS/My_Implementations/gym_examples/DQN_Experiments/Average_DQN_CartPole_V1_Results/' + 'CartPole_V1_value_function_loss' + 'Experiment_' + str(e) + '.npy', loss_per_ep)
env.close()
print('Saving Average Cumulative Rewards Over Experiments')
Average_Cum_Rwd = np.divide(Experiments_All_Rewards, Experiments)
np.save('/Users/Riashat/Documents/PhD_Research/BASIC_ALGORITHMS/My_Implementations/gym_examples/DQN_Experiments/Average_DQN_CartPole_V1_Results/' + 'Average_Cum_Rwd_CartPole_V1' + '.npy', Average_Cum_Rwd)
print "All Experiments DONE"
#####################
#PLOT RESULTS
eps = range(ep)
plt.figure()
plt.subplot(211)
plt.plot(eps, Average_Cum_Rwd)
Rwd_avg = movingaverage(Average_Cum_Rwd, 100)
plt.plot(eps[len(eps) - len(Rwd_avg):], Rwd_avg)
plt.xlabel("Episode number")
plt.ylabel("Reward per episode")
plt.grid(True)
plt.title("Total reward")
| [
"riashat.islam.93@gmail.com"
] | riashat.islam.93@gmail.com |
838df2bb911c2fe314b5652625d5a57027bb1644 | 3eed7b405d1fb9305225718f4c01494bc856da88 | /swExpertAcademy/python_basic/6262_set,dict.py | 9975b904fe77de00c41287c94b3333c4c28cc26a | [] | no_license | tesschung/TIL | b2610d714ec9e4778aafe7538d02b3e3d9fe89d9 | bd79e4af68ef19599cb843f3ce8f5d81a322a2f7 | refs/heads/master | 2020-06-17T11:53:52.595880 | 2019-07-26T08:02:03 | 2019-07-26T08:02:03 | 195,916,443 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 929 | py | """
다음의 결과와 같이 입력된 문자열의 문자 빈도수를 구하는 프로그램을 작성하십시오.
입력
abcdefgabc
출력
a,2
b,2
c,2
d,1
e,1
f,1
g,1
"""
## dict 외우기
a = 'abcdefgabc'
a = list(a)
print(a)
alphabet_count={}
for alphabet in a:
if alphabet in alphabet_count:
alphabet_count[alphabet] += 1
else:
alphabet_count[alphabet] = 1
print(alphabet_count)
print(alphabet_count['a'])
print(alphabet_count.keys())
print(alphabet_count.values())
# key와 value를 한꺼번에 for문을 반복하려면 items() 를 사용합니다.
for key, val in alphabet_count.items():
print('{},{}'.format(key,val))
""" 실수
for alphabet_one in alphabet_count.keys():
print(alphabet_one)
for alphabet_num in alphabet_count.values():
if alphabet_one == alphabet_one:
print(alphabet_num)
print(alphabet_one,",",alphabet_num)
""" | [
"geobera0910@naver.com"
] | geobera0910@naver.com |
5c80ef81d655783a11e72b107e7460ec06e90969 | 6f3389c93cf1057bca5398940932561c19dbec1d | /Solving Club/2/Diamond.py | cf87ccb41f7082bb50c22b4f1782141b2dcfe91f | [] | no_license | Jeonseoghyeon/APR | 0af9ac1b4ba666a97d78b92e3e599c5a8bc87acc | 7a3822913b84ae6ecf80c8e35c7c8e400981d1fe | refs/heads/master | 2020-12-23T13:55:24.194463 | 2020-06-30T07:00:23 | 2020-06-30T07:00:23 | 237,172,582 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 374 | py | import sys
sys.stdin = open("Pascal input.txt","r")
tc = int(input())
for i in range(1,tc+1):
word = input()
lw = len(word)
print('..#.'*(lw)+'.', end='')
print()
print('.#'*(lw*2)+'.')
for x in range(lw):
print('#',end='')
print('.{}.'.format(word[x]),end='')
print('#')
print('.#'*(lw*2)+'.')
print('..#.'*(lw)+'.') | [
"jsh28592@gmail.com"
] | jsh28592@gmail.com |
41587d72a71685d71fb47ce204224c2ce9746626 | edbd6ee1c76ed53c24c711ca68d643c94ac97481 | /Algorithms/binary/268_Missing Number.py | 954f204785803a1de2690446d79ae59cd39b43e9 | [] | no_license | Linjiayu6/LeetCode | dd0ee7cff962fce7298227d9ce52ed6700fed98b | 2dea64cb7198bd7c71ba023d074b1036088d5632 | refs/heads/master | 2021-07-22T21:44:23.536275 | 2020-07-09T00:56:28 | 2020-07-09T00:56:28 | 194,610,005 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,472 | py |
# -*- coding: utf-8 -*
"""
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
i: [1,2]
o: 0
i: [1]
o: 0
"""
# exceed the time limit
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for i in range(0, len(nums) + 1):
# 这种匹配是没有哈希表快的
if i not in nums:
return i
return len(nums)
# 哈希表 dict和set 比 list查找速度要快很多
class Solution1(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# hash table
dictionary = set(nums)
for i in range(len(nums) + 1):
if i not in dictionary:
return i
return len(nums)
# 数学方法 该方法是最好的
class Solution3(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
return n * (n + 1) / 2 - sum(nums)
# print Solution3().missingNumber([0,1,2,3])
# 位运算 异或方法
"""
下标: 0,1,2
数字: 1,2,0
每一位累计异或
3^(0^1)^(1^2)^(2^0)
= (0^0)^(1^1)^(2^2)^3
= 3
"""
class Solution3(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
miss = len(nums)
for index, data in enumerate(nums):
miss = miss ^ index ^ data
return miss | [
"linjiayu@meituan.com"
] | linjiayu@meituan.com |
a4df40171c0718ad80625bd65a1955dc68217bff | c46f6015a2b9f7c6e5aec3d043f0b75057756852 | /scripts/create_initial_admin_user.py | 228fdaa760d9de5715af2b45428539b5623ed244 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | peerau/byceps | 6a7db0f8db00d8a77e824018d6efdbab57abbaaf | 1f691280f5c086179ce372a471a0f1d9952a86f5 | refs/heads/master | 2020-07-28T06:31:29.468607 | 2019-09-15T00:18:48 | 2019-09-15T00:18:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,874 | py | #!/usr/bin/env python
"""Create an initial user with admin privileges to begin BYCEPS setup.
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import click
from byceps.services.authorization import service as authorization_service
from byceps.services.user import command_service as user_command_service
from byceps.services.user import creation_service as user_creation_service
from byceps.util.system import get_config_filename_from_env_or_exit
from _util import app_context
@click.command()
@click.option('--screen_name', prompt=True)
@click.option('--email_address', prompt=True)
@click.option('--password', prompt=True, hide_input=True)
def execute(screen_name, email_address, password):
click.echo(f'Creating user "{screen_name}" ... ', nl=False)
user = _create_user(screen_name, email_address, password)
click.secho('done.', fg='green')
click.echo(f'Enabling user "{screen_name}" ... ', nl=False)
user_command_service.enable_user(user.id, user.id)
click.secho('done.', fg='green')
roles = _get_roles()
click.echo(f'Assigning {len(roles)} roles to user "{screen_name}" ... ',
nl=False)
_assign_roles_to_user(roles, user.id)
click.secho('done.', fg='green')
def _create_user(screen_name, email_address, password):
try:
return user_creation_service \
.create_basic_user(screen_name, email_address, password)
except ValueError as e:
raise click.UsageError(e)
def _get_roles():
return authorization_service.get_all_roles_with_titles()
def _assign_roles_to_user(roles, user_id):
for role in roles:
authorization_service.assign_role_to_user(role.id, user_id)
if __name__ == '__main__':
config_filename = get_config_filename_from_env_or_exit()
with app_context(config_filename):
execute()
| [
"homework@nwsnet.de"
] | homework@nwsnet.de |
0ea7d01fd4094a8bf1e86275477930c3ab0eda4f | 32c56293475f49c6dd1b0f1334756b5ad8763da9 | /google-cloud-sdk/lib/googlecloudsdk/command_lib/ml/translate/hooks.py | 34fbbf2dc37439bcabeac9f790eaad94761c8833 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | bopopescu/socialliteapp | b9041f17f8724ee86f2ecc6e2e45b8ff6a44b494 | 85bb264e273568b5a0408f733b403c56373e2508 | refs/heads/master | 2022-11-20T03:01:47.654498 | 2020-02-01T20:29:43 | 2020-02-01T20:29:43 | 282,403,750 | 0 | 0 | MIT | 2020-07-25T08:31:59 | 2020-07-25T08:31:59 | null | UTF-8 | Python | false | false | 6,520 | py | # -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Declarative hooks for ml speech."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import os
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base as calliope_base
from googlecloudsdk.core import exceptions
from googlecloudsdk.core import properties
from googlecloudsdk.core.util import files
SPEECH_API = 'translate'
def _GetApiVersion(args):
if args.calliope_command.ReleaseTrack() == calliope_base.ReleaseTrack.BETA:
return 'v3'
else:
return 'v3beta1'
class Error(exceptions.Error):
"""Exceptions for this module."""
class ContentFileError(Error):
"""Error if content file can't be read and isn't a GCS URL."""
def UpdateRequestLangDetection(unused_instance_ref, args, request):
"""The hook to inject content into the language detection request."""
content = args.content
content_file = args.content_file
messages = apis.GetMessagesModule(SPEECH_API, _GetApiVersion(args))
detect_language_request = messages.DetectLanguageRequest()
project = properties.VALUES.core.project.GetOrFail()
request.parent = 'projects/{}/locations/{}'.format(project, args.zone)
if args.IsSpecified('model'):
project = properties.VALUES.core.project.GetOrFail()
model = 'projects/{}/locations/{}/models/language-detection/{}'.format(
project, args.zone, args.model)
detect_language_request.model = model
if content_file:
if os.path.isfile(content_file):
detect_language_request.content = files.ReadFileContents(content_file)
else:
raise ContentFileError(
'Could not find --content-file [{}]. Content file must be a path '
'to a local file)'.format(content_file))
else:
detect_language_request.content = content
if args.IsSpecified('mime_type'):
detect_language_request.mimeType = args.mime_type
request.detectLanguageRequest = detect_language_request
return request
def UpdateRequestTranslateText(unused_instance_ref, args, request):
"""The hook to inject content into the translate request."""
content = args.content
content_file = args.content_file
messages = apis.GetMessagesModule(SPEECH_API, _GetApiVersion(args))
translate_text_request = messages.TranslateTextRequest()
project = properties.VALUES.core.project.GetOrFail()
request.parent = 'projects/{}/locations/{}'.format(project, args.zone)
if args.IsSpecified('model'):
project = properties.VALUES.core.project.GetOrFail()
model = 'projects/{}/locations/{}/models/{}'.format(
project, args.zone, args.model)
translate_text_request.model = model
if content_file:
if os.path.isfile(content_file):
translate_text_request.contents = [files.ReadFileContents(content_file)]
else:
raise ContentFileError(
'Could not find --content-file [{}]. Content file must be a path '
'to a local file)'.format(content_file))
else:
translate_text_request.contents = [content]
if args.IsSpecified('mime_type'):
translate_text_request.mimeType = args.mime_type
if args.IsSpecified('glossary_config'):
translate_text_request.glossaryConfig = \
messages.TranslateTextGlossaryConfig(glossary=args.glossaryConfig)
if args.IsSpecified('source_language'):
translate_text_request.sourceLanguageCode = args.source_language
translate_text_request.targetLanguageCode = args.target_language
request.translateTextRequest = translate_text_request
return request
def UpdateRequestGetSupportedLanguages(unused_instance_ref, args, request):
"""The hook to inject content into the getSupportedLanguages request."""
project = properties.VALUES.core.project.GetOrFail()
request.parent = 'projects/{}/locations/{}'.format(project, args.zone)
if args.IsSpecified('model'):
model = 'projects/{}/locations/{}/models/{}'.format(
project, args.zone, args.model)
request.model = model
return request
def UpdateRequestBatchTranslateText(unused_instance_ref, args, request):
"""The hook to inject content into the batch translate request."""
messages = apis.GetMessagesModule(SPEECH_API, _GetApiVersion(args))
batch_translate_text_request = messages.BatchTranslateTextRequest()
project = properties.VALUES.core.project.GetOrFail()
request.parent = 'projects/{}/locations/{}'.format(project, args.zone)
batch_translate_text_request.sourceLanguageCode = args.source_language
batch_translate_text_request.targetLanguageCodes = args.target_language_codes
batch_translate_text_request.outputConfig = messages.OutputConfig(
gcsDestination=messages.GcsDestination(outputUriPrefix=args.destination))
batch_translate_text_request.inputConfigs = \
[messages.InputConfig(gcsSource=messages.GcsSource(inputUri=k),
mimeType=v if v else None)
for k, v in sorted(args.source.items())]
if args.IsSpecified('models'):
batch_translate_text_request.models = \
messages.BatchTranslateTextRequest.ModelsValue(
additionalProperties=[
messages.BatchTranslateTextRequest.ModelsValue.AdditionalProperty(
key=k, value='projects/{}/locations/{}/models/{}'.format(
project, args.zone, v)) for k, v in sorted(args.models.items())
]
)
if args.IsSpecified('glossaries'):
additional_properties = \
[messages.BatchTranslateTextRequest.GlossariesValue.AdditionalProperty(
key=k, value=messages.TranslateTextGlossaryConfig(
glossary='projects/{}/locations/{}/glossaries/{}'.format(project, args.zone, v))) for k, v in sorted(args.glossaries.items())]
batch_translate_text_request.glossaries = \
messages.BatchTranslateTextRequest.GlossariesValue(
additionalProperties=additional_properties)
request.batchTranslateTextRequest = batch_translate_text_request
return request
| [
"jonathang132298@gmail.com"
] | jonathang132298@gmail.com |
51fdb88c14d2221f54fb2b293029612539b61752 | ced0efb0666b5817b9656cd533cf6f5db0085fe8 | /coding/codejam/apac/Aug/3.py | 2ca01808b5e807bc2132b1dfc20b4781743052a4 | [] | no_license | adithyaphilip/learning | 11fb6997ab3d613a358502dfff0ae9b91cd5ee27 | 64ecd3bc622077c7256df91cdf4dfbc8adf23068 | refs/heads/master | 2021-06-01T18:04:46.733092 | 2016-09-22T18:22:46 | 2016-09-22T18:22:46 | 68,949,350 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 259 | py | chunks_d = {}
def max_chunks(n, m):
if n not in chunks_d:
sum_c = (n ** 2) % m
for i in range(n - 2, 0, -1):
sum_c += (max_chunks(i, m) ** 2) % m
sum_c %= m
return chunks_d[n]
def main():
pass
main()
| [
"adithyaphilip@gmail.com"
] | adithyaphilip@gmail.com |
41af7f6a19d875d44349cb7afca4084535e46ebd | 1af49694004c6fbc31deada5618dae37255ce978 | /content/test/gpu/run_gpu_integration_test_fuchsia.py | 7e33505aa105b1e959de8d8e632e53300b81a4f0 | [
"BSD-3-Clause"
] | permissive | sadrulhc/chromium | 59682b173a00269ed036eee5ebfa317ba3a770cc | a4b950c23db47a0fdd63549cccf9ac8acd8e2c41 | refs/heads/master | 2023-02-02T07:59:20.295144 | 2020-12-01T21:32:32 | 2020-12-01T21:32:32 | 317,678,056 | 3 | 0 | BSD-3-Clause | 2020-12-01T21:56:26 | 2020-12-01T21:56:25 | null | UTF-8 | Python | false | false | 3,389 | py | #!/usr/bin/env vpython
# Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Wrapper for running gpu integration tests on Fuchsia devices."""
import argparse
import logging
import os
import shutil
import subprocess
import sys
import tempfile
from gpu_tests import path_util
sys.path.insert(0,
os.path.join(path_util.GetChromiumSrcDir(), 'build', 'fuchsia'))
from common_args import (AddCommonArgs, ConfigureLogging,
GetDeploymentTargetForArgs)
from symbolizer import RunSymbolizer
def main():
parser = argparse.ArgumentParser()
AddCommonArgs(parser)
args, gpu_test_args = parser.parse_known_args()
ConfigureLogging(args)
additional_target_args = {}
# If output_dir is not set, assume the script is being launched
# from the output directory.
if not args.out_dir:
args.out_dir = os.getcwd()
additional_target_args['out_dir'] = args.out_dir
# Create a temporary log file that Telemetry will look to use to build
# an artifact when tests fail.
temp_log_file = False
if not args.system_log_file:
args.system_log_file = os.path.join(tempfile.mkdtemp(), 'system-log')
temp_log_file = True
additional_target_args['system_log_file'] = args.system_log_file
package_names = ['web_engine_with_webui', 'web_engine_shell']
web_engine_dir = os.path.join(args.out_dir, 'gen', 'fuchsia', 'engine')
gpu_script = [
os.path.join(path_util.GetChromiumSrcDir(), 'content', 'test', 'gpu',
'run_gpu_integration_test.py')
]
# Pass all other arguments to the gpu integration tests.
gpu_script.extend(gpu_test_args)
try:
with GetDeploymentTargetForArgs(additional_target_args) as target:
target.Start()
fuchsia_device_address, fuchsia_ssh_port = target._GetEndpoint()
gpu_script.extend(['--chromium-output-directory', args.out_dir])
gpu_script.extend(['--fuchsia-device-address', fuchsia_device_address])
gpu_script.extend(['--fuchsia-ssh-config', target._GetSshConfigPath()])
if fuchsia_ssh_port:
gpu_script.extend(['--fuchsia-ssh-port', str(fuchsia_ssh_port)])
gpu_script.extend(['--fuchsia-system-log-file', args.system_log_file])
if args.verbose:
gpu_script.append('-v')
# Set up logging of WebEngine
listener = target.RunCommandPiped(['log_listener'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
build_ids_paths = map(
lambda package_name: os.path.join(
web_engine_dir, package_name, 'ids.txt'),
package_names)
RunSymbolizer(listener.stdout, open(args.system_log_file, 'w'),
build_ids_paths)
# Keep the Amber repository live while the test runs.
with target.GetAmberRepo():
# Install necessary packages on the device.
far_files = map(
lambda package_name: os.path.join(
web_engine_dir, package_name, package_name + '.far'),
package_names)
target.InstallPackage(far_files)
return subprocess.call(gpu_script)
finally:
if temp_log_file:
shutil.rmtree(os.path.dirname(args.system_log_file))
if __name__ == '__main__':
sys.exit(main())
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
93759af8f7a6ac24af30c0957f2296cf3c95c118 | 52b5773617a1b972a905de4d692540d26ff74926 | /.history/knapsack_20200708152715.py | 6b2ae69fdf511f9fa60dc4defa0e8ddffc9845b1 | [] | no_license | MaryanneNjeri/pythonModules | 56f54bf098ae58ea069bf33f11ae94fa8eedcabc | f4e56b1e4dda2349267af634a46f6b9df6686020 | refs/heads/master | 2022-12-16T02:59:19.896129 | 2020-09-11T12:05:22 | 2020-09-11T12:05:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 416 | py | def Knap(a,b,w):
# declare an empty dictionary
newArr = []
for i,j in zip(a,b):
smallArr = []
smallArr.append(i)
smallArr.append(j)
newArr.append(smallArr)
i = 0
# at position 0 is the weight and at position 1 is the value
# goal is to find highest value but not greater than
while i < len(newArr):
Knap([10,20,30],[60,100,120],220) | [
"mary.jereh@gmail.com"
] | mary.jereh@gmail.com |
6c810f9843558ebd9fdbcfb4f069f53ab3020afd | 44b2743ff70ce0631e9714ce78c44720fa63a9ad | /app/productdb/migrations/0012_auto_20160725_2252.py | f0305b66317e1a360acdb83ff2cb9af81c7a6a76 | [
"MIT"
] | permissive | hoelsner/product-database | 1b1b4db8e968f5bc149605093e4639c48a9ae1ad | c649569fb82bc4b0a5e9ef9615fff8a364ce652f | refs/heads/master | 2023-07-24T21:39:01.870692 | 2023-07-09T17:03:56 | 2023-07-09T17:03:56 | 43,767,455 | 43 | 27 | MIT | 2023-04-16T19:17:25 | 2015-10-06T17:44:50 | Python | UTF-8 | Python | false | false | 628 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-07-25 20:52
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('productdb', '0011_userprofile_regex_search'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
name='regex_search',
field=models.BooleanField(default=False, help_text='Use regular expression in any search field (fallback to simple search if no valid regular expression is used)', verbose_name='use regex search'),
),
]
| [
"henry@codingnetworker.com"
] | henry@codingnetworker.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.