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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
caedcb717831f3959e5cb1d6e58f728a5038387b
|
702ad30ea1de11f109a5207919bddb5381bd206e
|
/toy_data.py
|
c3921fdb841e6d73e0f8bc8a2f4009eb6fbe2202
|
[] |
no_license
|
glouppe/flowing-with-jax
|
84e2dfc1a81073328518ca95806f031fefe30287
|
f58b1772d08e235e71f10d4b28e2a39b771b17cf
|
refs/heads/master
| 2023-02-09T00:52:32.157418
| 2020-12-28T22:30:41
| 2020-12-28T22:30:41
| 323,332,121
| 17
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,601
|
py
|
# Source: https://raw.githubusercontent.com/rtqichen/ffjord/master/lib/toy_data.py
import numpy as np
import sklearn
import sklearn.datasets
from sklearn.utils import shuffle as util_shuffle
# Dataset iterator
def inf_train_gen(data, rng=None, batch_size=200):
if rng is None:
rng = np.random.RandomState()
if data == "swissroll":
data = sklearn.datasets.make_swiss_roll(n_samples=batch_size, noise=1.0)[0]
data = data.astype("float32")[:, [0, 2]]
data /= 5
return data
elif data == "circles":
data = sklearn.datasets.make_circles(n_samples=batch_size, factor=.5, noise=0.08)[0]
data = data.astype("float32")
data *= 3
return data
elif data == "rings":
n_samples4 = n_samples3 = n_samples2 = batch_size // 4
n_samples1 = batch_size - n_samples4 - n_samples3 - n_samples2
# so as not to have the first point = last point, we set endpoint=False
linspace4 = np.linspace(0, 2 * np.pi, n_samples4, endpoint=False)
linspace3 = np.linspace(0, 2 * np.pi, n_samples3, endpoint=False)
linspace2 = np.linspace(0, 2 * np.pi, n_samples2, endpoint=False)
linspace1 = np.linspace(0, 2 * np.pi, n_samples1, endpoint=False)
circ4_x = np.cos(linspace4)
circ4_y = np.sin(linspace4)
circ3_x = np.cos(linspace4) * 0.75
circ3_y = np.sin(linspace3) * 0.75
circ2_x = np.cos(linspace2) * 0.5
circ2_y = np.sin(linspace2) * 0.5
circ1_x = np.cos(linspace1) * 0.25
circ1_y = np.sin(linspace1) * 0.25
X = np.vstack([
np.hstack([circ4_x, circ3_x, circ2_x, circ1_x]),
np.hstack([circ4_y, circ3_y, circ2_y, circ1_y])
]).T * 3.0
X = util_shuffle(X, random_state=rng)
# Add noise
X = X + rng.normal(scale=0.08, size=X.shape)
return X.astype("float32")
elif data == "moons":
data = sklearn.datasets.make_moons(n_samples=batch_size, noise=0.1)[0]
data = data.astype("float32")
data = data * 2 + np.array([-1, -0.2])
return data
elif data == "8gaussians":
scale = 4.
centers = [(1, 0), (-1, 0), (0, 1), (0, -1), (1. / np.sqrt(2), 1. / np.sqrt(2)),
(1. / np.sqrt(2), -1. / np.sqrt(2)), (-1. / np.sqrt(2),
1. / np.sqrt(2)), (-1. / np.sqrt(2), -1. / np.sqrt(2))]
centers = [(scale * x, scale * y) for x, y in centers]
dataset = []
for i in range(batch_size):
point = rng.randn(2) * 0.5
idx = rng.randint(8)
center = centers[idx]
point[0] += center[0]
point[1] += center[1]
dataset.append(point)
dataset = np.array(dataset, dtype="float32")
dataset /= 1.414
return dataset
elif data == "pinwheel":
radial_std = 0.3
tangential_std = 0.1
num_classes = 5
num_per_class = batch_size // 5
rate = 0.25
rads = np.linspace(0, 2 * np.pi, num_classes, endpoint=False)
features = rng.randn(num_classes*num_per_class, 2) \
* np.array([radial_std, tangential_std])
features[:, 0] += 1.
labels = np.repeat(np.arange(num_classes), num_per_class)
angles = rads[labels] + rate * np.exp(features[:, 0])
rotations = np.stack([np.cos(angles), -np.sin(angles), np.sin(angles), np.cos(angles)])
rotations = np.reshape(rotations.T, (-1, 2, 2))
return 2 * rng.permutation(np.einsum("ti,tij->tj", features, rotations))
elif data == "2spirals":
n = np.sqrt(np.random.rand(batch_size // 2, 1)) * 540 * (2 * np.pi) / 360
d1x = -np.cos(n) * n + np.random.rand(batch_size // 2, 1) * 0.5
d1y = np.sin(n) * n + np.random.rand(batch_size // 2, 1) * 0.5
x = np.vstack((np.hstack((d1x, d1y)), np.hstack((-d1x, -d1y)))) / 3
x += np.random.randn(*x.shape) * 0.1
return x
elif data == "checkerboard":
x1 = np.random.rand(batch_size) * 4 - 2
x2_ = np.random.rand(batch_size) - np.random.randint(0, 2, batch_size) * 2
x2 = x2_ + (np.floor(x1) % 2)
return np.concatenate([x1[:, None], x2[:, None]], 1) * 2
elif data == "line":
x = rng.rand(batch_size) * 5 - 2.5
y = x
return np.stack((x, y), 1)
elif data == "cos":
x = rng.rand(batch_size) * 5 - 2.5
y = np.sin(x) * 2.5
return np.stack((x, y), 1)
else:
return inf_train_gen("8gaussians", rng, batch_size)
|
[
"g.louppe@gmail.com"
] |
g.louppe@gmail.com
|
379c1fa52e66c607912bbf3aec01ca28e4d2b81b
|
377dc973a58d30154cf485de141223d7ca5424dd
|
/havok_classes/hclStorageSetupMeshSectionSectionEdgeSelectionChannel.py
|
2a0b1f269d753d07efa1c18f0755cf5070e00a60
|
[
"MIT"
] |
permissive
|
sawich/havok-reflection
|
d6a5552f2881bb4070ad824fb7180ad296edf4c4
|
1d5b768fb533b3eb36fc9e42793088abeffbad59
|
refs/heads/master
| 2021-10-11T12:56:44.506674
| 2019-01-25T22:37:31
| 2019-01-25T22:37:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 530
|
py
|
from .hkReferencedObject import hkReferencedObject
from typing import List
from .common import get_array
class hclStorageSetupMeshSectionSectionEdgeSelectionChannel(hkReferencedObject):
edgeIndices: List[int]
def __init__(self, infile):
self.edgeIndices = get_array(infile, int, 4) # TYPE_ARRAY:TYPE_UINT32
def __repr__(self):
return "<{class_name} edgeIndices=[{edgeIndices}]>".format(**{
"class_name": self.__class__.__name__,
"edgeIndices": self.edgeIndices,
})
|
[
"kevin@turtlerockweb.com"
] |
kevin@turtlerockweb.com
|
eff804ac1d48782d19505cda1ee199107169edf8
|
354b26a5d854bd044286047d4aef1a0aa54961f1
|
/lock.py
|
1bddd56489c297a1cedc7b6e3ede027691018df2
|
[
"MIT"
] |
permissive
|
liondani/pytshares
|
3796ca8705de409825ef8631604f49319887b510
|
45458a026a23c53ad2bacd56abb9e930e8268bb4
|
refs/heads/master
| 2020-12-31T01:36:56.896329
| 2014-12-14T00:08:22
| 2014-12-14T00:08:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 193
|
py
|
#!/usr/bin/python
from btsrpcapi import *
import config
if __name__ == "__main__":
rpc = btsrpcapi(config.url, config.user, config.passwd)
print rpc.walletopen("delegate")
print rpc.lock()
|
[
"mail@xeroc.org"
] |
mail@xeroc.org
|
67a21a65d9789ec1615b82c1d99d08c87c6c9089
|
da1f49aa0ee3cbbd0b7add4a8ee4210c50fc81b7
|
/demo/funs/passing_by_value_ref.py
|
37a1dea123297fec3d8947fe4dabb9f97c94cefb
|
[] |
no_license
|
srikanthpragada/PYTHON_30_AUG_2021
|
a1cde290072e152440dcd07dce377154a9e3052e
|
f84f272718b483fbf67ca8f950e6e4f933307e63
|
refs/heads/master
| 2023-08-25T14:11:12.826321
| 2021-10-11T14:14:36
| 2021-10-11T14:14:36
| 402,412,522
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 252
|
py
|
# Pass an immutable object by reference
def increment(v):
print(id(v))
v += 1
print(id(v))
print(v)
def prepend(lst, value):
lst.insert(0, value)
a = 100
print(id(a))
increment(a)
print(a)
l = [1, 2, 3]
prepend(l, 10)
print(l)
|
[
"srikanthpragada@gmail.com"
] |
srikanthpragada@gmail.com
|
63af416133ae408431705293a3634711f5cf8416
|
7bcc7f36743694a2b0a8aa1b496ceca1371b130e
|
/rltools/rltools/distributions.py
|
8759f25a04a5caad0764865ddf21a86f17d5cb22
|
[] |
no_license
|
parachutel/MADRL
|
7cfa32ab0e9a6bee2b6e31434a8e2835b9e9265d
|
f03b8009ede6d3324f6e2091dcfa3911b5968fe0
|
refs/heads/master
| 2020-04-25T07:23:21.004116
| 2019-10-09T21:21:16
| 2019-10-09T21:21:16
| 172,612,159
| 0
| 1
| null | 2019-02-26T01:10:00
| 2019-02-26T01:10:00
| null |
UTF-8
|
Python
| false
| false
| 5,032
|
py
|
import numpy as np
import tensorflow as tf
from rltools import tfutil
from rltools import util
TINY = 1e-10
class Distribution(object):
@property
def dim(self):
raise NotImplementedError()
def kl(self, old, new):
raise NotImplementedError()
def log_density(self, dist_params, x):
raise NotImplementedError()
def entropy(self, logprobs_N_K):
raise NotImplementedError()
def sample(self, logprobs_N_K):
raise NotImplementedError()
def kl_expr(self, logprobs1, logprobs2):
raise NotImplementedError()
def log_density_expr(self, dist_params, x):
raise NotImplementedError()
class Categorical(Distribution):
def __init__(self, dim):
self._dim = dim
@property
def dim(self):
return self._dim
def log_density(self, dist_params_B_A, x_B_A):
return util.lookup_last_idx(dist_params_B_A, x_B_A)
def entropy(self, probs_N_K):
tmp = -probs_N_K * np.log(probs_N_K + TINY)
tmp[~np.isfinite(tmp)] = 0
return tmp.sum(axis=1)
def sample(self, probs_N_K):
"""Sample from N categorical distributions, each over K outcomes"""
N, K = probs_N_K.shape
return np.array([np.random.choice(K, p=probs_N_K[i, :]) for i in range(N)])
def kl_expr(self, logprobs1_B_A, logprobs2_B_A, name=None):
"""KL divergence between categorical distributions, specified as log probabilities"""
with tf.op_scope([logprobs1_B_A, logprobs2_B_A], name, 'categorical_kl') as scope:
kl_B = tf.reduce_sum(
tf.exp(logprobs1_B_A) * (logprobs1_B_A - logprobs2_B_A), 1, name=scope)
return kl_B
def log_density_expr(self, dist_params_B_A, x_B_A):
"""Log density from categorical distribution params"""
return tfutil.lookup_last_idx(dist_params_B_A, x_B_A)
class RecurrentCategorical(Distribution):
def __init__(self, dim):
self._dim = dim
self._cat = Categorical(dim)
@property
def dim(self):
return self._dim
def log_density(self, dist_params_B_H_A, x_B_H_A):
adim = dist_params_B_H_A.shape[-1]
flat_logd = self._cat.log_density(
dist_params_B_H_A.reshape((-1, adim)), x_B_H_A.reshape((-1, adim)))
return flat_logd.reshape(dist_params_B_H_A.shape)
def entropy(self, probs_N_H_K):
tmp = -probs_N_H_K * np.log(probs_N_H_K + TINY)
tmp[~np.isfinite(tmp)] = 0
return tmp.sum(axis=-1)
def sample(self, probs_N_K):
"""Sample from N categorical distributions, each over K outcomes"""
return self._cat.sample(probs_N_K)
def kl_expr(self, logprobs1_B_H_A, logprobs2_B_H_A, name=None):
"""KL divergence between categorical distributions, specified as log probabilities"""
with tf.op_scope([logprobs1_B_H_A, logprobs2_B_H_A], name, 'categorical_kl') as scope:
kl_B_H = tf.reduce_sum(
tf.exp(logprobs1_B_H_A) * (logprobs1_B_H_A - logprobs2_B_H_A), 2, name=scope)
return kl_B_H
def log_density_expr(self, dist_params_B_H_A, x_B_H_A):
adim = tf.shape(dist_params_B_H_A)[len(dist_params_B_H_A.get_shape()) - 1]
flat_logd = self._cat.log_density_expr(
tf.reshape(dist_params_B_H_A, tf.pack([-1, adim])),
tf.reshape(x_B_H_A, tf.pack([-1, adim])))
return tf.reshape(flat_logd, tf.shape(dist_params_B_H_A)[:2])
class Gaussian(Distribution):
def __init__(self, dim):
self._dim = dim
@property
def dim(self):
return self._dim
def entropy(self, stdevs):
d = stdevs.shape[-1]
return .5 * d * (1. + np.log(2. * np.pi)) + np.log(stdevs).sum(axis=-1)
def kl_expr(self, means1_stdevs1, means2_stdevs2, name=None):
"""KL divergence wbw diagonal covariant gaussians"""
means1, stdevs1 = means1_stdevs1
means2, stdevs2 = means2_stdevs2
with tf.op_scope([means1, stdevs1, means2, stdevs2], name, 'gaussian_kl') as scope:
D = tf.shape(means1)[len(means1.get_shape()) - 1]
kl = tf.mul(.5, (tf.reduce_sum(tf.square(stdevs1 / stdevs2), -1) + tf.reduce_sum(
tf.square((means2 - means1) / stdevs2), -1) + 2. * (tf.reduce_sum(
tf.log(stdevs2), -1) - tf.reduce_sum(tf.log(stdevs1), -1)) - tf.to_float(D)),
name=scope)
return kl
def log_density_expr(self, means, stdevs, x, name=None):
"""Log density of diagonal gauss"""
with tf.op_scope([means, stdevs, x], name, 'gauss_log_density') as scope:
D = tf.shape(means)[len(means.get_shape()) - 1]
lognormconsts = -.5 * tf.to_float(D) * np.log(2. * np.pi) + 2. * tf.reduce_sum(
tf.log(stdevs), -1) # log norm consts
logprobs = tf.add(-.5 * tf.reduce_sum(tf.square((x - means) / stdevs), -1),
lognormconsts, name=scope)
return logprobs
RecurrentGaussian = Gaussian
|
[
"lisheng@stanford.edu"
] |
lisheng@stanford.edu
|
be1820b5330c658d7e0361946656285991cd853c
|
7a4f61d55378fec4df952bd574cb1db57e795084
|
/analyze/simulation/Trader.py
|
273c29a7e0b47bf9d142acc039fb3a9db5d5fd64
|
[] |
no_license
|
569593913/enoch
|
9da83638b99aa6e6a649914e01bef3abdc236895
|
8c8c7ff5a527a5287894b6522fe4e87974cc5e01
|
refs/heads/master
| 2021-05-05T15:48:45.931858
| 2019-03-03T12:07:47
| 2019-03-03T12:07:47
| 117,324,651
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,497
|
py
|
# -*- coding: utf-8 -*-
from .HoldStock import *
from .TradeRecord import *
import threading
from datetime import *
class Trader:
"""
模拟交易者
attribute:
original 初始资金
cash 当前资金
own 当前拥有的股票,map类,key为股票代码,value为HoldStock list
record 交易记录
taxRate 税率
earningsLine 收益曲线,list类型,值为[时间,当开收益]
"""
def __init__(self, original=1000000):
"""
:param original:初始资金
"""
self.original = original
self.cash = original
self.own = {}
self.record = []
self.earningsLine = []
self.taxRate = 0.002
self.lock = threading.Lock()
def buy(self, code, buyTime, buyPrice, buyAmount=None,condition=None):
"""
买一只股票
:param code: 股票代码
:param buyTime: 购买时间,long型
:param buyPrice: 购买价格
:param buyAmount: 购买金额
:return:
"""
with self.lock:
if buyPrice <= 0:
print("buyPrice=0 return")
return
#获取可买的金额
if buyAmount == None or buyAmount > self.cash:
buyAmount = self.cash
#税后可买金额
afterTaxAmount = 0
tax = 0
if buyAmount*(1+self.taxRate) < self.cash:
afterTaxAmount = buyAmount
tax = buyAmount*self.taxRate
else:
tax = self.cash * self.taxRate
afterTaxAmount = self.cash - tax
#可买到的数量
canBuyQuantity = afterTaxAmount / buyPrice
if canBuyQuantity < 100:
# print('buy code:%s quantity:%s less 100,price:%s,cash:%s,original:%s,isHold:%s' \
# % (code,quantity,buyPrice,self.cash,self.original,self.isHold(code)))
return
holdStock = HoldStock(code, buyTime, buyPrice, buyPrice, canBuyQuantity)
if code not in self.own:
self.own[code] = []
self.own[code].append(holdStock)
tradeRecord = TradeRecord(code, buyTime, "buy", buyPrice, canBuyQuantity,condition)
self.record.append(tradeRecord)
self.cash -= (afterTaxAmount+tax)
def isHold(self, code):
if (code not in self.own) or (len(self.own[code]) < 1):
return False
return True
def sell(self, code, sellTime, sellPrice, quantity=None,condition=None):
"""
卖一只股票
:param code: 股票代码
:param sellTime: 卖出时间,long型
:param sellPrice: 卖出价格
:param quantity: 卖出数量
:return:
"""
with self.lock:
if self.isHold(code) == False:
# print("%s 没有持有,不可卖!" % code)
return
if sellPrice <= 0:
print('price:%s' % sellPrice)
return
if None == quantity:
quantity = 0
for hs in self.own[code]:
quantity += hs.quantity
if quantity < 100:
print('sell quantity:% less 100' % quantity)
return
# 获取可卖出的数量
actualSellQuantity = 0
holdStocks = []
for hs in self.own[code]: # list顺序保证先买先卖
if quantity > 0:
if (sellTime - hs.buyTime) > 1000: # 超过一天才能卖,只有天粒度的数据才能这么简单计算
if hs.quantity >= quantity:
actualSellQuantity += quantity
hs.quantity -= quantity
quantity = 0
else:
actualSellQuantity += hs.quantity
quantity -= hs.quantity
hs.quantity = 0
if hs.quantity != 0: # quantity为0的清理掉
holdStocks.append(hs)
self.own[code] = holdStocks
self.cash += sellPrice * actualSellQuantity
tradeRecord = TradeRecord(code, sellTime, "sell", sellPrice, actualSellQuantity,condition)
self.record.append(tradeRecord)
def asset(self):
"""
获取当前的资产
:return:
"""
with self.lock:
asset = self.cash
for hsl in self.own.values():
for hs in hsl:
asset += hs.capitalisation()
return asset
def earnings(self):
"""
当前收益
:return:
"""
return (self.asset() - self.original) / self.original
def fresh(self,date, dic):
"""
刷新股票的价格
:param dic: 股票代码:价格
:return:
"""
with self.lock:
for code, price in dic.items():
for hs in self.own.get(code, []):
hs.currentPice = price
self.earningsLine.append([date,self.earnings()])
def __repr__(self):
return "Trader{earnings=%s,asset=%s,\noriginal=%s,\ncash=%s,\nown=%s,\nrecord=%s,\nearningsLine=%s}" % \
(self.earnings(), self.asset(), self.original, self.cash, self.own, self.record,self.earnings())
|
[
"gogs@fake.local"
] |
gogs@fake.local
|
f957d70afd2e84447f77b11cfb6357e00c3b3251
|
09cd370cdae12eb45090033a00e9aae45ee26638
|
/BOJ/[S1]2110 공유기 설치.py
|
f30a43696c21b9a44ec824111b7989ae7af87ed9
|
[] |
no_license
|
KWONILCHEOL/Python
|
ee340f6328945651eb29d2b23c425a92c84a4adb
|
1ea5f5f74894a5929e0e894c5c12f049b8eb9fb4
|
refs/heads/main
| 2023-04-11T09:36:54.874638
| 2021-04-24T04:29:12
| 2021-04-24T04:29:12
| 328,658,511
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 666
|
py
|
# [S1]2110 공유기 설치
# https://www.acmicpc.net/problem/2110
# 파라메트릭 서치, 이진탐색
def check(k):
value = arr[0]
cnt = 1
for i in range(1,n):
if arr[i] >= value + k:
value = arr[i]
cnt += 1
if cnt == c:
return True
return False
import sys
input = sys.stdin.readline
n,c = list(map(int, input().split()))
arr = []
for _ in range(n):
arr.append(int(input()))
arr.sort()
lo = 1 #최소 gap
hi = arr[-1] - arr[0] #최대 gap
result = 0
while lo + 1 < hi: #O(logN)
mid = (lo + hi) // 2
if check(mid) == False:
hi = mid
else:
lo = mid
result = mid
value = arr[0]
cnt = 1
print(lo)
|
[
"kwon6460@gmail.com"
] |
kwon6460@gmail.com
|
bf376078d8387fe06b0ee8b09d2774dda4c6d84a
|
78c4f0d5cfcdcec678ff78e259b64550692120fa
|
/ormar/models/__init__.py
|
eb6bdd7c5c5224e69246a5b734a225109dc2cd42
|
[
"MIT"
] |
permissive
|
dudil/ormar
|
3c31d592f6a23cacff2ac0e3a6163f4778ab286f
|
7c0f8e976a651c40dbc669f1caba1361f0af2ead
|
refs/heads/master
| 2023-07-07T22:26:20.165473
| 2021-03-05T11:37:28
| 2021-03-05T11:37:28
| 344,250,603
| 0
| 0
|
MIT
| 2021-09-07T03:44:08
| 2021-03-03T20:08:35
|
Python
|
UTF-8
|
Python
| false
| false
| 555
|
py
|
"""
Definition of Model, it's parents NewBaseModel and mixins used by models.
Also defines a Metaclass that handles all constructions and relations registration,
ass well as vast number of helper functions for pydantic, sqlalchemy and relations.
"""
from ormar.models.newbasemodel import NewBaseModel # noqa I100
from ormar.models.model_row import ModelRow # noqa I100
from ormar.models.model import Model # noqa I100
from ormar.models.excludable import ExcludableItems # noqa I100
__all__ = ["NewBaseModel", "Model", "ModelRow", "ExcludableItems"]
|
[
"collerek@gmail.com"
] |
collerek@gmail.com
|
f459e40a8809ff26b3ca6c6860a1ad7d2bc37866
|
eb2ebaf1c53cfeb5a1abbc05e6423c5fdc27ca8a
|
/.history/game_functions_20200129213418.py
|
3fdbdaa6f774bd7226f7e217a22bd777294d0e99
|
[] |
no_license
|
HeperW/VSCO
|
8120bde36c73601e5b956955c0b68b599c9a663d
|
4c3ee4aa45424313e335ff05934fbb6df7950304
|
refs/heads/master
| 2022-05-08T00:51:44.618385
| 2022-03-16T03:18:34
| 2022-03-16T03:18:34
| 233,367,724
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 429
|
py
|
import sys
import pygame
def check_events():
"""响应按键与鼠标事件"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
def update_screen(ai_settings,screen,ship):
"""更新屏幕上的图像,并切换到新屏幕"""
#每次循环时都重绘屏幕
screen.fill(ai_settings,bg_color)
ship.blitme()
#让最近绘制的屏幕可见
pygame.dis
|
[
"hgym300400@126.com"
] |
hgym300400@126.com
|
3d5b02ff98f9c65ed8a040f582968c14c0bc5442
|
53fa34a5ecfbeea84c960afc3ba088c3a7a41587
|
/subunit2sql/migrations/versions/10a2b6d4b06e_add_even_more_indexes.py
|
76c52efc0511d66674a0a73f6f3796157a16d32f
|
[
"Apache-2.0"
] |
permissive
|
mguiney/subunit2sql
|
dd7259110363416c7892fdab63e2391884a5179b
|
6f95e43478ba91027e07af0d9c7e1305f0829c2e
|
refs/heads/master
| 2021-09-06T23:09:21.095681
| 2018-02-07T19:42:46
| 2018-02-07T19:42:46
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,503
|
py
|
# Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
#
# 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.
"""Add even more indexes
Revision ID: 10a2b6d4b06e
Revises: 35cd45895e56
Create Date: 2015-12-01 18:19:11.328298
"""
# revision identifiers, used by Alembic.
revision = '10a2b6d4b06e'
down_revision = '35cd45895e56'
from alembic import op
def upgrade():
with op.batch_alter_table('run_metadata') as batch_op:
batch_op.create_unique_constraint('uq_run_metadata',
['run_id', 'key', 'value'])
with op.batch_alter_table('test_metadata') as batch_op:
batch_op.create_unique_constraint('uq_test_metadata',
['test_id', 'key', 'value'])
with op.batch_alter_table('test_run_metadata') as batch_op:
batch_op.create_unique_constraint('uq_test_run_metadata',
['test_run_id', 'key', 'value'])
def downgrade():
NotImplementedError()
|
[
"mtreinish@kortar.org"
] |
mtreinish@kortar.org
|
61ef95b1f797f2f0ce56bf7014743057452773e3
|
6e601105760f09d3c9f5306e18e4cf085f0bb4a2
|
/10000-99999/10875.py
|
2f6f2663592474c300ad791f26143b1e12197241
|
[] |
no_license
|
WSJI0/BOJ
|
6412f69fddd46c4bcc96377e2b6e013f3bb1b524
|
160d8c13f72d7da835d938686f433e7b245be682
|
refs/heads/master
| 2023-07-06T15:35:50.815021
| 2023-07-04T01:39:48
| 2023-07-04T01:39:48
| 199,650,520
| 2
| 0
| null | 2020-04-20T09:03:03
| 2019-07-30T12:48:37
|
Python
|
UTF-8
|
Python
| false
| false
| 633
|
py
|
'''
10875번
뱀
미완성
'''
import sys
input=sys.stdin.readline
l=int(input())
n=int(input())
a=[]
for _ in range(n):
a.append(list(input().rstrip().split()))
visited=[]
now=[0, 0]
d='r'
change={
'r':['u', 'd'],
'd':['r', 'l'],
'l':['d', 'u'],
'u':['l', 'r']
}
ans=0
for i in range(n):
if d=='r':
if now[0]+a[i][0]<=l:
col=-1
for j in range(len(visited)):
if
else:
ans+=l-(now[0]+a[i][0])
break
visited.append([now[0], now[1], now[0]+a[i][0], now[1]])
if a[i][1]=='L': d=change[d][0]
else: d=change[d][1]
|
[
"lifedev@naver.com"
] |
lifedev@naver.com
|
de60657dc3cdcffb3495e5a43f9c653e3ec535ad
|
81d7c62c357c086a8990105d4179c9a2cda0f89c
|
/Requests_module_old_project_cDVR_reference/aurora_cdvr_sanity_tests/scripts/sanity_scripts/sanity_dataplane_MOSrecorder.py
|
b8be0ae710863f822af8a34ae23dcbfa6aa0c8e1
|
[] |
no_license
|
JAGASABARIVEL/Python_reference
|
57f49a3f8d894f02f8003657a914395f4b55d844
|
f2438289f189fc364dbe9dff0421c3df9be366b2
|
refs/heads/master
| 2020-04-08T19:23:23.406783
| 2018-11-29T12:25:43
| 2018-11-29T12:25:43
| 159,653,055
| 0
| 1
| null | 2020-01-25T19:07:42
| 2018-11-29T11:06:42
|
Python
|
UTF-8
|
Python
| false
| false
| 3,606
|
py
|
#!/usr/bin/python
import os
import sys
import time
import requests
import json
import ast
import mypaths
from readYamlConfig import readYAMLConfigs
from L1commonFunctions import *
from L2commonFunctions import *
##########################################################################
# Get MOS recorder
##########################################################################
def doit(cfg,printflg=False):
disable_warning() #Method Called to suppress all warnings
# announce
abspath = os.path.abspath(__file__)
scriptName = os.path.basename(__file__)
(test, ext) = os.path.splitext(scriptName)
name = (__file__.split('/'))[-1]
I = 'Core DVR Functionality' #rally initiatives
US = ' Get MOS recorder'
TIMS_testlog = []
TIMS_testlog = [name,I,US]
print "Starting test " + test
recording_api = cfg['recording_api']
if recording_api != 'mos':
TIMS_testlog.append(2)
msg = 'Testcase warning :Test bypassed since for MOS'
print msg
TIMS_testlog.append(msg)
return TIMS_testlog
# set values based on config
hosts = get_hosts_by_config_type(cfg,'rm',printflg)
print hosts
if hosts == None:
msg = 'Testcase failed :unable to get the host ip'
print msg
TIMS_testlog.append(1)
TIMS_testlog.append(msg)
return TIMS_testlog
protocol = cfg['protocol']
throttle_milliseconds = cfg['sanity']['throttle_milliseconds']
if throttle_milliseconds < 1:
throttle_milliseconds = 25
headers = {
'Content-Type': 'application/json; charset=utf-8',
}
timeout=5
any_host_pass = 0
for index, host in enumerate(hosts):
if index > 1:
time.sleep(throttle_milliseconds / 1000.0 )
url = protocol +"://" + host + "/emdata/MosRecorder"
print "Get MOS recorder via ", url
r = sendURL("get",url,timeout,headers)
if r is not None :
if ( r.status_code != 200):
print "Problem accessing: " + url
print r.status_code
print r.headers
print r.content
msg= 'Testcase failed :Problem accessing url'
print msg
TIMS_testlog.append(1)
TIMS_testlog.append(msg)
return TIMS_testlog
else:
if r.content is None :
print "\n" + "#"*20 + " DEBUG STARTED "+ "#"*20+ "\n"
print "Get MOS recorder \n" + json.dumps(json.loads(r.content),indent = 4, sort_keys=False)
print "\n" + "#"*20 + " DEBUG ENDED "+ "#"*20+ "\n"
any_host_pass = any_host_pass + 1
printLog("Get MOS recorder \n" + json.dumps(json.loads(r.content),indent = 4, sort_keys=False),printflg)
if any_host_pass:
msg = 'Testcase passed :MOS recorder is successfully retrieved'
print msg
TIMS_testlog.append(0)
TIMS_testlog.append(msg)
return TIMS_testlog
else:
msg = 'Testcase failed :MOS recorder is not successfully retrieved '
print msg
TIMS_testlog.append(1)
TIMS_testlog.append(msg)
return TIMS_testlog
if __name__ == '__main__':
scriptName = os.path.basename(__file__)
#read config file
sa = sys.argv
cfg = relative_config_file(sa,scriptName)
if cfg['sanity']['print_cfg']:
print "\nThe following configuration is being used:\n"
pprint(cfg)
print
L = doit(cfg, True)
exit(L[3] )
|
[
"jkarunan@cisco.com"
] |
jkarunan@cisco.com
|
907c9f9d2b9bd1d9a072348f7dbe58b4a396c314
|
877bd6d9f9f38320a82f46d6c581d6099f77597b
|
/dev/installers/windows/substitute_version.py
|
b93fc7dafa563a3d23215c2ebe705f6cdd978140
|
[
"BSD-3-Clause",
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
caltechlibrary/holdit
|
04b7563722e6883ffe135398401e35da35b0af73
|
474165764e3514303dfd118d1beb0b6570fb6e13
|
refs/heads/main
| 2021-06-01T17:06:24.569179
| 2020-12-04T20:39:45
| 2020-12-04T20:39:45
| 141,499,163
| 2
| 0
|
NOASSERTION
| 2020-07-28T00:18:25
| 2018-07-18T23:13:58
|
Python
|
UTF-8
|
Python
| false
| false
| 1,097
|
py
|
# =============================================================================
# @file substitute_version.py
# @brief Replace version string in holdit_innosetup_script.iss.in
# @author Michael Hucka <mhucka@caltech.edu>
# @license Please see the file named LICENSE in the project directory
# @website https://github.com/caltechlibrary/holdit
# =============================================================================
import os
from os import path
this_version = 0
here = path.abspath(path.dirname(__file__))
with open(path.join(here, '../../../holdit/__version__.py')) as f:
lines = f.read().rstrip().splitlines()
for line in [x for x in lines if x.startswith('__') and '=' in x]:
setting = line.split('=')
name = setting[0].strip()
if name == '__version__':
this_version = setting[1].strip().replace("'", '')
with open(path.join(here, 'holdit_innosetup_script.iss.in')) as infile:
with open(path.join(here, 'holdit_innosetup_script.iss'), 'w') as outfile:
outfile.write(infile.read().replace('@@VERSION@@', this_version))
|
[
"mhucka@caltech.edu"
] |
mhucka@caltech.edu
|
532e42534f668fbcfe7009eba86ba479f485e7fc
|
54937a50e74ad209f648f69b4a4509113d90b016
|
/unsubscribe/views.py
|
d96d3bcc0ba01c063caa2d37ec5e26c29e6f0e08
|
[
"MIT"
] |
permissive
|
MHM5000/mechanical-mooc
|
0a728ab45659075f6cf28bd3cafb72ac9abff259
|
a0faa6d06f4cb157e4b92cc35d6d148e53096a41
|
refs/heads/master
| 2021-01-17T15:16:37.531668
| 2013-11-15T19:56:41
| 2013-11-15T19:56:41
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 789
|
py
|
from django import http
from django.views.decorators.csrf import csrf_exempt
from mailgun import utils
import models as unsubscribe_model
import logging
log = logging.getLogger(__name__)
@csrf_exempt
def unsubscribe_webhook(request):
verified = utils.verify_webhook(
request.POST.get('token'),
request.POST.get('timestamp'),
request.POST.get('signature')
)
if not verified:
return http.HttpResponseForbidden()
address = request.POST.get('recipient')
try:
if request.POST.get('mailing-list'):
unsubscribe_model.unsubscribe_from_sequence(address)
else:
unsubscribe_model.unsubscribe_user(address)
except:
log.error(u'Could not unsubscribe {0}')
return http.HttpResponse('')
|
[
"dirkcuys@gmail.com"
] |
dirkcuys@gmail.com
|
e145bb17d89f0c7fbcba3dcc46cf5bdd6350a7af
|
3fcd2c184abaa9bef5f4a916fbf0e9587da06346
|
/ByTags/Two_pointers/N_Sum/Two_Sum.py
|
5e3fdf31bf183199ab56e2d7f281fb29c83cf6ef
|
[] |
no_license
|
chinitacode/Python_Learning
|
865ff42722e256776ae91d744b779fa476e23f45
|
49aa02367e3097aca107b70dab43b5f60a67ef9f
|
refs/heads/master
| 2020-06-29T01:05:39.331297
| 2020-03-21T14:29:51
| 2020-03-21T14:29:51
| 200,393,997
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,263
|
py
|
'''
1. 两数之和 [简单]
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,
并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
[Method 1] 字典(空间换时间)
[Time]: O(N)
[Space]: O(N)
'''
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
visited = {}
for i, num in enumerate(nums):
if target-num in visited:
return [visited[target-num], i]
visited[num] = i
return []
'''
[Method 2]: Two-Pointer
双指针用法只能用于数组是排好序的或者数组未排序但是只要求返回和为target的数值而非索引,
因为排好序后索引就乱了,就算是先用一个字典记录其value:index,遇到有duplicates的情况,
字典中的同一个value只会记录下它最新的index,当2nums = target的时候就会出错。
'''
# 如果只要求返回满足和为target的两个num:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
nums.sort()
if not nums or nums [0] > target: return []
i, j = 0, len(nums)-1
while nums[j] > target:
j -= 1
while i < j:
if nums[i] + nums[j] == target:
return [nums[i], nums[j]]
elif nums[i] + nums[j] < target:
i += 1
else:
j -= 1
return []
# 如果要求返回索引,数组未排序但是无duplicates:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = {num:i for i, num in enumerate(nums)}
nums.sort()
if not nums or nums [0] > target: return []
i, j = 0, len(nums)-1
while nums[j] > target:
j -= 1
while i < j:
if nums[i] + nums[j] == target:
return [dic[nums[i]], dic[nums[j]]]
elif nums[i] + nums[j] < target:
i += 1
else:
j -= 1
return []
|
[
"ziyu_zhou_victoria@163.com"
] |
ziyu_zhou_victoria@163.com
|
f8b6383e310a57cf9e66e15cab84cf3a09b22109
|
2071cf1aec8e9762a70b8c932943d8769da7f37a
|
/python_source/gui/tkinter/tkcascade.py
|
e795b56bd5793825da24ee9c77edbe452742da7b
|
[] |
no_license
|
rinkeigun/linux_module
|
70581a793d1f170ad1a776fd1acf4cda1abecd52
|
94450fb2c6af0fc56f451ae9bf74f7aca248d0a6
|
refs/heads/master
| 2020-05-21T17:49:15.608902
| 2018-09-18T22:57:40
| 2018-09-18T22:57:40
| 60,572,658
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,149
|
py
|
from tkinter import *
import tkinter.messagebox as tkmsg
root = Tk()
root.option_add('*font', ('FixedSys', 14))
var = StringVar()
var.set('normal')
def dummy(): pass
# 状態の変更
def change_state():
m1.entryconfigure('Menu1', state = var.get())
m1.entryconfigure('Menu2', state = var.get())
m1.entryconfigure('Menu3', state = var.get())
m0.entryconfigure('SingleMenu', state = var.get())
def tandoku():
res=tkmsg.askquestion( title = 'about', message = '単独メニューが選ばれました')
print('戻り値:',res)
# メニューの設定
m0 = Menu(root)
root.configure(menu = m0)
m1 = Menu(m0, tearoff = False)
m0.add_cascade(label = 'カスケードMenu', under = 0, menu = m1)
m1.add_command(label = 'Menu1', command = dummy)
m1.add_command(label = 'Menu2', command = dummy)
m1.add_command(label = 'Menu3', command = dummy)
m0.add_command(label = 'SingleMenu', command = tandoku)
# ラジオボタンの設定
for x in ('normal', 'active', 'disabled'):
Radiobutton(root, text = x, value = x,
variable = var, command = change_state).pack(anchor = W)
root.mainloop()
|
[
"huiqun.lin@gmail.com"
] |
huiqun.lin@gmail.com
|
0087bc89d3f65b6eb2c771479968d35395ed9bca
|
e7b7d22571fba04f333422a4d39cc24a9b6ccc18
|
/btre/accounts/models.py
|
5037b67096f7019f1fa95cf54cdf9d9aa17fa811
|
[] |
no_license
|
fayblash/RealEstateSite
|
21ca7ef15d3e10d44e95e6d1028943f230166d64
|
49c94ccef58fd1a6bc0b022a8221f04d4163c2d6
|
refs/heads/main
| 2023-05-09T20:36:38.472318
| 2021-06-07T19:39:39
| 2021-06-07T19:39:39
| 374,766,507
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 185
|
py
|
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.
|
[
"fayblash@gmail.com"
] |
fayblash@gmail.com
|
86204860d504da65e8bee2af93e4a12db6e22975
|
0f79fd61dc47fcafe22f83151c4cf5f2f013a992
|
/BOJ/20061.py
|
513d669ff1856e5b91e001f0bd0c2ed3df46b2e8
|
[] |
no_license
|
sangm1n/problem-solving
|
670e119f28b0f0e293dbc98fc8a1aea74ea465ab
|
bc03f8ea9a6a4af5d58f8c45c41e9f6923f55c62
|
refs/heads/master
| 2023-04-22T17:56:21.967766
| 2021-05-05T12:34:01
| 2021-05-05T12:34:01
| 282,863,638
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,676
|
py
|
"""
모노미노도미노는 아래와 같이 생긴 보드에서 진행되는 게임이다. 보드는 빨간색 보드, 파란색 보드, 초록색 보드가 그림과 같이 붙어있는 형태이다.
게임에서 사용하는 좌표 (x, y)에서 x는 행, y는 열을 의미한다. 빨간색, 파란색, 초록색 보드가 사용하는 좌표는 그 색으로 그림에 적혀있다.
이 게임에서 사용하는 블록은 타일 하나 또는 두 개가 가로 또는 세로로 붙어있는 형태이다. 아래와 같이 세 종류가 있으며, 왼쪽부터 순서대로 크기가 1×1, 1×2, 2×1 이다.
행이나 열이 타일로 가득찬 경우와 연한 칸에 블록이 있는 경우가 동시에 발생할 수 있다.
이 경우에는 행이나 열이 타일로 가득 찬 경우가 없을 때까지 점수를 획득하는 과정이 모두 진행된 후, 연한 칸에 블록이 있는 경우를 처리해야 한다.
블록은 보드에 놓인 이후에 다른 블록과 합쳐지지 않는다. 블록을 놓은 위치가 순서대로 주어졌을 때, 얻은 점수와 초록색 보드와 파란색 보드에 타일이 있는 칸의 개수를 모두 구해보자.
"""
import sys
input = sys.stdin.readline
N = int(input())
red = [[0] * 4 for _ in range(4)]
blue = [[0] * 6 for _ in range(4)]
green = [[0] * 4 for _ in range(6)]
def green_domino(t, tile):
dx, dy = 1, 0
if t == 1:
x1, y1 = -1, tile[1]
while True:
nx, ny = x1 + dx, y1 + dy
if nx > 5 or green[nx][ny] != 0:
break
x1, y1 = nx, ny
green[nx-1][ny] = 1
else:
if t == 2:
x1, y1 = -1, tile[0][1]
x2, y2 = -1, tile[1][1]
else:
x1, y1 = -1, tile[0][1]
x2, y2 = 0, tile[1][1]
while True:
nx1, ny1 = x1 + dx, y1 + dy
nx2, ny2 = x2 + dx, y2 + dy
if nx1 > 5 or nx2 > 5 or green[nx1][ny1] != 0 or green[nx2][ny2] != 0:
break
x1, y1 = nx1, ny1
x2, y2 = nx2, ny2
green[nx1-1][ny1] = 1
green[nx2-1][ny2] = 1
def blue_domino(t, tile):
dx, dy = 0, 1
if t == 1:
x1, y1 = tile[0], -1
while True:
nx, ny = x1 + dx, y1 + dy
if ny > 5 or blue[nx][ny] != 0:
break
x1, y1 = nx, ny
blue[nx][ny-1] = 1
else:
if t == 2:
x1, y1 = tile[0][0], -1
x2, y2 = tile[1][0], 0
else:
x1, y1 = tile[0][0], -1
x2, y2 = tile[1][0], -1
while True:
nx1, ny1 = x1 + dx, y1 + dy
nx2, ny2 = x2 + dx, y2 + dy
if ny1 > 5 or ny2 > 5 or blue[nx1][ny1] != 0 or blue[nx2][ny2] != 0:
break
x1, y1 = nx1, ny1
x2, y2 = nx2, ny2
blue[nx1][ny1-1] = 1
blue[nx2][ny2-1] = 1
def green_check():
global score
for i in range(6):
if green[i].count(1) == 4:
for j in range(i, -1, -1):
green[j] = green[j-1]
green[0] = [0, 0, 0, 0]
score += 1
block_count = 0
for i in range(2):
if green[i].count(1) > 0:
block_count += 1
for i in range(block_count):
green.pop()
green.insert(0, [0, 0, 0, 0])
def blue_check():
global score
for i in range(6):
cnt = 0
for j in range(4):
if blue[j][i] == 1:
cnt += 1
if cnt == 4:
for j in range(i, -1, -1):
for k in range(4):
blue[k][j] = blue[k][j-1]
for j in range(4):
blue[j][0] = 0
score += 1
block_count = 0
for i in range(2):
for j in range(4):
if blue[j][i] == 1:
block_count += 1
break
for i in range(block_count):
for j in range(4):
blue[j].pop()
blue[j].insert(0, 0)
def green_sum():
global total
for i in range(6):
for j in range(4):
if green[i][j] == 1:
total += 1
def blue_sum():
global total
for i in range(4):
for j in range(6):
if blue[i][j] == 1:
total += 1
score, total = 0, 0
for _ in range(N):
t, x, y = map(int, input().split())
if t == 1:
tile = (x, y)
elif t == 2:
tile = [(x, y), (x, y+1)]
elif t == 3:
tile = [(x, y), (x+1, y)]
green_domino(t, tile)
blue_domino(t, tile)
green_check()
blue_check()
green_sum()
blue_sum()
print(score)
print(total)
|
[
"dltkd96als@naver.com"
] |
dltkd96als@naver.com
|
520f12149113622abf4fab89bc8f557df8cb8448
|
9743d5fd24822f79c156ad112229e25adb9ed6f6
|
/xai/brain/wordbase/nouns/_stopcocks.py
|
68ca2f6991ffbd35b964e278c28a3a6940bfce02
|
[
"MIT"
] |
permissive
|
cash2one/xai
|
de7adad1758f50dd6786bf0111e71a903f039b64
|
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
|
refs/heads/master
| 2021-01-19T12:33:54.964379
| 2017-01-28T02:00:50
| 2017-01-28T02:00:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 252
|
py
|
from xai.brain.wordbase.nouns._stopcock import _STOPCOCK
#calss header
class _STOPCOCKS(_STOPCOCK, ):
def __init__(self,):
_STOPCOCK.__init__(self)
self.name = "STOPCOCKS"
self.specie = 'nouns'
self.basic = "stopcock"
self.jsondata = {}
|
[
"xingwang1991@gmail.com"
] |
xingwang1991@gmail.com
|
0a9a17d46c80539a638273628970b034d16c45ab
|
cbf9f600374d7510988632d7dba145c8ff0cd1f0
|
/AISing/c.py
|
1bced9d46211c10b0d06d2db890caae23670859b
|
[] |
no_license
|
sakakazu2468/AtCoder_py
|
d0945d03ad562474e40e413abcec39ded61e6855
|
34bdf39ee9647e7aee17e48c928ce5288a1bfaa5
|
refs/heads/master
| 2022-04-27T18:32:28.825004
| 2022-04-21T07:27:00
| 2022-04-21T07:27:00
| 225,844,364
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 404
|
py
|
n = int(input())
xyz = [[[0 for i in range(101)] for j in range(101)] for k in range(101)]
ans = [0 for i in range(n+1)]
def gen_n(x, y, z):
return x**2 + y**2 + z**2 + x*y + y*z + z*x
for i in range(1, 101):
for j in range(1, 101):
for k in range(1, 101):
num = gen_n(i, j, k)
if n >= num:
ans[num] += 1
for i in range(1, n+1):
print(ans[i])
|
[
"sakakazu2468@icloud.com"
] |
sakakazu2468@icloud.com
|
d392365edbf57883fa52e225c5ec1c543754e39e
|
cccf0b4c6b08502dea94ac1febb49fc0f8561cc2
|
/src/bind.py
|
e9823644dd74973261df64057956374e5c7b9592
|
[] |
no_license
|
rpm-io/rpm.io
|
55e13a4795f421a2514f45d707820c4fe605dbf2
|
80cd5f0703c550628d62a7f45e213e9434a64e8d
|
refs/heads/master
| 2022-12-15T21:54:14.040117
| 2019-08-25T16:44:28
| 2019-08-25T16:44:28
| 187,483,128
| 1
| 0
| null | 2022-12-10T15:03:44
| 2019-05-19T13:53:28
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 3,020
|
py
|
import sys
import uuid
import json
from importlib import import_module
import os
sys.path.append(os.getcwd())
class Bind:
__VARIABLES__ = {
"END": "END"
}
def __init__(self):
self.module = import_module(sys.argv[1])
self.ok = True
def declare(self, value):
name = str(uuid.uuid1())
self.__VARIABLES__[name] = value
return name
def var(self, name):
if name:
return self.__VARIABLES__[name]
def var_from(self, name):
if name in self.message:
return self.var(self.message[name])
def val_from(self, name):
if name in self.message:
return self.message[name]
def init(self, clazz, params):
return clazz(*params)
def call(self, method, params):
return method(*params)
def command(self):
self.message = json.loads(input())
def is_primitive(self, data):
if data:
return not hasattr(self.var(data), "__dict__")
return True
def value_of(self, name):
data = self.var(name)
if data:
return str(data)
return data
def type_of(self, data):
if data:
return str(type(self.var(data)))
def show(self, data, __id__):
print(json.dumps({
"data": data,
"type": self.type_of(data),
"primitive": self.is_primitive(data),
"value": self.value_of(data),
"__id__": __id__
}), flush=True)
def run(self):
self.show(self.declare(self.module), "__self__")
while self.ok:
self.command()
COMMAND = self.val_from('com')
__id__ = self.val_from('__id__')
if COMMAND == 'attr':
variable = self.var_from('var')
name = self.val_from('attr')
if variable and name:
if hasattr(variable, name):
attr = getattr(variable, name)
self.show(self.declare(attr), __id__)
else:
self.show(None, __id__)
if COMMAND == 'new':
clazz = self.var_from('var')
params = self.val_from('params')
instance = self.init(clazz, params)
self.show(self.declare(instance), __id__)
if COMMAND == 'str':
self.show(self.var_from('var'), __id__)
if COMMAND == 'call':
method = self.var_from('var')
params = self.val_from('params')
result = self.call(method, params)
self.show(self.declare(result), __id__)
if COMMAND == 'describe':
self.show(self.var_from('var').__dict__, __id__)
if COMMAND == 'destroy':
self.ok = False
self.show("END", __id__)
if __name__ == "__main__":
Bind().run()
|
[
"luismiguel.mopa@gmail.com"
] |
luismiguel.mopa@gmail.com
|
ae21549b8b1f5138084eb96159f1b2b83e5bc6a6
|
fc772efe3eccb65e4e4a8da7f2b2897586b6a0e8
|
/Controller/glance/common/location_strategy/store_type.py
|
75f8c239670b96c2e5855ca2b5e1b7de69bda730
|
[] |
no_license
|
iphonestack/Openstack_Kilo
|
9ae12505cf201839631a68c9ab4c041f737c1c19
|
b0ac29ddcf24ea258ee893daf22879cff4d03c1f
|
refs/heads/master
| 2021-06-10T23:16:48.372132
| 2016-04-18T07:25:40
| 2016-04-18T07:25:40
| 56,471,076
| 0
| 2
| null | 2020-07-24T02:17:46
| 2016-04-18T02:32:43
|
Python
|
UTF-8
|
Python
| false
| false
| 4,238
|
py
|
# Copyright 2014 IBM Corp.
# 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.
"""Storage preference based location strategy module"""
from oslo.config import cfg
import six
import six.moves.urllib.parse as urlparse
from glance import i18n
_ = i18n._
store_type_opts = [
cfg.ListOpt("store_type_preference",
default=[],
help=_("The store names to use to get store preference order. "
"The name must be registered by one of the stores "
"defined by the 'known_stores' config option. "
"This option will be applied when you using "
"'store_type' option as image location strategy "
"defined by the 'location_strategy' config option."))
]
CONF = cfg.CONF
CONF.register_opts(store_type_opts, group='store_type_location_strategy')
_STORE_TO_SCHEME_MAP = {}
def get_strategy_name():
"""Return strategy module name."""
return 'store_type'
def init():
"""Initialize strategy module."""
# NOTE(zhiyan): We have a plan to do a reusable glance client library for
# all clients like Nova and Cinder in near period, it would be able to
# contains common code to provide uniform image service interface for them,
# just like Brick in Cinder, this code can be moved to there and shared
# between Glance and client both side. So this implementation as far as
# possible to prevent make relationships with Glance(server)-specific code,
# for example: using functions within store module to validate
# 'store_type_preference' option.
mapping = {'filesystem': ['file', 'filesystem'],
'http': ['http', 'https'],
'rbd': ['rbd'],
's3': ['s3', 's3+http', 's3+https'],
'swift': ['swift', 'swift+https', 'swift+http'],
'gridfs': ['gridfs'],
'sheepdog': ['sheepdog'],
'cinder': ['cinder'],
'vmware_datastore': ['vsphere']}
_STORE_TO_SCHEME_MAP.clear()
_STORE_TO_SCHEME_MAP.update(mapping)
def get_ordered_locations(locations, uri_key='url', **kwargs):
"""
Order image location list.
:param locations: The original image location list.
:param uri_key: The key name for location URI in image location dictionary.
:return: The image location list with preferred store type order.
"""
def _foreach_store_type_preference():
store_types = CONF.store_type_location_strategy.store_type_preference
for preferred_store in store_types:
preferred_store = str(preferred_store).strip()
if not preferred_store:
continue
yield preferred_store
if not locations:
return locations
preferences = {}
others = []
for preferred_store in _foreach_store_type_preference():
preferences[preferred_store] = []
for location in locations:
uri = location.get(uri_key)
if not uri:
continue
pieces = urlparse.urlparse(uri.strip())
store_name = None
for store, schemes in six.iteritems(_STORE_TO_SCHEME_MAP):
if pieces.scheme.strip() in schemes:
store_name = store
break
if store_name in preferences:
preferences[store_name].append(location)
else:
others.append(location)
ret = []
# NOTE(zhiyan): While configuration again since py26 does not support
# ordereddict container.
for preferred_store in _foreach_store_type_preference():
ret.extend(preferences[preferred_store])
ret.extend(others)
return ret
|
[
"wwang@linx-info.com"
] |
wwang@linx-info.com
|
d54bbda96683cdd763c1b279aba965e3873a5a09
|
34599596e145555fde0d4264a1d222f951f49051
|
/pcat2py/class/21ede120-5cc5-11e4-af55-00155d01fe08.py
|
517fcbf9e1895c3f103154e3d831715a37a09a75
|
[
"MIT"
] |
permissive
|
phnomcobra/PCAT2PY
|
dc2fcbee142ce442e53da08476bfe4e68619346d
|
937c3b365cdc5ac69b78f59070be0a21bdb53db0
|
refs/heads/master
| 2021-01-11T02:23:30.669168
| 2018-02-13T17:04:03
| 2018-02-13T17:04:03
| 70,970,520
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,497
|
py
|
#!/usr/bin/python
################################################################################
# 21ede120-5cc5-11e4-af55-00155d01fe08
#
# Justin Dierking
# justindierking@hardbitsolutions.com
# phnomcobra@gmail.com
#
# 10/24/2014 Original Construction
################################################################################
class Finding:
def __init__(self):
self.output = []
self.is_compliant = False
self.uuid = "21ede120-5cc5-11e4-af55-00155d01fe08"
def check(self, cli):
# Initialize Compliance
self.is_compliant = False
# Get Registry DWORD
dword = cli.get_reg_dword(r'HKCU:\Software\Policies\Microsoft\Office\12.0\Outlook\Security\TrustedAddins', '')
# Output Lines
self.output = [r'HKCU:\Software\Policies\Microsoft\Office\12.0\Outlook\Security\TrustedAddins', ('=' + str(dword))]
if dword == -1:
self.is_compliant = True
return self.is_compliant
def fix(self, cli):
cli.powershell(r"New-Item -path 'HKCU:\Software\Policies\Microsoft\Office\12.0\Outlook'")
cli.powershell(r"New-Item -path 'HKCU:\Software\Policies\Microsoft\Office\12.0\Outlook\Security'")
cli.powershell(r"New-Item -path 'HKCU:\Software\Policies\Microsoft\Office\12.0\Outlook\Security\TrustedAddins'")
cli.powershell(r"Set-ItemProperty -path 'HKCU:\Software\Policies\Microsoft\Office\12.0\Outlook\Security\TrustedAddins' -name '' -value -Type DWord")
|
[
"phnomcobra@gmail.com"
] |
phnomcobra@gmail.com
|
bc1680235109bc4da1b863579b5bf349298ae9fe
|
2ae59d7f70f083fc255c29669ada5dcacbd3411f
|
/encasa/utils/models/common_regex.py
|
7b41e0009066740932b74d66f52a278a95a23019
|
[] |
no_license
|
gonza56d/django_docker_template
|
aeccfec357aa9732abf869f8baf0c0b9f11f7200
|
f739c71dcb01819caf4520a2169264ea1abcf4b0
|
refs/heads/master
| 2023-03-14T04:09:01.200633
| 2021-03-07T21:08:28
| 2021-03-07T21:08:28
| 345,263,273
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 606
|
py
|
# Django
from django.core.validators import RegexValidator
class CommonRegex:
"""Common validation regular expressions."""
LOWERCASE_AND_NUMBERS = RegexValidator(
regex='[a0-z9]',
message='Only lowercase letters and numbers allowed.'
)
LETTERS_AND_NUMBERS = RegexValidator(
regex='[aA0-zA9]',
message='Only letters and numbers allowed.'
)
LETTERS = RegexValidator(
regex='[aA-zZ]',
message='Only letters allowed.'
)
LOWERCASE = RegexValidator(
regex='[a-z]',
message='Only lowercase letters allowed.'
)
|
[
"gonza56d@gmail.com"
] |
gonza56d@gmail.com
|
4bd1566537db005bd9d5471cb5b042372ba16b80
|
7ba4e38e0835cd009a078ce39a480b5bacaba21f
|
/sample_code/chap8/8.4.5.rectify.py
|
0b0fab1f3600418d5bf6050b41150c51447f663e
|
[] |
no_license
|
moguranran/computer_vision_test
|
fe0641987905755c733e4ab16f48c3b76d01b3f4
|
4c5b5572d01e13a42eefb2423e66e34675c305cb
|
refs/heads/master
| 2022-04-20T17:53:37.668609
| 2020-03-31T00:13:02
| 2020-03-31T00:13:02
| 249,196,701
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 806
|
py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from PIL import Image
from pylab import *
from scipy import ndimage
import homography
imname = 'sudoku_images/sudokus/sudoku8.JPG'
im = array(Image.open(imname).convert('L'))
# 4隅を入力する
figure()
imshow(im)
gray()
x = ginput(4)
# 左上、右上、右下、左下
fp = array([array([p[1],p[0],1]) for p in x]).T
tp = array([[0,0,1],[0,1000,1],[1000,1000,1],[1000,0,1]]).T
# ホモグラフィーを推定する
H = homography.H_from_points(tp,fp)
# geometric_transform用のヘルパー関数
def warpfcn(x):
x = array([x[0],x[1],1])
xt = dot(H,x)
xt = xt/xt[2]
return xt[0],xt[1]
# 射影変換を使って画像を変形する
im_g = ndimage.geometric_transform(im,warpfcn,(1000,1000))
figure()
imshow(im_g)
axis('off')
gray()
show()
|
[
"peehssalg@gmail.com"
] |
peehssalg@gmail.com
|
15006b6d8c7f8ae7ecca9c43b3bfa34aa5e18d1c
|
62ea331d8da218e65a4aee517f4473110f80c03c
|
/matches/migrations/0011_auto_20180601_2337.py
|
5afbf4770bf95e23ffe57a987598cffa7867b8b4
|
[] |
no_license
|
maddrum/world_cup_results
|
11f47a1b0f9a68a0761c7d83d25cc1efb57c2240
|
282d8f55344ba718ea371a22f34454673f23a615
|
refs/heads/master
| 2020-03-20T05:40:44.173185
| 2018-07-16T13:12:15
| 2018-07-16T13:12:15
| 136,724,186
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,612
|
py
|
# Generated by Django 2.0.2 on 2018-06-01 20:37
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('matches', '0010_auto_20180601_1641'),
]
operations = [
migrations.CreateModel(
name='UserPredictions',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('prediction_match_state', models.CharField(choices=[('home', 'Победа домакин'), ('guest', 'Победа гост'), ('tie', 'Равен')], max_length=20)),
('prediction_goals_home', models.IntegerField()),
('prediction_goals_guest', models.IntegerField()),
('user_points', models.IntegerField()),
],
),
migrations.AlterUniqueTogether(
name='matches',
unique_together={('country_home', 'country_guest', 'phase')},
),
migrations.AddField(
model_name='userpredictions',
name='match',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_predictions', to='matches.Matches'),
),
migrations.AddField(
model_name='userpredictions',
name='user_id',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user', to=settings.AUTH_USER_MODEL),
),
]
|
[
"maddrum9@gmail.com"
] |
maddrum9@gmail.com
|
f68dedf0d4f41d08e278bea9df10e7841f8c749b
|
46c76c7ca1d9d030606f2e3e95a2a9e6bbad2789
|
/workspace201406/ClassExamples/accounts.py
|
77f58e4bc1ffee16226f5db5e4c1ad21430917fc
|
[] |
no_license
|
KayMutale/pythoncourse
|
be9ff713cffc73c1b9b3c1dd2bdd6d293637ce1e
|
985a747ff17133aa533b7a049f83b37fc0fed80e
|
refs/heads/master
| 2023-04-13T07:58:00.993724
| 2021-04-16T14:19:41
| 2021-04-16T14:19:41
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,401
|
py
|
'''
Created on 10 Jun 2014
@author: mark
'''
class Account(object):
'''
classdocs
'''
last_accno = 0
types = ("ASSET","LIABILITY","EQUITY","INCOME","EXPENCE")
_perm_accounts = types[:3]
_credit_accounts = types[1:4]
_debit_accounts = types[0] +types[4]
def __init__(self,balance=0):
self.balance = balance
Account.last_accno += 1
self.accno = Account.last_accno
self.type = Account.types[0]
def debit(self,amount):
self.balance += amount if self.type in Account._debit_accounts else -amount
def credit(self,amount):
self.balance += amount if self.type in Account._credit_accounts else -amount
class CreditAccount(Account):
def __init__(self,credit_limmit=0,balance=0):
Account.__init__(self,balance)
self.credit_limmit = credit_limmit
def credit(self,amount):
assert self.balance + self.ceditlimmit > amount, "not enough funds"
Account.credit(self,amount)
if __name__ == "__main__":
check = Account()
card = CreditAccount()
print isinstance(check,Account)
card.type = "LIABILITY"
print card.balance
check.balance = 100
check.debit(5)
print check.balance
card.debit(50)
print card.balance
card.debit(10) #Account.debit(card,10)
print card.balance
print Account.__dict__
|
[
"mark@ledge.co.za"
] |
mark@ledge.co.za
|
f4630ba76d4e6069dec7ef7512e88ed698af23d2
|
5f61724fc5cad3f82094a681c853cc9f0337f050
|
/test/test_xmlpart.py
|
9f1f8a02e7773b2d4bbc9354889b40ace6f30d36
|
[
"Apache-2.0"
] |
permissive
|
barseghyanartur/odfdo
|
2cecbbbb33f23d5ed0ba80cb9208a8e7857b93a0
|
e628a9e9daa40319a777d216ec7ebca4057b3344
|
refs/heads/master
| 2022-11-17T15:43:15.662484
| 2020-06-27T00:41:38
| 2020-06-28T22:53:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,598
|
py
|
#!/usr/bin/env python
# Copyright 2018 Jérôme Dumonteil
# Copyright (c) 2009-2010 Ars Aperta, Itaapy, Pierlis, Talend.
#
# 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.
#
#
# Authors (odfdo project): jerome.dumonteil@gmail.com
# The odfdo project is a derivative work of the lpod-python project:
# https://github.com/lpod/lpod-python
# Authors: Hervé Cauwelier <herve@itaapy.com>
# David Versmisse <david.versmisse@itaapy.com>
from unittest import TestCase, main
from lxml.etree import _ElementTree
from odfdo.const import ODF_CONTENT
from odfdo.container import Container
from odfdo.element import Element
from odfdo.xmlpart import XmlPart
from odfdo.content import Content
class XmlPartTestCase(TestCase):
def setUp(self):
self.container = Container()
self.container.open('samples/example.odt')
def tearDown(self):
del self.container
def test_get_element_list(self):
content_part = XmlPart(ODF_CONTENT, self.container)
elements = content_part.get_elements('//text:p')
# The annotation paragraph is counted
self.assertEqual(len(elements), 8)
def test_tree(self):
# Testing a private but important method
content = XmlPart(ODF_CONTENT, self.container)
tree = content._XmlPart__get_tree()
self.assertTrue(isinstance(tree, _ElementTree))
self.assertNotEqual(content._XmlPart__tree, None)
def test_root(self):
content = XmlPart(ODF_CONTENT, self.container)
root = content.root
self.assertTrue(isinstance(root, Element))
self.assertEqual(root.tag, "office:document-content")
self.assertNotEqual(content._XmlPart__root, None)
def test_serialize(self):
container = self.container
content_bytes = container.get_part(ODF_CONTENT)
content_part = XmlPart(ODF_CONTENT, container)
# differences with lxml
serialized = content_part.serialize().replace(b"'", b"'")
self.assertEqual(content_bytes, serialized)
def test_pretty_serialize(self):
# With pretty = True
element = Element.from_tag('<root><a>spam</a><b/></root>')
serialized = element.serialize(pretty=True)
expected = ('<root>\n' ' <a>spam</a>\n' ' <b/>\n' '</root>\n')
self.assertEqual(serialized, expected)
def test_clone(self):
# Testing that the clone works on subclasses too
container = self.container
content = Content(ODF_CONTENT, container)
clone = content.clone
self.assertEqual(clone.part_name, content.part_name)
self.assertNotEqual(id(container), id(clone.container))
self.assertEqual(clone._XmlPart__tree, None)
def test_delete(self):
container = self.container
content = XmlPart(ODF_CONTENT, container)
paragraphs = content.get_elements('//text:p')
for paragraph in paragraphs:
content.delete_element(paragraph)
serialized = content.serialize()
self.assertEqual(serialized.count(b'<text:p'), 0)
if __name__ == '__main__':
main()
|
[
"jerome.dumonteil@gmail.com"
] |
jerome.dumonteil@gmail.com
|
dee86a91a321348c1a9ea17593f58fb0fab6248f
|
a39f7413dcd87bb26319fe032d59cf12d7c69d54
|
/backbones/decoder.py
|
67afba19646e66388f3d87d8fefe214f1dc4ee88
|
[] |
no_license
|
liangyuandg/cross_modality_ibsr
|
8ad937b5475bd5e6b00ad50351706304a962f975
|
bb5cefd890f5fa0e15eae6e54d9559f5e8eb94ed
|
refs/heads/master
| 2023-06-24T02:58:25.318170
| 2021-07-27T08:29:27
| 2021-07-27T08:29:27
| 389,904,637
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,455
|
py
|
import torch.nn as nn
import torch
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=dilation, groups=groups, bias=False, dilation=dilation)
class ResNet_Decoder(nn.Module):
def __init__(self, inplanes, midplanes, outplanes):
super(ResNet_Decoder, self).__init__()
self.mse = nn.MSELoss(reduction='mean')
self.layer1 = self._make_layer(inplanes[0], midplanes[0], outplanes[0])
self.layer2 = self._make_layer(inplanes[1], midplanes[1], outplanes[1])
self.layer3 = self._make_layer(inplanes[2], midplanes[2], outplanes[2])
self.layer4 = self._make_layer(inplanes[3], midplanes[3], outplanes[3])
self.finallayer = conv3x3(outplanes[3], 3)
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def _make_layer(self, inplane, midplane, outplane):
layers = []
layers.append(conv3x3(inplane, midplane))
layers.append(nn.BatchNorm2d(midplane))
layers.append(nn.ReLU(inplace=True))
layers.append(conv3x3(midplane, midplane))
layers.append(nn.BatchNorm2d(midplane))
layers.append(nn.ReLU(inplace=True))
layers.append(nn.ConvTranspose2d(midplane, outplane, 2, stride=2))
layers.append(nn.BatchNorm2d(outplane))
return nn.Sequential(*layers)
def train_forward(self, directs, gt):
x = self.layer1(directs[2])
x = torch.cat((x, directs[1]), 1)
x = self.layer2(x)
x = torch.cat((x, directs[0]), 1)
x = self.layer3(x)
x = self.layer4(x)
x = self.finallayer(x)
return x, self.mse(x, gt)
def test_forward(self, directs):
x = self.layer1(directs[2])
x = torch.cat((x, directs[1]), 1)
x = self.layer2(x)
x = torch.cat((x, directs[0]), 1)
x = self.layer3(x)
x = self.layer4(x)
x = self.finallayer(x)
return x
def load(self, file_path):
checkpoint = torch.load(file_path)
# normal
self.load_state_dict(checkpoint, strict=False)
|
[
"liangyuandg@g.ucla.edu"
] |
liangyuandg@g.ucla.edu
|
9a3d85f621d23e6aedf6d0d238f468b8abd4befc
|
1f94b6ff9477e380084bf00c591d92b0b2985e69
|
/PythonEshow/apis/AUsers.py
|
1b2e67a5504df084d2dec10fb70253366de4ad1d
|
[] |
no_license
|
guofengma/Eshow
|
dff32fa1da152f30d776b7e8fdc2d5ffc1ef4c40
|
4b13cb4c328d7832bea3393000635106dd683b28
|
refs/heads/master
| 2020-04-24T07:22:46.757263
| 2018-05-03T00:59:31
| 2018-05-03T00:59:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 669
|
py
|
# *- coding:utf8 *-
import sys
import os
sys.path.append(os.path.dirname(os.getcwd()))
from flask_restful import Resource
from config.requests import apis_wrong, param_miss
class AUsers(Resource):
def __init__(self):
from control.CUsers import CUsers
self.cusers = CUsers()
def post(self, users):
print "==================================================="
print "api name is {0}".format(users)
print "==================================================="
apis = {
"login": "self.cusers.login()"
}
if users not in apis:
return apis_wrong
return eval(apis[users])
|
[
"1276121237@qq.com"
] |
1276121237@qq.com
|
e5dbd30c0c8cca38c4563b3f180af1302597c50f
|
6c48ad953031fd6be870e8bd8775538b9ac7033e
|
/python/demo08_module/demo12_file_copy_2.py
|
d6dbda50aec8cdfa170dae8235f52b3bb86b0ea9
|
[] |
no_license
|
yeswhos/Code-Practice
|
b080c9484f510d02c2d78e388fc03eedc397aa7b
|
0fd8263a5c87dbd0e8b1dd5a38f32a188870308b
|
refs/heads/master
| 2023-04-08T13:11:06.105039
| 2023-03-16T11:34:03
| 2023-03-16T11:34:03
| 247,809,031
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 233
|
py
|
file_read = open("D:\GitR\Code-Practice\README.md")
file_write = open("D:\python_a.md", "w")
while True:
text = file_read.readline()
if not text:
break
file_write.write(text)
file_read.close()
file_write.close()
|
[
"yeswhos@outlook.com"
] |
yeswhos@outlook.com
|
50da484a10d8c1763aa27665fa7bb665fd69438e
|
2aace9bb170363e181eb7520e93def25f38dbe5c
|
/build/idea-sandbox/system/python_stubs/cache/bdf774aa44376518b55fa0857c4aa1e281ab006abf9d2169b8b93383f1e63a63/cython_runtime.py
|
2f39ea21b21c76ab3e8b7b67c14f4bc7f0faba86
|
[] |
no_license
|
qkpqkp/PlagCheck
|
13cb66fd2b2caa2451690bb72a2634bdaa07f1e6
|
d229904674a5a6e46738179c7494488ca930045e
|
refs/heads/master
| 2023-05-28T15:06:08.723143
| 2021-06-09T05:36:34
| 2021-06-09T05:36:34
| 375,235,940
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 277
|
py
|
# encoding: utf-8
# module cython_runtime
# from C:\Users\Doly\Anaconda3\lib\site-packages\scipy\interpolate\interpnd.cp37-win_amd64.pyd
# by generator 1.147
# no doc
# no imports
# Variables with simple values
__loader__ = None
__spec__ = None
# no functions
# no classes
|
[
"qinkunpeng2015@163.com"
] |
qinkunpeng2015@163.com
|
354a96afb879b8c3ef70574d8789f264ecd2c01f
|
51f887286aa3bd2c3dbe4c616ad306ce08976441
|
/pybind/nos/v6_0_2f/interface/fortygigabitethernet/snmp/__init__.py
|
548b4c7ea3ff0beb53b6146afc568278cdfc288f
|
[
"Apache-2.0"
] |
permissive
|
b2220333/pybind
|
a8c06460fd66a97a78c243bf144488eb88d7732a
|
44c467e71b2b425be63867aba6e6fa28b2cfe7fb
|
refs/heads/master
| 2020-03-18T09:09:29.574226
| 2018-04-03T20:09:50
| 2018-04-03T20:09:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,251
|
py
|
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from decimal import Decimal
from bitarray import bitarray
import __builtin__
import trap
class snmp(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module brocade-interface - based on the path /interface/fortygigabitethernet/snmp. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: The SNMP configurations for an interface.
"""
__slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__trap',)
_yang_name = 'snmp'
_rest_name = 'snmp'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
path_helper_ = kwargs.pop("path_helper", None)
if path_helper_ is False:
self._path_helper = False
elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper):
self._path_helper = path_helper_
elif hasattr(self, "_parent"):
path_helper_ = getattr(self._parent, "_path_helper", False)
self._path_helper = path_helper_
else:
self._path_helper = False
extmethods = kwargs.pop("extmethods", None)
if extmethods is False:
self._extmethods = False
elif extmethods is not None and isinstance(extmethods, dict):
self._extmethods = extmethods
elif hasattr(self, "_parent"):
extmethods = getattr(self._parent, "_extmethods", None)
self._extmethods = extmethods
else:
self._extmethods = False
self.__trap = YANGDynClass(base=trap.trap, is_container='container', presence=False, yang_name="trap", rest_name="trap", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Trap related configurations', u'cli-incomplete-no': None, u'sort-priority': u'RUNNCFG_INTERFACE_LEVEL_BASIC_CONFIG', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-interface', defining_module='brocade-interface', yang_type='container', is_config=True)
load = kwargs.pop("load", None)
if args:
if len(args) > 1:
raise TypeError("cannot create a YANG container with >1 argument")
all_attr = True
for e in self._pyangbind_elements:
if not hasattr(args[0], e):
all_attr = False
break
if not all_attr:
raise ValueError("Supplied object did not have the correct attributes")
for e in self._pyangbind_elements:
nobj = getattr(args[0], e)
if nobj._changed() is False:
continue
setmethod = getattr(self, "_set_%s" % e)
if load is None:
setmethod(getattr(args[0], e))
else:
setmethod(getattr(args[0], e), load=load)
def _path(self):
if hasattr(self, "_parent"):
return self._parent._path()+[self._yang_name]
else:
return [u'interface', u'fortygigabitethernet', u'snmp']
def _rest_path(self):
if hasattr(self, "_parent"):
if self._rest_name:
return self._parent._rest_path()+[self._rest_name]
else:
return self._parent._rest_path()
else:
return [u'interface', u'FortyGigabitEthernet', u'snmp']
def _get_trap(self):
"""
Getter method for trap, mapped from YANG variable /interface/fortygigabitethernet/snmp/trap (container)
YANG Description: SNMP Trap configuration
"""
return self.__trap
def _set_trap(self, v, load=False):
"""
Setter method for trap, mapped from YANG variable /interface/fortygigabitethernet/snmp/trap (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_trap is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_trap() directly.
YANG Description: SNMP Trap configuration
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=trap.trap, is_container='container', presence=False, yang_name="trap", rest_name="trap", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Trap related configurations', u'cli-incomplete-no': None, u'sort-priority': u'RUNNCFG_INTERFACE_LEVEL_BASIC_CONFIG', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-interface', defining_module='brocade-interface', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """trap must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=trap.trap, is_container='container', presence=False, yang_name="trap", rest_name="trap", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Trap related configurations', u'cli-incomplete-no': None, u'sort-priority': u'RUNNCFG_INTERFACE_LEVEL_BASIC_CONFIG', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-interface', defining_module='brocade-interface', yang_type='container', is_config=True)""",
})
self.__trap = t
if hasattr(self, '_set'):
self._set()
def _unset_trap(self):
self.__trap = YANGDynClass(base=trap.trap, is_container='container', presence=False, yang_name="trap", rest_name="trap", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Trap related configurations', u'cli-incomplete-no': None, u'sort-priority': u'RUNNCFG_INTERFACE_LEVEL_BASIC_CONFIG', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-interface', defining_module='brocade-interface', yang_type='container', is_config=True)
trap = __builtin__.property(_get_trap, _set_trap)
_pyangbind_elements = {'trap': trap, }
|
[
"badaniya@brocade.com"
] |
badaniya@brocade.com
|
c4b8c299ef806ae544a61f97faf8c7b11cc72052
|
7bc54bae28eec4b735c05ac7bc40b1a8711bb381
|
/src/tf_util/show_record.py
|
8ed8b6ce8bda4b761875613a73799b90c7385020
|
[] |
no_license
|
clover3/Chair
|
755efd4abbd5f3f2fb59e9b1bc6e7bc070b8d05e
|
a2102ebf826a58efbc479181f1ebb5de21d1e49f
|
refs/heads/master
| 2023-07-20T17:29:42.414170
| 2023-07-18T21:12:46
| 2023-07-18T21:12:46
| 157,024,916
| 0
| 0
| null | 2023-02-16T05:20:37
| 2018-11-10T21:55:29
|
Python
|
UTF-8
|
Python
| false
| false
| 708
|
py
|
import sys
import tensorflow as tf
def file_show(fn):
cnt = 0
n_display = 5
for record in tf.compat.v1.python_io.tf_record_iterator(fn):
example = tf.train.Example()
example.ParseFromString(record)
feature = example.features.feature
keys = feature.keys()
print("---- record -----")
for key in keys:
if key in ["masked_lm_weights", "rel_score"]:
v = feature[key].float_list.value
else:
v = feature[key].int64_list.value
print(key)
print(v)
cnt += 1
if cnt >= n_display: ##
break
if __name__ == "__main__":
file_show(sys.argv[1])
|
[
"lesterny@gmail.com"
] |
lesterny@gmail.com
|
d81d54bc1bb25218cba01ca8702d7129ffa2acb9
|
bd498cbbb28e33370298a84b693f93a3058d3138
|
/Google/benchmarks/transformer/implementations/transformer-research-TF-tpu-v4-128/lingvo/tasks/mt/params/params.py
|
a2907a7f5d715856f2ba60d1e0f68757bd1f29b4
|
[
"Apache-2.0"
] |
permissive
|
piyushghai/training_results_v0.7
|
afb303446e75e3e9789b0f6c40ce330b6b83a70c
|
e017c9359f66e2d814c6990d1ffa56654a73f5b0
|
refs/heads/master
| 2022-12-19T16:50:17.372320
| 2020-09-24T01:02:00
| 2020-09-24T18:01:01
| 298,127,245
| 0
| 1
|
Apache-2.0
| 2020-09-24T00:27:21
| 2020-09-24T00:27:21
| null |
UTF-8
|
Python
| false
| false
| 1,198
|
py
|
# Copyright 2018 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.
# ==============================================================================
"""Machine translation model hyper-parameters."""
# Import ModelParams to ensure that they are added to the global registry.
# pylint: disable=unused-import
import REDACTED.tensorflow_models.mlperf.models.rough.transformer_lingvo.lingvo.tasks.mt.params.wmt14_en_de
import REDACTED.tensorflow_models.mlperf.models.rough.transformer_lingvo.lingvo.tasks.mt.params.wmtm16_en_de
import REDACTED.tensorflow_models.mlperf.models.rough.transformer_lingvo.lingvo.tasks.mt.params.mlperf
# pylint: enable=unused-import
|
[
"vbittorf@google.com"
] |
vbittorf@google.com
|
b063bd197215f270b9d6e66e2f4be27ffb58d140
|
3777658387aa9e78d7c04202d7fd47d59b9e1271
|
/MachineLearning/FeatureEngineering/target_encoding.py
|
f69b809d8d766c93e3a1d6807f5f2eb76abfff60
|
[] |
no_license
|
jocoder22/PythonDataScience
|
709363ada65b6db61ee73c27d8be60587a74f072
|
c5a9af42e41a52a7484db0732ac93b5945ade8bb
|
refs/heads/master
| 2022-11-08T17:21:08.548942
| 2022-10-27T03:21:53
| 2022-10-27T03:21:53
| 148,178,242
| 4
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,099
|
py
|
#!/usr/bin/env python
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import KFold
from contextlib import contextmanager
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_squared_error
from sklearn.ensemble import RandomForestRegressor
sp = {'sep':'\n\n', 'end':'\n\n'}
path = r'C:\Users\Jose\Desktop\PythonDataScience\MachineLearning\FeatureEngineering'
os.chdir(path)
df = pd.read_csv('housing.csv')
kfold = KFold(n_splits=4, shuffle=True, random_state=1973)
def test_encoding(train, test, target, cat, alpha=7):
# global mean on the train data
mean_global = train[target].mean()
# Get categorical feature sum and size
cat_sum = train.groupby(cat)[target].sum()
cat_size = train.groupby(cat).size()
# smoothed statistics
train_smoothed = (cat_sum + mean_global * alpha) / (cat_size + alpha)
# get encodings for test data
test_encoded = test[cat].map(train_smoothed).fillna(mean_global)
return test_encoded.values
def train_encoding(train, target, cat, alpha=7):
# 4-fold cross-validation
k_fold = KFold(n_splits=4, random_state=1973, shuffle=True)
feature_t = pd.Series(index=train.index)
# train k-fold encoding
for train_index, test_index in k_fold.split(train):
cv_train, cv_test = train.iloc[train_index], train.iloc[test_index]
# out-of-fold statistics and apply to cv_test
cv_test_feature = test_encoding(cv_train, cv_test, target, cat, alpha)
# create new train feature for the fold
feature_t.iloc[test_index] = cv_test_feature
return feature_t.values
def target_encoding(train, test, target, cat, alpha=7):
# test data mean target coded feature
test_mean_coded = test_encoding(train, test, target, cat, alpha)
# train data mean target coded feature
train_mean_coded = train_encoding(train, target, cat, alpha)
# Return new features to add to the model
return train_mean_coded, test_mean_coded
|
[
"okigbookey@gmail.com"
] |
okigbookey@gmail.com
|
f9d1d9cf9b8c99744ce68c3ed06d3bf7eefe6d21
|
648fbac90569e520540a14ad7be6714dc3aa303d
|
/scripts/cell/card_10000220.py
|
d05d6fc2bb0421c57d41269da5248ce6095fe30e
|
[] |
no_license
|
zhlhmjz/kbe_lscs
|
e573c1eac74c12005cb6c50288a952b2874e231b
|
6dc4eae5ab7fee66e929204abc80125f4f6be8f6
|
refs/heads/master
| 2021-08-24T13:43:42.208183
| 2017-11-21T08:39:14
| 2017-11-21T08:39:14
| 111,522,225
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 719
|
py
|
# -*- coding: utf-8 -*-
import KBEngine
from KBEDebug import *
from interfaces.GameObj import GameObj
class card_10000220(GameObj):
#卡牌名称:尘魔
#卡牌描述:<b>风怒</b>,<b>过载:</b>2
def __init__(self):
GameObj.__init__(self)
#--------------------------------------------------------------------------------------------
# Callbacks
#--------------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------------
# Effect
#--------------------------------------------------------------------------------------------
|
[
"752612571@qq.com"
] |
752612571@qq.com
|
1a421e4b7a56288ef0f491e649e419218ddae590
|
b3ac12dfbb8fa74500b406a0907337011d4aac72
|
/tests/simulation/test_simulation.py
|
4d360e7d047c84c5a25402b92a5ff5871f45f7c9
|
[
"Apache-2.0"
] |
permissive
|
chia-os/goldcoin-blockchain
|
ab62add5396b7734c11d3c37c41776994489d5e7
|
5c294688dbbe995ae1d4422803f6fcf3e1cc6077
|
refs/heads/main
| 2023-08-11T23:58:53.617051
| 2021-09-12T15:33:26
| 2021-09-12T15:33:26
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,165
|
py
|
import pytest
from goldcoin.types.peer_info import PeerInfo
from tests.block_tools import BlockTools
from goldcoin.util.ints import uint16
from tests.core.node_height import node_height_at_least
from tests.setup_nodes import self_hostname, setup_full_node, setup_full_system, test_constants
from tests.time_out_assert import time_out_assert
test_constants_modified = test_constants.replace(
**{
"DIFFICULTY_STARTING": 2 ** 8,
"DISCRIMINANT_SIZE_BITS": 1024,
"SUB_EPOCH_BLOCKS": 140,
"WEIGHT_PROOF_THRESHOLD": 2,
"WEIGHT_PROOF_RECENT_BLOCKS": 350,
"MAX_SUB_SLOT_BLOCKS": 50,
"NUM_SPS_SUB_SLOT": 32, # Must be a power of 2
"EPOCH_BLOCKS": 280,
"SUB_SLOT_ITERS_STARTING": 2 ** 20,
"NUMBER_ZERO_BITS_PLOT_FILTER": 5,
}
)
class TestSimulation:
@pytest.fixture(scope="function")
async def extra_node(self):
b_tools = BlockTools(constants=test_constants_modified)
async for _ in setup_full_node(test_constants_modified, "blockchain_test_3.db", 21240, b_tools):
yield _
@pytest.fixture(scope="function")
async def simulation(self):
async for _ in setup_full_system(test_constants_modified):
yield _
@pytest.mark.asyncio
async def test_simulation_1(self, simulation, extra_node):
node1, node2, _, _, _, _, _, _, _, server1 = simulation
await server1.start_client(PeerInfo(self_hostname, uint16(21238)))
# Use node2 to test node communication, since only node1 extends the chain.
await time_out_assert(1500, node_height_at_least, True, node2, 7)
async def has_compact(node1, node2):
peak_height_1 = node1.full_node.blockchain.get_peak_height()
headers_1 = await node1.full_node.blockchain.get_header_blocks_in_range(0, peak_height_1)
peak_height_2 = node2.full_node.blockchain.get_peak_height()
headers_2 = await node2.full_node.blockchain.get_header_blocks_in_range(0, peak_height_2)
# Commented to speed up.
# cc_eos = [False, False]
# icc_eos = [False, False]
# cc_sp = [False, False]
# cc_ip = [False, False]
has_compact = [False, False]
for index, headers in enumerate([headers_1, headers_2]):
for header in headers.values():
for sub_slot in header.finished_sub_slots:
if sub_slot.proofs.challenge_chain_slot_proof.normalized_to_identity:
# cc_eos[index] = True
has_compact[index] = True
if (
sub_slot.proofs.infused_challenge_chain_slot_proof is not None
and sub_slot.proofs.infused_challenge_chain_slot_proof.normalized_to_identity
):
# icc_eos[index] = True
has_compact[index] = True
if (
header.challenge_chain_sp_proof is not None
and header.challenge_chain_sp_proof.normalized_to_identity
):
# cc_sp[index] = True
has_compact[index] = True
if header.challenge_chain_ip_proof.normalized_to_identity:
# cc_ip[index] = True
has_compact[index] = True
# return (
# cc_eos == [True, True] and icc_eos == [True, True] and cc_sp == [True, True] and cc_ip == [True, True]
# )
return has_compact == [True, True]
await time_out_assert(1500, has_compact, True, node1, node2)
node3 = extra_node
server3 = node3.full_node.server
peak_height = max(node1.full_node.blockchain.get_peak_height(), node2.full_node.blockchain.get_peak_height())
await server3.start_client(PeerInfo(self_hostname, uint16(21237)))
await server3.start_client(PeerInfo(self_hostname, uint16(21238)))
await time_out_assert(600, node_height_at_least, True, node3, peak_height)
|
[
"faurepierre78@yahoo.com"
] |
faurepierre78@yahoo.com
|
25964edc220c95004ffd24b272ac7962457a8fe4
|
0baac2c4aa84f65896054043486577b6e08ba9ef
|
/python/257-binaryTree.py
|
055403a0ce48d1fc8161d52f26eb968b284befbe
|
[] |
no_license
|
hy299792458/LeetCode
|
c302983b81151acddffe3a71b03b4aceb20b4fa4
|
bb24717283a6b3ddd463b68cba34f70df75ddfed
|
refs/heads/master
| 2021-01-21T17:01:58.082623
| 2017-09-12T16:49:44
| 2017-09-12T16:49:44
| 91,924,578
| 3
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 672
|
py
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def binaryTreePaths(self, root):
self.re = []
def DFS(root,path):
if root.left == root.right == None:
self.re.append(path + [root.val])
else:
if root.left:
DFS(root.left, path + [root.val])
if root.right:
DFS(root.right, path + [root.val])
if root:
DFS(root, [])
return map(lambda x: '->'.join(map(str, x)), self.re)
|
[
"hy299792458@gmail.com"
] |
hy299792458@gmail.com
|
e3b9d889f720be23cad9a69d505cfc0d1ee141aa
|
edfb435ee89eec4875d6405e2de7afac3b2bc648
|
/tags/selenium-2.0-beta-3/py/test/selenium/webdriver/common/children_finding_tests.py
|
f0ff588cab08890a162d720fadf174538ba0f18c
|
[
"Apache-2.0"
] |
permissive
|
Escobita/selenium
|
6c1c78fcf0fb71604e7b07a3259517048e584037
|
f4173df37a79ab6dd6ae3f1489ae0cd6cc7db6f1
|
refs/heads/master
| 2021-01-23T21:01:17.948880
| 2012-12-06T22:47:50
| 2012-12-06T22:47:50
| 8,271,631
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,205
|
py
|
#!/usr/bin/python
# Copyright 2008-2010 WebDriver committers
# Copyright 2008-2010 Google 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.
import os
import re
import tempfile
import time
import shutil
import unittest
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoSuchFrameException
class ChildrenFindingTests(unittest.TestCase):
def testShouldFindElementByXPath(self):
self._loadPage("nestedElements")
element = self.driver.find_element_by_name("form2")
child = element.find_element_by_xpath("select")
self.assertEqual(child.get_attribute("id"), "2")
def testShouldNotFindElementByXPath(self):
self._loadPage("nestedElements")
element = self.driver.find_element_by_name("form2")
try:
element.find_element_by_xpath("select/x")
self.fail("Expected NoSuchElementException to have been thrown")
except NoSuchElementException, e:
pass
except Exception, e:
self.fail("Expected NoSuchElementException to have been thrown but got " + str(e))
def testShouldFindElementsByXpath(self):
self._loadPage("nestedElements")
element = self.driver.find_element_by_name("form2")
children = element.find_elements_by_xpath("select/option")
self.assertEqual(len(children), 8);
self.assertEqual(children[0].text, "One")
self.assertEqual(children[1].text, "Two")
def testShouldNotFindElementsByXpath(self):
self._loadPage("nestedElements")
element = self.driver.find_element_by_name("form2")
children = element.find_elements_by_xpath("select/x")
self.assertEqual(len(children), 0)
def FindingElementsOnElementByXPathShouldFindTopLevelElements(self):
self._loadSimplePage()
parent = self.driver.find_element_by_id("multiline")
allParaElements = self.driver.find_elements_by_xpath("//p")
children = parent.find_elements_by_xpath("//p")
self.assertEqual(len(allParaElements), len(children))
def testShouldFindElementByName(self):
self._loadPage("nestedElements")
element = self.driver.find_element_by_name("form2")
child = element.find_element_by_name("selectomatic")
self.assertEqual(child.get_attribute("id"), "2")
def testShouldFindElementsByName(self):
self._loadPage("nestedElements")
element = self.driver.find_element_by_name("form2")
children = element.find_elements_by_name("selectomatic")
self.assertEqual(len(children), 2)
def testShouldFindElementById(self):
self._loadPage("nestedElements")
element = self.driver.find_element_by_name("form2")
child = element.find_element_by_id("2")
self.assertEqual(child.get_attribute("name"), "selectomatic")
def testShouldFindElementsById(self):
self._loadPage("nestedElements")
element = self.driver.find_element_by_name("form2")
child = element.find_elements_by_id("2")
self.assertEqual(len(child), 2)
def testShouldFindElementByIdWhenMultipleMatchesExist(self):
self._loadPage("nestedElements")
element = self.driver.find_element_by_id("test_id_div")
child = element.find_element_by_id("test_id")
self.assertEqual(child.text, "inside")
def testShouldFindElementByIdWhenNoMatchInContext(self):
self._loadPage("nestedElements")
element = self.driver.find_element_by_id("test_id_div")
try:
element.find_element_by_id("test_id_out")
self.Fail("Expected NoSuchElementException to have been thrown")
except NoSuchElementException, e:
pass
except Exception, e:
self.Fail("Expected NoSuchElementException to have been thrown but got " + str(e))
def testShouldFindElementByLinkText(self):
self._loadPage("nestedElements")
element = self.driver.find_element_by_name("div1")
child = element.find_element_by_link_text("hello world")
self.assertEqual(child.get_attribute("name"), "link1")
def testShouldFindElementByLinkText(self):
self._loadPage("nestedElements")
element = self.driver.find_element_by_name("div1")
children = element.find_elements_by_link_text("hello world")
self.assertEqual(len(children), 2)
def testShouldFindElementByClassName(self):
self._loadPage("nestedElements")
parent = self.driver.find_element_by_name("classes")
element = parent.find_element_by_class_name("one")
self.assertEqual("Find me", element.text)
def testShouldFindElementsByClassName(self):
self._loadPage("nestedElements")
parent = self.driver.find_element_by_name("classes")
elements = parent.find_elements_by_class_name("one")
self.assertEqual(2, len(elements))
def testShouldFindElementByTagName(self):
self._loadPage("nestedElements")
parent = self.driver.find_element_by_name("div1")
element = parent.find_element_by_tag_name("a")
self.assertEqual("link1", element.get_attribute("name"))
def testShouldFindElementsByTagName(self):
self._loadPage("nestedElements")
parent = self.driver.find_element_by_name("div1")
elements = parent.find_elements_by_tag_name("a")
self.assertEqual(2, len(elements))
def _pageURL(self, name):
return "http://localhost:%d/%s.html" % (self.webserver.port, name)
def _loadSimplePage(self):
self._loadPage("simpleTest")
def _loadPage(self, name):
self.driver.get(self._pageURL(name))
|
[
"simon.m.stewart@07704840-8298-11de-bf8c-fd130f914ac9"
] |
simon.m.stewart@07704840-8298-11de-bf8c-fd130f914ac9
|
35b8fad1bb1071613fe56f28618735be9dffbce5
|
6b9084d234c87d7597f97ec95808e13f599bf9a1
|
/models/TransT/variants/pvt_variant/network.py
|
94f771b0903e048e8623af1830ee9828453853d2
|
[] |
no_license
|
LitingLin/ubiquitous-happiness
|
4b46234ce0cb29c4d27b00ec5a60d3eeb52c26fc
|
aae2d764e136ca4a36c054212b361dd7e8b22cba
|
refs/heads/main
| 2023-07-13T19:51:32.227633
| 2021-08-03T16:02:03
| 2021-08-03T16:02:03
| 316,664,903
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,472
|
py
|
import torch
import torch.nn as nn
def _get_single_scale(feat):
if isinstance(feat, (list, tuple)):
assert len(feat) == 1
feat = feat[0]
return feat
class PVTFeatureFusionNetwork(nn.Module):
def __init__(self, backbone, transformer, head,
transformer_hidden_dim, enable_input_projection,
template_output_stage, template_output_dim, template_output_shape,
search_output_stage, search_output_dim, search_output_shape):
super(PVTFeatureFusionNetwork, self).__init__()
self.backbone = backbone
self.transformer = transformer
self.head = head
self.template_output_stage = template_output_stage
self.template_output_shape = template_output_shape[1], template_output_shape[0] # H, W
self.search_output_stage = search_output_stage
self.search_output_shape = search_output_shape[1], search_output_shape[0] # H, W
self.template_input_projection = None
self.search_input_projection = None
if enable_input_projection:
self.template_input_projection = nn.Linear(template_output_dim, transformer_hidden_dim)
self.search_input_projection = nn.Linear(search_output_dim, transformer_hidden_dim)
nn.init.xavier_uniform_(self.template_input_projection.weight)
nn.init.xavier_uniform_(self.search_input_projection.weight)
def _forward_feat(self, x, output_stage, input_projection):
x = _get_single_scale(self.backbone(x, (output_stage,), False))
if input_projection is not None:
x = input_projection(x)
return x
def forward(self, z, x):
z_feat = self._forward_feat(z, self.template_output_stage, self.template_input_projection)
x_feat = self._forward_feat(x, self.search_output_stage, self.search_input_projection)
feat = self.transformer(z_feat, x_feat, *self.template_output_shape, *self.search_output_shape)
return self.head(feat.unsqueeze(0))
@torch.no_grad()
def template(self, z):
return self._forward_feat(z, self.template_output_stage, self.template_input_projection)
@torch.no_grad()
def track(self, z_feat, x):
x_feat = self._forward_feat(x, self.search_output_stage, self.search_input_projection)
feat = self.transformer(z_feat, x_feat, *self.template_output_shape, *self.search_output_shape)
return self.head(feat.unsqueeze(0))
|
[
"linliting06@live.com"
] |
linliting06@live.com
|
6f0e28490cd886a03f99cc71aa0351c98825ad0a
|
a6e4a6f0a73d24a6ba957277899adbd9b84bd594
|
/sdk/python/pulumi_azure_native/management/v20171101preview/get_management_group.py
|
c098e353012344ab7443b776bd5a168f08338890
|
[
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
MisinformedDNA/pulumi-azure-native
|
9cbd75306e9c8f92abc25be3f73c113cb93865e9
|
de974fd984f7e98649951dbe80b4fc0603d03356
|
refs/heads/master
| 2023-03-24T22:02:03.842935
| 2021-03-08T21:16:19
| 2021-03-08T21:16:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,338
|
py
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
__all__ = [
'GetManagementGroupResult',
'AwaitableGetManagementGroupResult',
'get_management_group',
]
@pulumi.output_type
class GetManagementGroupResult:
"""
The management group details.
"""
def __init__(__self__, children=None, details=None, display_name=None, id=None, name=None, tenant_id=None, type=None):
if children and not isinstance(children, list):
raise TypeError("Expected argument 'children' to be a list")
pulumi.set(__self__, "children", children)
if details and not isinstance(details, dict):
raise TypeError("Expected argument 'details' to be a dict")
pulumi.set(__self__, "details", details)
if display_name and not isinstance(display_name, str):
raise TypeError("Expected argument 'display_name' to be a str")
pulumi.set(__self__, "display_name", display_name)
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if tenant_id and not isinstance(tenant_id, str):
raise TypeError("Expected argument 'tenant_id' to be a str")
pulumi.set(__self__, "tenant_id", tenant_id)
if type and not isinstance(type, str):
raise TypeError("Expected argument 'type' to be a str")
pulumi.set(__self__, "type", type)
@property
@pulumi.getter
def children(self) -> Optional[Sequence['outputs.ManagementGroupChildInfoResponse']]:
"""
The list of children.
"""
return pulumi.get(self, "children")
@property
@pulumi.getter
def details(self) -> Optional['outputs.ManagementGroupDetailsResponse']:
"""
The details of a management group.
"""
return pulumi.get(self, "details")
@property
@pulumi.getter(name="displayName")
def display_name(self) -> Optional[str]:
"""
The friendly name of the management group.
"""
return pulumi.get(self, "display_name")
@property
@pulumi.getter
def id(self) -> str:
"""
The fully qualified ID for the management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000
"""
return pulumi.get(self, "id")
@property
@pulumi.getter
def name(self) -> str:
"""
The name of the management group. For example, 00000000-0000-0000-0000-000000000000
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="tenantId")
def tenant_id(self) -> Optional[str]:
"""
The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000
"""
return pulumi.get(self, "tenant_id")
@property
@pulumi.getter
def type(self) -> str:
"""
The type of the resource. For example, /providers/Microsoft.Management/managementGroups
"""
return pulumi.get(self, "type")
class AwaitableGetManagementGroupResult(GetManagementGroupResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetManagementGroupResult(
children=self.children,
details=self.details,
display_name=self.display_name,
id=self.id,
name=self.name,
tenant_id=self.tenant_id,
type=self.type)
def get_management_group(expand: Optional[str] = None,
group_id: Optional[str] = None,
recurse: Optional[bool] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetManagementGroupResult:
"""
The management group details.
:param str expand: The $expand=children query string parameter allows clients to request inclusion of children in the response payload.
:param str group_id: Management Group ID.
:param bool recurse: The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload.
"""
__args__ = dict()
__args__['expand'] = expand
__args__['groupId'] = group_id
__args__['recurse'] = recurse
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-native:management/v20171101preview:getManagementGroup', __args__, opts=opts, typ=GetManagementGroupResult).value
return AwaitableGetManagementGroupResult(
children=__ret__.children,
details=__ret__.details,
display_name=__ret__.display_name,
id=__ret__.id,
name=__ret__.name,
tenant_id=__ret__.tenant_id,
type=__ret__.type)
|
[
"noreply@github.com"
] |
MisinformedDNA.noreply@github.com
|
106f06f8c9ccb5d0b6bbaf7b92803d75acdbb60c
|
422faa17d37d453fc5a9b5a05854f144c90c0477
|
/tests/test_general.py
|
9a6e97a00ee7a608bac542ac8f21b69817781f2f
|
[
"MIT"
] |
permissive
|
ArtellaPipe/artellapipe-tools-playblastmanager
|
71ae722425c33040770de00be295ecc9b1674765
|
05f1647b6b3b367c9ba9d5e8978cf32b5823f819
|
refs/heads/master
| 2020-08-03T01:14:20.291644
| 2020-05-04T02:00:53
| 2020-05-04T02:00:53
| 211,578,868
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 264
|
py
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains general tests for artellapipe-tools-playblastmanager
"""
import pytest
from artellapipe.tools.playblastmanager import __version__
def test_version():
assert __version__.get_version()
|
[
"tpovedatd@gmail.com"
] |
tpovedatd@gmail.com
|
11074d328013b09d059a18ca498387b2322d0959
|
acaa1e54cf7963560b1ffe2c84136767f266d928
|
/luxPlugin/Lux/LuxNodes/ShaderNodes/arealightShader.py
|
23577a4a29e604d7a5d9fc8dd4d6c0d85e069563
|
[] |
no_license
|
LuxRender/LuxMaya
|
c019deba3c284d691f75dfbf2caed3b2418828b9
|
3891e40c3c4c3a054e5ff1ff16d051d4e690cc4a
|
refs/heads/master
| 2021-01-01T02:25:32.792668
| 2014-04-09T12:06:04
| 2014-04-09T12:06:04
| 239,139,345
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,526
|
py
|
# ------------------------------------------------------------------------------
# Lux material shader node for Maya
#
# by Doug Hammond 05/2008
#
# This file is licensed under the GPL
# http://www.gnu.org/licenses/gpl-3.0.txt
#
# $Id$
#
# ------------------------------------------------------------------------------
#
# Lux material shader node for Maya ( arealight attributes )
#
# ------------------------------------------------------------------------------
from maya import OpenMaya
from maya import OpenMayaMPx
from Lux.LuxNodes.ShaderNode import ShaderNode
class arealightShader(OpenMayaMPx.MPxNode, ShaderNode):
"""
AreaLight fragment of luxshader
"""
# arealight
L = OpenMaya.MObject() # color
gain = OpenMaya.MObject()
numsamples = OpenMaya.MObject()
lightGroup = OpenMaya.MObject()
def __init__(self):
OpenMayaMPx.MPxNode.__init__(self)
@staticmethod
def shaderInitializer():
try:
# color
arealightShader.L = arealightShader.makeColor("arealightL", "all")
arealightShader.gain = arealightShader.makeFloat("arealightGain","aga", 1.0)
arealightShader.numsamples = arealightShader.makeInteger("arealightNumsamples", "ans", 1)
arealightShader.lightGroup = arealightShader.makeString('arealightGroup', "alg", "default")
except:
OpenMaya.MGlobal.displayError("Failed to create arealight attributes\n")
raise
|
[
"devnull@localhost"
] |
devnull@localhost
|
1a3467126afd0d06ecc949e651ef026e823f9635
|
55d560fe6678a3edc9232ef14de8fafd7b7ece12
|
/libs/python/test/wrapper_held_type.py
|
5beb657e5fe8805cc00c6e996467e1a764b6ae9b
|
[
"BSL-1.0"
] |
permissive
|
stardog-union/boost
|
ec3abeeef1b45389228df031bf25b470d3d123c5
|
caa4a540db892caa92e5346e0094c63dea51cbfb
|
refs/heads/stardog/develop
| 2021-06-25T02:15:10.697006
| 2020-11-17T19:50:35
| 2020-11-17T19:50:35
| 148,681,713
| 0
| 0
|
BSL-1.0
| 2020-11-17T19:50:36
| 2018-09-13T18:38:54
|
C++
|
UTF-8
|
Python
| false
| false
| 740
|
py
|
# Copyright David Abrahams 2005. Distributed under the Boost
# Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
'''
>>> from wrapper_held_type_ext import *
>>> d = data()
>>> print(d.id())
42
>>> do_nothing( d )
>>> print(d.id())
42
>>> d = create_data()
>>> print(d.id())
42
>>> do_nothing( d )
>>> print(d.id())
42
'''
def run(args = None):
import sys
import doctest
if args is not None:
sys.argv = args
return doctest.testmod(sys.modules.get(__name__))
if __name__ == '__main__':
print("running...")
import sys
status = run()[0]
if (status == 0): print("Done.")
sys.exit(status)
|
[
"james.pack@stardog.com"
] |
james.pack@stardog.com
|
369057547a5b566698c0b19db73582f98621b00b
|
010215c1421f5275a846e7154189b22cdd3c89bc
|
/Misc/Data Structures/Tree/InOrderSucessor.py
|
c94e331a5097ff35d1f5ae308ec5f29381d89ff6
|
[] |
no_license
|
bsextion/CodingPractice_Py
|
ab54d5715298645a8fd7ab6945bf3b22d4e6a874
|
da2847a04705394c32a6fe1b5f6c6b64c24647a3
|
refs/heads/master
| 2023-08-16T17:14:47.643989
| 2021-09-28T19:23:40
| 2021-09-28T19:23:40
| 383,658,966
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 356
|
py
|
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorder_successor_bst(root, d):
list = inorder_successor_bst(root.left)
list.append(root.val)
list = inorder_successor_bst(root.right)
return list
inorder_successor_bst()
|
[
"bsextion@gmail.com"
] |
bsextion@gmail.com
|
8c3da2993bf4a417d5a34fbbd066b1711d95ab47
|
c4249ce9e7cb26ae006bc9951ea676ae2250777b
|
/gamslib/nemhaus/nemhaus-scalar.py
|
e2fafab032c25e83f003bf558a9659f2b3d2ede0
|
[] |
no_license
|
vaidasj/alg-mod-rev
|
79de3ef1e110f4bd07cbdef6951de2e4216f47f1
|
a3ec6b5c21700a2f28ac6bf7db6aa22540748c6e
|
refs/heads/master
| 2021-06-27T14:06:39.997411
| 2020-10-19T15:47:54
| 2020-10-19T15:47:54
| 180,074,989
| 3
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,629
|
py
|
# MIP written by GAMS Convert at 12/13/18 10:32:18
#
# Equation counts
# Total E G L N X C B
# 42 6 36 0 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc si
# Total cont binary integer sos1 sos2 scont sint
# 57 37 20 0 0 0 0 0
# FX 0 0 0 0 0 0 0 0
#
# Nonzero counts
# Total const NL DLL
# 165 165 0 0
#
# Reformulation has removed 1 variable and 1 equation
from pyomo.environ import *
model = m = ConcreteModel()
m.x2 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x3 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x4 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x5 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x6 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x7 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x8 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x9 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x10 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x11 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x12 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x13 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x14 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x15 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x16 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x17 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x18 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x19 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x20 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x21 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x22 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x23 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x24 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x25 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x26 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x27 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x28 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x29 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x30 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x31 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x32 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x33 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x34 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x35 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x36 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x37 = Var(within=Reals,bounds=(0,None),initialize=0)
m.b38 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b39 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b40 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b41 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b42 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b43 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b44 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b45 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b46 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b47 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b48 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b49 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b50 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b51 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b52 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b53 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b54 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b55 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b56 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b57 = Var(within=Binary,bounds=(0,1),initialize=0)
m.obj = Objective(expr= 2*m.x2 + 4*m.x3 + 3*m.x4 + 2*m.x5 + 4*m.x6 + 3*m.x7 + 2*m.x8 + 4*m.x9 + 3*m.x10 + 2*m.x11
+ 4*m.x12 + 3*m.x13 + 6*m.x14 + 2*m.x15 + 3*m.x16 + 6*m.x17 + 2*m.x18 + 3*m.x19 + 6*m.x20
+ 2*m.x21 + 3*m.x22 + 6*m.x23 + 2*m.x24 + 3*m.x25 + 5*m.x26 + 3*m.x27 + 5*m.x28 + 3*m.x29
+ 5*m.x30 + 3*m.x31 + 5*m.x32 + 3*m.x33 + 3*m.x34 + 3*m.x35 + 3*m.x36 + 3*m.x37, sense=minimize)
m.c2 = Constraint(expr= m.b38 + m.b39 + m.b40 + m.b41 == 1)
m.c3 = Constraint(expr= m.b42 + m.b43 + m.b44 + m.b45 == 1)
m.c4 = Constraint(expr= m.b46 + m.b47 + m.b48 + m.b49 == 1)
m.c5 = Constraint(expr= m.b50 + m.b51 + m.b52 + m.b53 == 1)
m.c6 = Constraint(expr= m.b54 + m.b55 + m.b56 + m.b57 == 1)
m.c7 = Constraint(expr= m.x2 - m.b38 - m.b46 >= -1)
m.c8 = Constraint(expr= m.x3 - m.b38 - m.b50 >= -1)
m.c9 = Constraint(expr= m.x4 - m.b38 - m.b54 >= -1)
m.c10 = Constraint(expr= m.x5 - m.b39 - m.b47 >= -1)
m.c11 = Constraint(expr= m.x6 - m.b39 - m.b51 >= -1)
m.c12 = Constraint(expr= m.x7 - m.b39 - m.b55 >= -1)
m.c13 = Constraint(expr= m.x8 - m.b40 - m.b48 >= -1)
m.c14 = Constraint(expr= m.x9 - m.b40 - m.b52 >= -1)
m.c15 = Constraint(expr= m.x10 - m.b40 - m.b56 >= -1)
m.c16 = Constraint(expr= m.x11 - m.b41 - m.b49 >= -1)
m.c17 = Constraint(expr= m.x12 - m.b41 - m.b53 >= -1)
m.c18 = Constraint(expr= m.x13 - m.b41 - m.b57 >= -1)
m.c19 = Constraint(expr= m.x14 - m.b42 - m.b46 >= -1)
m.c20 = Constraint(expr= m.x15 - m.b42 - m.b50 >= -1)
m.c21 = Constraint(expr= m.x16 - m.b42 - m.b54 >= -1)
m.c22 = Constraint(expr= m.x17 - m.b43 - m.b47 >= -1)
m.c23 = Constraint(expr= m.x18 - m.b43 - m.b51 >= -1)
m.c24 = Constraint(expr= m.x19 - m.b43 - m.b55 >= -1)
m.c25 = Constraint(expr= m.x20 - m.b44 - m.b48 >= -1)
m.c26 = Constraint(expr= m.x21 - m.b44 - m.b52 >= -1)
m.c27 = Constraint(expr= m.x22 - m.b44 - m.b56 >= -1)
m.c28 = Constraint(expr= m.x23 - m.b45 - m.b49 >= -1)
m.c29 = Constraint(expr= m.x24 - m.b45 - m.b53 >= -1)
m.c30 = Constraint(expr= m.x25 - m.b45 - m.b57 >= -1)
m.c31 = Constraint(expr= m.x26 - m.b46 - m.b50 >= -1)
m.c32 = Constraint(expr= m.x27 - m.b46 - m.b54 >= -1)
m.c33 = Constraint(expr= m.x28 - m.b47 - m.b51 >= -1)
m.c34 = Constraint(expr= m.x29 - m.b47 - m.b55 >= -1)
m.c35 = Constraint(expr= m.x30 - m.b48 - m.b52 >= -1)
m.c36 = Constraint(expr= m.x31 - m.b48 - m.b56 >= -1)
m.c37 = Constraint(expr= m.x32 - m.b49 - m.b53 >= -1)
m.c38 = Constraint(expr= m.x33 - m.b49 - m.b57 >= -1)
m.c39 = Constraint(expr= m.x34 - m.b50 - m.b54 >= -1)
m.c40 = Constraint(expr= m.x35 - m.b51 - m.b55 >= -1)
m.c41 = Constraint(expr= m.x36 - m.b52 - m.b56 >= -1)
m.c42 = Constraint(expr= m.x37 - m.b53 - m.b57 >= -1)
|
[
"v.jusevicius@gmail.com"
] |
v.jusevicius@gmail.com
|
abf75a6d88c345fc7b3aee14aaf48dc58804f6d2
|
d1c427249d1161c1f4f848e1de23d95c03ae40a3
|
/28_Paymentprofile_id_staging.py
|
6cb31265aecbbf31def67f0641571b8a566b21d4
|
[] |
no_license
|
Sangee2610/pythonscripts_march1
|
94b80ab3b037793022d114d7cd3604d69ba82147
|
2fb224fc0753beb3d65d873f658cdae247425cf1
|
refs/heads/master
| 2020-04-26T05:03:00.998024
| 2019-03-01T15:07:46
| 2019-03-01T15:07:46
| 173,321,199
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 674
|
py
|
import psycopg2
import config as cfg
conn = cfg.DATABASE_CONNECT
cur = conn.cursor()
import csv
import pandas as pd
import numpy as np
cur.execute("""
DROP TABLE IF EXISTS prd_Staging_Paymentprofile_Id;
CREATE TABLE prd_Staging_Paymentprofile_Id as
SELECT
(CASE WHEN directdebitkey = '' then NULL else cast(CAST(directdebitkey as FLOAT) as INT) END) as directdebitkey,
(CASE WHEN PaymentProfileKey = '' then NULL else cast(CAST(PaymentProfileKey as FLOAT) as INT) END) as PaymentProfileKey,
Id,
(CASE WHEN ContactKey = '' then NULL else cast(CAST(ContactKey as FLOAT) as INT) END) as ContactKey,
Contact
FROM prd_Landing_Paymentprofile_Id
""")
conn.commit()
conn.close()
|
[
"noreply@github.com"
] |
Sangee2610.noreply@github.com
|
7f9c4842c03b353925d9c9584a7d99ea198f1fd7
|
004ed43634f98ada91ce6f19ccfa26146bcac9f3
|
/137.py
|
3c803cd9ba6e6e62023064f539b951045f07b176
|
[] |
no_license
|
tusonggao/leetcode
|
490120028ccd1c33759fae5f7c2bc4cf820fab99
|
86be81f3df0d93bd676265211ccd1b29251c2824
|
refs/heads/master
| 2020-03-27T05:23:04.634426
| 2018-11-22T14:36:50
| 2018-11-22T14:36:50
| 146,014,483
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 965
|
py
|
#使用O(n)空间的解法1
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
s = sum(set(nums)) * 3
ans = (s - sum(nums))//2
return ans
#使用O(n)空间的解法2
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
from collections import Counter
counter = Counter(nums)
for val, num in counter.items():
if num != 3:
return val
#使用O(1)空间的解法1
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = 0
for i in range(32):
count = 0
for j in nums:
count += (j>>i) & 1
count %= 3
result |= count<<i
return int(result)
|
[
"tusonggao@163.com"
] |
tusonggao@163.com
|
059c47aad0c952917bc35d44b45e7a956c3726f0
|
eb93a40dd29f8f6b72d2e7bbc375c226e6dc78c7
|
/02_Arrays_in_Numpy/5.3_Indizierung.py
|
8b576d3b57eecb304312633160e4ad5b8e27b079
|
[
"MIT"
] |
permissive
|
felixdittrich92/numerisches_python
|
ac789a4b19da1b6566ef149c52ffbcb97e60db25
|
0f895ee19b4fa3cf7ad38cd3dfe3cd7020ee34a7
|
refs/heads/master
| 2020-12-01T18:41:30.269530
| 2020-01-13T15:45:44
| 2020-01-13T15:45:44
| 230,732,215
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,975
|
py
|
import numpy as np
print("--------------------------------------")
print("eindimensionale Arrays indizieren")
print("--------------------------------------")
F = np.array([1, 1, 2, 3, 5, 8, 13, 21])
# Ausgabe erstes Element
print(F[0])
# Ausgabe letzes Element
print(F[-1])
S = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
print(S[2:5])
print(S[:4])
print(S[6:])
print(S[:])
print("--------------------------------------")
print("Mehrdimensionale Arrays indizieren")
print("--------------------------------------")
# Spalte
# 0 1 2
A = np.array([[3.4, 5.7, -3.2], # 0
[1.1, -3.8, 7.7], # 1 Zeile
[2.2, 5.9, -1.0]]) # 2
# [Zeile][Spalte]
print(A[1][2])
# komplette Zeile
print(A[1])
# Position : [0, 1][0, 1]
# Spalte
# 0 1
B = np.array([ [[111, 112], [121, 122]], # 0
[[211, 212], [221, 222]], # 1 Zeile
[[311, 312], [321, 322]] ]) # 2
# [Zeile][Spalte][Position]
print(B[1][1][1])
print("--------------------------------------")
print("Mehrdimensionale Arrays indizieren")
print(" Teilbereichoperator")
print("--------------------------------------")
A = np.array([
[11, 12, 13, 14, 15],
[21, 22, 23, 24, 25],
[31, 32, 33, 34, 35],
[41, 42, 43, 44, 45],
[51, 52, 53, 54, 55] ])
# [start:stop:step]
# Spalte , Zeile von(inklusive) : bis(exklusive)
print(A[:3, 2:])
print("------------------")
print(A[3:,:])
print("------------------")
print(A[:, 4:])
print("------------------")
X = np.arange(28).reshape(4, 7)
print(X)
print("------------------")
print(X[::2, ::3])
print("------------------")
print(X[::, ::3])
print("------------------")
# dreidimensionales Array
A = np.array([ [ [45, 12, 4], [45, 13, 5], [46, 12, 6] ],
[ [46, 14, 4], [45, 14, 5], [46, 11, 5] ],
[ [47, 13, 2], [48, 15, 5], [46, 15, 1] ], ])
print(A[1:3, 0:2, :])
|
[
"you@example.com"
] |
you@example.com
|
cd2cf9f275c063541c25fbac765f7c8469b29af8
|
163bbb4e0920dedd5941e3edfb2d8706ba75627d
|
/Code/CodeRecords/2922/61020/315606.py
|
36b9d2abe54aaeb1adafe1950c49c73cccc9b584
|
[] |
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
| 206
|
py
|
n=int(input())
a=[int(x) for x in input().split()]
a=list(set(a))
a.sort()
if len(a)>3:
print("NO")
else:
if len(a)==3 and 2*a[1]!=a[0]+a[2]:
print("NO")
else:
print("YES")
|
[
"1069583789@qq.com"
] |
1069583789@qq.com
|
fc3d484eaf43c149b9bc4c394e98539e429435ff
|
81b20a9c51779c21b779ac0b1c5bf669359521ef
|
/py_object_detection/tf_api/object_detection/builders/box_coder_builder.py
|
a68bc0bba4d9538894ee1ba887e14d4f72a804dc
|
[] |
no_license
|
thekindler/py-object-detection
|
bae1401f025458605c9244f9a763e17a0138d2ec
|
a8d13c496bab392ef5c8ad91a20fbfa9af1899bb
|
refs/heads/master
| 2023-06-23T02:42:08.180311
| 2021-07-17T18:40:46
| 2021-07-17T18:40:46
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,897
|
py
|
# Copyright 2017 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.
# ==============================================================================
"""A function to build an object detection box coder from configuration."""
from py_object_detection.tf_api.object_detection.box_coders import mean_stddev_box_coder, faster_rcnn_box_coder, \
keypoint_box_coder
from py_object_detection.tf_api.object_detection.box_coders import square_box_coder
from py_object_detection.tf_api.object_detection.protos import box_coder_pb2
def build(box_coder_config):
"""Builds a box coder object based on the box coder config.
Args:
box_coder_config: A box_coder.proto object containing the config for the
desired box coder.
Returns:
BoxCoder based on the config.
Raises:
ValueError: On empty box coder proto.
"""
if not isinstance(box_coder_config, box_coder_pb2.BoxCoder):
raise ValueError('box_coder_config not of type box_coder_pb2.BoxCoder.')
if box_coder_config.WhichOneof('box_coder_oneof') == 'faster_rcnn_box_coder':
return faster_rcnn_box_coder.FasterRcnnBoxCoder(scale_factors=[
box_coder_config.faster_rcnn_box_coder.y_scale,
box_coder_config.faster_rcnn_box_coder.x_scale,
box_coder_config.faster_rcnn_box_coder.height_scale,
box_coder_config.faster_rcnn_box_coder.width_scale
])
if box_coder_config.WhichOneof('box_coder_oneof') == 'keypoint_box_coder':
return keypoint_box_coder.KeypointBoxCoder(
box_coder_config.keypoint_box_coder.num_keypoints,
scale_factors=[
box_coder_config.keypoint_box_coder.y_scale,
box_coder_config.keypoint_box_coder.x_scale,
box_coder_config.keypoint_box_coder.height_scale,
box_coder_config.keypoint_box_coder.width_scale
])
if (box_coder_config.WhichOneof('box_coder_oneof') ==
'mean_stddev_box_coder'):
return mean_stddev_box_coder.MeanStddevBoxCoder(
stddev=box_coder_config.mean_stddev_box_coder.stddev)
if box_coder_config.WhichOneof('box_coder_oneof') == 'square_box_coder':
return square_box_coder.SquareBoxCoder(scale_factors=[
box_coder_config.square_box_coder.y_scale,
box_coder_config.square_box_coder.x_scale,
box_coder_config.square_box_coder.length_scale
])
raise ValueError('Empty box coder.')
|
[
"uniquetrij@gmail.com"
] |
uniquetrij@gmail.com
|
3c42c9c5c4d05db796df9b1dbcd44d792c7c20c4
|
0faf042dafd21547e00a872f636298217f03ae7a
|
/setup.py
|
fa19c6ca95866fbd2ef029f241fa04d712d2ce6f
|
[
"MIT"
] |
permissive
|
thonra/acb.py
|
46a82ef4fa5ac4dfddb4b0e7870d99c0901fd54f
|
07b541b7febe2723d2479b53e9a138537ac039ce
|
refs/heads/master
| 2023-03-05T14:41:02.043840
| 2021-02-11T02:11:12
| 2021-02-11T02:11:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 300
|
py
|
import sys
from setuptools import setup, Extension
def main():
args = dict(
ext_modules=[
Extension(
"_acb_speedup", sources=["fast_sub/module.c"], py_limited_api=True
)
],
)
setup(**args)
if __name__ == "__main__":
main()
|
[
"summertriangle.dev@gmail.com"
] |
summertriangle.dev@gmail.com
|
f96f04496e819e172c6148e5e68b01f4b46af114
|
51ecea4fc3409cc2c2c9b2547ebefb3cae42ef87
|
/backend/chat/models.py
|
d83f538a9407b5e5d2ae0591fa29b4ced7d18cb4
|
[] |
no_license
|
crowdbotics-apps/binge-watch-28251
|
e2b8e7f711258afa3f04530c4a376e14fb71ad9b
|
a747c11de008eac81032e1aafa65b73914588eb7
|
refs/heads/master
| 2023-05-31T11:38:46.201806
| 2021-06-27T07:30:19
| 2021-06-27T07:30:19
| 380,675,252
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,152
|
py
|
from django.conf import settings
from django.db import models
class Thread(models.Model):
"Generated Model"
name = models.CharField(
max_length=255,
)
thread_photo = models.URLField()
timestamp_created = models.DateTimeField(
auto_now_add=True,
)
class ThreadMember(models.Model):
"Generated Model"
profile = models.ForeignKey(
"chat_user_profile.Profile",
on_delete=models.CASCADE,
related_name="threadmember_profile",
)
thread = models.ForeignKey(
"chat.Thread",
on_delete=models.CASCADE,
related_name="threadmember_thread",
)
is_admin = models.BooleanField()
timestamp_joined = models.DateTimeField(
auto_now_add=True,
)
timestamp_left = models.DateTimeField()
last_rejoined = models.DateTimeField()
class MessageAction(models.Model):
"Generated Model"
action = models.CharField(
max_length=7,
)
message = models.ForeignKey(
"chat.Message",
on_delete=models.CASCADE,
related_name="messageaction_message",
)
profile = models.ForeignKey(
"chat_user_profile.Profile",
on_delete=models.CASCADE,
related_name="messageaction_profile",
)
timestamp_action = models.DateTimeField(
auto_now_add=True,
)
class ThreadAction(models.Model):
"Generated Model"
action = models.CharField(
max_length=7,
)
thread = models.ForeignKey(
"chat.Thread",
on_delete=models.CASCADE,
related_name="threadaction_thread",
)
profile = models.ForeignKey(
"chat_user_profile.Profile",
on_delete=models.CASCADE,
related_name="threadaction_profile",
)
timestamp_action = models.DateTimeField(
auto_now_add=True,
)
class ForwardedMessage(models.Model):
"Generated Model"
message = models.ForeignKey(
"chat.Message",
on_delete=models.CASCADE,
related_name="forwardedmessage_message",
)
forwarded_by = models.ForeignKey(
"chat_user_profile.Profile",
on_delete=models.CASCADE,
related_name="forwardedmessage_forwarded_by",
)
forwarded_to = models.ForeignKey(
"chat.Thread",
on_delete=models.CASCADE,
related_name="forwardedmessage_forwarded_to",
)
timestamp_forwarded = models.DateTimeField(
auto_now_add=True,
)
class Message(models.Model):
"Generated Model"
message = models.TextField()
thread = models.ForeignKey(
"chat.Thread",
on_delete=models.CASCADE,
related_name="message_thread",
)
sent_by = models.ForeignKey(
"chat.ThreadMember",
on_delete=models.CASCADE,
related_name="message_sent_by",
)
attachment = models.URLField()
is_draft = models.BooleanField()
is_delivered = models.BooleanField()
is_read = models.BooleanField()
timestamp_created = models.DateTimeField(
auto_now_add=True,
)
timestamp_delivered = models.DateTimeField()
timestamp_read = models.DateTimeField()
# Create your models here.
|
[
"team@crowdbotics.com"
] |
team@crowdbotics.com
|
51223964a1071ee1dbf12ed363ebed058c2eb870
|
6a302928aad4cbb5d86c8bbcabded1f03a157adc
|
/Ensemble_Methods/bagging_classification.py
|
17d3a54b90d23066b4e3bea1dbb0d1f8cfdf2402
|
[] |
no_license
|
IvanRado/AI
|
c905a2c1d566777869405f371611c1bd9690d7e4
|
9c9d5cee02b18778e9a417de3e9ad07c0a1fd6c4
|
refs/heads/master
| 2020-12-08T06:51:45.766263
| 2020-06-20T23:41:16
| 2020-06-20T23:41:16
| 232,917,389
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,143
|
py
|
import numpy as np
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier
from sklearn.utils import shuffle
def plot_decision_boundary(X, model):
h = .02 # step size in the mesh
# create a mesh to plot in
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
# Plot the decision boundary. For that, we will assign a color to each
# point in the mesh [x_min, m_max]x[y_min, y_max].
Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.contour(xx, yy, Z, cmap=plt.cm.Paired)
np.random.seed(10)
N = 500
D = 2
X = np.random.randn(N,D)
sep = 2
X[:125] += np.array([sep, sep])
X[125:250] += np.array([sep, -sep])
X[250:375] += np.array([-sep, -sep])
X[375:] += np.array([-sep, sep])
Y = np.array([0]*125 + [1]*125 + [0]*125 + [1]*125 )
plt.scatter(X[:,0], X[:,1], s=100, c = Y, alpha = 0.5)
plt.show()
model = DecisionTreeClassifier()
model.fit(X, Y)
print("Score for 1 tree:", model.score(X,Y))
plt.scatter(X[:,0], X[:,1], s=100, c = Y, alpha=0.5)
plot_decision_boundary(X, model)
plt.show()
class BaggedTreeClassifier():
def __init__(self, B):
self.B = B
def fit(self, X, Y):
N = len(X)
self.models = []
for b in range(self.B):
idx = np.random.choice(N, size=N, replace = True)
Xb = X[idx]
Yb = Y[idx]
model = DecisionTreeClassifier(max_depth=2)
model.fit(Xb,Yb)
self.models.append(model)
def predict(self, X):
predictions = np.zeros(len(X))
for model in self.models:
predictions += model.predict(X)
return np.round(predictions / self.B)
def score(self, X, Y):
P = self.predict(X)
return np.mean(Y == P)
model = BaggedTreeClassifier(200)
model.fit(X,Y)
print("Score for bagged model:", model.score(X,Y))
plt.scatter(X[:,0], X[:,1], s=100, c = Y, alpha=0.5)
plot_decision_boundary(X, model)
plt.show()
|
[
"ivanradovicc@gmail.com"
] |
ivanradovicc@gmail.com
|
fc178c151c60fb7c502343b672b87caf93bd859b
|
9c0cae2af1111529cde36f57021751d576537f9f
|
/edxmarketo/urls.py
|
66f451fa9e36f2eda7fa65363c1eebc0d157fda0
|
[] |
no_license
|
ISCLC/edxmarketo
|
425ccc3aeafac3d3d319bda96ddab6973cefdeda
|
7d3223b9dad6b93863eed515c8b2e45b1133d6db
|
refs/heads/master
| 2021-01-21T06:02:19.749558
| 2016-04-06T00:12:53
| 2016-04-06T00:12:53
| 43,975,976
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 297
|
py
|
from django.conf.urls import url
from django.conf import settings
urlpatterns = [
url(r'^marketo_course_access$', 'edxmarketo.views.set_marketo_course_access_date'),
]
if settings.DEBUG:
urlpatterns += [
url(r'^marketo_test$', 'edxmarketo.views.test_marketo_connection'),
]
|
[
"bryanlandia@gmail.com"
] |
bryanlandia@gmail.com
|
f9c216d9e36499b2c663d881bad98abae74f7b89
|
2bb90b620f86d0d49f19f01593e1a4cc3c2e7ba8
|
/pardus/playground/ebayer/zabbix/comar/package.py
|
783303a21ba22b9377dc757238ebed5c1cbe27df
|
[] |
no_license
|
aligulle1/kuller
|
bda0d59ce8400aa3c7ba9c7e19589f27313492f7
|
7f98de19be27d7a517fe19a37c814748f7e18ba6
|
refs/heads/master
| 2021-01-20T02:22:09.451356
| 2013-07-23T17:57:58
| 2013-07-23T17:57:58
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 241
|
py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
def postInstall(fromVersion, fromRelease, toVersion, toRelease):
os.system("/bin/chown -R zabbix.zabbix /var/log/zabbix")
os.system("/bin/chown -R zabbix.zabbix /var/run/zabbix")
|
[
"yusuf.aydemir@istanbul.com"
] |
yusuf.aydemir@istanbul.com
|
d9b5608829804232254ebd2360dcae1406ed96ba
|
9c4ceb78678a8755c6ac7e54a47e8054b6e79c2c
|
/mozdns/create_zone/tests.py
|
256894622faca6aae8a54b697031acdf6bc21d4a
|
[] |
no_license
|
caseybecking/inventory
|
068ca06a9b2c28a4baaea1c71491fa029552ab1b
|
aa74ed891f665a0eed6899b631e08b2227e42887
|
refs/heads/master
| 2021-01-23T01:41:28.443608
| 2014-03-17T15:32:49
| 2014-03-17T15:32:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,506
|
py
|
from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from mozdns.domain.models import Domain
from mozdns.nameserver.models import Nameserver
from mozdns.soa.models import SOA
from mozdns.tests.utils import random_label, random_byte
from mozdns.view.models import View
def localize(url):
return '/en-US' + url
class CreateZoneTests(TestCase):
def setUp(self):
self.c = Client()
Domain(name="com").save()
Domain(name="mozilla.com").save()
self.private_view = View.objects.create(name='private')
self.public_view = View.objects.create(name='public')
def get_post_data(self):
"""Return a valid set of data"""
return {
'root_domain': '{0}.{0}.mozilla.com'.format(
random_label() + random_label()),
'soa_primary': 'ns1.mozilla.com',
'soa_contact': 'noc.mozilla.com',
'nameserver_1': 'ns1.mozilla.com',
'nameserver_2': 'ns2.mozilla.com',
'nameserver_3': 'ns3.mozilla.com',
'ttl_1': random_byte(),
'ttl_2': random_byte(),
'ttl_3': random_byte(),
'private_view_1': 'on',
'private_view_2': 'on',
'private_view_3': '',
'public_view_1': 'on',
'public_view_2': '',
'public_view_3': 'on',
}
# NS1 has all views
# NS2 has private and no public
# NS3 has no private and public
def _ensure_no_change(self, post_data):
soa_count = SOA.objects.all().count()
domain_count = Domain.objects.all().count()
ns_count = Nameserver.objects.all().count()
resp = self.c.post(localize(reverse('create-zone-ajax')), post_data)
self.assertEqual(200, resp.status_code)
new_soa_count = SOA.objects.all().count()
new_domain_count = Domain.objects.all().count()
new_ns_count = Nameserver.objects.all().count()
self.assertEqual(new_soa_count, soa_count)
self.assertEqual(new_domain_count, domain_count)
self.assertEqual(new_ns_count, ns_count)
def _check_domain_tree(self, root_domain_name):
self.assertTrue(Domain.objects.filter(name=root_domain_name))
root_domain = Domain.objects.get(name=root_domain_name)
self.assertFalse(root_domain.purgeable)
p_domain = root_domain.master_domain
while p_domain:
self.assertEqual(None, p_domain.soa)
p_domain = p_domain.master_domain
def test_create_zone(self):
soa_count = SOA.objects.all().count()
domain_count = Domain.objects.all().count()
ns_count = Nameserver.objects.all().count()
post_data = self.get_post_data()
resp = self.c.post(localize(reverse('create-zone-ajax')), post_data)
self.assertEqual(200, resp.status_code)
new_soa_count = SOA.objects.all().count()
new_domain_count = Domain.objects.all().count()
new_ns_count = Nameserver.objects.all().count()
self.assertEqual(new_soa_count, soa_count + 1)
self.assertEqual(new_domain_count, domain_count + 2)
self.assertEqual(new_ns_count, ns_count + 3)
self._check_domain_tree(post_data['root_domain'])
# Do it again. The use of a random domain should give us a new set of
# domain values.
soa_count = SOA.objects.all().count()
domain_count = Domain.objects.all().count()
ns_count = Nameserver.objects.all().count()
post_data = self.get_post_data()
resp = self.c.post(localize(reverse('create-zone-ajax')), post_data)
self.assertEqual(200, resp.status_code)
new_soa_count = SOA.objects.all().count()
new_domain_count = Domain.objects.all().count()
new_ns_count = Nameserver.objects.all().count()
self.assertEqual(new_soa_count, soa_count + 1)
self.assertEqual(new_domain_count, domain_count + 2)
self.assertEqual(new_ns_count, ns_count + 3)
self._check_domain_tree(post_data['root_domain'])
def test_more_realistic_creation(self):
post_data = self.get_post_data()
resp = self.c.post(localize(reverse('create-zone-ajax')), post_data)
self.assertEqual(200, resp.status_code)
first_root_domain = post_data['root_domain']
self._check_domain_tree(first_root_domain)
# Now create a new zone under the created zone. Make sure the tree
# under the new zone is preserved.
second_root_domain = "{0}.{1}".format(
random_label(), first_root_domain)
post_data['root_domain'] = second_root_domain
resp = self.c.post(localize(reverse('create-zone-ajax')), post_data)
self.assertEqual(200, resp.status_code)
self._check_domain_tree(first_root_domain)
self.assertTrue(Domain.objects.filter(name=second_root_domain))
root_domain = Domain.objects.get(name=second_root_domain)
self.assertFalse(root_domain.purgeable)
self.assertFalse(root_domain.master_domain.purgeable)
self.assertNotEqual(None, root_domain.soa)
self.assertFalse(None, root_domain.master_domain.soa)
def test_create_zone_bad_soa(self):
post_data = self.get_post_data()
post_data['root_domain'] = ''
self._ensure_no_change(post_data)
# Try a bad primary
post_data = self.get_post_data()
post_data['soa_primary'] = 'adsf..afds'
self._ensure_no_change(post_data)
# Try a bad contact
post_data = self.get_post_data()
post_data['soa_contact'] = 'adsf.#afds'
self._ensure_no_change(post_data)
# Try a missing contact
post_data = self.get_post_data()
del post_data['soa_contact']
self._ensure_no_change(post_data)
def test_create_zone_bad_ns(self):
# Bad ns server
post_data = self.get_post_data()
post_data['nameserver_1'] = '..'
self._ensure_no_change(post_data)
# No glue
post_data = self.get_post_data()
post_data['nameserver_3'] = 'ns1.' + post_data['root_domain']
self._ensure_no_change(post_data)
def test_create_tld(self):
# Try a bad primary
post_data = self.get_post_data()
post_data['root_domain'] = 'asdf'
post_data['soa_primary'] = 'adsf..'
self._ensure_no_change(post_data)
def test_create_validate_views(self):
# Try a bad primary
post_data = self.get_post_data()
post_data['root_domain'] = 'safasdf.mozilla.com'
resp = self.c.post(localize(reverse('create-zone-ajax')), post_data)
self.assertEqual(200, resp.status_code)
d = Domain.objects.get(name=post_data['root_domain'])
# NS1 has all views
# NS2 has private and no public
# NS3 has no private and public
ns1 = d.nameserver_set.get(server=post_data['nameserver_1'])
self.assertTrue(self.private_view in ns1.views.all())
self.assertTrue(self.public_view in ns1.views.all())
ns2 = d.nameserver_set.get(server=post_data['nameserver_2'])
self.assertTrue(self.private_view in ns2.views.all())
self.assertTrue(self.public_view not in ns2.views.all())
ns3 = d.nameserver_set.get(server=post_data['nameserver_3'])
self.assertTrue(self.private_view not in ns3.views.all())
self.assertTrue(self.public_view in ns3.views.all())
|
[
"uberj@onid.orst.edu"
] |
uberj@onid.orst.edu
|
91923f2d70578815bd5c42388cd28f696541cc8a
|
7ba4e38e0835cd009a078ce39a480b5bacaba21f
|
/sample_code/chap5/5.1.1.merton2d.py
|
4d23bc23a0147325378c2537d556466d3e55833f
|
[] |
no_license
|
moguranran/computer_vision_test
|
fe0641987905755c733e4ab16f48c3b76d01b3f4
|
4c5b5572d01e13a42eefb2423e66e34675c305cb
|
refs/heads/master
| 2022-04-20T17:53:37.668609
| 2020-03-31T00:13:02
| 2020-03-31T00:13:02
| 249,196,701
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 404
|
py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from PIL import Image
from pylab import *
execfile('load_vggdata.py')
# 3D点を同次座標にして射影する
X = vstack( (points3D,ones(points3D.shape[1])) )
x = P[0].project(X)
# 画像1の上に点を描画する
figure()
imshow(im1)
plot(points2D[0][0],points2D[0][1],'*')
axis('off')
figure()
imshow(im1)
plot(x[0],x[1],'r.')
axis('off')
show()
|
[
"peehssalg@gmail.com"
] |
peehssalg@gmail.com
|
073f60314ce1438ff3d603dd52a52964ccd838c4
|
521580589177e7eb44ef809d7be2ae0f74d1d2ce
|
/tests/utils.py
|
1d25782e40bb0dac7ea8339f7197e5e84187cbd0
|
[
"BSD-3-Clause"
] |
permissive
|
isabella232/typeseam
|
3e2455ad27ae6234868a4b17ade25b9867500c69
|
3e9d090ec84f2110ae69051364bb0905feb2f02c
|
refs/heads/master
| 2023-04-01T16:12:57.666686
| 2016-08-18T01:56:14
| 2016-08-18T01:56:14
| 358,551,773
| 0
| 0
|
BSD-3-Clause
| 2021-04-16T09:52:11
| 2021-04-16T09:49:54
| null |
UTF-8
|
Python
| false
| false
| 213
|
py
|
import re
from bs4 import BeautifulSoup
def get_value_for_name(name, unicode_text):
soup = BeautifulSoup(unicode_text, 'html.parser')
t = soup.find(attrs={'name': name})
return t.attrs.get('value')
|
[
"benjamin.j.golder@gmail.com"
] |
benjamin.j.golder@gmail.com
|
47b493a00ab878d569dab455ac4af3ca7a951d1c
|
f8ad6963bfc851657ea50c6a036cfad29cdd7f60
|
/Books/DeepLearningLearningFromTheFounderOfKeras/chapter6/sub6_3_2.py
|
e226b633774a2b310e3e59774ec825790fb6fef2
|
[] |
no_license
|
foru120/PythonRepository
|
e1ab0265c0f50ef2e9acdf7447237c913560692b
|
db6b6be0f9fb91b0a81a3b6a2ec5631daab10f98
|
refs/heads/master
| 2021-01-01T06:53:11.728109
| 2019-04-25T13:52:50
| 2019-04-25T13:52:50
| 97,541,222
| 4
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,583
|
py
|
#todo p.282 ~ p.299
#todo code 6-32 ~ code 6-44
#todo 6.3.2 데이터 준비
import os
import numpy as np
data_dir = 'G:/04.dataset/09.jena_climate'
fname = os.path.join(data_dir, 'jena_climate_2009_2016.csv')
f = open(fname)
data = f.read()
f.close()
lines = data.split('\n')
header = lines[0].split(',')
lines = lines[1:]
float_data = np.zeros((len(lines), len(header) - 1))
for i, line in enumerate(lines):
values = [float(x) for x in line.split(',')[1:]]
float_data[i, :] = values
mean = float_data[:200000].mean(axis=0)
std = float_data[:200000].std(axis=0)
float_data -= mean
float_data /= std
def generator(data, lookback, delay, min_index, max_index, shuffle=False, batch_size=128, step=6):
"""
:param data: 원본 데이터 배열
:param lookback: 입력으로 사용하기 위해 거슬러 올라갈 타임스텝
:param delay: 타깃으로 사용할 미래의 타임스텝
:param min_index: 추출할 타임스텝의 범위를 지정하기 위한 data 배열의 인덱스. 검증 데이터와 테스트 데이터를 분리하는 데 사용
:param max_index: 추출할 타임스텝의 범위를 지정하기 위한 data 배열의 인덱스. 검증 데이터와 테스트 데이터를 분리하는 데 사용
:param shuffle: 샘플을 섞을지, 시간 순서대로 추출할지를 결정
:param batch_size: 배치의 샘플 수
:param step: 데이터를 샘플링할 타임스텝 간격. 1시간에 하나의 데이터 포인트를 추출하기 위해 기본값 6으로 지정
:return:
"""
if max_index is None:
max_index = len(data) - delay - 1
i = min_index + lookback
while True:
if shuffle:
rows = np.random.randint(min_index + lookback, max_index, size=batch_size)
else:
if i + batch_size >= max_index:
i = min_index + lookback
rows = np.arange(i, min(i + batch_size, max_index))
i += len(rows)
samples = np.zeros((len(rows),
lookback // step,
data.shape[-1]))
targets = np.zeros((len(rows),))
for j, row in enumerate(rows):
indices = range(rows[j] - lookback, rows[j], step)
samples[j] = data[indices]
targets[j] = data[rows[j] + delay][1]
yield samples, targets
lookback = 1440
step = 6
delay = 144
batch_size = 128
train_gen = generator(data=float_data,
lookback=lookback,
delay=delay,
min_index=0,
max_index=200000,
shuffle=True,
step=step,
batch_size=batch_size)
val_gen = generator(data=float_data,
lookback=lookback,
delay=delay,
min_index=200001,
max_index=300000,
step=step,
batch_size=batch_size)
test_gen = generator(data=float_data,
lookback=lookback,
delay=delay,
min_index=300001,
max_index=None,
step=step,
batch_size=batch_size)
val_steps = (300000 - 200001 - lookback) // batch_size
test_steps = (len(float_data) - 300001 - lookback) // batch_size
#todo 상식 수준의 기준점 (loss: 0.29)
def evaluate_naive_method():
batch_maes = []
for step in range(val_steps):
samples, targets = next(val_gen)
preds = samples[:, -1, 1]
mae = np.mean(np.abs(preds - targets))
batch_maes.append(mae)
print('상식 수준의 기준점:', np.mean(batch_maes) * std[1])
# evaluate_naive_method()
#todo 기본적인 머신 러닝 방법 (loss: 0.3378)
# from keras.models import Sequential
# from keras import layers
# from keras.optimizers import RMSprop
#
# model = Sequential()
# model.add(layers.Flatten(input_shape=(lookback // step, float_data.shape[-1])))
# model.add(layers.Dense(32, activation='relu'))
# model.add(layers.Dense(1))
#
# model.compile(optimizer=RMSprop(), loss='mae')
# history = model.fit_generator(generator=train_gen,
# steps_per_epoch=500,
# epochs=20,
# validation_data=val_gen,
# validation_steps=val_steps)
#todo 첫 번째 순환 신경망-GRU (loss: 0.2980)
# from keras.models import Sequential
# from keras import layers
# from keras.optimizers import RMSprop
#
# model = Sequential()
# model.add(layers.GRU(32, input_shape=(None, float_data.shape[-1])))
# model.add(layers.Dense(1))
#
# model.compile(optimizer=RMSprop(), loss='mae')
# history = model.fit_generator(generator=train_gen,
# steps_per_epoch=500,
# epochs=20,
# validation_data=val_gen,
# validation_steps=val_steps)
#todo 드롭아웃 규제된 GPU를 사용한 모델을 훈련하고 평가하기 (loss: 0.2702)
# from keras.models import Sequential
# from keras import layers
# from keras.optimizers import RMSprop
#
# model = Sequential()
# model.add(layers.GRU(32,
# dropout=0.2,
# recurrent_dropout=0.2,
# input_shape=(None, float_data.shape[-1])))
# model.add(layers.Dense(1))
#
# model.compile(optimizer=RMSprop(), loss='mae')
# history = model.fit_generator(generator=train_gen,
# steps_per_epoch=500,
# epochs=40,
# validation_data=val_gen,
# validation_steps=val_steps)
#todo 스태킹 순환 층 (loss: 0.2686)
# from keras.models import Sequential
# from keras import layers
# from keras.optimizers import RMSprop
#
# model = Sequential()
# model.add(layers.GRU(32,
# dropout=0.1,
# recurrent_dropout=0.5,
# return_sequences=True,
# input_shape=(None, float_data.shape[-1])))
# model.add(layers.GRU(64,
# activation='relu',
# dropout=0.1,
# recurrent_dropout=0.5))
# model.add(layers.Dense(1))
#
# model.compile(optimizer=RMSprop(), loss='mae')
# history = model.fit_generator(generator=train_gen,
# steps_per_epoch=500,
# epochs=40,
# validation_data=val_gen,
# validation_steps=val_steps)
#todo 양방향 LSTM 을 훈련하고 평가하기 (loss: )
from keras.models import Sequential
from keras import layers
from keras.optimizers import RMSprop
model = Sequential()
model.add(layers.Bidirectional(layers.GRU(32), input_shape=(None, float_data.shape[-1])))
model.add(layers.Dense(1))
model.compile(optimizer=RMSprop(), loss='mae')
history = model.fit_generator(generator=train_gen,
steps_per_epoch=500,
epochs=40,
validation_data=val_gen,
validation_steps=val_steps)
import matplotlib.pyplot as plt
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(loss) + 1)
plt.figure()
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()
|
[
"broodsky1122@hanmail.net"
] |
broodsky1122@hanmail.net
|
bb7df9eaa48f87436b6a91a78aade6d51d87c59b
|
bd275d991b6c87609c2d1c7a00e42d09d6f8284c
|
/zhrtvc/tools/run_local.py
|
aa1a5284c94eefbd1142c55e0c608ac20a4068c4
|
[
"MIT"
] |
permissive
|
wulol/zhrtvc
|
01dcfe9e5a087dbdca8f2ba773a8a9e46cabc483
|
99e594621643d1f6a8197b2c1f616c1d4a89c79b
|
refs/heads/master
| 2023-01-18T23:29:56.108717
| 2020-12-05T10:02:43
| 2020-12-05T10:02:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,034
|
py
|
#!usr/bin/env python
# -*- coding: utf-8 -*-
# author: kuangdd
# date: 2020/2/20
"""
"""
from pathlib import Path
from functools import partial
from multiprocessing.pool import Pool
from matplotlib import pyplot as plt
from tqdm import tqdm
import collections as clt
import os
import re
import json
import numpy as np
import shutil
import aukit
from aukit.audio_griffinlim import default_hparams, mel_spectrogram
# from hparams import hparams
my_hp = {
"n_fft": 1024, "hop_size": 256, "win_size": 1024,
"sample_rate": 22050, "max_abs_value": 4.0,
"fmin": 0, "fmax": 8000,
"preemphasize": True,
'symmetric_mels': True,
}
# default_hparams.update(hparams.values())
# # default_hparams.update(my_hp)
#
# a = {(k, v) for k, v in hparams.values().items() if type(v) in {str, int, float, tuple, bool, type(None)}}
# b = {(k, v) for k, v in default_hparams.items() if type(v) in {str, int, float, tuple, bool, type(None)}}
# print(a - b)
# print(b - a)
#
# _pad_len = (default_hparams.n_fft - default_hparams.hop_size) // 2
def wavs2mels(indir: Path, outdir: Path):
for fpath in tqdm(indir.glob("*.wav")):
wav = aukit.load_wav(fpath, sr=16000)
wav = np.pad(wav.flatten(), (_pad_len, _pad_len), mode="reflect")
mel = mel_spectrogram(wav, default_hparams)
np.save(outdir.joinpath(fpath.stem + ".npy"), mel, allow_pickle=False)
def get_train_files(indir: Path):
others = []
names = []
for fpath in tqdm(sorted(indir.glob("**/*.wav"))):
s = os.path.getsize(fpath)
if s < 32000:
print(s, fpath)
others.append(fpath)
continue
name = "/".join(fpath.relative_to(indir).parts)
names.append(name)
with open(indir.joinpath("train_files.txt"), "w", encoding="utf8") as fout:
for name in names:
fout.write(name + "\n")
_hanzi_re = re.compile(r'[\u4E00-\u9FA5]')
_pause_dict = {'#1': '%', '#2': '%', '#3': '$', '#4': '$'}
def convert_line(line):
index, han_text, pny_text = line.strip().split('\t')
pnys = pny_text.strip().split()
parts = re.split(r'(#\d)', han_text)
cnt = 0
outs = []
for part in parts:
if part.startswith('#'):
pny = _pause_dict[part]
outs.append(pny)
else:
for zi in part:
if _hanzi_re.search(zi):
if zi != '儿':
pny = pnys[cnt]
outs.append(pny)
cnt += 1
else:
if len(pnys) - 1 >= cnt and pnys[cnt].startswith('er'):
pny = pnys[cnt]
outs.append(pny)
cnt += 1
# else:
# outs.append(zi)
out_text = ' '.join(outs)
# out_line = f'{index}|{out_text}|{han_text}\n'
out_line = f'wav/biaobei/{index}.wav\t{out_text}\tbiaobei\n'
return out_line
def biaobei2aishell3():
"""
000085 现在是#2道儿#2越走#1越宽#3,人气#2越搞#1越旺#4。 xian4 zai4 shi4 daor4 yue4 zou3 yue4 kuan1 ren2 qi4 yue4 gao3 yue4 wang4
"""
inpath = r'F:\bigdata\public_audio\bznsyp\metadata.csv'
outpath = r'F:\bigdata\public_audio\bznsyp\train.txt'
with open(outpath, 'wt', encoding='utf8') as fout:
for num, line in enumerate(tqdm(open(inpath, encoding='utf8'))):
out_line = convert_line(line)
fout.write(out_line)
if __name__ == "__main__":
print(__file__)
indir = Path(r"E:\lab\melgan\data\aliexamples")
outdir = Path(r"E:\lab\melgan\data\aliexamples_mel")
# outdir.mkdir(exist_ok=True)
# wavs2mels(indir=indir, outdir=outdir)
indir = Path(r"E:\data\aliaudio\alijuzi")
# get_train_files(indir=indir)
line = '000085 现在是#2道儿#2越走#1越宽#3,人气#2越搞#1越旺#4。 xian4 zai4 shi4 daor4 yue4 zou3 yue4 kuan1 ren2 qi4 yue4 gao3 yue4 wang4'
out = convert_line(line)
print(out)
biaobei2aishell3()
|
[
"kqhyj@163.com"
] |
kqhyj@163.com
|
abf6d188268e5a9aa36725a70f24302522e07c35
|
1a0d5e2e9da4be4babbb55fa0edfb4e708044567
|
/P0-Sudoku/solution.py
|
0191cc77c0671765cfe6a4b1185fc8cb0c0781ff
|
[] |
no_license
|
andy1li/udacity-aind
|
45adc280b8880aa1e5592f9b40ea76133eac10c8
|
ecf1d9466578557e1ed991ffa925d620fd0f87ed
|
refs/heads/master
| 2021-05-15T07:50:37.877110
| 2018-04-04T02:18:11
| 2018-04-04T02:18:11
| 109,645,801
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,562
|
py
|
from utils import *
from collections import Counter
row_units = [cross(r, cols) for r in rows]
column_units = [cross(rows, c) for c in cols]
square_units = [cross(rs, cs) for rs in ('ABC','DEF','GHI')
for cs in ('123','456','789')]
diag_units = [[r+c for r, c in zip(rows, cols)],
[r+c for r, c in zip(rows, reversed(cols))]]
unitlist = row_units + column_units + square_units + diag_units
# Must be called after all units (including diagonals) are added to the unitlist
units = extract_units(unitlist, boxes)
peers = extract_peers(units, boxes)
def naked_twins(values):
"""Eliminate values using the naked twins strategy.
Parameters
----------
values(dict)
a dictionary of the form {'box_name': '123456789', ...}
Returns
-------
dict
The values dictionary with the naked twins eliminated from peers
"""
for unit in unitlist:
twos = Counter(values[box] for box in unit
if len(values[box]) == 2)
for twins, count in twos.items():
if count == 2: # if naked twins
for box in unit:
if values[box] != twins: # for non-twins box
new_value = values[box]
for twin in twins:
new_value = new_value.replace(twin, '')
assign_value(values, box, new_value)
return values
def eliminate(values):
"""Apply the eliminate strategy to a Sudoku puzzle
The eliminate strategy says that if a box has a value assigned, then none
of the peers of that box can have the same value.
Parameters
----------
values(dict)
a dictionary of the form {'box_name': '123456789', ...}
Returns
-------
dict
The values dictionary with the assigned values eliminated from peers
"""
solved = [box for box in values
if len(values[box]) == 1]
for box in solved:
for peer in peers[box]:
new_value = values[peer].replace(values[box],'')
assign_value(values, peer, new_value)
return values
def only_choice(values):
"""Apply the only choice strategy to a Sudoku puzzle
The only choice strategy says that if only one box in a unit allows a certain
digit, then that box must be assigned that digit.
Parameters
----------
values(dict)
a dictionary of the form {'box_name': '123456789', ...}
Returns
-------
dict
The values dictionary with all single-valued boxes assigned
"""
for unit in unitlist:
for digit in '123456789':
appearances = [box for box in unit
if digit in values[box]]
if len(appearances) == 1:
assign_value(values, appearances[0], digit)
return values
def count_box(values, n):
return sum(len(v) == n for v in values.values())
def reduce_puzzle(values):
"""Reduce a Sudoku puzzle by repeatedly applying all constraint strategies
Parameters
----------
values(dict)
a dictionary of the form {'box_name': '123456789', ...}
Returns
-------
dict or False
The values dictionary after continued application of the constraint strategies
no longer produces any changes, or False if the puzzle is unsolvable
"""
stalled = False
while not stalled:
before = count_box(values, 1)
values = naked_twins(only_choice(eliminate(values)))
after = count_box(values, 1)
stalled = before == after
if count_box(values, 0): return False
return values
def search(values):
"""Apply depth first search to solve Sudoku puzzles in order to solve puzzles
that cannot be solved by repeated reduction alone.
Parameters
----------
values(dict)
a dictionary of the form {'box_name': '123456789', ...}
Returns
-------
dict or False
The values dictionary with all boxes assigned or False
"""
values = reduce_puzzle(values)
if values is False:
return False ## Failed earlier
if count_box(values, 1) == 81:
return values ## Solved!
n, box = min((len(values[box]), box) for box in boxes
if len(values[box]) > 1)
for value in values[box]:
new_sudoku = values.copy()
new_sudoku[box] = value
attempt = search(new_sudoku)
if attempt: return attempt
return False
def solve(grid):
"""Find the solution to a Sudoku puzzle using search and constraint propagation
Parameters
----------
grid(string)
a string representing a sudoku grid.
Ex. '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'
Returns
-------
dict or False
The dictionary representation of the final sudoku grid or False if no solution exists.
"""
return search(grid2values(grid))
if __name__ == "__main__":
diag_sudoku_grid = '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'
display(grid2values(diag_sudoku_grid))
result = solve(diag_sudoku_grid)
display(result)
try:
import PySudoku
PySudoku.play(grid2values(diag_sudoku_grid), result, history)
except SystemExit:
pass
except:
print('We could not visualize your board due to a pygame issue. Not a problem! It is not a requirement.')
|
[
"li.chenxing@gmail.com"
] |
li.chenxing@gmail.com
|
b4a29825c5aa72eb08388b9b95ccd734c2c97f45
|
1a9696b7f30c7164e4b7c57933b7b2d8df83ab2c
|
/Camera_Functions.py
|
ac8225bbbdba87107de0a732272afe2616447dc5
|
[
"MIT"
] |
permissive
|
SBCV/PythonBlenderUtility
|
5bc6d20bd4298097b6893b2739a6879e29b0e084
|
4f91c5a356fede103bcb8c2a9ba1d4d0b01aadc3
|
refs/heads/master
| 2020-04-02T02:06:52.888904
| 2020-02-17T13:04:02
| 2020-02-17T13:04:02
| 153,892,269
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,888
|
py
|
import bpy
import numpy as np
from Utility.Types.Camera import Camera
from Utility.Math.Conversion.Conversion_Collection import convert_opengl_to_computer_vision_camera
from Utility.Logging_Extension import logger
def get_calibration_mat(blender_camera):
#logger.info('get_calibration_mat: ...')
scene = bpy.context.scene
render_resolution_width = scene.render.resolution_x
render_resolution_height = scene.render.resolution_y
focal_length_in_mm = float(blender_camera.data.lens)
sensor_width_in_mm = float(blender_camera.data.sensor_width)
focal_length_in_pixel = \
float(max(scene.render.resolution_x, scene.render.resolution_y)) * \
focal_length_in_mm / sensor_width_in_mm
max_extent = max(render_resolution_width, render_resolution_height)
p_x = render_resolution_width / 2.0 - blender_camera.data.shift_x * max_extent
p_y = render_resolution_height / 2.0 - blender_camera.data.shift_y * max_extent
calibration_mat = Camera.compute_calibration_mat(
focal_length_in_pixel, cx=p_x, cy=p_y)
#logger.info('get_calibration_mat: Done')
return calibration_mat
def get_computer_vision_camera_matrix(blender_camera):
"""
Blender and Computer Vision Camera Coordinate Frame Systems (like VisualSfM, Bundler)
differ by their y and z axis
:param blender_camera:
:return:
"""
# Only if the objects have a scale of 1,
# the 3x3 part of the corresponding matrix_world contains a pure rotation
# Otherwise it also contains scale or shear information
if tuple(blender_camera.scale) != (1, 1, 1):
logger.vinfo('blender_camera.scale', blender_camera.scale)
assert False
opengl_cam_mat = np.array(blender_camera.matrix_world)
computer_vision_cam_mat = convert_opengl_to_computer_vision_camera(
opengl_cam_mat)
return computer_vision_cam_mat
|
[
"sebastian.bullinger@iosb.fraunhofer.de"
] |
sebastian.bullinger@iosb.fraunhofer.de
|
eddd22a4f755d6844fc83b4621b94e1687021fd6
|
e65d16ea1e8d412bac75a809be6d390126bdf528
|
/homeassistant/components/google_assistant_sdk/__init__.py
|
e2791f6000f3ebf95250338fe0b609d7c1df0863
|
[
"Apache-2.0"
] |
permissive
|
syssi/home-assistant
|
6347d57866cb16ab9d4499ad38e2be6f0399077f
|
fd43687833741b21221769d46b4d1ecef8a94711
|
refs/heads/dev
| 2023-08-17T09:31:52.680518
| 2023-06-11T14:22:12
| 2023-06-11T14:22:12
| 97,874,495
| 6
| 16
|
Apache-2.0
| 2023-09-13T06:31:21
| 2017-07-20T20:12:37
|
Python
|
UTF-8
|
Python
| false
| false
| 6,693
|
py
|
"""Support for Google Assistant SDK."""
from __future__ import annotations
import aiohttp
from gassist_text import TextAssistant
from google.oauth2.credentials import Credentials
import voluptuous as vol
from homeassistant.components import conversation
from homeassistant.config_entries import ConfigEntry, ConfigEntryState
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_NAME, Platform
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from homeassistant.helpers import config_validation as cv, discovery, intent
from homeassistant.helpers.config_entry_oauth2_flow import (
OAuth2Session,
async_get_config_entry_implementation,
)
from homeassistant.helpers.typing import ConfigType
from .const import (
CONF_ENABLE_CONVERSATION_AGENT,
CONF_LANGUAGE_CODE,
DATA_MEM_STORAGE,
DATA_SESSION,
DOMAIN,
)
from .helpers import (
GoogleAssistantSDKAudioView,
InMemoryStorage,
async_send_text_commands,
default_language_code,
)
SERVICE_SEND_TEXT_COMMAND = "send_text_command"
SERVICE_SEND_TEXT_COMMAND_FIELD_COMMAND = "command"
SERVICE_SEND_TEXT_COMMAND_FIELD_MEDIA_PLAYER = "media_player"
SERVICE_SEND_TEXT_COMMAND_SCHEMA = vol.All(
{
vol.Required(SERVICE_SEND_TEXT_COMMAND_FIELD_COMMAND): vol.All(
cv.ensure_list, [vol.All(str, vol.Length(min=1))]
),
vol.Optional(SERVICE_SEND_TEXT_COMMAND_FIELD_MEDIA_PLAYER): cv.comp_entity_ids,
},
)
CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up Google Assistant SDK component."""
hass.async_create_task(
discovery.async_load_platform(
hass, Platform.NOTIFY, DOMAIN, {CONF_NAME: DOMAIN}, config
)
)
return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Google Assistant SDK from a config entry."""
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {}
implementation = await async_get_config_entry_implementation(hass, entry)
session = OAuth2Session(hass, entry, implementation)
try:
await session.async_ensure_token_valid()
except aiohttp.ClientResponseError as err:
if 400 <= err.status < 500:
raise ConfigEntryAuthFailed(
"OAuth session is not valid, reauth required"
) from err
raise ConfigEntryNotReady from err
except aiohttp.ClientError as err:
raise ConfigEntryNotReady from err
hass.data[DOMAIN][entry.entry_id][DATA_SESSION] = session
mem_storage = InMemoryStorage(hass)
hass.data[DOMAIN][entry.entry_id][DATA_MEM_STORAGE] = mem_storage
hass.http.register_view(GoogleAssistantSDKAudioView(mem_storage))
await async_setup_service(hass)
entry.async_on_unload(entry.add_update_listener(update_listener))
await update_listener(hass, entry)
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
hass.data[DOMAIN].pop(entry.entry_id)
loaded_entries = [
entry
for entry in hass.config_entries.async_entries(DOMAIN)
if entry.state == ConfigEntryState.LOADED
]
if len(loaded_entries) == 1:
for service_name in hass.services.async_services()[DOMAIN]:
hass.services.async_remove(DOMAIN, service_name)
if entry.options.get(CONF_ENABLE_CONVERSATION_AGENT, False):
conversation.async_unset_agent(hass, entry)
return True
async def async_setup_service(hass: HomeAssistant) -> None:
"""Add the services for Google Assistant SDK."""
async def send_text_command(call: ServiceCall) -> None:
"""Send a text command to Google Assistant SDK."""
commands: list[str] = call.data[SERVICE_SEND_TEXT_COMMAND_FIELD_COMMAND]
media_players: list[str] | None = call.data.get(
SERVICE_SEND_TEXT_COMMAND_FIELD_MEDIA_PLAYER
)
await async_send_text_commands(hass, commands, media_players)
hass.services.async_register(
DOMAIN,
SERVICE_SEND_TEXT_COMMAND,
send_text_command,
schema=SERVICE_SEND_TEXT_COMMAND_SCHEMA,
)
async def update_listener(hass, entry):
"""Handle options update."""
if entry.options.get(CONF_ENABLE_CONVERSATION_AGENT, False):
agent = GoogleAssistantConversationAgent(hass, entry)
conversation.async_set_agent(hass, entry, agent)
else:
conversation.async_unset_agent(hass, entry)
class GoogleAssistantConversationAgent(conversation.AbstractConversationAgent):
"""Google Assistant SDK conversation agent."""
def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Initialize the agent."""
self.hass = hass
self.entry = entry
self.assistant: TextAssistant | None = None
self.session: OAuth2Session | None = None
@property
def attribution(self):
"""Return the attribution."""
return {
"name": "Powered by Google Assistant SDK",
"url": "https://www.home-assistant.io/integrations/google_assistant_sdk/",
}
@property
def supported_languages(self) -> list[str]:
"""Return a list of supported languages."""
language_code = self.entry.options.get(
CONF_LANGUAGE_CODE, default_language_code(self.hass)
)
return [language_code]
async def async_process(
self, user_input: conversation.ConversationInput
) -> conversation.ConversationResult:
"""Process a sentence."""
if self.session:
session = self.session
else:
session = self.hass.data[DOMAIN][self.entry.entry_id][DATA_SESSION]
self.session = session
if not session.valid_token:
await session.async_ensure_token_valid()
self.assistant = None
if not self.assistant:
credentials = Credentials(session.token[CONF_ACCESS_TOKEN])
language_code = self.entry.options.get(
CONF_LANGUAGE_CODE, default_language_code(self.hass)
)
self.assistant = TextAssistant(credentials, language_code)
resp = self.assistant.assist(user_input.text)
text_response = resp[0] or "<empty response>"
intent_response = intent.IntentResponse(language=user_input.language)
intent_response.async_set_speech(text_response)
return conversation.ConversationResult(
response=intent_response, conversation_id=user_input.conversation_id
)
|
[
"noreply@github.com"
] |
syssi.noreply@github.com
|
5d38c3be05c32a6e2c9c7214932c4650eef0e83d
|
01776becc70eafe6dcbad140eb40a862bc623341
|
/LeetCode/Easy/989.Add to Array-Form of Integer.py
|
d22f06f8e69782b38fd59c1bb2f89bad9b11807f
|
[] |
no_license
|
AnthonyTsui/AlgoPractice
|
8eae4d197080c0a94b0127ed5a95198f5d2f3269
|
59fcb2826fb95a304cf7b4b9a77c2ae710fb5c9a
|
refs/heads/master
| 2022-12-02T18:20:58.104356
| 2020-08-29T23:58:17
| 2020-08-29T23:58:17
| 250,649,377
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,138
|
py
|
# For a non-negative integer X, the array-form of X is an array of its digits in left to right order. For example, if X = 1231, then the array form is [1,2,3,1].
# Given the array-form A of a non-negative integer X, return the array-form of the integer X+K.
# Example 1:
# Input: A = [1,2,0,0], K = 34
# Output: [1,2,3,4]
# Explanation: 1200 + 34 = 1234
# Example 2:
# Input: A = [2,7,4], K = 181
# Output: [4,5,5]
# Explanation: 274 + 181 = 455
# Example 3:
# Input: A = [2,1,5], K = 806
# Output: [1,0,2,1]
# Explanation: 215 + 806 = 1021
# Example 4:
# Input: A = [9,9,9,9,9,9,9,9,9,9], K = 1
# Output: [1,0,0,0,0,0,0,0,0,0,0]
# Explanation: 9999999999 + 1 = 10000000000
#Time Complexity: O(N)
#Space Complexity: O(1)
class Solution(object):
def addToArrayForm(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: List[int]
"""
for i in range(len(A)-1, -1, -1):
K, A[i] = divmod(K+A[i], 10)
return [int(i) for i in str(K)] + A if K else A
# toNum = int(''.join(str(c) for c in A)) + K
# return [c for c in str(toNum)]
|
[
"atsui4688@gmail.com"
] |
atsui4688@gmail.com
|
0fea981dccef636eea89d4210cf00364ba2d1897
|
46caeb8f8a896036b5a1d054416c7c5530076381
|
/tests/test_app.py
|
76a63be24e856031dfeed6d51195aeef37a16987
|
[
"MIT"
] |
permissive
|
c137digital/unv_template
|
dce0a65eacf18faa3ca6cdf08202fe11d45c943a
|
2c356478408a27eb68eaaf38a74b32a6633a11d0
|
refs/heads/master
| 2020-04-14T06:41:16.725736
| 2019-11-02T13:19:27
| 2019-11-02T13:19:27
| 163,693,073
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 293
|
py
|
import pytest
from package.app import SomeExampleApp
@pytest.fixture
def instance():
return SomeExampleApp('test')
def test_calls_count(instance):
assert instance.ncalls == 0
assert instance.name == 'test'
assert instance.power(2, 3) == 8
assert instance.ncalls == 1
|
[
"morty.space@gmail.com"
] |
morty.space@gmail.com
|
175a78136f62e7e999d0cc195755ace57255346f
|
93bda31263d66cc557cb084d08c26388cf3d6bd5
|
/fluid/image_classification/caffe2fluid/kaffe/custom_layers/__init__.py
|
703c6a0a8091df79c73465be8c52248af518f3ca
|
[
"Apache-2.0"
] |
permissive
|
denglelaibh/models
|
323982b172e6aced9b6e99ecdbfe00d98c23be8f
|
f93838a4258c2a197cfa9e14c244b4da7a042a88
|
refs/heads/develop
| 2020-03-19T13:53:17.619489
| 2018-06-08T04:43:04
| 2018-06-08T04:43:04
| 126,789,492
| 0
| 0
|
Apache-2.0
| 2018-05-16T03:17:38
| 2018-03-26T07:21:18
|
Python
|
UTF-8
|
Python
| false
| false
| 2,781
|
py
|
"""
"""
from .register import get_registered_layers
#custom layer import begins
import axpy
import flatten
import argmax
import reshape
#custom layer import ends
custom_layers = get_registered_layers()
def set_args(f, params, node=None):
""" set args for function 'f' using the parameters in node.layer.parameters
Args:
f (function): a python function object
params (object): a object contains attributes needed by f's arguments
Returns:
arg_names (list): a list of argument names
kwargs (dict): a dict contains needed arguments
"""
from ..protobuf_to_dict import protobuf_to_dict
argc = f.__code__.co_argcount
arg_list = f.__code__.co_varnames[0:argc]
kwargs = {}
for arg_name in arg_list:
if arg_name in params:
kwargs[arg_name] = params[arg_name]
return arg_list, kwargs
def has_layer(kind):
""" test whether this layer exists in custom layer
"""
return kind in custom_layers
def compute_output_shape(kind, node):
assert kind in custom_layers, "layer[%s] not exist in custom layers" % (
kind)
shape_func = custom_layers[kind]['shape']
parents = node.parents
inputs = [list(p.output_shape) for p in parents]
arg_names, kwargs = set_args(shape_func, node.params)
if len(inputs) == 1:
inputs = inputs[0]
return shape_func(inputs, **kwargs)
def make_node(template, kind, node):
""" make a PaddleNode for custom layer which means construct
a piece of code to define a layer implemented in 'custom_layers'
Args:
@template (PaddleNode): a factory to new a instance of PaddleNode
@kind (str): type of custom layer
@node (graph.Node): a layer in the net
Returns:
instance of PaddleNode
"""
assert kind in custom_layers, "layer[%s] not exist in custom layers" % (
kind)
layer_func = custom_layers[kind]['layer']
#construct arguments needed by custom layer function from node's parameters
arg_names, kwargs = set_args(layer_func, node.params, node)
return template('custom_layer', kind, **kwargs)
def make_custom_layer(kind, inputs, name, *args, **kwargs):
""" execute a custom layer which is implemented by users
Args:
@kind (str): type name of this layer
@inputs (vars): variable list created by fluid
@namme (str): name for this layer
@args (tuple): other positional arguments
@kwargs (dict): other kv arguments
Returns:
output (var): output variable for this layer
"""
assert kind in custom_layers, "layer[%s] not exist in custom layers" % (
kind)
layer_func = custom_layers[kind]['layer']
return layer_func(inputs, name, *args, **kwargs)
|
[
"dangqingqing@baidu.com"
] |
dangqingqing@baidu.com
|
13e7e0e3254aa8534f9f9b8c72d17e9b62aca991
|
1dac4a650f5061bed9574a84cef4bdb87fdc3ebf
|
/tests/contrib/test_tone_convert.py
|
f25f8dc1434179aa9d3c1b2f9af4eb1bc7134c1d
|
[
"MIT"
] |
permissive
|
rontian/python-pinyin
|
29cf191ac1812de30a147ffdbd90a74b52ef2c2d
|
a421a83127ee55cba09ecabbf63d0c1bfb3a3aea
|
refs/heads/master
| 2023-09-04T18:01:13.417107
| 2021-11-14T03:42:51
| 2021-11-14T03:42:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,342
|
py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from pytest import mark
from pypinyin.contrib.tone_convert import (
tone_to_normal,
tone_to_tone2,
tone2_to_tone,
tone_to_tone3,
tone3_to_tone,
tone2_to_normal,
tone2_to_tone3,
tone3_to_tone2,
tone3_to_normal,
to_normal,
to_tone,
to_tone2,
to_tone3,
)
@mark.parametrize('pinyin,result', [
['zhōng', 'zhong'],
['ān', 'an'],
['yuè', 'yue'],
['er', 'er'],
['nǚ', 'nv'],
['nv', 'nv'],
['ā', 'a'],
['a', 'a'],
])
def test_tone_to_normal(pinyin, result):
assert tone_to_normal(pinyin) == result
assert to_normal(pinyin) == result
assert to_normal(result) == result
@mark.parametrize('pinyin,v_to_u,result', [
['nǚ', False, 'nv'],
['nv', False, 'nv'],
['nǚ', True, 'nü'],
['nv', True, 'nü'],
])
def test_tone_to_normal_with_v_to_u(pinyin, v_to_u, result):
assert tone_to_normal(pinyin, v_to_u=v_to_u) == result
assert to_normal(pinyin, v_to_u=v_to_u) == result
@mark.parametrize('pinyin,result', [
['zhōng', 'zho1ng'],
['ān', 'a1n'],
['yuè', 'yue4'],
['er', 'er'],
['nǚ', 'nv3'],
['nv', 'nv'],
['ā', 'a1'],
['a', 'a'],
['shang', 'shang'],
])
def test_tone_tone2(pinyin, result):
assert tone_to_tone2(pinyin) == result
assert to_tone2(pinyin) == result
assert tone2_to_tone(result) == pinyin
assert to_tone(result) == pinyin
assert to_tone(pinyin) == pinyin
assert to_tone2(result) == result
@mark.parametrize('pinyin,neutral_tone_with_5,result', [
['shang', False, 'shang'],
['shang', True, 'sha5ng'],
])
def test_tone_tone2_with_neutral_tone_with_5(
pinyin, neutral_tone_with_5, result):
assert tone_to_tone2(
pinyin, neutral_tone_with_5=neutral_tone_with_5) == result
assert to_tone2(pinyin, neutral_tone_with_5=neutral_tone_with_5) == result
assert tone2_to_tone(result) == pinyin
assert to_tone(result) == pinyin
@mark.parametrize('pinyin,v_to_u,result', [
['nǚ', False, 'nv3'],
['nv', False, 'nv'],
['nǚ', True, 'nü3'],
['nv', True, 'nü'],
])
def test_tone_tone2_with_v_to_u(pinyin, v_to_u, result):
assert tone_to_tone2(pinyin, v_to_u=v_to_u) == result
assert to_tone2(pinyin, v_to_u=v_to_u) == result
assert tone2_to_tone(result) == pinyin
if 'v' not in pinyin:
assert to_tone(result) == pinyin
@mark.parametrize('pinyin,result', [
['zhōng', 'zhong1'],
['ān', 'an1'],
['yuè', 'yue4'],
['er', 'er'],
['nǚ', 'nv3'],
['nv', 'nv'],
['ā', 'a1'],
['a', 'a'],
['shang', 'shang'],
])
def test_tone_tone3(pinyin, result):
assert tone_to_tone3(pinyin) == result
assert to_tone3(pinyin) == result
assert tone3_to_tone(result) == pinyin
assert to_tone(result) == pinyin
assert to_tone(pinyin) == pinyin
assert to_tone3(result) == result
@mark.parametrize('pinyin,neutral_tone_with_5,result', [
['shang', False, 'shang'],
['shang', True, 'shang5'],
])
def test_tone_tone3_with_neutral_tone_with_5(
pinyin, neutral_tone_with_5, result):
assert tone_to_tone3(
pinyin, neutral_tone_with_5=neutral_tone_with_5) == result
assert to_tone3(
pinyin, neutral_tone_with_5=neutral_tone_with_5) == result
assert tone3_to_tone(result) == pinyin
assert to_tone(result) == pinyin
@mark.parametrize('pinyin,v_to_u,result', [
['nǚ', False, 'nv3'],
['nǚ', True, 'nü3'],
['nv', True, 'nü'],
])
def test_tone_tone3_with_v_to_u(pinyin, v_to_u, result):
assert tone_to_tone3(pinyin, v_to_u=v_to_u) == result
assert to_tone3(pinyin, v_to_u=v_to_u) == result
assert tone3_to_tone(result) == pinyin
if 'v' not in pinyin:
assert to_tone(result) == pinyin
@mark.parametrize('pinyin,result', [
['zho1ng', 'zhong1'],
['a1n', 'an1'],
['yue4', 'yue4'],
['er', 'er'],
['nv3', 'nv3'],
['nü3', 'nv3'],
['a1', 'a1'],
['a', 'a'],
['shang', 'shang'],
['sha5ng', 'shang5'],
])
def test_tone2_tone3(pinyin, result):
assert tone2_to_tone3(pinyin) == result
assert to_tone3(pinyin) == result
@mark.parametrize('pinyin,v_to_u,result', [
['lüe3', False, 'lve3'],
['lüe3', True, 'lüe3'],
])
def test_tone2_tone3_with_v_to_u(pinyin, v_to_u, result):
assert tone2_to_tone3(pinyin, v_to_u=v_to_u) == result
@mark.parametrize('pinyin,result', [
['zho1ng', 'zhong'],
['a1n', 'an'],
['yue4', 'yue'],
['er', 'er'],
['nv3', 'nv'],
['nü3', 'nv'],
['a1', 'a'],
['a', 'a'],
['shang', 'shang'],
['sha5ng', 'shang'],
])
def test_tone2_to_normal(pinyin, result):
assert tone2_to_normal(pinyin) == result
assert to_normal(pinyin) == result
assert to_normal(result) == result
@mark.parametrize('pinyin,v_to_u,result', [
['nv3', False, 'nv'],
['nv3', True, 'nü'],
['nü3', False, 'nv'],
['nü3', True, 'nü'],
])
def test_tone2_to_normal_with_v_to_u(pinyin, v_to_u, result):
assert tone2_to_normal(pinyin, v_to_u=v_to_u) == result
assert to_normal(pinyin, v_to_u=v_to_u) == result
assert to_normal(result, v_to_u=v_to_u) == result
@mark.parametrize('pinyin,result', [
['zhong1', 'zhong'],
['an1', 'an'],
['yue4', 'yue'],
['er', 'er'],
['nv3', 'nv'],
['nü3', 'nv'],
['a1', 'a'],
['a', 'a'],
['shang', 'shang'],
['shang5', 'shang'],
])
def test_tone3_to_normal(pinyin, result):
assert tone3_to_normal(pinyin) == result
assert to_normal(pinyin) == result
@mark.parametrize('pinyin,v_to_u,result', [
['nv3', False, 'nv'],
['nv3', True, 'nü'],
['nü3', False, 'nv'],
['nü3', True, 'nü'],
])
def test_tone3_to_normal_with_v_to_u(pinyin, v_to_u, result):
assert tone3_to_normal(pinyin, v_to_u=v_to_u) == result
assert to_normal(pinyin, v_to_u=v_to_u) == result
@mark.parametrize('pinyin,result', [
['zhong1', 'zho1ng'],
['lüe4', 'lve4'],
])
def test_tone3_to_tone2(pinyin, result):
assert tone3_to_tone2(pinyin) == result
@mark.parametrize('pinyin,v_to_u,result', [
['lüe4', False, 'lve4'],
['lüe4', True, 'lüe4'],
])
def test_tone3_to_tone2_with_v_to_u(pinyin, v_to_u, result):
assert tone3_to_tone2(pinyin, v_to_u=v_to_u) == result
|
[
"mozillazg101@gmail.com"
] |
mozillazg101@gmail.com
|
2713cbac7261c36dc7f85e151ef0d25eb08925bf
|
60d737103373825b858e67292865bda8c6f2094f
|
/active/theses-riogrande.py
|
0781b43ee13bfe2d8da1cbb43eb58928f2b60efa
|
[] |
no_license
|
fschwenn/ejlmod
|
fbf4692b857f9f056f9105a7f616a256725f03b6
|
ef17512c2e44baa0164fdc6abc997c70ed3d2a74
|
refs/heads/master
| 2023-01-24T18:56:35.581517
| 2023-01-20T11:18:16
| 2023-01-20T11:18:16
| 91,459,496
| 1
| 1
| null | 2021-10-04T11:58:15
| 2017-05-16T13:06:57
|
Python
|
UTF-8
|
Python
| false
| false
| 6,015
|
py
|
# -*- coding: utf-8 -*-
#harvest theses from Rio Grande do Sul U.
#FS: 2020-10-08
import getopt
import sys
import os
import urllib2
import urlparse
from bs4 import BeautifulSoup
import re
import ejlmod2
import codecs
import datetime
import time
import json
xmldir = '/afs/desy.de/user/l/library/inspire/ejl'#+'/special'
retfiles_path = "/afs/desy.de/user/l/library/proc/retinspire/retfiles"#+'_special'
now = datetime.datetime.now()
stampoftoday = '%4d-%02d-%02d' % (now.year, now.month, now.day)
jnlfilename = 'THESES-RioGrandeDoSul-%s' % (stampoftoday)
publisher = 'Rio Grande do Sul U.'
hdr = {'User-Agent' : 'Magic Browser'}
rpp = 50
pages = 4
boringdegrees = ['mestrado']
prerecs = []
for (depnr, department) in [('46', 'Physics'), ('48', 'Mathematics'), ('49', 'Applied Mathematics'), ('43', 'Computation')]:
for page in range(pages):
tocurl = 'https://lume.ufrgs.br/handle/10183/' + depnr +'/discover?rpp=' + str(rpp) + '&etal=0&group_by=none&page=' + str(page+1) + '&sort_by=dc.date.issued_dt&order=desc'
print '==={ %s }==={ %i/%i }==={ %s }===' % (department, page+1, pages, tocurl)
req = urllib2.Request(tocurl, headers=hdr)
tocpage = BeautifulSoup(urllib2.urlopen(req), features="lxml")
for div in tocpage.body.find_all('div', attrs = {'class' : 'artifact-description'}):
new = True
rec = {'tc' : 'T', 'jnl' : 'BOOK', 'note' : [department], 'keyw' : [], 'supervisor' : []}
for span in div.find_all('span', attrs = {'class' : 'date'}):
if re.search('[12]\d\d\d', span.text):
rec['year'] = re.sub('.*([12]\d\d\d).*', r'\1', span.text.strip())
if int(rec['year']) < now.year - 2:
new = False
print ' skip', rec['year']
if depnr in ['46', '48']:
rec['fc'] = 'm'
elif depnr == '43':
rec['fc'] = 'c'
if new:
for a in div.find_all('a'):
if re.search('handle', a['href']):
rec['artlink'] = 'https://lume.ufrgs.br' + a['href'] + '?show=full'
rec['hdl'] = re.sub('.*handle\/', '', a['href'])
prerecs.append(rec)
time.sleep(2)
i = 0
recs = []
for rec in prerecs:
keepit = True
i += 1
print '---{ %i/%i (%i) }---{ %s }------' % (i, len(prerecs), len(recs), rec['artlink'])
try:
artpage = BeautifulSoup(urllib2.build_opener(urllib2.HTTPCookieProcessor).open(rec['artlink']), features="lxml")
time.sleep(3)
except:
try:
print "retry %s in 180 seconds" % (rec['artlink'])
time.sleep(180)
artpage = BeautifulSoup(urllib2.build_opener(urllib2.HTTPCookieProcessor).open(rec['artlink']), features="lxml")
except:
print "no access to %s" % (rec['artlink'])
continue
for meta in artpage.head.find_all('meta'):
if meta.has_attr('name'):
#author
if meta['name'] == 'DC.creator':
author = meta['content']
rec['autaff'] = [[ author ]]
rec['autaff'][-1].append(publisher)
#title
elif meta['name'] == 'citation_title':
rec['tit'] = meta['content']
#date
elif meta['name'] == 'DCTERMS.issued':
rec['date'] = meta['content']
#abstract
elif meta['name'] == 'DCTERMS.abstract':
if meta['content']:
if meta.has_attr('xml:lang'):
if meta['xml:lang'] == 'en':
rec['abs'] = meta['content']
elif meta['xml:lang'] == 'pt':
rec['abspt'] = meta['content']
else:
rec['abs'] = meta['content']
#FFT
elif meta['name'] == 'citation_pdf_url':
rec['FFT'] = meta['content']
#keywords
elif meta['name'] == 'citation_keywords':
for keyw in re.split('[,;] ', meta['content']):
if not re.search('^info.eu.repo', keyw):
rec['keyw'].append(keyw)
#abstract
if 'abspt' in rec.keys() and not 'abs' in rec.keys():
rec['abs'] = rec['abspt']
for tr in artpage.body.find_all('tr', attrs = {'class' : 'ds-table-row'}):
for td in tr.find_all('td', attrs = {'class' : 'label-cell'}):
tdt = td.text.strip()
td.decompose()
for td in tr.find_all('td'):
if td.text.strip() == 'pt_BR':
continue
#supervisor
if tdt == 'dc.contributor.advisor':
rec['supervisor'] = [[ re.sub(' \(.*', '', td.text.strip()) ]]
#degree
elif tdt == 'dc.degree.level':
degree = td.text.strip()
if degree in boringdegrees:
print ' skip "%s"' % (degree)
keepit = False
else:
rec['note'].append(degree)
#language
elif tdt == 'dc.language.iso':
if td.text.strip() == 'por':
rec['language'] = 'portuguese'
for a in artpage.body.find_all('a'):
if a.has_attr('href') and re.search('creativecommons.org', a['href']):
rec['license'] = {'url' : a['href']}
if keepit:
recs.append(rec)
print ' ', rec.keys()
#closing of files and printing
xmlf = os.path.join(xmldir, jnlfilename+'.xml')
xmlfile = codecs.EncodedFile(codecs.open(xmlf, mode='wb'),'utf8')
ejlmod2.writenewXML(recs, xmlfile, publisher, jnlfilename)
xmlfile.close()
#retrival
retfiles_text = open(retfiles_path, "r").read()
line = jnlfilename+'.xml'+ "\n"
if not line in retfiles_text:
retfiles = open(retfiles_path, "a")
retfiles.write(line)
retfiles.close()
|
[
"florian.schwennsen@desy.de"
] |
florian.schwennsen@desy.de
|
990eee06dfeaf47b24859f2490bc130d5f365b43
|
a3c68eafdb433c981f2b90e86f895e4f121c69fb
|
/笔试/腾讯/安排任务.py
|
7774742e90b1ce6c0ce1f601472364aa5efae663
|
[] |
no_license
|
Cassiexyq/Program-Exercise
|
ccc236ea76ca99ddc6fe0c4c47edebc3d557cfad
|
e962cc3add047d61df275dd3e22a091018fd964a
|
refs/heads/master
| 2020-04-25T20:27:33.561226
| 2019-09-22T15:29:35
| 2019-09-22T15:29:35
| 173,050,531
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 913
|
py
|
# -*- coding: utf-8 -*-
# @Author: xyq
n,m = [int(i) for i in input().strip().split()]
machine,task = [],[]
for i in range(n):
hours, level = [int(i) for i in input().strip().split()]
machine.append([hours, level])
for i in range(m):
hours,level = [int(i) for i in input().strip().split()]
task.append([hours,level])
machine.sort(key=lambda x:(x[0],x[1]),reverse=True)
task.sort(key=lambda x:(x[0],x[1]),reverse=True)
dp = [0 for i in range(101)]
j,cnt, res = 0,0,0
# 遍历每个任务,把满足时间的任务对应的难度级别+1
# 遍历大于任务难度级别的,找到符合难度级别的
for h, l in task:
while j < len(machine) and machine[j][0] >= h:
dp[machine[j][1]] += 1
j += 1
for i in range(l,101):
if dp[i] > 0 :
dp[i] -= 1
res += 200 * h + 3 * l
cnt += 1
break
print("%d %d" % (cnt, res))
|
[
"cassiexuan_yq@163.com"
] |
cassiexuan_yq@163.com
|
ad88264e1c80fd051137abcd95d7cc5ca5c19016
|
4ca7480c27ed98fd9c49ac11911f6c1229e53631
|
/main.py
|
e3a55d8bf6eb0bdc2a30bedbaf60580310a6ed74
|
[] |
no_license
|
shawwn/tfimg
|
33ba7b2fc7fa60fb41ba1bd4c76065170c40c3f8
|
0d464f56f1092996d90870f765d6a1d875f09b4f
|
refs/heads/master
| 2023-03-05T09:47:53.394086
| 2023-02-18T13:58:48
| 2023-02-18T13:58:48
| 274,115,458
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,821
|
py
|
import tensorflow as tf
import functools
def op_scope(fn, name=None):
if name is None:
name = fn.__name__
@functools.wraps(fn)
def _fn(*args, **kwargs):
with tf.name_scope(fn.__name__):
return fn(*args, **kwargs)
return _fn
@op_scope
def clamp(v, min=0., max=1.):
if anum(v):
return np.clip(v, min, max)
else:
return tf.clip_by_value(v, min, max)
@op_scope
def wrap(uv, wrap_mode="reflect"):
assert wrap_mode in ["clamp", "wrap", "reflect"]
if wrap_mode == "wrap":
return tf.math.floormod(uv, 1.0)
elif wrap_mode == "reflect":
return 1.0 - tf.abs(tf.math.floormod(uv, 2.0) - 1.0)
elif wrap_mode == "clamp":
return clamp(uv)
def aten(u):
return tf.is_tensor(u)
def anum(u):
return isinstance(u, float) or isinstance(u, int)
@op_scope
def iround(u):
if anum(u):
return u // 1.0
else:
return i32(tf.math.floordiv(f32(u), 1.0))
@op_scope
def lsh(u, by):
if anum(u) and anum(by):
return int(u) << by
else:
return tf.bitwise.left_shift(u, by)
@op_scope
def rsh(u, by):
if anum(u) and anum(by):
return int(u) >> by
else:
return tf.bitwise.right_shift(u, by)
import numpy as np
@op_scope
def sign(u):
if anum(u):
return np.sign(u)
else:
return tf.sign(u)
@op_scope
def min2(a, b):
if anum(a) and anum(b):
return min(a, b)
else:
return tf.minimum(a, b)
@op_scope
def max2(a, b):
if anum(a) and anum(b):
return max(a, b)
else:
return tf.maximum(a, b)
@op_scope
def min3(a, b, c):
if anum(a) and anum(b) and anum(c):
return min(a, b, c)
else:
return tf.minimum(a, tf.minimum(b, c))
@op_scope
def max3(a, b, c):
if anum(a) and anum(b) and anum(c):
return max(a, b, c)
else:
return tf.maximum(a, tf.maximum(b, c))
@op_scope
def min4(a, b, c, d):
if anum(a) and anum(b) and anum(c) and anum(d):
return min(a, b, c, d)
else:
return tf.minimum(a, tf.minimum(b, tf.minimum(c, d)))
@op_scope
def max4(a, b, c, d):
if anum(a) and anum(b) and anum(c) and anum(d):
return max(a, b, c, d)
else:
return tf.maximum(a, tf.maximum(b, tf.maximum(c, d)))
@op_scope
def f32(u):
if isinstance(u, (tuple, list)):
return tuple(f32(v) for v in u)
if anum(u):
return float(u)
else:
return tf.cast(u, tf.float32)
@op_scope
def i32(u):
if isinstance(u, (tuple, list)):
return tuple(i32(v) for v in u)
if anum(u):
return int(u)
else:
return tf.cast(u, tf.int32)
@op_scope
def u8(u):
if isinstance(u, (tuple, list)):
return tuple(u8(v) for v in u)
if anum(u):
return np.asarray(u).astype(np.uint8)
else:
return tf.cast(u, tf.uint8)
def arglist(*args):
if len(args) >= 1 and isinstance(args[0], (list, tuple)):
return tuple(args[0]) + args[1:]
return args
def unlist(args):
args = arglist(*args)
if len(args) == 1:
return args[0]
return args
@op_scope
def vzip(*xs):
return tf.stack(arglist(*xs), axis=-1)
@op_scope
def vunzip(uv, keepdims=False):
xs = tf.split(uv, np.shape(uv)[-1], -1)
if not keepdims:
xs = [tf.squeeze(x, -1) for x in xs]
return tuple(xs)
def lerp(a, b, t):
return (b - a) * t + a
def vspan(*dims):
dims = arglist(*dims)
return unlist(tf.range(0.0, n) / n for n in f32(iround(dims)))
def vmesh(*spans):
grids = tf.meshgrid(*spans, indexing='xy')
return vzip(grids)
def vgrid(*dims):
spans = vspan(*dims)
return vmesh(*spans)
def vshape(x):
if hasattr(x, 'shape'):
return np.shape(x)
return x
def bounds(img):
"""returns width and height"""
shape = vshape(img)
if len(shape) > 2:
shape = shape[0:-1]
return list(shape)
def channels(img):
shape = vshape(img)
assert len(shape) > 2
return shape[-1]
def area(shape):
return np.prod(bounds(shape))
def grab(src, u, v):
IH, IW = bounds(src)
u = clamp(iround(f32(u) + 0.5), 0, IW - 1)
v = clamp(iround(f32(v) + 0.5), 0, IH - 1)
inds = vzip(v, u)
out = tf.raw_ops.GatherNd(params=src, indices=tf.reshape(inds, (-1, inds.shape[-1])))
return tf.reshape(out, bounds(inds) + [channels(src)])
@op_scope
def sample(tex, uv, method="bilinear", wrap_mode="reflect"):
assert method in ["nearest", "bilinear", "area"]
if isinstance(uv, (list, tuple)):
uv = vzip(uv)
IH, IW = bounds(tex)
d_uv = 1.0 / vzip(f32(bounds(uv)))
uv = wrap(uv, wrap_mode)
ix, iy = vunzip(uv)
# normalize ix, iy from [0, 1] to [0, H-1] & [0, W-1]
ix = ix * (IW-1)
iy = iy * (IH-1)
if method == "nearest":
return grab(tex, ix, iy)
elif method == "bilinear":
# https://github.com/pytorch/pytorch/blob/f064c5aa33483061a48994608d890b968ae53fb5/aten/src/THNN/generic/SpatialGridSamplerBilinear.c#L105
# get NE, NW, SE, SW pixel values from (x, y)
ix_nw = iround(ix)
iy_nw = iround(iy)
ix_ne = ix_nw + 1
iy_ne = iy_nw
ix_sw = ix_nw
iy_sw = iy_nw + 1
ix_se = ix_nw + 1
iy_se = iy_nw + 1
# get surfaces to each neighbor:
sub = lambda a, b: f32(a) - f32(b)
nw = sub(ix_se , ix) * sub(iy_se , iy);
ne = sub(ix , ix_sw) * sub(iy_sw , iy);
sw = sub(ix_ne , ix) * sub(iy , iy_ne);
se = sub(ix , ix_nw) * sub(iy , iy_nw);
nw_val = grab(tex, ix_nw, iy_nw)
ne_val = grab(tex, ix_ne, iy_ne)
sw_val = grab(tex, ix_sw, iy_sw)
se_val = grab(tex, ix_se, iy_se)
def mul(a, da):
return f32(a) * tf.expand_dims(da, -1)
out = mul(nw_val, nw)
out += mul(ne_val, ne)
out += mul(sw_val, sw)
out += mul(se_val, se)
return out
else:
u_0, v_0 = vunzip(uv)
u_1, v_1 = vunzip(uv + d_uv)
# summed area table.
# if uvs are flipped, result is negative, so take abs
img_sum = tf.cumsum(tf.cumsum(f32(img), 0), 1) / area(img)
out_00 = sample(img_sum, (u_0, v_0), "bilinear", wrap_mode=wrap_mode)
out_01 = sample(img_sum, (u_0, v_1), "bilinear", wrap_mode=wrap_mode)
out_10 = sample(img_sum, (u_1, v_0), "bilinear", wrap_mode=wrap_mode)
out_11 = sample(img_sum, (u_1, v_1), "bilinear", wrap_mode=wrap_mode)
out = abs(out_00 + out_11 - out_10 - out_01) * area(uv)
return out
def readwrite(filename, mode, data=None):
if filename == '-':
if mode.startswith('r'):
f = sys.stdin.buffer if 'b' in mode else sys.stdin
return f.read()
else:
f = sys.stdout.buffer if 'b' in mode else sys.stdout
return f.write(data)
else:
try:
from smart_open import open
except ImportError:
from builtins import open
with open(filename, mode) as f:
if mode.startswith('r'):
return f.read()
else:
return f.write(data)
if __name__ == "__main__":
import sys
args = sys.argv[1:]
indata = readwrite(args[0], 'rb')
img = tf.io.decode_image(indata, channels=3)
IW, IH, *IC = np.shape(img)
outfile = args[1]
w = '64' if len(args) <= 2 else args[2]
h = '0' if len(args) <= 3 else args[3]
if w.endswith('%'): w = (float(w[:-1])/100 * IW)
if h.endswith('%'): h = (float(h[:-1])/100 * IH)
w = int(w)
h = int(h)
method = ("bilinear" if w >= IW and (h <= 0 or h >= IH) else "area") if len(args) <= 4 else args[4]
wrap_mode = "reflect" if len(args) <= 5 else args[5]
u_sx, u_sy = (1.0, 1.0) if len(args) <= 6 else [float(x) for x in args[6].split(',')]
u_tx, u_ty = (0.0, 0.0) if len(args) <= 7 else [float(x) for x in args[7].split(',')]
if w <= 0: w = h / (IW/IH)
if h <= 0: h = w * (IW/IH)
w *= u_sx
h *= u_sy
uv = vgrid(w, h)
uv = uv * vzip( u_sx, u_sy)
uv = uv + vzip( u_tx, -u_ty)
img2 = sample(img, uv, method=method, wrap_mode=wrap_mode)
img2 = u8(clamp(img2, 0, 255))
if args[1] == '-' and sys.stdout.isatty():
import imgcat
imgcat.imgcat(img2.numpy())
else:
data = tf.image.encode_png(img2).numpy()
readwrite(args[1], 'wb', data)
|
[
"shawnpresser@gmail.com"
] |
shawnpresser@gmail.com
|
e21782c742d83cd1fd0c8e9c99a1ccce363fc50a
|
d14be9a07437f395c36c73aebfd1c5434ff4300e
|
/vmware_static_dhcp/hosts_file.py
|
ea682e177a5b8fc9e3ef5432174408c596cf3e8a
|
[
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] |
permissive
|
zcutlip/vmware-static-dhcp
|
f6122cdb7ca0fcd895c536d3a23e2469bfceaedc
|
4f7747703bca8f440c56407c5e1437cfe9ff8cba
|
refs/heads/master
| 2020-09-08T11:13:41.192702
| 2019-11-12T03:11:03
| 2019-11-12T03:11:03
| 221,117,693
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,573
|
py
|
class MalformedHostsEntryException(Exception):
pass
class MalformedHostsFileException(Exception):
pass
class HostsEntry:
ADDR_COLUMN_WIDTH = 24
FOUR_SPACES = " "
def __init__(self, addr, hostname, comment):
self._sanity_check(addr, hostname)
self.address = addr
self.hostname = hostname
self.comment = comment
self.blank_line = self._is_blank_line(addr, hostname, comment)
@classmethod
def parse_hostline(cls, hostline):
addr = None
hostname = None
comment = None
if hostline.startswith("#"):
comment = hostline
else:
parts = hostline.split(maxsplit=2)
if len(parts):
addr = parts.pop(0)
if len(parts):
hostname = parts.pop(0)
if len(parts):
comment = parts.pop(0)
return (addr, hostname, comment)
def _sanity_check(self, addr, hostname):
addr_hostname = [addr, hostname]
if None in addr_hostname:
if [None, None] != addr_hostname:
raise MalformedHostsEntryException(
"Malformed address/hostname pair: {}".format(str(addr_hostname)))
def _is_blank_line(self, addr, hostname, comment):
return [None, None, None] == [addr, hostname, comment]
def __str__(self):
_str = None
if [self.address, self.hostname] == [None, None] and self.comment is not None:
_str = self.comment
elif self.blank_line:
_str = ""
else:
fmt = "{:%ds}" + self.FOUR_SPACES + "{:s}"
fmt = fmt % self.ADDR_COLUMN_WIDTH
_str = fmt.format(self.address, self.hostname)
if self.comment is not None:
_str += self.FOUR_SPACES + self.comment
return _str
class HostsFile:
def __init__(self, path="/etc/hosts"):
hosts, address_map = self._parse_hosts_file(path)
self.hosts = hosts
self.address_map = address_map
def _parse_hosts_file(self, path):
entries = []
address_map = {}
lines = open(path, "r").read().splitlines()
for line in lines:
addr, hostname, comment = HostsEntry.parse_hostline(line)
entry = HostsEntry(addr, hostname, comment)
if entry.address is not None:
if entry.address in address_map:
raise MalformedHostsFileException("Duplicate address: {}".format(line))
else:
address_map[entry.address] = entry
entries.append(entry)
return (entries, address_map)
def add_host_entry(self, addr, hostname, comment):
if addr in self.address_map:
raise MalformedHostsEntryException("Address already in hosts file: {}".format(addr))
entry = HostsEntry(addr, hostname, comment)
self.address_map[addr] = entry
self.hosts.append(entry)
def remove_host_entry(self, addr):
if addr not in self.address_map:
raise Exception("Address not found: {}".format(addr))
entry = self.address_map[addr]
self.hosts.remove(entry)
def write_hosts(self, outpath):
print("Writing updated hosts file to {}".format(outpath))
with open(outpath, "w") as outhosts:
for entry in self.hosts:
outhosts.write("{}\n".format(str(entry)))
if __name__ == "__main__":
hosts = HostsFile(path="/etc/hosts")
for host in hosts.hosts:
print(str(host))
|
[
"uid000@gmail.com"
] |
uid000@gmail.com
|
975c2da1189e6e45391dd92d380c8e1342d46cca
|
abf31091690614f7949c1ddc50ef36d4a46658f8
|
/Old Sspider/Gomine_DOC_utf/zhuan_weiyi_run.py
|
ee3258e8cd083db50a9d680df0af86d3f3e605bd
|
[] |
no_license
|
SuperShen9/work_by_sh
|
7132196b0b40ab88c4baaac6bb4813babc2f3dcb
|
60a3693eb040b2f86165bfa439f3a718f38bae44
|
refs/heads/master
| 2021-01-20T01:50:34.795903
| 2018-06-19T06:14:11
| 2018-06-19T06:14:11
| 89,328,784
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,154
|
py
|
# -*- coding: utf-8 -*-
# author:Super
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import pandas as pd
import time,os,shutil
import codecs
pd.set_option('expand_frame_repr',False)
os.chdir('C:\\Users\Administrator\Desktop')
# #openpyxl模块
# wb = openpyxl.load_workbook('sheet1.xlsx')
# sheet = wb.get_sheet_by_name('Sheet1')
# print sheet['A2'].value
# print type(sheet['A2'].value.encode("gbk"))
# exit()
# # 查看text文件
# file=open('text.txt')
# lines=file.readlines()
# print lines
# for i in lines:
# print i
# exit()
df=pd.read_excel('sheet1.xlsx')
if os.path.exists('RUN'):
shutil.rmtree('RUN')
os.makedirs('C:\\Users\Administrator\Desktop\\RUN')
os.chdir('C:\\Users\Administrator\Desktop\\RUN')
# df.shape[0]
for i in range(df.shape[0]):
count=0
for x in df.columns:
count+=1
val = df[x].loc[i]
if isinstance(val, float):
val = ''
else:
val = val.encode('gbk')
fl = open('%s-%s-%s.txt' % (df['name'].loc[i],df['organization'].loc[i],df['webName'].loc[i]), 'a')
if count<=len(df.columns)-4:
if x == 'webName':
fl.write('{')
fl.write('\r"webUrl": "http://www.chictr.org.cn/searchproj.aspx",')
fl.write('\r"{}": "{}",'.format(x, str(val)))
fl.write("")
elif x == 'remark':
fl.write('\r"remark":"",')
else:
fl.write('\r"{}": "{}",'.format(x, str(val)))
elif count==len(df.columns)-3:
fl.write('\r"info": {')
fl.write('\r"name": "{}",'.format(str(val)))
elif count==len(df.columns)-1:
if val[-1]=='0':
fl.write('\r"{}": "{}",'.format(x, str(val)[:4]))
else:
fl.write('\r"{}": "{}",'.format(x, str(val)[4:]))
elif count == len(df.columns):
fl.write('\r"{}": "{}"'.format(x, str(val)))
fl.write('}')
fl.write('}')
else:
fl.write('\r"{}": "{}",'.format(x, str(val)))
|
[
"675153178@qq.com"
] |
675153178@qq.com
|
ddcdbe45016ee01b23f44ed1f9d03021eae00fb4
|
dc30b6ecea0a1ad2342244871817a5882f506fda
|
/Tentamen/Opdracht1.py
|
5247492fd3260ea011617607a84e6974c049e3cd
|
[] |
no_license
|
CasperHagenaars/WISB256
|
26e4b272a80d687b22ce7fd48a6040e45e152b85
|
d0871a2221f71fe64d7aba4efcd3a1e276c22f34
|
refs/heads/master
| 2020-05-20T17:03:27.182900
| 2015-06-18T12:43:33
| 2015-06-18T12:43:33
| 34,313,132
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 295
|
py
|
import math
import time
tekst = input()
lijn = "Ug"
try:
if(int(tekst) > 1):
for i in range(1,int(tekst)):
lijn += " ug"
lijn += "!"
lijn = str(lijn)
else:
lijn = "Ug!"
except:
lengte = (len(tekst) / 3)
lijn = int(lengte)
print(lijn)
|
[
"casperhagenaars@gmail.com"
] |
casperhagenaars@gmail.com
|
732064d7c77be799ca1907b7c19d461d4303dbf1
|
543fc91aa311e39b3119a509b8151c31c1bfdb27
|
/code/BalancedBinaryTree.py
|
ea7ddfe29074ce64631957588924d753eee6795d
|
[] |
no_license
|
shinrain/leetcode-python
|
399879ea8ebffdc73575c897228e33d7a62825de
|
5497f496fb6b87b387f0d2eb316d152446dfc8cc
|
refs/heads/master
| 2021-01-01T06:00:23.517122
| 2015-01-03T07:15:26
| 2015-01-03T07:15:26
| 26,843,970
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 472
|
py
|
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a boolean
def isBalanced(self, root):
return helper(root)!=-1
def helper(root):
if root is None:
return 0
left = helper(root.left)
right = helper(root.right)
if left==-1 or right==-1 or abs(left-right)>1:
return -1
return max(left, right)+1
|
[
"shinrainxie@gmail.com"
] |
shinrainxie@gmail.com
|
22c37ae2c3ab66a66b668cd84fcf3b548b17736a
|
bf94a22b20a81d0557488357bc1ceaebb9742d50
|
/bc/utils/dask_grenoble.py
|
a1cc516402f4df15c1e25d5cfebb650b3645782f
|
[
"MIT"
] |
permissive
|
ikalevatykh/rlbc
|
ccbcb73034d0f9b638b26abbe6d97479b3494903
|
feb31bf5e8442335ce4b4a06a7171b1f64afe9b5
|
refs/heads/master
| 2022-03-05T04:03:36.053834
| 2019-11-05T10:04:05
| 2019-11-05T10:04:05
| 261,451,513
| 2
| 0
|
MIT
| 2020-05-05T11:58:14
| 2020-05-05T11:58:13
| null |
UTF-8
|
Python
| false
| false
| 2,318
|
py
|
import os
import datetime
from dask_jobqueue import OARCluster
class AlpesCluster(OARCluster):
def __init__(
self,
cores,
name,
processes=1,
mem_req=4000,
walltime='72:00:00',
venv=None,
to_source='~/.bashrc',
log_dir='/home/apashevi/Logs/dask/',
spill_dir='/home/apashevi/Logs/dask/',
env_extra=None,
besteffort=False,
job_extra=None,
interface_node=None,
extra='',
**kwargs):
if name == 'dask-cpu':
resource_spec = 'nodes=1/core={}'.format(cores)
elif name == 'dask-gpu':
resource_spec = None
else:
raise NotImplementedError
name += '_' + datetime.datetime.now().strftime('%Y%m%dT%H%M%S')
os.path.join(log_dir, 'logs')
if besteffort:
if job_extra is None:
job_extra = []
job_extra += [' -t besteffort -t idempotent']
job_extra += [
'--stdout={}'.format(os.path.join(log_dir, '%jobid%_stdout.txt'))
]
job_extra += [
'--stderr={}'.format(os.path.join(log_dir, '%jobid%_stderr.txt'))
]
OARCluster.__init__(
self,
resource_spec=resource_spec,
walltime=walltime,
name=name,
cores=cores,
processes=processes,
memory='{}m'.format(mem_req),
local_directory=spill_dir,
extra=extra,
env_extra=env_extra,
job_extra=job_extra,
interface_node=interface_node,
**kwargs)
class CPUCluster(AlpesCluster):
def __init__(self, ncpus=1, **kwargs):
cores = ncpus
AlpesCluster.__init__(self, cores=cores, name='dask-cpu', **kwargs)
class GPUCluster(AlpesCluster):
def __init__(self, **kwargs):
job_extra = [
'-p \'not host=\'\"\'\"\'gpuhost23\'\"\'\"\' and not host=\'\"\'\"\'gpuhost24\'\"\'\"\' and not host=\'\"\'\"\'gpuhost25\'\"\'\"\' and not host=\'\"\'\"\'gpuhost26\'\"\'\"\' and not host=\'\"\'\"\'gpuhost27\'\"\'\"\'\''
]
AlpesCluster.__init__(
self, cores=1, name='dask-gpu', job_extra=job_extra, **kwargs)
|
[
"rstrudel@gmail.com"
] |
rstrudel@gmail.com
|
241ef0bf4ffd075de96f0a553cfb8c7cb1005833
|
78c3b9ca4d10b84ea9ec853da39324ba38ad224e
|
/commentonx/__init__.py
|
ebff6b27414a0c3e8e9c9028f145047909b976d3
|
[
"MIT"
] |
permissive
|
trickeydan/commentonx
|
2a892c47b1a535b23bc8ef044e14b4ef58839135
|
b7dbfd6af0f58503acba576033a43be3aabbb0e9
|
refs/heads/master
| 2022-12-10T06:34:16.528489
| 2018-09-29T23:20:57
| 2018-09-29T23:20:57
| 150,874,538
| 0
| 1
|
MIT
| 2021-03-20T00:10:25
| 2018-09-29T14:56:32
|
HTML
|
UTF-8
|
Python
| false
| false
| 441
|
py
|
from flask import Flask
from flask_scss import Scss
from commentonx.config import config
app = Flask(__name__)
app.config.update(config)
if 'VIEW_CONFIG' in app.config:
# Allow view config access in templates
app.jinja_env.globals['VIEW_CONFIG'] = app.config['VIEW_CONFIG']
else:
app.jinja_env.globals['VIEW_CONFIG'] = {}
app.secret_key = app.config["SESSION_KEY"]
Scss(app)
from commentonx import views # noqa F401, E402
|
[
"dan@trickey.io"
] |
dan@trickey.io
|
1531be40d6bc6d91bd6b92fa06158a74798f9ea7
|
4f75ac595ef58c8e42b2a711180bbb1832b30aad
|
/articles/data_python_c/listings_py/mod_immut_parameter.py
|
bf5a3b308c0b2ebfc75a520857e06e99d15589ed
|
[] |
no_license
|
amitsaha/notes
|
4548554a164a4a423795c3103f3462f3fea9b28b
|
6fffe2529d390418616eff71d9b44afb40474278
|
refs/heads/master
| 2021-05-04T10:56:05.266501
| 2018-01-26T07:11:59
| 2018-01-26T07:11:59
| 8,493,168
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 863
|
py
|
#!/usr/bin/env python
""" Passing immutable data objects
and returning a modified version.
"""
from __future__ import print_function
def func(astr):
print('In func() before modification')
print('{0} : {1}'.format(astr,id(astr)))
print()
astr = astr.replace('a','b')
print('In func() after modification')
print('{0} : {1}'.format(astr,id(astr)))
print()
# return the new string
return astr
if __name__ == '__main__':
s = str('a string')
print('Before func()')
print('{0} : {1}'.format(s,id(s)))
print()
# since s is an immutbale object, modifications
# are not possible without creating a new object
# with the modified string
# recieve the modified string back as the
# return value
s = func(s)
print('After func()')
print('{0} : {1}'.format(s,id(s)))
print()
|
[
"amitsaha.in@gmail.com"
] |
amitsaha.in@gmail.com
|
f0be020b789a57fa3ec5391f4ac6e442fe06921d
|
26d37aa0560ecc5725b17e965e16d528bce161ff
|
/schedule/migrations/0016_course_course_active.py
|
ab457d8c32e3d849dc5154823ba04405c584b5c8
|
[] |
no_license
|
dmic23/hga
|
25dfaa177f788b309eeb84a77d3ac126d092bac1
|
aea67fdb8e5baad1206ecca93aadbea427b7af28
|
refs/heads/master
| 2021-01-21T14:23:16.402218
| 2017-10-23T18:07:10
| 2017-10-23T18:07:10
| 57,150,174
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 458
|
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-07-01 07:26
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('schedule', '0015_auto_20160630_0333'),
]
operations = [
migrations.AddField(
model_name='course',
name='course_active',
field=models.BooleanField(default=True),
),
]
|
[
"danielmicaletti@gmail.com"
] |
danielmicaletti@gmail.com
|
882fd9151d05de09700e7726253804eba88370c1
|
4c424214344a3d8cc6fe0978f462410597619e71
|
/archer_apps/accounts/serializers.py
|
156d880a23db7748bbae53fdcc9297944bcc0f08
|
[] |
no_license
|
SergeZazik/Archer-Test
|
65e903b7859c4f9a852d0a88c31a2222f0aebd43
|
6c858f401b95f52551fbf8096cdb17507da399cf
|
refs/heads/master
| 2020-04-08T12:17:49.941503
| 2018-11-27T15:33:09
| 2018-11-27T15:33:09
| 159,340,326
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,308
|
py
|
from .models import CustomUser
from django.contrib.auth import authenticate
from rest_framework import serializers
from rest_framework_jwt.serializers import JSONWebTokenSerializer
class CustomJSONWebTokenSerializer(JSONWebTokenSerializer):
def validate(self, attrs):
credentials = {
self.username_field: attrs.get(self.username_field),
'password': attrs.get('password')
}
if all(credentials.values()):
user = authenticate(**credentials)
if user:
if not user.is_active:
msg = 'User account is disabled.'
raise serializers.ValidationError(msg)
return {
'token': user.jwt_token,
'user': user.id
}
else:
msg = 'Unable to log in with provided credentials.'
raise serializers.ValidationError(msg)
else:
msg = 'Must include "{username_field}" and "password".'
msg = msg.format(username_field=self.username_field)
raise serializers.ValidationError(msg)
class CustomUserSerializer(serializers.ModelSerializer):
class Meta:
model = CustomUser
exclude = ('groups', 'user_permissions', 'last_login')
|
[
"zavizionsergey@gmail.com"
] |
zavizionsergey@gmail.com
|
9d35cc4ff98d0ade4747b6614d96798f75ee21ff
|
a2d36e471988e0fae32e9a9d559204ebb065ab7f
|
/huaweicloud-sdk-drs/huaweicloudsdkdrs/v3/model/user_role_vo.py
|
b2e30bea30f52f1267a762acaee3d4e2c5cb897b
|
[
"Apache-2.0"
] |
permissive
|
zhouxy666/huaweicloud-sdk-python-v3
|
4d878a90b8e003875fc803a61414788e5e4c2c34
|
cc6f10a53205be4cb111d3ecfef8135ea804fa15
|
refs/heads/master
| 2023-09-02T07:41:12.605394
| 2021-11-12T03:20:11
| 2021-11-12T03:20:11
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,203
|
py
|
# coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class UserRoleVO:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'role': 'str',
'comment': 'str',
'is_transfer': 'bool',
'privileges': 'str',
'inherits_roles': 'list[str]',
'selected': 'bool'
}
attribute_map = {
'role': 'role',
'comment': 'comment',
'is_transfer': 'is_transfer',
'privileges': 'privileges',
'inherits_roles': 'inherits_roles',
'selected': 'selected'
}
def __init__(self, role=None, comment=None, is_transfer=None, privileges=None, inherits_roles=None, selected=None):
"""UserRoleVO - a model defined in huaweicloud sdk"""
self._role = None
self._comment = None
self._is_transfer = None
self._privileges = None
self._inherits_roles = None
self._selected = None
self.discriminator = None
self.role = role
if comment is not None:
self.comment = comment
self.is_transfer = is_transfer
self.privileges = privileges
if inherits_roles is not None:
self.inherits_roles = inherits_roles
if selected is not None:
self.selected = selected
@property
def role(self):
"""Gets the role of this UserRoleVO.
角色
:return: The role of this UserRoleVO.
:rtype: str
"""
return self._role
@role.setter
def role(self, role):
"""Sets the role of this UserRoleVO.
角色
:param role: The role of this UserRoleVO.
:type: str
"""
self._role = role
@property
def comment(self):
"""Gets the comment of this UserRoleVO.
说明
:return: The comment of this UserRoleVO.
:rtype: str
"""
return self._comment
@comment.setter
def comment(self, comment):
"""Sets the comment of this UserRoleVO.
说明
:param comment: The comment of this UserRoleVO.
:type: str
"""
self._comment = comment
@property
def is_transfer(self):
"""Gets the is_transfer of this UserRoleVO.
是否支持迁移。
:return: The is_transfer of this UserRoleVO.
:rtype: bool
"""
return self._is_transfer
@is_transfer.setter
def is_transfer(self, is_transfer):
"""Sets the is_transfer of this UserRoleVO.
是否支持迁移。
:param is_transfer: The is_transfer of this UserRoleVO.
:type: bool
"""
self._is_transfer = is_transfer
@property
def privileges(self):
"""Gets the privileges of this UserRoleVO.
权限
:return: The privileges of this UserRoleVO.
:rtype: str
"""
return self._privileges
@privileges.setter
def privileges(self, privileges):
"""Sets the privileges of this UserRoleVO.
权限
:param privileges: The privileges of this UserRoleVO.
:type: str
"""
self._privileges = privileges
@property
def inherits_roles(self):
"""Gets the inherits_roles of this UserRoleVO.
继承角色列表
:return: The inherits_roles of this UserRoleVO.
:rtype: list[str]
"""
return self._inherits_roles
@inherits_roles.setter
def inherits_roles(self, inherits_roles):
"""Sets the inherits_roles of this UserRoleVO.
继承角色列表
:param inherits_roles: The inherits_roles of this UserRoleVO.
:type: list[str]
"""
self._inherits_roles = inherits_roles
@property
def selected(self):
"""Gets the selected of this UserRoleVO.
是否选择。
:return: The selected of this UserRoleVO.
:rtype: bool
"""
return self._selected
@selected.setter
def selected(self, selected):
"""Sets the selected of this UserRoleVO.
是否选择。
:param selected: The selected of this UserRoleVO.
:type: bool
"""
self._selected = selected
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
import simplejson as json
if six.PY2:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)
def __repr__(self):
"""For `print`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, UserRoleVO):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
[
"hwcloudsdk@huawei.com"
] |
hwcloudsdk@huawei.com
|
c780bb18ed86e9e63411028da9535cea55bfe611
|
0607fa7255fa47608407b3cfd819e83d55ba9eab
|
/InvenTree/part/test_part.py
|
84d9900aff2a8c4914aec16079bbfd4198715ff4
|
[
"MIT"
] |
permissive
|
IsThisNameGoodEnough/InvenTree
|
f7d71aa8c33f69654b2bb4d3827d4a60290df8ad
|
fa789036e0ae7d56ced3c9e1f2d2ff596983a365
|
refs/heads/master
| 2020-07-26T02:31:34.316571
| 2019-09-13T14:14:45
| 2019-09-13T14:14:45
| 208,505,299
| 0
| 0
|
MIT
| 2019-09-14T21:20:24
| 2019-09-14T21:20:24
| null |
UTF-8
|
Python
| false
| false
| 2,536
|
py
|
# Tests for the Part model
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
import os
from .models import Part
from .models import rename_part_image, match_part_names
from .templatetags import inventree_extras
class TemplateTagTest(TestCase):
""" Tests for the custom template tag code """
def test_multiply(self):
self.assertEqual(inventree_extras.multiply(3, 5), 15)
def test_version(self):
self.assertEqual(type(inventree_extras.inventree_version()), str)
def test_hash(self):
hash = inventree_extras.inventree_commit()
self.assertEqual(len(hash), 7)
def test_github(self):
self.assertIn('github.com', inventree_extras.inventree_github())
class PartTest(TestCase):
""" Tests for the Part model """
fixtures = [
'category',
'part',
'location',
]
def setUp(self):
self.R1 = Part.objects.get(name='R_2K2_0805')
self.R2 = Part.objects.get(name='R_4K7_0603')
self.C1 = Part.objects.get(name='C_22N_0805')
def test_str(self):
p = Part.objects.get(pk=100)
self.assertEqual(str(p), "BOB | Bob | A2 - Can we build it?")
def test_metadata(self):
self.assertEqual(self.R1.name, 'R_2K2_0805')
self.assertEqual(self.R1.get_absolute_url(), '/part/3/')
def test_category(self):
self.assertEqual(str(self.C1.category), 'Electronics/Capacitors - Capacitors')
orphan = Part.objects.get(name='Orphan')
self.assertIsNone(orphan.category)
self.assertEqual(orphan.category_path, '')
def test_rename_img(self):
img = rename_part_image(self.R1, 'hello.png')
self.assertEqual(img, os.path.join('part_images', 'part_3_img.png'))
img = rename_part_image(self.R2, 'test')
self.assertEqual(img, os.path.join('part_images', 'part_4_img'))
def test_stock(self):
# No stock of any resistors
res = Part.objects.filter(description__contains='resistor')
for r in res:
self.assertEqual(r.total_stock, 0)
self.assertEqual(r.available_stock, 0)
def test_barcode(self):
barcode = self.R1.format_barcode()
self.assertIn('InvenTree', barcode)
self.assertIn(self.R1.name, barcode)
def test_copy(self):
self.R2.deepCopy(self.R1, image=True, bom=True)
def test_match_names(self):
matches = match_part_names('M2x5 LPHS')
self.assertTrue(len(matches) > 0)
|
[
"oliver.henry.walters@gmail.com"
] |
oliver.henry.walters@gmail.com
|
f304df27684fea353834a729f98e0123e8e0d1a3
|
1f8812be38ff5dfc2bf8488e757077ebae1791be
|
/apps/askfm/migrations/0002_question_time.py
|
c67c1931e178fe5fd55e4d4a8669cc226355fdf9
|
[
"MIT"
] |
permissive
|
Morsa11/AskFmClone
|
d51e28a2568a2678af488fcbda63c2b1a23943e3
|
50ded5126926989627b7aa0fb445da5a8a4a5d68
|
refs/heads/master
| 2020-04-25T21:46:03.899930
| 2016-12-13T07:51:57
| 2016-12-13T07:51:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 557
|
py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.utils.timezone import utc
import datetime
class Migration(migrations.Migration):
dependencies = [
('askfm', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='question',
name='time',
field=models.DateTimeField(auto_now_add=True, default=datetime.datetime(2016, 8, 15, 18, 14, 24, 455606, tzinfo=utc)),
preserve_default=False,
),
]
|
[
"shakib609@gmail.com"
] |
shakib609@gmail.com
|
61e6312cb372d66857c1f7cfdaa20a156aaf971c
|
82e18cc7b20e98b90b739618d6517b384f1f0cf5
|
/tests/test_defaults.py
|
85f5a74c223c24d2a6a2aa0c8b5d9e7364408c41
|
[
"MIT"
] |
permissive
|
atng/draftjs_exporter
|
9480600f04843bce700dce73080d5527c896a78e
|
df5e24a69301e6c78fae74ec62615d6444773980
|
refs/heads/master
| 2020-12-28T11:24:01.953669
| 2020-02-04T22:56:45
| 2020-02-04T22:56:45
| 238,312,334
| 0
| 0
|
MIT
| 2020-02-04T21:38:33
| 2020-02-04T21:38:33
| null |
UTF-8
|
Python
| false
| false
| 615
|
py
|
import unittest
from draftjs_exporter.defaults import BLOCK_MAP, STYLE_MAP, code_block, render_children
from draftjs_exporter.dom import DOM
class TestDefaults(unittest.TestCase):
def test_default_block_map(self):
self.assertIsInstance(BLOCK_MAP, object)
def test_default_style_map(self):
self.assertIsInstance(STYLE_MAP, object)
def test_render_children(self):
self.assertEqual(render_children({'children': 'test'}), 'test')
def test_render_code_block(self):
self.assertEqual(DOM.render_debug(code_block({'children': 'test'})), '<pre><code>test</code></pre>')
|
[
"thibaudcolas@gmail.com"
] |
thibaudcolas@gmail.com
|
1caefba7b7e4fdb55fbe74db57fc8e404ddd15a7
|
e1e08ca2df1caadc30b5b62263fa1e769d4904d8
|
/cps/modules/usercp.py
|
c42b820652056203e9e39da4353a725554cbf8b9
|
[] |
no_license
|
tiench189/ClassbookStore
|
509cedad5cc4109b8fb126ad59e25b922dfae6be
|
4fff9bc6119d9ec922861cbecf23a3f676551485
|
refs/heads/master
| 2020-12-02T07:48:26.575023
| 2017-07-10T02:45:09
| 2017-07-10T02:45:09
| 96,728,874
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,411
|
py
|
# -*- coding: utf-8 -*-
__author__ = 'tanbm'
from datetime import datetime
def addzero(num):
if num < 10:
return "0" + str(num)
else:
return str(num)
def user_get_id_cp(member_id, db):
info = user_get_info(member_id, db)
try:
return info['user_cp_info']['cp_id']
except:
return info['user_info']['id']
#return 1
def user_get_info(member_id, db):
data_user = db(db.auth_user.id == member_id).select()
if len(data_user) <= 0:
return "Không tìm thấy thông tin"
data_user = data_user[0]
info = dict()
info['user_info'] = dict(id=data_user.id, first_name=data_user.first_name, last_name=data_user.last_name,
email=data_user.email, user_name=data_user.username)
try:
user_cp = db(db.auth_user.id == data_user.created_by).select()[0]
info['user_cp_info'] = dict(cp_id=user_cp.id, cp_first_name=user_cp.first_name, cp_last_name=user_cp.last_name,
cp_email=user_cp.email, cp_user_name=user_cp.username)
info['user_info']['is_admin'] = False
except:
info['user_cp_info'] = "Không có thông tin"
info['user_info']['is_admin'] = True
return info
def user_gen_product_code(user_cp, cp_type):
now = datetime.now()
token = addzero(now.year) + addzero(now.month) + addzero(now.day) + addzero(now.hour) + addzero(
now.minute) + addzero(now.second)
code = user_cp + cp_type[:3] + token
return code
def info_by_token(username, token, db):
user_info = db(db.auth_user.username == username)(db.auth_user.token == token).select()
if len(user_info) <= 0:
return dict(error="Hết phiên làm việc. Bạn vui lòng đăng nhập lại!")
return dict(result=user_get_info(user_info[0].id, db))
def check_is_root(token, db):
info = db((db.auth_user.token.like(token)) & (db.auth_user.is_root == True)).select()
if len(info) <= 0:
return False
else:
return True
def get_user_token(user_email, db):
token = ""
try:
if user_email is None or user_email == '':
return token
rows = db(db.clsb_user.email == user_email).select()
if len(rows) < 1:
return token
row = rows.first()
token = row['user_token']
except Exception as e:
print str(e)
return token
|
[
"caotien189@gmail.com"
] |
caotien189@gmail.com
|
a262ab878556b9c9c939d132c8e39567a05531ab
|
fc80698bcbae0b94907697fc4df023101bd19887
|
/xptracker/settings/base.py
|
1dbb792983757d847a3bab19d103e031d550cf0c
|
[
"Apache-2.0"
] |
permissive
|
Django-Lessons/xptracker
|
1ee982440ab71110f1d228479cd016ccb167db01
|
c152de874872857c8896787eeea35744e1f3e02f
|
refs/heads/master
| 2023-08-13T17:34:09.180379
| 2020-06-25T07:04:44
| 2020-06-25T07:04:44
| 270,729,777
| 2
| 1
|
NOASSERTION
| 2021-09-22T19:10:54
| 2020-06-08T15:55:14
|
Python
|
UTF-8
|
Python
| false
| false
| 2,961
|
py
|
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/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'py8=&ynt*vq4s5^$b4u!fij9=3+)qal_*xn&u6^-v&2@+ahuwn'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
SITE_ID = 1
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'core',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.sites',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'allauth',
'allauth.account',
'allauth.socialaccount',
'django_extensions'
]
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 = 'xptracker.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 = 'xptracker.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/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/3.0/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/3.0/howto/static-files/
STATIC_URL = '/static/'
AUTH_USER_MODEL = 'core.User'
|
[
"eugen@django-lessons.com"
] |
eugen@django-lessons.com
|
107043c3897bddc4c62e4fe077338a1d50b32d6f
|
43470b9aab53ae3d0f5e63402bb5727981619ddb
|
/Python/image/migrations/0002_auto_20200906_1916.py
|
4f60badb4789e3f1ea5ad3246a0dd927499d48e4
|
[] |
no_license
|
nnocturnnn/Pixelizator
|
04baa2cda666a581c6c24ca6b2d74f5999a07785
|
1386235f6e7bc01fced684e3922ef51b3f64bd59
|
refs/heads/master
| 2023-03-06T11:27:03.241013
| 2021-02-17T13:19:49
| 2021-02-17T13:19:49
| 315,136,923
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 377
|
py
|
# Generated by Django 3.1.1 on 2020-09-06 19:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('image', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='image',
name='file',
field=models.ImageField(upload_to='origin/'),
),
]
|
[
"vikchehovich@gmail.com"
] |
vikchehovich@gmail.com
|
18eac29dd0f67198041e3f6ea97457ba2bcd9a1d
|
b82057c77dd4d00ff9bca9a979a1a3075f0528c4
|
/Exicom_gateway/checks/rectifierindiv_recline1_input_voltage
|
a2a1215661ecd5575e47a479f335c922630d5c47
|
[] |
no_license
|
subhash-007/photography-blog
|
7ee0c4f930fee29d76106c45b09e6b76cb19cf56
|
b1ae66794b48bfe3862cb6e727a3a15a6ef79024
|
refs/heads/master
| 2020-03-31T04:33:00.276628
| 2019-07-12T06:00:39
| 2019-07-12T06:00:39
| 151,910,256
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,497
|
#!/usr/bin/python
import binascii
"""
vlan Poller script.
This is part of device application.
Poller script determines the vlan.
poller script takes the snmp value of OID .1.3.6.1.4.1.161.19.3.2.1.55.0 from snmp agent of device at specific interval.
all ports status are sent to device application
"""
# ######################################################################
# Function : check_exicom_model_no_invent
#
# Parameters: info (SNMP Output) _no_params(No Parameters)
#
# Output: service state and plugin output
# #####################################################################
def check_rectifierindiv_recline1_input_voltage(item, _no_params, info):
"""
check_exicom_model_no_invent function calculates vlan
Args:
item (str) Specific item on SNMP output on which we want to filter results
Kwargs:
params (tuple) Check parameters for critical and warning state of service
Returns:
state (int) :
0 : OK
1 : Warning
2: Critical
3: unknown
infotext(string):
plugin output
Example : OK - vlan=1;;;;
Raises:
Exception
"""
state = 3
infotext = "unknown_value"
input_voltage = None
index =0
perfdata = []
try:
for line in info:
index= index + 1
input_voltage = line[0]
try:
input_voltage = float(input_voltage)
except Exception,e:
input_voltage = line[0].replace(' ','@')
state = 0
perfdata.append(("recline1_%d_input_voltage" %index,input_voltage))
infotext = "recline1_input_voltage=%s" % input_voltage
except Exception,e:
infotext = "unknown_value"
return (state,infotext,perfdata)
check_info["rectifierindiv_recline1_input_voltage"] = {
'check_function': check_rectifierindiv_recline1_input_voltage,
'service_description': 'rectifierindiv_recline1_input_voltage',
'has_perfdata': True,
'snmp_info': ('.1.3.6.1.4.1.38016.14.2.8.6', ['1.7']),
'snmp_scan_function': lambda oid: "m1000" in oid(".1.3.6.1.4.1.38016.14.1.1.0").lower(),
}
|
[
"sbmoond@gmail.com"
] |
sbmoond@gmail.com
|
|
1b8ea813e6adfcf05a77b0fcdb6d9cb30cc95657
|
21bbc3fbeb7a1616dbd6993b66dc44d9b30df3e7
|
/python_training/samp_proj1/day_011118/plotting1.py
|
803db5cf4412574052bef093c3c79f673bf6c82a
|
[] |
no_license
|
PoornimaDevii/python_training
|
6124640608d8bf14289ae61b2b28e0db3b473b6f
|
42b535590a6a244a91bd48b4451b74a29c1aaa80
|
refs/heads/master
| 2020-04-05T19:55:49.723114
| 2018-12-04T11:49:59
| 2018-12-04T11:49:59
| 157,157,063
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,420
|
py
|
import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(-np.pi, np.pi, 256)
Y1 = np.sin(X)
Y2 = np.cos(X)
Y3 = np.tan(X)
Y4 = np.sqrt(1 - X*X)
plt.figure(figsize=(6,4), dpi=80) # 6 for x axis and 4 for y axis, dpi decides how large the plot will be,
# figsize is proportional x and y values
plt.plot(X,Y1, color='blue',linewidth=2.5, linestyle=':', label='sin')
#plt.show()
plt.plot(X,Y2,color='red', linewidth=2.5, label='cos')
plt.xlim(X.min()*1.2)
plt.xticks([-np.pi,-np.pi/2,0,np.pi/2,np.pi],[r'$-\pi$',r'$-\pi/2$',r'$0$',r'$\pi/2$',r'$\pi$'],rotation=30) # to view the actual values
plt.yticks([+1,0,-1],rotation=30)
ax = plt.gca()
ax.spines['right'].set_color(None)
ax.spines['top'].set_color(None)
ax.xaxis.set_ticks_position('bottom') # top means the x-axis values will be floating at the top
ax.spines['left'].set_position(('data',0))
ax.spines['bottom'].set_position(('data',0))
plt.legend(loc='best')
for labels in ax.get_xticklabels() + ax.get_yticklabels():
labels.set_fontsize(16)
labels.set_bbox(dict(facecolor='grey', # to create a box around the values ( color of box -> facecolor,
edgecolor='red', # outline of box -> edgecolor, alpha-> transparency of box
alpha=0.35))
plt.savefig('myplot.png') #savefig before show
plt.show()
plt.plot(X,Y3)
plt.ylim(Y3.min()*1.5)
plt.show()
plt.plot(X,Y4)
plt.show()
|
[
"poornimadevi.rama@gmail.com"
] |
poornimadevi.rama@gmail.com
|
f104f06f86d3958325c83c0ba9b5beffdb89c3ec
|
4b7e282fe480415f5d52c0fc0429f144156190fe
|
/google/ads/googleads/v8/services/types/campaign_simulation_service.py
|
9c4efef727ac0a515e6de9bbdcf66a4dcaca2149
|
[
"Apache-2.0"
] |
permissive
|
Z2Xsoft/google-ads-python
|
c4750357bb19da91bb3b6bf2fa84bef9d2df36d3
|
1779d52a0446c8afb2437b0a9e103dcb849f5590
|
refs/heads/main
| 2023-08-18T15:22:17.840364
| 2021-09-26T04:08:53
| 2021-09-26T04:08:53
| 410,444,398
| 0
| 0
|
Apache-2.0
| 2021-09-26T04:08:53
| 2021-09-26T03:55:38
| null |
UTF-8
|
Python
| false
| false
| 1,265
|
py
|
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import proto # type: ignore
__protobuf__ = proto.module(
package="google.ads.googleads.v8.services",
marshal="google.ads.googleads.v8",
manifest={"GetCampaignSimulationRequest",},
)
class GetCampaignSimulationRequest(proto.Message):
r"""Request message for
[CampaignSimulationService.GetCampaignSimulation][google.ads.googleads.v8.services.CampaignSimulationService.GetCampaignSimulation].
Attributes:
resource_name (str):
Required. The resource name of the campaign
simulation to fetch.
"""
resource_name = proto.Field(proto.STRING, number=1,)
__all__ = tuple(sorted(__protobuf__.manifest))
|
[
"noreply@github.com"
] |
Z2Xsoft.noreply@github.com
|
fd09d4b9e667639b7e0480f72e689ede4c098f7a
|
b5ea580240b372297b2b61922decff1aa15375e8
|
/dico/emailer.py
|
33f71525ae927efc7cddcd4ecb99ce01f0714e55
|
[] |
no_license
|
michaelcrubenstein/IDoDeclare
|
ca7e1c1ef8c89a330e0cb97e961a757039f68f66
|
1b8f4a4ca8d2bd953389d47786144502c9347921
|
refs/heads/master
| 2021-01-18T01:42:00.889655
| 2015-07-28T14:15:06
| 2015-07-28T14:15:06
| 31,086,954
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,014
|
py
|
from django.core.mail import send_mail
class Emailer():
# Sends a reset password message to the specified email recipient.
def sendResetPasswordEmail(recipientEMail, resetURL):
htmlMessage = """\
<p>There has been a request to reset your password for I Do Declare.</p>
<p>Click <a href="%s">here</a> to reset your password.</p>
<b>The I Do Declare Team</b>
""" % resetURL
message = """\
There has been a request to reset your password for I Do Declare.
Open the following link in your web browser to reset your password:
%s
Thanks.
The I Do Declare Team
""" % resetURL
send_mail('Password Reset', message, 'feedback@idodeclare.org',
[recipientEMail], fail_silently=False, html_message=htmlMessage)
def merge(html, dir):
p = re.compile(r'{{\s*([^}\s]+)\s*}}')
def f(match):
s = match.group(1)
if s in dir:
return dir[s]
else:
return s
return p.sub(f, html)
|
[
"michaelcrubenstein@gmail.com"
] |
michaelcrubenstein@gmail.com
|
3ee38094628c51ffb37b52ecd815c4075878c2a5
|
eacff46eda2c6b509449979a16002b96d4645d8e
|
/Collections-a-installer/community-general-2.4.0/tests/unit/plugins/module_utils/xenserver/conftest.py
|
52f654bcc6ab90e4315772942e04f9f690466651
|
[
"MIT",
"GPL-3.0-only",
"GPL-3.0-or-later"
] |
permissive
|
d-amien-b/simple-getwordpress
|
5e6d4d15d5f87124ab591e46b63fec552998fdc3
|
da90d515a0aa837b633d50db4d91d22b031c04a2
|
refs/heads/master
| 2023-04-08T22:13:37.347545
| 2021-04-06T09:25:51
| 2021-04-06T09:25:51
| 351,698,069
| 0
| 0
|
MIT
| 2021-03-31T16:16:45
| 2021-03-26T07:30:00
|
HTML
|
UTF-8
|
Python
| false
| false
| 3,744
|
py
|
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2019, Bojan Vitnik <bvitnik@mainstream.rs>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
import importlib
import os
import json
import pytest
from .FakeAnsibleModule import FakeAnsibleModule
from ansible.module_utils import six
from mock import MagicMock
@pytest.fixture
def fake_ansible_module(request):
"""Returns fake AnsibleModule with fake module params."""
if hasattr(request, 'param'):
return FakeAnsibleModule(request.param)
else:
params = {
"hostname": "somehost",
"username": "someuser",
"password": "somepwd",
"validate_certs": True,
}
return FakeAnsibleModule(params)
@pytest.fixture(autouse=True)
def XenAPI():
"""Imports and returns fake XenAPI module."""
# Import of fake XenAPI module is wrapped by fixture so that it does not
# affect other unit tests which could potentialy also use XenAPI module.
# First we use importlib.import_module() to import the module and assign
# it to a local symbol.
fake_xenapi = importlib.import_module('ansible_collections.community.general.tests.unit.plugins.module_utils.xenserver.FakeXenAPI')
# Now we populate Python module cache with imported fake module using the
# original module name (XenAPI). That way, any 'import XenAPI' statement
# will just load already imported fake module from the cache.
sys.modules['XenAPI'] = fake_xenapi
return fake_xenapi
@pytest.fixture(autouse=True)
def xenserver(XenAPI):
"""Imports and returns xenserver module util."""
# Since we are wrapping fake XenAPI module inside a fixture, all modules
# that depend on it have to be imported inside a test function. To make
# this easier to handle and remove some code repetition, we wrap the import
# of xenserver module util with a fixture.
from ansible_collections.community.general.plugins.module_utils import xenserver
return xenserver
@pytest.fixture
def mock_xenapi_failure(XenAPI, mocker):
"""
Returns mock object that raises XenAPI.Failure on any XenAPI
method call.
"""
fake_error_msg = "Fake XAPI method call error!"
# We need to use our MagicMock based class that passes side_effect to its
# children because calls to xenapi methods can generate an arbitrary
# hierarchy of mock objects. Any such object when called should use the
# same side_effect as its parent mock object.
class MagicMockSideEffect(MagicMock):
def _get_child_mock(self, **kw):
child_mock = super(MagicMockSideEffect, self)._get_child_mock(**kw)
child_mock.side_effect = self.side_effect
return child_mock
mocked_xenapi = mocker.patch.object(XenAPI.Session, 'xenapi', new=MagicMockSideEffect(), create=True)
mocked_xenapi.side_effect = XenAPI.Failure(fake_error_msg)
return mocked_xenapi, fake_error_msg
@pytest.fixture
def fixture_data_from_file(request):
"""Loads fixture data from files."""
if not hasattr(request, 'param'):
return {}
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
fixture_data = {}
if isinstance(request.param, six.string_types):
request.param = [request.param]
for fixture_name in request.param:
path = os.path.join(fixture_path, fixture_name)
with open(path) as f:
data = f.read()
try:
data = json.loads(data)
except Exception:
pass
fixture_data[fixture_name] = data
return fixture_data
|
[
"test@burdo.fr"
] |
test@burdo.fr
|
f2fe8040e6b6e400ff5b3e70fd88c10f94a82945
|
75f0580af1734b9edb9e06bfadfe48f45b057872
|
/2019/8/sol.py
|
6052c056bbeb201b13ed23d24370c34a7c3d6a11
|
[] |
no_license
|
penteract/adventofcode
|
5bb317f8093f60c1d776d0983016a5288d059603
|
7b7344708ef1d58caa339a32a13f3390556b664c
|
refs/heads/master
| 2023-01-29T16:08:13.541190
| 2023-01-16T20:21:02
| 2023-01-16T20:21:02
| 160,901,373
| 5
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,104
|
py
|
from functools import *
from itertools import *
from collections import defaultdict
print ("hi")
f = open("input")
l = list(f)
print(len(l))
print(len(l[0]))
dat = l[0][:-1]
x=0
lays=[]
while x<len(dat):
lays.append(dat[x:x+25*6])
x+=25*6
print(x)
print("here")
print(min([(l.count("0"),l.count("1")*l.count("2")) for l in lays ]))
dd=["2" for i in range(25*6)]
for l in lays:
for i,x in enumerate(l):
if dd[i]=="2": dd[i]=x
for i in range(6):
print("".join(dd[25*i:25*(i+1)]))
for i in range(6):
print("".join(" " if c== "0" else "#" for c in dd[25*i:25*(i+1)]))
##d={"COM":[]}
##
##for a,b in inp:#b orbits a
## if a not in d:
## d[a]=[]
## d[a].append(b)
## if b not in d:
## d[b]=[]
##
##def f(c,n=0):
## tot=n
## for x in d[c]:
## tot += f(x,n+1)
## return tot
##print (f("COM"))
##
##
##def dist(x,y):
## if x==y:
## return 0
## return min([10000]+[1+dist(z,y) for z in d[x]])
##
##print(min(dist(x,"SAN")+dist(x,"YOU")-2 for x in d))
#lll = list(map(int,l[0].split(",")) )#+[0 for i in range(3850694)]
|
[
"tcathcartburn@gmail.com"
] |
tcathcartburn@gmail.com
|
25ebe5fafa9fe727571d9b95d86bb183de99cf83
|
b76615ff745c6d66803506251c3d4109faf50802
|
/pyobjc-framework-ApplicationServices/PyObjCTest/test_axactionconstants.py
|
0fd99b65a921cc20e9aef2f2d09a1649d4f9ee0a
|
[
"MIT"
] |
permissive
|
danchr/pyobjc-git
|
6ef17e472f54251e283a0801ce29e9eff9c20ac0
|
62b787fddeb381184043c7ff136f1c480755ab69
|
refs/heads/master
| 2021-01-04T12:24:31.581750
| 2020-02-02T20:43:02
| 2020-02-02T20:43:02
| 240,537,392
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 858
|
py
|
import HIServices
from PyObjCTools.TestSupport import *
class TestAXActionConstants(TestCase):
def testConstants(self):
self.assertEqual(HIServices.kAXPressAction, "AXPress")
self.assertEqual(HIServices.kAXIncrementAction, "AXIncrement")
self.assertEqual(HIServices.kAXDecrementAction, "AXDecrement")
self.assertEqual(HIServices.kAXConfirmAction, "AXConfirm")
self.assertEqual(HIServices.kAXCancelAction, "AXCancel")
self.assertEqual(HIServices.kAXShowAlternateUIAction, "AXShowAlternateUI")
self.assertEqual(HIServices.kAXShowDefaultUIAction, "AXShowDefaultUI")
self.assertEqual(HIServices.kAXRaiseAction, "AXRaise")
self.assertEqual(HIServices.kAXShowMenuAction, "AXShowMenu")
self.assertEqual(HIServices.kAXPickAction, "AXPick")
if __name__ == "__main__":
main()
|
[
"ronaldoussoren@mac.com"
] |
ronaldoussoren@mac.com
|
a7d3c422b559f44ac3e3715060cf05f7dd47073a
|
f879a7bc37da3fa998fc6925b8cede788cde6a70
|
/lunch/migrations/0001_initial.py
|
81c83ebf338d11f881cf9a075d340bfbfeee507b
|
[
"MIT"
] |
permissive
|
pythondev0101/eats_easy_ordering_system
|
65672c90d6937cdf3173b0e3445dc2967b296fe4
|
f65a88b4a46e056be35909799a01784f741cdfac
|
refs/heads/master
| 2021-08-22T22:32:39.358470
| 2019-05-08T15:50:56
| 2019-05-08T15:50:56
| 168,003,924
| 0
| 0
|
MIT
| 2021-06-10T21:18:36
| 2019-01-28T17:22:58
|
Python
|
UTF-8
|
Python
| false
| false
| 1,703
|
py
|
# Generated by Django 2.1.5 on 2019-03-28 22:30
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('core', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Order',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(default='', max_length=255)),
('total', models.DecimalField(decimal_places=2, max_digits=9, verbose_name='Total')),
('status', models.CharField(blank=True, choices=[('new', 'New'), ('received', 'Received'), ('ordered', 'Ordered'), ('cancelled', 'Cancelled')], default='new', max_length=10, verbose_name='Status')),
('date', models.DateField()),
('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='OrderLine',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date', models.DateField(null=True, verbose_name='Date')),
('order', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='lunch.Order')),
('product', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.Product')),
],
),
]
|
[
"rmontemayor0101@gmail.com"
] |
rmontemayor0101@gmail.com
|
74008430a1be80fcb8c52208585fda0fb87e88c3
|
9716798c8ede92793d5dece271f7d2d2cb8f718e
|
/django-backend/grants/migrations/0003_auto_20160622_2128.py
|
c562bd57d5e9e1ab867f5406efa6b9c716039607
|
[] |
no_license
|
experiment/experiment-grant-scapie-mcscrapeface
|
020066f42be1503dcaecb43a9e90b1091bf67d87
|
43388d3a621df1fcaf5ae57656b7537a384b4ed0
|
refs/heads/master
| 2021-01-18T04:51:31.871971
| 2016-06-26T20:41:54
| 2016-06-26T20:41:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 956
|
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-06-22 21:28
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('grants', '0002_auto_20160615_1928'),
]
operations = [
migrations.CreateModel(
name='Funder',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=500)),
],
),
migrations.RemoveField(
model_name='grant',
name='organization',
),
migrations.AddField(
model_name='grant',
name='funder',
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='grants.Funder'),
),
]
|
[
"frey.maxim@gmail.com"
] |
frey.maxim@gmail.com
|
8980dbace4b9b52b7f3d2df6afa42b4cb87ba0e1
|
de4da7c45581f72adaf8e328a89cb3d57fe3613f
|
/fundamentos/slides/marcoandre/pyMordida0-fontes/py33.py
|
12654acc12581c53d9458751e59ef50bb3a132ab
|
[] |
no_license
|
ramalho/propython
|
2469be7492554762d05f9b0ce5c0dc3a51bd3a18
|
76c2b52755e08d49929cdc2a523db72735240e72
|
refs/heads/master
| 2022-06-01T22:51:07.659074
| 2022-05-22T18:22:21
| 2022-05-22T18:22:21
| 140,458
| 39
| 13
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 207
|
py
|
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from random import shuffle
palavra = 'python'
print palavra
l = list(palavra)
print l
shuffle(l)
print l
palavraEmbaralhada = ''.join(l)
print palavraEmbaralhada
|
[
"luciano@ramalho.org"
] |
luciano@ramalho.org
|
6a183eba351a084f4cfb4b32477ae15de49b2df7
|
b2a3328ec0caeb4231528094ec374f8168b08e91
|
/Scence/Scence/authrouter.py
|
5fb3b54537fa43dd3338f9df122cb9becc294916
|
[] |
no_license
|
sugerStill/ScenceWeb
|
1185d10b300d57af22cc72cbc6b50e1840bdc127
|
b189ea27d9ca383528d095ab3d81c79c87fbaea2
|
refs/heads/master
| 2020-06-05T19:37:50.446509
| 2019-06-18T11:47:12
| 2019-06-18T11:47:12
| 192,527,209
| 1
| 0
| null | 2019-06-18T11:31:28
| 2019-06-18T11:31:28
| null |
UTF-8
|
Python
| false
| false
| 1,642
|
py
|
from django.conf import settings
DATABASE_MAPPING = settings.DATABASE_APPS_MAPPING
class AuthRouter:
def db_for_read(self, model, **hints):
if model._meta.app_label == 'TrafficView':
return 'trafficdatabase'
if model._meta.app_label == "ScenceView":
return "webdata"
if model._meta.app_label == "weather":
return "weather"
if model._meta.app_label == "internetdata":
return "internetdata"
return None
def db_for_write(self, model, **hints):
if model._meta.app_label == 'TrafficView':
return 'trafficdatabase'
if model._meta.app_label == "ScenceView":
return "webdata"
if model._meta.app_label == "weather":
return "weather"
if model._meta.app_label == "internetdata":
return "internetdata"
return None
def allow_relation(self, obj1, obj2, **hints):
db_list = ['trafficdatabase', 'webdata', 'weather', 'internetdata']
if obj1._state.db in db_list and obj2._state.db in db_list:
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
if app_label == 'TrafficView':
return 'trafficdatabase ' if db == "trafficdatabase" else False
elif app_label == 'ScenceView':
return 'webdata' if db == "webdata" else False
elif app_label == 'weather':
return 'weather' if db == "weather" else False
elif app_label == "internet":
return "internetdata" if db == "internetdata" else False
return None
|
[
"2214057556@qq.com"
] |
2214057556@qq.com
|
9766fca774c3ffe621b37970eadc241e084e6d66
|
7a4da5ec2196bf975a9e6115846244788b36b952
|
/3.7.0/lldb-3.7.0.src/test/expression_command/call-function/TestCallStdStringFunction.py
|
c36577a54133afe6418d68e03c4acf03aee2a13d
|
[
"NCSA",
"MIT"
] |
permissive
|
androm3da/clang_sles
|
ca4ada2ec85d625c65818ca9b60dcf1bc27f0756
|
2ba6d0711546ad681883c42dfb8661b842806695
|
refs/heads/master
| 2021-01-10T13:50:25.353394
| 2016-03-31T21:38:29
| 2016-03-31T21:38:29
| 44,787,977
| 3
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,117
|
py
|
"""
Test calling std::String member functions.
"""
import unittest2
import lldb
import lldbutil
from lldbtest import *
class ExprCommandCallFunctionTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
def setUp(self):
# Call super's setUp().
TestBase.setUp(self)
# Find the line number to break for main.c.
self.line = line_number('main.cpp',
'// Please test these expressions while stopped at this line:')
@skipUnlessDarwin
@dsym_test
@expectedFailureDarwin(16361880) # <rdar://problem/16361880>, we get the result correctly, but fail to invoke the Summary formatter.
def test_with_dsym(self):
"""Test calling std::String member function."""
self.buildDsym()
self.call_function()
@dwarf_test
@expectedFailureFreeBSD('llvm.org/pr17807') # Fails on FreeBSD buildbot
@expectedFailureIcc # llvm.org/pr14437, fails with ICC 13.1
@expectedFailureDarwin(16361880) # <rdar://problem/16361880>, we get the result correctly, but fail to invoke the Summary formatter.
def test_with_dwarf(self):
"""Test calling std::String member function."""
self.buildDwarf()
self.call_function()
def call_function(self):
"""Test calling std::String member function."""
self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
# Some versions of GCC encode two locations for the 'return' statement in main.cpp
lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1, loc_exact=True)
self.runCmd("run", RUN_SUCCEEDED)
self.expect("print str",
substrs = ['Hello world'])
# Calling this function now succeeds, but we follow the typedef return type through to
# const char *, and thus don't invoke the Summary formatter.
self.expect("print str.c_str()",
substrs = ['Hello world'])
if __name__ == '__main__':
import atexit
lldb.SBDebugger.Initialize()
atexit.register(lambda: lldb.SBDebugger.Terminate())
unittest2.main()
|
[
"brian.cain@gmail.com"
] |
brian.cain@gmail.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.