blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
616
| 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 777
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 149
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 3
10.2M
| extension
stringclasses 188
values | content
stringlengths 3
10.2M
| authors
listlengths 1
1
| author_id
stringlengths 1
132
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f29162293d3a13e04e0d593b2f83ffadeb585c75 | 3dcfa266c4b7321a4c3a224b98f9ca0dff891e47 | /archives/weather.py | 34f3228017b06836750a7051d94df776a005b29f | []
| no_license | CandyTt20/Notes | a2ef681d123c5219a29334e99aeb900b74bf1834 | ec092f881122ebdd91ef9764ec7ce4d9cc4723ae | refs/heads/master | 2022-08-21T18:08:33.204223 | 2020-05-19T23:55:49 | 2020-05-19T23:55:49 | 255,209,760 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 985 | py | import matplotlib
from matplotlib import pyplot as plt
import random
import io
import sys
# 改变标准输出的默认编码
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf8')
# 绘图中设置中文字体显示以及粗细MicroSoft YaHei
font = {'family': 'MicroSoft YaHei',
'weight': 'bold',
'size': '10'}
matplotlib.rc("font", **font)
# 设置画图大小
plt.figure(figsize=(50, 10), dpi=80)
t = [random.randint(20, 35) for i in range(0, 120, 10)]
x = range(0, 120, 10)
# 坐标轴显示字符串
_x = x
_x_tick_1 = ['10点{}分'.format(i) for i in range(10, 60, 10)]
_x_tick_2 = ['11点{}分'.format(i) for i in range(0, 60, 10)]
for i in _x_tick_2:
_x_tick_1.append(i)
_x_tick_1.append('12点0分')
plt.xticks(_x, _x_tick_1, rotation=45) # 字符要和数字一一对应,rotation->旋转字符
# 设置描述信息
plt.xlabel('时间')
plt.ylabel('温度(摄氏度)')
plt.title('温度变化图')
# 画图
plt.plot(x, t)
plt.show()
| [
"[email protected]"
]
| |
2228c4692a90aa59d2655ff1ce6cc044e27f3662 | c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c | /cases/pa2/sample/expr_id-7.py | 6734afff5e760b3c35cb53011e1e7c464aebcad8 | []
| no_license | Virtlink/ccbench-chocopy | c3f7f6af6349aff6503196f727ef89f210a1eac8 | c7efae43bf32696ee2b2ee781bdfe4f7730dec3f | refs/heads/main | 2023-04-07T15:07:12.464038 | 2022-02-03T15:42:39 | 2022-02-03T15:42:39 | 451,969,776 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 17 | py | x:$ID = 1
x - 1
| [
"[email protected]"
]
| |
3edf3d407e6ecd51e113a38e8f163fb129b401ad | 54f352a242a8ad6ff5516703e91da61e08d9a9e6 | /Source Codes/AtCoder/abc059/B/4903797.py | b032dc42a02c10e399ae6919bab6161e7ebcff25 | []
| no_license | Kawser-nerd/CLCDSA | 5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb | aee32551795763b54acb26856ab239370cac4e75 | refs/heads/master | 2022-02-09T11:08:56.588303 | 2022-01-26T18:53:40 | 2022-01-26T18:53:40 | 211,783,197 | 23 | 9 | null | null | null | null | UTF-8 | Python | false | false | 149 | py | ab = [int(input()) for i in range(2)]
if (ab[0] > ab[1]):
print("GREATER")
elif (ab[0] < ab[1]):
print("LESS")
else:
print("EQUAL") | [
"[email protected]"
]
| |
c343a8e6103ecb162f0314933cee28a37ae3e35c | 43102360e998f8972e06689f64f39c7cf22479d7 | /Decision Trees/Applying Decision Trees-92.py | 59662f44cd14ce508327652d24d4176d49e44b9b | []
| no_license | HarshCasper/Dataquest-Tracks | 8da914101c19442a63ab46732a1cc792c135c3c9 | 9fc87415377824cf2c82d9ed34178ee53509eb67 | refs/heads/master | 2020-12-21T21:04:19.015006 | 2020-01-27T18:28:55 | 2020-01-27T18:28:55 | 236,560,422 | 5 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,619 | py | ## 2. Using Decision Trees With scikit-learn ##
from sklearn.tree import DecisionTreeClassifier
# A list of columns to train with
# We've already converted all columns to numeric
columns = ["age", "workclass", "education_num", "marital_status", "occupation", "relationship", "race", "sex", "hours_per_week", "native_country"]
# Instantiate the classifier
# Set random_state to 1 to make sure the results are consistent
clf = DecisionTreeClassifier(random_state=1)
# We've already loaded the variable "income," which contains all of the income data
clf.fit(income[columns], income["high_income"])
## 3. Splitting the Data into Train and Test Sets ##
import numpy
import math
# Set a random seed so the shuffle is the same every time
numpy.random.seed(1)
# Shuffle the rows
# This permutes the index randomly using numpy.random.permutation
# Then, it reindexes the dataframe with the result
# The net effect is to put the rows into random order
income = income.reindex(numpy.random.permutation(income.index))
train_max_row = math.floor(income.shape[0] * .8)
train = income.iloc[:train_max_row]
test = income.iloc[train_max_row:]
## 4. Evaluating Error With AUC ##
from sklearn.metrics import roc_auc_score
clf = DecisionTreeClassifier(random_state=1)
clf.fit(train[columns], train["high_income"])
predictions = clf.predict(test[columns])
error = roc_auc_score(test["high_income"], predictions)
print(error)
## 5. Computing Error on the Training Set ##
predictions = clf.predict(train[columns])
print(roc_auc_score(train["high_income"], predictions))
## 7. Reducing Overfitting With a Shallower Tree ##
# Decision trees model from the last screen
clf = DecisionTreeClassifier(random_state=1)
clf = DecisionTreeClassifier(min_samples_split=13, random_state=1)
clf.fit(train[columns], train["high_income"])
predictions = clf.predict(test[columns])
test_auc = roc_auc_score(test["high_income"], predictions)
train_predictions = clf.predict(train[columns])
train_auc = roc_auc_score(train["high_income"], train_predictions)
print(test_auc)
print(train_auc)
## 8. Tweaking Parameters to Adjust AUC ##
# The first decision trees model we trained and tested
clf = DecisionTreeClassifier(random_state=1)
clf.fit(train[columns], train["high_income"])
predictions = clf.predict(test[columns])
test_auc = roc_auc_score(test["high_income"], predictions)
train_predictions = clf.predict(train[columns])
train_auc = roc_auc_score(train["high_income"], train_predictions)
print(test_auc)
print(train_auc)
clf = DecisionTreeClassifier(random_state=1, min_samples_split=13, max_depth=7)
clf.fit(train[columns], train["high_income"])
predictions = clf.predict(test[columns])
test_auc = roc_auc_score(test["high_income"], predictions)
train_predictions = clf.predict(train[columns])
train_auc = roc_auc_score(train["high_income"], train_predictions)
print(test_auc)
print(train_auc)
## 9. Tweaking Tree Depth to Adjust AUC ##
# The first decision tree model we trained and tested
clf = DecisionTreeClassifier(random_state=1)
clf.fit(train[columns], train["high_income"])
predictions = clf.predict(test[columns])
test_auc = roc_auc_score(test["high_income"], predictions)
train_predictions = clf.predict(train[columns])
train_auc = roc_auc_score(train["high_income"], train_predictions)
print(test_auc)
print(train_auc)
clf = DecisionTreeClassifier(random_state=1, min_samples_split=100, max_depth=2)
clf.fit(train[columns], train["high_income"])
predictions = clf.predict(test[columns])
test_auc = roc_auc_score(test["high_income"], predictions)
train_predictions = clf.predict(train[columns])
train_auc = roc_auc_score(train["high_income"], train_predictions)
print(test_auc)
print(train_auc)
## 12. Exploring Decision Tree Variance ##
numpy.random.seed(1)
# Generate a column containing random numbers from 0 to 4
income["noise"] = numpy.random.randint(4, size=income.shape[0])
# Adjust "columns" to include the noise column
columns = ["noise", "age", "workclass", "education_num", "marital_status", "occupation", "relationship", "race", "sex", "hours_per_week", "native_country"]
# Make new train and test sets
train_max_row = math.floor(income.shape[0] * .8)
train = income.iloc[:train_max_row]
test = income.iloc[train_max_row:]
# Initialize the classifier
clf = DecisionTreeClassifier(random_state=1)
clf.fit(train[columns], train["high_income"])
predictions = clf.predict(test[columns])
test_auc = roc_auc_score(test["high_income"], predictions)
train_predictions = clf.predict(train[columns])
train_auc = roc_auc_score(train["high_income"], train_predictions)
print(test_auc)
print(train_auc) | [
"[email protected]"
]
| |
83b38141d2b2a9fe4ace95e23ea76ba72ddbf024 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02753/s018106418.py | 43f2350835f00370c906db3dceb850869d7371e6 | []
| no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 148 | py | # A - Station and Bus
# https://atcoder.jp/contests/abc158/tasks/abc158_a
s = input()
if len(set(s)) == 2:
print('Yes')
else:
print('No')
| [
"[email protected]"
]
| |
1bf2e6f3d5b517933c42a191a777276597e6abbb | 58509347cca790fce26884f027425170c5891a17 | /deep_image_converter/loss/base_loss.py | bc1534d557ddf20f3091662c29ed216000fbf416 | []
| no_license | Hiroshiba/signico_real_to_anime | e22d07ca6531b75b3987ecc309e02bcd405f6f61 | 0a68b132fc77e24539d7ddc65b3078fd0c7f3858 | refs/heads/master | 2021-01-19T23:25:37.149611 | 2018-03-21T17:24:32 | 2018-03-21T17:32:45 | 88,979,946 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,249 | py | from abc import ABCMeta, abstractmethod
import chainer
from deep_image_converter.config import LossConfig
class BaseLoss(object, metaclass=ABCMeta):
def __init__(self, config: LossConfig, model):
self.config = config
self.model = model
@staticmethod
def blend_loss(loss, blend_config):
assert sorted(loss.keys()) == sorted(blend_config.keys()), '{} {}'.format(loss.keys(), blend_config.keys())
sum_loss = None
for key in sorted(loss.keys()):
blend = blend_config[key]
if blend == 0.0:
continue
l = loss[key] * blend_config[key]
if sum_loss is None:
sum_loss = l
else:
sum_loss += l
return sum_loss
def should_compute(self, key: str):
return key in self.config.blend['main']
def get_loss_names(self):
return ['sum_loss'] + list(self.config.blend['main'].keys())
@abstractmethod
def forward(self, *args, **kwargs):
pass
@abstractmethod
def make_loss(self, outputs, target):
pass
@abstractmethod
def sum_loss(self, loss):
pass
@abstractmethod
def test(self, *args, **kwargs):
pass
| [
"[email protected]"
]
| |
bf77468ee650a613d6bf14b965954b3156f6dfcd | f70d11f54732808c4ed40886bdd57bbdca6542eb | /pyalgotrade/tools/resample.py | a8a8ae23b99fed15d20a792c88399406d61cf367 | [
"Apache-2.0"
]
| permissive | stephenagyeman/pyalgotrade | 1aa4c22b20c707791c5e81ad1bdfb8fb55c8d542 | a783b8da8c63a1fc25a4bdee560d4c5a6e0c1a8c | refs/heads/master | 2021-01-15T12:03:16.370138 | 2014-01-14T02:15:41 | 2014-01-14T02:15:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,927 | py | # PyAlgoTrade
#
# Copyright 2011-2013 Gabriel Martin Becedillas Ruiz
#
# 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.
"""
.. moduleauthor:: Gabriel Martin Becedillas Ruiz <[email protected]>
"""
import os
from pyalgotrade import observer
from pyalgotrade.dataseries import resampled
datetime_format = "%Y-%m-%d %H:%M:%S"
class CSVFileWriter(object):
def __init__(self, csvFile):
self.__file = open(csvFile, "w")
self.__writeLine("Date Time", "Open", "High", "Low", "Close", "Volume", "Adj Close")
def __writeLine(self, *values):
line = ",".join([str(value) for value in values])
self.__file.write(line)
self.__file.write(os.linesep)
def writeSlot(self, slot):
adjClose = slot.getAdjClose()
if adjClose is None:
adjClose = ""
dateTime = slot.getDateTime().strftime(datetime_format)
self.__writeLine(dateTime, slot.getOpen(), slot.getHigh(), slot.getLow(), slot.getClose(), slot.getVolume(), adjClose)
def close(self):
self.__file.close()
class Sampler(object):
def __init__(self, barFeed, frequency, csvFile):
instruments = barFeed.getRegisteredInstruments()
if len(instruments) != 1:
raise Exception("Only barfeeds with 1 instrument can be resampled")
barFeed.getNewBarsEvent().subscribe(self.__onBars)
self.__barFeed = barFeed
self.__frequency = frequency
self.__instrument = instruments[0]
self.__slot = None
self.__writer = CSVFileWriter(csvFile)
def __onBars(self, dateTime, bars):
slotDateTime = resampled.get_slot_datetime(dateTime, self.__frequency)
bar = bars[self.__instrument]
if self.__slot is None:
self.__slot = resampled.Slot(slotDateTime, bar)
elif self.__slot.getDateTime() == slotDateTime:
self.__slot.addBar(bar)
else:
self.__writer.writeSlot(self.__slot)
self.__slot = resampled.Slot(slotDateTime, bar)
def finish(self):
if self.__slot is not None:
self.__writer.writeSlot(self.__slot)
self.__writer.close()
def resample_impl(barFeed, frequency, csvFile):
sampler = Sampler(barFeed, frequency, csvFile)
# Process all bars.
disp = observer.Dispatcher()
disp.addSubject(barFeed)
disp.run()
sampler.finish()
def resample_to_csv(barFeed, frequency, csvFile):
"""Resample a BarFeed into a CSV file grouping bars by a certain frequency.
The resulting file can be loaded using :class:`pyalgotrade.barfeed.csvfeed.GenericBarFeed`.
The CSV file will have the following format:
::
Date Time,Open,High,Low,Close,Volume,Adj Close
2013-01-01 00:00:00,13.51001,13.56,13.51,13.56,273.88014126,13.51001
:param barFeed: The bar feed that will provide the bars. It should only hold bars from a single instrument.
:type barFeed: :class:`pyalgotrade.barfeed.BarFeed`
:param frequency: The grouping frequency in seconds. Must be > 0.
:param csvFile: The path to the CSV file to write.
:type csvFile: string.
.. note::
* Datetimes are stored without timezone information.
* **Adj Close** column may be empty if the input bar feed doesn't have that info.
"""
if frequency > 0:
resample_impl(barFeed, frequency, csvFile)
else:
raise Exception("Invalid frequency")
| [
"[email protected]"
]
| |
ac862313a9b98f5a1267b8153262f40789aaf7b9 | 5c900c1801e73aad21a90e97d73e8f10c9f31129 | /src/02_convert_xlsx_to_rdf.py | 631659e6768279523bbd07ac609632d3d0d969fd | [
"Apache-2.0"
]
| permissive | utda/kunshujo | 024ea7bb1016ba28ae17632ad5e998203bab16fa | fbae79171dfd017a47a89bcb18d7862711f0689f | refs/heads/master | 2022-09-11T12:09:23.438408 | 2022-08-31T05:19:52 | 2022-08-31T05:19:52 | 156,177,231 | 0 | 1 | Apache-2.0 | 2022-08-31T05:20:36 | 2018-11-05T07:27:44 | Python | UTF-8 | Python | false | false | 1,685 | py | import pandas as pd
from rdflib import URIRef, BNode, Literal, Graph
from rdflib.namespace import RDF, RDFS, FOAF, XSD
from rdflib import Namespace
import numpy as np
import math
import sys
import argparse
import json
def parse_args(args=sys.argv[1:]):
""" Get the parsed arguments specified on this script.
"""
parser = argparse.ArgumentParser(description="")
parser.add_argument(
'path',
action='store',
type=str,
help='Ful path.')
return parser.parse_args(args)
args = parse_args()
path = args.path
g = Graph()
df = pd.read_excel(path, sheet_name=0, header=None, index_col=None)
r_count = len(df.index)
c_count = len(df.columns)
map = {}
for i in range(1, c_count):
label = df.iloc[0, i]
uri = df.iloc[1, i]
type = df.iloc[2, i]
if not pd.isnull(type):
obj = {}
map[i] = obj
obj["label"] = label
obj["uri"] = uri
obj["type"] = type
for j in range(3, r_count):
subject = df.iloc[j,0]
subject = URIRef(subject)
for i in map:
value = df.iloc[j,i]
if not pd.isnull(value) and value != 0:
obj = map[i]
p = URIRef(obj["uri"])
if obj["type"].upper() == "RESOURCE":
g.add((subject, p, URIRef(value)))
else:
g.add((subject, p, Literal(value)))
g.serialize(destination=path+'.rdf')
json_path = path+'.json'
f2 = open(json_path, "wb")
f2.write(g.serialize(format='json-ld'))
f2.close()
with open(json_path) as f:
df = json.load(f)
with open(path+"_min.json", 'w') as f:
json.dump(df, f, ensure_ascii=False, sort_keys=True, separators=(',', ': '))
| [
"[email protected]"
]
| |
c346eb614b07d36c5320bc514531a1b812e3e811 | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /v8/tools/testrunner/local/pool_unittest.py | 335d20a6bf9a71a8efd476cc4b67aa83e812b801 | [
"BSD-3-Clause",
"SunPro",
"bzip2-1.0.6"
]
| permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | Python | false | false | 1,252 | py | #!/usr/bin/env python
# Copyright 2014 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
from pool import Pool
def Run(x):
if x == 10:
raise Exception("Expected exception triggered by test.")
return x
class PoolTest(unittest.TestCase):
def testNormal(self):
results = set()
pool = Pool(3)
for result in pool.imap_unordered(Run, [[x] for x in range(0, 10)]):
results.add(result.value)
self.assertEquals(set(range(0, 10)), results)
def testException(self):
results = set()
pool = Pool(3)
for result in pool.imap_unordered(Run, [[x] for x in range(0, 12)]):
# Item 10 will not appear in results due to an internal exception.
results.add(result.value)
expect = set(range(0, 12))
expect.remove(10)
self.assertEquals(expect, results)
def testAdd(self):
results = set()
pool = Pool(3)
for result in pool.imap_unordered(Run, [[x] for x in range(0, 10)]):
results.add(result.value)
if result.value < 30:
pool.add([result.value + 20])
self.assertEquals(set(range(0, 10) + range(20, 30) + range(40, 50)),
results)
| [
"[email protected]"
]
| |
5a40aaec7aacb3d61f3c59a5a873c57e5c626c01 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02630/s691363854.py | db496ce9e82c844b6fd645661f57cc1b9cd4e228 | []
| no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 322 | py | from collections import defaultdict
N = int(input())
A = list(map(int, input().split()))
Q = int(input())
d = defaultdict(int)
ans = 0
for a in A:
ans += a
d[a] += 1
for _ in range(Q):
b, c = map(int, input().split())
n = d[b]
ans -= n * b
ans += n * c
print(ans)
d[b] = 0
d[c] += n | [
"[email protected]"
]
| |
fb7272b01c3d2d1856ab5326a9e09a3f548ce4b6 | 757b100c2689f61dbd140672fc10059938bda603 | /SportsSimulation/sportsSchedule_algo.py | 9d1b323bee878638324f1f70b3030fefd4325dac | []
| no_license | tbkrft567/Portfolio | 089d8d94d735bbb757eb61688c515f9f25451595 | bbe514905a734e14c0bda5579928fdc9dad5a69e | refs/heads/master | 2023-03-15T23:02:01.640998 | 2021-02-21T21:32:44 | 2021-02-21T21:32:44 | 231,143,663 | 0 | 0 | null | 2023-03-08T20:27:46 | 2019-12-31T20:31:56 | HTML | UTF-8 | Python | false | false | 3,531 | py |
def generateSchedule(numOfTeams):
scheduleGrid = []
weeklyGrid = []
for x in range(numOfTeams): # Create a grid for all matches to be played
scheduleGrid.append([])
weeklyGrid.append([])
allMatches = []
for home in range(1, numOfTeams+1): # Insert all matches to be played
for away in range(1, numOfTeams+1):
allMatches.append([home, away])
match = 0
team = 1
for x in range(len(scheduleGrid)):
while match < len(allMatches):
if allMatches[match][0] != team and scheduleGrid[x][len(scheduleGrid) - 1] != None:
break
if allMatches[match][0] != allMatches[match][1]:
scheduleGrid[x].append(allMatches[match])
weeklyGrid[x].append([])
else:
scheduleGrid[x].append(None)
weeklyGrid[x].append([])
match += 1
team += 1
matchesToPlay = pow(numOfTeams, 2) - numOfTeams
matchesPerWeek = int(numOfTeams / 2)
weeks = int(matchesToPlay / matchesPerWeek)
for nullValue in range(numOfTeams):
weeklyGrid[nullValue][nullValue].append(None)
x = 0
for weekCount in range(1, int(weeks)+1):
for row in range(len(weeklyGrid)):
for col in range(len(weeklyGrid[row])):
if row == col:
continue
rowTotal = 0
for tempCol in range(numOfTeams):
if len(weeklyGrid[row][tempCol]) != 0 and weeklyGrid[row][tempCol][0] != None:
rowTotal += 1
colTotal = 0
for tempRow in range(numOfTeams):
if len(weeklyGrid[tempRow][col]) != 0 and weeklyGrid[tempRow][col][0] != None:
colTotal += 1
if rowTotal == weekCount:
break
if colTotal == weekCount:
continue
if row > col:
continue
if len(weeklyGrid[row][col]) == 0:
weeklyGrid[row][col].append(weekCount)
weeklyGrid[col][row].append(
int(weekCount + ((pow(numOfTeams, 2) - numOfTeams) / (numOfTeams / 2) / 2)))
break
for homeTeam in range(numOfTeams):
for awayTeam in range(numOfTeams):
if scheduleGrid[homeTeam][awayTeam] == None:
continue
scheduleGrid[homeTeam][awayTeam].append(weeklyGrid[homeTeam][awayTeam][0])
leagueSchedule = []
for weekCount in range(1, weeks+1):
matchesConfirmed = 0
for homeTeam in range(numOfTeams): #Row
for awayTeam in range(numOfTeams): #Col
if scheduleGrid[homeTeam][awayTeam] != None:
if scheduleGrid[homeTeam][awayTeam][2] == weekCount:
leagueSchedule.append(scheduleGrid[homeTeam][awayTeam])
matchesConfirmed += 1
#if scheduleGrid[homeTeam][awayTeam][0] or [1] == homeTeam break awayTeam FOR
if scheduleGrid[homeTeam][awayTeam][0] == homeTeam+1 or scheduleGrid[homeTeam][awayTeam][1] == homeTeam+1:
break
if matchesConfirmed == matchesPerWeek:
break
if matchesConfirmed == matchesPerWeek:
break
return leagueSchedule
numOfTeams = 16
Schedule = generateSchedule(numOfTeams)
print(len(Schedule)) | [
"[email protected]"
]
| |
4e4eae80ffa5c9109129d78b060c7b96e3479ca3 | 656c384011734403e60a205ffa44bd7a494ebaff | /migrations/versions/b509892e3432_.py | cb902f6cd5fb52b8c0f7e01248c8f702bfafe762 | []
| no_license | jreiher2003/Composite | cf721737917b3b50f83f7bc8790804f35de82797 | 3547b0ec8568d2212a530b14ccf358acf2e6bec3 | refs/heads/master | 2021-01-21T04:47:25.694869 | 2016-07-22T21:38:20 | 2016-07-22T21:38:20 | 53,373,294 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 764 | py | """empty message
Revision ID: b509892e3432
Revises: None
Create Date: 2016-07-21 17:53:01.499715
"""
# revision identifiers, used by Alembic.
revision = 'b509892e3432'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('users',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(), nullable=True),
sa.Column('password', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('username')
)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('users')
### end Alembic commands ###
| [
"[email protected]"
]
| |
68f198e20b5cf9bd2d0f06bd412da9e1b1e528ef | 568da13e0f0bfc3276508d67b020adea04f3036a | /final/170401067/tcpI.py | ccf2b2f4734d1f601b25d25fb5169fdd6b13e16d | [
"Unlicense"
]
| permissive | BaranAkcakaya/blm304 | 75a6be14afb0d9a012d17c56bd1e5ad5abe03630 | 3bca2b2520e673d15c0667418789903b119b9170 | refs/heads/master | 2022-10-15T21:04:49.367816 | 2020-06-08T12:34:02 | 2020-06-08T12:34:02 | 267,668,790 | 0 | 0 | Unlicense | 2020-06-07T13:36:48 | 2020-05-28T18:42:21 | Python | UTF-8 | Python | false | false | 889 | py | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 3 22:26:03 2020
@author: EnesNK
"""
import socket
import os
# Socket oluşturulması
s = socket.socket()
# Bağlanılacak adres ve port
host = "192.168.1.32"
port = 142
try:
# Bağlantıyı yap
komut = 'sudo date --set="'
s.connect((host, port))
# serverden yanıtı al
yanit = s.recv(1024)
print(yanit.decode("utf-8"))
s.send(yanit) #yanki yolla
# bağlantıyı kapat
komut = komut + s.recv(1024).decode() + '"' #gerekli terminal komutun hazırlanması
print(komut)
zamandilimi = s.recv(1024)
print(zamandilimi.decode())
os.system(komut) #komutun çalıştırılması
s.close()
except socket.error as msg:
print("[Server aktif değil.] Mesaj:", msg)
| [
"[email protected]"
]
| |
c0e643ad4fa8ef59d8fc7c410dae20ba6ce83e43 | 6223dc2e5de7921696cb34fb62142fd4a4efe361 | /.metadata/.plugins/org.eclipse.core.resources/.history/73/60f8cf3a196b00141928c597445b4e35 | cc1d592056af8a6b636607c3a5fc66693511d529 | []
| no_license | Mushirahmed/python_workspace | 5ef477b2688e8c25b1372f546752501ee53d93e5 | 46e2ed783b17450aba29e4e2df7b656522b2b03b | refs/heads/master | 2021-03-12T19:24:50.598982 | 2015-05-25T10:23:54 | 2015-05-25T10:23:54 | 24,671,376 | 0 | 1 | null | 2015-02-06T09:27:40 | 2014-10-01T08:40:33 | Python | UTF-8 | Python | false | false | 5,406 | #!/usr/bin/env python
#
# Copyright 2014 <+YOU OR YOUR COMPANY+>.
#
# This is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
import numpy
#from operator import add
#import copy
#from gnuradio import gr
import gras
class expo(gras.Block):
"""
docstring for block expo
"""
def __init__(self):
gras.Block.__init__(self,
name="expo",
in_sig=[numpy.float32],
out_sig=[numpy.float32])
def set_parameters(self,g,a,b):
self.gama=g
self.alpha=a
self.beta=b
def yield_times(self):
from datetime import date, time, datetime, timedelta
start = datetime.combine(date.today(), time(0, 0))
yield start.strftime("%S")
while True:
start += timedelta(seconds=0.5)
yield start.strftime("%S")
def work(self, input_items, output_items):
#in0 = input_items[0]
#out = output_items[0]
tmrg = []
o1 = []
o2 = []
o3 = []
ans = []
final_output = []
gen = self.yield_times()
for ii in range(20):
tmrg.append(gen.next())
# print "tmrg :",tmrg
"""for i1 in range(0,10):
o1.append((self.gama)/(self.alpha*self.beta))
print "o1 : ", o1
for i2 in range(0,10):
o2.append(((self.gama)*(-numpy.exp(self.alpha)))/(self.alpha*(self.beta-self.alpha)))
print "o2 : ",o2
for i3 in range(0,10):
o3.append(((self.gama)*(-numpy.exp(self.beta)))/(self.beta*(self.alpha-self.beta)))
print "o3 : ",o3
#ans.append(o1+o2+o3)
for i in range(0,10):
ans.append(list(numpy.array(o1[i])+numpy.array(o2[i])+numpy.array(o3[i])))
print "Final Ans : ",ans
print "Type out : ",type(out)
print "Type ans :",type(ans)
out = copy.copy(ans)
#out[0:1] = ans
print "Output is : " ,out
self.consume(0,1)
self.produce(0,1)"""
#o1.append((self.gama)/(self.alpha*self.beta))
#print "o1 : ", o1
for i in range(0,20):
o1.append((self.gama)/(self.alpha*self.beta))
print "o1 : ", o1[i]
o2.append(((self.gama)*(numpy.exp(-(self.alpha*i)))/(self.alpha*(self.beta-self.alpha))))
print "o2 : ",o2[i]
o3.append(((self.gama)*(numpy.exp(-(self.beta*i)))/(self.beta*(self.alpha-self.beta))))
print "o3 : ",o3[i]
ans.append(o1[i]+o2[i]+o3[i])
print "Final Ans : ",ans
"""for i in range(0,len(ans)):
#out = copy.copy(ans[i])
#out[0:1] = ans
#print "Output is : " ,out"""
"""for i1 in range(0,len(ans)):
final_output.append(o1+ans[i1])
print "Final OutPut : ", final_output"""
#for i1 in range(0,len(ans)):
#out[0] = ans[i1]
#print "Output Sent : ", output_items[i1]
#out[:len(final_output)] = copy.copy(final_output)
for i in range(0,20):
a =
output_items [0] [:1] = a
self.consume(0,1)
self.produce(0,1)
"""result = []
for i in range(0,20):
result.append(numpy.exp(i))
print "Result : ",result
out[0] = result
self.consume(0,1)
self.produce(0,1) """
#o2 = -numpy.exp(-2*in0[0:1])
#o3 = -numpy.exp(-3*in0[0:1])
#o2=numpy.exp(-(in0[0:1]*self.alpha))
#print("o2 :",o2)
#o3=numpy.sin((self.freq*in0[0:1])+(self.sigma))
#print("o3 :",o3)
#o4=numpy.sqrt(o1-numpy.square(self.zita))
#print("o4 :",o4)
"""ans = o1-(mul/o4)
#ans.append(o1-((numpy.exp(-in0[0:1]*self.sigma)*(numpy.sin((self.freq*in0[0:1])+(self.sigma))))/numpy.sqrt(o1-numpy.square(self.zita))))
print("Final Value : ",ans)
out[0:1] = ans"""
#o2 = -numpy.exp(-2*tmrg)
#o3 = -numpy.exp(-3*in0[0:1])
#o2 = numpy.exp(-in0[0:1]*self.alpha)
#o3 = numpy.exp(-in0[0:1]*self.beta)
#o4 = numpy.sqrt(1-numpy.square(self.alpha))
#ans = 1-((o2*o3)/o4)
#ans.append(o2)
#ans.append(o1-((numpy.exp(-in0[0:1]*self.sigma)*(numpy.sin((self.freq*in0[0:1])+(self.sigma))))/numpy.sqrt(o1-numpy.square(self.zita))))
#print("Final Value : ",ans)
#out[0:1] = ans
#out = copy.copy(ans)
#self.consume(0,1)
#self.produce(0,1)
#return len(output_items[0])
| [
"[email protected]"
]
| ||
923a73b286091e48661d2498f48f73f6650f64ed | e35fd52fe4367320024a26f2ee357755b5d5f4bd | /leetcode/problems/74.search-a-2d-matrix.py | 1569ac34b90c9406f662f03ef22de36da49b9a0d | []
| no_license | liseyko/CtCI | a451967b0a0ce108c491d30b81e88d20ad84d2cd | c27f19fac14b4acef8c631ad5569e1a5c29e9e1f | refs/heads/master | 2020-03-21T14:28:47.621481 | 2019-11-12T22:59:07 | 2019-11-12T22:59:07 | 138,658,372 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 966 | py | #
# @lc app=leetcode id=74 lang=python3
#
# [74] Search a 2D Matrix
#
# https://leetcode.com/problems/search-a-2d-matrix/description/
#
# algorithms
# Medium (35.49%)
# Total Accepted: 262.2K
# Total Submissions: 738.7K
# Testcase Example: '[[1,3,5,7],[10,11,16,20],[23,30,34,50]]\n3'
#
# Write an efficient algorithm that searches for a value in an m x n matrix.
# This matrix has the following properties:
#
#
# Integers in each row are sorted from left to right.
# The first integer of each row is greater than the last integer of the
# previous row.
#
#
# Example 1:
#
#
# Input:
# matrix = [
# [1, 3, 5, 7],
# [10, 11, 16, 20],
# [23, 30, 34, 50]
# ]
# target = 3
# Output: true
#
#
# Example 2:
#
#
# Input:
# matrix = [
# [1, 3, 5, 7],
# [10, 11, 16, 20],
# [23, 30, 34, 50]
# ]
# target = 13
# Output: false
#
#
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
| [
"[email protected]"
]
| |
ca3cd643be45c6a9a5f944743ece02ac4fc85764 | 15f321878face2af9317363c5f6de1e5ddd9b749 | /solutions_python/Problem_53/567.py | 05e6ad00cbf4b7bba63051f353ec913a4811d281 | []
| no_license | dr-dos-ok/Code_Jam_Webscraper | c06fd59870842664cd79c41eb460a09553e1c80a | 26a35bf114a3aa30fc4c677ef069d95f41665cc0 | refs/heads/master | 2020-04-06T08:17:40.938460 | 2018-10-14T10:12:47 | 2018-10-14T10:12:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 403 | py | #!/usr/bin/python
import sys
def snapper(n,k):
return ( ( k & ( (1<<n) - 1) ) == ( (1<<n) - 1) )
num_entries = input()
entries = []
c = 0
while c < num_entries:
s = sys.stdin.readline()
entries.append(map(int, s.split(' ')))
c += 1
c = 0
while c < num_entries:
if snapper(entries[c][0], entries[c][1]):
print "Case #" + str(c+1) + ": ON"
else:
print "Case #" + str(c+1) + ": OFF"
c += 1
| [
"[email protected]"
]
| |
ddeea8ef6ffc46729b0a8139f950b546b159e1ae | 91fe4b06b331be287518731614067e5d65a85e82 | /GetNearestAgents/GetNearestAgents/urls.py | a01a6b849148b911ca3a3fc6124c09c422da1e18 | []
| no_license | Niharika3128/GetAgentsByNearestLocations | e8b1af4dc011efb4ff0e79383478333747ff2a22 | 9e954344e50a3f92d40fd3aa7810569c727f0c46 | refs/heads/master | 2022-12-16T04:57:45.667615 | 2020-09-11T18:32:59 | 2020-09-11T18:32:59 | 294,387,893 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,066 | py | """GetNearestAgents URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
# from django.contrib import admin
from django.urls import path
from agents import views
from django.views.generic import TemplateView
urlpatterns = [
# path('admin/', admin.site.urls),
path('',TemplateView.as_view(template_name='home.html'),name='main'),
path('locations/',views.getNearestLocations,name='locations'),
path('get_page/(?P<pno>\d+)/(?P<id>\d)/',views.getNearestLocations,name='get_page'),
]
| [
"[email protected]"
]
| |
3edaba52aa526852e5576903a2ca6d968a293149 | 18305efd1edeb68db69880e03411df37fc83b58b | /pdb_files_1000rot/qp/1qpe/tractability_500/pymol_results_file.py | ba2530e6b7d97a0245b21db20af8a6d3f359eb47 | []
| no_license | Cradoux/hotspot_pipline | 22e604974c8e38c9ffa979092267a77c6e1dc458 | 88f7fab8611ebf67334474c6e9ea8fc5e52d27da | refs/heads/master | 2021-11-03T16:21:12.837229 | 2019-03-28T08:31:39 | 2019-03-28T08:31:39 | 170,106,739 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,204 | py |
from os.path import join
import tempfile
import zipfile
from pymol import cmd, finish_launching
from pymol.cgo import *
finish_launching()
dirpath = None
def cgo_arrow(atom1='pk1', atom2='pk2', radius=0.07, gap=0.0, hlength=-1, hradius=-1, color='blue red', name=''):
from chempy import cpv
radius, gap = float(radius), float(gap)
hlength, hradius = float(hlength), float(hradius)
try:
color1, color2 = color.split()
except:
color1 = color2 = color
color1 = list(cmd.get_color_tuple(color1))
color2 = list(cmd.get_color_tuple(color2))
def get_coord(v):
if not isinstance(v, str):
return v
if v.startswith('['):
return cmd.safe_list_eval(v)
return cmd.get_atom_coords(v)
xyz1 = get_coord(atom1)
xyz2 = get_coord(atom2)
normal = cpv.normalize(cpv.sub(xyz1, xyz2))
if hlength < 0:
hlength = radius * 3.0
if hradius < 0:
hradius = hlength * 0.6
if gap:
diff = cpv.scale(normal, gap)
xyz1 = cpv.sub(xyz1, diff)
xyz2 = cpv.add(xyz2, diff)
xyz3 = cpv.add(cpv.scale(normal, hlength), xyz2)
obj = [cgo.CYLINDER] + xyz1 + xyz3 + [radius] + color1 + color2 + [cgo.CONE] + xyz3 + xyz2 + [hradius, 0.0] + color2 + color2 + [1.0, 0.0]
return obj
dirpath = tempfile.mkdtemp()
zip_dir = 'out.zip'
with zipfile.ZipFile(zip_dir) as hs_zip:
hs_zip.extractall(dirpath)
cmd.load(join(dirpath,"protein.pdb"), "protein")
cmd.show("cartoon", "protein")
if dirpath:
f = join(dirpath, "label_threshold_10.mol2")
else:
f = "label_threshold_10.mol2"
cmd.load(f, 'label_threshold_10')
cmd.hide('everything', 'label_threshold_10')
cmd.label("label_threshold_10", "name")
cmd.set("label_font_id", 7)
cmd.set("label_size", -0.4)
if dirpath:
f = join(dirpath, "label_threshold_14.mol2")
else:
f = "label_threshold_14.mol2"
cmd.load(f, 'label_threshold_14')
cmd.hide('everything', 'label_threshold_14')
cmd.label("label_threshold_14", "name")
cmd.set("label_font_id", 7)
cmd.set("label_size", -0.4)
if dirpath:
f = join(dirpath, "label_threshold_17.mol2")
else:
f = "label_threshold_17.mol2"
cmd.load(f, 'label_threshold_17')
cmd.hide('everything', 'label_threshold_17')
cmd.label("label_threshold_17", "name")
cmd.set("label_font_id", 7)
cmd.set("label_size", -0.4)
colour_dict = {'acceptor':'red', 'donor':'blue', 'apolar':'yellow', 'negative':'purple', 'positive':'cyan'}
threshold_list = [10, 14, 17]
gfiles = ['donor.grd', 'apolar.grd', 'acceptor.grd']
grids = ['donor', 'apolar', 'acceptor']
num = 0
surf_transparency = 0.2
if dirpath:
gfiles = [join(dirpath, g) for g in gfiles]
for t in threshold_list:
for i in range(len(grids)):
try:
cmd.load(r'%s'%(gfiles[i]), '%s_%s'%(grids[i], str(num)))
cmd.isosurface('surface_%s_%s_%s'%(grids[i], t, num), '%s_%s'%(grids[i], num), t)
cmd.set('transparency', surf_transparency, 'surface_%s_%s_%s'%(grids[i], t, num))
cmd.color(colour_dict['%s'%(grids[i])], 'surface_%s_%s_%s'%(grids[i], t, num))
cmd.group('threshold_%s'%(t), members = 'surface_%s_%s_%s'%(grids[i],t, num))
cmd.group('threshold_%s' % (t), members='label_threshold_%s' % (t))
except:
continue
try:
cmd.group('hotspot_%s' % (num), members='threshold_%s' % (t))
except:
continue
for g in grids:
cmd.group('hotspot_%s' % (num), members='%s_%s' % (g,num))
cluster_dict = {"16.1944999695":[], "16.1944999695_arrows":[]}
cluster_dict["16.1944999695"] += [COLOR, 0.00, 0.00, 1.00] + [ALPHA, 0.6] + [SPHERE, float(18.0), float(37.5), float(84.5), float(1.0)]
cluster_dict["16.1944999695_arrows"] += cgo_arrow([18.0,37.5,84.5], [16.732,39.933,86.734], color="blue red", name="Arrows_16.1944999695_1")
cluster_dict["16.1944999695"] += [COLOR, 0.00, 0.00, 1.00] + [ALPHA, 0.6] + [SPHERE, float(21.0), float(34.0), float(86.0), float(1.0)]
cluster_dict["16.1944999695_arrows"] += cgo_arrow([21.0,34.0,86.0], [20.128,33.403,83.414], color="blue red", name="Arrows_16.1944999695_2")
cluster_dict["16.1944999695"] += [COLOR, 0.00, 0.00, 1.00] + [ALPHA, 0.6] + [SPHERE, float(22.0), float(35.0), float(82.5), float(1.0)]
cluster_dict["16.1944999695_arrows"] += cgo_arrow([22.0,35.0,82.5], [20.128,33.403,83.414], color="blue red", name="Arrows_16.1944999695_3")
cluster_dict["16.1944999695"] += [COLOR, 0.00, 0.00, 1.00] + [ALPHA, 0.6] + [SPHERE, float(22.0), float(40.5), float(86.5), float(1.0)]
cluster_dict["16.1944999695_arrows"] += cgo_arrow([22.0,40.5,86.5], [20.326,41.875,84.711], color="blue red", name="Arrows_16.1944999695_4")
cluster_dict["16.1944999695"] += [COLOR, 1.00, 1.000, 0.000] + [ALPHA, 0.6] + [SPHERE, float(24.6252880167), float(37.7325779305), float(84.4628325968), float(1.0)]
cluster_dict["16.1944999695"] += [COLOR, 1.00, 0.00, 0.00] + [ALPHA, 0.6] + [SPHERE, float(19.0), float(38.5), float(82.5), float(1.0)]
cluster_dict["16.1944999695_arrows"] += cgo_arrow([19.0,38.5,82.5], [17.965,41.525,82.457], color="red blue", name="Arrows_16.1944999695_5")
cluster_dict["16.1944999695"] += [COLOR, 1.00, 0.00, 0.00] + [ALPHA, 0.6] + [SPHERE, float(20.0), float(36.0), float(83.0), float(1.0)]
cluster_dict["16.1944999695_arrows"] += cgo_arrow([20.0,36.0,83.0], [20.128,33.403,83.414], color="red blue", name="Arrows_16.1944999695_6")
cluster_dict["16.1944999695"] += [COLOR, 1.00, 0.00, 0.00] + [ALPHA, 0.6] + [SPHERE, float(19.5), float(38.5), float(86.5), float(1.0)]
cluster_dict["16.1944999695_arrows"] += cgo_arrow([19.5,38.5,86.5], [16.732,39.933,86.734], color="red blue", name="Arrows_16.1944999695_7")
cluster_dict["16.1944999695"] += [COLOR, 1.00, 0.00, 0.00] + [ALPHA, 0.6] + [SPHERE, float(22.0), float(39.5), float(83.5), float(1.0)]
cluster_dict["16.1944999695_arrows"] += cgo_arrow([22.0,39.5,83.5], [20.326,41.875,84.711], color="red blue", name="Arrows_16.1944999695_8")
cluster_dict["16.1944999695"] += [COLOR, 1.00, 0.00, 0.00] + [ALPHA, 0.6] + [SPHERE, float(24.5), float(34.5), float(82.5), float(1.0)]
cluster_dict["16.1944999695_arrows"] += cgo_arrow([24.5,34.5,82.5], [24.977,33.392,79.234], color="red blue", name="Arrows_16.1944999695_9")
cmd.load_cgo(cluster_dict["16.1944999695"], "Features_16.1944999695", 1)
cmd.load_cgo(cluster_dict["16.1944999695_arrows"], "Arrows_16.1944999695")
cmd.set("transparency", 0.2,"Features_16.1944999695")
cmd.group("Pharmacophore_16.1944999695", members="Features_16.1944999695")
cmd.group("Pharmacophore_16.1944999695", members="Arrows_16.1944999695")
if dirpath:
f = join(dirpath, "label_threshold_16.1944999695.mol2")
else:
f = "label_threshold_16.1944999695.mol2"
cmd.load(f, 'label_threshold_16.1944999695')
cmd.hide('everything', 'label_threshold_16.1944999695')
cmd.label("label_threshold_16.1944999695", "name")
cmd.set("label_font_id", 7)
cmd.set("label_size", -0.4)
cmd.group('Pharmacophore_16.1944999695', members= 'label_threshold_16.1944999695')
cmd.bg_color("white")
cmd.show("cartoon", "protein")
cmd.color("slate", "protein")
cmd.show("sticks", "organic")
cmd.hide("lines", "protein")
| [
"[email protected]"
]
| |
57563df581ac1c0a00ac5c91318c1352f0584a59 | 8336ea48994f9ecbddd9caf853d08f05b2e4c15c | /-二叉树-遍历.py | c2e78d315571c82f3bca1e8199f2110b88a3277b | []
| no_license | swain-s/lc | fb2058931853b83aeb0737447a67e2fee08fdacd | 9e793935b999540e20e6c7f025f3f765f43039af | refs/heads/master | 2021-01-09T00:33:23.943824 | 2020-04-06T11:50:38 | 2020-04-06T11:50:38 | 242,172,007 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,498 | py | # 问题描述:二叉树的前序、中序、后续和层次遍历
# 模板: 7
# 3 10
# 1 5 9 12
# 4 14
#
from a_bin_tree import root, tin_travel
class TreeNode(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class BinTreeTreveral(object):
def __init__(self):
pass
def pre_order_traveral(self, root, output):
if root == None:
return
output.append(root.val)
self.pre_order_traveral(root.left, output)
self.pre_order_traveral(root.right, output)
#先序遍历的迭代版本
def pre_order_traveral_stack(self, root):
output = []
if root == None:
return output
stack = []
cur = root
while cur or len(stack) > 0:
if cur:
stack.append(cur)
output.append(cur.val)
cur = cur.left
else:
cur = stack.pop()
cur = cur.right
return output
def in_order_traveral(self, root, output):
if root == None:
return
self.in_order_traveral(root.left, output)
output.append(root.val)
self.in_order_traveral(root.right, output)
#中序遍历的迭代版本
def in_order_traveral_stack(self, root):
output = []
if root == None:
return output
stack = []
cur = root
while cur or len(stack) > 0:
if cur:
stack.append(cur)
cur = cur.left
else:
cur = stack.pop()
output.append(cur.val)
cur = cur.right
return output
def post_order_traveral(self, root, output):
if root == None:
return
self.post_order_traveral(root.left, output)
self.post_order_traveral(root.right, output)
output.append(root.val)
def level_order_traveral(self, root):
pass
if __name__ == "__main__":
S = BinTreeTreveral()
pre_arr = []
S.pre_order_traveral(root, pre_arr)
print(pre_arr)
pre_arr_stack = []
print(S.pre_order_traveral_stack(root))
in_arr = []
S.in_order_traveral(root, in_arr)
print(in_arr)
in_arr_stack = []
print(S.in_order_traveral_stack(root))
post_arr = []
S.post_order_traveral(root, post_arr)
print(post_arr)
| [
"[email protected]"
]
| |
6b986ebc0f99796b46a53f789dadc82ecf2fcd69 | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/adjectives/_forgivable.py | 17e88f7334c72b963bdb051e7591385f4638ce97 | [
"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 | 436 | py |
#calss header
class _FORGIVABLE():
def __init__(self,):
self.name = "FORGIVABLE"
self.definitions = [u'used to say that you can forgive something because you understand it: ']
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.specie = 'adjectives'
def run(self, obj1, obj2):
self.jsondata[obj2] = {}
self.jsondata[obj2]['properties'] = self.name.lower()
return self.jsondata
| [
"[email protected]"
]
| |
7e9ff9af780f43f5e27b10dfb86f30c622c4311f | 21f8a6f018748aa714bd63d68944d6474f011781 | /coverage_wss/vrep_ros_interface/devel/lib/python2.7/dist-packages/vrep_common/srv/_simRosAuxiliaryConsolePrint.py | 297e3406a278e743d7f5125779740b2adfb6d5a4 | []
| no_license | ElliWhite/group_1_coverage | e04dd3d5374cad76b3914bf0dfca719dc934989e | 565c325e4dc4188716f5233b6de05671a3d89b1c | refs/heads/master | 2020-05-27T17:27:37.807828 | 2019-05-29T21:48:43 | 2019-05-29T21:48:43 | 188,720,706 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 8,519 | py | # This Python file uses the following encoding: utf-8
"""autogenerated by genpy from vrep_common/simRosAuxiliaryConsolePrintRequest.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class simRosAuxiliaryConsolePrintRequest(genpy.Message):
_md5sum = "01b8405a29eed17e1ac8fe2b1db7c0a0"
_type = "vrep_common/simRosAuxiliaryConsolePrintRequest"
_has_header = False #flag to mark the presence of a Header object
_full_text = """
int32 consoleHandle
string text
"""
__slots__ = ['consoleHandle','text']
_slot_types = ['int32','string']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
consoleHandle,text
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(simRosAuxiliaryConsolePrintRequest, self).__init__(*args, **kwds)
#message fields cannot be None, assign default values for those that are
if self.consoleHandle is None:
self.consoleHandle = 0
if self.text is None:
self.text = ''
else:
self.consoleHandle = 0
self.text = ''
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
buff.write(_get_struct_i().pack(self.consoleHandle))
_x = self.text
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.pack('<I%ss'%length, length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
try:
end = 0
start = end
end += 4
(self.consoleHandle,) = _get_struct_i().unpack(str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.text = str[start:end].decode('utf-8')
else:
self.text = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
buff.write(_get_struct_i().pack(self.consoleHandle))
_x = self.text
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.pack('<I%ss'%length, length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
try:
end = 0
start = end
end += 4
(self.consoleHandle,) = _get_struct_i().unpack(str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.text = str[start:end].decode('utf-8')
else:
self.text = str[start:end]
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
_struct_I = genpy.struct_I
def _get_struct_I():
global _struct_I
return _struct_I
_struct_i = None
def _get_struct_i():
global _struct_i
if _struct_i is None:
_struct_i = struct.Struct("<i")
return _struct_i
# This Python file uses the following encoding: utf-8
"""autogenerated by genpy from vrep_common/simRosAuxiliaryConsolePrintResponse.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class simRosAuxiliaryConsolePrintResponse(genpy.Message):
_md5sum = "034a8e20d6a306665e3a5b340fab3f09"
_type = "vrep_common/simRosAuxiliaryConsolePrintResponse"
_has_header = False #flag to mark the presence of a Header object
_full_text = """int32 result
"""
__slots__ = ['result']
_slot_types = ['int32']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
result
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(simRosAuxiliaryConsolePrintResponse, self).__init__(*args, **kwds)
#message fields cannot be None, assign default values for those that are
if self.result is None:
self.result = 0
else:
self.result = 0
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
buff.write(_get_struct_i().pack(self.result))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
try:
end = 0
start = end
end += 4
(self.result,) = _get_struct_i().unpack(str[start:end])
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
buff.write(_get_struct_i().pack(self.result))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
try:
end = 0
start = end
end += 4
(self.result,) = _get_struct_i().unpack(str[start:end])
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
_struct_I = genpy.struct_I
def _get_struct_I():
global _struct_I
return _struct_I
_struct_i = None
def _get_struct_i():
global _struct_i
if _struct_i is None:
_struct_i = struct.Struct("<i")
return _struct_i
class simRosAuxiliaryConsolePrint(object):
_type = 'vrep_common/simRosAuxiliaryConsolePrint'
_md5sum = '9d84d1075d5165c5c1bafd9cf0faa6fd'
_request_class = simRosAuxiliaryConsolePrintRequest
_response_class = simRosAuxiliaryConsolePrintResponse
| [
"[email protected]"
]
| |
b8709d1ed22fe57824a0b3ea1da243b08abaeccc | e281ce2330656a6a0a7f795f535f78881df8b5ba | /Python Study/Backup All the file/Common/ZipFile.py | c11a684f7044dbb2a6408fa18934115512d93791 | []
| no_license | sunruihua0522/SIG-PyCode | 70db0b57bbf9ce35dc42bd8de62c5bb56a2e888e | 483a67bf679f54ab7405c2362d9cfe47daa2bc0f | refs/heads/master | 2020-07-12T14:46:32.588227 | 2020-04-02T04:37:02 | 2020-04-02T04:37:02 | 204,842,675 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,983 | py | import zipfile
import os
from tqdm import tqdm
class ZipFile:
@staticmethod
def zipDir(dirpath,outFullName):
"""
压缩指定文件夹
:param dirpath: 目标文件夹路径
:param outFullName: 压缩文件保存路径+xxxx.zip
:return: 无
"""
zip = zipfile.ZipFile(outFullName,"w",zipfile.ZIP_DEFLATED)
for path,dirnames,filenames in os.walk(dirpath):
# 去掉目标跟路径,只对目标文件夹下边的文件及文件夹进行压缩
fpath = path.replace(dirpath,'')
for filename in tqdm(filenames,ncols = 50):
zip.write(os.path.join(path,filename),os.path.join(fpath,filename))
#print('%s\r\n%s\r\n\r\n\r\n'%(os.path.join(path,filename),os.path.join(fpath,filename)))
zip.close()
@staticmethod
def ZipFile(fileModelInfoLIst):
'''
:param fileModelInfoLIst: -> fileModelInfo of Array
:return: None
'''
for l in fileModelInfoLIst:
if (l.IsFile()):
pass
else:
strPre = l.Root.split('\\')[-1]
if (not os.path.exists(l.PathDes)):
os.makedirs(l.PathDes)
zip = zipfile.ZipFile(os.path.join(l.PathDes, '%s.zip' % strPre), "w", zipfile.ZIP_DEFLATED)
for path, dirpath, filenames in os.walk(l.FullName):
fpath = path.replace(l.FullName, '')
for filename in tqdm(filenames,ncols = 50):
condication1 = len(list(filter(lambda x: x.FullName == path, l.ListIn))) > 0
condication2 = len(
list(filter(lambda y: os.path.join(path, filename) == y.FullName, l.ListIn))) > 0
if (condication1 or condication2):
zip.write(os.path.join(path, filename), os.path.join(fpath, filename))
zip.close()
| [
"--global"
]
| --global |
b0122bfe88e38f332099985954a6a5d8bd7fda29 | 427ab1f7f7fe08f76fab6468f6ea24dc5bc2701d | /bugscan/exp-2424.py | c8dd3e9935415447b4bce32457f6ae74829b5ecb | []
| no_license | gayhub-blackerie/poc | b852b2bcdba78185efd68817c31579247c6e4b83 | 8b7c95d765deb450c029a921031eb1c90418f2a7 | refs/heads/master | 2021-07-24T03:05:52.697820 | 2017-11-04T10:33:51 | 2017-11-04T10:33:51 | 107,093,079 | 1 | 0 | null | 2017-10-16T07:31:31 | 2017-10-16T07:31:31 | null | UTF-8 | Python | false | false | 761 | py | #!/usr/bin/evn python
#--coding:utf-8--*--
#Name: shopnum1注入3
#Refer:http://www.wooyun.org/bugs/wooyun-2015-0118352
#Author:xq17
def assign(service,arg):
if service=="shopnum1":
return True,arg
def audit(arg):
payload = "ProductListCategory.html?BrandGuid=ac69ddd9-3900-43b0-939b-3b1d438ca190%27%20and%20(CHAR(126)%2BCHAR(116)%2BCHAR(101)%2BCHAR(115)%2BCHAR(116)%2BCHAR(88)%2BCHAR(81)%2BCHAR(49)%2BCHAR(55))%3E0--"
url=arg+payload
code, head, res, errcode,finalurl = curl.curl(url)
if code == 200 and "testXQ17" in res:
security_hole('find sql injection: ' + arg)
if __name__ == '__main__':
from dummy import *
audit(assign("shopnum1","http://www.dapeng.net/")[1]) | [
"[email protected]"
]
| |
778ffa1ac232b1d139916fb722187dabf44fc75f | 5f0a72ccc780a9649c6adb15ccab6ddcb02a146b | /marshmallow/core/mechanics/music.py | 644a8e26dbbecfa004973ebc4fe8d6f3d4eccc2c | []
| no_license | bretzle/Marshmallow-Bot | 1eb020bdf910bd29b324a79a0ee1b094d13f72fc | 72175c0f58e36c7b6325a6cb2224731434781aca | refs/heads/master | 2021-09-01T16:56:23.727278 | 2017-12-28T01:11:15 | 2017-12-28T01:11:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,414 | py | import asyncio
import functools
import hashlib
import os
from asyncio.queues import Queue
from concurrent.futures import ThreadPoolExecutor
import discord
import youtube_dl
ytdl_params = {
'format': 'bestaudio/best',
'extractaudio': True,
'audioformat': 'mp3',
'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'noplaylist': False,
'nocheckcertificate': True,
'ignoreerrors': True,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0'
}
class QueueItem(object):
def __init__(self, requester, item_info):
self.requester = requester
self.item_info = item_info
self.url = self.item_info['webpage_url']
self.video_id = self.item_info['id']
if 'uploader' in self.item_info:
self.uploader = self.item_info['uploader']
else:
self.uploader = 'Unknown'
self.title = self.item_info['title']
if 'thumbnail' in self.item_info:
self.thumbnail = self.item_info['thumbnail']
else:
self.thumbnail = 'https://i.imgur.com/CGPNJDT.png'
self.duration = int(self.item_info['duration'])
self.downloaded = False
self.loop = asyncio.get_event_loop()
self.threads = ThreadPoolExecutor(2)
self.ytdl_params = ytdl_params
self.ytdl = youtube_dl.YoutubeDL(self.ytdl_params)
self.token = self.tokenize()
self.location = None
def tokenize(self):
name = 'yt_' + self.video_id
crypt = hashlib.new('md5')
crypt.update(name.encode('utf-8'))
final = crypt.hexdigest()
return final
async def download(self):
out_location = f'cache/{self.token}'
if not os.path.exists(out_location):
self.ytdl.params['outtmpl'] = out_location
task = functools.partial(self.ytdl.extract_info, self.url)
await self.loop.run_in_executor(self.threads, task)
self.downloaded = True
self.location = out_location
async def create_player(self, voice_client):
await self.download()
audio_source = discord.FFmpegPCMAudio(self.location)
if not voice_client.is_playing():
voice_client.play(audio_source)
class MusicCore(object):
def __init__(self, bot):
self.bot = bot
self.db = bot.db
self.loop = asyncio.get_event_loop()
self.threads = ThreadPoolExecutor(2)
self.queues = {}
self.currents = {}
self.repeaters = []
self.ytdl_params = ytdl_params
self.ytdl = youtube_dl.YoutubeDL(self.ytdl_params)
async def extract_info(self, url):
task = functools.partial(self.ytdl.extract_info, url, False)
information = await self.loop.run_in_executor(self.threads, task)
return information
def get_queue(self, guild_id):
if guild_id in self.queues:
queue = self.queues[guild_id]
else:
queue = Queue()
self.queues.update({guild_id: queue})
return queue
@staticmethod
async def listify_queue(queue):
item_list = []
while not queue.empty():
item = await queue.get()
item_list.append(item)
for item in item_list:
await queue.put(item)
return item_list | [
"[email protected]"
]
| |
1f69cce9ab69c9327883e50c082b673410e47b63 | 57dfd89d63b3b52eed144653c8264d50fa9fba6e | /miembros/api.py | faf4e4a8eaed9ebaf9a89ff12fa7d84346885925 | []
| no_license | geovanniberdugo/siiom | c850620214a1a3b8b1fc83ab895c0601241da3b4 | 5e2b72aff7ac5e94a93b7575603114b4ea5f628a | refs/heads/main | 2023-02-16T15:02:30.539674 | 2021-01-15T22:29:36 | 2021-01-15T22:29:36 | 330,036,242 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,077 | py | from django.contrib.auth.decorators import permission_required
from django.utils.translation import ugettext as _
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.http import JsonResponse
from .forms import DesvincularLiderGrupoForm, ResetearContrasenaAdminForm
from .models import Miembro
from .decorators import user_is_cabeza_red
from common.decorators import login_required_api
from common import constants
from common.api import get_error_forms_to_json
@login_required_api
@user_is_cabeza_red # No hay soporte con JSON
def desvincular_lider_grupo_api(request, pk):
"""
Desvincula a un lider de un grupo de amistad
"""
miembro = get_object_or_404(Miembro.objects.filter(grupo__isnull=False), pk=pk)
if request.method == 'POST':
form = DesvincularLiderGrupoForm(data=request.POST)
if form.is_valid():
form.desvincular_lider()
return JsonResponse({'url': reverse('miembros:editar_perfil', args=(miembro.id, ))})
else:
errors = get_error_forms_to_json(form)
return JsonResponse(errors, safe=False)
return JsonResponse({constants.RESPONSE_CODE: constants.RESPONSE_DENIED})
@login_required_api
@permission_required('miembros.es_administrador', raise_exception=True)
def resetear_contrasena(request):
"""Permite a un administrador resetear la contraseña de un miembro."""
msg = 'La contraseña se reseteó correctamente y se envió un email al miembro con su nueva contraseña.'
msg2 = 'La nueva contraseña es la cedula del miembro.'
if request.method == 'POST':
form = ResetearContrasenaAdminForm(request.POST)
if form.is_valid():
form.resetear()
return JsonResponse({
'message': _(msg + msg2),
constants.RESPONSE_CODE: constants.RESPONSE_SUCCESS
})
errors = get_error_forms_to_json(form)
return JsonResponse(errors, safe=False)
return JsonResponse({constants.RESPONSE_CODE: constants.RESPONSE_DENIED})
| [
"[email protected]"
]
| |
c06968f887196e0d4bba47819a0615fd85804f54 | d8ea695288010f7496c8661bfc3a7675477dcba0 | /django/ewm/home/__init__.py | 1ce0de44a99c764e6ca82d5b03db2231ae692086 | []
| no_license | dabolau/demo | de9c593dabca26144ef8098c437369492797edd6 | 212f4c2ec6b49baef0ef5fcdee6f178fa21c5713 | refs/heads/master | 2021-01-17T16:09:48.381642 | 2018-10-08T10:12:45 | 2018-10-08T10:12:45 | 90,009,236 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 119 | py | ###
# 定义后台组名称
# 需要配合apps.py文件中的配置
###
default_app_config = 'home.apps.HomeConfig' | [
"[email protected]"
]
| |
afc2a53cd1ff9057a75418b6ed601b4422063eb9 | 51f887286aa3bd2c3dbe4c616ad306ce08976441 | /pybind/slxos/v17r_2_00/cfm_config/protocol/cfm/y1731/test_profile/test_profile_params/start/__init__.py | 464a82b2e745fb276b70ea5398de815d30573b55 | [
"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 | 14,413 | 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__
class start(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module brocade-dot1ag - based on the path /cfm-config/protocol/cfm/y1731/test-profile/test-profile-params/start. Each member element of
the container is represented as a class variable - with a specific
YANG type.
"""
__slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__start_type','__start_time','__start_periodic',)
_yang_name = 'start'
_rest_name = 'start'
_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.__start_type = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'after': {'value': 2}, u'at': {'value': 1}},), is_leaf=True, yang_name="start-type", rest_name="start-type", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Specify start type as at/after sometime', u'cli-drop-node-name': None, u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-dot1ag', defining_module='brocade-dot1ag', yang_type='schedule-type', is_config=True)
self.__start_time = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'([0-1][0-9]|[2][0-3]){1}(:[0-5][0-9]){2}'}), is_leaf=True, yang_name="start-time", rest_name="start-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Specify start time in hh:mm:ss', u'cli-drop-node-name': None}}, namespace='urn:brocade.com:mgmt:brocade-dot1ag', defining_module='brocade-dot1ag', yang_type='time-in-hhmmss', is_config=True)
self.__start_periodic = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'daily': {'value': 1}},), is_leaf=True, yang_name="start-periodic", rest_name="start-periodic", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Specify start type as periodic', u'cli-optional-in-sequence': None, u'cli-break-sequence-commands': None, u'cli-drop-node-name': None}}, namespace='urn:brocade.com:mgmt:brocade-dot1ag', defining_module='brocade-dot1ag', yang_type='y1731-start-periodic', 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'cfm-config', u'protocol', u'cfm', u'y1731', u'test-profile', u'test-profile-params', u'start']
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'protocol', u'cfm', u'y1731', u'test-profile', u'start']
def _get_start_type(self):
"""
Getter method for start_type, mapped from YANG variable /cfm_config/protocol/cfm/y1731/test_profile/test_profile_params/start/start_type (schedule-type)
"""
return self.__start_type
def _set_start_type(self, v, load=False):
"""
Setter method for start_type, mapped from YANG variable /cfm_config/protocol/cfm/y1731/test_profile/test_profile_params/start/start_type (schedule-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_start_type is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_start_type() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'after': {'value': 2}, u'at': {'value': 1}},), is_leaf=True, yang_name="start-type", rest_name="start-type", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Specify start type as at/after sometime', u'cli-drop-node-name': None, u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-dot1ag', defining_module='brocade-dot1ag', yang_type='schedule-type', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """start_type must be of a type compatible with schedule-type""",
'defined-type': "brocade-dot1ag:schedule-type",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'after': {'value': 2}, u'at': {'value': 1}},), is_leaf=True, yang_name="start-type", rest_name="start-type", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Specify start type as at/after sometime', u'cli-drop-node-name': None, u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-dot1ag', defining_module='brocade-dot1ag', yang_type='schedule-type', is_config=True)""",
})
self.__start_type = t
if hasattr(self, '_set'):
self._set()
def _unset_start_type(self):
self.__start_type = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'after': {'value': 2}, u'at': {'value': 1}},), is_leaf=True, yang_name="start-type", rest_name="start-type", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Specify start type as at/after sometime', u'cli-drop-node-name': None, u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-dot1ag', defining_module='brocade-dot1ag', yang_type='schedule-type', is_config=True)
def _get_start_time(self):
"""
Getter method for start_time, mapped from YANG variable /cfm_config/protocol/cfm/y1731/test_profile/test_profile_params/start/start_time (time-in-hhmmss)
"""
return self.__start_time
def _set_start_time(self, v, load=False):
"""
Setter method for start_time, mapped from YANG variable /cfm_config/protocol/cfm/y1731/test_profile/test_profile_params/start/start_time (time-in-hhmmss)
If this variable is read-only (config: false) in the
source YANG file, then _set_start_time is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_start_time() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'([0-1][0-9]|[2][0-3]){1}(:[0-5][0-9]){2}'}), is_leaf=True, yang_name="start-time", rest_name="start-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Specify start time in hh:mm:ss', u'cli-drop-node-name': None}}, namespace='urn:brocade.com:mgmt:brocade-dot1ag', defining_module='brocade-dot1ag', yang_type='time-in-hhmmss', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """start_time must be of a type compatible with time-in-hhmmss""",
'defined-type': "brocade-dot1ag:time-in-hhmmss",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'([0-1][0-9]|[2][0-3]){1}(:[0-5][0-9]){2}'}), is_leaf=True, yang_name="start-time", rest_name="start-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Specify start time in hh:mm:ss', u'cli-drop-node-name': None}}, namespace='urn:brocade.com:mgmt:brocade-dot1ag', defining_module='brocade-dot1ag', yang_type='time-in-hhmmss', is_config=True)""",
})
self.__start_time = t
if hasattr(self, '_set'):
self._set()
def _unset_start_time(self):
self.__start_time = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'([0-1][0-9]|[2][0-3]){1}(:[0-5][0-9]){2}'}), is_leaf=True, yang_name="start-time", rest_name="start-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Specify start time in hh:mm:ss', u'cli-drop-node-name': None}}, namespace='urn:brocade.com:mgmt:brocade-dot1ag', defining_module='brocade-dot1ag', yang_type='time-in-hhmmss', is_config=True)
def _get_start_periodic(self):
"""
Getter method for start_periodic, mapped from YANG variable /cfm_config/protocol/cfm/y1731/test_profile/test_profile_params/start/start_periodic (y1731-start-periodic)
"""
return self.__start_periodic
def _set_start_periodic(self, v, load=False):
"""
Setter method for start_periodic, mapped from YANG variable /cfm_config/protocol/cfm/y1731/test_profile/test_profile_params/start/start_periodic (y1731-start-periodic)
If this variable is read-only (config: false) in the
source YANG file, then _set_start_periodic is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_start_periodic() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'daily': {'value': 1}},), is_leaf=True, yang_name="start-periodic", rest_name="start-periodic", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Specify start type as periodic', u'cli-optional-in-sequence': None, u'cli-break-sequence-commands': None, u'cli-drop-node-name': None}}, namespace='urn:brocade.com:mgmt:brocade-dot1ag', defining_module='brocade-dot1ag', yang_type='y1731-start-periodic', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """start_periodic must be of a type compatible with y1731-start-periodic""",
'defined-type': "brocade-dot1ag:y1731-start-periodic",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'daily': {'value': 1}},), is_leaf=True, yang_name="start-periodic", rest_name="start-periodic", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Specify start type as periodic', u'cli-optional-in-sequence': None, u'cli-break-sequence-commands': None, u'cli-drop-node-name': None}}, namespace='urn:brocade.com:mgmt:brocade-dot1ag', defining_module='brocade-dot1ag', yang_type='y1731-start-periodic', is_config=True)""",
})
self.__start_periodic = t
if hasattr(self, '_set'):
self._set()
def _unset_start_periodic(self):
self.__start_periodic = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'daily': {'value': 1}},), is_leaf=True, yang_name="start-periodic", rest_name="start-periodic", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Specify start type as periodic', u'cli-optional-in-sequence': None, u'cli-break-sequence-commands': None, u'cli-drop-node-name': None}}, namespace='urn:brocade.com:mgmt:brocade-dot1ag', defining_module='brocade-dot1ag', yang_type='y1731-start-periodic', is_config=True)
start_type = __builtin__.property(_get_start_type, _set_start_type)
start_time = __builtin__.property(_get_start_time, _set_start_time)
start_periodic = __builtin__.property(_get_start_periodic, _set_start_periodic)
_pyangbind_elements = {'start_type': start_type, 'start_time': start_time, 'start_periodic': start_periodic, }
| [
"[email protected]"
]
| |
094caf4e026a82c8bfd7136623542fccc36fe22e | 07da31b260bf2949ffd9463ad4f777ca93b75d43 | /sleekforum/src/sleekapps/threads/models/__init__.py | 5d512f2d8e6692557d4f27c0ab34238865c7ea3e | []
| no_license | adepeter/sleek-docker | 134fd7de12ade8c521ceb8e1b2b2611fa2224dde | dcf010c3da53093600101d970c6888c82360209f | refs/heads/master | 2022-12-15T14:53:01.499098 | 2020-09-14T00:42:31 | 2020-09-14T00:42:31 | 282,499,689 | 0 | 0 | null | 2020-07-31T14:31:22 | 2020-07-25T18:12:19 | JavaScript | UTF-8 | Python | false | false | 61 | py | from .post.post import Post
from .thread.thread import Thread | [
"[email protected]"
]
| |
19f6e1bec12fed1808c6705f4480960abebeb23a | 7cc6e942d23b24795eed11fb01eff2b2c770fe43 | /list_exercises/exercise7.py | 606bb18c73a44f02cf93fcf3fce0dcd9b3855981 | []
| no_license | ziqingW/python-exercises-flex-Mar03 | f6c166401400197d531fad3bd5d070255e4fe3b5 | 0034cc760e6a696ca537ff28b2d6d8290573d31b | refs/heads/master | 2021-01-25T14:34:10.138564 | 2018-03-06T20:00:39 | 2018-03-06T20:00:39 | 123,713,796 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 110 | py | numbers = [23,12,34,5,89,2,10,4]
multiple = 7
multilist = [num * multiple for num in numbers]
print(multilist) | [
"[email protected]"
]
| |
c14afc507b95a9c36595c24c46ae812c7fcc71c9 | 92993cff825da80a8ff601572a0c52b0b7d3cbde | /algorithms/Svm/APG/L1/APG_L1_m41.py | b1c19880dfe598d8378581b2300d5a68093c2d18 | []
| no_license | yingzhuoy/MRs-of-linear-models | 06e8b1f84b08c6aa77553813824cf35c1806c5a7 | c3df8299e039a12613f2022b370b8c3e9c2dd822 | refs/heads/master | 2023-04-07T23:09:37.736952 | 2021-04-04T05:33:37 | 2021-04-04T05:33:37 | 265,124,549 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,864 | py | import numpy as np
from numpy import linalg
from algorithms.clf import Clf
# L1-svm
import cvxopt
from cvxopt import matrix,solvers
## accelerate proximal gradient method
def backtracking(l0, x0, p, q, low, up):
# update x
beta = 0.5
l = l0
L0 = 0.5*x0.T*(p*x0) + q.T*x0
g0 = p*x0 + q
for k in range(128):
xp = x0 - l * g0
xp[xp < low] = low
xp[xp > up] = up
Lx = 0.5*xp.T*(p*xp) + q.T*xp
gt = (x0-xp) / l
#if Lx > L0 - l *(g0.T*gt) + 0.5*l*gt.T*(gt):
#----bug----
if Lx > L0 - l /(g0.T*gt) + 0.5*l*gt.T*(gt):
l = beta * l
else:
break
return xp, l
def projected_apg(p, q, bounds, step_size=0.1, max_iter=5000):
m = p.shape[0]
low, up = bounds
x = np.ones((m, 1), np.float64) * 0.5
y = x
p = p + np.diag(np.ones(m, np.float64)) * np.mean(p)
v, w = np.linalg.eigh(p)
# print(v)
# v[v < 0] = 1e-10
# p = w * np.diag(v) * w.T
l = 1/v[-1] - 1e-10
for k in range(max_iter): # heavy on matrix operations
# p = p + np.eye(p.shape[0]) * (.1/(k+1))
# saving previous x
y = x
# compute loss and its gradient
# gradient = p*x + q
# proximal mapping
# x = x - l * gradient
# x[x < low] = low
# x[x > up] = up
x, l = backtracking(l, y, p, q, low, up)
# if(np.linalg.norm(x1-x)):
# print('error', np.linalg.norm(x1-x))
# stop criteria
rnormw = np.linalg.norm(y-x) / (1+np.linalg.norm(x))
if k > 1 and rnormw < 1e-6:
#print('convergence!')
break
return x
class APG_L1_m41():
def fit(self, X, y):
m, n = X.shape
X = np.column_stack((X, np.ones((m, 1))))
y = y.astype(np.float64)
data_num = len(y)
C = 1.0
kernel = np.dot(X, np.transpose(X))
# np.outer()表示的是两个向量相乘,拿第一个向量的元素分别与第二个向量所有元素相乘得到结果的一行。
# p = np.matrix(kernel * np.outer(y, y)) * .5
# kernel = np.dot(X, np.transpose(X)) + np.eye(data_num) * (.5 / C)
p = np.matrix(np.multiply(kernel, np.outer(y, y)), np.float64)
q = np.matrix(-np.ones([data_num, 1], np.float64))
p = p + np.eye(data_num) * 0.1
bounds = (0, C)
alpha_svs = projected_apg(p, q, bounds)
# alpha_svs = alpha_svs1
y1 = np.reshape(y, (-1, 1))
alpha1 = alpha_svs
lambda1 = np.multiply(y1,alpha1)
w = np.dot(X.T, lambda1)
w = np.array(w).reshape(-1)
# b = np.mean(y1-np.reshape(np.dot(w, np.transpose(X)), [-1, 1]))
b = w[n]
w = w[0:n]
clf = Clf(w, b)
return clf
| [
"[email protected]"
]
| |
dd0fa4ba786eb9d8f8734622a18724a5acb42751 | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/verbs/_occasioned.py | f6245b1a5cf35679f3af0adee45fb97bbfcfd1d5 | [
"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 | 254 | py |
from xai.brain.wordbase.verbs._occasion import _OCCASION
#calss header
class _OCCASIONED(_OCCASION, ):
def __init__(self,):
_OCCASION.__init__(self)
self.name = "OCCASIONED"
self.specie = 'verbs'
self.basic = "occasion"
self.jsondata = {}
| [
"[email protected]"
]
| |
f1e5a981d26f50623a516c785ceb31ecc02bb287 | 2ed82c46dc08930bcf1a42bae6b50d0efd6e8899 | /rho_T_plot/rhoTPlot_physical_EAGLE.py | 1cb7f4fbbecf9894e961a7fa20fcaa11d676d703 | [
"MIT"
]
| permissive | SWIFTSIM/swiftsimio-examples | 3a96fb910c42fe90cd48a0974ea3b16678214204 | f038df3aa12a129185857b5cee2d4a7c2c6b4d03 | refs/heads/master | 2020-04-30T23:01:02.966239 | 2020-02-14T12:18:09 | 2020-02-14T12:18:09 | 177,133,622 | 0 | 1 | MIT | 2020-02-14T12:18:11 | 2019-03-22T12:10:18 | Python | UTF-8 | Python | false | false | 4,289 | py | """
Makes a rho-T plot. Uses the swiftsimio library.
"""
import matplotlib.pyplot as plt
import numpy as np
import h5py
from unyt import mh, cm, Gyr
from tqdm import tqdm
from matplotlib.colors import LogNorm
from matplotlib.animation import FuncAnimation
# Constants; these could be put in the parameter file but are rarely changed.
density_bounds = [1e-8, 1e5] # in nh/cm^3
temperature_bounds = [10 ** (3), 10 ** (8)] # in K
bins = 128
VMIN, VMAX = [1e0, 7.5e5]
# Plotting controls
cmap = "viridis"
def load_data(filename: str, n_files: int, to_read: str):
"""
Loads the data from snapshots made of multiple files.
"""
output = []
for file in tqdm(range(n_files), desc=f"Reading {to_read}"):
current_filename = f"{filename}.{file}.hdf5"
with h5py.File(current_filename, "r") as handle:
output.append(handle[to_read][...])
return np.concatenate(output)
def get_data(filename, n_files):
"""
Grabs the data (T in Kelvin and density in mh / cm^3).
"""
density = load_data(filename, n_files, "PartType0/Density")
# Already in K
temperature = load_data(filename, n_files, "PartType0/Temperature")
with h5py.File(f"{filename}.0.hdf5", "r") as handle:
print(handle["Header"].attrs["NumPart_Total"])
scale_factor = handle["Header"].attrs["Time"]
h = handle["Header"].attrs["HubbleParam"]
unit_density = handle["Units"].attrs["UnitDensity_in_cgs"]
mh = 1.673_723_6e-24
unit_density /= mh
print(len(density))
density *= unit_density
density *= h ** 2
density /= scale_factor ** 3
return density, temperature
def make_hist(filename, n_files, density_bounds, temperature_bounds, bins):
"""
Makes the histogram for filename with bounds as lower, higher
for the bins and "bins" the number of bins along each dimension.
Also returns the edges for pcolormesh to use.
"""
density_bins = np.logspace(
np.log10(density_bounds[0]), np.log10(density_bounds[1]), bins
)
temperature_bins = np.logspace(
np.log10(temperature_bounds[0]), np.log10(temperature_bounds[1]), bins
)
H, density_edges, temperature_edges = np.histogram2d(
*get_data(filename, n_files), bins=[density_bins, temperature_bins]
)
return H.T, density_edges, temperature_edges
def setup_axes():
"""
Creates the figure and axis object.
"""
fig, ax = plt.subplots(1, figsize=(6, 5), dpi=300)
ax.set_xlabel("Density [$n_H$ cm$^{-3}$]")
ax.set_ylabel("Temperature [K]")
ax.loglog()
return fig, ax
def make_single_image(filename, n_files, density_bounds, temperature_bounds, bins):
"""
Makes a single image and saves it to rhoTPlot_{filename}.png.
Filename should be given _without_ hdf5 extension.
"""
fig, ax = setup_axes()
hist, d, T = make_hist(filename, n_files, density_bounds, temperature_bounds, bins)
mappable = ax.pcolormesh(d, T, hist, cmap=cmap, norm=LogNorm(vmin=VMIN, vmax=VMAX))
fig.colorbar(mappable, label="Number of particles", pad=0)
fig.tight_layout()
fig.savefig("rhoTPlot_EAGLE.png")
return
if __name__ == "__main__":
import argparse as ap
parser = ap.ArgumentParser(
description="""
Plotting script for making a rho-T plot.
Takes the filename handle, start, and (optionally) stop
snapshots. If stop is not given, png plot is produced for
that snapshot. If given, a movie is made.
"""
)
parser.add_argument(
"-s",
"--stub",
help="""Stub for the filename (e.g. santabarbara). This is
the first part of the filename for the snapshots,
not including the final underscore. Required.""",
type=str,
required=True,
)
parser.add_argument(
"-n",
"--nfiles",
help="""Number of EAGLE files to read""",
type=int,
required=True,
)
# Run in single image mode.
args = vars(parser.parse_args())
make_single_image(
args["stub"],
n_files=args["nfiles"],
density_bounds=density_bounds,
temperature_bounds=temperature_bounds,
bins=bins,
)
| [
"[email protected]"
]
| |
98c7fc6457ff198ee87f3568232bf6841406a99e | eacfc1c0b2acd991ec2cc7021664d8e79c9e58f6 | /ccpnmr2.4/python/ccpnmr/format/converters/PalesFormat.py | cd5aa27d66e02596823c00d666e4173bae16967a | []
| no_license | edbrooksbank/ccpnmr2.4 | cfecb0896dcf8978d796e6327f7e05a3f233a921 | f279ca9bb2d972b1ce075dad5fcc16e6f4a9496c | refs/heads/master | 2021-06-30T22:29:44.043951 | 2019-03-20T15:01:09 | 2019-03-20T15:01:09 | 176,757,815 | 0 | 1 | null | 2020-07-24T14:40:26 | 2019-03-20T14:59:23 | HTML | UTF-8 | Python | false | false | 6,344 | py | #!/usr/bin/python
"""
======================COPYRIGHT/LICENSE START==========================
ModuleFormat.py: Contains functions specific to PALES program conversions.
Copyright (C) 2010 Wim Vranken (European Bioinformatics Institute)
Brian Smith (University of Glasgow)
=======================================================================
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
A copy of this license can be found in ../../../../license/LGPL.license
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
======================COPYRIGHT/LICENSE END============================
for further information, please contact :
- CCPN website (http://www.ccpn.ac.uk/)
- MSD website (http://www.ebi.ac.uk/msd/)
- contact Wim Vranken ([email protected])
=======================================================================
If you are using this software for academic purposes, we suggest
quoting the following references:
===========================REFERENCE START=============================
R. Fogh, J. Ionides, E. Ulrich, W. Boucher, W. Vranken, J.P. Linge, M.
Habeck, W. Rieping, T.N. Bhat, J. Westbrook, K. Henrick, G. Gilliland,
H. Berman, J. Thornton, M. Nilges, J. Markley and E. Laue (2002). The
CCPN project: An interim report on a data model for the NMR community
(Progress report). Nature Struct. Biol. 9, 416-418.
Wim F. Vranken, Wayne Boucher, Tim J. Stevens, Rasmus
H. Fogh, Anne Pajon, Miguel Llinas, Eldon L. Ulrich, John L. Markley, John
Ionides and Ernest D. Laue (2005). The CCPN Data Model for NMR Spectroscopy:
Development of a Software Pipeline. Proteins 59, 687 - 696.
===========================REFERENCE END===============================
"""
import string
from ccpnmr.format.converters.DataFormat import DataFormat, IOkeywords
from ccp.format.general.Constants import defaultSeqInsertCode
from ccpnmr.format.general.Constants import distanceConstraintDefaultLowerLimit
from ccpnmr.format.general.Util import getNameInfo
from ccp.general.Util import getResonancesFromPairwiseConstraintItem
class PalesFormat(DataFormat):
def setFormat(self):
self.format = 'pales'
self.IOkeywords = IOkeywords
def setGenericImports(self):
self.getConstraints = self.getConstraintsGeneric
self.createConstraintFile = self.createConstraintFileGeneric
#
# Functions different to default functions in DataFormat
#
def setRawRdcConstraint(self):
self.constraintFile.constraints.append(self.rawConstraintClass(self.constraint.serial))
self.rawConstraint = self.constraintFile.constraints[-1]
#
# Have to get some sensible values out
#
lowerLimit = self.constraint.lowerLimit
upperLimit = self.constraint.upperLimit
targetValue = self.constraint.targetValue
if targetValue == None:
targetValue = (lowerLimit + upperLimit) / 2
self.rawConstraint.setRdcData(targetValue,error = self.constraint.error)
def setRawRdcConstraintItem(self):
self.rawConstraint.items.append(self.rawConstraintItemClass())
self.rawConstraintItem = self.rawConstraint.items[-1]
def setRawRdcConstraintItemMembers(self):
itemResonances = getResonancesFromPairwiseConstraintItem(self.item)
for i in range(0,2):
(chainCode,seqCode,spinSystemId,seqInsertCode,atomName) = getNameInfo(self.resSetNames[i])
resLabel = self.getResonanceResLabel(itemResonances[i])
self.rawConstraintItem.members.append(self.rawConstraintItemMemberClass(chainCode,seqCode,resLabel,atomName))
def getPresetChainMapping(self,chainList):
return self.getSingleChainFormatPresetChainMapping(chainList)
def getResonanceResLabel(self,resonance):
# copied from DyanaFormat.py (also in AquaFormat.py - scope for common function in Util?)
resLabel = None
chemCompVar = resonance.resonanceSet.findFirstAtomSet().findFirstAtom().residue.chemCompVar
namingSystem = chemCompVar.chemComp.findFirstNamingSystem(name = self.namingSystemName)
chemCompSysName = chemCompVar.findFirstSpecificSysName(namingSystem = namingSystem)
if not chemCompSysName:
chemCompSysName = chemCompVar.findFirstChemCompSysName(namingSystem = namingSystem)
if chemCompSysName:
resLabel = chemCompSysName.sysName
else:
resLabel = chemCompVar.chemComp.ccpCode.upper()
return resLabel
def createConstraintFileFormatSpecific(self):
# Here bit tricky because first have to get number of chains, and format
# doesn't really handle it. I'd do this by having a specific
# chain keyword for writing RDC constraints for PALES, if it's not set
# and there's only one chain, all good, otherwise throw an
# error or ask the user for the relevant chain, then filter out
# constraints (that's all in place in case it's needed, just ask). Wim
# I do something similar already in DataFormat.py, but it happens at a later stage in the workflow.
chains = []
for constraint in self.constraintList.constraints:
for item in constraint.sortedItems():
for fixedResonance in item.resonances:
if fixedResonance.resonanceSet:
refAtom = fixedResonance.resonanceSet.findFirstAtomSet().findFirstAtom()
if refAtom.residue.chain not in chains:
chains.append(refAtom.residue.chain)
seqStrings = []
for chain in chains:
# Filter out most ligands, hopefully.
if len(chain.residues) > 1:
seqStrings.append(chain.molecule.seqString)
if len(seqStrings) > 1:
print "Warning: multiple sequences present, picking first one"
print 'in', self
self.writeKeywds['oneLetterSequence'] = seqStrings[0]
| [
"[email protected]"
]
| |
982438385f1000e3976346a2dc1120aabdcb9938 | c66955c6fc178955c2024e0318ec7a91a8386c2d | /headfirst/example/example2.py | 6f06549a6c1978e95a4a31f7b5543a9d99fc5481 | []
| no_license | duheng18/python-study | a98642d6ee1b0043837c3e7c5b91bf1e28dfa588 | 13c0571ac5d1690bb9e615340482bdb2134ecf0e | refs/heads/master | 2022-11-30T17:36:57.060130 | 2019-11-18T07:31:40 | 2019-11-18T07:31:40 | 147,268,053 | 1 | 0 | null | 2022-11-22T03:36:51 | 2018-09-04T00:49:42 | Python | UTF-8 | Python | false | false | 751 | py | man=[]
other=[]
try:
data=open('/Users/duheng/Documents/HeadFirstPython/chapter3/sketch.txt','r',encoding='utf-8')
for each_line in data:
try:
(role,line_spoken)=each_line.split(':',1)
line_spoken=line_spoken.strip()
if role=='Man':
man.append(line_spoken)
elif role=='Other Man':
other.append(line_spoken)
except ValueError:
pass
data.close()
except IOError:
print('The data file is missing!')
try:
man_file=open('man_data.txt','w')
other_file=open('other_data.txt','w')
print(man,file=man_file)
print(other,file=other_file)
man_file.close()
other_file.close()
except IOError:
print('File error.')
| [
"[email protected]"
]
| |
0ec907252b0568f7621cb0e98415d6dc0de57206 | 5da5473ff3026165a47f98744bac82903cf008e0 | /packages/google-cloud-channel/samples/generated_samples/cloudchannel_v1_generated_cloud_channel_service_provision_cloud_identity_async.py | 294b8255ef654e0f099f9422b69dfee53a729aba | [
"Apache-2.0"
]
| permissive | googleapis/google-cloud-python | ed61a5f03a476ab6053870f4da7bc5534e25558b | 93c4e63408c65129422f65217325f4e7d41f7edf | refs/heads/main | 2023-09-04T09:09:07.852632 | 2023-08-31T22:49:26 | 2023-08-31T22:49:26 | 16,316,451 | 2,792 | 917 | Apache-2.0 | 2023-09-14T21:45:18 | 2014-01-28T15:51:47 | Python | UTF-8 | Python | false | false | 2,026 | py | # -*- coding: utf-8 -*-
# Copyright 2023 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.
#
# Generated code. DO NOT EDIT!
#
# Snippet for ProvisionCloudIdentity
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-channel
# [START cloudchannel_v1_generated_CloudChannelService_ProvisionCloudIdentity_async]
# This snippet has been automatically generated and should be regarded as a
# code template only.
# It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in:
# https://googleapis.dev/python/google-api-core/latest/client_options.html
from google.cloud import channel_v1
async def sample_provision_cloud_identity():
# Create a client
client = channel_v1.CloudChannelServiceAsyncClient()
# Initialize request argument(s)
request = channel_v1.ProvisionCloudIdentityRequest(
customer="customer_value",
)
# Make the request
operation = client.provision_cloud_identity(request=request)
print("Waiting for operation to complete...")
response = (await operation).result()
# Handle the response
print(response)
# [END cloudchannel_v1_generated_CloudChannelService_ProvisionCloudIdentity_async]
| [
"[email protected]"
]
| |
64a7d6b3abb2ff86e6c68063872fb3310bc2f17e | 0265e740dbc38ab543236a12d98ee9e0b57cb927 | /crawler_world/proxy_pool/Util/utilFunction.py | 2d8f46d84651dfe2e5f6940874d6370dc351f9c4 | [
"MIT"
]
| permissive | ForeverDreamer/scrapy_learning | c5e604c6a285fa6fef112bdc5617b2129288477a | 6d38c58af5b8ba87803ee77de61f2a54cc65a4db | refs/heads/master | 2023-05-13T18:46:43.715685 | 2022-09-22T10:26:11 | 2022-09-22T10:26:11 | 179,958,600 | 0 | 0 | null | 2023-05-01T19:51:39 | 2019-04-07T11:48:43 | Python | UTF-8 | Python | false | false | 4,154 | py | # -*- coding: utf-8 -*-
# !/usr/bin/env python
"""
-------------------------------------------------
File Name: utilFunction.py
Description : tool function
Author : JHao
date: 2016/11/25
-------------------------------------------------
Change Activity:
2016/11/25: 添加robustCrawl、verifyProxy、getHtmlTree
-------------------------------------------------
"""
import requests
import time
from bs4 import BeautifulSoup
import re
from Util.LogHandler import LogHandler
from Util.WebRequest import WebRequest
# logger = LogHandler(__name__, stream=False)
def tcpConnect(proxy):
"""
TCP 三次握手
:param proxy:
:return:
"""
from socket import socket, AF_INET, SOCK_STREAM
s = socket(AF_INET, SOCK_STREAM)
ip, port = proxy.split(':')
result = s.connect_ex((ip, int(port)))
return True if result == 0 else False
# noinspection PyPep8Naming
def robustCrawl(func):
def decorate(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
pass
# logger.info(u"sorry, 抓取出错。错误原因:")
# logger.info(e)
return decorate
# noinspection PyPep8Naming
def verifyProxyFormat(proxy):
"""
检查代理格式
:param proxy:
:return:
"""
import re
verify_regex = r"https?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,5}"
_proxy = re.findall(verify_regex, proxy)
return True if len(_proxy) == 1 and _proxy[0] == proxy else False
# noinspection PyPep8Naming
def getHtmlTree(url, proxy_ip):
# TODO 取代理服务器用代理服务器访问
wr = WebRequest()
# delay 2s for per request
time.sleep(2)
# ip, port, prot = proxy_ip.split(':')
# proxies = {prot: '{}://{}:{}'.format(prot, ip, port)}
#
html = wr.get(url, proxies=None).text
return BeautifulSoup(html, features='lxml')
def extract_ip(ip_info):
ip = re.findall(r'\d+\.\d+\.\d+\.\d+', ip_info)
if len(ip) > 0:
ip = ip[0]
port = re.findall(r'(\d{4,5})<', ip_info)
if len(port) > 0:
port = port[0]
protocol = re.findall(r'https?|HTTPS?', ip_info)
if len(protocol) > 0:
protocol = protocol[0].lower()
else:
protocol = 'http'
return "{}:{}:{}".format(protocol, ip, port)
# noinspection PyPep8Naming
# def validUsefulProxy(proxy):
# url = "http://ip.tool.chinaz.com/" # 查自己的ip
# # url = "http://www.ip138.com/" # 查自己的ip
# ip, port, prot = proxy.split(':')
#
# try:
# proxies = {
# 'protocol': '{}://{}:{}'.format(prot, ip, port)
# }
# r = requests.get(url, proxies=proxies, timeout=10, verify=False)
# soup = BeautifulSoup(r.text, 'lxml')
#
# parent_node = soup.find(class_="IpMRig-tit")
#
# if ip == soup.find(class_="fz24").get_text():
# for i in parent_node.find_all('dd'):
# print(i.get_text())
#
# return True
# except Exception as e:
# print(e)
#
# return False
def validUsefulProxy(proxy):
url = "http://crawleruniverse.com:8000/ct/ri" # 查自己的ip
prot, ip, port = proxy.split(':')
try:
proxies = {
prot: '{}://{}:{}'.format(prot, ip, port)
}
r = requests.get(url, proxies=proxies, timeout=10, verify=False)
soup = BeautifulSoup(r.text, 'lxml')
http_x_forwarded_for = re.findall(r'\d+.\d+.\d+.\d+', str(soup.find("h4")))
remote_addr = re.findall(r'\d+.\d+.\d+.\d+', str(soup.find("h5")))[0]
if ip == remote_addr:
print('http_x_forwarded_for: {}, remote_addr: {}, ip: {}, pass: {}'.format(http_x_forwarded_for,
remote_addr,
ip,
ip == remote_addr))
return True
except Exception as e:
# pass
print(e)
return False
| [
"[email protected]"
]
| |
69749573e1c7329b67e11083405f953765a7d54d | cd2ce8e913048a535d7680789d38a16f23ad04b3 | /server/settings/local.py | bdfb750ad6a8b98893ae27a61c1b35837399a5c8 | []
| no_license | wade333777/cocos-js-tips | 3758bbaccb168c1a7f4d17e243e8107cb9fbfb06 | 4f430d5631b1118ad251bdaf8384bc0dbdaf07b9 | refs/heads/master | 2021-01-20T20:35:48.273690 | 2016-06-22T10:02:15 | 2016-06-22T10:02:15 | 60,678,664 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,508 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from base import *
# 启用调试模式
DEBUG = True
# ============================================================================
CHANNEL = "android" # [只能小写]
WEB_KEY = 'spyykimech'
GAME_KEY = ')7yt4e!#)gcy&#0^hlme-+082=s!b!$8+h$+(j0bucx0+nu%pe'
ENCODE_DECODE_KEY = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
ENCODE_DECODE_IV = "1234567812345678"
# SECRET_KEY = ')7yt4e!#)gcy&#0^hlme-+082=s!b!$8+h$+(j0bucx0+nu%pe'
# ============================================================================
STATS_SWITCH = True
SCRIBE_SERVER = '127.0.0.1'
SCRIBE_PORT = 8250
# ============================================================================
LOGGER = {
'tornado': {
"OPEN": True,
"LEVEL": "INFO",
"HANDLERS": [
{
"module": "torngas.logger.CustomRotatingFileHandler",
"filename": "info",
"when": "W0",
"encoding": "utf-8",
"delay": True,
"backupCount": 100,
}
]
},
'torngas.accesslog': {
"OPEN": True,
"LEVEL": "INFO",
"FORMATTER": '%(message)s',
"HANDLERS": [
{
"module": "torngas.logger.CustomRotatingFileHandler",
"filename": "access",
"when": "W0",
"encoding": "utf-8",
"delay": False,
"backupCount": 100,
}
]
},
}
| [
"[email protected]"
]
| |
5c37a9079020b9f7860ca0f1c0674ef4efac94d4 | 3d05a382e418234558bed720ad5a56dbbf976a6a | /game.py | 3e0a01bab1c9d7a87849d46d9b85a0652467a729 | []
| no_license | richwandell/tank-tennis | 79354963197ea8469ecd90a682f1d522e5fd7c13 | 47e822d21b6ad3e0330f6f2427da56bf0043a668 | refs/heads/master | 2020-04-02T14:24:14.956038 | 2018-10-24T15:19:57 | 2018-10-24T15:19:57 | 154,523,097 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 470 | py | from modules.stage import Stage
from modules.main_menu import MainMenu
import json, pygame
pygame.init()
pygame.mixer.init()
screen, world = pygame.display.set_mode((0, 0),), {}
def showMenu():
global world, screen
world = MainMenu(screen)
def playLevel(level):
global world, screen
level1 = json.loads("".join(open("levels/level%s.json" % str(level)).readlines()))
world = Stage(screen, level1)
if __name__ == "__main__":
playLevel(1)
| [
"[email protected]"
]
| |
e27110a75e2ad24753a8b16d4b1adf2e73ea4238 | e3365bc8fa7da2753c248c2b8a5c5e16aef84d9f | /indices/nngarish.py | 287745db58ac4a715debb11514f0d36b70780a46 | []
| no_license | psdh/WhatsintheVector | e8aabacc054a88b4cb25303548980af9a10c12a8 | a24168d068d9c69dc7a0fd13f606c080ae82e2a6 | refs/heads/master | 2021-01-25T10:34:22.651619 | 2015-09-23T11:54:06 | 2015-09-23T11:54:06 | 42,749,205 | 2 | 3 | null | 2015-09-23T11:54:07 | 2015-09-18T22:06:38 | Python | UTF-8 | Python | false | false | 43 | py | ii = [('LyelCPG.py', 1), ('FerrSDO.py', 1)] | [
"[email protected]"
]
| |
69d4561868e7b4e9549331417be235f7bde6a826 | 45734abde30b437c2a1ba80653d7323e5c1d8c7f | /python/0735_asteroid_collision.py | c247bdeb01e2092efef3a66a280fd30416006c12 | []
| no_license | rdtr/leetcode_solutions | 6629e03dd5b5fee15aaabe7f53204778f237ed96 | 51800d33c57e36ef62b6067d6f91a82c0e55dc6d | refs/heads/main | 2022-05-21T12:17:23.201832 | 2022-03-12T09:20:46 | 2022-03-12T09:20:46 | 80,395,988 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 684 | py | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = []
i = 0
while i < len(asteroids):
if not stack:
stack.append(asteroids[i])
elif (asteroids[i] > 0 and stack[-1] > 0) or (asteroids[i] < 0 and stack[-1] < 0) or (
asteroids[i] > 0 and stack[-1] < 0):
stack.append(asteroids[i])
else:
size = -asteroids[i]
if size > stack[-1]:
stack.pop()
continue
elif size == stack[-1]:
stack.pop()
i += 1
return stack
| [
"[email protected]"
]
| |
d6ffee8f77d0617d1af183ab560feda3653eec61 | dc77f52db640fca23aa66be30f15378b09b205c1 | /pitchblog/models.py | 45de23c490eadfdabcd69a5f5c5b4b14e71aed09 | [
"MIT"
]
| permissive | marysinaida/PITCH_SITE | 233feb0401bc52c17d0f9e91a66c5f46829b1215 | 95d141baf92a24ce8273ca10b9ee64498d6f22dd | refs/heads/master | 2020-09-15T22:57:14.343802 | 2019-11-26T13:25:36 | 2019-11-26T13:25:36 | 223,576,612 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 978 | py | from datetime import datetime
from pitchblog import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(25), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
password = db.Column(db.String(60), nullable=False)
posts = db.relationship('Post', backref='author', lazy=True)
def __repr__(self):
return f("User{self.username} {self.email} {self.image_file}")
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
content = db.Column(db.Text, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
def __repr__(self):
return f("Post{self.title} {self.date_posted}")
| [
"[email protected]"
]
| |
493cb9e1cddcb1185f9306b497aa2473f7039a0d | dd5abf881b73dc2cca1d2a4b18c61179d1c73b4b | /web/model/t_task.py | b7144ac56cc03fdc02933ef91cd446ec94bc7f8e | []
| no_license | mafeicnnui/dbops | 858af1673f27716180cabc41329a0a07c0e1862c | aebacb3410d7d345bb720c7a341d2d83825f8a90 | refs/heads/main | 2023-06-08T14:24:11.782598 | 2023-06-05T07:41:55 | 2023-06-05T07:41:55 | 337,357,228 | 10 | 2 | null | 2023-06-02T06:23:18 | 2021-02-09T09:45:17 | HTML | UTF-8 | Python | false | false | 9,457 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/6/30 15:46
# @Author : ma.fei
# @File : t_user.py
# @Software: PyCharm
import os,json
import traceback
import requests
from web.utils.common import exception_info
from web.utils.common import get_connection,get_connection_dict
from web.utils.mysql_async import async_processer
async def query_task(tagname):
v_where = ' and 1=1 '
if tagname!='':
v_where=v_where+" and a.task_tag='{0}'\n".format(tagname)
sql = """SELECT a.task_tag,
a.comments,
concat(b.server_ip,':',b.server_port),
a.script_file,
a.run_time,
a.api_server,
CASE a.STATUS WHEN '1' THEN '启用' WHEN '0' THEN '禁用' END STATUS
FROM t_task a,t_server b
WHERE a.server_id=b.id
AND b.status='1' {0} """.format(v_where)
return await async_processer.query_list(sql)
async def query_minio_case(p_db_env):
res = {}
sql = """SELECT
c.dmmc AS 'db_type',
a.db_desc,
date_format(d.start_time,'%Y-%m-%d %H:%i:%s') as create_date,
CASE WHEN SUBSTR(d.total_size,-1)='M' THEN
SUBSTR(d.total_size,1,LENGTH(total_size)-1)
WHEN SUBSTR(d.total_size,-1)='G' THEN
SUBSTR(total_size,1,LENGTH(total_size)-1)*1024
ELSE 0 END AS total_size,
concat(d.elaspsed_backup+d.elaspsed_gzip,'') as backup_time,
CASE WHEN d.status='0' THEN '√' ELSE '×' END flag
FROM t_db_source a,t_dmmx b,t_dmmx c,t_db_backup_total d,t_db_config e
WHERE a.market_id='000'
AND a.db_env=b.dmm AND b.dm='03'
and a.db_env='{0}'
AND a.db_type=c.dmm AND c.dm='02'
AND d.db_tag=e.db_tag
AND e.db_id=a.id
AND create_date=DATE_SUB(DATE(NOW()),INTERVAL 1 DAY) ORDER BY a.db_env,a.db_type""".format(p_db_env)
res['data']=await async_processer.query_list(sql)
sql = """SELECT
cast(SUM(CASE WHEN d.status='0' THEN 1 ELSE 0 END) as char) AS success,
cast(SUM(CASE WHEN d.status='1' THEN 1 ELSE 0 END) as char) AS failure
FROM t_db_source a,t_dmmx b,t_dmmx c,t_db_backup_total d,t_db_config e
WHERE a.market_id='000'
AND a.db_env=b.dmm AND b.dm='03'
and a.db_env='{0}'
AND a.db_type=c.dmm AND c.dm='02'
AND d.db_tag=e.db_tag
AND e.db_id=a.id
AND create_date=DATE_SUB(DATE(NOW()),INTERVAL 1 DAY) ORDER BY a.db_env,a.db_type""".format(p_db_env)
rs = await async_processer.query_one(sql)
res['success'] = rs[0]
res['failure'] = rs[1]
return res
async def query_task_log(tagname,begin_date,end_date):
v_where = ' and 1=1 '
if tagname != '':
v_where = v_where+" and a.sync_tag='{0}'\n".format(tagname)
if begin_date != '':
v_where = v_where+" and b.create_date>='{0}'\n".format(begin_date+' 0:0:0')
if end_date != '':
v_where = v_where+" and b.create_date<='{0}'\n".format(end_date+' 23:59:59')
sql = """SELECT a.sync_tag,
a.comments,
b.sync_day,
b.download_time,
b.upload_time,
b.total_time,
b.transfer_file,
DATE_FORMAT(b.create_date,'%Y-%m-%d %h:%i:%s') AS create_date
FROM t_minio_config a ,t_minio_log b
WHERE a.sync_tag=b.sync_tag
AND a.status='1' {} ORDER BY b.sync_tag,b.create_date """.format(v_where)
return await async_processer.query_list(sql)
async def save_task(p_sync):
val = await check_task(p_sync,'I')
if val['code']=='-1':
return val
try:
sql = """insert into t_task(
task_tag,comments,server_id,python3_home,script_path,script_file,api_server,run_time,status)
values('{}','{}','{}','{}','{}','{}','{}','{}','{}')
""".format(p_sync['task_tag'],p_sync['task_desc'],p_sync['server_id'],
p_sync['python3_home'],p_sync['script_base'],p_sync['script_name'],
p_sync['api_server'],p_sync['run_time'],p_sync['status'])
await async_processer.exec_sql(sql)
return {'code': '0', 'message': '保存成功!'}
except:
traceback.print_exc()
return {'code': '-1', 'message': '保存失败!'}
async def upd_task(p_sync):
val = await check_task(p_sync,'U')
if val['code'] == '-1':
return val
try:
sql="""update t_task
set comments ='{}',
server_id ='{}',
python3_home ='{}',
script_path ='{}',
script_file ='{}',
api_server ='{}',
run_time ='{}',
STATUS ='{}'
where task_tag='{}'""".format(p_sync['task_desc'],p_sync['server_id'],p_sync['python3_home'],
p_sync['script_base'], p_sync['script_name'],p_sync['api_server'],
p_sync['run_time'],p_sync['status'],p_sync['task_tag'])
await async_processer.exec_sql(sql)
return {'code': '0', 'message': '更新成功!'}
except :
traceback.print_exc()
return {'code': '-1', 'message': '更新失败!'}
async def del_task(p_task_tag):
try:
sql="delete from t_task where task_tag='{0}'".format(p_task_tag)
await async_processer.exec_sql(sql)
return {'code': '0', 'message': '删除成功!'}
except :
traceback.print_exc()
return {'code': '-1', 'message': '删除失败!'}
async def check_tag_rep(p_task):
sql = "select count(0) from t_task where task_tag='{0}'".format(p_task["task_tag"])
rs = await async_processer.query_one(sql)
return rs[0]
async def check_task(p_task,p_flag):
result = {}
if p_task["task_tag"]=="":
result['code']='-1'
result['message']='任务标识不能为空!'
return result
if (await check_tag_rep(p_task))>0 and p_flag=='I':
result['code'] = '-1'
result['message'] = '同步标识重复!'
return result
if p_task["task_desc"]=="":
result['code']='-1'
result['message']='任务描述不能为空!'
return result
if p_task["server_id"]=="":
result['code']='-1'
result['message']='同步服务器不能为空!'
return result
if p_task["script_base"] == "":
result['code'] = '-1'
result['message'] = '脚本目录不能为空!'
return result
if p_task["script_name"] == "":
result['code'] = '-1'
result['message'] = '脚本名称不能为空!'
return result
if p_task["run_time"] == "":
result['code'] = '-1'
result['message'] = '运行时间不能为空!'
return result
if p_task["api_server"] == "":
result['code'] = '-1'
result['message'] = 'API服务器不能为空!'
return result
if p_task["status"] == "":
result['code'] = '-1'
result['message'] = '任务状态不能为空!'
return result
result['code'] = '0'
result['message'] = '验证通过'
return result
async def get_task_by_taskid(p_task_tag):
sql = "select * from t_task where task_tag='{0}'".format(p_task_tag)
return await async_processer.query_dict_one(sql)
def push_task(p_tag,p_api):
url = 'http://{}/push_task_remote'.format(p_api)
res = requests.post(url, data={'tag': p_tag})
jres = res.json()
v = ''
for c in jres['msg']['crontab'].split('\n'):
if c.count(p_tag) > 0:
v = v + "<span class='warning'>" + c + "</span>"
else:
v = v + c
v = v + '<br>'
jres['msg']['crontab'] = v
return jres
def run_task(p_tag,p_api):
try:
result = {}
result['code'] = '0'
result['message'] = '执行成功!'
v_cmd = "curl -XPOST {0}/run_task_remote -d 'tag={1}'".format(p_api,p_tag)
r = os.popen(v_cmd).read()
d = json.loads(r)
if d['code'] == 200:
return result
else:
result['code'] = '-1'
result['message'] = '{0}!'.format(d['msg'])
return result
except Exception as e:
result['code'] = '-1'
result['message'] = '{0!'.format(str(e))
return result
def stop_task(p_tag,p_api):
try:
result = {}
result['code'] = '0'
result['message'] = '执行成功!'
r = os.system("curl -XPOST {0}/stop_task_remote -d 'tag={1}'".format(p_api,p_tag))
if r == 0:
return result
else:
result['code'] = '-1'
result['message'] = '执行失败!'
return result
except:
result['code'] = '-1'
result['message'] = '执行失败!'
return result
| [
"[email protected]"
]
| |
d50b30de4699270bdccde2ab4e9bc05670de33f4 | 4a8c1f7d9935609b780aff95c886ef7781967be0 | /atcoder/_codeforces/1324_f.py | 057771514859b798e0ba37f2a0eda18a50f48caf | []
| no_license | recuraki/PythonJunkTest | d5e5f5957ac5dd0c539ef47759b1fe5ef7a2c52a | 2556c973d468a6988d307ce85c5f2f8ab15e759a | refs/heads/master | 2023-08-09T17:42:21.875768 | 2023-07-18T23:06:31 | 2023-07-18T23:06:31 | 13,790,016 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,066 | py | import sys
from io import StringIO
import unittest
import logging
logging.basicConfig(level=logging.DEBUG)
def resolve():
n = int(input())
dat = list(map(int, input().split()))
v =[]
for i in range(n+1):
v.append([])
score = [0] * (n)
for i in range(n-1):
a, b = map(int, input().split())
v[a-1].append(b-1)
v[b-1].append(a-1)
for i in range(n):
for x in v[i]:
score[i] += 1
class TestClass(unittest.TestCase):
def assertIO(self, input, output):
stdout, stdin = sys.stdout, sys.stdin
sys.stdout, sys.stdin = StringIO(), StringIO(input)
resolve()
sys.stdout.seek(0)
out = sys.stdout.read()[:-1]
sys.stdout, sys.stdin = stdout, stdin
self.assertEqual(out, output)
def test_input_1(self):
print("test_input_1")
input = """9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9"""
output = """2 2 2 2 2 1 1 0 2 """
self.assertIO(input, output)
if __name__ == "__main__":
unittest.main() | [
"[email protected]"
]
| |
a98077b547dbb92b9a08eedcba16e8d2d205d6c9 | 5312a19268af0f9ab2c319e46f8d460d64e6e898 | /arche_m2m/__init__.py | 55dbc9d8dab7729058fa4d83f25791c76e161c1c | []
| no_license | GlobalActionPlan/arche_m2m | 2b1bf57b89bb398d747966a5d094c40c6df66916 | 698381888ff55ec72f0027596c5afd9c9b6a3e78 | refs/heads/master | 2021-01-10T20:47:04.159490 | 2017-06-09T12:54:53 | 2017-06-09T12:54:53 | 23,307,596 | 1 | 0 | null | 2020-02-10T08:16:35 | 2014-08-25T08:49:12 | Python | UTF-8 | Python | false | false | 335 | py | from pyramid.i18n import TranslationStringFactory
_ = TranslationStringFactory('arche_m2m')
def includeme(config):
config.include('.ttw_translations')
config.include('.models')
config.include('.schemas')
config.include('.views')
config.include('.permissions')
config.add_translation_dirs('arche_m2m:locale')
| [
"[email protected]"
]
| |
3480e923215921c85813159158d11cb1c3266241 | 72af42076bac692f9a42e0a914913e031738cc55 | /01, 특강_210705_0706/02, source/CookData(2021.01.15)/Code06-05.py | 02e7ffd300f97cb0f38c79208316d1ec8986a4e6 | []
| no_license | goareum93/Algorithm | f0ab0ee7926f89802d851c2a80f98cba08116f6c | ec68f2526b1ea2904891b929a7bbc74139a6402e | refs/heads/master | 2023-07-01T07:17:16.987779 | 2021-08-05T14:52:51 | 2021-08-05T14:52:51 | 376,908,264 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 218 | py | def isStackEmpty() :
global SIZE, stack, top
if (top == -1) :
return True
else :
return False
SIZE = 5
stack = [ None for _ in range(SIZE) ]
top = -1
print("스택이 비었는지 여부 ==>", isStackEmpty())
| [
"[email protected]"
]
| |
0a9cd5b6a32f41249dcf985a2b629a1aeb6a130b | 1e9c9f2a9639db7cdb032aae69cb4d99aef1d3a5 | /tutsPlus/gettingStartedwithPython/1_helloWorld.py | 76232cb46c3fee9f08bb0213946e84e3a587858b | [
"MIT"
]
| permissive | sagarnikam123/learnNPractice | f0da3f8acf653e56c591353ab342765a6831698c | 1b3b0cb2cff2f478006626a4c37a99102acbb628 | refs/heads/master | 2023-02-04T11:21:18.211654 | 2023-01-24T14:47:52 | 2023-01-24T14:47:52 | 61,184,927 | 2 | 1 | MIT | 2022-03-06T11:07:18 | 2016-06-15T06:57:19 | Python | UTF-8 | Python | false | false | 89 | py | #! /usr/bin/env python
print "Hello World !"
2+1
3*7
2*(3+4)
print "hey"
3+2
print "yo"
| [
"[email protected]"
]
| |
e7f3e2452713e57c40f10d8e0d92f1f6a021a5e3 | 655050425d88874f570cab93d0613fd22abb8e06 | /superman/dataset/__init__.py | 0d5d78e309c63ed29fe0ac160d21389cc225ed51 | [
"MIT"
]
| permissive | vishalbelsare/superman | 86a23566323325d459d06f6ecad6d575b76972b6 | 346fc0d590f40bfe0141630e3146ec8e7ee18be3 | refs/heads/master | 2021-06-09T13:21:07.161740 | 2020-04-14T17:17:32 | 2020-04-14T17:17:32 | 143,188,314 | 0 | 0 | MIT | 2021-04-04T18:45:24 | 2018-08-01T17:35:44 | Python | UTF-8 | Python | false | false | 157 | py | from __future__ import absolute_import
from .ds import TrajDataset, VectorDataset
from .ds_view import DatasetView, MultiDatasetView
from .metadata import *
| [
"[email protected]"
]
| |
314d77c8e953502e48cee36510cebe43e82ae47b | 0a43afbcba776ed8ada0fef5425b1507aa4d51c1 | /waresmartbook/sales/views.py | 83b99ea9ccacc01a07c2213922764731927bc5f3 | []
| no_license | geethusuresh/inventory-systems | c76d6d10429f483499594df8c8f34d780531f18c | fd4211d29042776fa47da92162cbbbe8220090cd | refs/heads/master | 2021-01-02T08:51:31.278578 | 2014-09-28T07:35:54 | 2014-09-28T07:35:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 97,538 | py | # Create your views here.
import sys
import ast
import simplejson
import datetime as dt
from datetime import datetime
from decimal import *
from num2words import num2words
import math
import os
from django.db import IntegrityError
from django.db.models import Max
from django.contrib.auth.views import password_reset
from django.shortcuts import get_object_or_404, render
from django.views.generic.base import View
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.conf import settings
from sales.models import *
from inventory.models import InventoryItem
from web.models import Customer, OwnerCompany
from reportlab.lib.units import cm
from reportlab.lib.units import inch
from reportlab.lib.units import mm
from reportlab.pdfgen.canvas import Canvas
from reportlab.platypus import Frame, Image, Table, TableStyle, Paragraph, SimpleDocTemplate, Spacer
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter, A4
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.enums import TA_RIGHT, TA_JUSTIFY
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter, A4
from reportlab.lib.units import inch
from reportlab.pdfgen import canvas
from django.http import HttpResponse
class SalesEntry(View):
def get(self, request, *args, **kwargs):
current_date = dt.datetime.now().date()
inv_number = Sales.objects.aggregate(Max('id'))['id__max']
if not inv_number:
inv_number = 1
else:
inv_number = inv_number + 1
invoice_number = 'INV' + str(inv_number)
return render(request, 'sales/sales_entry.html',{
'sales_invoice_number': invoice_number,
'current_date': current_date.strftime('%d/%m/%Y'),
})
def post(self, request, *args, **kwargs):
sales_dict = ast.literal_eval(request.POST['sales'])
sales, sales_created = Sales.objects.get_or_create(sales_invoice_number=sales_dict['sales_invoice_number'])
sales.sales_invoice_number = sales_dict['sales_invoice_number']
sales.sales_invoice_date = datetime.strptime(sales_dict['sales_invoice_date'], '%d/%m/%Y')
salesman = User.objects.get(first_name=sales_dict['staff'])
sales.discount = sales_dict['net_discount']
sales.round_off = sales_dict['roundoff']
sales.net_amount = sales_dict['net_total']
sales.grant_total = sales_dict['grant_total']
sales.salesman = salesman
sales.lpo_number = sales_dict['lpo_number']
sales.save()
sales_items = sales_dict['sales_items']
for sales_item in sales_items:
item = Item.objects.get(code=sales_item['item_code'])
s_item, item_created = SalesItem.objects.get_or_create(item=item, sales=sales)
inventory, created = Inventory.objects.get_or_create(item=item)
if sales_created:
inventory.quantity = inventory.quantity - int(sales_item['qty_sold'])
else:
inventory.quantity = inventory.quantity + s_item.quantity_sold - int(sales_item['qty_sold'])
inventory.save()
s_item, item_created = SalesItem.objects.get_or_create(item=item, sales=sales)
s_item.sales = sales
s_item.item = item
s_item.quantity_sold = sales_item['qty_sold']
s_item.discount_given = sales_item['disc_given']
s_item.net_amount = sales_item['net_amount']
s_item.selling_price = sales_item['unit_price']
s_item.save()
stock, created = SalesmanStock.objects.get_or_create(item=item, salesman=salesman)
if created:
stock.quantity = int(sales_item['qty_sold'])
else:
if sales_created:
stock.quantity = stock.quantity + int(sales_item['qty_sold'])
else:
stock.quantity = stock.quantity - s_item.quantity_sold + int(sales_item['qty_sold'])
selling_price = sales_item['unit_price']
stock.selling_price = selling_price
stock.unit_price = inventory.unit_price
stock.discount_permit_percentage = inventory.discount_permit_percentage
stock.discount_permit_amount = inventory.discount_permit_amount
stock.save()
sales_invoice, created = SalesInvoice.objects.get_or_create(sales=sales)
sales.save()
sales_invoice.date = sales.sales_invoice_date
sales_invoice.invoice_no = sales.sales_invoice_number
sales_invoice.save()
res = {
'result': 'Ok',
'sales_invoice_id': 'sales_invoice.id',
}
response = simplejson.dumps(res)
status_code = 200
return HttpResponse(response, status = status_code, mimetype="application/json")
class SalesReturnView(View):
def get(self, request, *args, **kwargs):
if SalesReturn.objects.exists():
invoice_number = int(SalesReturn.objects.aggregate(Max('return_invoice_number'))['return_invoice_number__max']) + 1
else:
invoice_number = 1
if not invoice_number:
invoice_number = 1
return render(request, 'sales/return_entry.html', {
'invoice_number' : invoice_number,
})
def post(self, request, *args, **kwargs):
post_dict = request.POST['sales_return']
post_dict = ast.literal_eval(post_dict)
sales = Sales.objects.get(sales_invoice_number=post_dict['sales_invoice_number'])
sales_return, created = SalesReturn.objects.get_or_create(sales=sales, return_invoice_number = post_dict['invoice_number'])
sales_return.date = datetime.strptime(post_dict['sales_return_date'], '%d/%m/%Y')
sales_return.net_amount = float(sales_return.net_amount) + float(post_dict['net_return_total'])
sales_return.save()
return_items = post_dict['sales_items']
for item in return_items:
return_item = InventoryItem.objects.get(code=item['item_code'])
s_return_item, created = SalesReturnItem.objects.get_or_create(item=return_item, sales_return=sales_return)
s_return_item.amount = float(s_return_item.amount) + float(item['returned_amount'])
s_return_item.return_quantity = item['returned_quantity']
s_return_item.save()
return_item.quantity = return_item.quantity + int(item['returned_quantity'])
return_item.save()
# for s_item in sales.salesitem_set.all():
s_item = sales.salesitem_set.filter(delivery_note_item__item=return_item)
print s_item, s_item.count()
deliverynote_item = s_item[0].delivery_note_item
deliverynote_item.quantity_sold = deliverynote_item.quantity_sold - int(item['returned_quantity'])
deliverynote_item.is_completed = False
deliverynote_item.save()
delivery_note = deliverynote_item.delivery_note
delivery_note.is_pending = True
delivery_note.save()
response = {
'result': 'Ok',
}
status_code = 200
return HttpResponse(response, status = status_code, mimetype="application/json")
class ViewSales(View):
def get(self, request, *args, **kwargs):
return render(request, 'sales/view_sales.html',{})
class SalesDetails(View):
def get(self, request, *args, **kwargs):
if request.is_ajax():
invoice_number = request.GET['invoice_no']
try:
sales = Sales.objects.get(sales_invoice_number=invoice_number)
sales_return_obj = SalesReturn.objects.filter(sales=sales)
except:
sales = None
sales_return_obj = []
if sales:
sales_items = SalesItem.objects.filter(sales=sales)
sl_items = []
for item in sales_items:
if sales_return_obj:
sales_return_items = SalesReturnItem.objects.filter(sales_return__sales=sales, item=item.item)
total_return_quantity = 0
for ret_item in sales_return_items:
total_return_quantity = total_return_quantity + int(ret_item.return_quantity)
return_quantity = int(item.quantity_sold) - int(total_return_quantity)
else:
return_quantity = int(item.quantity_sold)
sl_items.append({
'item_code': item.delivery_note_item.item.code,
'item_name': item.delivery_note_item.item.name,
'barcode': item.delivery_note_item.item.barcode if item.delivery_note_item.item.barcode else '',
'stock': item.delivery_note_item.item.quantity,
'unit_price': item.selling_price,
'tax': item.delivery_note_item.item.tax if item.delivery_note_item.item.tax else 0 ,
'uom': item.delivery_note_item.item.uom.uom if item.delivery_note_item.item.uom else '',
'quantity_sold': item.quantity_sold,
'discount_given': item.discount_amount,
'max_return_qty': return_quantity,
'returned_amount': 0,
})
sales_dict = {
'invoice_number': sales.sales_invoice_number,
'sales_invoice_date': sales.sales_invoice_date.strftime('%d/%m/%Y'),
'customer': sales.customer.customer_name,
'sales_man': sales.salesman.first_name,
'net_amount': sales.net_amount,
'round_off': sales.round_off,
'grant_total': sales.grant_total,
'discount': sales.discount,
'sales_items': sl_items
}
res = {
'result': 'Ok',
'sales': sales_dict
}
else:
res = {
'result': 'No Sales entry for this invoice number',
}
response = simplejson.dumps(res)
status_code = 200
return HttpResponse(response, status = status_code, mimetype="application/json")
return render(request, 'sales/view_sales.html',{})
class CreateQuotation(View):
def get(self, request, *args, **kwargs):
current_date = dt.datetime.now().date()
ref_number = Quotation.objects.aggregate(Max('id'))['id__max']
if not ref_number:
ref_number = 1
prefix = 'QO'
else:
ref_number = ref_number + 1
prefix = Quotation.objects.latest('id').prefix
reference_number = prefix + str(ref_number)
context = {
'current_date': current_date.strftime('%d-%m-%Y'),
'reference_number': reference_number,
}
return render(request, 'sales/create_quotation.html', context)
def post(self, request, *args, **kwargs):
if request.is_ajax():
quotation_data = ast.literal_eval(request.POST['quotation'])
quotation, quotation_created = Quotation.objects.get_or_create(reference_id=quotation_data['reference_no'])
quotation.date = datetime.strptime(quotation_data['date'], '%d-%m-%Y')
quotation.attention = quotation_data['attention']
quotation.subject = quotation_data['subject']
quotation.net_total = quotation_data['total_amount']
quotation.delivery = quotation_data['delivery']
quotation.proof = quotation_data['proof']
quotation.payment = quotation_data['payment']
quotation.validity = quotation_data['validity']
quotation.save()
customer = Customer.objects.get(customer_name=quotation_data['customer'])
quotation.to = customer
quotation.save()
quotation_data_items = quotation_data['sales_items']
for quotation_item in quotation_data_items:
item = Item.objects.get(code=quotation_item['item_code'])
quotation_item_obj, item_created = QuotationItem.objects.get_or_create(item=item, quotation=quotation)
inventory, created = Inventory.objects.get_or_create(item=item)
inventory.quantity = inventory.quantity - int(quotation_item['qty_sold'])
inventory.save()
quotation_item_obj.net_amount = float(quotation_item['net_amount'])
quotation_item_obj.quantity_sold = int(quotation_item['qty_sold'])
quotation_item_obj.selling_price = float(quotation_item['unit_price'])
quotation_item_obj.save()
res = {
'result': 'OK',
'quotation_id': quotation.id,
}
response = simplejson.dumps(res)
return HttpResponse(response, status=200, mimetype='application/json')
class DeliveryNotePDF(View):
def get(self, request, *args, **kwargs):
delivery_note_id = kwargs['delivery_note_id']
delivery_note = DeliveryNote.objects.get(id=delivery_note_id)
response = HttpResponse(content_type='application/pdf')
p = canvas.Canvas(response, pagesize=(1000, 1200))
status_code = 200
y = 1100
style = [
('FONTSIZE', (0,0), (-1, -1), 20),
('FONTNAME',(0,0),(-1,-1),'Helvetica')
]
new_style = [
('FONTSIZE', (0,0), (-1, -1), 30),
('FONTNAME',(0,0),(-1,-1),'Helvetica')
]
para_style = ParagraphStyle('fancy')
para_style.fontSize = 20
para_style.fontName = 'Helvetica'
para = Paragraph('<b> DELIVERY NOTE TO SALESMAN</b>', para_style)
data =[['', delivery_note.date.strftime('%d-%m-%Y'), para , delivery_note.delivery_note_number]]
table = Table(data, colWidths=[30, 360, 420, 100], rowHeights=50, style=style)
# table.setStyle(TableStyle([
# ('FONTSIZE', (2,0), (2,0), 30),
# ]))
table.wrapOn(p, 200, 400)
table.drawOn(p,50, 980)
quotation = delivery_note.quotation
customer_name = ''
if delivery_note.customer:
customer_name = delivery_note.customer.customer_name
data=[['', customer_name, delivery_note.lpo_number if delivery_note.lpo_number else '' ]]
table = Table(data, colWidths=[30, 540, 60], rowHeights=30, style = style)
table.wrapOn(p, 200, 400)
table.drawOn(p, 50, 940)
data=[['', '', delivery_note.date.strftime('%d-%m-%Y')]]
table = Table(data, colWidths=[450, 120, 70], rowHeights=50, style = style)
table.wrapOn(p, 200, 400)
table.drawOn(p,50, 915)
if delivery_note.quotation:
data=[['', '', delivery_note.quotation.reference_id]]
table = Table(data, colWidths=[450, 120, 70], rowHeights=40, style = style)
table.wrapOn(p, 200, 400)
table.drawOn(p,50, 885)
y = 800
i = 0
i = i + 1
if delivery_note.quotation:
for q_item in delivery_note.quotation.quotationitem_set.all():
y = y-40
if y <= 270:
y = 800
p.showPage()
data1 = [[i, q_item.item.code, q_item.item.name, q_item.quantity_sold, q_item.item.uom.uom]]
table = Table(data1, colWidths=[80, 120, 400, 90, 100], rowHeights=40, style = style)
table.wrapOn(p, 200, 600)
table.drawOn(p, 10, y)
i = i + 1
if delivery_note.deliverynoteitem_set.all().count() > 0:
for delivery_item in delivery_note.deliverynoteitem_set.all():
y = y-40
if y <= 270:
y = 800
p.showPage()
data1 = [[i, delivery_item.item.code, delivery_item.item.name, delivery_item.quantity_sold, delivery_item.item.uom.uom]]
table = Table(data1, colWidths=[80, 120, 400, 90, 100], rowHeights=40, style = style)
table.wrapOn(p, 200, 600)
table.drawOn(p, 10, y)
i = i + 1
p.showPage()
p.save()
return response
class CreateQuotationPdf(View):
def get(self, request, *args, **kwargs):
quotation_id = kwargs['quotation_id']
quotation = Quotation.objects.get(id=quotation_id)
response = HttpResponse(content_type='application/pdf')
p = canvas.Canvas(response, pagesize=(1000, 1000))
status_code = 200
y = 915
style = [
('FONTSIZE', (0,0), (-1, -1), 16),
('FONTNAME',(0,0),(-1,-1),'Helvetica')
# ('INNERGRID', (0,0), (-1,1), 0.25, colors.black),
]
style1 = [
('FONTSIZE', (0,0), (-1, -1), 18),
('FONTNAME',(0,0),(-1,-1),'Helvetica')
# ('INNERGRID', (0,0), (-1,1), 0.25, colors.black),
]
try:
owner_company = OwnerCompany.objects.latest('id')
if owner_company.logo:
path = settings.PROJECT_ROOT.replace("\\", "/")+"/media/"+owner_company.logo.name
p.drawImage(path, 7*cm, 30*cm, width=20*cm, preserveAspectRatio=True)
except:
pass
p.roundRect(80, y-130, 840, 0.5*inch, 10, stroke=1, fill=0)
p.setFont("Helvetica-Bold", 20)
p.drawString(400, 800, "QUOTATION")
p.roundRect(80, y-250, 840, 120, 20, stroke=1, fill=0)
data=[['To :', quotation.to.customer_name]]
table = Table(data, colWidths=[125, 400], rowHeights=40, style = style)
table.wrapOn(p, 200, 400)
table.drawOn(p,160, 745)
data=[['Attention :', quotation.attention]]
table = Table(data, colWidths=[125, 400], rowHeights=40, style = style)
table.wrapOn(p, 200, 400)
table.drawOn(p,160, 715)
data=[['Subject :', quotation.subject]]
table = Table(data, colWidths=[125, 400], rowHeights=40, style = style)
table.wrapOn(p, 200, 400)
table.drawOn(p,160, 685)
data=[['Date :', quotation.date.strftime('%d-%m-%Y')]]
table = Table(data, colWidths=[100, 400], rowHeights=40, style = style)
table.wrapOn(p, 200, 400)
table.drawOn(p,700, 745)
data=[['Ref. id :', quotation.reference_id]]
table = Table(data, colWidths=[100, 400], rowHeights=40, style = style)
table.wrapOn(p, 200, 400)
table.drawOn(p,700, 715)
# data=[['Sl.No:', 'Description', 'Qty', 'Unit Price', 'Amount(AED)']]
# table = Table(data, colWidths=[100, 350, 100, 125, 125], rowHeights=40, style = style1)
# table.setStyle(TableStyle([
# ('BOX', (0,0), (-1,-1), 0.25, colors.black),
# ('VALIGN',(0,-1),(-1,-1),'MIDDLE'),
# # ('LINEBEFORE',(1,0), (0,-1),1,colors.black),
# ]))
# table.wrapOn(p, 200, 400)
# table.drawOn(p,105,575)
data=[['Sl.No:']]
table = Table(data, colWidths=[100], rowHeights=40, style = style1)
table.setStyle(TableStyle([
('BOX', (0,0), (-1,-1), 0.25, colors.black),
('VALIGN',(0,-1),(-1,-1),'MIDDLE'),
('ALIGN',(0,-1),(-1,-1),'CENTRE'),
]))
table.wrapOn(p, 200, 400)
table.drawOn(p,105,575)
data=[['Description']]
table = Table(data, colWidths=[350], rowHeights=40, style = style1)
table.setStyle(TableStyle([
('BOX', (0,0), (-1,-1), 0.25, colors.black),
('VALIGN',(0,-1),(-1,-1),'MIDDLE'),
('ALIGN',(0,-1),(-1,-1),'CENTRE'),
]))
table.wrapOn(p, 200, 400)
table.drawOn(p,205,575)
data=[['Qty']]
table = Table(data, colWidths=[100], rowHeights=40, style = style1)
table.setStyle(TableStyle([
('BOX', (0,0), (-1,-1), 0.25, colors.black),
('VALIGN',(0,-1),(-1,-1),'MIDDLE'),
('ALIGN',(0,-1),(-1,-1),'CENTRE'),
]))
table.wrapOn(p, 200, 400)
table.drawOn(p,555,575)
data=[['Unit Price']]
table = Table(data, colWidths=[125], rowHeights=40, style = style1)
table.setStyle(TableStyle([
('BOX', (0,0), (-1,-1), 0.25, colors.black),
('VALIGN',(0,-1),(-1,-1),'MIDDLE'),
('ALIGN',(0,-1),(-1,-1),'CENTRE'),
]))
table.wrapOn(p, 200, 400)
table.drawOn(p,655,575)
data=[['Amount(AED)']]
table = Table(data, colWidths=[135], rowHeights=40, style = style1)
table.setStyle(TableStyle([
('BOX', (0,0), (-1,-1), 0.25, colors.black),
('VALIGN',(0,-1),(-1,-1),'MIDDLE'),
('ALIGN',(0,-1),(-1,-1),'CENTRE'),
]))
table.wrapOn(p, 200, 400)
table.drawOn(p,780,575)
y = 575
i = 0
i = i + 1
for q_item in quotation.quotationitem_set.all():
if y <= 135:
p.showPage()
y = 915
y = y-40
# data1=[[i, q_item.item.name, q_item.quantity_sold, q_item.item.inventory_set.all()[0].selling_price, q_item.net_amount]]
# table = Table(data1, colWidths=[100, 350, 100, 125, 125], rowHeights=40, style = style)
# table.setStyle(TableStyle([
# # ('INNERGRID', (0,0), (0,0), 0.25, colors.black),
# # ('INNERGRID', (0,1), (-1,-1), 0.25, colors.black),
# ('BOX', (0,0), (-1,-1), 0.25, colors.black),
# ('VALIGN',(0,-1),(-1,-1),'MIDDLE'),
# # ('ALIGN', (0,0), (-1,-1),'RIGHT'),
# # ('SPACEBELOW', (0,0), (-1,-1), 10),
# # ('BACKGROUND',(0,0),(1,0),colors.lightgrey)
# ]))
# # table.wrapOn(p, 300, 200)
# table.wrapOn(p, 200, 400)
# # table.drawOn(p,105,460)
# table.drawOn(p,105, x)
data1=[[i]]
table = Table(data1, colWidths=[100], rowHeights=40, style = style)
table.setStyle(TableStyle([
# ('INNERGRID', (0,1), (-1,-1), 0.25, colors.black),
('BOX', (0,0), (-1,-1), 0.25, colors.black),
('VALIGN',(0,-1),(-1,-1),'MIDDLE'),
('ALIGN', (0,0), (-1,-1),'CENTRE'),
]))
# table.wrapOn(p, 300, 200)
table.wrapOn(p, 200, 400)
# table.drawOn(p,105,460)
table.drawOn(p,105, y)
data1=[[q_item.item.name]]
table = Table(data1, colWidths=[350], rowHeights=40, style = style)
table.setStyle(TableStyle([
# ('INNERGRID', (0,1), (-1,-1), 0.25, colors.black),
('BOX', (0,0), (-1,-1), 0.25, colors.black),
('VALIGN',(0,-1),(-1,-1),'MIDDLE'),
]))
# table.wrapOn(p, 300, 200)
table.wrapOn(p, 200, 400)
# table.drawOn(p,105,460)
table.drawOn(p,205, y)
data1=[[q_item.quantity_sold]]
table = Table(data1, colWidths=[100], rowHeights=40, style = style)
table.setStyle(TableStyle([
# ('INNERGRID', (0,1), (-1,-1), 0.25, colors.black),
('BOX', (0,0), (-1,-1), 0.25, colors.black),
('VALIGN',(0,-1),(-1,-1),'MIDDLE'),
('ALIGN', (0,0), (-1,-1),'CENTRE'),
]))
# table.wrapOn(p, 300, 200)
table.wrapOn(p, 200, 400)
# table.drawOn(p,105,460)
table.drawOn(p,555, y)
data1=[[q_item.selling_price]]
table = Table(data1, colWidths=[125], rowHeights=40, style = style)
table.setStyle(TableStyle([
# ('INNERGRID', (0,1), (-1,-1), 0.25, colors.black),
('BOX', (0,0), (-1,-1), 0.25, colors.black),
('VALIGN',(0,-1),(-1,-1),'MIDDLE'),
('ALIGN', (0,0), (-1,-1),'RIGHT'),
]))
# table.wrapOn(p, 300, 200)
table.wrapOn(p, 200, 400)
# table.drawOn(p,105,460)
table.drawOn(p,655, y)
data1=[[q_item.net_amount]]
table = Table(data1, colWidths=[135], rowHeights=40, style = style)
table.setStyle(TableStyle([
# ('INNERGRID', (0,1), (-1,-1), 0.25, colors.black),
('BOX', (0,0), (-1,-1), 0.25, colors.black),
('VALIGN',(0,-1),(-1,-1),'MIDDLE'),
('ALIGN', (0,0), (-1,-1),'RIGHT'),
]))
# table.wrapOn(p, 300, 200)
table.wrapOn(p, 200, 400)
# table.drawOn(p,105,460)
table.drawOn(p,780, y)
i = i + 1
data=[['', quotation.net_total]]
table = Table(data, colWidths=[650, 160], rowHeights=40, style = style)
table.setStyle(TableStyle([
# ('INNERGRID', (0,1), (-1,-1), 0.25, colors.black),
('BOX', (0,0), (-1,-1), 0.25, colors.black),
('VALIGN',(0,-1),(-1,-1),'MIDDLE'),
('ALIGN', (0,0), (-1,-1),'RIGHT'),
]))
table.wrapOn(p, 200, 400)
table.drawOn(p,105,y-40)
p.setFont("Helvetica", 15)
if y < 270:
p.showPage()
y = 1000
p.drawString(110, y-100, "Hope the above quoted prices will meet your satisfaction and for further information please do not hesitate to contact us.")
p.drawString(110, y-140, "Delivery : " + str(quotation.delivery))
p.drawString(110, y-160, "Proof : " + str(quotation.proof))
p.drawString(110, y-180, "Payment : " + str(quotation.payment))
p.drawString(110, y-200, "Validity : " + str(quotation.validity))
p.drawString(110, y-220, "For")
p.drawString(110, y-240, "Sunlight Stationary")
p.drawString(110, y-260, "Authorized Signatory")
p.drawString(700, y-260, "Prepared By")
# if x >= 270:
# p.drawString(110, 150, "For")
# p.drawString(110, 130, "Sunlight Stationary")
# p.drawString(110, 70, "Authorized Signatory")
# p.drawString(700, 70, "Prepared By")
# else:
#
# data=[['Tel: +971-2-6763571, Fax : +971-2-6763581,P.O.Box : 48296, Abu Dhabi, United Arab Emirates']]
# table = Table(data, colWidths=[700], rowHeights=30)
# table.setStyle(TableStyle([
# # ('BOX', (0,0), (-1,-1), 0.25, colors.black),
# ('ALIGN',(0,0), (-1,-1),'CENTRE'),
# ]))
# table.wrapOn(p, 200, 400)
# table.drawOn(p,160, 50)
p.showPage()
p.save()
return response
class CreateDeliveryNote(View):
def get(self, request, *args, **kwargs):
current_date = dt.datetime.now().date()
ref_number = DeliveryNote.objects.aggregate(Max('id'))['id__max']
if not ref_number:
ref_number = 1
prefix = 'DN'
else:
ref_number = ref_number + 1
prefix = DeliveryNote.objects.latest('id').prefix
delivery_no = prefix + str(ref_number)
context = {
'current_date': current_date.strftime('%d-%m-%Y'),
'delivery_no': delivery_no,
}
return render(request, 'sales/create_delivery_note.html', context)
def post(self, request, *args, **kwargs):
if request.is_ajax():
quotation_details = ast.literal_eval(request.POST['quotation'])
delivery_note_details = ast.literal_eval(request.POST['delivery_note'])
quotation = Quotation.objects.get(reference_id=delivery_note_details['quotation_no'])
for q_item in quotation.quotationitem_set.all():
quotation_item_names = []
for item_data in quotation_details['sales_items']:
quotation_item_names.append(item_data['item_name'])
if q_item.item.name not in quotation_item_names:
item = q_item.item
inventory, created = Inventory.objects.get_or_create(item=item)
inventory.quantity = inventory.quantity + int(q_item.quantity_sold)
inventory.save()
q_item.delete()
else:
for item_data in quotation_details['sales_items']:
if q_item.item.code == item_data['item_code']:
if q_item.quantity_sold != int(item_data['qty_sold']):
item = q_item.item
inventory, created = Inventory.objects.get_or_create(item=item)
inventory.quantity = inventory.quantity + int(q_item.quantity_sold)
inventory.save()
inventory.quantity = inventory.quantity - int(item_data['qty_sold'])
inventory.save()
q_item.quantity_sold = int(item_data['qty_sold'])
q_item.save()
if q_item.discount != float(item_data['disc_given']):
q_item.discount = item_data['disc_given']
q_item.save()
if q_item.net_amount != float(item_data['net_amount']):
q_item.net_amount = item_data['net_amount']
q_item.save()
if quotation.net_total != float(quotation_details['net_total']):
quotation.net_total = quotation_details['net_total']
quotation.save()
delivery_note, created = DeliveryNote.objects.get_or_create(quotation=quotation)
quotation.processed = True
quotation.save()
delivery_note.quotation = quotation
delivery_note.customer = quotation.to
delivery_note.date = datetime.strptime(delivery_note_details['date'], '%d-%m-%Y')
delivery_note.lpo_number = delivery_note_details['lpo_no']
delivery_note.delivery_note_number = delivery_note_details['delivery_note_no']
delivery_note.save()
res = {
'result': 'ok',
'delivery_note_id': delivery_note.id
}
response = simplejson.dumps(res)
return HttpResponse(response, status=200, mimetype='application/json')
class QuotationDetails(View):
def get(self, request, *args, **kwargs):
in_sales_invoice_creation = ''
sales_invoice_creation = request.GET.get('sales_invoice', '')
ref_number = request.GET.get('reference_no', '')
if sales_invoice_creation == 'true':
quotations = Quotation.objects.filter(reference_id__istartswith=ref_number, is_sales_invoice_created=False)
else:
quotations = Quotation.objects.filter(reference_id__istartswith=ref_number, processed=False, is_sales_invoice_created=False)
quotation_list = []
for quotation in quotations:
item_list = []
i = 0
i = i + 1
if quotation.deliverynote_set.all().count() > 0:
delivery_note = quotation.deliverynote_set.all()[0]
for q_item in delivery_note.deliverynoteitem_set.all():
item_list.append({
'sl_no': i,
'item_name': q_item.item.name,
'item_code': q_item.item.code,
'barcode': q_item.item.barcode if q_item.item.barcode else '',
'item_description': str(q_item.item.description),
'qty_sold': q_item.quantity_sold,
'tax': q_item.item.tax if q_item.item.tax else '',
'uom': q_item.item.uom.uom if q_item.item.uom else '',
'current_stock': q_item.item.inventory_set.all()[0].quantity if q_item.item.inventory_set.count() > 0 else 0 ,
'selling_price': q_item.item.inventory_set.all()[0].selling_price if q_item.item.inventory_set.count() > 0 else 0 ,
'discount_permit': q_item.item.inventory_set.all()[0].discount_permit_percentage if q_item.item.inventory_set.count() > 0 else 0,
'net_amount': q_item.net_amount,
'discount_given': q_item.discount,
})
i = i + 1
if quotation.quotationitem_set.all().count() > 0:
for q_item in quotation.quotationitem_set.all():
item_list.append({
'sl_no': i,
'item_name': q_item.item.name,
'item_code': q_item.item.code,
'barcode': q_item.item.barcode if q_item.item.barcode else '',
'item_description': str(q_item.item.description),
'qty_sold': q_item.quantity_sold,
'tax': q_item.item.tax if q_item.item.tax else '',
'uom': q_item.item.uom.uom if q_item.item.uom else '',
'current_stock': q_item.item.inventory_set.all()[0].quantity if q_item.item.inventory_set.count() > 0 else 0 ,
'selling_price': q_item.item.inventory_set.all()[0].selling_price if q_item.item.inventory_set.count() > 0 else 0 ,
'discount_permit': q_item.item.inventory_set.all()[0].discount_permit_percentage if q_item.item.inventory_set.count() > 0 else 0,
'net_amount': q_item.net_amount,
'discount_given': q_item.discount,
})
i = i + 1
quotation_list.append({
'date': quotation.date.strftime('%d/%m/%Y') if quotation.date else '',
'delivery': quotation.delivery,
'proof': quotation.proof,
'payment': quotation.payment,
'attention': quotation.attention,
'subject': quotation.subject,
'validity': quotation.validity,
'ref_no': quotation.reference_id,
'customer': quotation.to.customer_name if quotation.to else '' ,
'items': item_list,
'net_total': quotation.net_total,
'delivery_no': quotation.deliverynote_set.all()[0].delivery_note_number if quotation.deliverynote_set.all().count() > 0 else 0,
'lpo_number': quotation.deliverynote_set.all()[0].lpo_number if quotation.deliverynote_set.all().count() > 0 else '',
})
res = {
'quotations': quotation_list,
'result': 'ok',
}
response = simplejson.dumps(res)
return HttpResponse(response, status=200, mimetype='application/json')
class DeliveryNoteDetails(View):
def get(self, request, *args, **kwargs):
delivery_no = request.GET.get('delivery_no', '')
delivery_notes = DeliveryNote.objects.all()
delivery_note_details = DeliveryNote.objects.filter(delivery_note_number__istartswith=delivery_no, is_pending=True)
delivery_note_list = []
whole_delivery_note_details = []
net_total = 0
for delivery_note in delivery_note_details:
i = 0
i = i + 1
item_list = []
if delivery_note.deliverynoteitem_set.all().count() > 0:
for delivery_note_item in delivery_note.deliverynoteitem_set.all():
item_list.append({
'sl_no': i,
'id': delivery_note_item.item.id,
'item_name': delivery_note_item.item.name,
'item_code': delivery_note_item.item.code,
'barcode': delivery_note_item.item.barcode if delivery_note_item.item.barcode else '',
'item_description': str(delivery_note_item.item.description),
'qty_sold': delivery_note_item.quantity_sold,
'sold_qty': delivery_note_item.quantity_sold,
'tax': delivery_note_item.item.tax if delivery_note_item.item.tax else '',
'uom': delivery_note_item.item.uom.uom if delivery_note_item.item.uom else '',
'current_stock': delivery_note_item.total_quantity if delivery_note_item.item else 0 ,
'selling_price': delivery_note_item.selling_price if delivery_note_item.selling_price else delivery_note_item.item.selling_price ,
'discount_permit': delivery_note_item.item.discount_permit_percentage if delivery_note_item.item else 0,
'net_amount': delivery_note_item.net_amount,
'discount_given': delivery_note_item.discount,
'remaining_qty': int(delivery_note_item.total_quantity - delivery_note_item.quantity_sold) if delivery_note_item else 0,
'dis_amt': 0,
'dis_percentage': 0,
})
i = i + 1
delivery_note_list.append({
'salesman': delivery_note.salesman.first_name if delivery_note.salesman else '' ,
'items': item_list,
'net_total': delivery_note.net_total if delivery_note.net_total else '' ,
'delivery_no': delivery_note.delivery_note_number,
'lpo_number': delivery_note.lpo_number if delivery_note.lpo_number else '',
'date': delivery_note.date.strftime('%d/%m/%Y') if delivery_note.date else '',
})
for delivery_note in delivery_note_details:
i = 0
i = i + 1
item_list = []
if delivery_note.deliverynoteitem_set.all().count() > 0:
for delivery_note_item in delivery_note.deliverynoteitem_set.all():
item_list.append({
'sl_no': i,
'id': delivery_note_item.item.id,
'item_name': delivery_note_item.item.name,
'item_code': delivery_note_item.item.code,
'barcode': delivery_note_item.item.barcode if delivery_note_item.item.barcode else '',
'item_description': str(delivery_note_item.item.description),
'qty_sold': 0,
'sold_qty': delivery_note_item.quantity_sold,
'tax': delivery_note_item.item.tax if delivery_note_item.item.tax else '',
'uom': delivery_note_item.item.uom.uom if delivery_note_item.item.uom else '',
'current_stock': delivery_note_item.item.quantity if delivery_note_item.item else 0 ,
'selling_price': delivery_note_item.selling_price if delivery_note_item.selling_price else delivery_note_item.item.selling_price ,
'discount_permit': delivery_note_item.item.discount_permit_percentage if delivery_note_item.item else 0,
'net_amount': delivery_note_item.net_amount,
'discount_given': delivery_note_item.discount,
'total_qty': delivery_note_item.total_quantity,
'remaining_qty': int(delivery_note_item.total_quantity - delivery_note_item.quantity_sold) if delivery_note_item else 0,
'dis_amt': 0,
'dis_percentage': 0,
})
i = i + 1
whole_delivery_note_details.append({
'salesman': delivery_note.salesman.first_name if delivery_note.salesman else '' ,
'items': item_list,
'net_total': delivery_note.net_total if delivery_note.net_total else '' ,
'delivery_no': delivery_note.delivery_note_number,
'lpo_number': delivery_note.lpo_number if delivery_note.lpo_number else '',
'date': delivery_note.date.strftime('%d/%m/%Y') if delivery_note.date else '',
'id': delivery_note.id,
})
res = {
'delivery_notes': delivery_note_list,
'whole_delivery_note_details': whole_delivery_note_details,
'result': 'ok',
}
response = simplejson.dumps(res)
return HttpResponse(response, status=200, mimetype='application/json')
class QuotationDeliverynoteSales(View):
def get(self, request, *args, **kwargs):
inv_number = Sales.objects.aggregate(Max('id'))['id__max']
if not inv_number:
inv_number = 1
else:
inv_number = inv_number + 1
invoice_number = 'INV' + str(inv_number)
return render(request, 'sales/QNDN_sales_entry.html',{
'sales_invoice_number': invoice_number,
})
def post(self, request, *args, **kwargs):
sales_dict = ast.literal_eval(request.POST['sales'])
# delivery_note = DeliveryNote.objects.get(delivery_note_number=sales_dict['delivery_no'])
sales = Sales.objects.create(sales_invoice_number=sales_dict['sales_invoice_number'])
sales.sales_invoice_number = sales_dict['sales_invoice_number']
sales.sales_invoice_date = datetime.strptime(sales_dict['sales_invoice_date'], '%d/%m/%Y')
customer = Customer.objects.get(customer_name = sales_dict['customer'])
sales.customer = customer
sales.save()
not_completed_selling = []
sales.lpo_number = sales_dict['lpo_number']
sales.save()
salesman = User.objects.get(first_name=sales_dict['salesman'])
sales.discount = sales_dict['net_discount']
sales.round_off = sales_dict['roundoff']
sales.net_amount = sales_dict['net_total']
sales.grant_total = sales_dict['grant_total']
sales.salesman = salesman
sales.discount_for_sale = sales_dict['discount_sale']
sales.discount_percentage_for_sale = sales_dict['discount_sale_percentage']
sales.payment_mode = sales_dict['payment_mode']
sales.paid = sales_dict['paid']
sales.balance = sales_dict['balance']
if sales_dict['payment_mode'] == 'cheque':
sales.bank_name = sales_dict['bank_name']
sales.save()
if sales_dict['payment_mode'] == 'credit':
customer_account, created = CustomerAccount.objects.get_or_create(customer=customer, invoice_no=sales )
if created:
customer_account.total_amount = sales_dict['grant_total']
customer_account.paid = sales_dict['paid']
customer_account.balance = sales_dict['balance']
customer_account.save()
sales_items = sales_dict['sales_items']
for sales_item in sales_items:
delivery_note_items = DeliveryNoteItem.objects.filter(item__code=sales_item['item_code'], is_completed=False, delivery_note__salesman=salesman).order_by('id')
remaining_qty = 0
d_item_remaining_qty = 0
remaining_qty = int(sales_item['qty'])
for d_item in delivery_note_items:
sold_qty = 0
if remaining_qty > 0:
d_item_remaining_qty = int(d_item.total_quantity) - int(d_item.quantity_sold)
if int(d_item_remaining_qty) > int(remaining_qty):
d_item.quantity_sold = d_item.quantity_sold + int(remaining_qty)
sold_qty = remaining_qty
remaining_qty = 0
d_item.save()
else:
d_item.quantity_sold = int(d_item.quantity_sold) + int(d_item_remaining_qty)
sold_qty = d_item_remaining_qty
remaining_qty = int(remaining_qty) - int(d_item_remaining_qty)
d_item.save()
s_item, item_created = SalesItem.objects.get_or_create(delivery_note_item=d_item, sales=sales)
s_item.sales = sales
s_item.quantity_sold = sold_qty
s_item.discount_amount = sales_item['dis_amt']
s_item.discount_percentage = sales_item['dis_percentage']
s_item.net_amount = float(sold_qty) * float(sales_item['unit_price'])
s_item.selling_price = sales_item['unit_price']
# unit price is actually the selling price
s_item.save()
not_completed_selling = []
for sales_item in sales.salesitem_set.all():
delivery_note = sales_item.delivery_note_item.delivery_note
for delivery_item in delivery_note.deliverynoteitem_set.all():
if int(delivery_item.total_quantity) != int(delivery_item.quantity_sold):
not_completed_selling.append(delivery_item.id)
d_item.is_completed = False
else:
d_item.is_completed = True
d_item.save()
if len(not_completed_selling) == 0:
delivery_note.is_pending = False
else:
delivery_note.is_pending = True
delivery_note.save()
not_completed_selling = []
res = {
'result': 'Ok',
}
response = simplejson.dumps(res)
status_code = 200
return HttpResponse(response, status = status_code, mimetype="application/json")
class CreateSalesInvoicePDF(View):
def get(self, request, *args, **kwargs):
sales_invoice_id = kwargs['sales_invoice_id']
sales_invoice = Sales.objects.get(id=sales_invoice_id)
sales = sales_invoice
response = HttpResponse(content_type='application/pdf')
p = canvas.Canvas(response, pagesize=(1000, 1200))
status_code = 200
y = 1100
style = [
('FONTSIZE', (0,0), (-1, -1), 20),
('FONTNAME',(0,0),(-1,-1),'Helvetica')
]
new_style = [
('FONTSIZE', (0,0), (-1, -1), 30),
('FONTNAME',(0,0),(-1,-1),'Helvetica')
]
para_style = ParagraphStyle('fancy')
para_style.fontSize = 20
para_style.fontName = 'Helvetica'
para = Paragraph('<b> INVOICE </b>', para_style)
data =[['', sales_invoice.date.strftime('%d-%m-%Y'), para , sales_invoice.invoice_no]]
table = Table(data, colWidths=[30, 360, 420, 100], rowHeights=50, style=style)
# table.setStyle(TableStyle([
# ('FONTSIZE', (2,0), (2,0), 30),
# ]))
table.wrapOn(p, 200, 400)
table.drawOn(p,50, 975)
quotation = sales_invoice.quotation
customer_name = ''
if sales_invoice.customer:
customer_name = sales_invoice.customer.customer_name
data=[['', customer_name, sales_invoice.sales.lpo_number if sales_invoice.sales else '' ]]
table = Table(data, colWidths=[30, 540, 60], rowHeights=30, style = style)
table.wrapOn(p, 200, 400)
table.drawOn(p, 50, 935)
data=[['', '', sales_invoice.date.strftime('%d-%m-%Y')]]
table = Table(data, colWidths=[450, 120, 70], rowHeights=50, style = style)
table.wrapOn(p, 200, 400)
table.drawOn(p,50, 910)
if sales_invoice.quotation or sales_invoice.delivery_note:
data=[['', '', sales_invoice.delivery_note.delivery_note_number if sales_invoice.delivery_note else sales_invoice.quotation.reference_id]]
table = Table(data, colWidths=[450, 120, 70], rowHeights=40, style = style)
table.wrapOn(p, 200, 400)
table.drawOn(p,50, 880)
y = 790
i = 0
i = i + 1
TWOPLACES = Decimal(10) ** -2
total_amount = 0
for s_item in sales.salesitem_set.all():
y = y-30
if y <= 270:
y = 790
p.showPage()
item_price = s_item.selling_price
total_amount = total_amount + (item_price*s_item.quantity_sold)
data1=[[i, s_item.item.code, s_item.item.name, s_item.quantity_sold, s_item.item.uom.uom, s_item.selling_price.quantize(TWOPLACES), s_item.net_amount]]
table = Table(data1, colWidths=[50, 100, 440, 80, 90, 100, 50], rowHeights=40, style=style)
table.wrapOn(p, 200, 400)
table.drawOn(p,10,y)
i = i + 1
y = 600
if y <= 270:
y = 800
p.showPage()
total_amount = sales.net_amount
try:
total_amount = total_amount.quantize(TWOPLACES)
except:
total_amount = total_amount
total_amount_in_words = num2words(total_amount).title() + ' Only'
data=[[total_amount_in_words, total_amount]]
table = Table(data, colWidths=[700, 50], rowHeights=40, style = style)
table.wrapOn(p, 200, 100)
table.drawOn(p, 200, 10)
p.showPage()
p.save()
return response
class ReceiptVoucherCreation(View):
def get(self, request, *args, **kwargs):
voucher_no = ReceiptVoucher.objects.aggregate(Max('id'))['id__max']
if not voucher_no:
voucher_no = 1
else:
voucher_no = voucher_no + 1
voucher_no = 'RV' + str(voucher_no)
return render(request, 'sales/create_receipt_voucher.html',{
'voucher_no': voucher_no,
})
def post(self, request, *args, **kwargs):
if request.is_ajax():
receiptvoucher = ast.literal_eval(request.POST['receiptvoucher'])
customer = Customer.objects.get(customer_name=receiptvoucher['customer'])
sales_invoice_obj = Sales.objects.get(sales_invoice_number=receiptvoucher['invoice_no'])
receipt_voucher = ReceiptVoucher.objects.create(sales_invoice=sales_invoice_obj)
receipt_voucher.date = datetime.strptime(receiptvoucher['date'], '%d/%m/%Y')
receipt_voucher.total_amount = receiptvoucher['amount']
receipt_voucher.paid_amount = receiptvoucher['paid_amount']
receipt_voucher.receipt_voucher_no = receiptvoucher['voucher_no']
receipt_voucher.payment_mode = receiptvoucher['payment_mode']
receipt_voucher.bank = receiptvoucher['bank_name']
receipt_voucher.cheque_no = receiptvoucher['cheque_no']
if receiptvoucher['cheque_date']:
receipt_voucher.dated = datetime.strptime(receiptvoucher['cheque_date'], '%d/%m/%Y')
receipt_voucher.save()
customer_account, created = CustomerAccount.objects.get_or_create(customer=customer, invoice_no=sales_invoice_obj )
if created:
customer_account.total_amount = receiptvoucher['amount']
customer_account.paid = receiptvoucher['paid_amount']
else:
customer_account.total_amount = receiptvoucher['amount']
customer_account.paid = float(customer_account.paid) + float(receiptvoucher['paid_amount'])
customer_account.save()
customer_account.balance = float(customer_account.total_amount) - float(customer_account.paid)
customer_account.save()
sales_invoice_obj.balance = customer_account.balance
sales_invoice_obj.save()
if customer_account.balance == 0:
customer_account.is_complted = True
customer_account.save()
sales_invoice_obj.is_processed = True
sales_invoice_obj.save()
res = {
'result': 'OK',
'receiptvoucher_id': receipt_voucher.id,
}
response = simplejson.dumps(res)
return HttpResponse(response, status=200, mimetype='application/json')
class InvoiceDetails(View):
def get(self, request, *args, **kwargs):
invoice_no = request.GET.get('invoice_no', '')
sales_invoice_details = Sales.objects.filter(sales_invoice_number__istartswith=invoice_no, is_processed=False, payment_mode='credit')
invoices = Sales.objects.filter(sales_invoice_number__istartswith=invoice_no, is_processed=False)
ctx_invoice_details = []
ctx_sales_invoices = []
ctx_sales_item = []
if sales_invoice_details.count() > 0:
for sales_invoice in sales_invoice_details:
customer = sales_invoice.customer
customer_account, created = CustomerAccount.objects.get_or_create(customer=customer, invoice_no=sales_invoice)
ctx_invoice_details.append({
'invoice_no': sales_invoice.sales_invoice_number if sales_invoice.sales_invoice_number else '',
'dated': sales_invoice.sales_invoice_date.strftime('%d-%m-%Y') if sales_invoice.sales_invoice_date else '',
'customer': sales_invoice.customer.customer_name if sales_invoice.customer else '',
'amount': sales_invoice.grant_total if sales_invoice else '',
'paid_amount': customer_account.paid if customer_account.paid else 0,
})
i = 0
i = i + 1
if invoices.count() > 0:
for sales_invoice in invoices:
net_amount = 0
quantity_sold = 0
selling_price = 0
discount = 0
total_quantity = 0
quantity = 0
# delivery_note = sales_invoice.delivery_note
ct_item_ids = []
ctx_item_list = []
for sale in sales_invoice.salesitem_set.all():
if sale.delivery_note_item.item.id not in ctx_item_list:
ctx_item_list.append(sale.delivery_note_item.item.id)
ctx_item_id_list = []
for item_data in ctx_item_list:
item = InventoryItem.objects.get(id=item_data)
sale_items = SalesItem.objects.filter(sales=sales_invoice, delivery_note_item__item=item)
for sale in sale_items:
net_amount = float(net_amount) + float(sale.net_amount)
delivery_notes = DeliveryNoteItem.objects.filter(item=item, is_completed=False, delivery_note__salesman=sales_invoice.salesman)
if delivery_notes.count() > 0:
for delivery_note_item in delivery_notes:
quantity_sold = int(delivery_note_item.quantity_sold) + int(quantity_sold)
quantity = int(quantity) + int(delivery_note_item.item.quantity)
total_quantity = int(total_quantity) + int(delivery_note_item.total_quantity)
if delivery_notes.count() > 0:
selling_price = delivery_notes[::-1][0].selling_price if delivery_notes[::-1][0].selling_price else item.selling_price
discount = delivery_notes[::-1][0].discount if delivery_notes[::-1][0].discount else 0
ctx_sales_item.append({
'sl_no': i,
'id': item.id,
'item_name': item.name + ' - ' + str(int(total_quantity - quantity_sold)),
'item_code': item.code,
'barcode': item.barcode,
'qty_sold': quantity_sold,
'sold_qty': quantity_sold,
'current_stock': quantity,
'selling_price': selling_price,
'discount_permit': item.discount_permit_percentage if item else 0,
'qty': 0,
'net_amount': net_amount,
'discount_given': discount,
'total_qty': total_quantity,
'remaining_qty': int(total_quantity - quantity_sold),
'discount': sale_items[::-1][0].discount_amount,
'dis_percentage': sale_items[::-1][0].discount_percentage,
'code_of_item': item.code,
})
i = i + 1
net_amount = 0
net_amount = 0
quantity_sold = 0
selling_price = 0
discount = 0
total_quantity = 0
quantity = 0
else:
print "else"
total_quantity = 0
quantity_sold = 0
delivery_notes = DeliveryNoteItem.objects.filter(item=item, is_completed=True, delivery_note__salesman=sales_invoice.salesman)
selling_price = delivery_notes[::-1][0].selling_price if delivery_notes[::-1][0].selling_price else item.selling_price
discount = delivery_notes[::-1][0].discount if delivery_notes[::-1][0].discount else 0
sold_qty = 0
for delivery_note_item in delivery_notes:
quantity_sold = int(delivery_note_item.quantity_sold) + int(quantity_sold)
quantity = int(quantity) + int(delivery_note_item.item.quantity)
total_quantity = int(delivery_note_item.total_quantity) + int(total_quantity)
ctx_sales_item.append({
'sl_no': i,
'id': item.id,
'item_name': item.name + ' - ' + str(int(total_quantity - quantity_sold)),
'item_code': item.code,
'barcode': item.barcode,
'qty_sold': quantity_sold,
'sold_qty': quantity_sold,
'current_stock': total_quantity,
'selling_price': selling_price,
'discount_permit': item.discount_permit_percentage if item else 0,
'qty': 0,
'net_amount': net_amount,
'discount_given': discount,
'total_qty': total_quantity,
'remaining_qty': int(total_quantity - quantity_sold),
'discount': sale_items[::-1][0].discount_amount,
'dis_percentage': sale_items[::-1][0].discount_percentage,
'code_of_item': item.code,
})
i = i + 1
ctx_sales_invoices.append({
'invoice_no': sales_invoice.sales_invoice_number,
'date': sales_invoice.sales_invoice_date.strftime('%d/%m/%Y') if sales_invoice.sales_invoice_date else '',
'customer': sales_invoice.customer.customer_name if sales_invoice.customer else '',
'lpo_number': sales_invoice.lpo_number if sales_invoice else '',
'items': ctx_sales_item,
'salesman': sales_invoice.salesman.first_name if sales_invoice.salesman else '',
'payment_mode': sales_invoice.payment_mode,
'card_number': sales_invoice.card_number,
'bank_name': sales_invoice.bank_name,
'net_total': sales_invoice.net_amount,
'round_off': sales_invoice.round_off if sales_invoice.round_off else 0,
'grant_total': sales_invoice.grant_total,
'discount': sales_invoice.discount if sales_invoice.discount else 0,
'id': sales_invoice.id,
'balance': sales_invoice.balance,
'paid': sales_invoice.paid,
'discount_sale': sales_invoice.discount_for_sale,
'discount_sale_percentage': sales_invoice.discount_percentage_for_sale,
})
ctx_sales_item = []
res = {
'result': 'ok',
'invoice_details': ctx_invoice_details,
'sales_invoices': ctx_sales_invoices,
}
response = simplejson.dumps(res)
return HttpResponse(response, status=200, mimetype='application/json')
class PrintReceiptVoucher(View):
def get(self, request, *args, **kwargs):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'filename=ReceiptVoucher.pdf'
p = canvas.Canvas(response, pagesize=(1000, 1000))
status_code = 200
y = 850
receipt_voucher = ReceiptVoucher.objects.get(id=kwargs['receipt_voucher_id'])
p.setFont("Helvetica-Bold", 15)
p.drawString(30, 950, "SUNLIGHT STATIONARY")
p.setFont("Helvetica", 10)
p.drawString(30, 930, "P.O.Box : 48296")
p.drawString(30, 910, "Behind Russian Embassy")
p.drawString(30, 890, "Ziyani, Abu Dhabi, U.A.E.")
p.drawString(30, 870, "Tel. : +971-2-6763571")
p.drawString(30, 850, "Fax : +971-2-6763581")
p.drawString(30, 830, "E-mail : [email protected]")
try:
owner_company = OwnerCompany.objects.latest('id')
if owner_company.logo:
path = settings.PROJECT_ROOT.replace("\\", "/")+"/media/"+owner_company.logo.name
p.drawImage(path, 400, 810, width=20*cm, preserveAspectRatio=True)
except:
pass
p.line(30,790,970,790)
p.setFont("Helvetica", 20)
p.drawString(440, 740, "Receipt Voucher")
p.drawString(840, 740, 'No.')
p.setFont("Helvetica", 15)
p.drawString(880, 740, str(receipt_voucher.receipt_voucher_no))
p.setFont("Times-BoldItalic", 15)
p.drawString(30, 700, "Amount")
data=[[receipt_voucher.sum_of,'']]
table = Table(data, colWidths=[150,50], rowHeights=30)
table.setStyle(TableStyle([
('BOX', (0,0), (-1,-1), 0.25, colors.black),
('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
('FONTSIZE', (0,0), (-1, -1), 14),
('FONTNAME', (0,0), (-1,-1), 'Times-BoldItalic')
]))
table.wrapOn(p, 200, 400)
table.drawOn(p,120, 700)
p.drawString(840, 700, "Date")
p.drawString(880, 705, receipt_voucher.date.strftime('%d/%m/%Y'))
p.drawString(870, 700, "........................")
p.drawString(30, 660, "Received from Mr./M/s.")
p.drawString(210, 665,receipt_voucher.customer.customer_name)
p.drawString(180, 660, "...............................................................................................................................................................................................................")
p.drawString(30, 620, "The Sum of")
p.drawString(150, 625,str(receipt_voucher.sum_of))
p.drawString(110, 620, "..................................................................................................................................................................................................................................")
p.drawString(30, 580, "On Settlement of")
p.drawString(180, 585,str(receipt_voucher.sales_invoice.invoice_no))
p.drawString(140, 580, "..........................................................................................................................................................................................................................")
p.drawString(30, 540, "Cheque No")
if receipt_voucher.cheque_no:
p.drawString(110, 545,receipt_voucher.cheque_no)
p.drawString(100, 540, " ..........................................................................................")
p.drawString(450, 540, "Cash")
if receipt_voucher.sum_of:
p.drawString(500, 545,str(receipt_voucher.sum_of))
p.drawString(490, 540, ".............................................................................................................................")
p.drawString(30, 500, "Bank")
if receipt_voucher.bank:
p.drawString(75, 505, receipt_voucher.bank)
p.drawString(65, 500, " ...................................................................................................")
p.drawString(450, 500, "Dated")
if receipt_voucher.dated:
p.drawString(500, 505,receipt_voucher.dated.strftime('%d/%m/%Y'))
p.drawString(490, 500, " ............................................................................................................................")
p.drawString(30, 420, "Accountant")
p.drawString(100, 420, " .....................................................")
p.drawString(650, 420, "Receiver's Sign")
p.drawString(750, 420, " ......................................................")
p.showPage()
p.save()
return response
class LatestSalesDetails(View):
def get(self, request, *args, **kwargs):
customer_name = request.GET.get('customer', '')
item_name = request.GET.get('item_name', '')
sales_details = (SalesItem.objects.filter(item__name=item_name, sales__customer__customer_name=customer_name).order_by('-id'))[:3]
ctx_sales_details = []
for sale_item in sales_details:
ctx_sales_details.append({
'selling_price': sale_item.selling_price,
'discount_given': sale_item.discount_given,
'qty_sold': sale_item.quantity_sold,
'date': sale_item.sales.sales_invoice_date.strftime('%d/%m/%Y'),
})
res = {
'result': 'ok',
'latest_sales_details': ctx_sales_details
}
response = simplejson.dumps(res)
return HttpResponse(response, status=200, mimetype='application/json')
class DirectDeliveryNote(View):
def get(self, request, *args, **kwargs):
ref_number = DeliveryNote.objects.aggregate(Max('id'))['id__max']
if not ref_number:
ref_number = 1
else:
ref_number = ref_number + 1
delivery_no = 'DN' + str(ref_number)
context = {
'delivery_no': delivery_no,
}
return render(request, 'sales/direct_delivery_note.html', context)
def post(self, request, *args, **kwargs):
if request.is_ajax():
delivery_note_details = ast.literal_eval(request.POST['delivery_note'])
salesman = User.objects.get(first_name=delivery_note_details['salesman'])
delivery_note = DeliveryNote.objects.create(salesman=salesman)
delivery_note.date = datetime.strptime(delivery_note_details['date'], '%d/%m/%Y')
delivery_note.lpo_number = delivery_note_details['lpo_no']
delivery_note.delivery_note_number = delivery_note_details['delivery_note_no']
delivery_note.net_total = delivery_note_details['net_total']
delivery_note.save()
delivery_note_data_items = delivery_note_details['sales_items']
for delivery_note_item in delivery_note_data_items:
item, created = InventoryItem.objects.get_or_create(code=delivery_note_item['item_code'])
delivery_note_item_obj, item_created = DeliveryNoteItem.objects.get_or_create(item=item, delivery_note=delivery_note)
item.quantity = item.quantity - int(delivery_note_item['qty_sold'])
item.save()
delivery_note_item_obj.net_amount = float(delivery_note_item['net_amount'])
delivery_note_item_obj.total_quantity = int(delivery_note_item['qty_sold'])
delivery_note_item_obj.selling_price = float(delivery_note_item['unit_price'])
delivery_note_item_obj.save()
res = {
'result': 'ok',
}
response = simplejson.dumps(res)
return HttpResponse(response, status=200, mimetype='application/json')
class EditSalesInvoice(View):
def get(self, request, *args, **kwargs):
return render(request, 'sales/edit_sales_invoice.html', {})
def post(self, request, *args, **kwargs):
sales_invoice_details = ast.literal_eval(request.POST['invoice'])
sales = Sales.objects.get(id = sales_invoice_details['id'])
customer = sales.customer
salesman = sales.salesman
if sales.net_amount != sales_invoice_details['net_total']:
sales.net_amount = sales_invoice_details['net_total']
if sales.round_off != sales_invoice_details['roundoff']:
sales.round_off = sales_invoice_details['roundoff']
if sales.grant_total != sales_invoice_details['grant_total']:
sales.grant_total = sales_invoice_details['grant_total']
if sales.discount != sales_invoice_details['net_discount']:
sales.discount != sales_invoice_details['net_discount']
if sales.discount_for_sale != float(sales_invoice_details['discount_sale']):
sales.discount_for_sale = float(sales_invoice_details['discount_sale'])
if sales.discount_percentage_for_sale != float(sales_invoice_details['discount_sale_percentage']):
sales.discount_percentage_for_sale != float(sales_invoice_details['discount_sale_percentage'])
if sales_invoice_details['payment_mode'] == 'cash' or sales_invoice_details['payment_mode'] == 'cheque':
sales.payment_mode = sales_invoice_details['payment_mode']
sales.balance = 0
sales.save()
customer_account, created = CustomerAccount.objects.get_or_create(customer=customer, invoice_no=sales)
customer_account.balance = sales.balance
customer_account.save()
if sales_invoice_details['payment_mode'] == 'credit':
sales.payment_mode = sales_invoice_details['payment_mode']
if sales.balance != sales_invoice_details['balance']:
sales.balance = sales_invoice_details['balance']
sales.paid = float(sales.paid) + float(sales_invoice_details['paid'])
customer_account, created = CustomerAccount.objects.get_or_create(customer=customer, invoice_no=sales)
if customer_account.balance != sales.balance:
customer_account.balance = sales.balance
customer_account.save()
if customer_account.total_amount != sales.grant_total:
customer_account.total_amount = sales.grant_total
if customer_account.paid != sales.paid:
customer_account.paid = sales.paid
customer_account.save()
sales.save()
removed_items = sales_invoice_details['removed_items']
for r_item in removed_items:
item = InventoryItem.objects.get(code=r_item['item_code'])
d_item = DeliveryNoteItem.objects.get(id=r_item['delivery_note_item_id'], item=item)
s_item = SalesItem.objects.get(sales=sales, item=item, delivery_note_item=d_item)
d_item.quantity_sold = int(d_item.quantity_sold) - int(s_item.quantity_sold)
d_item.save()
if d_item.is_completed:
d_item.is_completed = False
d_item.save()
delivery_note = d_item.delivery_note
delivery_note.is_pending = True
delivery_note.save()
s_item.delete()
for item_data in sales_invoice_details['sales_items']:
if item_data['qty'] != 0:
item = InventoryItem.objects.get(code=item_data['item_code'])
s_items = SalesItem.objects.filter(sales=sales, delivery_note_item__item=item, delivery_note_item__is_completed=False)
remaining_qty = 0
for s_item in s_items:
remaining_qty = item_data['qty']
d_item = s_item.delivery_note_item
d_item_remaining_qty = int(d_item.total_quantity) - int(d_item.quantity_sold)
if remaining_qty != 0:
if int(d_item_remaining_qty) > int(remaining_qty):
d_item.quantity_sold = d_item.quantity_sold + int(remaining_qty)
sold_qty = remaining_qty
remaining_qty = 0
d_item.save()
s_item.discount_amount = item_data['dis_amt']
s_item.discount_percentage = item_data['dis_percentage']
s_item.selling_price = item_data['unit_price']
s_item.quantity_sold = int(s_item.quantity_sold) + int(sold_qty)
s_item.save()
s_item.net_amount = float(s_item.quantity_sold) * float(s_item.selling_price)
s_item.save()
else:
d_item.quantity_sold = int(d_item.quantity_sold) + int(d_item_remaining_qty)
sold_qty = d_item_remaining_qty
remaining_qty = int(remaining_qty) - int(d_item_remaining_qty)
if d_item.total_quantity == d_item.quantity_sold:
d_item.is_completed = True
d_item.save()
if remaining_qty > 0:
dn_items = DeliveryNoteItem.objects.filter(item=item, is_completed=False, delivery_note__salesman=salesman).order_by('id')
print dn_items
for dn_item in dn_items:
sold_qty = 0
if remaining_qty > 0:
dn_item_remaining_qty = int(dn_item.total_quantity) - int(dn_item.quantity_sold)
if int(dn_item_remaining_qty) > int(remaining_qty):
dn_item.quantity_sold = dn_item.quantity_sold + int(remaining_qty)
sold_qty = remaining_qty
remaining_qty = 0
dn_item.save()
else:
dn_item.quantity_sold = int(dn_item.quantity_sold) + int(dn_item_remaining_qty)
sold_qty = dn_item_remaining_qty
remaining_qty = int(remaining_qty) - int(dn_item_remaining_qty)
dn_item.save()
s_item, item_created = SalesItem.objects.get_or_create(delivery_note_item=dn_item, sales=sales)
s_item.sales = sales
s_item.quantity_sold = sold_qty
s_item.discount_amount = item_data['dis_amt']
s_item.discount_percentage = item_data['dis_percentage']
s_item.net_amount = float(sold_qty) * float(item_data['unit_price'])
s_item.selling_price = item_data['unit_price']
# unit price is actually the selling price
s_item.save()
not_completed_selling = []
for s_item in sales.salesitem_set.all():
d_item = s_item.delivery_note_item
delivery_note = d_item.delivery_note
for item in delivery_note.deliverynoteitem_set.all():
if item.total_quantity == item.quantity_sold:
item.is_completed = True
else:
item.is_completed = False
item.save()
if not item.is_completed:
not_completed_selling.append(item.id)
if len(not_completed_selling) != 0:
delivery_note.is_pending = False
delivery_note.save()
res = {
'result': 'ok',
}
response = simplejson.dumps(res)
return HttpResponse(response, status=200, mimetype='application/json')
class EditQuotation(View):
def get(self, request, *args, **kwargs):
return render(request, 'sales/edit_quotation.html', {})
def post(self, request, *args, **kwargs):
if request.is_ajax():
quotation_data = ast.literal_eval(request.POST['quotation'])
quotation, quotation_created = Quotation.objects.get_or_create(reference_id=quotation_data['reference_no'])
quotation.net_total = quotation_data['total_amount']
quotation.save()
customer = Customer.objects.get(customer_name=quotation_data['customer'])
quotation.to = customer
quotation.save()
stored_item_names = []
for q_item in quotation.quotationitem_set.all():
stored_item_names.append(q_item.item.name)
# Editing and Removing the Existing details of the Quotation item
for q_item in quotation.quotationitem_set.all():
q_item_names = []
for item_data in quotation_data['sales_items']:
q_item_names.append(item_data['item_name'])
# Removing the qutation item object that is not in inputed qutation items list
if q_item.item.name not in q_item_names:
item = q_item.item
inventory, created = Inventory.objects.get_or_create(item=item)
inventory.quantity = inventory.quantity + int(q_item.quantity_sold)
inventory.save()
q_item.delete()
else:
for item_data in quotation_data['sales_items']:
item = Item.objects.get(code=item_data['item_code'])
q_item, item_created = QuotationItem.objects.get_or_create(item=item, quotation=quotation)
inventory, created = Inventory.objects.get_or_create(item=item)
if item_created:
inventory.quantity = inventory.quantity - int(item_data['qty_sold'])
else:
inventory.quantity = inventory.quantity + q_item.quantity_sold - int(item_data['qty_sold'])
inventory.save()
q_item.net_amount = float(item_data['net_amount'])
q_item.quantity_sold = int(item_data['qty_sold'])
q_item.selling_price = float(item_data['unit_price'])
q_item.save()
# Create new sales item for the newly added item
for item_data in quotation_data['sales_items']:
if item_data['item_name'] not in stored_item_names:
item = Item.objects.get(code=item_data['item_code'])
q_item, item_created = QuotationItem.objects.get_or_create(item=item, quotation=quotation)
inventory, created = Inventory.objects.get_or_create(item=item)
if item_created:
inventory.quantity = inventory.quantity - int(item_data['qty_sold'])
else:
inventory.quantity = inventory.quantity + q_item.quantity_sold - int(item_data['qty_sold'])
inventory.save()
q_item.quantity_sold = item_data['qty_sold']
q_item.net_amount = item_data['net_amount']
q_item.selling_price = item_data['unit_price']
q_item.save()
res = {
'result': 'OK',
'quotation_id': quotation.id,
}
response = simplejson.dumps(res)
return HttpResponse(response, status=200, mimetype='application/json')
class EditDeliveryNote(View):
def get(self, request, *args, **kwargs):
return render(request, 'sales/edit_delivery_note.html', {})
def post(self, request, *args, **kwargs):
if request.is_ajax():
delivery_note_details = ast.literal_eval(request.POST['delivery_note'])
salesman = User.objects.get(first_name=delivery_note_details['salesman'])
delivery_note, created = DeliveryNote.objects.get_or_create(id=delivery_note_details['id'])
delivery_note.date = datetime.strptime(delivery_note_details['date'], '%d/%m/%Y')
delivery_note.lpo_number = delivery_note_details['lpo_no']
delivery_note.delivery_note_number = delivery_note_details['delivery_note_no']
delivery_note.net_total = delivery_note_details['net_total']
delivery_note.save()
delivery_note_data_items = delivery_note_details['sales_items']
removed_items = delivery_note_details['removed_items']
for r_item in removed_items:
inventory = InventoryItem.objects.get(code=r_item['item_code'])
d_item, created = DeliveryNoteItem.objects.get_or_create(item=inventory, delivery_note=delivery_note)
remaining_item_quantity = int(d_item.total_quantity) - int(d_item.quantity_sold)
inventory.quantity = inventory.quantity + int(remaining_item_quantity)
inventory.save()
d_item.delete()
for item in delivery_note_data_items:
inventory_item = InventoryItem.objects.get(code=item['item_code'])
d_item, created = DeliveryNoteItem.objects.get_or_create(item=inventory_item, delivery_note=delivery_note)
if created:
inventory_item.quantity = int(inventory_item.quantity) - int(item['qty_sold'])
else:
inventory_item.quantity = int(inventory_item.quantity) + int(d_item.quantity_sold) - int(item['qty_sold'])
inventory_item.save()
d_item.total_quantity = int(d_item.total_quantity) + int(item['qty_sold'])
d_item.net_amount = item['net_amount']
d_item.selling_price = item['unit_price']
d_item.save()
not_completed_selling = []
for d_item in delivery_note.deliverynoteitem_set.all():
if d_item.total_quantity != d_item.quantity_sold:
d_item.is_completed = False
d_item.save()
else:
d_item.is_completed = True
d_item.save()
if not d_item.is_completed:
not_completed_selling.append(d_item.id)
if len(not_completed_selling) != 0:
delivery_note.is_pending = True
delivery_note.save()
res = {
'result': 'ok',
'delivery_note_id': delivery_note.id
}
response = simplejson.dumps(res)
return HttpResponse(response, status=200, mimetype='application/json')
class PendingDeliveryNoteList(View):
def get(self, request, *args, **kwargs):
if request.is_ajax():
salesman_name = kwargs['salesman_name']
name_of_salesman = salesman_name.replace('_', ' ')
salesman = User.objects.get(first_name=name_of_salesman)
ctx_pendinglist = []
pending_deliverynotes = DeliveryNote.objects.filter(salesman=salesman, is_pending=True)
if pending_deliverynotes.count() > 0:
for delivery_note in pending_deliverynotes:
ctx_pendinglist.append(delivery_note.delivery_note_number)
res = {
'result': 'ok',
'pending_list': ctx_pendinglist,
}
status = 200
else:
res = {
'result': 'error',
'pending_list': ctx_pendinglist,
}
status = 200
response = simplejson.dumps(res)
return HttpResponse(response, status=status, mimetype='application/json')
class CheckDeliverynoteExistence(View):
def get(self, request, *args, **kwargs):
delivery_no = request.GET.get('delivery_no', '')
try:
delivery_note = DeliveryNote.objects.get(delivery_note_number=delivery_no)
res = {
'result': 'error',
}
print "Matching Query exists"
except Exception as ex:
print "Exception == ", str(ex)
res = {
'result': 'ok',
}
response = simplejson.dumps(res)
return HttpResponse(response, status=200, mimetype='application/json')
class CheckInvoiceExistence(View):
def get(self, request, *args, **kwargs):
invoice_no = request.GET.get('invoice_no', '')
try:
invoice = Sales.objects.get(sales_invoice_number=invoice_no)
res = {
'result': 'error',
}
print "Matching Query exists"
except Exception as ex:
print "Exception == ", str(ex)
res = {
'result': 'ok',
}
response = simplejson.dumps(res)
return HttpResponse(response, status=200, mimetype='application/json')
class CheckReturnInvoiceExistence(View):
def get(self, request, *args, **kwargs):
return_invoice_no = request.GET.get('return_invoice_no', '')
try:
return_invoice = SalesReturn.objects.get(return_invoice_number=return_invoice_no)
res = {
'result': 'error',
}
print "Matching Query exists"
except Exception as ex:
print "Exception == ", str(ex)
res = {
'result': 'ok',
}
response = simplejson.dumps(res)
return HttpResponse(response, status=200, mimetype='application/json')
class CheckReceiptVoucherExistence(View):
def get(self, request, *args, **kwargs):
rv_no = request.GET.get('rv_no', '')
try:
receiptvoucher = ReceiptVoucher.objects.get(receipt_voucher_no=rv_no)
res = {
'result': 'error',
}
print "Matching Query exists"
except Exception as ex:
print "Exception == ", str(ex)
res = {
'result': 'ok',
}
response = simplejson.dumps(res)
return HttpResponse(response, status=200, mimetype='application/json')
class DeliveryNoteItems(View):
def get(self, request, *args, **kwargs):
if request.is_ajax():
try:
item_code = request.GET.get('item_code', '')
item_name = request.GET.get('item_name', '')
barcode = request.GET.get('barcode', '')
salesman_name = request.GET.get('salesman', '')
if salesman_name:
salesman = User.objects.get(first_name=salesman_name)
items = []
if item_code:
items = InventoryItem.objects.filter(code__istartswith=item_code)
elif item_name:
items = InventoryItem.objects.filter(name__istartswith=item_name)
elif barcode:
items = InventoryItem.objects.filter(barcode__istartswith=barcode)
item_list = []
i = 0
i = i + 1
quantity_sold = 0
quantity = 0
selling_price = 0
discount = 0
total_quantity = 0
for item in items:
delivery_notes = DeliveryNoteItem.objects.filter(item=item, is_completed=False, delivery_note__salesman=salesman)
for delivery_note_item in delivery_notes:
quantity_sold = int(delivery_note_item.quantity_sold) + int(quantity_sold)
quantity = int(quantity) + int(delivery_note_item.item.quantity)
total_quantity = int(total_quantity) + int(delivery_note_item.total_quantity)
if delivery_notes.count() > 0:
selling_price = delivery_notes[::-1][0].selling_price if delivery_notes[::-1][0].selling_price else item.selling_price
discount = delivery_notes[::-1][0].discount if delivery_notes[::-1][0].discount else 0
item_list.append({
'sl_no': i,
'id': item.id,
'item_name': item.name + ' - ' + str(int(total_quantity - quantity_sold)),
'item_code': item.code,
'barcode': item.barcode,
'qty_sold': quantity_sold,
'sold_qty': quantity_sold,
'current_stock': quantity,
'selling_price': selling_price,
'discount_permit': item.discount_permit_percentage if item else 0,
# 'net_amount': delivery_note_item.net_amount,
'discount_given': discount,
'total_qty': total_quantity,
'remaining_qty': int(total_quantity - quantity_sold),
# 'dis_amt': 0,
# 'dis_percentage': 0,
'code_of_item': item.code,
# 'delivery_item_id': delivery_note_item.id,
})
i = i + 1
total_quantity = 0
quantity_sold = 0
# for delivery_note_item in items:
# item_list.append({
# 'sl_no': i,
# 'id': delivery_note_item.item.id,
# 'item_name': delivery_note_item.item.name +' - ' +delivery_note_item.delivery_note.delivery_note_number,
# 'item_code': delivery_note_item.item.code,
# 'barcode': delivery_note_item.item.barcode + ' - ' +delivery_note_item.delivery_note.delivery_note_number if delivery_note_item.item.barcode else '',
# 'item_description': str(delivery_note_item.item.description),
# 'qty_sold': delivery_note_item.quantity_sold,
# 'sold_qty': delivery_note_item.quantity_sold,
# 'tax': delivery_note_item.item.tax if delivery_note_item.item.tax else '',
# 'uom': delivery_note_item.item.uom.uom if delivery_note_item.item.uom else '',
# 'current_stock': delivery_note_item.item.quantity if delivery_note_item.item else 0 ,
# 'selling_price': delivery_note_item.selling_price if delivery_note_item.selling_price else delivery_note_item.item.selling_price ,
# 'discount_permit': delivery_note_item.item.discount_permit_percentage if delivery_note_item.item else 0,
# 'net_amount': delivery_note_item.net_amount,
# 'discount_given': delivery_note_item.discount,
# 'total_qty': delivery_note_item.total_quantity,
# 'remaining_qty': int(delivery_note_item.total_quantity - delivery_note_item.quantity_sold) if delivery_note_item else 0,
# 'dis_amt': 0,
# 'dis_percentage': 0,
# 'code_of_item': delivery_note_item.item.code + ' - ' +delivery_note_item.delivery_note.delivery_note_number,
# 'delivery_item_id': delivery_note_item.id,
# })
# i = i + 1
res = {
'items': item_list,
}
response = simplejson.dumps(res)
except Exception as ex:
print str(ex)
response = simplejson.dumps({'result': 'error', 'error': str(ex)})
status_code = 500
status_code = 200
return HttpResponse(response, status = status_code, mimetype = 'application/json')
| [
"[email protected]"
]
| |
486f719763164aae76c114ef5ed377847619037d | f95e73867e4383784d6fdd6a1c9fe06cffbfd019 | /PythonToolkit/CameraVideo/VideoObjectTracking.py | 5fa77270cb9a2b92474011d375924b1047c1764c | []
| no_license | linxiaohui/CodeLibrary | da03a9ed631d1d44b098ae393b4bd9e378ab38d3 | 96a5d22a8c442c4aec8a064ce383aba8a7559b2c | refs/heads/master | 2021-01-18T03:42:39.536939 | 2018-12-11T06:47:15 | 2018-12-11T06:47:15 | 85,795,767 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,499 | py | # -*- coding: utf-8 -*-
import cv2
import os
import numpy as np
# 摄像头只能一个进程获取
camera = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
#文件的名称,格式,帧率,帧大小,是否彩色
out = cv2.VideoWriter('output.avi',fourcc,24.0,(640,480))
#VideoCapture类的get()方法不能获取摄像头帧速率的准确值(总是返回0)
#print(camera.get(cv2.CAP_PROP_FPS))
print(camera.get(cv2.CAP_PROP_FRAME_HEIGHT), camera.get(cv2.CAP_PROP_FRAME_WIDTH))
objLower = np.array([20, 20, 100], dtype = "uint8")
objUpper = np.array([100, 100, 200],dtype = "uint8")
while True:
(grabbed, frame) = camera.read()
if not grabbed:
break
print(frame.shape)
obj = cv2.inRange(frame, objLower, objUpper)
obj = cv2.GaussianBlur(obj, (3, 3), 0)
#print(obj.shape)
#cv2.inRange的返回值是`a thresholded image`, 因此下面的函数会报错
#gray = cv2.cvtColor(obj, cv2.COLOR_BGR2GRAY)
(_, cnts, _) = cv2.findContours(obj, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if len(cnts) > 0:
cnt = sorted(cnts, key = cv2.contourArea, reverse = True)[0]
rect = np.int32(cv2.boxPoints(cv2.minAreaRect(cnt)))
cv2.drawContours(frame, [rect], -1, (0, 255, 0), 2)
cv2.imshow("Camera", frame)
#写入文件中
# out.write(frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
camera.release()
out.release()
cv2.destroyAllWindows()
| [
"[email protected]"
]
| |
ecc202cf0f419b414a4822218103363ee0bb5e9a | a1c20ec292350a4c8f2164ba21715414f8a77d19 | /Udemy/PythonMegaCourse/Section 12-Databases/PythonWithDatabases/script1.py | 10d35d8e80252412da1c086f2961b0c065006f25 | []
| no_license | nowacki69/Python | 2ae621b098241a614836a50cb1102094bf8e689f | e5325562801624e43b3975d9f246af25517be55b | refs/heads/master | 2021-08-22T21:30:39.534186 | 2019-09-03T01:21:11 | 2019-09-03T01:21:11 | 168,528,687 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,200 | py | import sqlite3
def create_table():
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS tbl_store (item TEXT, quantity INTEGER, price REAL)")
conn.commit()
conn.close()
def insert(item, quantity, price):
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("INSERT INTO tbl_store VALUES (?, ?, ?)", (item, quantity, price))
conn.commit()
conn.close()
def view():
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("SELECT * FROM tbl_store")
rows = cur.fetchall()
conn.close()
return rows
def delete(item):
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("DELETE FROM tbl_store WHERE item=?", (item,))
conn.commit()
conn.close()
def update(quantity, price, item):
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("UPDATE tbl_store SET quantity=?, price=? WHERE item=?", (quantity, price, item))
conn.commit()
conn.close()
# insert("Wine Glass", 8, 10.5)
# insert("Water Glass", 10, 5)
# insert("Coffee Cup", 10, 5)
# delete("Coffee Cup")
update(11, 6, "Water Glass")
print(view())
| [
"[email protected]"
]
| |
7b6da5134be3bbf7c5b79c9dd974d501bc13dc0f | d5219cd3094e5a72efdf2ed7e321f6c586dee58f | /account_report.py | dcc6421f6374efdae4c6b8f9d1d1257e606076c1 | []
| no_license | Descomplica-Marketing/Google-Adwords | d721b178bc2384cf069103e2cc83b79d4f529c0d | 808744852455aea9b24c4bd0fc9e4b065f729e54 | refs/heads/master | 2020-06-25T04:41:45.795739 | 2019-07-30T02:43:00 | 2019-07-30T02:43:00 | 199,204,786 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,026 | py | from googleads import adwords
from functions import get_report_df
report_query = (adwords.ReportQueryBuilder()
.Select('Date', 'AccountDescriptiveName', 'AdNetworkType1', 'AdNetworkType2', 'AveragePosition',
'Clicks', 'ConversionRate', 'Conversions', 'Cost', 'Engagements', 'Impressions')
.From('ACCOUNT_PERFORMANCE_REPORT')
.Where('Cost').GreaterThan(0)
.During('YESTERDAY')
.Build())
# Create a list with your client ids
client_ids = ()
report = get_report_df(client_ids, report_query)
# CASTING
# int fields
report[['clicks', 'engagements', 'impressions']] = report[['clicks', 'engagements', 'impressions']].astype(int)
# percentage fields
report['conv_rate'] = report['conv_rate'].str[:-1].astype(float)
# monetary fields
report[['cost']] = report[['cost']].astype(float) / 1000000
# float fields
report[['avg_position', 'conversions']] = report[['avg_position', 'conversions']].astype(float)
print(report)
| [
"[email protected]"
]
| |
d797428a2dbbc4d3a51fa24769f528e072f9af05 | 7134e45563b2045837296cb5c4f1974a025e4f2b | /.history/SANDBOX_20201206081849.py | 62633377c5a5963f4dd726aaecbd33aa33497e42 | []
| no_license | Nordenbox/Nordenbox_Python_Fundmental | dca175c471ac2c64453cc4bcf291dd0773be4add | 9c79fd5d0dada580072b523d5aa1d72f996e3a22 | refs/heads/master | 2022-01-21T06:37:15.084437 | 2022-01-06T13:55:30 | 2022-01-06T13:55:30 | 240,154,945 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 67 | py | import pandas as pd
data = pd.read_csv('to_addrs.csv')
print(data) | [
"[email protected]"
]
| |
ba580ba89c8fad29d726dfb35cbc4a7b1bd9b0e3 | e48f203d18b4eac537f5f69277fb497be1cec611 | /backend/mobile_25_app_dev_15680/wsgi.py | 70ed666f14facf20d2d59d70d3cb062261cc3522 | []
| no_license | crowdbotics-apps/mobile-25-app-dev-15680 | 107fea56fa665c134a51fc3ea0b642b0b582d15d | 9423eee5529d4a8a48cda334b1ac6eb2a5760838 | refs/heads/master | 2023-01-18T19:37:13.026096 | 2020-11-25T16:05:43 | 2020-11-25T16:05:43 | 315,973,809 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 423 | py | """
WSGI config for mobile_25_app_dev_15680 project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mobile_25_app_dev_15680.settings')
application = get_wsgi_application()
| [
"[email protected]"
]
| |
9b5d1cdf3282c3ca808fd6c68d5b75f12754cc6c | 60a831fb3c92a9d2a2b52ff7f5a0f665d4692a24 | /IronPythonStubs/release/stubs.min/Autodesk/Revit/DB/Structure/__init___parts/RebarShapeConstraintAngleFromFixedDir.py | 53925f2b3e8ecc1e9cd08fd6c3cf1445ad275918 | [
"MIT"
]
| permissive | shnlmn/Rhino-Grasshopper-Scripts | a9411098c5d1bbc55feb782def565d535b27b709 | 0e43c3c1d09fb12cdbd86a3c4e2ba49982e0f823 | refs/heads/master | 2020-04-10T18:59:43.518140 | 2020-04-08T02:49:07 | 2020-04-08T02:49:07 | 161,219,695 | 11 | 2 | null | null | null | null | UTF-8 | Python | false | false | 1,811 | py | class RebarShapeConstraintAngleFromFixedDir(RebarShapeConstraint,IDisposable):
"""
A constraint which can be applied to a RebarShapeSegment and drives the angle
of the segment relative to a fixed direction in UV-space.
RebarShapeConstraintAngleFromFixedDir(paramId: ElementId,sign: int,direction: UV)
"""
def Dispose(self):
""" Dispose(self: RebarShapeConstraint,A_0: bool) """
pass
def ReleaseUnmanagedResources(self,*args):
""" ReleaseUnmanagedResources(self: RebarShapeConstraint,disposing: bool) """
pass
def __enter__(self,*args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self,*args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,paramId,sign,direction):
""" __new__(cls: type,paramId: ElementId,sign: int,direction: UV) """
pass
Direction=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""A fixed direction in UV-space. The parameter will drive
the segment's angle relative to this direction.
Get: Direction(self: RebarShapeConstraintAngleFromFixedDir) -> UV
Set: Direction(self: RebarShapeConstraintAngleFromFixedDir)=value
"""
Sign=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""When the sign is 1,the Direction is rotated clockwise by the angle's value.
When -1,the Direction is rotated counter-clockwise.
Get: Sign(self: RebarShapeConstraintAngleFromFixedDir) -> int
Set: Sign(self: RebarShapeConstraintAngleFromFixedDir)=value
"""
| [
"[email protected]"
]
| |
c886e273972ecb4f7d0f52ed30b61359eaaba35b | 4f3a4c194451eae32f1ff7cf3b0db947e3892365 | /162/main.py | b3936348ba1e48aaef408bd1f16b59b4e55140f2 | []
| no_license | szhongren/leetcode | 84dd848edbfd728b344927f4f3c376b89b6a81f4 | 8cda0518440488992d7e2c70cb8555ec7b34083f | refs/heads/master | 2021-12-01T01:34:54.639508 | 2021-11-30T05:54:45 | 2021-11-30T05:54:45 | 83,624,410 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,689 | py | """
A peak element is an element that is greater than its neighbors.
Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that num[-1] = num[n] = -∞.
For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.
click to show spoilers.
Note:
Your solution should be in logarithmic complexity.
"""
class Solution(object):
def findPeakElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
self.l = len(nums)
if self.l == 1:
return 0
elif self.l == 2:
return nums.index(max(nums))
else:
return self.findPeakHelper(nums, 0, self.l)
def findPeakHelper(self, nums, start, end):
"""
:type nums: List[int]
:type start: int
:type end: int
:rtype: int
"""
if end - start <= 1 or start == self.l - 1:
return start
mid = (start + end) // 2
if mid == 0 and nums[mid + 1] < nums[mid]:
return mid
elif mid == self.l - 1 and nums[mid - 1] < nums[mid]:
return mid
elif nums[mid - 1] < nums[mid] and nums[mid + 1] < nums[mid]:
return mid
elif nums[mid - 1] > nums[mid]:
return self.findPeakHelper(nums, start, mid)
elif nums[mid + 1] > nums[mid]:
return self.findPeakHelper(nums, mid + 1, end)
ans = Solution()
print(ans.findPeakElement([1,2,3,4,3])) | [
"[email protected]"
]
| |
828310819742c4c59c63891d0d30da4ec07c7773 | bea0e4806236daff2a07df2f0949fe046ef76c03 | /apps/op/controllers/real/sku.py | 5b16a7fd874b0d32e199632174087a34a606d371 | []
| no_license | xutaoding/osp_autumn | 68903f7acf78d7572777a500172e2f8c09afed48 | daf260ecd5adf553490a8ac6b389a74439234b6a | refs/heads/master | 2021-01-09T21:51:51.248630 | 2015-11-23T08:20:00 | 2015-11-23T08:20:00 | 46,706,177 | 0 | 2 | null | null | null | null | UTF-8 | Python | false | false | 2,523 | py | # -*- coding: utf-8 -*-
from .. import BaseHandler
from .. import require
from voluptuous import Schema, Any
from autumn.torn.form import Form
from autumn.torn.paginator import Paginator
class SkuList(BaseHandler):
@require()
def get(self):
sql = 'select * from sku where deleted = 0 '
name = self.get_argument('name', '')
params = []
if name:
sql += 'and name like %s '
params.append('%' + name + '%')
sql += 'order by created_at desc'
page = Paginator(self, sql, params)
self.render('real/sku_list.html', page=page, name=name)
add_list = Schema({
'name': str,
'price': str,
'action': Any('edit', 'add'),
}, extra=True)
class SkuAdd(BaseHandler):
@require('storage')
def get(self):
form = Form(self.request.arguments, add_list)
form.action.value = 'add'
self.render('real/sku.html', form=form)
@require('storage')
def post(self):
form = Form(self.request.arguments, add_list)
form.action.value = 'add'
if not form.validate():
return self.render('real/sku.html', form=form)
supplier = self.db.get('select id from supplier where name = "视惠" limit 1')
self.db.execute('insert into sku(name, price, supplier_id, created_at) values(%s, %s, %s, NOW())',
form.name.value, form.price.value, supplier["id"])
self.redirect(self.reverse_url('real.show_sku'))
class SkuEdit(BaseHandler):
@require('storage')
def get(self):
sku = self.db.get('select name, price from sku where id = %s', self.get_argument('id'))
form = Form(sku, add_list)
form.action.value = 'edit'
self.render('real/sku.html', form=form, id=self.get_argument('id'))
@require('storage')
def post(self):
form = Form(self.request.arguments, add_list)
form.action.value = 'edit'
if not form.validate():
return self.render('real/sku.html', form=form, id=self.get_argument('id'))
self.db.execute('update sku set name = %s, price = %s where id = %s',
form.name.value, form.price.value, self.get_argument('id'))
self.redirect(self.reverse_url('real.show_sku'))
class SkuDelete(BaseHandler):
@require('storage')
def post(self):
id = self.get_argument('id')
self.db.execute('update sku set deleted = 1 where id = %s', id)
self.redirect(self.reverse_url('real.show_sku')) | [
"[email protected]"
]
| |
489e2344051b765a6a26da0bf20a60620a31b678 | 887fe8fa82b592e678e90e82ea2681f6f8a23a7f | /pygrim/formulas/airy.py | ac8bdeb4724cc36ec5c0c31787b7d3e823c1ea26 | [
"MIT"
]
| permissive | wbhart/fungrim | efcfa32c2466c36f852fb01a9d575add732da46a | 6febcbeee4b950bb421199706fc0c9ae729fe2e5 | refs/heads/master | 2020-08-01T23:07:46.997516 | 2019-09-26T16:32:20 | 2019-09-26T16:32:20 | 211,150,429 | 0 | 0 | null | 2019-09-26T17:57:32 | 2019-09-26T17:57:32 | null | UTF-8 | Python | false | false | 5,483 | py | # -*- coding: utf-8 -*-
from ..expr import *
def_Topic(
Title("Airy functions"),
Section("Definitions"),
Entries(
"9ac289",
"5a9d3f",
),
Section("Illustrations"),
Entries(
"b4c968",
"fa65f3",
),
Section("Differential equation"),
Entries(
"51b241",
"de9800", # Wronskian
),
Section("Special values"),
Entries(
"693cfe",
"807917",
"9a8d4d",
"fba07c",
),
Section("Higher derivatives"),
Entries(
"b2e9d0", # ai''
"70ec9f", # bi''
"eadca2", # recurrence
),
Section("Hypergeometric representations"),
Entries(
"01bbb6",
"bd319e",
"20e530",
"4d65e5",
),
Section("Analytic properties"),
Entries(
"def37e",
"1f0577",
"90f31e",
"b88f65",
"7194d4",
"d1f9d0",
"a2df77",
),
)
make_entry(ID("9ac289"),
SymbolDefinition(AiryAi, AiryAi(z), "Airy function of the first kind"))
make_entry(ID("5a9d3f"),
SymbolDefinition(AiryBi, AiryBi(z), "Airy function of the second kind"))
make_entry(ID("b4c968"),
Image(Description("X-ray of", AiryAi(z), "on", Element(z, ClosedInterval(-6,6) + ClosedInterval(-6,6)*ConstI)),
ImageSource("xray_airy_ai")),
description_xray,
)
make_entry(ID("fa65f3"),
Image(Description("X-ray of", AiryBi(z), "on", Element(z, ClosedInterval(-6,6) + ClosedInterval(-6,6)*ConstI)),
ImageSource("xray_airy_bi")),
description_xray,
)
make_entry(ID("51b241"),
Formula(Where(Equal(ComplexDerivative(y(z), For(z, z, 2)) - z*y(z), 0), Equal(y(z), C*AiryAi(z) + D*AiryBi(z)))),
Variables(z, C, D),
Assumptions(And(Element(z, CC), Element(C, CC), Element(D, CC))))
make_entry(ID("de9800"),
Formula(Equal(AiryAi(z)*AiryBi(z,1)-AiryAi(z,1)*AiryBi(z), 1/ConstPi)),
Variables(z),
Element(z, CC))
make_entry(ID("693cfe"),
Formula(EqualAndElement(AiryAi(0), Div(1, Pow(3,Div(2,3))*GammaFunction(Div(2,3))), RealBall(Decimal("0.355028053887817239260063186004"), Decimal("1.84e-31")))))
make_entry(ID("807917"),
Formula(EqualAndElement(AiryAi(0,1), -Div(1, Pow(3,Div(1,3))*GammaFunction(Div(1,3))), RealBall(Decimal("-0.258819403792806798405183560189"), Decimal("2.04e-31")))))
make_entry(ID("9a8d4d"),
Formula(EqualAndElement(AiryBi(0), Div(1, Pow(3,Div(1,6))*GammaFunction(Div(2,3))), RealBall(Decimal("0.614926627446000735150922369094"), Decimal("3.87e-31")))))
make_entry(ID("fba07c"),
Formula(EqualAndElement(AiryBi(0,1), Div(Pow(3,Div(1,6)), GammaFunction(Div(1,3))), RealBall(Decimal("0.448288357353826357914823710399"), Decimal("1.72e-31")))))
make_entry(ID("b2e9d0"),
Formula(Equal(AiryAi(z,2), z*AiryAi(z))),
Variables(z),
Assumptions(Element(z, CC)))
make_entry(ID("70ec9f"),
Formula(Equal(AiryBi(z,2), z*AiryBi(z))),
Variables(z),
Assumptions(Element(z, CC)))
make_entry(ID("eadca2"),
Formula(Where(Equal(ComplexDerivative(y(z), For(z, z, n)), z*ComplexDerivative(y(z), For(z, z, n-2)) + (n-2)*ComplexDerivative(y(z), For(z, z, n-3))),
Equal(y(z), C*AiryAi(z) + D*AiryBi(z)))),
Variables(n, z, C, D),
Assumptions(And(Element(z, CC), Element(n, ZZGreaterEqual(3)), Element(C, CC), Element(D, CC))))
make_entry(ID("01bbb6"),
Formula(Equal(AiryAi(z), AiryAi(0)*Hypergeometric0F1(Div(2,3),z**3/9) + z*AiryAi(0,1)*Hypergeometric0F1(Div(4,3),z**3/9))),
Variables(z),
Assumptions(Element(z, CC)))
make_entry(ID("bd319e"),
Formula(Equal(AiryBi(z), AiryBi(0)*Hypergeometric0F1(Div(2,3),z**3/9) + z*AiryBi(0,1)*Hypergeometric0F1(Div(4,3),z**3/9))),
Variables(z),
Assumptions(Element(z, CC)))
make_entry(ID("20e530"),
Formula(Equal(AiryAi(z,1), AiryAi(0,1)*Hypergeometric0F1(Div(1,3),z**3/9) + (z**2/2)*AiryAi(0)*Hypergeometric0F1(Div(5,3),z**3/9))),
Variables(z),
Assumptions(Element(z, CC)))
make_entry(ID("4d65e5"),
Formula(Equal(AiryBi(z,1), AiryBi(0,1)*Hypergeometric0F1(Div(1,3),z**3/9) + (z**2/2)*AiryBi(0)*Hypergeometric0F1(Div(5,3),z**3/9))),
Variables(z),
Assumptions(Element(z, CC)))
make_entry(ID("def37e"),
Formula(Equal(HolomorphicDomain(C*AiryAi(z) + D*AiryBi(z), z, Union(CC, Set(UnsignedInfinity))), CC)),
Variables(C, D),
Assumptions(And(Element(C, CC), Element(D, CC), Not(And(Equal(C,0), Equal(D,0))))))
make_entry(ID("1f0577"),
Formula(Equal(Poles(C*AiryAi(z) + D*AiryBi(z), z, Union(CC, Set(UnsignedInfinity))), Set())),
Variables(C, D),
Assumptions(And(Element(C, CC), Element(D, CC), Not(And(Equal(C,0), Equal(D,0))))))
make_entry(ID("90f31e"),
Formula(Equal(EssentialSingularities(C*AiryAi(z) + D*AiryBi(z), z, Union(CC, Set(UnsignedInfinity))), Set(UnsignedInfinity))),
Variables(C, D),
Assumptions(And(Element(C, CC), Element(D, CC), Not(And(Equal(C,0), Equal(D,0))))))
make_entry(ID("b88f65"),
Formula(Equal(BranchPoints(C*AiryAi(z) + D*AiryBi(z), z, Union(CC, Set(UnsignedInfinity))), Set())),
Variables(C, D),
Assumptions(And(Element(C, CC), Element(D, CC))))
make_entry(ID("7194d4"),
Formula(Equal(BranchCuts(C*AiryAi(z) + D*AiryBi(z), z, CC), Set())),
Variables(C, D),
Assumptions(And(Element(C, CC), Element(D, CC))))
make_entry(ID("d1f9d0"),
Formula(Subset(Zeros(AiryAi(z), Var(z), Element(z, CC)), RR)))
make_entry(ID("a2df77"),
Formula(Subset(Zeros(AiryAi(z,1), Var(z), Element(z, CC)), RR)))
| [
"[email protected]"
]
| |
bdfee875ae6b593bf36e99398d5e4e7e547569b3 | 2c6a101c1015a3508d901814e530f7346145650a | /hbase_regionserver_requests.py | a8c96ebb9ee92b7eb1f92580e2837e66a9003b39 | [
"MIT"
]
| permissive | mesenger/DevOps-Python-tools | 52f7973ea1349686afd7393c2e8cd94c2223e2e3 | 221dbda24a638b2f28dd26f3e015b9133709b012 | refs/heads/master | 2023-08-20T20:23:42.810544 | 2023-07-29T16:45:31 | 2023-07-29T16:45:31 | 284,710,736 | 0 | 0 | NOASSERTION | 2020-08-03T13:42:01 | 2020-08-03T13:42:00 | null | UTF-8 | Python | false | false | 8,358 | py | #!/usr/bin/env python3
# vim:ts=4:sts=4:sw=4:et
#
# Author: Hari Sekhon
# Date: 2016-10-06 10:42:59 +0100 (Thu, 06 Oct 2016)
#
# https://github.com/HariSekhon/DevOps-Python-tools
#
# License: see accompanying Hari Sekhon LICENSE file
#
# If you're using my code you're welcome to connect with me on LinkedIn
# and optionally send me feedback to help steer this or other code I publish
#
# https://www.linkedin.com/in/HariSekhon
#
"""
Tool to calculate HBase RegionServer Requests Per Second or Average Since Startup using JMX API stats
Designed to help analyze regionserver load imbalance (see also hbase_region_requests.py for region hotspotting)
Argument list should be one or more RegionServers to dump the JMX stats from
Tested on Apache HBase 1.0.3, 1.1.6, 1.2.1, 1.2.2, 1.3.1
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import json
import os
import re
import sys
import time
import traceback
import requests
libdir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'pylib'))
sys.path.append(libdir)
try:
# pylint: disable=wrong-import-position
from harisekhon.utils import validate_host, validate_port, validate_int
from harisekhon.utils import UnknownError, CriticalError, support_msg_api, printerr, plural, log
from harisekhon import CLI, RequestHandler
except ImportError as _:
print(traceback.format_exc(), end='')
sys.exit(4)
__author__ = 'Hari Sekhon'
__version__ = '0.5.3'
class HBaseRegionServerRequests(CLI):
def __init__(self):
# Python 2.x
super(HBaseRegionServerRequests, self).__init__()
# Python 3.x
# super().__init__()
self.host_list = []
self.port = 16030
self.interval = 1
self.count = 0
self.since_uptime = False
self.stats = {}
self.last = {}
self.first_iteration = 0
self.request_type = None
self.request_types = ('read', 'write', 'total', 'rpcScan', 'rpcMutate', 'rpcMulti', 'rpcGet', 'blocked')
self.timeout_default = 300
self.url = None
self._regions = None
def add_options(self):
self.add_opt('-P', '--port', default=os.getenv('HBASE_REGIONSERVER_PORT', self.port),
help='HBase RegionServer port (default: {})'.format(self.port))
self.add_opt('-i', '--interval', default=self.interval,
help='Interval to print rates at (default: {})'.format(self.interval))
self.add_opt('-c', '--count', default=self.count,
help='Number of times to print stats (default: {}, zero means infinite)'.format(self.count))
self.add_opt('-a', '--average', action='store_true', help='Calculate average since RegionServer startup')
self.add_opt('-T', '--type', help='Only return given metric types (comma separated list containing any of: {})'\
.format(', '.join(self.request_types)))
def process_args(self):
self.host_list = self.args
if not self.host_list:
self.usage('no host arguments given, must give at least one regionserver host as an argument')
for host in self.host_list:
validate_host(host)
self.port = self.get_opt('port')
validate_port(self.port)
self.interval = self.get_opt('interval')
self.count = self.get_opt('count')
self.since_uptime = self.get_opt('average')
validate_int(self.interval, 'interval')
validate_int(self.count, 'count')
self.interval = int(self.interval)
self.count = int(self.count)
if self.count == 0:
self.disable_timeout()
self.request_type = self.get_opt('type')
if self.request_type:
self.request_type = [_.strip() for _ in self.request_type.split(',')]
for _ in self.request_type:
if _ not in self.request_types:
self.usage('--type may only include: {}'.format(', '.join(self.request_types)))
def run(self):
if self.count:
for _ in range(self.count):
self.run_hosts()
if _ != self.count - 1:
time.sleep(self.interval)
else:
while True:
self.run_hosts()
time.sleep(self.interval)
def run_hosts(self):
for host in self.host_list:
url = 'http://{host}:{port}/jmx'.format(host=host, port=self.port)
if not self.since_uptime:
url += '?qry=Hadoop:service=HBase,name=RegionServer,sub=Server'
try:
self.run_host(host, url)
except (CriticalError, UnknownError, requests.RequestException) as _:
printerr("ERROR querying JMX stats for host '{}': {}".format(host, _), )
def run_host(self, host, url):
log.info('querying %s', host)
req = RequestHandler().get(url)
json_data = json.loads(req.text)
uptime = None
beans = json_data['beans']
if self.since_uptime:
for bean in beans:
if bean['name'] == 'java.lang:type=Runtime':
uptime = int(bean['Uptime'] / 1000)
break
if not uptime:
raise UnknownError("failed to find uptime in JMX stats for host '{}'. {}"\
.format(host, support_msg_api()))
for bean in beans:
log.debug('processing Regions bean')
if bean['name'] == 'Hadoop:service=HBase,name=RegionServer,sub=Server':
self.process_bean(host, bean, uptime)
self.print_stats(host)
def process_bean(self, host, bean, uptime):
region_regex = re.compile('^(.+)RequestCount$')
stats = self.stats
last = self.last
for key in bean:
match = region_regex.match(key)
if match:
metric_type = match.group(1)
log.info('matched regionserver %s %s request count = %s', host, metric_type, bean[key])
if host not in stats:
stats[host] = {}
if host not in last:
last[host] = {}
if self.request_type and metric_type not in self.request_type:
continue
if self.since_uptime:
stats[host][metric_type] = bean[key] / uptime
else:
if key not in last[host]:
self.first_iteration = 1
else:
stats[host][metric_type] = (bean[key] - last[host][key]) / self.interval
last[host][key] = bean[key]
def print_stats(self, host):
stats = self.stats
tstamp = time.strftime('%F %T')
if not stats:
print("No regionserver stats found. Did you specify correct regionserver addresses and --port?")
sys.exit(1)
if self.first_iteration:
log.info('first iteration, skipping iteration until we have a differential')
print('{}\t{} rate stats will be available in next iteration in {} sec{}'\
.format(tstamp, host, self.interval, plural(self.interval)))
self.first_iteration = 0
return
for metric in self.request_types:
if self.request_type and metric not in self.request_type:
continue
try:
val = '{:8.0f}'.format(stats[host][metric])
# might happen if server is down for maintenance - in which case N/A and retry later rather than crash
except KeyError:
val = 'N/A'
print('{:20s}\t{:20s}\t{:10s}\t{}'\
.format(tstamp, host, metric, val))
print()
# some extra effort to make it look the same as HBase presents it as
#def encode_char(self, char):
# if char in string.printable and char not in ('\t', '\n', '\r', '\x0b', '\x0c'):
# return char
# _ = '{0:#0{1}x}'.format(ord(char), 4).replace('0x', '\\x')
# _ = self.re_hex.sub(lambda x: x.group(1).upper(), _)
# return _
if __name__ == '__main__':
HBaseRegionServerRequests().main()
| [
"[email protected]"
]
| |
6abc53ffc8fe957131d887d4192ae8073b48d1be | 6e41636b8fae338cc3d1cb0885ca21c17af64ded | /echo-client.py | 8707638e8dbad4b61d11bb076b8fa20bfcfbc768 | []
| no_license | Menah3m/socket_work | 89e89febafce913b904c47549cbab558fb39a1d9 | 6a9eb05be0386fc709c92dc86afa67167d007c0a | refs/heads/master | 2021-03-26T13:42:38.004924 | 2020-03-16T13:26:17 | 2020-03-16T13:26:17 | 247,708,963 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 284 | py | # Name:echo-client
# Author:Yasu
# Time:2020/3/16
import socket
Host = '127.0.0.1'
Port = 6500
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect((Host,Port))
sock.sendall(b'Hello World!')
data = sock.recv(1024)
print('Received!', repr(data)) | [
"[email protected]"
]
| |
f3d34c28888679e66d0ab10777e49c22b3272308 | ebcbbe645d70d4f756704d3c5113ba25e8a1814c | /fabfile.py | 7cd23c5d488fb6645aa621eda37ae36c6056dd84 | [
"BSD-3-Clause"
]
| permissive | abhilashsn/standup | 2ea02078c6616c88f1a8cc28508b948bf4001c30 | 998341af354ed0ddcd15b673ea7af090a7efbce6 | refs/heads/master | 2021-01-18T09:11:58.371312 | 2014-08-29T16:25:07 | 2014-08-29T16:25:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | true | false | 355 | py | from fabric.api import env, local
env.hosts = ['localhost']
def npm_install():
"""Correctly runs npm install"""
local('cp node.json package.json')
local('npm install')
local('rm package.json')
def test():
"""Run tests with coverage"""
local('nosetests --with-coverage --cover-package=standup '
'--cover-inclusive')
| [
"[email protected]"
]
| |
b5a71f36acc625624a71208d512343d843b77b43 | 045ec3ae16fc554a05510abc3697557ebc5ce304 | /CIME/tests/test_unit_hist_utils.py | fe6d4866c34d5f7a2d90e63a11b14989b5d4d88b | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
]
| permissive | ESMCI/cime | c09223ee9b8a463bd00741ff39f60fda7639af89 | 02fad90a379cdbd3c1106cbd63324480f0bf7a22 | refs/heads/master | 2023-08-16T07:03:22.224344 | 2023-08-03T19:47:53 | 2023-08-03T19:47:53 | 31,605,662 | 159 | 179 | NOASSERTION | 2023-09-12T18:38:42 | 2015-03-03T15:33:00 | Python | UTF-8 | Python | false | false | 1,803 | py | import io
import unittest
from unittest import mock
from CIME.hist_utils import copy_histfiles
from CIME.XML.archive import Archive
class TestHistUtils(unittest.TestCase):
@mock.patch("CIME.hist_utils.safe_copy")
def test_copy_histfiles_exclude(self, safe_copy):
case = mock.MagicMock()
case.get_env.return_value.get_latest_hist_files.side_effect = [
["/tmp/testing.cpl.hi.nc"],
["/tmp/testing.atm.hi.nc"],
]
case.get_env.return_value.exclude_testing.side_effect = [True, False]
case.get_value.side_effect = [
"/tmp", # RUNDIR
None, # RUN_REFCASE
"testing", # CASE
True, # TEST
True, # TEST
]
case.get_compset_components.return_value = ["atm"]
test_files = [
"testing.cpl.hi.nc",
]
with mock.patch("os.listdir", return_value=test_files):
comments, num_copied = copy_histfiles(case, "base")
assert num_copied == 1
@mock.patch("CIME.hist_utils.safe_copy")
def test_copy_histfiles(self, safe_copy):
case = mock.MagicMock()
case.get_env.return_value.get_latest_hist_files.return_value = [
"/tmp/testing.cpl.hi.nc",
]
case.get_env.return_value.exclude_testing.return_value = False
case.get_value.side_effect = [
"/tmp", # RUNDIR
None, # RUN_REFCASE
"testing", # CASE
True, # TEST
]
case.get_compset_components.return_value = []
test_files = [
"testing.cpl.hi.nc",
]
with mock.patch("os.listdir", return_value=test_files):
comments, num_copied = copy_histfiles(case, "base")
assert num_copied == 1
| [
"[email protected]"
]
| |
a5197aea32de8058d3e8c39cda831c551cb28f70 | 91948d5be26636f1f2b941cb933701ea626a695b | /problem201_google_triangl number.py | 8997884bbddd5865d98e2a33713e6f7f60148908 | [
"MIT"
]
| permissive | loghmanb/daily-coding-problem | 4ae7dd201fde5ee1601e0acae9e9fc468dcd75c9 | b2055dded4276611e0e7f1eb088e0027f603aa7b | refs/heads/master | 2023-08-14T05:53:12.678760 | 2023-08-05T18:12:38 | 2023-08-05T18:12:38 | 212,894,228 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,424 | py | '''
This problem was asked by Google.
You are given an array of arrays of integers, where each array corresponds to a row in a triangle of numbers.
For example, [[1], [2, 3], [1, 5, 1]] represents the triangle:
1
2 3
1 5 1
We define a path in the triangle to start at the top and go down one row at a time to an adjacent value,
eventually ending with an entry on the bottom row.
For example, 1 -> 3 -> 5. The weight of the path is the sum of the entries.
Write a program that returns the weight of the maximum weight path.
'''
import unittest
class Solution:
def findMaxWeight(self, triangle):
max_val = triangle[0][0]
for i in range(1, len(triangle)):
N = len(triangle[i])
for j in range(N):
if j==0:
triangle[i][j] += triangle[i-1][j]
elif j==N-1:
triangle[i][j] += triangle[i-1][j-1]
else:
triangle[i][j] += max(triangle[i-1][j-1:j+1])
if max_val < triangle[i][j]:
max_val = triangle[i][j]
return max_val
class SolutionTestUnit(unittest.TestCase):
def setUp(self):
self.solution = Solution()
def test_simple_triangle(self):
triangle = [[1], [2, 3], [1, 5, 1]]
self.assertEqual(self.solution.findMaxWeight(triangle), 9)
if __name__ == "__main__":
unittest.main() | [
"[email protected]"
]
| |
6fdc84973dc21b05bd052a39b41e700fb09348f8 | 360c777a2b77be466b1cf7c8fd74d6fd04f56b55 | /nexus_auth/utils/eventlog.py | 1f7a88e78c520a5d6577a148fd8699927ab01510 | [
"MIT"
]
| permissive | hreeder/nexus-auth | 790a3b2623ddf443138a4b0f0af1380dbc4db8ae | 8d51aef01647e32ba4a284f02de73a2caad7cf49 | refs/heads/master | 2021-01-10T10:08:37.190558 | 2016-02-29T12:27:21 | 2016-02-29T12:27:21 | 52,789,087 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 913 | py | from nexus_auth import app, db
from nexus_auth.models.logging import AuditLogEntry
import requests
def log_event(origin, action, user, message, log_db=True, log_jabber=True):
if log_db:
entry = AuditLogEntry(user_id=user.uid,
area=origin.lower(),
action_type=action.lower(),
action_item=message)
db.session.add(entry)
db.session.commit()
if log_jabber:
post_jabber(origin, user.username, message)
def post_jabber(origin, username, message):
post_url = app.config['LOGBOT']['url']
secret_key = app.config['LOGBOT']['key']
logbot_args = {
'key': secret_key,
'tag': "Nexus",
'tag2': origin,
'message': username + ": " + message
}
request = requests.request('POST', post_url, data=logbot_args)
| [
"[email protected]"
]
| |
4e3dee2f1887cb0184fd6988050a82662ecb68dd | 0a3e24df172a206a751217e5f85b334f39983101 | /Design Pattern/sub1/abstract_factory.py | 132af56149cfd33171faadea742270d4210782f1 | []
| no_license | yeboahd24/python202 | 1f399426a1f46d72da041ab3d138c582c695462d | d785a038183e52941e0cee8eb4f6cedd3c6a35ed | refs/heads/main | 2023-05-06T04:14:19.336839 | 2021-02-10T02:53:19 | 2021-02-10T02:53:19 | 309,841,303 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 647 | py | #!usr/bin/env/python3
from decimal import Decimal
class Factory(object): # acting like abstract method
def build_sequence(self):
return []
def build_number(self, string):
return Decimal(string)
class Loader(object):
def load(string, factory): # note this does not take self
sequence = factory.build_sequence() # list
for substring in string.split(','):
item = factory.build_number(substring)
sequence.append(item)
return sequence
f = Factory()
result = Loader.load('1.23, 4.56', f)
print(result)
| [
"[email protected]"
]
| |
d04e7532c40544a2e7761f2cac929b1de7fe30e9 | d7ccb4225f623139995a7039f0981e89bf6365a4 | /.history/accounts/views_20211013005910.py | e7d21f3c6c15e95c3ad3a62aa89a8a4774cf69e8 | []
| no_license | tonnymuchui/django-mall | 64fd4abc3725c1bd0a3dcf20b93b490fe9307b37 | 55c083d8433be3c77adc61939cd197902de4ce76 | refs/heads/master | 2023-08-23T04:59:20.418732 | 2021-10-13T15:59:37 | 2021-10-13T15:59:37 | 415,668,388 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 91 | py | from django.shortcuts import render
# Create your views here.
def register(register):
| [
"[email protected]"
]
| |
ff22374f949580d7d69de2945038ce61fad4d099 | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/336/usersdata/288/98639/submittedfiles/matriz2.py | 4a79841bb3410b607b59d2b22c904ae1e0d6c91f | []
| no_license | rafaelperazzo/programacao-web | 95643423a35c44613b0f64bed05bd34780fe2436 | 170dd5440afb9ee68a973f3de13a99aa4c735d79 | refs/heads/master | 2021-01-12T14:06:25.773146 | 2017-12-22T16:05:45 | 2017-12-22T16:05:45 | 69,566,344 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,087 | py | # -*- coding: utf-8 -*-
import numpy as np
cont1=0
cont2=0
cont3=0
n=int(input('Digite um valor >=2: '))
while n<2:
n=int(input('Digite um valor >=2: '))
matriz=np.empy([n,n])
matriztrans=np.empy([2,n])
matrizultprim=np.empy([n,n])
mareizdiag=np.empy([n,n])
for i in range (0,n,1):
for j in range (0,n,1):
matriz[i][j]=float(input('Digite um valor'))
for i in range (0,n,1):
for j in range (0,n,1):
matriztrans[i][i]=matriz[j][i]
for i in range (0,n,1):
for j in range (0,n,1):
matrizultprim[i][j]=matriz[i][n-1-j]
for i in range (0,n,1):
matrizdiag[0][i]=matriz[i][i]
for i in range (0,n,1):
matrizdiag[i][i]=matrizultprim[i][i]
for i in range (0,n,1):
if sum(matriz[i])==sum(matriz[i+1]):
cont1+=1
for i in range (0,n-1,1):
if sum(matriztrans[i]==sum(matriz[i+1]):
cont2+=1
if sum(matrizdiag[0])==sum(matrizdiag[1]):
cont3+=1
if cont1==n-1 and cont2==n-1 and cont3==1:
print ('S')
else:
print ('N')
print ('S')
else:
print ('N')
| [
"[email protected]"
]
| |
26a316bf7646387f30d2cf7bd6388f587906bc45 | ff7c392e46baa2774b305a4999d7dbbcf8a3c0b3 | /ask-sdk-model/ask_sdk_model/interfaces/alexa/presentation/aplt/set_value_command.py | 630771459bd51d47999d9c25bc5d678cf3ce8029 | [
"Apache-2.0"
]
| permissive | rivamarco/alexa-apis-for-python | 83d035ba5beb5838ae977777191fa41cbe4ea112 | 62e3a9057a26003e836fa09aa12a2e1c8b62d6e0 | refs/heads/master | 2021-01-03T20:44:12.977804 | 2020-02-13T10:27:27 | 2020-02-13T10:29:24 | 240,229,385 | 2 | 0 | Apache-2.0 | 2020-02-13T10:05:45 | 2020-02-13T10:05:45 | null | UTF-8 | Python | false | false | 5,843 | py | # coding: utf-8
#
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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 pprint
import re # noqa: F401
import six
import typing
from enum import Enum
from ask_sdk_model.interfaces.alexa.presentation.aplt.command import Command
if typing.TYPE_CHECKING:
from typing import Dict, List, Optional, Union
from datetime import datetime
class SetValueCommand(Command):
"""
Change a dynamic property of a component without redrawing the screen.
:param delay: The delay in milliseconds before this command starts executing; must be non-negative. Defaults to 0.
:type delay: (optional) int
:param description: A user-provided description of this command.
:type description: (optional) str
:param screen_lock: If true, disable the Interaction Timer.
:type screen_lock: (optional) bool
:param when: A conditional expression to be evaluated in device. If false, the execution of the command is skipped. Defaults to true.
:type when: (optional) bool
:param component_id: The id of the component whose value to set.
:type component_id: (optional) str
:param object_property: The name of the property to set.
:type object_property: (optional) str
:param value: The property value to set.
:type value: (optional) str
"""
deserialized_types = {
'object_type': 'str',
'delay': 'int',
'description': 'str',
'screen_lock': 'bool',
'when': 'bool',
'component_id': 'str',
'object_property': 'str',
'value': 'str'
} # type: Dict
attribute_map = {
'object_type': 'type',
'delay': 'delay',
'description': 'description',
'screen_lock': 'screenLock',
'when': 'when',
'component_id': 'componentId',
'object_property': 'property',
'value': 'value'
} # type: Dict
supports_multiple_types = False
def __init__(self, delay=None, description=None, screen_lock=None, when=None, component_id=None, object_property=None, value=None):
# type: (Optional[int], Optional[str], Optional[bool], Union[bool, str, None], Optional[str], Optional[str], Optional[str]) -> None
"""Change a dynamic property of a component without redrawing the screen.
:param delay: The delay in milliseconds before this command starts executing; must be non-negative. Defaults to 0.
:type delay: (optional) int
:param description: A user-provided description of this command.
:type description: (optional) str
:param screen_lock: If true, disable the Interaction Timer.
:type screen_lock: (optional) bool
:param when: A conditional expression to be evaluated in device. If false, the execution of the command is skipped. Defaults to true.
:type when: (optional) bool
:param component_id: The id of the component whose value to set.
:type component_id: (optional) str
:param object_property: The name of the property to set.
:type object_property: (optional) str
:param value: The property value to set.
:type value: (optional) str
"""
self.__discriminator_value = "SetValue" # type: str
self.object_type = self.__discriminator_value
super(SetValueCommand, self).__init__(object_type=self.__discriminator_value, delay=delay, description=description, screen_lock=screen_lock, when=when)
self.component_id = component_id
self.object_property = object_property
self.value = value
def to_dict(self):
# type: () -> Dict[str, object]
"""Returns the model properties as a dict"""
result = {} # type: Dict
for attr, _ in six.iteritems(self.deserialized_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 if isinstance(x, Enum) else x,
value
))
elif isinstance(value, Enum):
result[attr] = value.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[0], item[1].value)
if isinstance(item[1], Enum) else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
# type: () -> str
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
# type: () -> str
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
# type: (object) -> bool
"""Returns true if both objects are equal"""
if not isinstance(other, SetValueCommand):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
# type: (object) -> bool
"""Returns true if both objects are not equal"""
return not self == other
| [
"[email protected]"
]
| |
05448ed43b175ae1a122ed5a12db2aec2e466780 | 844501294ca37f1859b9aa0a258e6dd6b1bf2349 | /stubs/parsedatetime/pdt_locales/icu.pyi | 93e28da6e29ef5045ea2b491419e771557f51683 | [
"MIT",
"BSD-2-Clause"
]
| permissive | 1ts-org/snipe | 2ac1719bc8f6b3b158c04536464f866c34051253 | ad84a629e9084f161e0fcf811dc86ba54aaf9e2b | refs/heads/master | 2021-06-04T22:32:36.038607 | 2020-03-27T05:18:36 | 2020-04-05T21:50:42 | 18,642,653 | 6 | 3 | NOASSERTION | 2019-10-08T02:02:50 | 2014-04-10T16:01:32 | Python | UTF-8 | Python | false | false | 271 | pyi | # Stubs for parsedatetime.pdt_locales.icu (Python 3)
#
# NOTE: This dynamically typed stub was automatically generated by stubgen.
from typing import Any
def icu_object(mapping: Any): ...
def merge_weekdays(base_wd: Any, icu_wd: Any): ...
def get_icu(locale: Any): ...
| [
"[email protected]"
]
| |
62bfc768f22263927da02c41851d63ced55b971a | 4f74e6d72b98cd1da2190313e4a7eb9d342cc93d | /glitchtip/asgi.py | f479b235c07dce1d668cb26b81df241eac0257c0 | [
"BSD-3-Clause",
"MIT"
]
| permissive | adamgogogo/glitchtip-backend | ef0c529b71d5a4632a235b40a10e0b428a1cee3a | ee71d1b732d92868189d520aa111c09b116b7b22 | refs/heads/master | 2023-02-01T23:10:53.734450 | 2020-12-19T19:32:10 | 2020-12-19T19:32:10 | 323,588,534 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 395 | py | """
ASGI config for glitchtip project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'glitchtip.settings')
application = get_asgi_application()
| [
"[email protected]"
]
| |
3f77faceca54e6c9157b0bf96c05959d07e66987 | 82b946da326148a3c1c1f687f96c0da165bb2c15 | /sdk/python/pulumi_azure_native/containerregistry/v20170301/list_registry_credentials.py | e349f4d7e946280f0116c31183bbc0cfceebebcf | [
"BSD-3-Clause",
"Apache-2.0"
]
| permissive | morrell/pulumi-azure-native | 3916e978382366607f3df0a669f24cb16293ff5e | cd3ba4b9cb08c5e1df7674c1c71695b80e443f08 | refs/heads/master | 2023-06-20T19:37:05.414924 | 2021-07-19T20:57:53 | 2021-07-19T20:57:53 | 387,815,163 | 0 | 0 | Apache-2.0 | 2021-07-20T14:18:29 | 2021-07-20T14:18:28 | null | UTF-8 | Python | false | false | 2,812 | 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, overload
from ... import _utilities
from . import outputs
__all__ = [
'ListRegistryCredentialsResult',
'AwaitableListRegistryCredentialsResult',
'list_registry_credentials',
]
@pulumi.output_type
class ListRegistryCredentialsResult:
"""
The response from the ListCredentials operation.
"""
def __init__(__self__, passwords=None, username=None):
if passwords and not isinstance(passwords, list):
raise TypeError("Expected argument 'passwords' to be a list")
pulumi.set(__self__, "passwords", passwords)
if username and not isinstance(username, str):
raise TypeError("Expected argument 'username' to be a str")
pulumi.set(__self__, "username", username)
@property
@pulumi.getter
def passwords(self) -> Optional[Sequence['outputs.RegistryPasswordResponse']]:
"""
The list of passwords for a container registry.
"""
return pulumi.get(self, "passwords")
@property
@pulumi.getter
def username(self) -> Optional[str]:
"""
The username for a container registry.
"""
return pulumi.get(self, "username")
class AwaitableListRegistryCredentialsResult(ListRegistryCredentialsResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return ListRegistryCredentialsResult(
passwords=self.passwords,
username=self.username)
def list_registry_credentials(registry_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableListRegistryCredentialsResult:
"""
The response from the ListCredentials operation.
:param str registry_name: The name of the container registry.
:param str resource_group_name: The name of the resource group to which the container registry belongs.
"""
__args__ = dict()
__args__['registryName'] = registry_name
__args__['resourceGroupName'] = resource_group_name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-native:containerregistry/v20170301:listRegistryCredentials', __args__, opts=opts, typ=ListRegistryCredentialsResult).value
return AwaitableListRegistryCredentialsResult(
passwords=__ret__.passwords,
username=__ret__.username)
| [
"[email protected]"
]
| |
74f9ecaca866ae301b1a61e7b75a95e7ed37042e | 2b13d0d7df4b32c51d4d85387fb3e27f8e84084e | /my_runs/_sources/Main_0ca85520be0184e32eba926c5770d7e2.py | 325709fe6a4927c97a7aafc2f8a14c1a0ab5d377 | []
| no_license | tobystaines/MScFinalProject | 8ce0ed1a9e5ac574dc8690e0509f4b03737464c4 | e365838a51ba561de04a8004a48be043b8fb146f | refs/heads/master | 2021-06-21T15:02:34.967696 | 2019-08-20T10:05:49 | 2019-08-20T10:05:49 | 140,541,666 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 16,331 | py | import numpy as np
import tensorflow as tf
from sacred import Experiment
from sacred.observers import FileStorageObserver
import os
import errno
import datetime
import pickle
import UNet
import Dataset
ex = Experiment('UNet_Speech_Separation', interactive=True)
ex.observers.append(FileStorageObserver.create('my_runs'))
@ex.config
def cfg():
model_config = {'saving': True, # Whether to take checkpoints
'loading': True, # Whether to load an existing checkpoint
'dataset': 'both', # Choice of 'LibriSpeech', 'CHiME', or 'both'
'local_run': False, # Whether experiment is running on laptop or server
'checkpoint_to_load': "36/36-6", # Checkpoint format: run/run-epoch
'INITIALISATION_TEST': True, # Whether or not to calculate test metrics before training
'SAMPLE_RATE': 16384, # Desired sample rate of audio. Input will be resampled to this
'N_FFT': 1024, # Number of samples in each fourier transform
'FFT_HOP': 256, # Number of samples between the start of each fourier transform
'N_PARALLEL_READERS': 16,
'PATCH_WINDOW': 256, # Number of fourier transforms (rows) in each patch
'PATCH_HOP': 128, # Number of fourier transforms between the start of each patch
'BATCH_SIZE': 50, # Number of patches in each batch
'N_SHUFFLE': 1000, # Number of patches buffered before batching
'EPOCHS': 14, # Number of full passes through the dataset to train for
'EARLY_STOPPING': True, # Should validation data checks be used for early stopping?
'VAL_BY_EPOCHS': False, # Validation at end of each epoch or every 'val_iters'?
'VAL_ITERS': 3000, # Number of training iterations between validation checks,
'NUM_WORSE_VAL_CHECKS': 3, # Number of successively worse validation checks before early stopping,
'NORMALISE_MAG': True # Are magnitude spectrograms normalised in pre-processing?
}
if model_config['local_run']: # Data and Checkpoint directories on my laptop
model_config['data_root'] = 'C:/Users/Toby/MSc_Project/Test_Audio/CHiME/'
model_config['model_base_dir'] = 'C:/Users/Toby/MSc_Project/MScFinalProjectCheckpoints'
model_config['log_dir'] = 'logs/local'
else: # Data and Checkpoint directories on the uni server
model_config['chime_data_root'] = '/data/Speech_Data/CHiME3/data/audio/16kHz/isolated/'
#model_config['librispeech_data_root'] = 'C:/Users/Toby/Speech_Data/LibriSpeech/'
model_config['librispeech_data_root'] = '/data/Speech_Data/LibriSpeech/'
#model_config['model_base_dir'] = 'C:/Users/Toby/MSc_Project/MScFinalProjectCheckpoints'
model_config['model_base_dir'] = '/home/enterprise.internal.city.ac.uk/acvn728/checkpoints'
model_config['log_dir'] = 'logs/ssh'
@ex.capture
def train(sess, model, model_config, model_folder, handle, training_iterator, training_handle, validation_iterator,
validation_handle, writer):
def validation(last_val_cost, min_val_cost, min_val_check, worse_val_checks, model, val_check):
print('Validating')
sess.run(validation_iterator.initializer)
val_costs = list()
val_iteration = 1
print('{ts}:\tEntering validation loop'.format(ts=datetime.datetime.now()))
while True:
try:
val_cost = sess.run(model.cost, {model.is_training: False, handle: validation_handle})
val_costs.append(val_cost)
if val_iteration % 200 == 0:
print("{ts}:\tValidation iteration: {i}, Loss: {vc}".format(ts=datetime.datetime.now(),
i=val_iteration, vc=val_cost))
val_iteration += 1
except tf.errors.OutOfRangeError:
# Calculate and record mean loss over validation dataset
val_check_mean_cost = sum(val_costs) / len(val_costs)
print('Validation check mean loss: {l}'.format(l=val_check_mean_cost))
summary = tf.Summary(
value=[tf.Summary.Value(tag='Validation_mean_loss', simple_value=val_check_mean_cost)])
writer.add_summary(summary, val_check)
# If validation loss has worsened increment the counter, else, reset the counter
if val_check_mean_cost > last_val_cost:
worse_val_checks += 1
print('Validation loss has worsened. worse_val_checks = {w}'.format(w=worse_val_checks))
else:
worse_val_checks = 0
print('Validation loss has improved!')
if val_check_mean_cost < min_val_cost:
min_val_cost = val_check_mean_cost
print('New best validation cost!')
min_val_check = val_check
last_val_cost = val_check_mean_cost
break
return last_val_cost, min_val_cost, min_val_check, worse_val_checks
print('Starting training')
# Initialise variables and define summary
epoch = 1
iteration = 1
last_val_cost = 1
min_val_cost = 1
min_val_check = None
val_check = 1
worse_val_checks = 0
#best_model = model
cost_summary = tf.summary.scalar('Training_loss', model.cost)
mix_summary = tf.summary.image('Mixture', model.mixed_mag)
voice_summary = tf.summary.image('Voice', model.voice_mag)
mask_summary = tf.summary.image('Voice_Mask', model.voice_mask)
gen_voice_summary = tf.summary.image('Generated_Voice', model.gen_voice)
saver = tf.train.Saver(tf.global_variables(), max_to_keep=3, write_version=tf.train.SaverDef.V2)
sess.run(training_iterator.initializer)
# Begin training loop
# Train for the specified number of epochs, unless early stopping is triggered
while epoch < model_config['EPOCHS'] + 1 and worse_val_checks < model_config['NUM_WORSE_VAL_CHECKS']:
try:
_, cost, cost_sum, mix, voice, mask, gen_voice = sess.run([model.train_op, model.cost, cost_summary,
mix_summary, voice_summary, mask_summary,
gen_voice_summary], {model.is_training: True,
handle: training_handle})
writer.add_summary(cost_sum, iteration) # Record the loss at each iteration
if iteration % 200 == 0:
print("{ts}:\tTraining iteration: {i}, Loss: {c}".format(ts=datetime.datetime.now(),
i=iteration, c=cost))
# If using early stopping by iterations, enter validation loop
if model_config['EARLY_STOPPING'] and not model_config['VAL_BY_EPOCHS'] and iteration % model_config['VAL_ITERS'] == 0:
last_val_cost, min_val_cost, min_val_check, worse_val_checks = validation(last_val_cost,
min_val_cost,
min_val_check,
worse_val_checks,
model,
val_check)
val_check += 1
iteration += 1
# When the dataset is exhausted, note the end of the epoch
except tf.errors.OutOfRangeError:
print('{ts}:\tEpoch {e} finished after {i} iterations.'.format(ts=datetime.datetime.now(),
e=epoch, i=iteration))
try:
writer.add_summary(mix, iteration)
writer.add_summary(voice, iteration)
writer.add_summary(mask, iteration)
writer.add_summary(gen_voice, iteration)
except NameError: # Indicates the try has not been successfully executed at all
print('No images to record')
break
epoch += 1
# If using early stopping by epochs, enter validation loop
if model_config['EARLY_STOPPING'] and model_config['VAL_BY_EPOCHS'] and iteration > 1:
last_val_cost, min_val_cost, min_val_check, worse_val_checks = validation(last_val_cost,
min_val_cost,
min_val_check,
worse_val_checks,
model,
val_check)
val_check += 1
if model_config['saving']:
# Make sure there is a folder to save the checkpoint in
checkpoint_path = os.path.join(model_config["model_base_dir"], model_folder)
try:
os.makedirs(checkpoint_path)
except OSError as e:
if e.errno != errno.EEXIST:
raise
print('Checkpoint')
saver.save(sess, os.path.join(checkpoint_path, model_folder), global_step=int(epoch))
sess.run(training_iterator.initializer)
if model_config['EARLY_STOPPING'] and worse_val_checks >= model_config['NUM_WORSE_VAL_CHECKS']:
print('Stopped early due to validation criteria.')
else:
# Final validation check
if (iteration % model_config['VAL_ITERS'] != 1 or not model_config['EARLY_STOPPING']) and not model_config['VAL_BY_EPOCHS']:
last_val_cost, min_val_cost, min_val_check, _ = validation(last_val_cost, min_val_cost, min_val_check,
worse_val_checks, model, val_check)
print('Finished requested number of epochs. Training complete.')
print('Final validation loss: {lvc}'.format(lvc=last_val_cost))
if last_val_cost == min_val_cost:
print('This was the best validation loss achieved')
else:
print('Best validation loss ({mvc}) achieved at validation check {mvck}'.format(mvc=min_val_cost,
mvck=min_val_check))
#model = best_model
return model
@ex.capture
def test(sess, model, model_config, handle, testing_iterator, testing_handle, writer, test_count, experiment_id):
dump_folder = 'dumps/' + str(experiment_id)
if not os.path.isdir(dump_folder):
os.mkdir(dump_folder)
# Calculate L1 loss
print('Starting testing')
sess.run(testing_iterator.initializer)
iteration = 0
test_costs = list()
print('{ts}:\tEntering test loop'.format(ts=datetime.datetime.now()))
while True:
try:
cost, voice_est_mag, voice, mixed_audio, mixed_phase = sess.run([model.cost, model.gen_voice,
model.voice_audio, model.mixed_audio,
model.mixed_phase], {model.is_training: False,
handle: testing_handle})
results = (cost, voice_est_mag, voice, mixed_audio, mixed_phase, model_config)
test_costs.append(cost)
dump_name = dump_folder + '/test_count_' + str(test_count) + '_iteration_' + str(iteration)
pickle.dump(results, open(dump_name, 'wb'))
if iteration % 200 == 0:
print("{ts}:\tTesting iteration: {i}, Loss: {c}".format(ts=datetime.datetime.now(),
i=iteration, c=cost))
iteration += 1
except tf.errors.OutOfRangeError:
# At the end of the dataset, calculate, record and print mean results
mean_cost = sum(test_costs) / len(test_costs)
print('Test pass complete\n'
'Mean loss over test set: {}\n'
'Data saved to {} for later audio metric calculation'.format(mean_cost, dump_folder))
break
test_count += 1
return mean_cost, test_count
@ex.automain
def do_experiment(model_config):
tf.reset_default_graph()
experiment_id = ex.current_run._id
print('Experiment ID: {eid}'.format(eid=experiment_id))
# Prepare data
print('Preparing dataset')
train_data, val_data, test_data = Dataset.prepare_datasets(model_config)
print('Dataset ready')
# Start session
tf_config = tf.ConfigProto()
#tf_config.gpu_options.allow_growth = True
tf_config.gpu_options.visible_device_list = "1"
sess = tf.Session(config=tf_config)
#sess = tf.Session()
print('Session started')
# Create iterators
handle = tf.placeholder(tf.string, shape=[])
iterator = tf.data.Iterator.from_string_handle(handle, train_data.output_types, train_data.output_shapes)
mixed_spec, voice_spec, mixed_audio, voice_audio = iterator.get_next()
training_iterator = train_data.make_initializable_iterator()
validation_iterator = val_data.make_initializable_iterator()
testing_iterator = test_data.make_initializable_iterator()
training_handle = sess.run(training_iterator.string_handle())
validation_handle = sess.run(validation_iterator.string_handle())
testing_handle = sess.run(testing_iterator.string_handle())
print('Iterators created')
# Create variable placeholders
is_training = tf.placeholder(shape=(), dtype=bool)
mixed_mag = tf.expand_dims(mixed_spec[:, :, :-1, 0], 3)
mixed_phase = tf.expand_dims(mixed_spec[:, :, :-1, 1], 3)
voice_mag = tf.expand_dims(voice_spec[:, :, :-1, 0], 3)
# Build U-Net model
print('Creating model')
model = UNet.UNetModel(mixed_mag, voice_mag, mixed_phase, mixed_audio, voice_audio, 'unet', is_training, name='U_Net_Model')
sess.run(tf.global_variables_initializer())
if model_config['loading']:
# TODO - Think this works now but needs proper testing
print('Loading checkpoint')
checkpoint = os.path.join(model_config['model_base_dir'], model_config['checkpoint_to_load'])
restorer = tf.train.Saver()
restorer.restore(sess, checkpoint)
# Summaries
model_folder = str(experiment_id)
writer = tf.summary.FileWriter(os.path.join(model_config["log_dir"], model_folder), graph=sess.graph)
# Get baseline metrics at initialisation
test_count = 0
if model_config['INITIALISATION_TEST']:
print('Running initialisation test')
initial_test_loss, test_count = test(sess, model, model_config, handle, testing_iterator, testing_handle,
writer, test_count, experiment_id)
# Train the model
model = train(sess, model, model_config, model_folder, handle, training_iterator, training_handle,
validation_iterator, validation_handle, writer)
# Test trained model
mean_test_loss, test_count = test(sess, model, model_config, handle, testing_iterator, testing_handle, writer,
test_count, experiment_id)
print('{ts}:\n\tAll done!'.format(ts=datetime.datetime.now()))
if model_config['INITIALISATION_TEST']:
print('\tInitial test loss: {init}'.format(init=initial_test_loss))
print('\tFinal test loss: {final}'.format(final=mean_test_loss))
| [
"[email protected]"
]
| |
02021ac93fca1584a2349483cd7570d2f89723d1 | 82b946da326148a3c1c1f687f96c0da165bb2c15 | /sdk/python/pulumi_azure_native/apimanagement/v20180601preview/get_api.py | 93062e0ebfbfb10e03747f5860446f007966ef4e | [
"BSD-3-Clause",
"Apache-2.0"
]
| permissive | morrell/pulumi-azure-native | 3916e978382366607f3df0a669f24cb16293ff5e | cd3ba4b9cb08c5e1df7674c1c71695b80e443f08 | refs/heads/master | 2023-06-20T19:37:05.414924 | 2021-07-19T20:57:53 | 2021-07-19T20:57:53 | 387,815,163 | 0 | 0 | Apache-2.0 | 2021-07-20T14:18:29 | 2021-07-20T14:18:28 | null | UTF-8 | Python | false | false | 12,915 | 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, overload
from ... import _utilities
from . import outputs
__all__ = [
'GetApiResult',
'AwaitableGetApiResult',
'get_api',
]
@pulumi.output_type
class GetApiResult:
"""
API details.
"""
def __init__(__self__, api_revision=None, api_revision_description=None, api_type=None, api_version=None, api_version_description=None, api_version_set=None, api_version_set_id=None, authentication_settings=None, description=None, display_name=None, id=None, is_current=None, is_online=None, name=None, path=None, protocols=None, service_url=None, subscription_key_parameter_names=None, subscription_required=None, type=None):
if api_revision and not isinstance(api_revision, str):
raise TypeError("Expected argument 'api_revision' to be a str")
pulumi.set(__self__, "api_revision", api_revision)
if api_revision_description and not isinstance(api_revision_description, str):
raise TypeError("Expected argument 'api_revision_description' to be a str")
pulumi.set(__self__, "api_revision_description", api_revision_description)
if api_type and not isinstance(api_type, str):
raise TypeError("Expected argument 'api_type' to be a str")
pulumi.set(__self__, "api_type", api_type)
if api_version and not isinstance(api_version, str):
raise TypeError("Expected argument 'api_version' to be a str")
pulumi.set(__self__, "api_version", api_version)
if api_version_description and not isinstance(api_version_description, str):
raise TypeError("Expected argument 'api_version_description' to be a str")
pulumi.set(__self__, "api_version_description", api_version_description)
if api_version_set and not isinstance(api_version_set, dict):
raise TypeError("Expected argument 'api_version_set' to be a dict")
pulumi.set(__self__, "api_version_set", api_version_set)
if api_version_set_id and not isinstance(api_version_set_id, str):
raise TypeError("Expected argument 'api_version_set_id' to be a str")
pulumi.set(__self__, "api_version_set_id", api_version_set_id)
if authentication_settings and not isinstance(authentication_settings, dict):
raise TypeError("Expected argument 'authentication_settings' to be a dict")
pulumi.set(__self__, "authentication_settings", authentication_settings)
if description and not isinstance(description, str):
raise TypeError("Expected argument 'description' to be a str")
pulumi.set(__self__, "description", description)
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 is_current and not isinstance(is_current, bool):
raise TypeError("Expected argument 'is_current' to be a bool")
pulumi.set(__self__, "is_current", is_current)
if is_online and not isinstance(is_online, bool):
raise TypeError("Expected argument 'is_online' to be a bool")
pulumi.set(__self__, "is_online", is_online)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if path and not isinstance(path, str):
raise TypeError("Expected argument 'path' to be a str")
pulumi.set(__self__, "path", path)
if protocols and not isinstance(protocols, list):
raise TypeError("Expected argument 'protocols' to be a list")
pulumi.set(__self__, "protocols", protocols)
if service_url and not isinstance(service_url, str):
raise TypeError("Expected argument 'service_url' to be a str")
pulumi.set(__self__, "service_url", service_url)
if subscription_key_parameter_names and not isinstance(subscription_key_parameter_names, dict):
raise TypeError("Expected argument 'subscription_key_parameter_names' to be a dict")
pulumi.set(__self__, "subscription_key_parameter_names", subscription_key_parameter_names)
if subscription_required and not isinstance(subscription_required, bool):
raise TypeError("Expected argument 'subscription_required' to be a bool")
pulumi.set(__self__, "subscription_required", subscription_required)
if type and not isinstance(type, str):
raise TypeError("Expected argument 'type' to be a str")
pulumi.set(__self__, "type", type)
@property
@pulumi.getter(name="apiRevision")
def api_revision(self) -> Optional[str]:
"""
Describes the Revision of the Api. If no value is provided, default revision 1 is created
"""
return pulumi.get(self, "api_revision")
@property
@pulumi.getter(name="apiRevisionDescription")
def api_revision_description(self) -> Optional[str]:
"""
Description of the Api Revision.
"""
return pulumi.get(self, "api_revision_description")
@property
@pulumi.getter(name="apiType")
def api_type(self) -> Optional[str]:
"""
Type of API.
"""
return pulumi.get(self, "api_type")
@property
@pulumi.getter(name="apiVersion")
def api_version(self) -> Optional[str]:
"""
Indicates the Version identifier of the API if the API is versioned
"""
return pulumi.get(self, "api_version")
@property
@pulumi.getter(name="apiVersionDescription")
def api_version_description(self) -> Optional[str]:
"""
Description of the Api Version.
"""
return pulumi.get(self, "api_version_description")
@property
@pulumi.getter(name="apiVersionSet")
def api_version_set(self) -> Optional['outputs.ApiVersionSetContractDetailsResponse']:
"""
An API Version Set contains the common configuration for a set of API Versions relating
"""
return pulumi.get(self, "api_version_set")
@property
@pulumi.getter(name="apiVersionSetId")
def api_version_set_id(self) -> Optional[str]:
"""
A resource identifier for the related ApiVersionSet.
"""
return pulumi.get(self, "api_version_set_id")
@property
@pulumi.getter(name="authenticationSettings")
def authentication_settings(self) -> Optional['outputs.AuthenticationSettingsContractResponse']:
"""
Collection of authentication settings included into this API.
"""
return pulumi.get(self, "authentication_settings")
@property
@pulumi.getter
def description(self) -> Optional[str]:
"""
Description of the API. May include HTML formatting tags.
"""
return pulumi.get(self, "description")
@property
@pulumi.getter(name="displayName")
def display_name(self) -> Optional[str]:
"""
API name.
"""
return pulumi.get(self, "display_name")
@property
@pulumi.getter
def id(self) -> str:
"""
Resource ID.
"""
return pulumi.get(self, "id")
@property
@pulumi.getter(name="isCurrent")
def is_current(self) -> bool:
"""
Indicates if API revision is current api revision.
"""
return pulumi.get(self, "is_current")
@property
@pulumi.getter(name="isOnline")
def is_online(self) -> bool:
"""
Indicates if API revision is accessible via the gateway.
"""
return pulumi.get(self, "is_online")
@property
@pulumi.getter
def name(self) -> str:
"""
Resource name.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def path(self) -> str:
"""
Relative URL uniquely identifying this API and all of its resource paths within the API Management service instance. It is appended to the API endpoint base URL specified during the service instance creation to form a public URL for this API.
"""
return pulumi.get(self, "path")
@property
@pulumi.getter
def protocols(self) -> Optional[Sequence[str]]:
"""
Describes on which protocols the operations in this API can be invoked.
"""
return pulumi.get(self, "protocols")
@property
@pulumi.getter(name="serviceUrl")
def service_url(self) -> Optional[str]:
"""
Absolute URL of the backend service implementing this API.
"""
return pulumi.get(self, "service_url")
@property
@pulumi.getter(name="subscriptionKeyParameterNames")
def subscription_key_parameter_names(self) -> Optional['outputs.SubscriptionKeyParameterNamesContractResponse']:
"""
Protocols over which API is made available.
"""
return pulumi.get(self, "subscription_key_parameter_names")
@property
@pulumi.getter(name="subscriptionRequired")
def subscription_required(self) -> Optional[bool]:
"""
Specifies whether an API or Product subscription is required for accessing the API.
"""
return pulumi.get(self, "subscription_required")
@property
@pulumi.getter
def type(self) -> str:
"""
Resource type for API Management resource.
"""
return pulumi.get(self, "type")
class AwaitableGetApiResult(GetApiResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetApiResult(
api_revision=self.api_revision,
api_revision_description=self.api_revision_description,
api_type=self.api_type,
api_version=self.api_version,
api_version_description=self.api_version_description,
api_version_set=self.api_version_set,
api_version_set_id=self.api_version_set_id,
authentication_settings=self.authentication_settings,
description=self.description,
display_name=self.display_name,
id=self.id,
is_current=self.is_current,
is_online=self.is_online,
name=self.name,
path=self.path,
protocols=self.protocols,
service_url=self.service_url,
subscription_key_parameter_names=self.subscription_key_parameter_names,
subscription_required=self.subscription_required,
type=self.type)
def get_api(api_id: Optional[str] = None,
resource_group_name: Optional[str] = None,
service_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetApiResult:
"""
API details.
:param str api_id: API revision identifier. Must be unique in the current API Management service instance. Non-current revision has ;rev=n as a suffix where n is the revision number.
:param str resource_group_name: The name of the resource group.
:param str service_name: The name of the API Management service.
"""
__args__ = dict()
__args__['apiId'] = api_id
__args__['resourceGroupName'] = resource_group_name
__args__['serviceName'] = service_name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-native:apimanagement/v20180601preview:getApi', __args__, opts=opts, typ=GetApiResult).value
return AwaitableGetApiResult(
api_revision=__ret__.api_revision,
api_revision_description=__ret__.api_revision_description,
api_type=__ret__.api_type,
api_version=__ret__.api_version,
api_version_description=__ret__.api_version_description,
api_version_set=__ret__.api_version_set,
api_version_set_id=__ret__.api_version_set_id,
authentication_settings=__ret__.authentication_settings,
description=__ret__.description,
display_name=__ret__.display_name,
id=__ret__.id,
is_current=__ret__.is_current,
is_online=__ret__.is_online,
name=__ret__.name,
path=__ret__.path,
protocols=__ret__.protocols,
service_url=__ret__.service_url,
subscription_key_parameter_names=__ret__.subscription_key_parameter_names,
subscription_required=__ret__.subscription_required,
type=__ret__.type)
| [
"[email protected]"
]
| |
2e9f9655ca4058857243f10f5a530a99417d7011 | 70f1c694bea6178c98b134b9c44952ef6693be9f | /CAAS/ReNameSRA_RelocaTEi_ReRunOnResults.py | 25ba7a64d511690710dea248e4e0a2a1f10ef582 | []
| no_license | JinfengChen/Rice_pop | 5c19c5837805e51ddb3b2ffba4baffdc59c9bfd3 | ef272bf4825b29610c94de55eb53f231fb5febc6 | refs/heads/master | 2020-04-07T04:55:36.606594 | 2018-03-02T16:52:53 | 2018-03-02T16:52:53 | 33,501,941 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,540 | py | #!/opt/Python/2.7.3/bin/python
import sys
from collections import defaultdict
import numpy as np
import re
import os
import argparse
import glob
import time
from Bio import SeqIO
def usage():
test="name"
message='''
python ReNameSRA_RelocaTEi.py --input Japonica_fastq
Run RelocaTEi for rice strain in Japonica_fastq
'''
print message
def runjob(script, lines):
cmd = 'perl /rhome/cjinfeng/BigData/software/bin/qsub-pbs.pl --maxjob 80 --lines %s --interval 120 --resource nodes=1:ppn=1,walltime=100:00:00,mem=10G --convert no %s' %(lines, script)
#print cmd
os.system(cmd)
def fasta_id(fastafile):
fastaid = defaultdict(str)
for record in SeqIO.parse(fastafile,"fasta"):
fastaid[record.id] = 1
return fastaid
def readtable(infile):
data = defaultdict(str)
with open (infile, 'r') as filehd:
for line in filehd:
line = line.rstrip()
if len(line) > 2:
unit = re.split(r' ',line)
data[unit[0]] = line
#print unit[0], line
return data
def rerun_shell(outfile, script, topdir):
script_cmd = readtable(script)
script_list= re.split(r' ', script_cmd['python'])
script_list[1] = '/rhome/cjinfeng/BigData/00.RD/RelocaTE2_mPing/scripts/relocaTE_absenceFinder.py'
ofile = open(outfile, 'w')
for i in range(1,13):
script_list[3] = 'Chr%s' %(i)
cmd = ' '.join(script_list)
cmd = re.sub(r'.RepeatMasker.out', r'.mPing.RepeatMasker.out', cmd)
cmd = re.sub(r'/shared/wesslerlab/', r'/bigdata/wesslerlab/shared/', cmd)
print >> ofile, cmd
print >> ofile, 'cat %s/repeat/results/*.all_ref_insert.txt > %s/repeat/results/ALL.all_ref_insert.txt' %(topdir, topdir)
print >> ofile, 'cat %s/repeat/results/*.all_ref_insert.gff > %s/repeat/results/ALL.all_ref_insert.gff' %(topdir, topdir)
ofile.close()
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input')
parser.add_argument('-o', '--output')
parser.add_argument('-g', '--genome')
parser.add_argument('-r', '--repeat')
parser.add_argument('-v', dest='verbose', action='store_true')
args = parser.parse_args()
try:
len(args.input) > 0
except:
usage()
sys.exit(2)
if not args.output:
args.output = '%s' %(os.path.abspath(args.input))
if not args.genome:
args.genome = '/rhome/cjinfeng/BigData/00.RD/RelocaTE_i/Simulation/Reference/MSU_r7.fa'
if not args.repeat:
args.repeat = '/rhome/cjinfeng/BigData/00.RD/RelocaTE_i/Simulation/Reference/ping.fa'
#args.repeat = '/rhome/cjinfeng/BigData/00.RD/RelocaTE_i/Simulation/Reference/Rice.TE.short.unique.fa'
#-t ../input/mping_UNK.fa -g /rhome/cjinfeng/HEG4_cjinfeng/seqlib/MSU_r7.fa -d ../input/FC52_7 -e HEG4 -o mPing_HEG4_UNK -r 1 -p 1 -a 1
#RelocaTE = 'python /rhome/cjinfeng/software/tools/RelocaTE_1.0.3_i/RelocaTE/scripts/relocaTE.py'
#RelocaTE = 'python /rhome/cjinfeng/BigData/00.RD/RelocaTE2/scripts/relocaTE.py'
RelocaTE = 'python /rhome/cjinfeng/BigData/00.RD/RelocaTE2_mPing/scripts/relocaTE.py'
Reference= os.path.abspath(args.genome)
Repeat = os.path.abspath(args.repeat)
project = os.path.split(args.output)[1]
cpu = 16
if not os.path.exists(project):
os.mkdir(project)
print project
read_dirs = glob.glob('%s/ERS*' %(os.path.abspath(args.input)))
ofile = open('%s.run.sh' %(args.output), 'w')
for read_dir in sorted(read_dirs):
outdir = '%s/%s' %(os.path.abspath(args.output), os.path.split(read_dir)[1])
existingTE = '%s.mPing.RepeatMasker.out' %(Reference)
# relocate will not run if there is result exists
#if not os.path.exists(outdir):
if 1:
#relocaTE = '%s --te_fasta %s --genome_fasta %s --fq_dir %s --outdir %s --reference_ins %s' %(RelocaTE, Repeat, Reference, read_dir, outdir, existingTE)
os.system('cp /rhome/cjinfeng/Rice/Rice_population_sequence/Rice_3000/CAAS/existingTE.bed %s/repeat/' %(outdir))
rerun_shell('%s/run_these_jobs_rerun.sh' %(outdir), '%s/shellscripts/step_6/0.repeat.absence.sh' %(outdir), outdir)
shell = 'bash %s/run_these_jobs_rerun.sh > %s/run.log 2> %s/run.log2' %(outdir, outdir, outdir)
#os.system(relocaTE)
#print >> ofile, relocaTE
print >> ofile, shell
ofile.close()
runjob('%s.run.sh' %(args.output), 20)
if __name__ == '__main__':
main()
| [
"[email protected]"
]
| |
dc21944a63569648b8573e6a433f04b29ad4e6be | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/nouns/_mac.py | 5e19d494c3783030806afa034e10968ddcfdb409 | [
"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 | 342 | py |
#calss header
class _MAC():
def __init__(self,):
self.name = "MAC"
self.definitions = [u'a waterproof coat (= one that does not allow rain to pass through): ']
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.specie = 'nouns'
def run(self, obj1 = [], obj2 = []):
return self.jsondata
| [
"[email protected]"
]
| |
70f2b9210119f2d5879668567b0e9e207d2bba8e | 2153a7ecfa69772797e379ff5642d52072a69b7c | /library/test/test_compiler/testcorpus/74_class_super_nested.py | a1686c98c0d832a9bd8aedfe422ee687411b168b | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"Python-2.0"
]
| permissive | KCreate/skybison | a3789c84541f39dc6f72d4d3eb9783b9ed362934 | d1740e08d8de85a0a56b650675717da67de171a0 | refs/heads/trunk | 2023-07-26T04:50:55.898224 | 2021-08-31T08:20:46 | 2021-09-02T19:25:08 | 402,908,053 | 1 | 0 | NOASSERTION | 2021-09-03T22:05:57 | 2021-09-03T22:05:57 | null | UTF-8 | Python | false | false | 212 | py | # Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com)
def fun():
class Foo:
def __init__(self):
super().__init__()
def no_super(self):
return
| [
"[email protected]"
]
| |
fff36f777febf189bd59b825f350b690367de7e3 | f64aaa4b0f78774464033148290a13453c96528e | /generated/intermediate/ansible-module-sdk/azure_rm_apimanagementapioperation_info.py | 5609631c7061089b2d3158989eb60ef08ef6b8e4 | [
"MIT"
]
| permissive | audevbot/autorest.cli.debug | e8996270a6a931f243532f65782c7f8fbb1b55c6 | a507fb6e2dd7826212537f27d583f203aac1c28f | refs/heads/master | 2020-06-04T05:25:17.018993 | 2019-08-27T21:57:18 | 2019-08-27T21:57:18 | 191,876,321 | 0 | 0 | MIT | 2019-08-28T05:57:19 | 2019-06-14T04:35:39 | Python | UTF-8 | Python | false | false | 15,795 | py | #!/usr/bin/python
#
# Copyright (c) 2019 Zim Kalinowski, (@zikalino)
#
# 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
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: azure_rm_apimanagementapioperation_info
version_added: '2.9'
short_description: Get ApiOperation info.
description:
- Get info of ApiOperation.
options:
resource_group:
description:
- The name of the resource group.
required: true
type: str
service_name:
description:
- The name of the API Management service.
required: true
type: str
api_id:
description:
- >-
API revision identifier. Must be unique in the current API Management
service instance. Non-current revision has ;rev=n as a suffix where n is
the revision number.
required: true
type: str
operation_id:
description:
- >-
Operation identifier within an API. Must be unique in the current API
Management service instance.
type: str
id:
description:
- Resource ID.
type: str
name:
description:
- Resource name.
type: str
type:
description:
- Resource type for API Management resource.
type: str
template_parameters:
description:
- Collection of URL template parameters.
type: list
suboptions:
name:
description:
- Parameter name.
required: true
type: str
description:
description:
- Parameter description.
type: str
type:
description:
- Parameter type.
required: true
type: str
default_value:
description:
- Default parameter value.
type: str
required:
description:
- Specifies whether parameter is required or not.
type: boolean
values:
description:
- Parameter values.
type: list
description:
description:
- Description of the operation. May include HTML formatting tags.
type: str
request:
description:
- An entity containing request details.
type: dict
suboptions:
description:
description:
- Operation request description.
type: str
query_parameters:
description:
- Collection of operation request query parameters.
type: list
suboptions:
name:
description:
- Parameter name.
required: true
type: str
description:
description:
- Parameter description.
type: str
type:
description:
- Parameter type.
required: true
type: str
default_value:
description:
- Default parameter value.
type: str
required:
description:
- Specifies whether parameter is required or not.
type: boolean
values:
description:
- Parameter values.
type: list
headers:
description:
- Collection of operation request headers.
type: list
suboptions:
name:
description:
- Parameter name.
required: true
type: str
description:
description:
- Parameter description.
type: str
type:
description:
- Parameter type.
required: true
type: str
default_value:
description:
- Default parameter value.
type: str
required:
description:
- Specifies whether parameter is required or not.
type: boolean
values:
description:
- Parameter values.
type: list
representations:
description:
- Collection of operation request representations.
type: list
suboptions:
content_type:
description:
- >-
Specifies a registered or custom content type for this
representation, e.g. application/xml.
required: true
type: str
sample:
description:
- An example of the representation.
type: str
schema_id:
description:
- >-
Schema identifier. Applicable only if 'contentType' value is
neither 'application/x-www-form-urlencoded' nor
'multipart/form-data'.
type: str
type_name:
description:
- >-
Type name defined by the schema. Applicable only if
'contentType' value is neither
'application/x-www-form-urlencoded' nor 'multipart/form-data'.
type: str
form_parameters:
description:
- >-
Collection of form parameters. Required if 'contentType' value
is either 'application/x-www-form-urlencoded' or
'multipart/form-data'..
type: list
suboptions:
name:
description:
- Parameter name.
required: true
type: str
description:
description:
- Parameter description.
type: str
type:
description:
- Parameter type.
required: true
type: str
default_value:
description:
- Default parameter value.
type: str
required:
description:
- Specifies whether parameter is required or not.
type: boolean
values:
description:
- Parameter values.
type: list
responses:
description:
- Array of Operation responses.
type: list
suboptions:
status_code:
description:
- Operation response HTTP status code.
required: true
type: number
description:
description:
- Operation response description.
type: str
representations:
description:
- Collection of operation response representations.
type: list
suboptions:
content_type:
description:
- >-
Specifies a registered or custom content type for this
representation, e.g. application/xml.
required: true
type: str
sample:
description:
- An example of the representation.
type: str
schema_id:
description:
- >-
Schema identifier. Applicable only if 'contentType' value is
neither 'application/x-www-form-urlencoded' nor
'multipart/form-data'.
type: str
type_name:
description:
- >-
Type name defined by the schema. Applicable only if
'contentType' value is neither
'application/x-www-form-urlencoded' nor 'multipart/form-data'.
type: str
form_parameters:
description:
- >-
Collection of form parameters. Required if 'contentType' value
is either 'application/x-www-form-urlencoded' or
'multipart/form-data'..
type: list
suboptions:
name:
description:
- Parameter name.
required: true
type: str
description:
description:
- Parameter description.
type: str
type:
description:
- Parameter type.
required: true
type: str
default_value:
description:
- Default parameter value.
type: str
required:
description:
- Specifies whether parameter is required or not.
type: boolean
values:
description:
- Parameter values.
type: list
headers:
description:
- Collection of operation response headers.
type: list
suboptions:
name:
description:
- Parameter name.
required: true
type: str
description:
description:
- Parameter description.
type: str
type:
description:
- Parameter type.
required: true
type: str
default_value:
description:
- Default parameter value.
type: str
required:
description:
- Specifies whether parameter is required or not.
type: boolean
values:
description:
- Parameter values.
type: list
policies:
description:
- Operation Policies
type: str
display_name:
description:
- Operation Name.
required: true
type: str
method:
description:
- >-
A Valid HTTP Operation Method. Typical Http Methods like GET, PUT, POST
but not limited by only them.
required: true
type: str
url_template:
description:
- >-
Relative URL template identifying the target resource for this
operation. May include parameters. Example:
/customers/{cid}/orders/{oid}/?date={date}
required: true
type: str
extends_documentation_fragment:
- azure
author:
- Zim Kalinowski (@zikalino)
'''
EXAMPLES = '''
- name: ApiManagementListApiOperations
azure_rm_apimanagementapioperation_info:
resource_group: myResourceGroup
service_name: myService
api_id: myApi
operation_id: 57d2ef278aa04f0ad01d6cdc
- name: ApiManagementGetApiOperation
azure_rm_apimanagementapioperation_info:
resource_group: myResourceGroup
service_name: myService
api_id: myApi
operation_id: myOperation
- name: ApiManagementGetApiOperationPetStore
azure_rm_apimanagementapioperation_info:
resource_group: myResourceGroup
service_name: myService
api_id: myApi
operation_id: myOperation
'''
RETURN = '''
api_operation:
description: >-
A list of dict results where the key is the name of the ApiOperation and the
values are the facts for that ApiOperation.
returned: always
type: complex
contains:
apioperation_name:
description: The key is the name of the server that the values relate to.
type: complex
contains:
id:
description:
- Resource ID.
returned: always
type: str
sample: null
name:
description:
- Resource name.
returned: always
type: str
sample: null
type:
description:
- Resource type for API Management resource.
returned: always
type: str
sample: null
properties:
description:
- Properties of the Operation Contract.
returned: always
type: dict
sample: null
'''
import time
import json
from ansible.module_utils.azure_rm_common import AzureRMModuleBase
from copy import deepcopy
try:
from msrestazure.azure_exceptions import CloudError
from azure.mgmt.apimanagement import ApiManagementClient
from msrestazure.azure_operation import AzureOperationPoller
from msrest.polling import LROPoller
except ImportError:
# This is handled in azure_rm_common
pass
class AzureRMApiOperationInfo(AzureRMModuleBase):
def __init__(self):
self.module_arg_spec = dict(
resource_group=dict(
type='str',
required=true
),
service_name=dict(
type='str',
required=true
),
api_id=dict(
type='str',
required=true
),
operation_id=dict(
type='str'
)
)
self.resource_group = None
self.service_name = None
self.api_id = None
self.tags = None
self.operation_id = None
self.id = None
self.name = None
self.type = None
self.properties = None
self.results = dict(changed=False)
self.mgmt_client = None
self.state = None
self.url = None
self.status_code = [200]
self.query_parameters = {}
self.query_parameters['api-version'] = '2019-01-01'
self.header_parameters = {}
self.header_parameters['Content-Type'] = 'application/json; charset=utf-8'
self.mgmt_client = None
super(AzureRMApiOperationInfo, self).__init__(self.module_arg_spec, supports_tags=True)
def exec_module(self, **kwargs):
for key in self.module_arg_spec:
setattr(self, key, kwargs[key])
self.mgmt_client = self.get_mgmt_svc_client(ApiManagementClientClient,
base_url=self._cloud_environment.endpoints.resource_manager)
if (self.resource_group is not None and
self.service_name is not None and
self.api_id is not None and
self.operation_id is not None):
self.results['api_operation'] = self.format_item(self.get())
elif (self.resource_group is not None and
self.service_name is not None and
self.api_id is not None):
self.results['api_operation'] = self.format_item(self.listbyapi())
return self.results
def get(self):
response = None
try:
response = self.mgmt_client.api_operation.get(resource_group_name=self.resource_group,
service_name=self.service_name,
api_id=self.api_id,
operation_id=self.operation_id)
except CloudError as e:
self.log('Could not get info for @(Model.ModuleOperationNameUpper).')
return response.as_dict()
def listbyapi(self):
response = None
try:
response = self.mgmt_client.api_operation.list_by_api(resource_group_name=self.resource_group,
service_name=self.service_name,
api_id=self.api_id)
except CloudError as e:
self.log('Could not get info for @(Model.ModuleOperationNameUpper).')
return response.as_dict()
def format_item(item):
return item
def main():
AzureRMApiOperationInfo()
if __name__ == '__main__':
main()
| [
"[email protected]"
]
| |
c4441728e4c2fd660644adf3f31bc7b040393369 | 3b11dc40c7d772fffeb4d8683e5c9791c41f6454 | /custom/community/general/status_bar_clock/controllers/__init__.py | 5dacb5b2ac9861e919e683cd781d6bbe6496ff37 | []
| no_license | Jacky-odoo/Ecobank | b986352abac9416ab00008a4abaec2b1f1a1f262 | 5c501bd03a22421f47c76380004bf3d62292f79d | refs/heads/main | 2023-03-09T18:10:45.058530 | 2021-02-25T14:11:12 | 2021-02-25T14:11:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 176 | py | # -*- coding: utf-8 -*-
# © 2018-Today Aktiv Software (http://www.aktivsoftware.com).
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from . import main
| [
"[email protected]"
]
| |
66ac6b7417d7be10dff36b4974463b6abe8aad0c | 70149a0c3ec6b413574e52285ef083d40ce5b408 | /test.py | 35bcc485aaa90d24b4484cb37a821d7a8d359938 | []
| no_license | lychlov/compaign | 7d7ed3e0af9e03ebc0ed6bb6b586f046c49069b5 | 8b4d88f22c8278c2bfdd2eedc911a19652865945 | refs/heads/master | 2021-06-03T08:40:27.415833 | 2020-08-25T07:20:17 | 2020-08-25T07:20:17 | 145,792,189 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 29,668 | py | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: test
Description :
Author : Lychlov
date: 2018/8/16
-------------------------------------------------
Change Activity:
2018/8/16:
-------------------------------------------------
"""
import re
html = """
<ol class="commentlist" style="list-style-type: none;">
<li id="comment-3930785">
<div>
<div class="row">
<div class="author"><strong title="防伪码:9eabd9af22b168c229ae4ece9f8c6f6614307176" class="orange-name">大姨胶布</strong> <br>
<small><a href="#footer" title="@回复" onclick="document.getElementById('comment').value += '@<a href="//jandan.net/pic/page-226#comment-3930785">大姨胶布</a>: '">@4 mins ago</a></small>
</div>
<div class="text"><span class="righttext"><a href="//jandan.net/pic/page-226#comment-3930785">3930785</a></span><p style="position: relative;"><a href="//wx2.sinaimg.cn/large/ddf0f092gy1fubb247plxg208w08wx6r.gif" target="_blank" class="view_img_link">[查看原图]</a><br><img src="http://wx2.sinaimg.cn/thumb180/ddf0f092gy1fubb247plxg208w08wx6r.gif" org_src="http://wx2.sinaimg.cn/mw690/ddf0f092gy1fubb247plxg208w08wx6r.gif" style="max-width: 100%; max-height: 450px;"><div class="gif-mask" style="top:21.5999755859375px;left:0px;width:180px;height:180px;line-height:180px;">PLAY</div></p>
</div>
<div class="jandan-vote">
<span class="comment-report-c">
<a title="举报" href="javascript:;" class="comment-report" data-id="3930785">[举报]</a>
</span>
<span class="tucao-like-container">
<a title="圈圈/支持" href="javascript:;" class="comment-like like" data-id="3930785" data-type="pos">OO</a> [<span>0</span>]
</span>
<span class="tucao-unlike-container">
<a title="叉叉/反对" href="javascript:;" class="comment-unlike unlike" data-id="3930785" data-type="neg">XX</a> [<span>0</span>]
<a href="javascript:;" class="tucao-btn" data-id="3930785"> 吐槽 [0] </a>
</span>
</div>
</div>
</div>
</li>
<li id="comment-3930784">
<div>
<div class="row">
<div class="author"><strong title="防伪码:9eabd9af22b168c229ae4ece9f8c6f6614307176" class="orange-name">大姨胶布</strong> <br>
<small><a href="#footer" title="@回复" onclick="document.getElementById('comment').value += '@<a href="//jandan.net/pic/page-226#comment-3930784">大姨胶布</a>: '">@4 mins ago</a></small>
</div>
<div class="text"><span class="righttext"><a href="//jandan.net/pic/page-226#comment-3930784">3930784</a></span><p style="position: relative;"><a href="//wx3.sinaimg.cn/large/ddf0f092gy1fubb25ut8wg207v09z7wl.gif" target="_blank" class="view_img_link">[查看原图]</a><br><img src="http://wx3.sinaimg.cn/thumb180/ddf0f092gy1fubb25ut8wg207v09z7wl.gif" org_src="http://wx3.sinaimg.cn/mw690/ddf0f092gy1fubb25ut8wg207v09z7wl.gif" style="max-width: 100%; max-height: 450px;"><div class="gif-mask" style="top:21.5999755859375px;left:0px;width:180px;height:180px;line-height:180px;">PLAY</div></p>
</div>
<div class="jandan-vote">
<span class="comment-report-c">
<a title="举报" href="javascript:;" class="comment-report" data-id="3930784">[举报]</a>
</span>
<span class="tucao-like-container">
<a title="圈圈/支持" href="javascript:;" class="comment-like like" data-id="3930784" data-type="pos">OO</a> [<span>0</span>]
</span>
<span class="tucao-unlike-container">
<a title="叉叉/反对" href="javascript:;" class="comment-unlike unlike" data-id="3930784" data-type="neg">XX</a> [<span>1</span>]
<a href="javascript:;" class="tucao-btn" data-id="3930784"> 吐槽 [0] </a>
</span>
</div>
</div>
</div>
</li>
<li id="comment-3930783">
<div>
<div class="row">
<div class="author"><strong title="防伪码:9eabd9af22b168c229ae4ece9f8c6f6614307176" class="orange-name">大姨胶布</strong> <br>
<small><a href="#footer" title="@回复" onclick="document.getElementById('comment').value += '@<a href="//jandan.net/pic/page-226#comment-3930783">大姨胶布</a>: '">@4 mins ago</a></small>
</div>
<div class="text"><span class="righttext"><a href="//jandan.net/pic/page-226#comment-3930783">3930783</a></span><p style="position: relative;"><a href="//wx2.sinaimg.cn/large/ddf0f092gy1fubb26qzztg209406rx6r.gif" target="_blank" class="view_img_link">[查看原图]</a><br><img src="http://wx2.sinaimg.cn/thumb180/ddf0f092gy1fubb26qzztg209406rx6r.gif" org_src="http://wx2.sinaimg.cn/mw690/ddf0f092gy1fubb26qzztg209406rx6r.gif" style="max-width: 100%; max-height: 450px;"><div class="gif-mask" style="top:21.60009765625px;left:0px;width:180px;height:180px;line-height:180px;">PLAY</div></p>
</div>
<div class="jandan-vote">
<span class="comment-report-c">
<a title="举报" href="javascript:;" class="comment-report" data-id="3930783">[举报]</a>
</span>
<span class="tucao-like-container">
<a title="圈圈/支持" href="javascript:;" class="comment-like like" data-id="3930783" data-type="pos">OO</a> [<span>0</span>]
</span>
<span class="tucao-unlike-container">
<a title="叉叉/反对" href="javascript:;" class="comment-unlike unlike" data-id="3930783" data-type="neg">XX</a> [<span>0</span>]
<a href="javascript:;" class="tucao-btn" data-id="3930783"> 吐槽 [0] </a>
</span>
</div>
</div>
</div>
</li>
<span class="break"></span><li class="row">
<div style="padding-left:120px;padding-top:10px;padding-bottom:15px;width:336px;">
<font color="#AAA">[ 广告 ]</font><br>
<!-- 336-adx -->
<script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- 煎蛋网-首页-336x280 -->
<ins class="adsbygoogle" style="display:inline-block;width:336px;height:280px" data-ad-client="ca-pub-5673546663729848" data-ad-slot="1965170595/jandannet-home-336x280" data-adsbygoogle-status="done"><ins id="aswift_0_expand" style="display:inline-table;border:none;height:280px;margin:0;padding:0;position:relative;visibility:visible;width:336px;background-color:transparent;"><ins id="aswift_0_anchor" style="display:block;border:none;height:280px;margin:0;padding:0;position:relative;visibility:visible;width:336px;background-color:transparent;"><iframe width="336" height="280" frameborder="0" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" allowfullscreen="true" onload="var i=this.id,s=window.google_iframe_oncopy,H=s&&s.handlers,h=H&&H[i],w=this.contentWindow,d;try{d=w.document}catch(e){}if(h&&d&&(!d.body||!d.body.firstChild)){if(h.call){setTimeout(h,0)}else if(h.match){try{h=s.upd(h,i)}catch(e){}w.location.replace(h)}}" id="aswift_0" name="aswift_0" style="left:0;position:absolute;top:0;width:336px;height:280px;"></iframe></ins></ins></ins>
<script>
(adsbygoogle=window.adsbygoogle || []).push({});
</script></div>
</li>
<li id="comment-3930781">
<div>
<div class="row">
<div class="author"><strong title="防伪码:9eabd9af22b168c229ae4ece9f8c6f6614307176" class="orange-name">大姨胶布</strong> <br>
<small><a href="#footer" title="@回复" onclick="document.getElementById('comment').value += '@<a href="//jandan.net/pic/page-226#comment-3930781">大姨胶布</a>: '">@4 mins ago</a></small>
</div>
<div class="text"><span class="righttext"><a href="//jandan.net/pic/page-226#comment-3930781">3930781</a></span><p style="position: relative;"><a href="//wx1.sinaimg.cn/large/ddf0f092gy1fubb2858nhg20cs0a8x6q.gif" target="_blank" class="view_img_link">[查看原图]</a><br><img src="http://wx1.sinaimg.cn/thumb180/ddf0f092gy1fubb2858nhg20cs0a8x6q.gif" org_src="http://wx1.sinaimg.cn/mw690/ddf0f092gy1fubb2858nhg20cs0a8x6q.gif" style="max-width: 100%; max-height: 450px;"><div class="gif-mask" style="top:21.5999755859375px;left:0px;width:180px;height:180px;line-height:180px;">PLAY</div></p>
</div>
<div class="jandan-vote">
<span class="comment-report-c">
<a title="举报" href="javascript:;" class="comment-report" data-id="3930781">[举报]</a>
</span>
<span class="tucao-like-container">
<a title="圈圈/支持" href="javascript:;" class="comment-like like" data-id="3930781" data-type="pos">OO</a> [<span>0</span>]
</span>
<span class="tucao-unlike-container">
<a title="叉叉/反对" href="javascript:;" class="comment-unlike unlike" data-id="3930781" data-type="neg">XX</a> [<span>1</span>]
<a href="javascript:;" class="tucao-btn" data-id="3930781"> 吐槽 [0] </a>
</span>
</div>
</div>
</div>
</li>
<li id="comment-3930780">
<div>
<div class="row">
<div class="author"><strong title="防伪码:9eabd9af22b168c229ae4ece9f8c6f6614307176" class="orange-name">大姨胶布</strong> <br>
<small><a href="#footer" title="@回复" onclick="document.getElementById('comment').value += '@<a href="//jandan.net/pic/page-226#comment-3930780">大姨胶布</a>: '">@5 mins ago</a></small>
</div>
<div class="text"><span class="righttext"><a href="//jandan.net/pic/page-226#comment-3930780">3930780</a></span><p style="position: relative;"><a href="//wx3.sinaimg.cn/large/ddf0f092gy1fubb2a47i8g20a80csnpn.gif" target="_blank" class="view_img_link">[查看原图]</a><br><img src="http://wx3.sinaimg.cn/thumb180/ddf0f092gy1fubb2a47i8g20a80csnpn.gif" org_src="http://wx3.sinaimg.cn/mw690/ddf0f092gy1fubb2a47i8g20a80csnpn.gif" style="max-width: 100%; max-height: 450px;"><div class="gif-mask" style="top:21.5999755859375px;left:0px;width:180px;height:180px;line-height:180px;">PLAY</div></p>
</div>
<div class="jandan-vote">
<span class="comment-report-c">
<a title="举报" href="javascript:;" class="comment-report" data-id="3930780">[举报]</a>
</span>
<span class="tucao-like-container">
<a title="圈圈/支持" href="javascript:;" class="comment-like like" data-id="3930780" data-type="pos">OO</a> [<span>0</span>]
</span>
<span class="tucao-unlike-container">
<a title="叉叉/反对" href="javascript:;" class="comment-unlike unlike" data-id="3930780" data-type="neg">XX</a> [<span>0</span>]
<a href="javascript:;" class="tucao-btn" data-id="3930780"> 吐槽 [0] </a>
</span>
</div>
</div>
</div>
</li>
<li id="comment-3930779">
<div>
<div class="row">
<div class="author"><strong title="防伪码:9eabd9af22b168c229ae4ece9f8c6f6614307176" class="orange-name">大姨胶布</strong> <br>
<small><a href="#footer" title="@回复" onclick="document.getElementById('comment').value += '@<a href="//jandan.net/pic/page-226#comment-3930779">大姨胶布</a>: '">@5 mins ago</a></small>
</div>
<div class="text"><span class="righttext"><a href="//jandan.net/pic/page-226#comment-3930779">3930779</a></span><p style="position: relative;"><a href="//wx1.sinaimg.cn/large/ddf0f092gy1fubb2c8240g20bs090kju.gif" target="_blank" class="view_img_link">[查看原图]</a><br><img src="http://wx1.sinaimg.cn/thumb180/ddf0f092gy1fubb2c8240g20bs090kju.gif" org_src="http://wx1.sinaimg.cn/mw690/ddf0f092gy1fubb2c8240g20bs090kju.gif" style="max-width: 100%; max-height: 450px;"><div class="gif-mask" style="top:21.60009765625px;left:0px;width:180px;height:180px;line-height:180px;">PLAY</div></p>
</div>
<div class="jandan-vote">
<span class="comment-report-c">
<a title="举报" href="javascript:;" class="comment-report" data-id="3930779">[举报]</a>
</span>
<span class="tucao-like-container">
<a title="圈圈/支持" href="javascript:;" class="comment-like like" data-id="3930779" data-type="pos">OO</a> [<span>0</span>]
</span>
<span class="tucao-unlike-container">
<a title="叉叉/反对" href="javascript:;" class="comment-unlike unlike" data-id="3930779" data-type="neg">XX</a> [<span>0</span>]
<a href="javascript:;" class="tucao-btn" data-id="3930779"> 吐槽 [0] </a>
</span>
</div>
</div>
</div>
</li>
<li id="comment-3930777">
<div>
<div class="row">
<div class="author"><strong title="防伪码:9eabd9af22b168c229ae4ece9f8c6f6614307176" class="orange-name">大姨胶布</strong> <br>
<small><a href="#footer" title="@回复" onclick="document.getElementById('comment').value += '@<a href="//jandan.net/pic/page-226#comment-3930777">大姨胶布</a>: '">@5 mins ago</a></small>
</div>
<div class="text"><span class="righttext"><a href="//jandan.net/pic/page-226#comment-3930777">3930777</a></span><p style="position: relative;"><a href="//wx4.sinaimg.cn/large/ddf0f092gy1fubb2drwuzg20ac0ace88.gif" target="_blank" class="view_img_link">[查看原图]</a><br><img src="http://wx4.sinaimg.cn/thumb180/ddf0f092gy1fubb2drwuzg20ac0ace88.gif" org_src="http://wx4.sinaimg.cn/mw690/ddf0f092gy1fubb2drwuzg20ac0ace88.gif" style="max-width: 100%; max-height: 450px;"><div class="gif-mask" style="top:21.60009765625px;left:0px;width:180px;height:180px;line-height:180px;">PLAY</div></p>
</div>
<div class="jandan-vote">
<span class="comment-report-c">
<a title="举报" href="javascript:;" class="comment-report" data-id="3930777">[举报]</a>
</span>
<span class="tucao-like-container">
<a title="圈圈/支持" href="javascript:;" class="comment-like like" data-id="3930777" data-type="pos">OO</a> [<span>0</span>]
</span>
<span class="tucao-unlike-container">
<a title="叉叉/反对" href="javascript:;" class="comment-unlike unlike" data-id="3930777" data-type="neg">XX</a> [<span>0</span>]
<a href="javascript:;" class="tucao-btn" data-id="3930777"> 吐槽 [0] </a>
</span>
</div>
</div>
</div>
</li>
<li id="comment-3930776">
<div>
<div class="row">
<div class="author"><strong title="防伪码:9eabd9af22b168c229ae4ece9f8c6f6614307176" class="orange-name">大姨胶布</strong> <br>
<small><a href="#footer" title="@回复" onclick="document.getElementById('comment').value += '@<a href="//jandan.net/pic/page-226#comment-3930776">大姨胶布</a>: '">@6 mins ago</a></small>
</div>
<div class="text"><span class="righttext"><a href="//jandan.net/pic/page-226#comment-3930776">3930776</a></span><p style="position: relative;"><a href="//wx4.sinaimg.cn/large/ddf0f092gy1fubb2gcxwag20bs06lx72.gif" target="_blank" class="view_img_link">[查看原图]</a><br><img src="http://wx4.sinaimg.cn/thumb180/ddf0f092gy1fubb2gcxwag20bs06lx72.gif" org_src="http://wx4.sinaimg.cn/mw690/ddf0f092gy1fubb2gcxwag20bs06lx72.gif" style="max-width: 100%; max-height: 450px;"><div class="gif-mask" style="top:21.60009765625px;left:0px;width:180px;height:180px;line-height:180px;">PLAY</div></p>
</div>
<div class="jandan-vote">
<span class="comment-report-c">
<a title="举报" href="javascript:;" class="comment-report" data-id="3930776">[举报]</a>
</span>
<span class="tucao-like-container">
<a title="圈圈/支持" href="javascript:;" class="comment-like like" data-id="3930776" data-type="pos">OO</a> [<span>0</span>]
</span>
<span class="tucao-unlike-container">
<a title="叉叉/反对" href="javascript:;" class="comment-unlike unlike" data-id="3930776" data-type="neg">XX</a> [<span>0</span>]
<a href="javascript:;" class="tucao-btn" data-id="3930776"> 吐槽 [0] </a>
</span>
</div>
</div>
</div>
</li>
<li id="comment-3930775">
<div>
<div class="row">
<div class="author"><strong title="防伪码:9eabd9af22b168c229ae4ece9f8c6f6614307176" class="orange-name">大姨胶布</strong> <br>
<small><a href="#footer" title="@回复" onclick="document.getElementById('comment').value += '@<a href="//jandan.net/pic/page-226#comment-3930775">大姨胶布</a>: '">@6 mins ago</a></small>
</div>
<div class="text"><span class="righttext"><a href="//jandan.net/pic/page-226#comment-3930775">3930775</a></span><p style="position: relative;"><a href="//wx2.sinaimg.cn/large/ddf0f092gy1fubb2jb7oag20bs0kxnpt.gif" target="_blank" class="view_img_link">[查看原图]</a><br><img src="http://wx2.sinaimg.cn/thumb180/ddf0f092gy1fubb2jb7oag20bs0kxnpt.gif" org_src="http://wx2.sinaimg.cn/mw690/ddf0f092gy1fubb2jb7oag20bs0kxnpt.gif" style="max-width: 100%; max-height: 450px;"><div class="gif-mask" style="top:21.60009765625px;left:0px;width:180px;height:180px;line-height:180px;">PLAY</div></p>
</div>
<div class="jandan-vote">
<span class="comment-report-c">
<a title="举报" href="javascript:;" class="comment-report" data-id="3930775">[举报]</a>
</span>
<span class="tucao-like-container">
<a title="圈圈/支持" href="javascript:;" class="comment-like like" data-id="3930775" data-type="pos">OO</a> [<span>0</span>]
</span>
<span class="tucao-unlike-container">
<a title="叉叉/反对" href="javascript:;" class="comment-unlike unlike" data-id="3930775" data-type="neg">XX</a> [<span>0</span>]
<a href="javascript:;" class="tucao-btn" data-id="3930775"> 吐槽 [0] </a>
</span>
</div>
</div>
</div>
</li>
<li id="comment-3930774">
<div>
<div class="row">
<div class="author"><strong title="防伪码:9eabd9af22b168c229ae4ece9f8c6f6614307176" class="orange-name">大姨胶布</strong> <br>
<small><a href="#footer" title="@回复" onclick="document.getElementById('comment').value += '@<a href="//jandan.net/pic/page-226#comment-3930774">大姨胶布</a>: '">@7 mins ago</a></small>
</div>
<div class="text"><span class="righttext"><a href="//jandan.net/pic/page-226#comment-3930774">3930774</a></span><p style="position: relative;"><a href="//wx2.sinaimg.cn/large/ddf0f092gy1fubb2kgu3vg20b4063x6q.gif" target="_blank" class="view_img_link">[查看原图]</a><br><img src="http://wx2.sinaimg.cn/thumb180/ddf0f092gy1fubb2kgu3vg20b4063x6q.gif" org_src="http://wx2.sinaimg.cn/mw690/ddf0f092gy1fubb2kgu3vg20b4063x6q.gif" style="max-width: 100%; max-height: 450px;"><div class="gif-mask" style="top:21.60009765625px;left:0px;width:180px;height:180px;line-height:180px;">PLAY</div></p>
</div>
<div class="jandan-vote">
<span class="comment-report-c">
<a title="举报" href="javascript:;" class="comment-report" data-id="3930774">[举报]</a>
</span>
<span class="tucao-like-container">
<a title="圈圈/支持" href="javascript:;" class="comment-like like" data-id="3930774" data-type="pos">OO</a> [<span>0</span>]
</span>
<span class="tucao-unlike-container">
<a title="叉叉/反对" href="javascript:;" class="comment-unlike unlike" data-id="3930774" data-type="neg">XX</a> [<span>0</span>]
<a href="javascript:;" class="tucao-btn" data-id="3930774"> 吐槽 [0] </a>
</span>
</div>
</div>
</div>
</li>
<li id="comment-3930773">
<div>
<div class="row">
<div class="author"><strong title="防伪码:9eabd9af22b168c229ae4ece9f8c6f6614307176" class="orange-name">大姨胶布</strong> <br>
<small><a href="#footer" title="@回复" onclick="document.getElementById('comment').value += '@<a href="//jandan.net/pic/page-226#comment-3930773">大姨胶布</a>: '">@7 mins ago</a></small>
</div>
<div class="text"><span class="righttext"><a href="//jandan.net/pic/page-226#comment-3930773">3930773</a></span><p style="position: relative;"><a href="//wx3.sinaimg.cn/large/ddf0f092gy1fubb2lgcseg20ap0dcnpi.gif" target="_blank" class="view_img_link">[查看原图]</a><br><img src="http://wx3.sinaimg.cn/thumb180/ddf0f092gy1fubb2lgcseg20ap0dcnpi.gif" org_src="http://wx3.sinaimg.cn/mw690/ddf0f092gy1fubb2lgcseg20ap0dcnpi.gif" style="max-width: 100%; max-height: 450px;"><div class="gif-mask" style="top:21.60009765625px;left:0px;width:180px;height:180px;line-height:180px;">PLAY</div></p>
</div>
<div class="jandan-vote">
<span class="comment-report-c">
<a title="举报" href="javascript:;" class="comment-report" data-id="3930773">[举报]</a>
</span>
<span class="tucao-like-container">
<a title="圈圈/支持" href="javascript:;" class="comment-like like" data-id="3930773" data-type="pos">OO</a> [<span>0</span>]
</span>
<span class="tucao-unlike-container">
<a title="叉叉/反对" href="javascript:;" class="comment-unlike unlike" data-id="3930773" data-type="neg">XX</a> [<span>0</span>]
<a href="javascript:;" class="tucao-btn" data-id="3930773"> 吐槽 [0] </a>
</span>
</div>
</div>
</div>
</li>
<li id="comment-3930772">
<div>
<div class="row">
<div class="author"><strong title="防伪码:9eabd9af22b168c229ae4ece9f8c6f6614307176" class="orange-name">大姨胶布</strong> <br>
<small><a href="#footer" title="@回复" onclick="document.getElementById('comment').value += '@<a href="//jandan.net/pic/page-226#comment-3930772">大姨胶布</a>: '">@7 mins ago</a></small>
</div>
<div class="text"><span class="righttext"><a href="//jandan.net/pic/page-226#comment-3930772">3930772</a></span><p style="position: relative;"><a href="//wx1.sinaimg.cn/large/ddf0f092gy1fubb2om52eg20b40dwqvm.gif" target="_blank" class="view_img_link">[查看原图]</a><br><img src="http://wx1.sinaimg.cn/thumb180/ddf0f092gy1fubb2om52eg20b40dwqvm.gif" org_src="http://wx1.sinaimg.cn/mw690/ddf0f092gy1fubb2om52eg20b40dwqvm.gif" style="max-width: 100%; max-height: 450px;"><div class="gif-mask" style="top:21.60009765625px;left:0px;width:180px;height:180px;line-height:180px;">PLAY</div></p>
</div>
<div class="jandan-vote">
<span class="comment-report-c">
<a title="举报" href="javascript:;" class="comment-report" data-id="3930772">[举报]</a>
</span>
<span class="tucao-like-container">
<a title="圈圈/支持" href="javascript:;" class="comment-like like" data-id="3930772" data-type="pos">OO</a> [<span>0</span>]
</span>
<span class="tucao-unlike-container">
<a title="叉叉/反对" href="javascript:;" class="comment-unlike unlike" data-id="3930772" data-type="neg">XX</a> [<span>0</span>]
<a href="javascript:;" class="tucao-btn" data-id="3930772"> 吐槽 [0] </a>
</span>
</div>
</div>
</div>
</li>
</ol>
"""
regex = r'img src="(.+?)"'
img_src = re.findall(regex,html)
html.find()
print(img_src) | [
"[email protected]"
]
| |
6fef571360e9314e5f9c731b7aac3ac1e1026cf4 | 9242319ca7796c6a3b18e760ddbf8290944d4b49 | /test/test_enocean_receiver.py | 1e118b4b6390d5bdfd67f5a6a7059a35599cbe38 | [
"MIT"
]
| permissive | MainRo/python-flock | 79cfd7ce4edab40439c556b6621768438868d16c | e1faa78d6aba374493336651848daadad82387a8 | refs/heads/master | 2021-01-10T19:16:52.907538 | 2015-11-18T21:15:38 | 2015-11-18T21:15:38 | 29,210,634 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,817 | py | from unittest import TestCase
from mock import patch, call
from flock.controller.enocean.protocol import EnoceanReceiver
class TestProtocol(EnoceanReceiver):
def packet_received(self, data):
return
@patch.object(TestProtocol, 'packet_received')
class EnoceanReceiverTestCase(TestCase):
def test_receive_without_connection(self, test_packet_received):
protocol = TestProtocol()
data = '\x55\x00\x02\x00\x08\x42\x01\x02\x42'
protocol.dataReceived(data)
def test_receive_one_packet(self, test_packet_received):
protocol = TestProtocol()
protocol.connectionMade()
data = '\x55\x00\x02\x00\x08\x42\x01\x02\x42'
protocol.dataReceived(data)
test_packet_received.assert_called_with(ord(data[4]), data[6:8], '')
def test_receive_packet_from_chunks(self, test_packet_received):
protocol = TestProtocol()
protocol.connectionMade()
data = '\x55\x00\x02\x00\x08\x42\x01\x02\x42'
protocol.dataReceived(data[:3])
protocol.dataReceived(data[3:6])
protocol.dataReceived(data[6:])
test_packet_received.assert_called_with(ord(data[4]), data[6:8], '')
def test_receive_several_packets(self, test_packet_received):
protocol = TestProtocol()
protocol.connectionMade()
data = '\x55\x00\x02\x00\x08\x42\x01\x02\x42'
protocol.dataReceived(data)
test_packet_received.assert_called_with(ord(data[4]), data[6:8], '')
data = '\x55\x00\x02\x00\x08\x42\x03\x04\x42'
protocol.dataReceived(data)
test_packet_received.assert_called_with(ord(data[4]), data[6:8], '')
data = '\x55\x00\x02\x00\x08\x42\x05\x06\x42'
protocol.dataReceived(data)
test_packet_received.assert_called_with(ord(data[4]), data[6:8], '')
| [
"[email protected]"
]
| |
aea7626754bf828a192cfb8b75e2737f4ca1bb81 | 751d837b8a4445877bb2f0d1e97ce41cd39ce1bd | /edabit/get-the-sum-of-all-array-elements.py | 93bdaa39d63ddef0d914699453ead734f12d464a | [
"MIT"
]
| permissive | qeedquan/challenges | d55146f784a3619caa4541ac6f2b670b0a3dd8ba | 56823e77cf502bdea68cce0e1221f5add3d64d6a | refs/heads/master | 2023-08-11T20:35:09.726571 | 2023-08-11T13:02:43 | 2023-08-11T13:02:43 | 115,886,967 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 417 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
u"""
Create a function that takes an array and returns the sum of all numbers in the array.
Examples
getSumOfItems([2, 7, 4]) ➞ 13
getSumOfItems([45, 3, 0]) ➞ 48
getSumOfItems([-2, 84, 23]) ➞ 105
"""
import operator
def sum(xs):
return reduce(operator.add, xs)
assert(sum([2, 7, 4]) == 13)
assert(sum([45, 3, 0]) == 48)
assert(sum([-2, 84, 23]) == 105)
| [
"[email protected]"
]
| |
0e602dfaa845ca851703c413ce1a548c2cec1477 | 5a52ccea88f90dd4f1acc2819997fce0dd5ffb7d | /alipay/aop/api/domain/IsvAuthSceneInfo.py | 59bf8806f92b1610731009758157f4352bc08cb4 | [
"Apache-2.0"
]
| permissive | alipay/alipay-sdk-python-all | 8bd20882852ffeb70a6e929038bf88ff1d1eff1c | 1fad300587c9e7e099747305ba9077d4cd7afde9 | refs/heads/master | 2023-08-27T21:35:01.778771 | 2023-08-23T07:12:26 | 2023-08-23T07:12:26 | 133,338,689 | 247 | 70 | Apache-2.0 | 2023-04-25T04:54:02 | 2018-05-14T09:40:54 | Python | UTF-8 | Python | false | false | 1,493 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class IsvAuthSceneInfo(object):
def __init__(self):
self._scene_code = None
self._scene_permissions = None
@property
def scene_code(self):
return self._scene_code
@scene_code.setter
def scene_code(self, value):
self._scene_code = value
@property
def scene_permissions(self):
return self._scene_permissions
@scene_permissions.setter
def scene_permissions(self, value):
self._scene_permissions = value
def to_alipay_dict(self):
params = dict()
if self.scene_code:
if hasattr(self.scene_code, 'to_alipay_dict'):
params['scene_code'] = self.scene_code.to_alipay_dict()
else:
params['scene_code'] = self.scene_code
if self.scene_permissions:
if hasattr(self.scene_permissions, 'to_alipay_dict'):
params['scene_permissions'] = self.scene_permissions.to_alipay_dict()
else:
params['scene_permissions'] = self.scene_permissions
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = IsvAuthSceneInfo()
if 'scene_code' in d:
o.scene_code = d['scene_code']
if 'scene_permissions' in d:
o.scene_permissions = d['scene_permissions']
return o
| [
"[email protected]"
]
| |
b4e67e6713486739e9c8bab0cafa343f4640205b | a53998e56ee06a96d59d97b2601fd6ec1e4124d7 | /Mysql/day5/insert.py | ff40cb7ca8bbbe14a540f848df8e7f9f0de5504f | []
| no_license | zh-en520/aid1901 | f0ec0ec54e3fd616a2a85883da16670f34d4f873 | a56f82d0ea60b2395deacc57c4bdf3b6bc73bd2e | refs/heads/master | 2020-06-28T21:16:22.259665 | 2019-08-03T07:09:29 | 2019-08-03T07:09:29 | 200,344,127 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 571 | py | # insert_test.py
# 插入测试
import pymysql
from db_conf import *
#创建数据库连接
try:
conn = pymysql.connect(host,user,passwd,dbname)
cursor = conn.cursor() #获取游标
#定义sql语句
# sql = '''insert into orders
# (order_id,cust_id,amt)
# values('201801010002','C0002',444.55)
# '''
sql = 'delete from orders where amt=444.55'
cursor.execute(sql)#执行SQL语句
conn.commit()#提交事务
print('插入成功')
except Exception as e:
conn.rollback()#回滚事务
print(e)
cursor.close()
conn.close()
| [
"[email protected]"
]
| |
84d572034fee02964f3c369d9520d27f1e66dad6 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03679/s869008403.py | 48a02e5eb2d96856b887b33de82b64a54cfa0625 | []
| no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 147 | py | x, a, b = map(int, input().split())
a *= -1
a += b
if a <= 0:
print("delicious")
elif a <= x:
print("safe")
else:
print("dangerous") | [
"[email protected]"
]
| |
33ba7708ad40728b600a25ef784d8dd3537d2f47 | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/verbs/_foreclose.py | 123d60eb470560c241e67bbf37217dea6bac11e8 | [
"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 | 507 | py |
#calss header
class _FORECLOSE():
def __init__(self,):
self.name = "FORECLOSE"
self.definitions = [u'(especially of banks) to take back property that was bought with borrowed money because the money was not being paid back as formally agreed: ', u'to prevent something from being considered as a possibility in the future: ']
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.specie = 'verbs'
def run(self, obj1 = [], obj2 = []):
return self.jsondata
| [
"[email protected]"
]
| |
edc5f5b0ffedbe6dba2d55c3cae53622b0a66c40 | e6dab5aa1754ff13755a1f74a28a201681ab7e1c | /.parts/lib/python2.7/lib2to3/tests/data/py2_test_grammar.py | 87585511947baea14ec9fbdf2c9880c945b3ca08 | []
| no_license | ronkagan/Euler_1 | 67679203a9510147320f7c6513eefd391630703e | 022633cc298475c4f3fd0c6e2bde4f4728713995 | refs/heads/master | 2021-01-06T20:45:52.901025 | 2014-09-06T22:34:16 | 2014-09-06T22:34:16 | 23,744,842 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 95 | py | /home/action/.parts/packages/python2/2.7.6/lib/python2.7/lib2to3/tests/data/py2_test_grammar.py | [
"[email protected]"
]
| |
c14adaf27ac8d243d23ed47ee8d7fd61530e0bb1 | d9504b779ca6d25a711c13fafc1b8669c60e6f62 | /shape_recognition/libraries/general/confighardware.py | 017e0a4ded22f83515c5ec8383669473fd3c48c2 | [
"MIT"
]
| permissive | ys1998/tactile-shape-recognition | dcdd3f4da66b4b3f6159dccf9cec4d367f6483d9 | b5ab6f1cdf04ff23e14b467a590533e7ee740b52 | refs/heads/master | 2020-03-18T03:01:17.985074 | 2018-07-28T09:46:16 | 2018-07-28T09:46:16 | 134,218,923 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,249 | py | # -*- coding: utf-8 -*-
'''
#-------------------------------------------------------------------------------
# NATIONAL UNIVERSITY OF SINGAPORE - NUS
# SINGAPORE INSTITUTE FOR NEUROTECHNOLOGY - SINAPSE
# Singapore
# URL: http://www.sinapseinstitute.org
#-------------------------------------------------------------------------------
# Neuromorphic Engineering Group
# ONR Presentation: June 13th, 2018
#-------------------------------------------------------------------------------
# Description:
#-------------------------------------------------------------------------------
'''
#-------------------------------------------------------------------------------
class FileHardwareHandler():
def __init__(self):
self.fileHandler = None
self.UR10 = None
self.iLimb = None
self.tactileBoards = None
def getParameters(self):
return self.UR10, self.iLimb, self.tactileBoards
#loads the parameters stored in the file
def load(self):
#open the file stream for reading
self.fileHandler = open('hardware.cfg','r')
#read all the lines
lines = self.fileHandler.readlines()
#print(lines) #debugging
urs = lines[0].split('\n')[0].split(' ')
self.UR10 = [urs[0], urs[1]]
hands = lines[1].split('\n')[0].split(' ')
self.iLimb = [hands[0],hands[1]]
boards = lines[2].split('\n')[0].split(' ')
self.tactileBoards = [boards[0],boards[1]]
#generates a new file containing the hardware configuration parameters
#ur10: ip addresses for left and right arm (UR10)
#ilimb: com ports for left and right hands (iLimb)
#tactile: com ports for left and right hands (tactile boards)
def save(self,ur10,ilimb,tactile):
#open the file stream for writing
self.fileHandler = open('hardware.cfg','w')
self.fileHandler.write(str(ur10[0]) + ' ' + str(ur10[1]) + '\n')
self.fileHandler.write(str(ilimb[0]) + ' ' + str(ilimb[1]) + '\n')
self.fileHandler.write(str(tactile[0]) + ' ' + str(tactile[1]) + '\n')
self.fileHandler.close()
#-------------------------------------------------------------------------------
| [
"[email protected]"
]
| |
7055b86d75dd80e1d208efe51177f3480945ae42 | 160c83b723cf03516ee99270b437a9a76aaf2b9f | /grr/core/grr_response_core/stats/stats_test_utils.py | 6f20bf5a1913b11afcc841713ef5ab64398dc480 | [
"Apache-2.0"
]
| permissive | ehossam/grr | 3a3d32596a8b7ffc7195f57fb10fe2a1e0153bef | 08a57f6873ee13f425d0106e4143663bc6dbdd60 | refs/heads/master | 2022-01-06T19:51:40.628744 | 2018-11-01T07:43:22 | 2018-11-01T07:43:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 18,372 | py | #!/usr/bin/env python
"""Common tests for stats-collector implementations."""
from __future__ import absolute_import
from __future__ import unicode_literals
import abc
import time
import builtins
from future.utils import with_metaclass
import mock
import unittest
from grr_response_core.lib.rdfvalues import stats as rdf_stats
from grr_response_core.stats import stats_collector
from grr_response_core.stats import stats_collector_instance
from grr_response_core.stats import stats_utils
_INF = float("inf")
def FakeStatsContext(fake_stats_collector):
"""Stubs out the stats-collector singleton with the given fake object."""
return mock.patch.object(stats_collector_instance, "_stats_singleton",
fake_stats_collector)
# pytype: disable=ignored-abstractmethod
class StatsCollectorTest(with_metaclass(abc.ABCMeta, unittest.TestCase)):
"""Stats collection tests.
Each test method has uniquely-named metrics to accommodate implementations
that do not support re-definition of metrics.
"""
def setUp(self):
super(StatsCollectorTest, self).setUp()
self._mock_time = 100.0
time_patcher = mock.patch.object(time, "time", lambda: self._mock_time)
time_patcher.start()
self.addCleanup(time_patcher.stop)
@abc.abstractmethod
def _CreateStatsCollector(self, metadata_list):
"""Creates a new stats collector with the given metadata."""
# Return a mock stats collector to satisfy type-checking (pytype).
return mock.Mock(spec_set=stats_collector.StatsCollector)
def _Sleep(self, n):
"""Simulates sleeping for a given number of seconds."""
self._mock_time += n
def testSimpleCounter(self):
counter_name = "testSimpleCounter_counter"
collector = self._CreateStatsCollector(
[stats_utils.CreateCounterMetadata(counter_name)])
self.assertEqual(0, collector.GetMetricValue(counter_name))
for _ in builtins.range(5):
collector.IncrementCounter(counter_name)
self.assertEqual(5, collector.GetMetricValue(counter_name))
collector.IncrementCounter(counter_name, 2)
self.assertEqual(7, collector.GetMetricValue(counter_name))
def testDecrementingCounterRaises(self):
counter_name = "testDecrementingCounterRaises_counter"
collector = self._CreateStatsCollector(
[stats_utils.CreateCounterMetadata(counter_name)])
with self.assertRaises(ValueError):
collector.IncrementCounter(counter_name, -1)
def testCounterWithFields(self):
counter_name = "testCounterWithFields_counter"
collector = self._CreateStatsCollector([
stats_utils.CreateCounterMetadata(
counter_name, fields=[("dimension", str)])
])
# Test that default values for any fields values are 0."
self.assertEqual(0, collector.GetMetricValue(counter_name, fields=["a"]))
self.assertEqual(0, collector.GetMetricValue(counter_name, fields=["b"]))
for _ in builtins.range(5):
collector.IncrementCounter(counter_name, fields=["dimension_value_1"])
self.assertEqual(
5, collector.GetMetricValue(counter_name, fields=["dimension_value_1"]))
collector.IncrementCounter(counter_name, 2, fields=["dimension_value_1"])
self.assertEqual(
7, collector.GetMetricValue(counter_name, fields=["dimension_value_1"]))
collector.IncrementCounter(counter_name, 2, fields=["dimension_value_2"])
self.assertEqual(
2, collector.GetMetricValue(counter_name, fields=["dimension_value_2"]))
# Check that previously set values with other fields are not affected.
self.assertEqual(
7, collector.GetMetricValue(counter_name, fields=["dimension_value_1"]))
def testSimpleGauge(self):
int_gauge_name = "testSimpleGauge_int_gauge"
string_gauge_name = "testSimpleGauge_string_gauge"
collector = self._CreateStatsCollector([
stats_utils.CreateGaugeMetadata(int_gauge_name, int),
stats_utils.CreateGaugeMetadata(string_gauge_name, str)
])
self.assertEqual(0, collector.GetMetricValue(int_gauge_name))
self.assertEqual("", collector.GetMetricValue(string_gauge_name))
collector.SetGaugeValue(int_gauge_name, 42)
collector.SetGaugeValue(string_gauge_name, "some")
self.assertEqual(42, collector.GetMetricValue(int_gauge_name))
self.assertEqual("some", collector.GetMetricValue(string_gauge_name))
# At least default Python type checking is enforced in gauges:
# we can't assign string to int
with self.assertRaises(ValueError):
collector.SetGaugeValue(int_gauge_name, "some")
# but we can assign int to string
collector.SetGaugeValue(string_gauge_name, 42)
def testGaugeWithFields(self):
int_gauge_name = "testGaugeWithFields_int_gauge"
collector = self._CreateStatsCollector([
stats_utils.CreateGaugeMetadata(
int_gauge_name, int, fields=[("dimension", str)])
])
self.assertEqual(
0, collector.GetMetricValue(
int_gauge_name, fields=["dimension_value_1"]))
self.assertEqual(
0, collector.GetMetricValue(
int_gauge_name, fields=["dimesnioN_value_2"]))
collector.SetGaugeValue(int_gauge_name, 1, fields=["dimension_value_1"])
collector.SetGaugeValue(int_gauge_name, 2, fields=["dimension_value_2"])
self.assertEqual(
1, collector.GetMetricValue(
int_gauge_name, fields=["dimension_value_1"]))
self.assertEqual(
2, collector.GetMetricValue(
int_gauge_name, fields=["dimension_value_2"]))
def testGaugeWithCallback(self):
int_gauge_name = "testGaugeWithCallback_int_gauge"
string_gauge_name = "testGaugeWithCallback_string_gauge"
collector = self._CreateStatsCollector([
stats_utils.CreateGaugeMetadata(int_gauge_name, int),
stats_utils.CreateGaugeMetadata(string_gauge_name, str)
])
self.assertEqual(0, collector.GetMetricValue(int_gauge_name))
self.assertEqual("", collector.GetMetricValue(string_gauge_name))
collector.SetGaugeCallback(int_gauge_name, lambda: 42)
collector.SetGaugeCallback(string_gauge_name, lambda: "some")
self.assertEqual(42, collector.GetMetricValue(int_gauge_name))
self.assertEqual("some", collector.GetMetricValue(string_gauge_name))
def testSimpleEventMetric(self):
event_metric_name = "testSimpleEventMetric_event_metric"
collector = self._CreateStatsCollector([
stats_utils.CreateEventMetadata(
event_metric_name, bins=[0.0, 0.1, 0.2]),
])
data = collector.GetMetricValue(event_metric_name)
self.assertAlmostEqual(0, data.sum)
self.assertEqual(0, data.count)
self.assertEqual([-_INF, 0.0, 0.1, 0.2], list(data.bins))
self.assertEqual({-_INF: 0, 0.0: 0, 0.1: 0, 0.2: 0}, data.bins_heights)
collector.RecordEvent(event_metric_name, 0.15)
data = collector.GetMetricValue(event_metric_name)
self.assertAlmostEqual(0.15, data.sum)
self.assertEqual(1, data.count)
self.assertEqual([-_INF, 0.0, 0.1, 0.2], list(data.bins))
self.assertEqual({-_INF: 0, 0.0: 0, 0.1: 1, 0.2: 0}, data.bins_heights)
collector.RecordEvent(event_metric_name, 0.5)
data = collector.GetMetricValue(event_metric_name)
self.assertAlmostEqual(0.65, data.sum)
self.assertEqual(2, data.count)
self.assertEqual([-_INF, 0.0, 0.1, 0.2], list(data.bins))
self.assertEqual({-_INF: 0, 0.0: 0, 0.1: 1, 0.2: 1}, data.bins_heights)
collector.RecordEvent(event_metric_name, -0.1)
data = collector.GetMetricValue(event_metric_name)
self.assertAlmostEqual(0.55, data.sum)
self.assertEqual(3, data.count)
self.assertEqual([-_INF, 0.0, 0.1, 0.2], list(data.bins))
self.assertEqual({-_INF: 1, 0.0: 0, 0.1: 1, 0.2: 1}, data.bins_heights)
def testEventMetricWithFields(self):
event_metric_name = "testEventMetricWithFields_event_metric"
collector = self._CreateStatsCollector([
stats_utils.CreateEventMetadata(
event_metric_name,
bins=[0.0, 0.1, 0.2],
fields=[("dimension", str)])
])
data = collector.GetMetricValue(
event_metric_name, fields=["dimension_value_1"])
self.assertAlmostEqual(0, data.sum)
self.assertEqual(0, data.count)
self.assertEqual([-_INF, 0.0, 0.1, 0.2], list(data.bins))
self.assertEqual({-_INF: 0, 0.0: 0, 0.1: 0, 0.2: 0}, data.bins_heights)
collector.RecordEvent(event_metric_name, 0.15, fields=["dimension_value_1"])
collector.RecordEvent(event_metric_name, 0.25, fields=["dimension_value_2"])
data = collector.GetMetricValue(
event_metric_name, fields=["dimension_value_1"])
self.assertAlmostEqual(0.15, data.sum)
self.assertEqual(1, data.count)
self.assertEqual([-_INF, 0.0, 0.1, 0.2], list(data.bins))
self.assertEqual({-_INF: 0, 0.0: 0, 0.1: 1, 0.2: 0}, data.bins_heights)
data = collector.GetMetricValue(
event_metric_name, fields=["dimension_value_2"])
self.assertAlmostEqual(0.25, data.sum)
self.assertEqual(1, data.count)
self.assertEqual([-_INF, 0.0, 0.1, 0.2], list(data.bins))
self.assertEqual({-_INF: 0, 0.0: 0, 0.1: 0, 0.2: 1}, data.bins_heights)
def testRaisesOnImproperFieldsUsage1(self):
counter_name = "testRaisesOnImproperFieldsUsage1_counter"
int_gauge_name = "testRaisesOnImproperFieldsUsage1_int_gauge"
event_metric_name = "testRaisesOnImproperFieldsUsage1_event_metric"
collector = self._CreateStatsCollector([
stats_utils.CreateCounterMetadata(counter_name),
stats_utils.CreateGaugeMetadata(int_gauge_name, int),
stats_utils.CreateEventMetadata(event_metric_name)
])
# Check for counters
with self.assertRaises(ValueError):
collector.GetMetricValue(counter_name, fields=["a"])
# Check for gauges
with self.assertRaises(ValueError):
collector.GetMetricValue(int_gauge_name, fields=["a"])
# Check for event metrics
self.assertRaises(
ValueError,
collector.GetMetricValue,
event_metric_name,
fields=["a", "b"])
def testRaisesOnImproperFieldsUsage2(self):
counter_name = "testRaisesOnImproperFieldsUsage2_counter"
int_gauge_name = "testRaisesOnImproperFieldsUsage2_int_gauge"
event_metric_name = "testRaisesOnImproperFieldsUsage2_event_metric"
collector = self._CreateStatsCollector([
stats_utils.CreateCounterMetadata(
counter_name, fields=[("dimension", str)]),
stats_utils.CreateGaugeMetadata(
int_gauge_name, int, fields=[("dimension", str)]),
stats_utils.CreateEventMetadata(
event_metric_name, fields=[("dimension", str)])
])
# Check for counters
self.assertRaises(ValueError, collector.GetMetricValue, counter_name)
self.assertRaises(
ValueError, collector.GetMetricValue, counter_name, fields=["a", "b"])
# Check for gauges
self.assertRaises(ValueError, collector.GetMetricValue, int_gauge_name)
self.assertRaises(
ValueError, collector.GetMetricValue, int_gauge_name, fields=["a", "b"])
# Check for event metrics
self.assertRaises(ValueError, collector.GetMetricValue, event_metric_name)
self.assertRaises(
ValueError,
collector.GetMetricValue,
event_metric_name,
fields=["a", "b"])
def testGetAllMetricsMetadataWorksCorrectlyOnSimpleMetrics(self):
counter_name = "testGAMM_SimpleMetrics_counter"
int_gauge_name = "testGAMM_SimpleMetrics_int_gauge"
event_metric_name = "testGAMM_SimpleMetrics_event_metric"
collector = self._CreateStatsCollector([
stats_utils.CreateCounterMetadata(counter_name),
stats_utils.CreateGaugeMetadata(
int_gauge_name, int, fields=[("dimension", str)]),
stats_utils.CreateEventMetadata(event_metric_name)
])
metrics = collector.GetAllMetricsMetadata()
self.assertEqual(metrics[counter_name].metric_type,
rdf_stats.MetricMetadata.MetricType.COUNTER)
self.assertFalse(metrics[counter_name].fields_defs)
self.assertEqual(metrics[int_gauge_name].metric_type,
rdf_stats.MetricMetadata.MetricType.GAUGE)
self.assertEqual(metrics[int_gauge_name].fields_defs, [
rdf_stats.MetricFieldDefinition(
field_name="dimension",
field_type=rdf_stats.MetricFieldDefinition.FieldType.STR)
])
self.assertEqual(metrics[event_metric_name].metric_type,
rdf_stats.MetricMetadata.MetricType.EVENT)
self.assertFalse(metrics[event_metric_name].fields_defs)
def testGetMetricFieldsWorksCorrectly(self):
counter_name = "testGetMetricFieldsWorksCorrectly_counter"
int_gauge_name = "testGetMetricFieldsWorksCorrectly_int_gauge"
event_metric_name = "testGetMetricFieldsWorksCorrectly_event_metric"
collector = self._CreateStatsCollector([
stats_utils.CreateCounterMetadata(
counter_name, fields=[("dimension1", str), ("dimension2", str)]),
stats_utils.CreateGaugeMetadata(
int_gauge_name, int, fields=[("dimension", str)]),
stats_utils.CreateEventMetadata(
event_metric_name, fields=[("dimension", str)]),
])
collector.IncrementCounter(counter_name, fields=["b", "b"])
collector.IncrementCounter(counter_name, fields=["a", "c"])
collector.SetGaugeValue(int_gauge_name, 20, fields=["a"])
collector.SetGaugeValue(int_gauge_name, 30, fields=["b"])
collector.RecordEvent(event_metric_name, 0.1, fields=["a"])
collector.RecordEvent(event_metric_name, 0.1, fields=["b"])
fields = sorted(collector.GetMetricFields(counter_name), key=lambda t: t[0])
self.assertEqual([("a", "c"), ("b", "b")], fields)
fields = sorted(
collector.GetMetricFields(int_gauge_name), key=lambda t: t[0])
self.assertEqual([("a",), ("b",)], fields)
fields = sorted(
collector.GetMetricFields(event_metric_name), key=lambda t: t[0])
self.assertEqual([("a",), ("b",)], fields)
def testCountingDecorator(self):
"""Test _Function call counting."""
counter_name = "testCountingDecorator_counter"
collector = self._CreateStatsCollector(
[stats_utils.CreateCounterMetadata(counter_name)])
@stats_utils.Counted(counter_name)
def CountedFunc():
pass
with FakeStatsContext(collector):
for _ in builtins.range(10):
CountedFunc()
self.assertEqual(collector.GetMetricValue(counter_name), 10)
def testMaps(self):
"""Test binned timings."""
event_metric_name = "testMaps_event_metric"
collector = self._CreateStatsCollector([
stats_utils.CreateEventMetadata(
event_metric_name, bins=[0.0, 0.1, 0.2])
])
@stats_utils.Timed(event_metric_name)
def TimedFunc(n):
self._Sleep(n)
with FakeStatsContext(collector):
m = collector.GetMetricValue(event_metric_name)
self.assertEqual(m.bins_heights[0.0], 0)
self.assertEqual(m.bins_heights[0.1], 0)
self.assertEqual(m.bins_heights[0.2], 0)
for _ in builtins.range(3):
TimedFunc(0)
m = collector.GetMetricValue(event_metric_name)
self.assertEqual(m.bins_heights[0.0], 3)
self.assertEqual(m.bins_heights[0.1], 0)
self.assertEqual(m.bins_heights[0.2], 0)
TimedFunc(0.11)
m = collector.GetMetricValue(event_metric_name)
self.assertEqual(m.bins_heights[0.0], 3)
self.assertEqual(m.bins_heights[0.1], 1)
self.assertEqual(m.bins_heights[0.2], 0)
def testCombiningDecorators(self):
"""Test combining decorators."""
counter_name = "testCombiningDecorators_counter"
event_metric_name = "testCombiningDecorators_event_metric"
collector = self._CreateStatsCollector([
stats_utils.CreateCounterMetadata(counter_name),
stats_utils.CreateEventMetadata(
event_metric_name, bins=[0.0, 0.1, 0.2])
])
@stats_utils.Timed(event_metric_name)
@stats_utils.Counted(counter_name)
def OverdecoratedFunc(n):
self._Sleep(n)
with FakeStatsContext(collector):
OverdecoratedFunc(0.02)
# Check if all vars get updated
m = collector.GetMetricValue(event_metric_name)
self.assertEqual(m.bins_heights[0.0], 1)
self.assertEqual(m.bins_heights[0.1], 0)
self.assertEqual(m.bins_heights[0.2], 0)
self.assertEqual(collector.GetMetricValue(counter_name), 1)
def testExceptionHandling(self):
"""Test decorators when exceptions are thrown."""
counter_name = "testExceptionHandling_counter"
event_metric_name = "testExceptionHandling_event_metric"
collector = self._CreateStatsCollector([
stats_utils.CreateCounterMetadata(counter_name),
stats_utils.CreateEventMetadata(
event_metric_name, bins=[0.0, 0.1, 0.2])
])
@stats_utils.Timed(event_metric_name)
@stats_utils.Counted(counter_name)
def RaiseFunc(n):
self._Sleep(n)
raise Exception()
with FakeStatsContext(collector):
self.assertRaises(Exception, RaiseFunc, 0.11)
# Check if all vars get updated
m = collector.GetMetricValue(event_metric_name)
self.assertEqual(m.bins_heights[0.0], 0)
self.assertEqual(m.bins_heights[0.1], 1)
self.assertEqual(m.bins_heights[0.2], 0)
self.assertEqual(collector.GetMetricValue(counter_name), 1)
def testMultipleFuncs(self):
"""Tests if multiple decorators produce aggregate stats."""
counter_name = "testMultipleFuncs_counter"
event_metric_name = "testMultipleFuncs_event_metric"
collector = self._CreateStatsCollector([
stats_utils.CreateCounterMetadata(counter_name),
stats_utils.CreateEventMetadata(event_metric_name, bins=[0, 1, 2])
])
@stats_utils.Counted(counter_name)
def Func1(n):
self._Sleep(n)
@stats_utils.Counted(counter_name)
def Func2(n):
self._Sleep(n)
@stats_utils.Timed(event_metric_name)
def Func3(n):
self._Sleep(n)
@stats_utils.Timed(event_metric_name)
def Func4(n):
self._Sleep(n)
with FakeStatsContext(collector):
Func1(0)
Func2(0)
self.assertEqual(collector.GetMetricValue(counter_name), 2)
Func3(0)
Func4(1)
m = collector.GetMetricValue(event_metric_name)
self.assertEqual(m.bins_heights[0.0], 1)
self.assertEqual(m.bins_heights[1], 1)
self.assertEqual(m.bins_heights[2], 0)
| [
"[email protected]"
]
| |
3bf43960f9da4d4e5d45b38e5e355589716262fb | b26e1704b963881e7681712c923787772ac463ec | /Courses/PythonBeyondTheBasics(OO-Programming)_David-Blaikie/5_DecoratorsAbstractOverloading/Overloading.py | 363bc69ec423eaffc2ff2f78f05e6164582b97c9 | []
| no_license | lakshmikantdeshpande/Python-Courses | 64f8a397b727042f2662fa7597ea0e73491717f3 | d15364b42c182d3487532853bde37deb48865494 | refs/heads/master | 2021-09-02T06:51:19.490674 | 2017-12-31T06:55:53 | 2017-12-31T06:55:53 | 94,890,325 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,174 | py | import abc
class GetSetParent(object):
__metaclass__ = abc.ABCMeta
def __init__(self, value):
self.val = 0
def set_val(self, value):
self.val = value
def get_val(self):
return self.val
@abc.abstractmethod
def showdoc(self):
return
class GetSetInt(GetSetParent):
def set_val(self, value):
if not isinstance(value, int):
value = 0
super(GetSetInt, self).set_val(value)
def showdoc(self):
print('GetSetInt object {} only accepts integer values'.format(id(self)))
class GetSetList(GetSetInt):
def __init__(self, value=0):
self.vallist = [value]
def get_val(self):
return self.vallist[-1]
def get_vals(self):
return self.vallist
def set_val(self, value):
self.vallist.append(value)
def showdoc(self):
print('GetSetList object, len({}), stores '
'history of values set'.format(self.vallist))
gsint = GetSetInt(57)
gsint.set_val(5)
print(gsint.get_val())
gsint.showdoc()
print()
gslist = GetSetList(98)
print(gslist.get_val())
gslist.set_val(45)
print(gslist.get_vals())
gslist.showdoc()
| [
"[email protected]"
]
| |
df4255064e8d974709ec6b02c138f0f2edbd3933 | 7a6aca7d300c0752f2a73730b743a1a7361e941b | /tensorflow_graphics/projects/gan/losses.py | ff518414c8cdfba6b0e0cb2ad729061770a4a0b4 | [
"Apache-2.0"
]
| permissive | tensorflow/graphics | ef0abe102398a58eb7c41b709393df3d0b0a2811 | 1b0203eb538f2b6a1013ec7736d0d548416f059a | refs/heads/master | 2023-09-03T20:41:25.992578 | 2023-08-08T21:16:36 | 2023-08-08T21:17:31 | 164,626,274 | 2,920 | 413 | Apache-2.0 | 2023-08-27T14:26:47 | 2019-01-08T10:39:44 | Python | UTF-8 | Python | false | false | 12,394 | py | # Copyright 2020 The TensorFlow Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Module with loss functions."""
from collections import abc
from typing import Sequence, Union
import tensorflow as tf
def gradient_penalty_loss(real_data: Union[tf.Tensor, Sequence[tf.Tensor]],
generated_data: Union[tf.Tensor, Sequence[tf.Tensor]],
discriminator: tf.keras.Model,
weight: float = 10.0,
eps: float = 1e-8,
name_scope: str = 'gradient_penalty') -> tf.Tensor:
"""Gradient penalty loss.
This function implements the gradient penalty loss from "Improved Training of
Wasserstein GANs"
https://arxiv.org/abs/1704.00028
This version also implements the multi-scale extension proposed in "MSG-GAN:
Multi-Scale Gradient GAN for Stable Image Synthesis"
https://arxiv.org/abs/1903.06048
Args:
real_data: Samples from the real data.
generated_data: Samples from the generated data.
discriminator: The Keras model of the discriminator. This model is expected
to take as input a tf.Tensor or a sequence of tf.Tensor depending on what
is provided as generated_data and real_data.
weight: The weight of the loss.
eps: A small positive value that is added to the argument of the square root
to avoid undefined gradients.
name_scope: The name scope of the loss.
Returns:
The gradient penalty loss.
Raises:
TypeError if real_data and generated_data are not both either tf.Tensor or
both a sequence of tf.Tensor.
ValueError if the numnber of elements in real_data and generated_data are
not equal.
"""
with tf.name_scope(name=name_scope):
with tf.GradientTape() as tape:
if (isinstance(real_data, tf.Tensor) and
isinstance(generated_data, tf.Tensor)):
epsilon = tf.random.uniform(
[tf.shape(real_data)[0]] + [1] * (real_data.shape.ndims - 1),
minval=0.0,
maxval=1.0,
dtype=real_data.dtype)
interpolated_data = epsilon * real_data + (1.0 -
epsilon) * generated_data
elif (isinstance(real_data, abc.Sequence) and
isinstance(generated_data, abc.Sequence)):
if len(real_data) != len(generated_data):
raise ValueError(
'The number of elements in real_data and generated_data are '
'expected to be equal but got: %d and %d' %
(len(real_data), len(generated_data)))
epsilon = tf.random.uniform(
[tf.shape(real_data[0])[0]] + [1] * (real_data[0].shape.ndims - 1),
minval=0.0,
maxval=1.0,
dtype=real_data[0].dtype)
interpolated_data = [
epsilon * real_level + (1.0 - epsilon) * generated_level
for real_level, generated_level in zip(real_data, generated_data)
]
else:
raise TypeError(
'real_data and generated data should either both be a tf.Tensor '
'or both a sequence of tf.Tensor but got: %s and %s' %
(type(real_data), type(generated_data)))
# By default the gradient tape only watches trainable variables.
tape.watch(interpolated_data)
interpolated_labels = discriminator(interpolated_data)
with tf.name_scope(name='gradients'):
gradients = tape.gradient(
target=interpolated_labels, sources=interpolated_data)
if isinstance(real_data, tf.Tensor):
gradient_squares = tf.reduce_sum(
input_tensor=tf.square(gradients),
axis=tuple(range(1, gradients.shape.ndims)))
gradient_norms = tf.sqrt(gradient_squares + eps)
penalties_squared = tf.square(gradient_norms - 1.0)
return weight * penalties_squared
else:
all_penalties_squared = []
for gradients_level in gradients:
gradient_squares_level = tf.reduce_sum(
input_tensor=tf.square(gradients_level),
axis=tuple(range(1, gradients_level.shape.ndims)))
gradient_norms_level = tf.sqrt(gradient_squares_level + eps)
all_penalties_squared.append(tf.square(gradient_norms_level - 1.0))
return weight * tf.add_n(all_penalties_squared) * 1.0 / len(real_data)
def _sum_of_squares(input_tensor):
"""Computes the sum of squares of the tensor for each element in the batch."""
return tf.reduce_sum(
input_tensor=tf.square(input_tensor),
axis=tuple(range(1, input_tensor.shape.ndims)))
def r1_regularization(real_data: Union[tf.Tensor, Sequence[tf.Tensor]],
discriminator: tf.keras.Model,
weight: float = 10.0,
name='r1_regularization') -> tf.Tensor:
"""Implements the r1 regulariztion loss.
This regularization loss for discriminators is proposed in "Which Training
Methods for GANs do actually Converge?"
https://arxiv.org/abs/1801.04406
This version also implements the multi-scale extension proposed in "MSG-GAN:
Multi-Scale Gradient GAN for Stable Image Synthesis"
https://arxiv.org/abs/1903.06048
Args:
real_data: Samples from the real data.
discriminator: The Keras model of the discriminator. This model is expected
to take as input a tf.Tensor or a sequence of tf.Tensor depending on what
is provided as real_data.
weight: The weight of the loss.
name: The name scope of the loss.
Returns:
The r1 regulatization loss per example as tensor of shape [batch_size].
"""
with tf.name_scope(name):
with tf.GradientTape() as tape:
tape.watch(real_data)
discriminator_output = discriminator(real_data)
with tf.name_scope(name='gradients'):
gradients = tape.gradient(
target=discriminator_output, sources=real_data)
if isinstance(real_data, tf.Tensor):
gradient_squares = _sum_of_squares(gradients)
return weight * 0.5 * gradient_squares
else:
gradient_squares_level = [
_sum_of_squares(gradients_level) for gradients_level in gradients
]
return weight * 0.5 * tf.add_n(gradient_squares_level) * 1.0 / len(
real_data)
def wasserstein_generator_loss(
discriminator_output_generated_data: tf.Tensor,
name: str = 'wasserstein_generator_loss') -> tf.Tensor:
"""Generator loss for Wasserstein GAN.
This loss function is generally used together with a regularization of the
discriminator such as weight clipping (https://arxiv.org/abs/1701.07875),
gradient penalty (https://arxiv.org/abs/1704.00028) or spectral
normalization (https://arxiv.org/abs/1802.05957).
Args:
discriminator_output_generated_data: Output of the discriminator for
generated data.
name: The name of the name_scope that is placed around the loss.
Returns:
The loss for the generator.
"""
with tf.name_scope(name=name):
return -discriminator_output_generated_data
def wasserstein_discriminator_loss(
discriminator_output_real_data: tf.Tensor,
discriminator_output_generated_data: tf.Tensor,
name: str = 'wasserstein_discriminator_loss') -> tf.Tensor:
"""Discriminator loss for Wasserstein GAN.
This loss function is generally used together with a regularization of the
discriminator such as weight clipping (https://arxiv.org/abs/1701.07875),
gradient penalty (https://arxiv.org/abs/1704.00028) or spectral
normalization (https://arxiv.org/abs/1802.05957).
Args:
discriminator_output_real_data: Output of the discriminator for the real
data.
discriminator_output_generated_data: Output of the discriminator for
generated data.
name: The name of the name_scope that is placed around the loss.
Returns:
The loss for the discriminator.
"""
with tf.name_scope(name=name):
return discriminator_output_generated_data - discriminator_output_real_data
def wasserstein_hinge_generator_loss(
discriminator_output_generated_data: tf.Tensor,
name: str = 'wasserstein_hinge_generator_loss') -> tf.Tensor:
"""Generator loss for the hinge Wasserstein GAN.
This loss function is generally used together with a regularization of the
discriminator such as weight clipping (https://arxiv.org/abs/1701.07875),
gradient penalty (https://arxiv.org/abs/1704.00028) or spectral
normalization (https://arxiv.org/abs/1802.05957).
Note that the generator loss does not have a hinge
(https://arxiv.org/pdf/1805.08318.pdf).
Args:
discriminator_output_generated_data: Output of the discriminator for
generated data.
name: The name of the name_scope that is placed around the loss.
Returns:
The loss for the generator.
"""
with tf.name_scope(name=name):
return -discriminator_output_generated_data
def wasserstein_hinge_discriminator_loss(
discriminator_output_real_data: tf.Tensor,
discriminator_output_generated_data: tf.Tensor,
name: str = 'wasserstein_hinge_discriminator_loss') -> tf.Tensor:
"""Discriminator loss for the hinge Wasserstein GAN.
This loss function is generally used together with a regularization of the
discriminator such as weight clipping (https://arxiv.org/abs/1701.07875),
gradient penalty (https://arxiv.org/abs/1704.00028) or spectral
normalization (https://arxiv.org/abs/1802.05957).
Args:
discriminator_output_real_data: Output of the discriminator for the real
data.
discriminator_output_generated_data: Output of the discriminator for
generated data.
name: The name of the name_scope that is placed around the loss.
Returns:
The loss for the discriminator.
"""
with tf.name_scope(name=name):
return tf.nn.relu(1.0 - discriminator_output_real_data) + tf.nn.relu(
discriminator_output_generated_data + 1.0)
def minimax_generator_loss(discriminator_output_generated_data: tf.Tensor,
name: str = 'minimax_generator_loss') -> tf.Tensor:
"""Generator loss from the original minimax GAN.
This loss function implements the non saturating version of the minimax loss
for the generator as proposed in https://arxiv.org/pdf/1406.2661.pdf.
Args:
discriminator_output_generated_data: Output of the discriminator for
generated data.
name: The name of the name_scope that is placed around the loss.
Returns:
The loss for the generator.
"""
with tf.name_scope(name=name):
# -log(sigmoid(discriminator_output_generated_data))
return tf.nn.sigmoid_cross_entropy_with_logits(
labels=tf.ones_like(discriminator_output_generated_data),
logits=discriminator_output_generated_data)
def minimax_discriminator_loss(
discriminator_output_real_data: tf.Tensor,
discriminator_output_generated_data: tf.Tensor,
name: str = 'minimax_discriminator_loss') -> tf.Tensor:
"""Discriminator loss from the original minimax GAN.
This loss function implements the minimax loss
for the discriminator as proposed in https://arxiv.org/pdf/1406.2661.pdf.
Args:
discriminator_output_real_data: Output of the discriminator for the real
data.
discriminator_output_generated_data: Output of the discriminator for
generated data.
name: The name of the name_scope that is placed around the loss.
Returns:
The loss for the discriminator.
"""
with tf.name_scope(name=name):
# -log(sigmoid(discriminator_output_real_data))
loss_real = tf.nn.sigmoid_cross_entropy_with_logits(
labels=tf.ones_like(discriminator_output_real_data),
logits=discriminator_output_real_data)
# -log(1 - sigmoid(discriminator_output_generated_data))
loss_generated = tf.nn.sigmoid_cross_entropy_with_logits(
labels=tf.zeros_like(discriminator_output_generated_data),
logits=discriminator_output_generated_data)
return loss_real + loss_generated
| [
"[email protected]"
]
| |
0a59b48100a131f414e36062aac414f027c0acbf | d85f3bfcc7efb3313bd77ba43abbde8527c731d9 | /ch09/bottle_test.py | 970ecfd6283ec60311f0f7a3468eeda61c222bd3 | []
| no_license | freebz/Introducing-Python | 8c62767e88b89eb614abd3ea4cf19aae946f5379 | ecf2082946eac83072328a80ed1e06b416ef5170 | refs/heads/master | 2020-04-08T21:14:42.398462 | 2018-11-29T17:03:11 | 2018-11-29T17:03:11 | 159,736,171 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 263 | py | import requests
resp = requests.get('http://localhost:9999/echo/Mothra')
if resp.status_code == 200 and \
resp.text == 'Say hello to my little friend: Mothra!':
print('It worked! That almost never happens!')
else:
print('Argh, got this:', resp.text)
| [
"[email protected]"
]
| |
713e8ca9e8e74d63af7aaad24b92e81f479bd8fe | 1d63d795ceb579f3f4ac7d27d61ad2c3298dd8d1 | /vendor/blockwise_view.py | d52cfd63cbe14666bfdd5bf7da6bdd7ef32d8076 | [
"MIT"
]
| permissive | austinpray/hey-brether | 4fd1f95f08673e35a15c53a9d4aca43502d0dc7e | 8fa9f83df0da5bc570f60a83a27f72babecb0c18 | refs/heads/master | 2021-08-27T16:42:29.578384 | 2021-08-22T21:41:22 | 2021-08-22T21:41:22 | 142,895,876 | 3 | 1 | MIT | 2018-07-30T20:13:18 | 2018-07-30T15:42:09 | Python | UTF-8 | Python | false | false | 3,745 | py | # lifted from
# https://github.com/ilastik/lazyflow/blob/master/lazyflow/utility/blockwise_view.py
# https://github.com/ilastik/lazyflow/blob/e98aa81cf2d55595df41b161d8e74607ec09c716/lazyflow/utility/blockwise_view.py
from __future__ import division
from builtins import map
import numpy
try:
# If you use vigra, we do special handling to preserve axistags
import vigra
_vigra_available = True
except ImportError:
_vigra_available = False
def blockwise_view( a, blockshape, aslist=False, require_aligned_blocks=True ):
"""
Return a 2N-D view of the given N-D array, rearranged so each ND block (tile)
of the original array is indexed by its block address using the first N
indexes of the output array.
Note: This function is nearly identical to ``skimage.util.view_as_blocks()``, except:
- "imperfect" block shapes are permitted (via require_aligned_blocks=False)
- only contiguous arrays are accepted. (This function will NOT silently copy your array.)
As a result, the return value is *always* a view of the input.
Args:
a: The ND array
blockshape: The tile shape
aslist: If True, return all blocks as a list of ND blocks
instead of a 2D array indexed by ND block coordinate.
require_aligned_blocks: If True, check to make sure no data is "left over"
in each row/column/etc. of the output view.
That is, the blockshape must divide evenly into the full array shape.
If False, "leftover" items that cannot be made into complete blocks
will be discarded from the output view.
Here's a 2D example (this function also works for ND):
>>> a = numpy.arange(1,21).reshape(4,5)
>>> print a
[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[11 12 13 14 15]
[16 17 18 19 20]]
>>> view = blockwise_view(a, (2,2), False)
>>> print view
[[[[ 1 2]
[ 6 7]]
<BLANKLINE>
[[ 3 4]
[ 8 9]]]
<BLANKLINE>
<BLANKLINE>
[[[11 12]
[16 17]]
<BLANKLINE>
[[13 14]
[18 19]]]]
Inspired by the 2D example shown here: http://stackoverflow.com/a/8070716/162094
"""
assert a.flags['C_CONTIGUOUS'], "This function relies on the memory layout of the array."
blockshape = tuple(blockshape)
outershape = tuple(numpy.array(a.shape) // blockshape)
view_shape = outershape + blockshape
if require_aligned_blocks:
assert (numpy.mod(a.shape, blockshape) == 0).all(), \
"blockshape {} must divide evenly into array shape {}"\
.format( blockshape, a.shape )
# inner strides: strides within each block (same as original array)
intra_block_strides = a.strides
# outer strides: strides from one block to another
inter_block_strides = tuple(a.strides * numpy.array(blockshape))
# This is where the magic happens.
# Generate a view with our new strides (outer+inner).
view = numpy.lib.stride_tricks.as_strided(a,
shape=view_shape,
strides=(inter_block_strides+intra_block_strides))
# Special handling for VigraArrays
if _vigra_available and isinstance(a, vigra.VigraArray) and hasattr(a, 'axistags'):
view_axistags = vigra.AxisTags([vigra.AxisInfo() for _ in blockshape] + list(a.axistags))
view = vigra.taggedView(view, view_axistags)
if aslist:
return list(map(view.__getitem__, numpy.ndindex(outershape)))
return view
if __name__ == "__main__":
import doctest
doctest.testmod()
| [
"[email protected]"
]
| |
d9040e75c7238b479f6ec9ac27efe459df9a5925 | 652121d51e6ff25aa5b1ad6df2be7eb341683c35 | /programs/e2boxadjust.py | 04168ce207137b8a80ac1faef462b4297f3943e0 | []
| no_license | jgalaz84/eman2 | be93624f1c261048170b85416e517e5813992501 | 6d3a1249ed590bbc92e25fb0fc319e3ce17deb65 | refs/heads/master | 2020-04-25T18:15:55.870663 | 2015-06-05T20:21:44 | 2015-06-05T20:21:44 | 36,952,784 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,711 | py | #!/usr/bin/env python
#
# Author: Steven Ludtke, 3/29/15 ([email protected])
# Copyright (c) 2000-2015 Baylor College of Medicine
#
# This software is issued under a joint BSD/GNU license. You may use the
# source code in this file under either license. However, note that the
# complete EMAN2 and SPARX software packages have some GPL dependencies,
# so you are responsible for compliance with the licenses of these packages
# if you opt to use BSD licensing. The warranty disclaimer below holds
# in either instance.
#
# This complete copyright notice must be included in any revised version of the
# source code. Additional authorship citations may be added, but existing
# author citations must be preserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 2111-1307 USA
#
from EMAN2 import *
from math import *
import time
import os
import sys
def main():
progname = os.path.basename(sys.argv[0])
usage = """prog [options] <sets/file.lst> <classmx_xx.hdf> <box3d 1> <box3d 2> ...
This program is part of a pipeline to improve centering of subtomograms prior to alignment and averaging.
This is a typical workflow:
1) select 3-D particles and store locations in .box3d files with names agreeing with the name of the tomogram, eg
rawtomograms/file0001.hdf -> rawtomograms/file0001.box3d
2) extract the 3-D particles from the tomograms, and generate Z-projections corresponding to each particle (this may be done automatically by e2spt_boxer)
3) insure that the Z-projections are normalized, filtered and have postive (white) contrast against the background, eg:
e2proc2d.py spt_particles/file0001_prjsz.hdf spt_particles/file0001_prjsz.hdf --inplace --process filter.lowpass.gauss:cutoff_abs=0.1 --process filter.highpass.gauss:cutoff_abs=0.02 --mult -1 --process normalize.edgemean
4) build a set containing all of the z projection stacks, eg
e2proclst.py spt_particles/file0001_prjsz.hdf spt_particles/file0002_prjsz.hdf --create sets/all_prjsz.lst
5) run e2refine2d.py
6) run this program, eg
e2boxadjust.py sets/all_prjsz.lst r2d_01/classmx_08.hdf rawtomograms/*box3d -v 2
7) re-extract the particles using the new _cen.box3d files
"""
parser = EMArgumentParser(usage=usage,version=EMANVERSION)
#parser.add_argument("--normproj",action="store_true",help="Normalize the projections resulting from 'project', such that the length of each vector is 1",default=False)
#parser.add_argument("--normalize",type=str,help="Normalize the input images using the named processor. Specify None to disable.",default="normalize.unitlen")
parser.add_argument("--verbose", "-v", dest="verbose", action="store", metavar="n",type=int, default=0, help="verbose level [0-9], higner number means higher level of verboseness")
parser.add_argument("--ppid", type=int, help="Set the PID of the parent process, used for cross platform PPID",default=-1)
(options, args) = parser.parse_args()
# if len(args)>0 : parser.error("e2basis.py takes no arguments, only options")
logid=E2init(sys.argv,options.ppid)
# The classmx file contains particle alignment information
classmx=EMData(args[1],0)
nptcl=classmx["ny"]
cmxtx=EMData(args[1],2)
cmxty=EMData(args[1],3)
cmxalpha=EMData(args[1],4)
cmxmirror=EMData(args[1],5)
print "Classmx has info on ",nptcl," particles"
# The files containing the particle locations
boxfiles=[base_name(args[i],nodir=True) for i in xrange(2,len(args))]
# The .lst file allowing us to reference original files from the information in cls files
lsx=LSXFile(args[0])
lpfile=None
skipfile=True
for p in xrange(nptcl):
# The number and file of particle N
pn,pfile,com = lsx[p]
if pfile!=lpfile:
# write the boxes from the last file
if not skipfile: write_boxes(curboxfile,curboxes)
skipfile=False
pfileb=base_name(pfile,nodir=True)
if not pfileb in boxfiles :
print "No box file found for: ",pfileb
lpfile=pfile
skipfile=True
continue
# This is the file containing the box locations for this range of particles
curboxfile=args[boxfiles.index(pfileb)+2]
p0=p
if options.verbose: print pfileb,"->",curboxfile
# These are the box locations within that file
curboxes=[[int(j) for j in i.split()] for i in file(curboxfile,"r") if i[0]!="#"]
lpfile=pfile
else:
if skipfile : continue # we've already identified this as a file we don't have box locations for
ptclxf=Transform({"type":"2d","alpha":cmxalpha[0,p],"mirror":int(cmxmirror[0,p]),"tx":cmxtx[0,p],"ty":cmxty[0,p]})
pt2d=ptclxf.get_pre_trans_2d()
curboxes[p-p0][0]-=pt2d[0]
curboxes[p-p0][1]-=pt2d[1]
if options.verbose>1:
try: print "{}) {}: {}\t {:d},{:d}".format(p,p-p0,pfileb,int(pt2d[0]),int(pt2d[1]))
except: pass
if not skipfile: write_boxes(curboxfile,curboxes)
E2end(logid)
def write_boxes(curboxfile,curboxes):
print "Writing updated boxes for: ",curboxfile
out=file(curboxfile.split(".")[0]+"_cen.box3d","w")
for b in curboxes: out.write("{:d}\t{:d}\t{:d}\n".format(int(b[0]),int(b[1]),int(b[2])))
if __name__== "__main__":
main()
| [
"[email protected]"
]
| |
ddb9ad202cdbc5e33117c89d3cc18c383c3bf9cd | 576d1fb42b1a99dba18e78da58b352ebeac8fe64 | /tests/single_instruction_translation_validation/mcsema/register-variants/cmovncl_r32_r32/Output/test-z3.py | e8ffc88d2a477848d33164003d16aec5c67597ef | [
"LicenseRef-scancode-unknown-license-reference",
"NCSA"
]
| permissive | mewbak/validating-binary-decompilation-1 | b4542919d2e8f4a603cdadeade4dcf7919d6d1d8 | e7ae1838e8da7930730d76aaf01f315cf1d966a1 | refs/heads/master | 2021-01-08T05:33:48.560721 | 2020-02-12T00:27:01 | 2020-02-12T18:07:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,564 | py | #############################################
######## Auto Generated Proof Scripts #######
#############################################
import z3
import sys
status=True
test_name="UnK"
if(len(sys.argv) > 1):
test_name = sys.argv[1]
def solve(msg, lvar, xvar, s):
global status
s.set("timeout", 60000)
res = s.check()
if(z3.unknown == res):
print(test_name + "::" + msg + "::unk")
status = "Unknown"
if(z3.sat == res):
if("UNDEF" in xvar.sexpr()):
print(test_name + "::" + msg + "::undef-sat")
else:
m = s.model()
print(test_name + "::" + msg + "::sat")
print("\n")
print("query", s)
print("\n")
print("model", m)
print("\n")
print("xvar =", m.evaluate(xvar))
print("lvar =", m.evaluate(lvar))
print("\n")
status = False
##############################
## X86 specific variables ####
##############################
### GPRs
VX_RAX = z3.BitVec('VX_RAX',64)
VX_RBX = z3.BitVec('VX_RBX',64)
VX_RCX = z3.BitVec('VX_RCX',64)
VX_RDX = z3.BitVec('VX_RDX',64)
VX_RSI = z3.BitVec('VX_RSI',64)
VX_RDI = z3.BitVec('VX_RDI',64)
### Flags
VX_CF = z3.BitVec('VX_CF',1)
VX_PF = z3.BitVec('VX_PF',1)
VX_ZF = z3.BitVec('VX_ZF',1)
VX_SF = z3.BitVec('VX_SF',1)
VX_AF = z3.BitVec('VX_AF',1)
VX_OF = z3.BitVec('VX_OF',1)
### YMM Registers
VX_YMM1 = z3.BitVec('VX_YMM1', 256)
VX_YMM2 = z3.BitVec('VX_YMM2', 256)
## Undef
VX_UNDEF_1 = z3.BitVec('VX_UNDEF_1', 1)
##############################
## X86 specific variables ####
##############################
### GPRs
VL_RAX = z3.BitVec('VL_RAX',64)
VL_RBX = z3.BitVec('VL_RBX',64)
VL_RCX = z3.BitVec('VL_RCX',64)
VL_RDX = z3.BitVec('VL_RDX',64)
VL_RSI = z3.BitVec('VL_RSI',64)
VL_RDI = z3.BitVec('VL_RDI',64)
### Flags
VL_CF = z3.BitVec('VL_CF',8)
VL_PF = z3.BitVec('VL_PF',8)
VL_ZF = z3.BitVec('VL_ZF',8)
VL_SF = z3.BitVec('VL_SF',8)
VL_AF = z3.BitVec('VL_AF',8)
VL_OF = z3.BitVec('VL_OF',8)
### YMM Registers
VL_YMM1_0 = z3.BitVec('VL_YMM1_0', 64)
VL_YMM1_1 = z3.BitVec('VL_YMM1_1', 64)
VL_YMM1_2 = z3.BitVec('VL_YMM1_2', 64)
VL_YMM1_3 = z3.BitVec('VL_YMM1_3', 64)
VL_YMM2_0 = z3.BitVec('VL_YMM2_0', 64)
VL_YMM2_1 = z3.BitVec('VL_YMM2_1', 64)
VL_YMM2_2 = z3.BitVec('VL_YMM2_2', 64)
VL_YMM2_3 = z3.BitVec('VL_YMM2_3', 64)
##############################
## Proof variables ###########
##############################
V_R = z3.BitVec('V_R',64)
V_F = z3.BitVec('V_F',1)
V_Y = z3.BitVec('V_Y',256)
## Solver instance
s = z3.Solver()
##############################
## Default constraints #######
##############################
### GPRs
s.add(VX_RAX == VL_RAX)
s.add(VX_RBX == VL_RBX)
s.add(VX_RCX == VL_RCX)
s.add(VX_RDX == VL_RDX)
s.add(VX_RDI == VL_RDI)
s.add(VX_RSI == VL_RSI)
### Flags
s.add(z3.Or(VL_CF == 0, VL_CF == 1))
s.add(z3.Or(VL_ZF == 0, VL_ZF == 1))
s.add(z3.Or(VL_PF == 0, VL_PF == 1))
s.add(z3.Or(VL_SF == 0, VL_SF == 1))
s.add(z3.Or(VL_AF == 0, VL_AF == 1))
s.add(z3.Or(VL_OF == 0, VL_OF == 1))
s.add(z3.Extract(0,0, VL_CF) == VX_CF)
s.add(z3.Extract(0,0, VL_SF) == VX_SF)
s.add(z3.Extract(0,0, VL_ZF) == VX_ZF)
s.add(z3.Extract(0,0, VL_PF) == VX_PF)
s.add(z3.Extract(0,0, VL_AF) == VX_AF)
s.add(z3.Extract(0,0, VL_OF) == VX_OF)
### Ymms
s.add(z3.Concat(VL_YMM1_3, VL_YMM1_2, VL_YMM1_1, VL_YMM1_0) == VX_YMM1)
s.add(z3.Concat(VL_YMM2_3, VL_YMM2_2, VL_YMM2_1, VL_YMM2_0) == VX_YMM2)
## =******= AF =******=
s.push()
lvar = z3.And(
z3.Implies(
(z3.If((VL_CF == z3.BitVecVal(0, 8)), z3.BitVecVal(1, 8), z3.BitVecVal(0, 8)) == z3.BitVecVal(0, 8)),
V_F == z3.Extract(0, 0, z3.Extract(7, 0, VL_AF))
),
z3.Implies(
((z3.If((VL_CF == z3.BitVecVal(0, 8)), z3.BitVecVal(1, 8), z3.BitVecVal(0, 8)) == z3.BitVecVal(0, 8)) == False),
V_F == z3.Extract(0, 0, z3.Extract(7, 0, VL_AF))
),
)
xvar = (V_F == VX_AF)
s.add(lvar != xvar)
solve("AF", lvar, xvar, s)
s.pop()
## =******= CF =******=
s.push()
lvar = z3.And(
z3.Implies(
(z3.If((VL_CF == z3.BitVecVal(0, 8)), z3.BitVecVal(1, 8), z3.BitVecVal(0, 8)) == z3.BitVecVal(0, 8)),
V_F == z3.Extract(0, 0, z3.Extract(7, 0, VL_CF))
),
z3.Implies(
((z3.If((VL_CF == z3.BitVecVal(0, 8)), z3.BitVecVal(1, 8), z3.BitVecVal(0, 8)) == z3.BitVecVal(0, 8)) == False),
V_F == z3.Extract(0, 0, z3.Extract(7, 0, VL_CF))
),
)
xvar = (V_F == VX_CF)
s.add(lvar != xvar)
solve("CF", lvar, xvar, s)
s.pop()
## =******= OF =******=
s.push()
lvar = z3.And(
z3.Implies(
(z3.If((VL_CF == z3.BitVecVal(0, 8)), z3.BitVecVal(1, 8), z3.BitVecVal(0, 8)) == z3.BitVecVal(0, 8)),
V_F == z3.Extract(0, 0, z3.Extract(7, 0, VL_OF))
),
z3.Implies(
((z3.If((VL_CF == z3.BitVecVal(0, 8)), z3.BitVecVal(1, 8), z3.BitVecVal(0, 8)) == z3.BitVecVal(0, 8)) == False),
V_F == z3.Extract(0, 0, z3.Extract(7, 0, VL_OF))
),
)
xvar = (V_F == VX_OF)
s.add(lvar != xvar)
solve("OF", lvar, xvar, s)
s.pop()
## =******= PF =******=
s.push()
lvar = z3.And(
z3.Implies(
(z3.If((VL_CF == z3.BitVecVal(0, 8)), z3.BitVecVal(1, 8), z3.BitVecVal(0, 8)) == z3.BitVecVal(0, 8)),
V_F == z3.Extract(0, 0, z3.Extract(7, 0, VL_PF))
),
z3.Implies(
((z3.If((VL_CF == z3.BitVecVal(0, 8)), z3.BitVecVal(1, 8), z3.BitVecVal(0, 8)) == z3.BitVecVal(0, 8)) == False),
V_F == z3.Extract(0, 0, z3.Extract(7, 0, VL_PF))
),
)
xvar = (V_F == VX_PF)
s.add(lvar != xvar)
solve("PF", lvar, xvar, s)
s.pop()
## =******= RAX =******=
s.push()
lvar = z3.And(
z3.Implies(
(z3.If((VL_CF == z3.BitVecVal(0, 8)), z3.BitVecVal(1, 8), z3.BitVecVal(0, 8)) == z3.BitVecVal(0, 8)),
V_R == z3.Concat(z3.Extract(63, 56, VL_RAX), z3.Extract(55, 48, VL_RAX), z3.Extract(47, 40, VL_RAX), z3.Extract(39, 32, VL_RAX), z3.Extract(31, 24, VL_RAX), z3.Extract(23, 16, VL_RAX), z3.Extract(15, 8, VL_RAX), z3.Extract(7, 0, VL_RAX))
),
z3.Implies(
((z3.If((VL_CF == z3.BitVecVal(0, 8)), z3.BitVecVal(1, 8), z3.BitVecVal(0, 8)) == z3.BitVecVal(0, 8)) == False),
V_R == z3.Concat(z3.Extract(63, 56, VL_RAX), z3.Extract(55, 48, VL_RAX), z3.Extract(47, 40, VL_RAX), z3.Extract(39, 32, VL_RAX), z3.Extract(31, 24, VL_RAX), z3.Extract(23, 16, VL_RAX), z3.Extract(15, 8, VL_RAX), z3.Extract(7, 0, VL_RAX))
),
)
xvar = (V_R == VX_RAX)
s.add(lvar != xvar)
solve("RAX", lvar, xvar, s)
s.pop()
## =******= RBX =******=
s.push()
lvar = z3.And(
z3.Implies(
(z3.If((VL_CF == z3.BitVecVal(0, 8)), z3.BitVecVal(1, 8), z3.BitVecVal(0, 8)) == z3.BitVecVal(0, 8)),
V_R == z3.Concat(z3.Extract(63, 56, ((VL_RBX & z3.BitVecVal(4294967295, 64)) & z3.BitVecVal(18446744073709551616 - 1, 64))), z3.Extract(55, 48, ((VL_RBX & z3.BitVecVal(4294967295, 64)) & z3.BitVecVal(18446744073709551616 - 1, 64))), z3.Extract(47, 40, ((VL_RBX & z3.BitVecVal(4294967295, 64)) & z3.BitVecVal(18446744073709551616 - 1, 64))), z3.Extract(39, 32, ((VL_RBX & z3.BitVecVal(4294967295, 64)) & z3.BitVecVal(18446744073709551616 - 1, 64))), z3.Extract(31, 24, ((VL_RBX & z3.BitVecVal(4294967295, 64)) & z3.BitVecVal(18446744073709551616 - 1, 64))), z3.Extract(23, 16, ((VL_RBX & z3.BitVecVal(4294967295, 64)) & z3.BitVecVal(18446744073709551616 - 1, 64))), z3.Extract(15, 8, ((VL_RBX & z3.BitVecVal(4294967295, 64)) & z3.BitVecVal(18446744073709551616 - 1, 64))), z3.Extract(7, 0, ((VL_RBX & z3.BitVecVal(4294967295, 64)) & z3.BitVecVal(18446744073709551616 - 1, 64))))
),
z3.Implies(
((z3.If((VL_CF == z3.BitVecVal(0, 8)), z3.BitVecVal(1, 8), z3.BitVecVal(0, 8)) == z3.BitVecVal(0, 8)) == False),
V_R == z3.Concat(z3.Extract(63, 56, ((z3.Concat(z3.BitVecVal(0, 32), z3.Concat(z3.Extract(31, 24, VL_RCX),z3.Extract(23, 16, VL_RCX),z3.Extract(15, 8, VL_RCX),z3.Extract(7, 0, VL_RCX),)) & z3.BitVecVal(4294967295, 64)) & z3.BitVecVal(18446744073709551616 - 1, 64))), z3.Extract(55, 48, ((z3.Concat(z3.BitVecVal(0, 32), z3.Concat(z3.Extract(31, 24, VL_RCX),z3.Extract(23, 16, VL_RCX),z3.Extract(15, 8, VL_RCX),z3.Extract(7, 0, VL_RCX),)) & z3.BitVecVal(4294967295, 64)) & z3.BitVecVal(18446744073709551616 - 1, 64))), z3.Extract(47, 40, ((z3.Concat(z3.BitVecVal(0, 32), z3.Concat(z3.Extract(31, 24, VL_RCX),z3.Extract(23, 16, VL_RCX),z3.Extract(15, 8, VL_RCX),z3.Extract(7, 0, VL_RCX),)) & z3.BitVecVal(4294967295, 64)) & z3.BitVecVal(18446744073709551616 - 1, 64))), z3.Extract(39, 32, ((z3.Concat(z3.BitVecVal(0, 32), z3.Concat(z3.Extract(31, 24, VL_RCX),z3.Extract(23, 16, VL_RCX),z3.Extract(15, 8, VL_RCX),z3.Extract(7, 0, VL_RCX),)) & z3.BitVecVal(4294967295, 64)) & z3.BitVecVal(18446744073709551616 - 1, 64))), z3.Extract(31, 24, ((z3.Concat(z3.BitVecVal(0, 32), z3.Concat(z3.Extract(31, 24, VL_RCX),z3.Extract(23, 16, VL_RCX),z3.Extract(15, 8, VL_RCX),z3.Extract(7, 0, VL_RCX),)) & z3.BitVecVal(4294967295, 64)) & z3.BitVecVal(18446744073709551616 - 1, 64))), z3.Extract(23, 16, ((z3.Concat(z3.BitVecVal(0, 32), z3.Concat(z3.Extract(31, 24, VL_RCX),z3.Extract(23, 16, VL_RCX),z3.Extract(15, 8, VL_RCX),z3.Extract(7, 0, VL_RCX),)) & z3.BitVecVal(4294967295, 64)) & z3.BitVecVal(18446744073709551616 - 1, 64))), z3.Extract(15, 8, ((z3.Concat(z3.BitVecVal(0, 32), z3.Concat(z3.Extract(31, 24, VL_RCX),z3.Extract(23, 16, VL_RCX),z3.Extract(15, 8, VL_RCX),z3.Extract(7, 0, VL_RCX),)) & z3.BitVecVal(4294967295, 64)) & z3.BitVecVal(18446744073709551616 - 1, 64))), z3.Extract(7, 0, ((z3.Concat(z3.BitVecVal(0, 32), z3.Concat(z3.Extract(31, 24, VL_RCX),z3.Extract(23, 16, VL_RCX),z3.Extract(15, 8, VL_RCX),z3.Extract(7, 0, VL_RCX),)) & z3.BitVecVal(4294967295, 64)) & z3.BitVecVal(18446744073709551616 - 1, 64))))
),
)
xvar = (V_R == z3.Concat(z3.BitVecVal(0, 32), z3.If(z3.Not((VX_CF == z3.BitVecVal(1, 1))), z3.Extract(31, 0, VX_RCX), z3.Extract(31, 0, VX_RBX))))
s.add(lvar != xvar)
solve("RBX", lvar, xvar, s)
s.pop()
## =******= RCX =******=
s.push()
lvar = z3.And(
z3.Implies(
(z3.If((VL_CF == z3.BitVecVal(0, 8)), z3.BitVecVal(1, 8), z3.BitVecVal(0, 8)) == z3.BitVecVal(0, 8)),
V_R == z3.Concat(z3.Extract(63, 56, VL_RCX), z3.Extract(55, 48, VL_RCX), z3.Extract(47, 40, VL_RCX), z3.Extract(39, 32, VL_RCX), z3.Extract(31, 24, VL_RCX), z3.Extract(23, 16, VL_RCX), z3.Extract(15, 8, VL_RCX), z3.Extract(7, 0, VL_RCX))
),
z3.Implies(
((z3.If((VL_CF == z3.BitVecVal(0, 8)), z3.BitVecVal(1, 8), z3.BitVecVal(0, 8)) == z3.BitVecVal(0, 8)) == False),
V_R == z3.Concat(z3.Extract(63, 56, VL_RCX), z3.Extract(55, 48, VL_RCX), z3.Extract(47, 40, VL_RCX), z3.Extract(39, 32, VL_RCX), z3.Extract(31, 24, VL_RCX), z3.Extract(23, 16, VL_RCX), z3.Extract(15, 8, VL_RCX), z3.Extract(7, 0, VL_RCX))
),
)
xvar = (V_R == VX_RCX)
s.add(lvar != xvar)
solve("RCX", lvar, xvar, s)
s.pop()
## =******= RDX =******=
s.push()
lvar = z3.And(
z3.Implies(
(z3.If((VL_CF == z3.BitVecVal(0, 8)), z3.BitVecVal(1, 8), z3.BitVecVal(0, 8)) == z3.BitVecVal(0, 8)),
V_R == z3.Concat(z3.Extract(63, 56, VL_RDX), z3.Extract(55, 48, VL_RDX), z3.Extract(47, 40, VL_RDX), z3.Extract(39, 32, VL_RDX), z3.Extract(31, 24, VL_RDX), z3.Extract(23, 16, VL_RDX), z3.Extract(15, 8, VL_RDX), z3.Extract(7, 0, VL_RDX))
),
z3.Implies(
((z3.If((VL_CF == z3.BitVecVal(0, 8)), z3.BitVecVal(1, 8), z3.BitVecVal(0, 8)) == z3.BitVecVal(0, 8)) == False),
V_R == z3.Concat(z3.Extract(63, 56, VL_RDX), z3.Extract(55, 48, VL_RDX), z3.Extract(47, 40, VL_RDX), z3.Extract(39, 32, VL_RDX), z3.Extract(31, 24, VL_RDX), z3.Extract(23, 16, VL_RDX), z3.Extract(15, 8, VL_RDX), z3.Extract(7, 0, VL_RDX))
),
)
xvar = (V_R == VX_RDX)
s.add(lvar != xvar)
solve("RDX", lvar, xvar, s)
s.pop()
## =******= SF =******=
s.push()
lvar = z3.And(
z3.Implies(
(z3.If((VL_CF == z3.BitVecVal(0, 8)), z3.BitVecVal(1, 8), z3.BitVecVal(0, 8)) == z3.BitVecVal(0, 8)),
V_F == z3.Extract(0, 0, z3.Extract(7, 0, VL_SF))
),
z3.Implies(
((z3.If((VL_CF == z3.BitVecVal(0, 8)), z3.BitVecVal(1, 8), z3.BitVecVal(0, 8)) == z3.BitVecVal(0, 8)) == False),
V_F == z3.Extract(0, 0, z3.Extract(7, 0, VL_SF))
),
)
xvar = (V_F == VX_SF)
s.add(lvar != xvar)
solve("SF", lvar, xvar, s)
s.pop()
## =******= ZF =******=
s.push()
lvar = z3.And(
z3.Implies(
(z3.If((VL_CF == z3.BitVecVal(0, 8)), z3.BitVecVal(1, 8), z3.BitVecVal(0, 8)) == z3.BitVecVal(0, 8)),
V_F == z3.Extract(0, 0, z3.Extract(7, 0, VL_ZF))
),
z3.Implies(
((z3.If((VL_CF == z3.BitVecVal(0, 8)), z3.BitVecVal(1, 8), z3.BitVecVal(0, 8)) == z3.BitVecVal(0, 8)) == False),
V_F == z3.Extract(0, 0, z3.Extract(7, 0, VL_ZF))
),
)
xvar = (V_F == VX_ZF)
s.add(lvar != xvar)
solve("ZF", lvar, xvar, s)
s.pop()
if(status == True):
print('[6;30;42m' + 'Test-Pass: ' + '[0m' + test_name)
else:
if(status == False):
print('[0;30;41m' + 'Test-Fail: ' + '[0m' + test_name)
else:
print('[6;30;47m' + 'Test-Unk: ' + '[0m' + test_name)
| [
"[email protected]"
]
| |
81c1ef2bb1721cb5d7b56e1f3673cd180502ce97 | eb9c3dac0dca0ecd184df14b1fda62e61cc8c7d7 | /google/ads/googleads/v4/googleads-py/google/ads/googleads/v4/services/services/language_constant_service/transports/base.py | 3eb9eee19afd04d6ca83dd2da69278f139f23822 | [
"Apache-2.0"
]
| permissive | Tryweirder/googleapis-gen | 2e5daf46574c3af3d448f1177eaebe809100c346 | 45d8e9377379f9d1d4e166e80415a8c1737f284d | refs/heads/master | 2023-04-05T06:30:04.726589 | 2021-04-13T23:35:20 | 2021-04-13T23:35:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,721 | py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import abc
import typing
import pkg_resources
from google import auth
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
from google.auth import credentials # type: ignore
from google.ads.googleads.v4.resources.types import language_constant
from google.ads.googleads.v4.services.types import language_constant_service
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution(
'google-ads-googleads',
).version,
)
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
class LanguageConstantServiceTransport(metaclass=abc.ABCMeta):
"""Abstract transport class for LanguageConstantService."""
AUTH_SCOPES = (
'https://www.googleapis.com/auth/adwords',
)
def __init__(
self, *,
host: str = 'googleads.googleapis.com',
credentials: credentials.Credentials = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
"""Instantiate the transport.
Args:
host (Optional[str]): The hostname to connect to.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
"""
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ':' not in host:
host += ':443'
self._host = host
# If no credentials are provided, then determine the appropriate
# defaults.
if credentials is None:
credentials, _ = auth.default(scopes=self.AUTH_SCOPES)
# Save the credentials.
self._credentials = credentials
# Lifted into its own function so it can be stubbed out during tests.
self._prep_wrapped_messages(client_info)
def _prep_wrapped_messages(self, client_info):
# Precomputed wrapped methods
self._wrapped_methods = {
self.get_language_constant: gapic_v1.method.wrap_method(
self.get_language_constant,
default_timeout=None,
client_info=client_info,
),
}
@property
def get_language_constant(self) -> typing.Callable[
[language_constant_service.GetLanguageConstantRequest],
language_constant.LanguageConstant]:
raise NotImplementedError
__all__ = (
'LanguageConstantServiceTransport',
)
| [
"bazel-bot-development[bot]@users.noreply.github.com"
]
| bazel-bot-development[bot]@users.noreply.github.com |
7a202d230c87166a61c32289c482c0b4b5907e88 | d042b8895dc8347356fa4d5984d07bff41eecc73 | /tools/bt_store.py | 61a04f137230eb3634848d34dbc1a8d1e41c65c3 | [
"Apache-2.0"
]
| permissive | jzx1230/obtainfo | 257b075c32c3448096391f258f42dd7f0c081350 | 883c29ab0a462d11682b60b9b52b2fc93031b816 | refs/heads/master | 2021-05-08T04:19:33.810848 | 2015-10-13T10:10:10 | 2015-10-13T10:10:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,111 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import os
import json
import codecs
import random
import pymongo
import sqlite3
import libtorrent
import chardet
import datetime
from pony.orm import *
from django.utils.encoding import force_unicode, DjangoUnicodeDecodeError
re_urn = re.compile(ur'xt=urn:btih:(\w+)')
re_pass = re.compile(r'^_____padding_file')
re_file_name = re.compile(r"[\/\\\:\*\?\"\<\>\|]")
prefix = ["[www.obtainfo.com]", "www.obtainfo.com_"]
db = Database('sqlite', 'obtainfo.sqlite', create_db=True)
class Torrent(db.Entity):
id = PrimaryKey(str, 40)
upload = Required(bool, default=False, index=True)
netdisk = Required(bool, default=False, index=True)
torrent = Required(buffer, lazy=True)
db.generate_mapping(create_tables=True)
is_exist_urn = lambda urn : db.exists("* from Torrent where id = $urn")
def unicode_name(name):
for encoding in ['utf-8', 'gbk', 'gb2312', 'gb18030', 'latin1', 'big5']:
try:
return force_unicode(name, encoding)
except DjangoUnicodeDecodeError:
continue
else:
try:
return force_unicode(name, chardet.detect(name)['encoding'])
except DjangoUnicodeDecodeError:
raise
@db_session
def save_torrent_to_db(urn, blob):
torrent = Torrent(id=urn, torrent=blob)
commit()
# check torrent file for get urn
def check_torrent(content):
try:
metadata = libtorrent.bdecode(content)
info = libtorrent.torrent_info(metadata)
urn = str(info.info_hash()).lower()
return urn
except:
return None
# content is torrent raw bin data, 校验是否已经存在
@db_session
def save_torrent(content):
urn = check_torrent(content)
if urn:
if not is_exist_urn(urn):
save_torrent_to_db(urn, sqlite3.Binary(content))
else:
print 'dumplate urn %s' % urn
return True
else:
print 'check urn %s fail' % urn
return False
@db_session
def get_server_magnet(num=5000):
server = pymongo.Connection().server
count = 0
urns = list()
magnets = list()
max_urns = 0
df = set(db.select("id from Torrent"))
for d in server.server.find():
for m in d['resource']['download']:
try:
urn = re.findall(ur'xt=urn:btih:(\w+)', m['link'])[0].lower()
if len(urn) > max_urns:
max_urns = len(urn)
if urn not in df:
magnets.append(m['link'])
urns.append(urn)
count += 1
if count >= num:
print max_urns
return (magnets, urns)
except IndexError:
pass
print max_urns
return (magnets, urns)
# rules = ['full', 'upload', 'netdisk']
@db_session
def dump_urn(where, rule='upload', status=False, update=False, num=1000):
torrents = select(t.id for t in Torrent)
urn = [t.lower() for t in torrents]
with codecs.open(os.path.join(where, 'urn.json'), 'wb', 'utf-8') as f:
json.dump(urn, f)
@db_session
def dump_torrent(where, rule='upload', status=False, update=False, num=1000):
if rule == 'upload':
torrents = Torrent.select(lambda t: t.upload == status)
elif rule == 'netdisk':
torrents = Torrent.select(lambda t: t.netdisk == status)
else:
torrents = select(t for t in Torrent)
if num != -1:
torrents = torrents[ : num]
for t in torrents:
src = os.path.join(where, t.id[:2], "%s.torrent" % t.id)
if not os.path.exists(os.path.join(where, t.id[:2])):
os.mkdir(os.path.join(where, t.id[:2]))
with open(src, 'wb') as f:
bin_data = t.torrent
if bin_data:
f.write(bin_data)
else:
f.write(t.torrent)
if update == True:
if rule == 'upload':
t.set(upload = not status)
elif rule == 'netdisk':
t.set(netdisk = not status)
# 从外部文件夹加载种子文件到数据库中
def load_torrent(directory):
for name in os.listdir(directory):
src = os.path.join(directory, name)
if os.path.isdir(src):
load_torrent(src)
else:
with open(src, 'rb') as source:
content = source.read()
save_torrent(content)
def rename_torrent(directory, newfolder=None):
for name in os.listdir(directory):
src = os.path.join(directory, name)
with open(src, 'rb') as source:
meta = libtorrent.bdecode(source.read())
try:
torrent_name = unicode_name(meta['info']['name'])
except:
continue
if not newfolder:
new = os.path.join(directory, re_file_name.sub('', torrent_name) + '.torrent' )
else:
new = os.path.join(newfolder, re_file_name.sub('', torrent_name) + '.torrent' )
os.rename(src, new)
@db_session
def stats_torrent(rule='upload', status=False):
if rule == 'upload':
return select(t for t in Torrent if t.upload == status).count()
elif rule == 'netdisk':
return select(t for t in Torrent if t.netdisk == status).count()
else:
return select(t for t in Torrent).count() | [
"[email protected]"
]
| |
0aeef5b781b774b162ccd571d7f2cfa4c241ed0e | e75148cf551a6b88c1af821ec1f624dbd8678900 | /tests/test_models/test_user.py | a997a9efdbcc970a3b699cd68c2599245042198c | []
| no_license | pforciol/AirBnB_clone | 8f4e22e4370bb22bf6c5a33af0d33384615c1be6 | 996141f4dd58c3e228231edd48ef831a1a1547d6 | refs/heads/master | 2023-03-20T00:00:26.283048 | 2021-03-03T11:41:56 | 2021-03-03T11:41:56 | 337,645,428 | 1 | 5 | null | null | null | null | UTF-8 | Python | false | false | 4,482 | py | #!/usr/bin/python3
"""
Contains the TestUserDocs classes
"""
from datetime import datetime
import inspect
from models import user
from models.base_model import BaseModel
import pep8
import unittest
User = user.User
class TestUserDocs(unittest.TestCase):
"""Tests to check the documentation and style of User class"""
@classmethod
def setUpClass(cls):
"""Set up for the doc tests"""
cls.user_f = inspect.getmembers(User, inspect.isfunction)
def test_pep8_conformance_user(self):
"""Test that models/user.py conforms to PEP8."""
pep8s = pep8.StyleGuide(quiet=True)
result = pep8s.check_files(['models/user.py'])
self.assertEqual(result.total_errors, 0,
"Found code style errors (and warnings).")
def test_pep8_conformance_test_user(self):
"""Test that tests/test_models/test_user.py conforms to PEP8."""
pep8s = pep8.StyleGuide(quiet=True)
result = pep8s.check_files(['tests/test_models/test_user.py'])
self.assertEqual(result.total_errors, 0,
"Found code style errors (and warnings).")
def test_user_module_docstring(self):
"""Test for the user.py module docstring"""
self.assertIsNot(user.__doc__, None,
"user.py needs a docstring")
self.assertTrue(len(user.__doc__) >= 1,
"user.py needs a docstring")
def test_user_class_docstring(self):
"""Test for the City class docstring"""
self.assertIsNot(User.__doc__, None,
"User class needs a docstring")
self.assertTrue(len(User.__doc__) >= 1,
"User class needs a docstring")
def test_user_func_docstrings(self):
"""Test for the presence of docstrings in User methods"""
for func in self.user_f:
self.assertIsNot(func[1].__doc__, None,
"{:s} method needs a docstring".format(func[0]))
self.assertTrue(len(func[1].__doc__) >= 1,
"{:s} method needs a docstring".format(func[0]))
class TestUser(unittest.TestCase):
"""Test the User class"""
def test_is_subclass(self):
"""Test that User is a subclass of BaseModel"""
user = User()
self.assertIsInstance(user, BaseModel)
self.assertTrue(hasattr(user, "id"))
self.assertTrue(hasattr(user, "created_at"))
self.assertTrue(hasattr(user, "updated_at"))
def test_email_attr(self):
"""Test that User has attr email, and it's an empty string"""
user = User()
self.assertTrue(hasattr(user, "email"))
self.assertEqual(user.email, "")
def test_password_attr(self):
"""Test that User has attr password, and it's an empty string"""
user = User()
self.assertTrue(hasattr(user, "password"))
self.assertEqual(user.password, "")
def test_first_name_attr(self):
"""Test that User has attr first_name, and it's an empty string"""
user = User()
self.assertTrue(hasattr(user, "first_name"))
self.assertEqual(user.first_name, "")
def test_last_name_attr(self):
"""Test that User has attr last_name, and it's an empty string"""
user = User()
self.assertTrue(hasattr(user, "last_name"))
self.assertEqual(user.last_name, "")
def test_to_dict_creates_dict(self):
"""test to_dict method creates a dictionary with proper attrs"""
u = User()
new_d = u.to_dict()
self.assertEqual(type(new_d), dict)
for attr in u.__dict__:
self.assertTrue(attr in new_d)
self.assertTrue("__class__" in new_d)
def test_to_dict_values(self):
"""test that values in dict returned from to_dict are correct"""
t_format = "%Y-%m-%dT%H:%M:%S.%f"
u = User()
new_d = u.to_dict()
self.assertEqual(new_d["__class__"], "User")
self.assertEqual(type(new_d["created_at"]), str)
self.assertEqual(type(new_d["updated_at"]), str)
self.assertEqual(new_d["created_at"], u.created_at.strftime(t_format))
self.assertEqual(new_d["updated_at"], u.updated_at.strftime(t_format))
def test_str(self):
"""test that the str method has the correct output"""
user = User()
string = "[User] ({}) {}".format(user.id, user.__dict__)
self.assertEqual(string, str(user))
| [
"[email protected]"
]
| |
5c6f6a8921c5ac8bc3e36835c949fe3bf80386ba | 46d09a43bbb7ea25c7e949fc3d4910779378f9fc | /pipeline/jinja2/ext.py | 3505f15a806422d8877b7e72d0c6a4e96ffa8490 | [
"MIT"
]
| permissive | vstoykov/django-pipeline | 9af20061a7ee93c167c7a4900fe8fb37143511f8 | e33375455174adb37e568efa2eccb988a86e132b | refs/heads/master | 2021-01-16T20:52:33.504023 | 2013-02-25T08:12:10 | 2013-02-25T08:12:10 | 8,404,848 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,082 | py | from __future__ import unicode_literals
from jinja2 import nodes, TemplateSyntaxError
from jinja2.ext import Extension
from django.contrib.staticfiles.storage import staticfiles_storage
from pipeline.packager import PackageNotFound
from pipeline.utils import guess_type
from pipeline.templatetags.compressed import CompressedMixin
class PipelineExtension(CompressedMixin, Extension):
tags = set(['compressed_css', 'compressed_js'])
def parse(self, parser):
tag = next(parser.stream)
package_name = parser.parse_expression()
if not package_name:
raise TemplateSyntaxError("Bad package name", tag.lineno)
args = [package_name]
if tag.value == "compressed_css":
return nodes.CallBlock(self.call_method('package_css', args), [], [], []).set_lineno(tag.lineno)
if tag.value == "compressed_js":
return nodes.CallBlock(self.call_method('package_js', args), [], [], []).set_lineno(tag.lineno)
return []
def package_css(self, package_name, *args, **kwargs):
try:
package = self.package_for(package_name, 'css')
except PackageNotFound:
return '' # fail silently, do not return anything if an invalid group is specified
return self.render_compressed(package, 'css')
def render_css(self, package, path):
template_name = package.template_name or "pipeline/css.jinja"
context = package.extra_context
context.update({
'type': guess_type(path, 'text/css'),
'url': staticfiles_storage.url(path)
})
template = self.environment.get_template(template_name)
return template.render(**context)
def render_individual_css(self, package, paths):
tags = [self.render_css(package, path) for path in paths]
return '\n'.join(tags)
def package_js(self, package_name, *args, **kwargs):
try:
package = self.package_for(package_name, 'js')
except PackageNotFound:
return '' # fail silently, do not return anything if an invalid group is specified
return self.render_compressed(package, 'js')
def render_js(self, package, path):
template_name = package.template_name or "pipeline/js.jinja"
context = package.extra_context
context.update({
'type': guess_type(path, 'text/javascript'),
'url': staticfiles_storage.url(path)
})
template = self.environment.get_template(template_name)
return template.render(**context)
def render_inline(self, package, js):
context = package.extra_context
context.update({
'source': js
})
template = self.environment.get_template("pipeline/inline_js.jinja")
return template.render(**context)
def render_individual_js(self, package, paths, templates=None):
tags = [self.render_js(package, js) for js in paths]
if templates:
tags.append(self.render_inline(package, templates))
return '\n'.join(tags)
| [
"[email protected]"
]
| |
38d5285ea9c56fe8af3ac150ca8d0023b1b63f08 | c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c | /cases/synthetic/tree-big-1600.py | 98ea760c85a4dfcc68c58d2397d47f6d2eafcc4c | []
| no_license | Virtlink/ccbench-chocopy | c3f7f6af6349aff6503196f727ef89f210a1eac8 | c7efae43bf32696ee2b2ee781bdfe4f7730dec3f | refs/heads/main | 2023-04-07T15:07:12.464038 | 2022-02-03T15:42:39 | 2022-02-03T15:42:39 | 451,969,776 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 23,274 | py | # Binary-search trees
class TreeNode(object):
value:int = 0
left:"TreeNode" = None
right:"TreeNode" = None
def insert(self:"TreeNode", x:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode(x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode(x)
return True
else:
return self.right.insert(x)
return False
def contains(self:"TreeNode", x:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
class TreeNode2(object):
value:int = 0
value2:int = 0
left:"TreeNode2" = None
left2:"TreeNode2" = None
right:"TreeNode2" = None
right2:"TreeNode2" = None
def insert(self:"TreeNode2", x:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode2(x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode2(x, x)
return True
else:
return self.right.insert(x)
return False
def insert2(self:"TreeNode2", x:int, x2:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode2(x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode2(x, x)
return True
else:
return self.right.insert(x)
return False
def contains(self:"TreeNode2", x:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains2(self:"TreeNode2", x:int, x2:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
class TreeNode3(object):
value:int = 0
value2:int = 0
value3:int = 0
left:"TreeNode3" = None
left2:"TreeNode3" = None
left3:"TreeNode3" = None
right:"TreeNode3" = None
right2:"TreeNode3" = None
right3:"TreeNode3" = None
def insert(self:"TreeNode3", x:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode3(x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode3(x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert2(self:"TreeNode3", x:int, x2:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode3(x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode3(x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert3(self:"TreeNode3", x:int, x2:int, x3:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode3(x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode3(x, x, x)
return True
else:
return self.right.insert(x)
return False
def contains(self:"TreeNode3", x:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return $Exp(x)
else:
return True
def contains2(self:"TreeNode3", x:int, x2:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains3(self:"TreeNode3", x:int, x2:int, x3:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
class TreeNode4(object):
value:int = 0
value2:int = 0
value3:int = 0
value4:int = 0
left:"TreeNode4" = None
left2:"TreeNode4" = None
left3:"TreeNode4" = None
left4:"TreeNode4" = None
right:"TreeNode4" = None
right2:"TreeNode4" = None
right3:"TreeNode4" = None
right4:"TreeNode4" = None
def insert(self:"TreeNode4", x:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode4(x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode4(x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert2(self:"TreeNode4", x:int, x2:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode4(x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode4(x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert3(self:"TreeNode4", x:int, x2:int, x3:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode4(x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode4(x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert4(self:"TreeNode4", x:int, x2:int, x3:int, x4:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode4(x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode4(x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def contains(self:"TreeNode4", x:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains2(self:"TreeNode4", x:int, x2:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains3(self:"TreeNode4", x:int, x2:int, x3:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains4(self:"TreeNode4", x:int, x2:int, x3:int, x4:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
class TreeNode5(object):
value:int = 0
value2:int = 0
value3:int = 0
value4:int = 0
value5:int = 0
left:"TreeNode5" = None
left2:"TreeNode5" = None
left3:"TreeNode5" = None
left4:"TreeNode5" = None
left5:"TreeNode5" = None
right:"TreeNode5" = None
right2:"TreeNode5" = None
right3:"TreeNode5" = None
right4:"TreeNode5" = None
right5:"TreeNode5" = None
def insert(self:"TreeNode5", x:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode5(x, x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode5(x, x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert2(self:"TreeNode5", x:int, x2:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode5(x, x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode5(x, x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert3(self:"TreeNode5", x:int, x2:int, x3:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode5(x, x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode5(x, x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert4(self:"TreeNode5", x:int, x2:int, x3:int, x4:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode5(x, x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode5(x, x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert5(self:"TreeNode5", x:int, x2:int, x3:int, x4:int, x5:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode5(x, x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode5(x, x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def contains(self:"TreeNode5", x:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains2(self:"TreeNode5", x:int, x2:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains3(self:"TreeNode5", x:int, x2:int, x3:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains4(self:"TreeNode5", x:int, x2:int, x3:int, x4:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains5(self:"TreeNode5", x:int, x2:int, x3:int, x4:int, x5:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
class Tree(object):
root:TreeNode = None
size:int = 0
def insert(self:"Tree", x:int) -> object:
if self.root is None:
self.root = makeNode(x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def contains(self:"Tree", x:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
class Tree2(object):
root:TreeNode2 = None
root2:TreeNode2 = None
size:int = 0
size2:int = 0
def insert(self:"Tree2", x:int) -> object:
if self.root is None:
self.root = makeNode2(x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert2(self:"Tree2", x:int, x2:int) -> object:
if self.root is None:
self.root = makeNode2(x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def contains(self:"Tree2", x:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains2(self:"Tree2", x:int, x2:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
class Tree3(object):
root:TreeNode3 = None
root2:TreeNode3 = None
root3:TreeNode3 = None
size:int = 0
size2:int = 0
size3:int = 0
def insert(self:"Tree3", x:int) -> object:
if self.root is None:
self.root = makeNode3(x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert2(self:"Tree3", x:int, x2:int) -> object:
if self.root is None:
self.root = makeNode3(x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert3(self:"Tree3", x:int, x2:int, x3:int) -> object:
if self.root is None:
self.root = makeNode3(x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def contains(self:"Tree3", x:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains2(self:"Tree3", x:int, x2:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains3(self:"Tree3", x:int, x2:int, x3:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
class Tree4(object):
root:TreeNode4 = None
root2:TreeNode4 = None
root3:TreeNode4 = None
root4:TreeNode4 = None
size:int = 0
size2:int = 0
size3:int = 0
size4:int = 0
def insert(self:"Tree4", x:int) -> object:
if self.root is None:
self.root = makeNode4(x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert2(self:"Tree4", x:int, x2:int) -> object:
if self.root is None:
self.root = makeNode4(x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert3(self:"Tree4", x:int, x2:int, x3:int) -> object:
if self.root is None:
self.root = makeNode4(x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert4(self:"Tree4", x:int, x2:int, x3:int, x4:int) -> object:
if self.root is None:
self.root = makeNode4(x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def contains(self:"Tree4", x:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains2(self:"Tree4", x:int, x2:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains3(self:"Tree4", x:int, x2:int, x3:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains4(self:"Tree4", x:int, x2:int, x3:int, x4:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
class Tree5(object):
root:TreeNode5 = None
root2:TreeNode5 = None
root3:TreeNode5 = None
root4:TreeNode5 = None
root5:TreeNode5 = None
size:int = 0
size2:int = 0
size3:int = 0
size4:int = 0
size5:int = 0
def insert(self:"Tree5", x:int) -> object:
if self.root is None:
self.root = makeNode5(x, x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert2(self:"Tree5", x:int, x2:int) -> object:
if self.root is None:
self.root = makeNode5(x, x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert3(self:"Tree5", x:int, x2:int, x3:int) -> object:
if self.root is None:
self.root = makeNode5(x, x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert4(self:"Tree5", x:int, x2:int, x3:int, x4:int) -> object:
if self.root is None:
self.root = makeNode5(x, x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert5(self:"Tree5", x:int, x2:int, x3:int, x4:int, x5:int) -> object:
if self.root is None:
self.root = makeNode5(x, x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def contains(self:"Tree5", x:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains2(self:"Tree5", x:int, x2:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains3(self:"Tree5", x:int, x2:int, x3:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains4(self:"Tree5", x:int, x2:int, x3:int, x4:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains5(self:"Tree5", x:int, x2:int, x3:int, x4:int, x5:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def makeNode(x: int) -> TreeNode:
b:TreeNode = None
b = TreeNode()
b.value = x
return b
def makeNode2(x: int, x2: int) -> TreeNode2:
b:TreeNode2 = None
b2:TreeNode2 = None
b = TreeNode2()
b.value = x
return b
def makeNode3(x: int, x2: int, x3: int) -> TreeNode3:
b:TreeNode3 = None
b2:TreeNode3 = None
b3:TreeNode3 = None
b = TreeNode3()
b.value = x
return b
def makeNode4(x: int, x2: int, x3: int, x4: int) -> TreeNode4:
b:TreeNode4 = None
b2:TreeNode4 = None
b3:TreeNode4 = None
b4:TreeNode4 = None
b = TreeNode4()
b.value = x
return b
def makeNode5(x: int, x2: int, x3: int, x4: int, x5: int) -> TreeNode5:
b:TreeNode5 = None
b2:TreeNode5 = None
b3:TreeNode5 = None
b4:TreeNode5 = None
b5:TreeNode5 = None
b = TreeNode5()
b.value = x
return b
# Input parameters
n:int = 100
n2:int = 100
n3:int = 100
n4:int = 100
n5:int = 100
c:int = 4
c2:int = 4
c3:int = 4
c4:int = 4
c5:int = 4
# Data
t:Tree = None
t2:Tree = None
t3:Tree = None
t4:Tree = None
t5:Tree = None
i:int = 0
i2:int = 0
i3:int = 0
i4:int = 0
i5:int = 0
k:int = 37813
k2:int = 37813
k3:int = 37813
k4:int = 37813
k5:int = 37813
# Crunch
t = Tree()
while i < n:
t.insert(k)
k = (k * 37813) % 37831
if i % c != 0:
t.insert(i)
i = i + 1
print(t.size)
for i in [4, 8, 15, 16, 23, 42]:
if t.contains(i):
print(i)
| [
"[email protected]"
]
| |
51d3af2173d61c3bb263950d8b476c00b5b27f45 | 48832d27da16256ee62c364add45f21b968ee669 | /res/scripts/client/gui/scaleform/daapi/view/meta/miniclientcomponentmeta.py | 7baac3f39ceaefa51e89191231fb90b8907f9ebf | []
| no_license | webiumsk/WOT-0.9.15.1 | 0752d5bbd7c6fafdd7f714af939ae7bcf654faf7 | 17ca3550fef25e430534d079876a14fbbcccb9b4 | refs/heads/master | 2021-01-20T18:24:10.349144 | 2016-08-04T18:08:34 | 2016-08-04T18:08:34 | 64,955,694 | 0 | 0 | null | null | null | null | WINDOWS-1250 | Python | false | false | 790 | py | # 2016.08.04 19:51:42 Střední Evropa (letní čas)
# Embedded file name: scripts/client/gui/Scaleform/daapi/view/meta/MiniClientComponentMeta.py
from gui.Scaleform.framework.entities.BaseDAAPIComponent import BaseDAAPIComponent
class MiniClientComponentMeta(BaseDAAPIComponent):
"""
DO NOT MODIFY!
Generated with yaml.
__author__ = 'yaml_processor'
@extends BaseDAAPIComponent
null
"""
def onHyperlinkClick(self):
"""
:return :
"""
self._printOverrideError('onHyperlinkClick')
# okay decompyling c:\Users\PC\wotsources\files\originals\res\scripts\client\gui\scaleform\daapi\view\meta\miniclientcomponentmeta.pyc
# decompiled 1 files: 1 okay, 0 failed, 0 verify failed
# 2016.08.04 19:51:42 Střední Evropa (letní čas)
| [
"[email protected]"
]
| |
8f889de0036edda16cc3215daa0c446fe28675f8 | 747f759311d404af31c0f80029e88098193f6269 | /extra-addons/syst_hr_payroll_ma/hr.py | e4887dca32ebf3ab1fd708f0c1ed3fdeb57426be | []
| no_license | sgeerish/sirr_production | 9b0d0f7804a928c0c582ddb4ccb7fcc084469a18 | 1081f3a5ff8864a31b2dcd89406fac076a908e78 | refs/heads/master | 2020-05-19T07:21:37.047958 | 2013-09-15T13:03:36 | 2013-09-15T13:03:36 | 9,648,444 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 5,063 | py | import netsvc
from osv import fields, osv
import pooler
from tools.translate import _
import time
class hr_employee(osv.osv):
_inherit = 'hr.employee'
_columns = {
'matricule' : fields.char('Matricule', size=64),
'cin' : fields.char('CIN', size=64),
'date': fields.date('Date entree', help='Cette date est requipe pour le calcule de la prime d\'anciennete'),
'anciennete': fields.boolean('Prime anciennete', help='Est ce que cet employe benificie de la prime d\'anciennete'),
'mode_reglement' : fields.selection([('virement', 'Virement'), ('cheque', 'Cheque'), ('espece', 'Espece'), ], 'Mode De Reglement'),
'bank' : fields.char('Banque', size=128),
'compte' : fields.char('Compte bancaire', size=128),
'chargefam' : fields.integer('Nombre de personnes a charge'),
'logement': fields.float('Abattement Fr Logement'),
'affilie':fields.boolean('Affilie', help='Est ce qu on va calculer les cotisations pour cet employe'),
'address_home' : fields.char('Adresse Personnelle', size=128),
'address' : fields.char('Adresse Professionnelle', size=128),
'phone_home' : fields.char('Telephone Personnel', size=128),
'licexpiry' : fields.char('Lic Expiry', size=128),
'licenseno' : fields.char('Lic No', size=128),
'licensetyp' : fields.char('Lic Type', size=128),
}
_defaults = {
'chargefam' : lambda * a: 0,
'logement' : lambda * a: 0,
'anciennete' : lambda * a: 'True',
'affilie' : lambda * a: 'True',
'date' : lambda * a: time.strftime('%Y-%m-%d'),
'mode_reglement' : lambda * a: 'virement'
}
hr_employee()
class hr_contract(osv.osv) :
_inherit = 'hr.contract'
_description = 'Employee Contract'
_columns = {
'working_days_per_month' : fields.integer('jours travailles par mois'),
'hour_salary' : fields.float('salaire Heure'),
'monthly_hour_number' : fields.float('Nombre Heures par mois'),
'cotisation':fields.many2one('hr.payroll_ma.cotisation.type', 'Type cotisations', required=True),
'rubrique_ids': fields.one2many('hr.payroll_ma.ligne_rubrique', 'id_contract', 'Les rubriques'),
}
_defaults = {
'working_days_per_month' : lambda * a : 26,
}
def net_to_brute(self, cr, uid, ids, context={}):
pool = pooler.get_pool(cr.dbname)
id_contract = ids[0]
contract = pool.get('hr.contract').browse(cr, uid, id_contract)
salaire_base = contract.wage
cotisation = contract.cotisation
personnes = contract.employee_id.chargefam
params = self.pool.get('hr.payroll_ma.parametres')
objet_ir = self.pool.get('hr.payroll_ma.ir')
id_ir = objet_ir.search(cr, uid, [])
liste = objet_ir.read(cr, uid, id_ir, ['debuttranche', 'fintranche', 'taux', 'somme'])
ids_params = params.search(cr, uid, [])
dictionnaire = params.read(cr, uid, ids_params[0])
abattement = personnes * dictionnaire['charge']
base = 0
salaire_brute = salaire_base
trouve=False
trouve2=False
while(trouve == False):
salaire_net_imposable=0
cotisations_employee=0
for cot in cotisation.cotisation_ids :
if cot.plafonee and salaire_brute >= cot.plafond:
base = cot.plafond
else : base = salaire_brute
cotisations_employee += base * cot['tauxsalarial'] / 100
fraispro = salaire_brute * dictionnaire['fraispro'] / 100
if fraispro < dictionnaire['plafond']:
salaire_net_imposable = salaire_brute - fraispro - cotisations_employee
else :
salaire_net_imposable = salaire_brute - dictionnaire['plafond'] - cotisations_employee
for tranche in liste:
if(salaire_net_imposable >= tranche['debuttranche']/12) and (salaire_net_imposable < tranche['fintranche']/12):
taux = (tranche['taux'])
somme = (tranche['somme']/12)
ir = (salaire_net_imposable - (somme*12))*taux/100 - abattement
if(ir < 0):ir = 0
salaire_net=salaire_brute - cotisations_employee - ir
if(int(salaire_net)==int(salaire_base) and trouve2==False):
trouve2=True
salaire_brute-=1
if(round(salaire_net,2)==salaire_base):trouve=True
elif trouve2==False : salaire_brute+=0.5
elif trouve2==True : salaire_brute+=0.01
self.write(cr, uid, [contract.id], {'wage' : round(salaire_brute,2)})
return True
hr_contract()
class hr_holidays_status(osv.osv):
_inherit = "hr.holidays.status"
_description = 'Holidays'
_columns = {
'payed':fields.boolean('paye', required=False),
}
_defaults = {
'payed': lambda * args: True
}
hr_holidays_status()
| [
"[email protected]"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.