blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
288
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
112
| license_type
stringclasses 2
values | repo_name
stringlengths 5
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 684
values | visit_date
timestamp[us]date 2015-08-06 10:31:46
2023-09-06 10:44:38
| revision_date
timestamp[us]date 1970-01-01 02:38:32
2037-05-03 13:00:00
| committer_date
timestamp[us]date 1970-01-01 02:38:32
2023-09-06 01:08:06
| github_id
int64 4.92k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-04 01:52:49
2023-09-14 21:59:50
⌀ | gha_created_at
timestamp[us]date 2008-05-22 07:58:19
2023-08-21 12:35:19
⌀ | gha_language
stringclasses 147
values | src_encoding
stringclasses 25
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 128
12.7k
| extension
stringclasses 142
values | content
stringlengths 128
8.19k
| authors
listlengths 1
1
| author_id
stringlengths 1
132
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
267bb492f6f1d1c52316995189ee560e6d5fac8b
|
cbbd5ae034bfc4a81a49af0fb7712516136afa6a
|
/PycharmProjects/Sensel/MISC/plot_contact_point_dynamic.py
|
c9c6a4d57c05bf7f73c33ae49037fdcb550ba242
|
[] |
no_license
|
pratikaher88/SenselWork
|
fafe12037ae8349510f29b3dc60130d26992ea77
|
d6f17bca7d2ac6ec6621f9b1b1540ca9e80eb2f7
|
refs/heads/master
| 2020-03-22T09:12:19.559029 | 2019-09-08T19:25:15 | 2019-09-08T19:25:15 | 139,822,527 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 5,496 |
py
|
#!/usr/bin/env python
##########################################################################
# MIT License
#
# Copyright (c) 2013-2017 Sensel, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
# to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
# FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
##########################################################################
import sys
from SenselUse import sensel,sensel_register_map
import binascii
import threading
import matplotlib.pyplot as plt
from matplotlib import animation
from matplotlib import style
style.use('fivethirtyeight')
fig=plt.figure()
ax1=fig.add_subplot(1,1,1)
global enter_pressed
X=[]
Y=[]
def waitForEnter():
global enter_pressed
input("Press Enter to exit...")
enter_pressed = True
return
def openSensel():
handle = None
(error, device_list) = sensel.getDeviceList()
if device_list.num_devices != 0:
(error, handle) = sensel.openDeviceByID(device_list.devices[0].idx)
return handle
def initFrame():
error = sensel.setFrameContent(handle, sensel.FRAME_CONTENT_PRESSURE_MASK | sensel.FRAME_CONTENT_CONTACTS_MASK)
sensel.setContactsMask(handle, sensel.CONTACT_MASK_ELLIPSE | sensel.CONTACT_MASK_BOUNDING_BOX)
# sensel.writeReg(handle, sensel_register_map.SENSEL_REG_BASELINE_DYNAMIC_ENABLED, 1, [0])
(error, frame) = sensel.allocateFrameData(handle)
error = sensel.startScanning(handle)
return frame
# def initFrameForContacts():
# error = sensel.setFrameContent(handle, sensel.FRAME_CONTENT_CONTACTS_MASK)
# (error, frame) = sensel.allocateFrameData(handle)
# error = sensel.startScanning(handle)
# return frame
def scanFrames(frame, info):
error = sensel.readSensor(handle)
(error, num_frames) = sensel.getNumAvailableFrames(handle)
for i in range(num_frames):
error = sensel.getFrame(handle, frame)
printFrame(frame, info)
def printFrame(frame, info):
# total_force = 0.0
# for n in range(info.num_rows * info.num_cols):
# total_force += frame.force_array[n]
# print("Total Force: " + str(total_force))
if frame.n_contacts > 0:
print("\nNum Contacts: ", frame.n_contacts)
for n in range(frame.n_contacts):
c = frame.contacts[n]
print("Contact ID: ", c.id)
print("X_pos",c.x_pos)
print("Y_pos",c.y_pos)
X.append(c.x_pos)
Y.append(c.y_pos)
plt.ion()
animated_plot = plt.plot(X, Y, 'ro')[0]
for i in range(len(X)):
animated_plot.set_xdata(X[0:i])
animated_plot.set_ydata(Y[0:i])
plt.draw()
plt.pause(0.0001)
# f = open('sampleText', 'a')
# f.write(str(c.x_pos)+','+str(c.y_pos)+'\n')
# animate(c.x_pos,c.y_pos)
# plt.scatter(c.x_pos, c.y_pos)
# ani = animation.FuncAnimation(plt.figure(), plt.scatter(c.x_pos,c.y_pos), interval=1000)
# plt.show(block=False)
total_force = 0.0
for n in range(info.num_rows * info.num_cols):
total_force += frame.force_array[n]
print("Total Force", total_force)
if c.state == sensel.CONTACT_START:
sensel.setLEDBrightness(handle, c.id, 100)
# Gives force at contact begin
# for n in range(info.num_rows * info.num_cols):
# total_force += frame.force_array[n]
elif c.state == sensel.CONTACT_END:
sensel.setLEDBrightness(handle, c.id, 0)
def closeSensel(frame):
error = sensel.freeFrameData(handle, frame)
error = sensel.stopScanning(handle)
error = sensel.close(handle)
if __name__ == "__main__":
global enter_pressed
enter_pressed = False
plt.xlim(0, 230)
plt.ylim(0, 130)
# plt.scatter(X, Y)
plt.gca().invert_yaxis()
# plt.show(block=False)
handle = openSensel()
if handle != None:
(error, info) = sensel.getSensorInfo(handle)
frame = initFrame()
t = threading.Thread(target=waitForEnter)
t.start()
while (enter_pressed == False):
scanFrames(frame, info)
closeSensel(frame)
# plt.xlim(0, 230)
# plt.ylim(0, 130)
plt.scatter(X, Y)
# plt.gca().invert_yaxis()
# ani = animation.FuncAnimation(fig, animatethis, interval=1000)
# plt.show()
# with open('sampleText', "w"):
# pass
print(X)
print(Y)
|
[
"[email protected]"
] | |
4c533330fc30bad9170734f0a1c30bbcfc8d9a59
|
b521802cca8e4ee4ff5a5ffe59175a34f2f6d763
|
/maya/maya-utils/Scripts/Animation/2019-2-15 Tim Cam_Route_Manager/.history/Cam_Main/Cam_Main/Cam_Item_Layout_20190117213541.py
|
1cc9c0f906fa3ff3efcc249cec01387c59eb07fa
|
[] |
no_license
|
all-in-one-of/I-Do-library
|
2edf68b29558728ce53fe17168694ad0353a076e
|
8972ebdcf1430ccc207028d8482210092acf02ce
|
refs/heads/master
| 2021-01-04T06:58:57.871216 | 2019-12-16T04:52:20 | 2019-12-16T04:52:20 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,830 |
py
|
# -*- coding:utf-8 -*-
# Require Header
import os
import json
from functools import partial
# Sys Header
import sys
import traceback
import subprocess
import plugin.Qt as Qt
from Qt.QtCore import *
from Qt.QtGui import *
from Qt.QtWidgets import *
def loadUiType(uiFile):
import plugin.Qt as Qt
if Qt.__binding__.startswith('PyQt'):
from Qt import _uic as uic
return uic.loadUiType(uiFile)
elif Qt.__binding__ == 'PySide':
import pysideuic as uic
else:
import pyside2uic as uic
import xml.etree.ElementTree as xml
from cStringIO import StringIO
parsed = xml.parse(uiFile)
widget_class = parsed.find('widget').get('class')
form_class = parsed.find('class').text
with open(uiFile, 'r') as f:
o = StringIO()
frame = {}
uic.compileUi(f, o, indent=0)
pyc = compile(o.getvalue(), '<string>', 'exec')
exec pyc in frame
# Fetch the base_class and form class based on their type
# in the xml from designer
form_class = frame['Ui_%s'%form_class]
base_class = eval('%s'%widget_class)
return form_class, base_class
from Qt.QtCompat import wrapInstance
DIR = os.path.dirname(__file__)
UI_PATH = os.path.join(DIR,"ui","Cam_Item_Layout.ui")
GUI_STATE_PATH = os.path.join(DIR, "json" ,'GUI_STATE.json')
form_class , base_class = loadUiType(UI_PATH)
class Cam_Item_Layout(form_class,base_class):
def __init__(self):
super(Cam_Item_Layout,self).__init__()
self.setupUi(self)
self.Item_Add_BTN.clicked.connect(self.Item_Add_Fn)
self.Item_Clear_BTN.clicked.connect(self.Item_Clear_Fn)
def Item_Add_Fn(self):
Cam_Item(self)
def Item_Clear_Fn(self):
for i,child in enumerate(self.Item_Layout.children()):
if i != 0:
child.deleteLater()
UI_PATH = os.path.join(DIR,"ui","Cam_Item.ui")
form_class , base_class = loadUiType(UI_PATH)
class Cam_Item(form_class,base_class):
def __init__(self,parent):
super(Cam_Item,self).__init__()
self.setupUi(self)
self.Cam_Del_BTN.clicked.connect(self.Cam_Del_BTN_Fn)
TotalCount = len(parent.Item_Layout.children())
parent.Item_Layout.layout().insertWidget(TotalCount-1,self)
self.Cam_LE.setText("Cam_Item_%s" % TotalCount)
self.Cam_Num_Label.setText(u"镜头%s" % TotalCount)
self.setObjectName("Cam_Item_%s" % TotalCount)
self.num = TotalCount
def Cam_Del_BTN_Fn(self):
self.deleteLater()
# # TotalCount = len(self.parent().children())
ChildrenList = self.parent().children()
# print ChildrenList
# for i in range(self.num,len(ChildrenList)):
# if i+1 == len(ChildrenList):
# del(ChildrenList[i])
# break
# ChildrenList[i] = ChildrenList[i+1]
# print ChildrenList
# count = 0
# for child in ChildrenList:
# if count != 0:
# child.Cam_Num_Label.setText(u"%s" % count)
# child.setObjectName("Cam_Item_%s" % count)
# print count
# count += 1
# for i,child in enumerate(ChildrenList):
# if i != 0:
# print u"%s" % i
# child.Cam_Num_Label.setText(u"%s" % i)
# child.setObjectName("Cam_Item_%s" % i)
index = 999999
for i,child in enumerate(ChildrenList):
if i != 0:
child.Cam_Num_Label.setText(u"镜头%s" % i)
child.setObjectName("Cam_Item_%s" % i)
if i < self.num:
child.Cam_Num_Label.setText(u"镜头%s" % (i-1))
child.setObjectName("Cam_Item_%s" % i-1)
|
[
"[email protected]"
] | |
cf24680305aff81ff86ab5ebb28a06a585343af1
|
cbfddfdf5c7fa8354162efe50b41f84e55aff118
|
/venv/lib/python3.7/site-packages/apscheduler/executors/debug.py
|
ac739aebcef52bb0b824e66c1fcfc7693b4fab6a
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
tclerico/SAAC
|
8d2245221dd135aea67c5e079ac7eaf542b25e2f
|
2f52007ae8043096662e76da828a84e87f71091e
|
refs/heads/master
| 2022-12-09T21:56:33.430404 | 2019-02-20T14:23:51 | 2019-02-20T14:23:51 | 153,152,229 | 3 | 0 |
MIT
| 2022-09-16T17:52:47 | 2018-10-15T17:13:29 |
Python
|
UTF-8
|
Python
| false | false | 573 |
py
|
import sys
from apscheduler.executors.base import BaseExecutor, run_job
class DebugExecutor(BaseExecutor):
"""
A special executor that executes the target callable directly instead of deferring it to a
thread or process.
Plugin alias: ``debug``
"""
def _do_submit_job(self, job, run_times):
try:
events = run_job(job, job._jobstore_alias, run_times, self._logger.name)
except BaseException:
self._run_job_error(job.id, *sys.exc_info()[1:])
else:
self._run_job_success(job.id, events)
|
[
"[email protected]"
] | |
fda997527f91121c4f1bffd1b3f2b0ddcc3dc4fa
|
1d7eec692553afc411ec1e7325634f71a2aed291
|
/backend/curriculum_tracking/migrations/0007_auto_20200710_1319.py
|
9c49a0b43cc247004d1e90d0e0992ef9482c6d27
|
[] |
no_license
|
Andy-Nkumane/Tilde
|
a41a2a65b3901b92263ae94d527de403f59a5caf
|
80de97edaf99f4831ca8cb989b93e3be5e09fdd6
|
refs/heads/develop
| 2023-05-09T10:02:41.240517 | 2021-05-28T09:20:51 | 2021-05-28T09:20:51 | 299,501,586 | 0 | 0 | null | 2020-10-25T22:37:30 | 2020-09-29T04:10:48 |
Python
|
UTF-8
|
Python
| false | false | 1,043 |
py
|
# Generated by Django 2.1.5 on 2020-07-10 13:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('curriculum_tracking', '0006_auto_20200701_0539'),
]
operations = [
migrations.AddField(
model_name='recruitproject',
name='code_review_competent_since_last_review_request',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='recruitproject',
name='code_review_excellent_since_last_review_request',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='recruitproject',
name='code_review_ny_competent_since_last_review_request',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='recruitproject',
name='code_review_red_flag_since_last_review_request',
field=models.IntegerField(default=0),
),
]
|
[
"[email protected]"
] | |
966665af55225f40fdd4da19c28dd883a43f62ff
|
3c8bc614c9f09db5efce54af3cbcaf78e0f48b54
|
/0x0B-python-input_output/4-append_write.py
|
e5256329fd3346953966d0bb9bdd0fec8b45629c
|
[] |
no_license
|
davidknoppers/holbertonschool-higher_level_programming
|
7848d301c4bf5c1fa285314392adfb577d6d082f
|
beaf6e5ece426c2086f34763e50c3ce0f56923ac
|
refs/heads/master
| 2021-04-29T10:10:27.071278 | 2017-05-03T02:46:44 | 2017-05-03T02:46:44 | 77,847,936 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 367 |
py
|
#!/usr/bin/python3
"""
One function in this module
append_write opens a file and appends some text to it
"""
def append_write(filename="", text=""):
"""
open file
put some text at the end of it
close that file
"""
with open(filename, mode='a', encoding="utf-8") as myFile:
chars_written = myFile.write(text)
return chars_written
|
[
"[email protected]"
] | |
e1164b25df69866a6cb1d50cfb9672d8d6217e7a
|
a9e81c87022fdde86d47a4ec1e74791da8aa0e30
|
/python-learning/libraries/pyqt5/base/layouts/complex-layout.py
|
b774d4700b1104671fb8542f99d2d70b4238e84f
|
[
"Apache-2.0"
] |
permissive
|
ymli1997/deeplearning-notes
|
c5c6926431b7efc1c6823d85e3eb470f3c986494
|
f2317d80cd998305814f988e5000241797205b63
|
refs/heads/master
| 2020-07-29T11:15:43.689307 | 2018-05-05T10:58:18 | 2018-05-05T10:58:18 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,356 |
py
|
# -*- coding: utf-8 -*-
'''
复杂布局
'''
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class Form(QMainWindow):
def __init__(self,parent=None):
super().__init__(parent)
centerWidget = QWidget()
defalutLayout = QVBoxLayout()
vboxlayout = QVBoxLayout()
hboxlayout = QHBoxLayout()
gridlayout = QGridLayout()
# 添加控件代码
buttons = []
for i in range(5):
buttons.append(QPushButton("Grid Button %d" %(i)))
vboxlayout.addWidget(QPushButton("VBox Button %d" %(i)))
hboxlayout.addWidget(QPushButton("HBox Button %d" %(i)))
gridlayout.addWidget(buttons[0],0,0)
gridlayout.addWidget(buttons[1],0,1)
gridlayout.addWidget(buttons[2],1,0,1,2) #跨1行2列
gridlayout.addWidget(buttons[3],2,0)
gridlayout.addWidget(buttons[4],2,1)
defalutLayout.addLayout(vboxlayout)
defalutLayout.addLayout(gridlayout)
defalutLayout.addLayout(hboxlayout)
centerWidget.setLayout(defalutLayout)
self.setCentralWidget(centerWidget)
self.resize(640,480)
self.setWindowTitle("PyQt5-")
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Form()
ex.show()
sys.exit(app.exec_())
|
[
"[email protected]"
] | |
1b9da0c86e0e095737f906fdf95ded574b5a0f3c
|
7ba5ec9aa9ddca3f9b3384fc4457b0a865c2a0a1
|
/src/301.py
|
55d8e16e1a35748acecac34a5c82e9d8d714e5c4
|
[] |
no_license
|
ecurtin2/Project-Euler
|
71f79ee90a9abd0943421677d78a6c087419e500
|
79479da7a45b3ae67c0c7ea24da5f7d43c6f25d3
|
refs/heads/master
| 2021-03-19T14:52:57.045443 | 2018-04-12T22:05:37 | 2018-04-12T22:05:37 | 100,059,180 | 0 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,760 |
py
|
"""
Nim is a game played with heaps of stones, where two players take it in turn to remove any number of stones from any heap until no stones remain.
We'll consider the three-heap normal-play version of Nim, which works as follows:
- At the start of the game there are three heaps of stones.
- On his turn the player removes any positive number of stones from any single heap.
- The first player unable to move (because no stones remain) loses.
If (n1,n2,n3) indicates a Nim position consisting of heaps of size n1, n2 and n3 then there is a simple function X(n1,n2,n3) — that you may look up or attempt to deduce for yourself — that returns:
zero if, with perfect strategy, the player about to move will eventually lose; or
non-zero if, with perfect strategy, the player about to move will eventually win.For example X(1,2,3) = 0 because, no matter what the current player does, his opponent can respond with a move that leaves two heaps of equal size, at which point every move by the current player can be mirrored by his opponent until no stones remain; so the current player loses. To illustrate:
- current player moves to (1,2,1)
- opponent moves to (1,0,1)
- current player moves to (0,0,1)
- opponent moves to (0,0,0), and so wins.
For how many positive integers n ≤ 230 does X(n,2n,3n) = 0 ?
"""
import numpy as np
import time
def X(n):
n = int(n)
return bool(n ^ (2 * n) ^ (3 * n))
N = 2**28
t = time.time()
n = np.arange(1, N)
x = np.bitwise_xor(n, np.bitwise_xor(2*n, 3*n)).astype(bool)
total = np.sum(x)
print("Numpy done in {:10.8f} seconds.".format(time.time() - t))
print(total)
#t = time.time()
#total = sum(X(i) for i in range(1, N))
#print("Python done in {:10.8f} seconds.".format(time.time() - t))
#print(total)
|
[
"[email protected]"
] | |
a24baa4d6bc822d4b1281390833220aec3d84176
|
2aa47f47fb81798afdf41437844cbbea8e9de66c
|
/02pythonBase/day10/res/exercise/mysum.py
|
f01610139cf297dab58d87dd27cd73d8d71c2bb2
|
[] |
no_license
|
nykh2010/python_note
|
83f2eb8979f2fb25b4845faa313dbd6b90b36f40
|
5e7877c9f7bf29969072f05b98277ef3ba090969
|
refs/heads/master
| 2020-04-27T23:10:16.578094 | 2019-03-23T02:43:14 | 2019-03-23T02:43:14 | 174,765,151 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 541 |
py
|
# 练习:
# 写一个函数 mysum, 可以传入任意个实参的数字,
# 此函数返回所有实参的和:
# def mysum(*args):
# ... # <<<--- 此处需要自己实现
# print(mysum(1, 2, 3, 4)) # 10
# print(mysum(1, 2, 3, 4, 5)) # 15
def mysum(*args):
print("第11行的mysum被调用!")
s = 0 # 用于累加和
for x in args:
s += x
return s
def mysum(*args):
print("第17行的mysum被调用!")
return sum(args)
print(mysum(1, 2, 3, 4)) # 10
print(mysum(1, 2, 3, 4, 5)) # 15
|
[
"[email protected]"
] | |
40dfe239746f14da2cd97adf27df4e81ed29da65
|
4f7140c62cc649373379941224072c9e6b707ef7
|
/examples/prompts/clock-input.py
|
fd1f8760ed2e77af6f65fbae97fa63ce949125fe
|
[
"BSD-3-Clause"
] |
permissive
|
qianhaohu/python-prompt-toolkit
|
03d282a0a6a258a08ef822bc342a6b7fb65667f7
|
237cf46ff50c8a689a72e3dfe664dfe69bffd245
|
refs/heads/master
| 2020-05-16T05:19:38.934218 | 2019-04-16T19:10:07 | 2019-04-16T19:40:47 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 607 |
py
|
#!/usr/bin/env python
"""
Example of a 'dynamic' prompt. On that shows the current time in the prompt.
"""
from __future__ import unicode_literals
import datetime
from prompt_toolkit.shortcuts import prompt
def get_prompt():
" Tokens to be shown before the prompt. "
now = datetime.datetime.now()
return [
('bg:#008800 #ffffff', '%s:%s:%s' % (now.hour, now.minute, now.second)),
('bg:cornsilk fg:maroon', ' Enter something: ')
]
def main():
result = prompt(get_prompt, refresh_interval=.5)
print('You said: %s' % result)
if __name__ == '__main__':
main()
|
[
"[email protected]"
] | |
5d9c0e1d64a54205baad6cd4387d049d7075add4
|
96622790b66e45926b79bc524ec75a0f4d53a7eb
|
/src/misc-preprocessing-scripts/maeToPdb.py
|
607322e4c183184fce0eb9365a2c80401d9cb81f
|
[] |
no_license
|
akma327/GPCR-WaterDynamics
|
a8c2e13e18f953b6af66a3e669052cb3eacd346b
|
685f4dea0605d65c003bf952afd964df6e605b06
|
refs/heads/master
| 2021-01-22T07:42:42.539496 | 2017-05-27T07:23:44 | 2017-05-27T07:23:44 | 92,574,339 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 2,514 |
py
|
# Author: Anthony Kai Kwang Ma
# Email: [email protected]
# maeToPdb.py
# MAE To PDB File Converter
# Usage:
# python maeToPdb.py <input path to mae> <output path for pdb> <optional pdb file name>
# <input path to mae> Provide the absolute path to the mae file name
# <output path for pdb> Provide the directory path to store the pdb
# <optional pdb file name> Default is to rename the pdb to the same prefix as mae, but user can specify new name
# Example:
#
import vmd, molecule
import sys
PROPER_USAGE_STR = """
# Usage:
# python maeToPdb.py <input path to mae> <output path for pdb> <optional pdb file name>
# <input path to mae> Provide the absolute path to the mae file name
# <output path for pdb> Provide the directory path to store the pdb
# <optional pdb file name> Default is to rename the pdb to the same prefix as mae, but user can specify new name
# Example:
# INPUT_MAE_PATH="/scratch/PI/rondror/DesRes-Simulations/ordered-from-DesRes/nature2013/DESRES-Trajectory_nature2013-AA-all/DESRES-Trajectory_nature2013-AA-58-all/nature2013-AA-58-all/nature2013-AA-58-all.mae"
# OUTPUT_PDB_PATH="/scratch/PI/rondror/akma327/noncovalent_Interaction_Scripts/DynamicInteractions/tools"
# PDB_FILE_NAME="nature2013-AA-58-new.pdb"
# python maeToPdb.py $INPUT_MAE_PATH $OINPUT_MAE_PATH="/scratch/PI/rondror/DesRes-Simulations/ordered-from-DesRes/nature2013/DESRES-Trajectory_nature2013-AA-all/DESRES-Trajectory_nature2013-AA-58-all/nature2013-AA-58-all/nature2013-AA-58-all.mae"
# OUTPUT_PDB_PATH="/scratch/PI/rondror/akma327/noncovalent_Interaction_Scripts/DynamicInteractions/tools"
# PDB_FILE_NAME="nature2013-AA-58-new.pdb"
# python maeToPdb.py $INPUT_MAE_PATH $OUTPUT_PDB_PATH $PDB_FILE_NAME UTPUT_PDB_PATH $PDB_FILE_NAME """
MIN_NUM_ARGS = 3
# import vmd, molecule
# input_mae_path= "nature2011-B-all.mae"
# output_pdb_file_path = "step5_assembly.pdb"
# molid = molecule.load('mae', input_mae_path)
# molecule.write(molid, 'pdb', output_pdb_file_path)
# import mdtraj as md
# t = md.load('step5_assembly.pdb')
def maeToPdb(input_mae_path, output_pdb_file_path):
molid = molecule.load('mae', input_mae_path)
molecule.write(molid, 'pdb', output_pdb_file_path)
print("Finished Conversion for: " + str(input_mae_path))
if __name__ == "__main__":
if(len(sys.argv) < MIN_NUM_ARGS):
print("Invalid Arguments")
print(PROPER_USAGE_STR)
exit(0)
input_mae_path = sys.argv[1]
output_pdb_path = sys.argv[2]
print(input_mae_path, output_pdb_path)
maeToPdb(input_mae_path, output_pdb_path)
|
[
"[email protected]"
] | |
d6d93cb282a9b64ae57a7522d83152c22b1aae24
|
6814b9b28204fa58f77598d01c760ddeb4b66353
|
/baselines/jft/experiments/jft300m_vit_base16_heteroscedastic_finetune_cifar.py
|
8384bfa093ad4ce0435cbcdfa7302096e6fa5720
|
[
"Apache-2.0"
] |
permissive
|
qiao-maoying/uncertainty-baselines
|
a499951ea1450323e00fe03891ba8f781fe1cdc7
|
54dce3711b559ae3955a8a7d05c88eb982dea470
|
refs/heads/main
| 2023-07-17T23:17:10.867509 | 2021-08-18T20:32:11 | 2021-08-18T20:32:44 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,620 |
py
|
# coding=utf-8
# Copyright 2021 The Uncertainty Baselines Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# pylint: disable=line-too-long
r"""Finetune a ViT-B/16 heteroscedastic model on CIFAR-10.
"""
# pylint: enable=line-too-long
import ml_collections
# TODO(dusenberrymw): Open-source remaining imports.
def get_sweep(hyper):
return hyper.product([])
def get_config():
"""Config for training a patch-transformer on JFT."""
config = ml_collections.ConfigDict()
# Fine-tuning dataset
config.dataset = 'cifar10'
config.val_split = 'train[98%:]'
config.train_split = 'train[:98%]'
config.num_classes = 10
BATCH_SIZE = 512 # pylint: disable=invalid-name
config.batch_size = BATCH_SIZE
config.total_steps = 10_000
INPUT_RES = 384 # pylint: disable=invalid-name
pp_common = '|value_range(-1, 1)'
# pp_common += f'|onehot({config.num_classes})'
# To use ancestor 'smearing', use this line instead:
pp_common += f'|onehot({config.num_classes}, key="label", key_result="labels")' # pylint: disable=line-too-long
pp_common += '|keep("image", "labels")'
config.pp_train = f'decode|inception_crop({INPUT_RES})|flip_lr' + pp_common
config.pp_eval = f'decode|resize({INPUT_RES})' + pp_common
config.shuffle_buffer_size = 50_000 # Per host, so small-ish is ok.
config.log_training_steps = 10
config.log_eval_steps = 100
# NOTE: eval is very fast O(seconds) so it's fine to run it often.
config.checkpoint_steps = 1000
config.checkpoint_timeout = 1
config.prefetch_to_device = 2
config.trial = 0
# Model section
# pre-trained model ckpt file
# !!! The below section should be modified per experiment
config.model_init = '/path/to/pretrained_model_ckpt.npz'
# Model definition to be copied from the pre-training config
config.model = ml_collections.ConfigDict()
config.model.patches = ml_collections.ConfigDict()
config.model.patches.size = [16, 16]
config.model.hidden_size = 768
config.model.transformer = ml_collections.ConfigDict()
config.model.transformer.attention_dropout_rate = 0.
config.model.transformer.dropout_rate = 0.
config.model.transformer.mlp_dim = 3072
config.model.transformer.num_heads = 12
config.model.transformer.num_layers = 12
config.model.classifier = 'token' # Or 'gap'
# This is "no head" fine-tuning, which we use by default
config.model.representation_size = None
# # Heteroscedastic
config.model.multiclass = True
config.model.temperature = 3.0
config.model.mc_samples = 1000
config.model.num_factors = 3
config.model.param_efficient = True
config.model.return_locs = True # set True to fine-tune a homoscedastic model
# Optimizer section
config.optim_name = 'Momentum'
config.optim = ml_collections.ConfigDict()
config.grad_clip_norm = 1.0
config.weight_decay = None # No explicit weight decay
config.loss = 'softmax_xent' # or 'sigmoid_xent'
config.lr = ml_collections.ConfigDict()
config.lr.base = 0.001
config.lr.warmup_steps = 500
config.lr.decay_type = 'cosine'
config.lr.scale_with_batchsize = False
config.args = {}
return config
|
[
"[email protected]"
] | |
5cffb5a2fb9d408a8f4fe88b0e46d790428e9c92
|
1bde114a847c629701e3acd004be5788594e0ef1
|
/Examples/Decorator/alldecorators/CoffeeShop.py
|
9e4861b473c3803d1d2a0b2ad0b382e4cce35f7a
|
[] |
no_license
|
BruceEckel/ThinkingInPython
|
0b234cad088ee144bb8511e1e7db9fd5bba78877
|
76a1310deaa51e02e9f83ab74520b8269aac6fff
|
refs/heads/master
| 2022-02-21T23:01:40.544505 | 2022-02-08T22:26:52 | 2022-02-08T22:26:52 | 97,673,620 | 106 | 33 | null | 2022-02-08T22:26:53 | 2017-07-19T04:43:50 |
Python
|
UTF-8
|
Python
| false | false | 1,722 |
py
|
# Decorator/alldecorators/CoffeeShop.py
# Coffee example using decorators
class DrinkComponent:
def getDescription(self):
return self.__class__.__name__
def getTotalCost(self):
return self.__class__.cost
class Mug(DrinkComponent):
cost = 0.0
class Decorator(DrinkComponent):
def __init__(self, drinkComponent):
self.component = drinkComponent
def getTotalCost(self):
return self.component.getTotalCost() + \
DrinkComponent.getTotalCost(self)
def getDescription(self):
return self.component.getDescription() + \
' ' + DrinkComponent.getDescription(self)
class Espresso(Decorator):
cost = 0.75
def __init__(self, drinkComponent):
Decorator.__init__(self, drinkComponent)
class Decaf(Decorator):
cost = 0.0
def __init__(self, drinkComponent):
Decorator.__init__(self, drinkComponent)
class FoamedMilk(Decorator):
cost = 0.25
def __init__(self, drinkComponent):
Decorator.__init__(self, drinkComponent)
class SteamedMilk(Decorator):
cost = 0.25
def __init__(self, drinkComponent):
Decorator.__init__(self, drinkComponent)
class Whipped(Decorator):
cost = 0.25
def __init__(self, drinkComponent):
Decorator.__init__(self, drinkComponent)
class Chocolate(Decorator):
cost = 0.25
def __init__(self, drinkComponent):
Decorator.__init__(self, drinkComponent)
cappuccino = Espresso(FoamedMilk(Mug()))
print(cappuccino.getDescription().strip() + \)
": $" + `cappuccino.getTotalCost()`
cafeMocha = Espresso(SteamedMilk(Chocolate(
Whipped(Decaf(Mug())))))
print(cafeMocha.getDescription().strip() + \)
": $" + `cafeMocha.getTotalCost()`
|
[
"[email protected]"
] | |
a7c8fa0bda79edadd701b585eff8e09a773467c6
|
e7c3d2b1fd7702b950e31beed752dd5db2d127bd
|
/code/super_pandigital_numbers/sol_571.py
|
50c76cee64069e830d981145a37c35c2cc3edff5
|
[
"Apache-2.0"
] |
permissive
|
Ved005/project-euler-solutions
|
bbadfc681f5ba4b5de7809c60eb313897d27acfd
|
56bf6a282730ed4b9b875fa081cf4509d9939d98
|
refs/heads/master
| 2021-09-25T08:58:32.797677 | 2018-10-20T05:40:58 | 2018-10-20T05:40:58 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 931 |
py
|
# -*- coding: utf-8 -*-
'''
File name: code\super_pandigital_numbers\sol_571.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #571 :: Super Pandigital Numbers
#
# For more information see:
# https://projecteuler.net/problem=571
# Problem Statement
'''
A positive number is pandigital in base b if it contains all digits from 0 to b - 1 at least once when written in base b.
A n-super-pandigital number is a number that is simultaneously pandigital in all bases from 2 to n inclusively.
For example 978 = 11110100102 = 11000203 = 331024 = 124035 is the smallest 5-super-pandigital number.
Similarly, 1093265784 is the smallest 10-super-pandigital number.
The sum of the 10 smallest 10-super-pandigital numbers is 20319792309.
What is the sum of the 10 smallest 12-super-pandigital numbers?
'''
# Solution
# Solution Approach
'''
'''
|
[
"[email protected]"
] | |
086f15693af91521b68d827e7613c2ac26e02baf
|
7f57c12349eb4046c40c48acb35b0f0a51a344f6
|
/2015/PopulatingNextRightPointersInEachNode_v1.py
|
3577626399488b0ca50d165ddf85bbb001892a21
|
[] |
no_license
|
everbird/leetcode-py
|
0a1135952a93b93c02dcb9766a45e481337f1131
|
b093920748012cddb77258b1900c6c177579bff8
|
refs/heads/master
| 2022-12-13T07:53:31.895212 | 2022-12-10T00:48:39 | 2022-12-10T00:48:39 | 11,116,752 | 2 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,362 |
py
|
#!/usr/bin/env python
# encoding: utf-8
# Definition for binary tree with next pointer.
class TreeLinkNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None
def __repr__(self):
return '<{}>'.format(self.val)
class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
self.dfs(root)
def dfs(self, root):
if not root:
return
if root.left:
root.left.next = root.right
if root.next and root.right:
root.right.next = root.next.left
self.dfs(root.left)
self.dfs(root.right)
def levelorder(self, root):
queue = [root]
while queue:
n = queue.pop()
print n, n.val, n.next, '<<<'
if n.left:
queue = [n.left] + queue
if n.right:
queue = [n.right] + queue
if __name__ == '__main__':
s = Solution()
n1 = TreeLinkNode(1)
n2 = TreeLinkNode(2)
n3 = TreeLinkNode(3)
n4 = TreeLinkNode(4)
n5 = TreeLinkNode(5)
n6 = TreeLinkNode(6)
n7 = TreeLinkNode(7)
root = n1
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
n3.left = n6
n3.right = n7
s.connect(root)
s.levelorder(root)
|
[
"[email protected]"
] | |
37a55e826ebb167071a7c6afe9b42c8b3264506b
|
b24e45267a8d01b7d3584d062ac9441b01fd7b35
|
/Usuario/.history/views_20191023114840.py
|
870eeb90df98b7537147ae14418728dfb2b3fb07
|
[] |
no_license
|
slalbertojesus/merixo-rest
|
1707b198f31293ced38930a31ab524c0f9a6696c
|
5c12790fd5bc7ec457baad07260ca26a8641785d
|
refs/heads/master
| 2022-12-10T18:56:36.346159 | 2020-05-02T00:42:39 | 2020-05-02T00:42:39 | 212,175,889 | 0 | 0 | null | 2022-12-08T07:00:07 | 2019-10-01T18:56:45 |
Python
|
UTF-8
|
Python
| false | false | 2,211 |
py
|
from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework.permissions import AllowAny
from .models import Usuario
from .serializers import UsuarioSerializer
SUCCESS = 'exito'
ERROR = 'error'
DELETE_SUCCESS = 'eliminado'
UPDATE_SUCCESS = 'actualizado'
CREATE_SUCCESS = 'creado'
@api_view(['GET', ])
def api_detail_usuario_view(request, identificador):
try:
usuario = Usuario.objects.get(identificador = identificador)
except usuario.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = UsuarioSerializer(usuario)
return Response(serializer.data)
@api_view(['PUT',])
def api_update_usuario_view(request, identificador):
try:
usuario = Usuario.objects.get(identificador = identificador)
except usuario.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'PUT':
serializer = UsuarioSerializer(usuario, data=request.data)
data = {}
if serializer.is_valid():
serializer.save()
data[SUCCESS] = UPDATE_SUCCESS
return Response(data=data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['DELETE',])
def api_delete_usuario_view(request, identificador):
try:
usuario = Usuario.objects.get(identificador=identificador)
except usuario.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'DELETE':
operation = usuario.delete()
data = {}
if operation:
data[SUCCESS] = DELETE_SUCCESS
return Response(data=data)
@api_view(['POST'])
@permission_classes([AllowAny])
def api_create_usuario_view(request, identificador):
try:
usuario = Usuario.objects.get(identificador = identificador)
except usuario.DoesNotExist:
if request.method == 'POST':
serializer = UsuarioSerializer(usuario, data=request.data)
data = {}
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
[
"[email protected]"
] | |
d2333889ef1fc70d5e7c0a79e6f3112aa752306a
|
6fc84acaaf012f6cbbcb918390a4ed5508f84414
|
/opalWebsrv/test.py
|
5f5f02fee393637efbf17662b5ee5d476b2f476d
|
[] |
no_license
|
missinglpf/MAS_finite_consenus
|
43f03bdb2417c6da98cb5ff5a6b8b888ec1944b3
|
a83e8709dd12e5965ef4a5b413d056a434dd1245
|
refs/heads/master
| 2020-08-01T03:42:44.747402 | 2018-06-25T06:01:10 | 2018-06-25T06:01:10 | 210,850,495 | 3 | 0 | null | 2019-09-25T13:20:32 | 2019-09-25T13:20:32 | null |
UTF-8
|
Python
| false | false | 2,298 |
py
|
#! /usr/bin/python
import struct
import socket
import urllib
import subprocess
import sys
import time
import os
import traceback
def portIsOpened(hostip, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((hostip,port))
if result == 0:
return True
else:
return False
def fakeOpalCom(vals, the_format_in, the_format_out, hostip, port):
sock=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
d4= struct.pack(the_format_out, *vals)
sent=sock.sendto(d4, (hostip, port))
print "Opal sends", vals
rawdata,server=sock.recvfrom(4096)
sock.close()
data = struct.unpack(the_format_in, rawdata)
print "Opal recvd", data
return data
def testsrv(http_port, opal_port, nbIn, nbOut):
print "Testing with a new set"
assert(not(portIsOpened('127.0.0.1',http_port)))
assert(not(portIsOpened('127.0.0.1',opal_port)))
p = subprocess.Popen([os.getcwd()+ "/opalWebSrv.py", "-s", "-I", str(nbIn), "-O", str(nbOut)], bufsize=1024, stdin=sys.stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
time.sleep(0.5)
the_format_in='<hih'+str(nbIn)+'d'
the_format_out='<hih'+str(nbOut)+'d'
HTTP_PORT=str(8000)
UDP_IP='127.0.0.1'
UDP_PORT=50000
vals=[1,2,3]+range(1,nbOut+1)
opalret = fakeOpalCom(vals, the_format_in, the_format_out, UDP_IP, UDP_PORT)
assert(opalret==tuple([1,0,8*nbIn]+[0 for i in range(nbIn)]))
f=urllib.urlopen('http://localhost:'+HTTP_PORT+'/asyncsrv/set?valin0=12.5&valin1=40.2')
print f.read()
f=urllib.urlopen('http://localhost:'+HTTP_PORT+'/asyncsrv/get?name0=valout0&name1=valout1')
ret=f.read()
print ret
assert(ret=='{"valout0": 1.0, "valout1": 2.0}')
vals=[1,2,3,10.]+range(2,nbOut+1)
opalret = fakeOpalCom(vals, the_format_in, the_format_out, UDP_IP, UDP_PORT)
assert(opalret==tuple([1,1,8*nbIn]+[12.5,40.2]+ [0 for i in range(nbIn-2)]))
f=urllib.urlopen('http://localhost:'+HTTP_PORT+'/asyncsrv/get?name0=valout0&name1=valout1')
assert(f.read()=='{"valout0": 10.0, "valout1": 2.0}')
except Exception as error:
p.kill()
traceback.print_exc()
raise(error)
p.kill()
params_list = [
{"http_port": 8000, "opal_port": 50000,"nbIn":16, "nbOut":16},
{"http_port": 8001, "opal_port": 50001,"nbIn":10, "nbOut":12}
]
for params in params_list:
testsrv(**params)
print "Testing succeeded"
|
[
"[email protected]"
] | |
43dcac20edd103067c8fa3fce010b8162d077b2a
|
552ba370742e346dbb1cf7c7bf4b99648a17979b
|
/tbx/services/blocks.py
|
cbd8282834c2d89bfbac3f75334fcd64d1e9a9a5
|
[
"MIT"
] |
permissive
|
arush15june/wagtail-torchbox
|
73e5cdae81b524bd1ee9c563cdc8a7b5315a809e
|
c4d06e096c72bd8007975dc016133024f9d27fab
|
refs/heads/master
| 2022-12-25T05:39:32.309635 | 2020-08-13T14:50:42 | 2020-08-13T14:50:42 | 299,591,277 | 0 | 0 |
MIT
| 2020-09-29T11:08:49 | 2020-09-29T11:08:48 | null |
UTF-8
|
Python
| false | false | 3,242 |
py
|
from wagtail.core.blocks import (CharBlock, ListBlock, PageChooserBlock,
RichTextBlock, StreamBlock, StructBlock,
TextBlock, URLBlock)
from wagtail.images.blocks import ImageChooserBlock
from tbx.core.blocks import PullQuoteBlock
class CaseStudyBlock(StructBlock):
title = CharBlock(required=True)
intro = TextBlock(required=True)
case_studies = ListBlock(StructBlock([
('page', PageChooserBlock('work.WorkPage')),
('title', CharBlock(required=False)),
('descriptive_title', CharBlock(required=False)),
('image', ImageChooserBlock(required=False)),
]))
class Meta:
template = 'blocks/services/case_study_block.html'
class HighlightBlock(StructBlock):
title = CharBlock(required=True)
intro = RichTextBlock(required=False)
highlights = ListBlock(TextBlock())
class Meta:
template = 'blocks/services/highlight_block.html'
class StepByStepBlock(StructBlock):
title = CharBlock(required=True)
intro = TextBlock(required=False)
steps = ListBlock(StructBlock([
('subtitle', CharBlock(required=False)),
('title', CharBlock(required=True)),
('icon', CharBlock(max_length=9000, required=True, help_text='Paste SVG code here')),
('description', RichTextBlock(required=True))
]))
class Meta:
template = 'blocks/services/step_by_step_block.html'
class PeopleBlock(StructBlock):
title = CharBlock(required=True)
intro = RichTextBlock(required=True)
people = ListBlock(PageChooserBlock())
class Meta:
template = 'blocks/services/people_block.html'
class FeaturedPagesBlock(StructBlock):
title = CharBlock()
pages = ListBlock(StructBlock([
('page', PageChooserBlock()),
('image', ImageChooserBlock()),
('text', TextBlock()),
('sub_text', CharBlock(max_length=100)),
]))
class Meta:
template = 'blocks/services/featured_pages_block.html'
class SignUpFormPageBlock(StructBlock):
page = PageChooserBlock('sign_up_form.SignUpFormPage')
def get_context(self, value, parent_context=None):
context = super(SignUpFormPageBlock, self).get_context(value, parent_context)
context['form'] = value['page'].sign_up_form_class()
return context
class Meta:
icon = 'doc-full'
template = 'blocks/services/sign_up_form_page_block.html'
class LogosBlock(StructBlock):
title = CharBlock()
intro = CharBlock()
logos = ListBlock(StructBlock((
('image', ImageChooserBlock()),
('link_page', PageChooserBlock(required=False)),
('link_external', URLBlock(required=False)),
)))
class Meta:
icon = 'site'
template = 'blocks/services/logos_block.html'
class ServicePageBlock(StreamBlock):
paragraph = RichTextBlock(icon="pilcrow")
case_studies = CaseStudyBlock()
highlights = HighlightBlock()
pull_quote = PullQuoteBlock(template='blocks/services/pull_quote_block.html')
process = StepByStepBlock()
people = PeopleBlock()
featured_pages = FeaturedPagesBlock()
sign_up_form_page = SignUpFormPageBlock()
logos = LogosBlock()
|
[
"[email protected]"
] | |
d5e6beb44c4d3eabfbc1f90c7e6154546b5390be
|
3a85089c2498ff04d1b9bce17a4b8bf6cf2380c9
|
/RecoMuon/TrackingTools/python/__init__.py
|
46c2d8c095c7740e0d099c19bde145fc026b6c15
|
[] |
no_license
|
sextonkennedy/cmssw-ib
|
c2e85b5ffa1269505597025e55db4ffee896a6c3
|
e04f4c26752e0775bd3cffd3a936b288ee7b0268
|
HEAD
| 2016-09-01T20:09:33.163593 | 2013-04-26T12:05:17 | 2013-04-29T16:40:30 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 196 |
py
|
#Automatically created by SCRAM
import os
__path__.append(os.path.dirname(os.path.abspath(__file__).rsplit('/RecoMuon/TrackingTools/',1)[0])+'/cfipython/slc6_amd64_gcc480/RecoMuon/TrackingTools')
|
[
"[email protected]"
] | |
afa46d68ecf6d61c6df7864fbb08ae004dd62027
|
47a3a59288792f654309bfc9ceb6cbfa890720ef
|
/ramda/pick_all_test.py
|
c1dcb75e4e093273553227d190646a1b2ddff6d4
|
[
"MIT"
] |
permissive
|
jakobkolb/ramda.py
|
9531d32b9036908df09107d2cc19c04bf9544564
|
982b2172f4bb95b9a5b09eff8077362d6f2f0920
|
refs/heads/master
| 2023-06-23T00:46:24.347144 | 2021-02-01T16:47:51 | 2021-02-01T16:48:25 | 388,051,418 | 0 | 0 |
MIT
| 2021-07-21T16:31:45 | 2021-07-21T08:40:22 | null |
UTF-8
|
Python
| false | false | 317 |
py
|
from ramda import *
from ramda.private.asserts import *
def pick_all_test():
assert_equal(
pick_all(["a", "d"], {"a": 1, "b": 2, "c": 3, "d": 4}), {"a": 1, "d": 4}
)
assert_equal(
pick_all(["a", "e", "f"], {"a": 1, "b": 2, "c": 3, "d": 4}),
{"a": 1, "e": None, "f": None},
)
|
[
"[email protected]"
] | |
e185236b6376cf931550d58de7dbc40d13c29ad2
|
1e0e610166b36e5c73e7ff82c4c0b8b1288990bf
|
/scrapy/scrapy28.py
|
6f5341d26d3402dea78b84c8a0d584f884360945
|
[] |
no_license
|
PythonOpen/PyhonProjects
|
4ef1e70a971b9ebd0eb6a09e63e22581ad302534
|
ede93314009564c31aa586d2f89ed8b1e4751c1b
|
refs/heads/master
| 2022-05-20T23:21:03.536846 | 2020-04-27T00:59:32 | 2020-04-27T00:59:32 | 250,142,108 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 141 |
py
|
import re
'''
findall
'''
hello = u'您好,世界!'
s = r'[\u4e00-\u9fa5]+'
pattern = re.compile(s)
m = pattern.findall(hello)
print(m)
|
[
"[email protected]"
] | |
c40ac47c517727668db2d5ecdab88a29f78e49cd
|
df7f13ec34591fe1ce2d9aeebd5fd183e012711a
|
/hata/discord/application_command/application_command_option_metadata/tests/test__ApplicationCommandOptionMetadataFloat__magic.py
|
5f59bf9f28ed267aba57cdf79310534c0cbe8d27
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
HuyaneMatsu/hata
|
63e2f6a2d7a7539fd8f18498852d9d3fe5c41d2e
|
53f24fdb38459dc5a4fd04f11bdbfee8295b76a4
|
refs/heads/master
| 2023-08-20T15:58:09.343044 | 2023-08-20T13:09:03 | 2023-08-20T13:09:03 | 163,677,173 | 3 | 3 |
Apache-2.0
| 2019-12-18T03:46:12 | 2018-12-31T14:59:47 |
Python
|
UTF-8
|
Python
| false | false | 2,571 |
py
|
import vampytest
from ...application_command_option_choice import ApplicationCommandOptionChoice
from ..float import ApplicationCommandOptionMetadataFloat
def test__ApplicationCommandOptionMetadataFloat__repr():
"""
Tests whether ``ApplicationCommandOptionMetadataFloat.__repr__`` works as intended.
"""
required = True
autocomplete = True
choices = [ApplicationCommandOptionChoice('19', 19.0), ApplicationCommandOptionChoice('18', 18.0)]
max_value = 10.0
min_value = 20.0
option_metadata = ApplicationCommandOptionMetadataFloat(
required = required,
autocomplete = autocomplete,
choices = choices,
max_value = max_value,
min_value = min_value,
)
vampytest.assert_instance(repr(option_metadata), str)
def test__ApplicationCommandOptionMetadataFloat__hash():
"""
Tests whether ``ApplicationCommandOptionMetadataFloat.__hash__`` works as intended.
"""
required = True
autocomplete = True
choices = [ApplicationCommandOptionChoice('19', 19.0), ApplicationCommandOptionChoice('18', 18.0)]
max_value = 10.0
min_value = 20.0
option_metadata = ApplicationCommandOptionMetadataFloat(
required = required,
autocomplete = autocomplete,
choices = choices,
max_value = max_value,
min_value = min_value,
)
vampytest.assert_instance(hash(option_metadata), int)
def test__ApplicationCommandOptionMetadataFloat__eq():
"""
Tests whether ``ApplicationCommandOptionMetadataFloat.__eq__`` works as intended.
"""
required = True
autocomplete = True
choices = [ApplicationCommandOptionChoice('19', 19.0), ApplicationCommandOptionChoice('18', 18.0)]
max_value = 10.0
min_value = 20.0
keyword_parameters = {
'required': required,
'autocomplete': autocomplete,
'choices': choices,
'max_value': max_value,
'min_value': min_value,
}
option_metadata = ApplicationCommandOptionMetadataFloat(**keyword_parameters)
vampytest.assert_eq(option_metadata, option_metadata)
vampytest.assert_ne(option_metadata, object())
for field_name, field_value in (
('required', False),
('autocomplete', False),
('choices', None),
('max_value', 11.0),
('min_value', 12.0),
):
test_option_metadata = ApplicationCommandOptionMetadataFloat(**{**keyword_parameters, field_name: field_value})
vampytest.assert_ne(option_metadata, test_option_metadata)
|
[
"[email protected]"
] | |
1cb3e56193bf9836e2e816dd830b90e36338db8b
|
490ffe1023a601760ae7288e86723f0c6e366bba
|
/kolla-docker/python-zunclient/zunclient/osc/v1/images.py
|
4af97886c8048a0d97904f5372e7928a39594407
|
[
"Apache-2.0"
] |
permissive
|
bopopescu/Cloud-User-Management
|
89696a5ea5d2f95191327fbeab6c3e400bbfb2b8
|
390988bf4915a276c7bf8d96b62c3051c17d9e6e
|
refs/heads/master
| 2022-11-19T10:09:36.662906 | 2018-11-07T20:28:31 | 2018-11-07T20:28:31 | 281,786,345 | 0 | 0 | null | 2020-07-22T21:26:07 | 2020-07-22T21:26:06 | null |
UTF-8
|
Python
| false | false | 5,747 |
py
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_log import log as logging
from osc_lib.command import command
from osc_lib import utils
from zunclient.common import utils as zun_utils
def _image_columns(image):
return image._info.keys()
def _get_client(obj, parsed_args):
obj.log.debug("take_action(%s)" % parsed_args)
return obj.app.client_manager.container
class ListImage(command.Lister):
"""List available images"""
log = logging.getLogger(__name__ + ".ListImage")
def get_parser(self, prog_name):
parser = super(ListImage, self).get_parser(prog_name)
parser.add_argument(
'--marker',
metavar='<marker>',
default=None,
help='The last image UUID of the previous page; '
'displays list of images after "marker".')
parser.add_argument(
'--limit',
metavar='<limit>',
type=int,
help='Maximum number of images to return')
parser.add_argument(
'--sort-key',
metavar='<sort-key>',
help='Column to sort results by')
parser.add_argument(
'--sort-dir',
metavar='<sort-dir>',
choices=['desc', 'asc'],
help='Direction to sort. "asc" or "desc".')
return parser
def take_action(self, parsed_args):
client = _get_client(self, parsed_args)
opts = {}
opts['marker'] = parsed_args.marker
opts['limit'] = parsed_args.limit
opts['sort_key'] = parsed_args.sort_key
opts['sort_dir'] = parsed_args.sort_dir
opts = zun_utils.remove_null_parms(**opts)
images = client.images.list(**opts)
columns = ('uuid', 'image_id', 'repo', 'tag', 'size')
return (columns, (utils.get_item_properties(image, columns)
for image in images))
class PullImage(command.ShowOne):
"""Pull specified image"""
log = logging.getLogger(__name__ + ".PullImage")
def get_parser(self, prog_name):
parser = super(PullImage, self).get_parser(prog_name)
parser.add_argument(
'image',
metavar='<image>',
help='Name of the image')
return parser
def take_action(self, parsed_args):
client = _get_client(self, parsed_args)
opts = {}
opts['repo'] = parsed_args.image
image = client.images.create(**opts)
columns = _image_columns(image)
return columns, utils.get_item_properties(image, columns)
class SearchImage(command.Lister):
"""Search specified image"""
log = logging.getLogger(__name__ + ".SearchImage")
def get_parser(self, prog_name):
parser = super(SearchImage, self).get_parser(prog_name)
parser.add_argument(
'--image-driver',
metavar='<image-driver>',
help='Name of the image driver')
parser.add_argument(
'image_name',
metavar='<image_name>',
help='Name of the image')
parser.add_argument(
'--exact-match',
default=False,
action='store_true',
help='exact match image name')
return parser
def take_action(self, parsed_args):
client = _get_client(self, parsed_args)
opts = {}
opts['image_driver'] = parsed_args.image_driver
opts['image'] = parsed_args.image_name
opts['exact_match'] = parsed_args.exact_match
opts = zun_utils.remove_null_parms(**opts)
images = client.images.search_image(**opts)
columns = ('ID', 'Name', 'Tags', 'Status', 'Size', 'Metadata')
return (columns, (utils.get_item_properties(image, columns)
for image in images))
class ShowImage(command.ShowOne):
"""Describe a specific image"""
log = logging.getLogger(__name__ + ".ShowImage")
def get_parser(self, prog_name):
parser = super(ShowImage, self).get_parser(prog_name)
parser.add_argument(
'uuid',
metavar='<uuid>',
help='UUID of image to describe')
return parser
def take_action(self, parsed_args):
client = _get_client(self, parsed_args)
opts = {}
opts['id'] = parsed_args.uuid
image = client.images.get(**opts)
columns = _image_columns(image)
return columns, utils.get_item_properties(image, columns)
class DeleteImage(command.Command):
"""Delete specified image"""
log = logging.getLogger(__name__ + ".DeleteImage")
def get_parser(self, prog_name):
parser = super(DeleteImage, self).get_parser(prog_name)
parser.add_argument(
'uuid',
metavar='<uuid>',
help='UUID of image to describe')
return parser
def take_action(self, parsed_args):
client = _get_client(self, parsed_args)
img_id = parsed_args.uuid
try:
client.images.delete(img_id)
print(_('Request to delete image %s has been accepted.')
% img_id)
except Exception as e:
print("Delete for image %(image)s failed: %(e)s" %
{'image': img_id, 'e': e})
|
[
"[email protected]"
] | |
605b9fe4d1a7957cb2c55e30fa0363e03ff3f7eb
|
8bde826917476ba95bd3e9b4c33d4b28284c1774
|
/bin/fasta2phylip.py
|
20c4f9be477fe93b9186aee62a7a87c516416368
|
[] |
no_license
|
rpetit3-education/ibs594-phylogenetics
|
2935d2ea3ba0ab41967cb0ddf42a2850328034e4
|
f39048354d636300ba1a2067a0bdc5f0c6bddc95
|
refs/heads/master
| 2020-05-29T12:27:21.973218 | 2014-10-08T01:42:56 | 2014-10-08T01:42:56 | 24,832,930 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 294 |
py
|
#! /usr/bin/env python
'''
'''
import sys
from Bio import AlignIO
input_handle = open(sys.argv[1], "rU")
output_handle = open(sys.argv[2], "w")
alignments = AlignIO.parse(input_handle, "fasta")
AlignIO.write(alignments, output_handle, "phylip")
output_handle.close()
input_handle.close()
|
[
"[email protected]"
] | |
a8a8b14820fcddd5bd55fd019f52ee57c7ff3a51
|
de9bd97adcbe4d278a1bf1d5f9107e87b94366e1
|
/coding_solutions/Day9(28-05-2020)/Program2.py
|
31f78a9bb4008fe640973829d9b4d7bc8af22e25
|
[] |
no_license
|
alvas-education-foundation/ANUSHA_4AL17CS007
|
6ed2957d6d1b1b1f2172de3c8ba6bfd3f886aab9
|
031849369448dd60f56769abb630fc7cf22fe325
|
refs/heads/master
| 2022-10-29T10:49:23.188604 | 2020-06-15T15:50:00 | 2020-06-15T15:50:00 | 267,532,875 | 0 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 366 |
py
|
#Python program to find digital root of a #number
n = int(input("Enter the digit\n"))
def digital_root(n):
m = len(str(n))
s=0
for i in range(m):
s = s+ n%10
n = n//10
print(s)
if(len(str(s))>1):
return(digital_root(s))
print(digital_root(n))
Output:
Enter the digit
162536738292
54
9
Enter the digit
0
0
|
[
"[email protected]"
] | |
6841b5f8f2844439542581821019d5fd11329764
|
07f837d8c5236fe5e75ef510cd296814452370ce
|
/py/four_hour_cloud.py
|
220c212f5dfc9d69fd0d4fccfd0d8b1a5659a04f
|
[
"Apache-2.0"
] |
permissive
|
vkuznet/h2o
|
6f9006a5186b964bac266981d9082aec7bc1067c
|
e08f7014f228cbaecfb21f57379970e6a3ac0756
|
refs/heads/master
| 2021-08-28T11:37:52.099953 | 2021-08-10T22:43:34 | 2021-08-10T22:43:34 | 20,032,996 | 0 | 0 |
Apache-2.0
| 2021-08-10T22:43:35 | 2014-05-21T18:46:27 |
Java
|
UTF-8
|
Python
| false | false | 3,693 |
py
|
#!/usr/bin/python
import unittest, time, sys, random, datetime
sys.path.extend(['.','..','py','../h2o/py','../../h2o/py'])
import h2o, h2o_hosts, h2o_cmd, h2o_browse as h2b
import h2o_print as h2p
beginning = time.time()
def log(msg):
print "\033[92m[0xdata] \033[0m", msg
CHECK_WHILE_SLEEPING = False
print "Don't start a test yet..."
class Basic(unittest.TestCase):
def tearDown(self):
h2o.check_sandbox_for_errors()
@classmethod
def setUpClass(cls):
global SEED, localhost
SEED = h2o.setup_random_seed()
localhost = h2o.decide_if_localhost()
if (localhost):
# h2o.nodes[0].delete_keys_at_teardown should cause the testdir_release
# tests to delete keys after each test completion (not cloud teardown)
h2o.build_cloud(3, create_json=True, java_heap_GB=4, delete_keys_at_teardown=False)
else:
h2o_hosts.build_cloud_with_hosts(create_json=True, delete_keys_at_teardown=False)
@classmethod
def tearDownClass(cls):
h2o.tear_down_cloud()
def test_build_for_clone(self):
# python gets confused about which 'start' if I used start here
elapsed = time.time() - beginning
print "\n%0.2f seconds to get here from start" % elapsed
# might as well open a browser on it? (because the ip/port will vary
# maybe just print the ip/port for now
## h2b.browseTheCloud()
maxTime = 4*3600
totalTime = 0
incrTime = 60
h2p.purple_print("\nSleeping for total of", (maxTime+0.0)/3600, "hours.")
print "Will check h2o logs every", incrTime, "seconds"
print "Should be able to run another test using h2o-nodes.json to clone cloud"
print "i.e. h2o.build_cloud_with_json()"
print "Bad test if a running test shuts down the cloud. I'm supposed to!\n"
h2p.green_print("To watch cloud in browser follow address:")
h2p.green_print(" http://{0}:{1}/Cloud.html".format(h2o.nodes[0].http_addr, h2o.nodes[0].port))
h2p.blue_print("You can start a test (or tests) now!")
h2p.blue_print("Will Check cloud status every %s secs and kill cloud if wrong or no answer" % incrTime)
if CHECK_WHILE_SLEEPING:
h2p.blue_print("Will also look at redirected stdout/stderr logs in sandbox every %s secs" % incrTime)
h2p.red_print("No checking of logs while sleeping, or check of cloud status")
h2p.yellow_print("So if H2O stack traces, it's up to you to kill me if 4 hours is too long")
h2p.yellow_print("ctrl-c will cause all jvms to die(thru psutil terminate, paramiko channel death or h2o shutdown...")
while (totalTime<maxTime): # die after 4 hours
h2o.sleep(incrTime)
totalTime += incrTime
# good to touch all the nodes to see if they're still responsive
# give them up to 120 secs to respond (each individually)
h2o.verify_cloud_size(timeoutSecs=120)
if CHECK_WHILE_SLEEPING:
print "Checking sandbox log files"
h2o.check_sandbox_for_errors(cloudShutdownIsError=True)
else:
print str(datetime.datetime.now()), h2o.python_cmd_line, "still here", totalTime, maxTime, incrTime
# don't do this, as the cloud may be hung?
if 1==0:
print "Shutting down cloud, but first delete all keys"
start = time.time()
h2i.delete_keys_at_all_nodes()
elapsed = time.time() - start
print "delete_keys_at_all_nodes(): took", elapsed, "secs"
if __name__ == '__main__':
h2o.unit_main()
|
[
"[email protected]"
] | |
51d94bb10630aafec0640620432c3ebe407246a3
|
f5b5a6e3f844d849a05ff56c497638e607f940e0
|
/capitulo 06/06.32 - Programa 6.10 Transformacao de range em uma lista.py
|
51cd535815fbd14cb32451d366d9badde5012cb3
|
[] |
no_license
|
alexrogeriodj/Caixa-Eletronico-em-Python
|
9237fa2f7f8fab5f17b7dd008af215fb0aaed29f
|
96b5238437c88e89aed7a7b9c34b303e1e7d61e5
|
refs/heads/master
| 2020-09-06T21:47:36.169855 | 2019-11-09T00:22:14 | 2019-11-09T00:22:14 | 220,563,960 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 770 |
py
|
##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2019
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Terceira edição - Janeiro/2019 - ISBN 978-85-7522-718-3
# Site: http://python.nilo.pro.br/
#
# Arquivo: listagem3\capítulo 06\06.32 - Programa 6.10 – Transformação de range em uma lista.py
# Descrição: Programa 6.10 – Transformação de range em uma lista
##############################################################################
# Programa 6.10 – Transformação de range em uma lista
L = list(range(100, 1100, 50))
print(L)
|
[
"[email protected]"
] | |
0f8f10c674666f80a8dfb7dc011afc0af5ca45d6
|
41e69a518ff146ef299e9b807a7a96428effd958
|
/test/test_full_operations_operation.py
|
ef25b6c9c5cb0a0793bc2948de26f0953af9ea2b
|
[] |
no_license
|
daxslab/enzona-payment-python
|
40797a8aea7d7185ad04fe401c4f699cb1d93309
|
9a7721445cc1331e14687374df872f911a565305
|
refs/heads/master
| 2022-07-13T15:34:53.171246 | 2020-05-16T04:18:51 | 2020-05-16T04:18:51 | 264,357,269 | 2 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,007 |
py
|
# coding: utf-8
"""
PaymentAPI
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: v1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import enzona_payment
from enzona_payment.models.full_operations_operation import FullOperationsOperation # noqa: E501
from enzona_payment.rest import ApiException
class TestFullOperationsOperation(unittest.TestCase):
"""FullOperationsOperation unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testFullOperationsOperation(self):
"""Test FullOperationsOperation"""
# FIXME: construct object with mandatory attributes with example values
# model = enzona_payment.models.full_operations_operation.FullOperationsOperation() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
|
[
"[email protected]"
] | |
247f95d2dd1ba8c30dc05f432d9df8ab67e809ea
|
cd995dbf44647858e092f22fd99228b3aadc138a
|
/16 트라이/56 트라이 구현.py
|
a9e65658e8ed722ea191413bbcd928d182b72dc5
|
[] |
no_license
|
Wooyongjeong/python-algorithm-interview
|
ed970ae046bd65ac46fd4f42aaa386f353f97233
|
c134dbb1aaff5f4c7aa930be79fcdf1dfad62cec
|
refs/heads/master
| 2023-08-17T04:51:19.727919 | 2021-10-07T14:29:24 | 2021-10-07T14:29:24 | 398,216,040 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,336 |
py
|
import collections
# 풀이 1. 딕셔너리를 이용해 간결한 트라이 구현
# 트라이의 노드
class TrieNode:
def __init__(self):
self.word = False
self.children = collections.defaultdict(TrieNode)
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
# 단어 삽입
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
node = self.root
for char in word:
node = node.children[char]
node.word = True
# 단어 존재 여부 판별
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.word
# 문자열로 시작 단어 존재 여부 판별별
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
node = self.root
for char in prefix:
if char not in node.children:
return False
node = node.children[char]
return True
|
[
"[email protected]"
] | |
2f1752c2bb239fc015ffd2b4a91ad7011d473660
|
177c2393fb86c6fbcc1e995a60805e4a6b901aae
|
/Sesion-02/Banco/tarjeta/views.py
|
d3de642d321bb86fe5f489875cbfc164f93fcf53
|
[] |
no_license
|
rctorr/TECP0008FUPYCMX2001
|
bc6a11e33486be2ccb5d2b79a9a64ba5e48a24f4
|
419635f02de189b91a06a9b366950320dfb0e00e
|
refs/heads/master
| 2023-05-20T22:37:25.194835 | 2021-06-08T03:12:37 | 2021-06-08T03:12:37 | 370,964,281 | 1 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 164 |
py
|
from django.shortcuts import render
# Create your views here.
def index(request):
""" Atiende la petición GET / """
return render(request, "tarjeta/index.html")
|
[
"[email protected]"
] | |
eda95050e4aab8b87d5ef0e01e7b3dd35478760f
|
d0bd9c3c5539141c74e0eeae2fa6b7b38af84ce2
|
/tests/test_data/test_molecular_weight.py
|
6743fdd25cc4c253454be447b8c4c52f01c76f3a
|
[
"BSD-3-Clause"
] |
permissive
|
KaneWh1te/cogent3
|
150c72e2f80a6439de0413b39c4c37c09c9966e3
|
115e9eb5700627fdb24be61441a7e3e155c02c61
|
refs/heads/master
| 2023-07-29T00:32:03.742351 | 2021-04-20T04:32:00 | 2021-04-20T04:32:00 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,793 |
py
|
#!/usr/bin/env python
"""Tests for molecular weight.
"""
from unittest import TestCase, main
from cogent3.data.molecular_weight import ProteinMW, RnaMW
__author__ = "Rob Knight"
__copyright__ = "Copyright 2007-2021, The Cogent Project"
__credits__ = ["Rob Knight"]
__license__ = "BSD-3"
__version__ = "2021.04.20a"
__maintainer__ = "Gavin Huttley"
__email__ = "[email protected]"
__status__ = "Production"
from numpy.testing import assert_allclose
class WeightCalculatorTests(TestCase):
"""Tests for WeightCalculator, which should calculate molecular weights."""
def test_call(self):
"""WeightCalculator should return correct molecular weight"""
r = RnaMW
p = ProteinMW
self.assertEqual(p(""), 0)
self.assertEqual(r(""), 0)
assert_allclose(p("A"), 89.09)
assert_allclose(r("A"), 375.17)
assert_allclose(p("AAA"), 231.27)
assert_allclose(r("AAA"), 1001.59)
assert_allclose(r("AAACCCA"), 2182.37)
assert_allclose(
p(
"MVQQAESLEAESNLPREALDTEEGEFMACSPVALDESDPDWCKTASGHIKRPMNAFMVWSKIERRKIMEQSPDMHNAEISKRLGKR\
WKMLKDSEKIPFIREAERLRLKHMADYPDYKYRPRKKPKMDPSAKPSASQSPEKSAAGGGGGSAGGGAGGAKTSKGSSKKCGKLKA\
PAAAGAKAGAGKAAQSGDYGGAGDDYVLGSLRVSGSGGGGAGKTVKCVFLDEDDDDDDDDDELQLQIKQEPDEEDEEPPHQQLLQP\
PGQQPSQLLRRYNVAKVPASPTLSSSAESPEGASLYDEVRAGATSGAGGGSRLYYSFKNITKQHPPPLAQPALSPASSRSVSTSSS\
SSSGSSSGSSGEDADDLMFDLSLNFSQSAHSASEQQLGGGAAAGNLSLSLVDKDLDSFSEGSLGSHFEFPDYCTPELSEMIAGDWL\
EANFSDLVFTY"
),
46685.97,
)
# run if called from command-line
if __name__ == "__main__":
main()
|
[
"[email protected]"
] | |
687ceb831757b55f605ca7582082dad5862e647f
|
aab50ee31f6107fd08d87bd4a93ded216eebb6be
|
/com/baizhi/杜亚博作业/杜亚博_9.5/杜亚博_9.24.py
|
e22353a598b8ddc8afb188119acb08d6855be8a8
|
[] |
no_license
|
dyb-py/pk
|
deaf50988694475bdfcda6f2535ba0e728d79931
|
b571b67a98fa0be6d73cccb48b66386bc4dfd191
|
refs/heads/master
| 2020-12-29T15:06:20.294353 | 2020-02-06T09:05:08 | 2020-02-06T09:05:08 | 238,646,794 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,139 |
py
|
#1
# SyntaxError 语法错误
#2
#下标越界 IndexError
#3
#属性错误 AttributeError
#4
#KeyError
#5
# SyntaxError
#6
# NameError
#7
#
# UnboundLocalError
#8
# try-except 之类的语句来处理异常
#9
# 可以, 因为异常有多种 多个except可以捕捉多个异常
#10
#自定义异常类 直接或间接继承BaseException
#except捕捉一切异常
#except(异常1,异常2.。。)
#11
#不建议 可读性极差 出现异常后 不清楚是那种异常 不好维护
#12
#用finally关闭文件
#13
# try:
# for i in range(3):
# for j in range(3):
# if i==2:
# raise KeyboardInterrupt
# print(i,j)
# except KeyboardInterrupt:
# print('退出了')
#14
# def in_input():
# a=input('输入整数')
# try:
# a=int(a)
# print(a)
# except:
# print('输入的不是整数')
# in_input()
#15
#出现NameError
# try:
# f=open('my.txt')
# print(f.read())
# except OSError as reason:
# print('出错了'+str(reason))
# finally:
# try:
# f.close()
# except NameError as e :
# print(e)
|
[
"[email protected]"
] | |
0d13290dc44ec8593cb073a1ca94340e77ff9ea9
|
146db8cd0f775e0c4d051ea675bd147f1cb08503
|
/old/md-service/SMDS/timestamp.py
|
e0bd0bdf1daac67b56a62833456e03a8e2b03702
|
[
"Apache-2.0"
] |
permissive
|
syndicate-storage/syndicate
|
3cb4a22a4ae0d92859f57ed4634b03f1665791e4
|
4837265be3e0aa18cdf4ee50316dbfc2d1f06e5b
|
refs/heads/master
| 2020-04-14T19:59:42.849428 | 2016-03-24T15:47:49 | 2016-03-24T15:47:49 | 10,639,326 | 16 | 6 | null | null | null | null |
UTF-8
|
Python
| false | false | 5,873 |
py
|
#
# Utilities to handle timestamps / durations from/to integers and strings
#
# $Id: Timestamp.py 18344 2010-06-22 18:56:38Z caglar $
# $URL: http://svn.planet-lab.org/svn/PLCAPI/trunk/PLC/Timestamp.py $
#
#
# datetime.{datetime,timedelta} are powerful tools, but these objects are not
# natively marshalled over xmlrpc
#
from types import StringTypes
import time, calendar
import datetime
from SMDS.faults import *
from SMDS.parameter import Parameter, Mixed
# a dummy class mostly used as a namespace
class Timestamp:
debug=False
# debug=True
# this is how we expose times to SQL
sql_format = "%Y-%m-%d %H:%M:%S"
sql_format_utc = "%Y-%m-%d %H:%M:%S UTC"
# this one (datetime.isoformat) would work too but that's less readable - we support this input though
iso_format = "%Y-%m-%dT%H:%M:%S"
# sometimes it's convenient to understand more formats
input_formats = [ sql_format,
sql_format_utc,
iso_format,
"%Y-%m-%d %H:%M",
"%Y-%m-%d %H:%M UTC",
]
# for timestamps we usually accept either an int, or an ISO string,
# the datetime.datetime stuff can in general be used locally,
# but not sure it can be marshalled over xmlrpc though
@staticmethod
def Parameter (doc):
return Mixed (Parameter (int, doc + " (unix timestamp)"),
Parameter (str, doc + " (formatted as %s)"%Timestamp.sql_format),
)
@staticmethod
def sql_validate (input, timezone=False, check_future = False):
"""
Validates the specified GMT timestamp, returns a
standardized string suitable for SQL input.
Input may be a number (seconds since UNIX epoch back in 1970,
or a string (in one of the supported input formats).
If timezone is True, the resulting string contains
timezone information, which is hard-wired as 'UTC'
If check_future is True, raises an exception if timestamp is in
the past.
Returns a GMT timestamp string suitable to feed SQL.
"""
if not timezone: output_format = Timestamp.sql_format
else: output_format = Timestamp.sql_format_utc
if Timestamp.debug: print 'sql_validate, in:',input,
if isinstance(input, StringTypes):
sql=''
# calendar.timegm() is the inverse of time.gmtime()
for time_format in Timestamp.input_formats:
try:
timestamp = calendar.timegm(time.strptime(input, time_format))
sql = time.strftime(output_format, time.gmtime(timestamp))
break
# wrong format: ignore
except ValueError: pass
# could not parse it
if not sql:
raise MDInvalidArgument, "Cannot parse timestamp %r - not in any of %r formats"%(input,Timestamp.input_formats)
elif isinstance (input,(int,long,float)):
try:
timestamp = long(input)
sql = time.strftime(output_format, time.gmtime(timestamp))
except Exception,e:
raise MDInvalidArgument, "Timestamp %r not recognized -- %r"%(input,e)
else:
raise MDInvalidArgument, "Timestamp %r - unsupported type %r"%(input,type(input))
if check_future and input < time.time():
raise MDInvalidArgument, "'%s' not in the future" % sql
if Timestamp.debug: print 'sql_validate, out:',sql
return sql
@staticmethod
def sql_validate_utc (timestamp):
"For convenience, return sql_validate(intput, timezone=True, check_future=False)"
return Timestamp.sql_validate (timestamp, timezone=True, check_future=False)
@staticmethod
def cast_long (input):
"""
Translates input timestamp as a unix timestamp.
Input may be a number (seconds since UNIX epoch, i.e., 1970-01-01
00:00:00 GMT), a string (in one of the supported input formats above).
"""
if Timestamp.debug: print 'cast_long, in:',input,
if isinstance(input, StringTypes):
timestamp=0
for time_format in Timestamp.input_formats:
try:
result=calendar.timegm(time.strptime(input, time_format))
if Timestamp.debug: print 'out:',result
return result
# wrong format: ignore
except ValueError: pass
raise MDInvalidArgument, "Cannot parse timestamp %r - not in any of %r formats"%(input,Timestamp.input_formats)
elif isinstance (input,(int,long,float)):
result=long(input)
if Timestamp.debug: print 'out:',result
return result
else:
raise MDInvalidArgument, "Timestamp %r - unsupported type %r"%(input,type(input))
# utility for displaying durations
# be consistent in avoiding the datetime stuff
class Duration:
MINUTE = 60
HOUR = 3600
DAY = 3600*24
@staticmethod
def to_string(duration):
result=[]
left=duration
(days,left) = divmod(left,Duration.DAY)
if days: result.append("%d d)"%td.days)
(hours,left) = divmod (left,Duration.HOUR)
if hours: result.append("%d h"%hours)
(minutes, seconds) = divmod (left, Duration.MINUTE)
if minutes: result.append("%d m"%minutes)
if seconds: result.append("%d s"%seconds)
if not result: result = ['void']
return "-".join(result)
@staticmethod
def validate (duration):
# support seconds only for now, works for int/long/str
try:
return long (duration)
except:
raise MDInvalidArgument, "Could not parse duration %r"%duration
|
[
"[email protected]"
] | |
93f760d29e6465c846af2a2e81bf5e01ba327359
|
4c67533d6d5183ed985288a55631fe1c99b5ae21
|
/448.py
|
9f64bb067dba432831726c47da96cfac37b25b7d
|
[] |
no_license
|
Jiongxiao/Leetcode
|
546f789a0d892fe56d7f53a41aa97ccb2a8e1813
|
641775f750a1197f9aaa23e5122b0add2ae064ee
|
refs/heads/master
| 2021-01-17T01:11:35.970423 | 2017-09-21T07:04:52 | 2017-09-21T07:04:52 | 56,422,836 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 302 |
py
|
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
for i in range(len(nums)):
nums[abs(nums[i])-1]=-abs(nums[abs(nums[i])-1])
return [j+1 for j in range(len(nums)) if nums[j]>0]
|
[
"[email protected]"
] | |
2c478fb713f273ebcc755c97aa70348d66391179
|
fea44d5ca4e6c9b2c7950234718a4531d453849e
|
/sktime/forecasting/tests/test_sarimax.py
|
17fdd9984ebd6c8806270391fc1ea39884dc931e
|
[
"BSD-3-Clause"
] |
permissive
|
mlgig/sktime
|
288069ab8c9b0743113877032dfca8cf1c2db3fb
|
19618df351a27b77e3979efc191e53987dbd99ae
|
refs/heads/master
| 2023-03-07T20:22:48.553615 | 2023-02-19T18:09:12 | 2023-02-19T18:09:12 | 234,604,691 | 1 | 0 |
BSD-3-Clause
| 2020-01-17T17:50:12 | 2020-01-17T17:50:11 | null |
UTF-8
|
Python
| false | false | 1,049 |
py
|
# -*- coding: utf-8 -*-
"""Tests the SARIMAX model."""
__author__ = ["TNTran92"]
import pytest
from numpy.testing import assert_allclose
from sktime.forecasting.sarimax import SARIMAX
from sktime.utils._testing.forecasting import make_forecasting_problem
from sktime.utils.validation._dependencies import _check_soft_dependencies
df = make_forecasting_problem()
@pytest.mark.skipif(
not _check_soft_dependencies("statsmodels", severity="none"),
reason="skip test if required soft dependency not available",
)
def test_SARIMAX_against_statsmodels():
"""Compares Sktime's and Statsmodel's SARIMAX."""
from statsmodels.tsa.api import SARIMAX as _SARIMAX
sktime_model = SARIMAX(order=(1, 0, 0), trend="t", seasonal_order=(1, 0, 0, 6))
sktime_model.fit(df)
y_pred = sktime_model.predict(df.index)
stats = _SARIMAX(endog=df, order=(1, 0, 0), trend="t", seasonal_order=(1, 0, 0, 6))
stats_fit = stats.fit()
stats_pred = stats_fit.predict(df.index[0])
assert_allclose(y_pred.tolist(), stats_pred.tolist())
|
[
"[email protected]"
] | |
8bbeda72f37a50488eb26bdbe34f50cb14917af4
|
fcc88521f63a3c22c81a9242ae3b203f2ea888fd
|
/Python3/0459-Repeated-Substring-Pattern/soln.py
|
4ebac002c8929e3bbc180c53514482b5e1dc4e61
|
[
"MIT"
] |
permissive
|
wyaadarsh/LeetCode-Solutions
|
b5963e3427aa547d485d3a2cb24e6cedc72804fd
|
3719f5cb059eefd66b83eb8ae990652f4b7fd124
|
refs/heads/master
| 2022-12-06T15:50:37.930987 | 2020-08-30T15:49:27 | 2020-08-30T15:49:27 | 291,811,790 | 0 | 1 |
MIT
| 2020-08-31T19:57:35 | 2020-08-31T19:57:34 | null |
UTF-8
|
Python
| false | false | 158 |
py
|
class Solution:
def repeatedSubstringPattern(self, s):
"""
:type s: str
:rtype: bool
"""
return s in (s + s)[1:-1]
|
[
"[email protected]"
] | |
947b2fcbdca5e1cac34017bc1c75d05e106a4700
|
9f79c4f9a8a9154fc3dc9202ab8ed2547a722b5f
|
/Dictionaries/char_count.py
|
6e73cf6fa167e94d9894e7ca32f38daa5956f09f
|
[] |
no_license
|
grigor-stoyanov/PythonFundamentals
|
31b6da00bd8294e8e802174dca4e62b231134090
|
5ae5f1f1b9ca9500d10e95318a731d3b29950a30
|
refs/heads/main
| 2023-02-11T12:17:19.010596 | 2021-01-14T22:14:54 | 2021-01-14T22:14:54 | 321,658,096 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 287 |
py
|
line = input().split()
char_dic = {}
for word in line:
for char in range(0, len(word)):
if word[char] not in char_dic:
char_dic[word[char]] = 1
else:
char_dic[word[char]] += 1
for key, value in char_dic.items():
print(f'{key} -> {value}')
|
[
"[email protected]"
] | |
0bb6bbb5cb9dab50c91c9d10e108fdd734f381b9
|
c77b2f06a971d5e77a3dc71e972ef27fc85475a5
|
/algo_ds/_general/pattern_matching_naive.py
|
b1c431aa83f479f3a7c749328a24bc2fee5b1372
|
[] |
no_license
|
thefr33radical/codeblue
|
f25520ea85110ed09b09ae38e7db92bab8285b2f
|
86bf4a4ba693b1797564dca66b645487973dafa4
|
refs/heads/master
| 2022-08-01T19:05:09.486567 | 2022-07-18T22:56:05 | 2022-07-18T22:56:05 | 110,525,490 | 3 | 6 | null | null | null | null |
UTF-8
|
Python
| false | false | 321 |
py
|
'''
txt[] = "THIS IS A TEST TEXT"
pat[] = "TEST"
'''
import re
def compute():
txt= "THIS IS A TEST TEXT TEST"
pat = "TEST"
m = re.search(pat, txt)
print(m.span())
if pat in txt:
print("yes")
if __name__=="__main__":
compute()
|
[
"[email protected]"
] | |
0da0f290f94f52c7dd23b74744834633d0fd949c
|
e5135867a8f2f5923b21523489c8f246d9c5a13a
|
/kaleo/management/commands/infinite_invites.py
|
b69ea50f7cd1935b122e67b8b0c4cb9bd4126e13
|
[
"BSD-3-Clause"
] |
permissive
|
exitio/kaleo
|
01574cc0675211a586995e08a4e19b6a1c9063ee
|
53e73e0acf3429d83b45e6b22b1a6ec76ac69c12
|
refs/heads/master
| 2021-01-21T01:27:44.609605 | 2013-01-31T15:50:10 | 2013-01-31T15:50:10 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 471 |
py
|
import sys
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from kaleo.models import InvitationStat
class Command(BaseCommand):
help = "Sets invites_allocated to -1 to represent infinite invites."
def handle(self, *args, **kwargs):
for user in User.objects.all():
stat, _ = InvitationStat.objects.get_or_create(user=user)
stat.invites_allocated = -1
stat.save()
|
[
"[email protected]"
] | |
d924c27a884790f3eccceeacebb5b4ef409f3586
|
da5ef82554c6c0413193b7c99192edd70fed58dd
|
/mozdns/soa/tests.py
|
529c22573446ed774dbfbfa53a43c6d989673fa2
|
[] |
no_license
|
rtucker-mozilla/mozilla_inventory
|
d643c7713c65aa870e732e18aaf19ce677e277b7
|
bf9154b0d77705d8c0fe1a9a35ce9c1bd60fcbea
|
refs/heads/master
| 2020-12-24T17:17:37.621418 | 2013-04-11T10:39:41 | 2013-04-11T10:39:41 | 2,709,399 | 1 | 2 | null | null | null | null |
UTF-8
|
Python
| false | false | 5,757 |
py
|
from django.test import TestCase
from django.core.exceptions import ValidationError
from mozdns.soa.models import SOA
from mozdns.domain.models import Domain
class SOATests(TestCase):
def setUp(self):
pass
def do_generic_add(self, primary, contact, retry, refresh, description):
soa = SOA(primary=primary, contact=contact,
retry=retry, refresh=refresh, description=description)
soa.save()
soa.save()
rsoa = SOA.objects.filter(primary=primary, contact=contact,
retry=retry, refresh=refresh)
self.assertTrue(len(rsoa) == 1)
return soa
def test_add_soa(self):
primary = "ns1.oregonstate.edu"
contact = "admin.oregonstate.edu"
retry = 1234
refresh = 1234123
description = "1"
self.do_generic_add(
primary, contact, retry, refresh, description=description)
soa = SOA.objects.filter(primary=primary, contact=contact,
retry=retry, refresh=refresh)
soa[0].save()
self.assertTrue(soa)
soa[0].__repr__()
soa = soa[0]
self.assertTrue(soa.details())
self.assertTrue(soa.get_absolute_url())
self.assertTrue(soa.get_edit_url())
self.assertTrue(soa.get_delete_url())
primary = "do.com"
contact = "admf.asdf"
retry = 432152
refresh = 1235146134
description = "2"
self.do_generic_add(
primary, contact, retry, refresh, description=description)
soa = SOA.objects.filter(primary=primary, contact=contact,
retry=retry, refresh=refresh)
self.assertTrue(soa)
soa = soa[0]
self.assertTrue(soa.details())
self.assertTrue(soa.get_absolute_url())
self.assertTrue(soa.get_edit_url())
self.assertTrue(soa.get_delete_url())
primary = "ns1.derp.com"
contact = "admf.asdf"
soa = SOA(primary=primary, contact=contact)
soa.save()
self.assertTrue(
soa.serial and soa.expire and soa.retry and soa.refresh)
self.assertTrue(soa.details())
self.assertTrue(soa.get_absolute_url())
self.assertTrue(soa.get_edit_url())
self.assertTrue(soa.get_delete_url())
def test_add_remove(self):
primary = "ns2.oregonstate.edu"
contact = "admin.oregonstate.edu"
retry = 1234
refresh = 1234123
description = "3"
soa = self.do_generic_add(
primary, contact, retry, refresh, description=description)
soa.delete()
soa = SOA.objects.filter(primary=primary, contact=contact,
retry=retry, refresh=refresh)
self.assertTrue(len(soa) == 0)
primary = "dddo.com"
contact = "admf.asdf"
retry = 432152
refresh = 1235146134
description = "4"
soa = self.do_generic_add(
primary, contact, retry, refresh, description=description)
soa.delete()
soa = SOA.objects.filter(primary=primary, contact=contact, retry=retry,
refresh=refresh, description=description)
self.assertTrue(len(soa) == 0)
# Add dup
description = "4"
soa = self.do_generic_add(
primary, contact, retry, refresh, description=description)
soa.save()
self.assertRaises(ValidationError, self.do_generic_add, *(
primary, contact, retry, refresh, description))
def test_add_invalid(self):
data = {'primary': "daf..fff", 'contact': "foo.com"}
soa = SOA(**data)
self.assertRaises(ValidationError, soa.save)
data = {'primary': 'foo.com', 'contact': 'dkfa..'}
soa = SOA(**data)
self.assertRaises(ValidationError, soa.save)
data = {'primary': 'adf', 'contact': '*@#$;'}
soa = SOA(**data)
self.assertRaises(ValidationError, soa.save)
def test_delete_with_domains(self):
data = {'primary': "ns1asfdadsf.foo.com", 'contact': "email.foo.com"}
soa = SOA(**data)
soa.save()
d0 = Domain(name='com')
d0.save()
d1 = Domain(name='foo.com', soa=soa)
d1.soa = soa
d1.save()
self.assertRaises(ValidationError, soa.delete)
def test_chain_soa_domain_add(self):
data = {'primary': "ns1.foo.com", 'contact': "email.foo.com"}
soa = SOA(**data)
soa.save()
d0 = Domain(name='com')
d0.save()
d1 = Domain(name='foo.com', soa=soa)
d1.save()
self.assertTrue(soa == d1.soa)
d2 = Domain(name='bar.foo.com', soa=soa)
d2.save()
self.assertTrue(soa == d2.soa)
d3 = Domain(name='new.foo.com', soa=soa)
d3.save()
self.assertTrue(soa == d3.soa)
d4 = Domain(name='far.bar.foo.com', soa=soa)
d4.save()
self.assertTrue(soa == d4.soa)
d5 = Domain(name='tee.new.foo.com', soa=soa)
d5.save()
self.assertTrue(soa == d5.soa)
d5.delete()
d4.delete()
self.assertTrue(soa == d1.soa)
self.assertTrue(soa == d2.soa)
self.assertTrue(soa == d3.soa)
def test_update_serial_no_dirty(self):
# If we update the serial, the dirty bit shouldn't change.
data = {'primary': "fakey.ns1.asdffoo.com", 'contact':
"adsffoopy.email.foo.com"}
soa = SOA(**data)
soa.save() # new soa's are always dirty
soa.dirty = False
soa.save()
soa.serial = soa.serial + 9
soa.save()
same_soa = SOA.objects.get(pk=soa.pk)
self.assertFalse(same_soa.dirty)
|
[
"[email protected]"
] | |
a2556ca3423248387c4752f977fd8c4b52bd63ec
|
de24f83a5e3768a2638ebcf13cbe717e75740168
|
/moodledata/vpl_data/135/usersdata/224/45859/submittedfiles/OBI.py
|
5fea3ee2b17d98501bf3732ea5e8dc6b5487efd9
|
[] |
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 | 278 |
py
|
# -*- coding: utf-8 -*-
N=int(input('Digite o numero de competidores: '))
P=int(input('Digite o numero mínimo de ponto para as duas fases: '))
somA=o
i=1
for i in range(1.n+1,1):
x=int(input('Nota1: '))
y=int(input('Nota2: '))
if x+y==P:
soma=soma+1
print(soma)
|
[
"[email protected]"
] | |
b13cac275f608ebea67b00f70a7d5e7ec19afebe
|
fa247fbb7755cf21fa262b02fa6c36a19adae55a
|
/manage.py
|
d344b73c096cab159e05d4a868f32b29a1888f88
|
[] |
no_license
|
crowdbotics-apps/csantosmachadogmailco-897
|
9ea0f851badc9678a8148ea051131eaa711b26de
|
b76954f678212ece02777d3deebb3e571bfb578c
|
refs/heads/master
| 2022-12-13T12:51:23.337978 | 2019-02-07T13:01:07 | 2019-02-07T13:01:07 | 169,572,262 | 0 | 0 | null | 2022-12-08T01:37:36 | 2019-02-07T12:59:48 |
Python
|
UTF-8
|
Python
| false | false | 823 |
py
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "csantosmachadogmailco_897.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
|
[
"[email protected]"
] | |
d14ce4d4e3bde8dff86cf8596a0610aa6ce7e652
|
210e88536cd2a917fb66010ff69f6710b2261e8e
|
/games/migrations/0002_auto__add_field_game_is_over.py
|
ab9299348edd60d9b0e5600523b1bc7cd285f9ce
|
[] |
no_license
|
tlam/multiverse_sidekick
|
e5ef1fa908c6fd3fee4d816aa1776b7243075e8c
|
9211e4cb36611088420a79666f0c40ecb0a6b645
|
refs/heads/master
| 2020-04-17T08:30:28.396623 | 2015-08-27T03:36:47 | 2015-08-27T03:36:47 | 9,423,955 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,875 |
py
|
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Game.is_over'
db.add_column(u'games_game', 'is_over',
self.gf('django.db.models.fields.BooleanField')(default=False),
keep_default=False)
def backwards(self, orm):
# Deleting field 'Game.is_over'
db.delete_column(u'games_game', 'is_over')
models = {
u'environment.environment': {
'Meta': {'object_name': 'Environment'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'games.activehero': {
'Meta': {'object_name': 'ActiveHero'},
'game': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['games.Game']"}),
'hero': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['heroes.Hero']"}),
'hp': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
u'games.game': {
'Meta': {'object_name': 'Game'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'environment': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['environment.Environment']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_over': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'profile': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['profiles.Profile']"}),
'villain': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['villains.Villain']"}),
'villain_hp': ('django.db.models.fields.IntegerField', [], {'default': '0'})
},
u'heroes.hero': {
'Meta': {'object_name': 'Hero'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'starting_hp': ('django.db.models.fields.IntegerField', [], {'default': '0'})
},
u'profiles.profile': {
'Meta': {'object_name': 'Profile'},
'date_of_birth': ('django.db.models.fields.DateField', [], {}),
'email': ('django.db.models.fields.EmailField', [], {'unique': 'True', 'max_length': '255', 'db_index': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_admin': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'})
},
u'villains.villain': {
'Meta': {'object_name': 'Villain'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'starting_hp': ('django.db.models.fields.IntegerField', [], {'default': '0'})
}
}
complete_apps = ['games']
|
[
"[email protected]"
] | |
d1d2b859904e2d714def63d27148d911b68e70b9
|
43e900f11e2b230cdc0b2e48007d40294fefd87a
|
/Facebook/PhoneInterview/shortest_job_first.py
|
02f0c808d6aad85a7f1028a46e84e57fdcc92298
|
[] |
no_license
|
DarkAlexWang/leetcode
|
02f2ed993688c34d3ce8f95d81b3e36a53ca002f
|
89142297559af20cf990a8e40975811b4be36955
|
refs/heads/master
| 2023-01-07T13:01:19.598427 | 2022-12-28T19:00:19 | 2022-12-28T19:00:19 | 232,729,581 | 3 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,058 |
py
|
import heapq
class process:
def process(self, arr, exe):
self.arrTime = arr
self.exeTime = exe
class Solution:
def shortest_job_first(self, req, dur):
if req == None or dur == None or len(req) != len(dur):
return 0
index, length = 0, len(req)
waitTime, curTime = 0, 0
pq = []
if p1.exeTime == p2.exeTime:
return p1.arrTime - p2.arrTime
return p1.exeTime - p2.exeTime
while pq or index < length:
if pq:
cur = pq.heappushpop()
waitTime += curTIme - cur.arrTime
curTime += cur.exeTime
while index < length and curTime >= req[index]:
pq.heappush((req[index], dur[index+1]))
else:
pq.heappush(req[index], dur[index])
curTime = req[index + 1]
return round(waitTime/length, 2)
if __name__ == '__main__':
solution = Solution()
res = solution.shortest_job_first([1,2, 3, 4], [1, 2, 3, 4])
print(res)
|
[
"[email protected]"
] | |
ee5988f7474b4fc537308710e17b74a741581fd1
|
d8ea695288010f7496c8661bfc3a7675477dcba0
|
/django/ewm/file/admin.py
|
edbb70030fbb242451d77d39501bf657b1b2fdb1
|
[] |
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 | 660 |
py
|
from django.contrib import admin
from file.models import *
###
# 注册附件信息数据库模型和自定义功能
###
@admin.register(File)
class FileAdmin(admin.ModelAdmin):
###
# 管理中要显示的字段名称
###
list_display = [
'file_name',
# 'manufacturer_name',
# 'model_specification',
# 'equipment_location',
# 'enable_date',
]
###
# 管理中要搜索的字段名称
###
search_fields = [
'file_name',
# 'manufacturer_name',
# 'model_specification',
# 'equipment_location',
# 'enable_date',
]
|
[
"[email protected]"
] | |
04153bb5d37ce2d86223a0bd652aa1f3ce650c12
|
4a344071b0dc0e43073f5aa680dc9ed46074d7db
|
/azure/mgmt/network/models/network_management_client_enums.py
|
5f0cd8bb7a6b49af179f7ff4a5221d9d397fba4a
|
[] |
no_license
|
pexip/os-python-azure-mgmt-network
|
59ee8859cda2a77e03c051d104b1e8d2f08c1fe3
|
fa4f791818b8432888c398b3841da58e5aeb370b
|
refs/heads/master
| 2023-08-28T05:02:29.843835 | 2017-02-28T11:38:16 | 2017-02-28T11:47:18 | 54,524,386 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 5,166 |
py
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from enum import Enum
class TransportProtocol(Enum):
udp = "Udp"
tcp = "Tcp"
class IPAllocationMethod(Enum):
static = "Static"
dynamic = "Dynamic"
class IPVersion(Enum):
ipv4 = "IPv4"
ipv6 = "IPv6"
class SecurityRuleProtocol(Enum):
tcp = "Tcp"
udp = "Udp"
asterisk = "*"
class SecurityRuleAccess(Enum):
allow = "Allow"
deny = "Deny"
class SecurityRuleDirection(Enum):
inbound = "Inbound"
outbound = "Outbound"
class RouteNextHopType(Enum):
virtual_network_gateway = "VirtualNetworkGateway"
vnet_local = "VnetLocal"
internet = "Internet"
virtual_appliance = "VirtualAppliance"
none = "None"
class ApplicationGatewayProtocol(Enum):
http = "Http"
https = "Https"
class ApplicationGatewayCookieBasedAffinity(Enum):
enabled = "Enabled"
disabled = "Disabled"
class ApplicationGatewayBackendHealthServerHealth(Enum):
unknown = "Unknown"
healthy = "Healthy"
unhealthy = "Unhealthy"
partial = "Partial"
class ApplicationGatewaySkuName(Enum):
standard_small = "Standard_Small"
standard_medium = "Standard_Medium"
standard_large = "Standard_Large"
waf_medium = "WAF_Medium"
waf_large = "WAF_Large"
class ApplicationGatewayTier(Enum):
standard = "Standard"
waf = "WAF"
class ApplicationGatewaySslProtocol(Enum):
tl_sv1_0 = "TLSv1_0"
tl_sv1_1 = "TLSv1_1"
tl_sv1_2 = "TLSv1_2"
class ApplicationGatewayRequestRoutingRuleType(Enum):
basic = "Basic"
path_based_routing = "PathBasedRouting"
class ApplicationGatewayOperationalState(Enum):
stopped = "Stopped"
starting = "Starting"
running = "Running"
stopping = "Stopping"
class ApplicationGatewayFirewallMode(Enum):
detection = "Detection"
prevention = "Prevention"
class AuthorizationUseStatus(Enum):
available = "Available"
in_use = "InUse"
class ExpressRouteCircuitPeeringAdvertisedPublicPrefixState(Enum):
not_configured = "NotConfigured"
configuring = "Configuring"
configured = "Configured"
validation_needed = "ValidationNeeded"
class ExpressRouteCircuitPeeringType(Enum):
azure_public_peering = "AzurePublicPeering"
azure_private_peering = "AzurePrivatePeering"
microsoft_peering = "MicrosoftPeering"
class ExpressRouteCircuitPeeringState(Enum):
disabled = "Disabled"
enabled = "Enabled"
class ExpressRouteCircuitSkuTier(Enum):
standard = "Standard"
premium = "Premium"
class ExpressRouteCircuitSkuFamily(Enum):
unlimited_data = "UnlimitedData"
metered_data = "MeteredData"
class ServiceProviderProvisioningState(Enum):
not_provisioned = "NotProvisioned"
provisioning = "Provisioning"
provisioned = "Provisioned"
deprovisioning = "Deprovisioning"
class LoadDistribution(Enum):
default = "Default"
source_ip = "SourceIP"
source_ip_protocol = "SourceIPProtocol"
class ProbeProtocol(Enum):
http = "Http"
tcp = "Tcp"
class EffectiveRouteSource(Enum):
unknown = "Unknown"
user = "User"
virtual_network_gateway = "VirtualNetworkGateway"
default = "Default"
class EffectiveRouteState(Enum):
active = "Active"
invalid = "Invalid"
class VirtualNetworkPeeringState(Enum):
initiated = "Initiated"
connected = "Connected"
disconnected = "Disconnected"
class VirtualNetworkGatewayType(Enum):
vpn = "Vpn"
express_route = "ExpressRoute"
class VpnType(Enum):
policy_based = "PolicyBased"
route_based = "RouteBased"
class VirtualNetworkGatewaySkuName(Enum):
basic = "Basic"
high_performance = "HighPerformance"
standard = "Standard"
ultra_performance = "UltraPerformance"
class VirtualNetworkGatewaySkuTier(Enum):
basic = "Basic"
high_performance = "HighPerformance"
standard = "Standard"
ultra_performance = "UltraPerformance"
class ProcessorArchitecture(Enum):
amd64 = "Amd64"
x86 = "X86"
class VirtualNetworkGatewayConnectionStatus(Enum):
unknown = "Unknown"
connecting = "Connecting"
connected = "Connected"
not_connected = "NotConnected"
class VirtualNetworkGatewayConnectionType(Enum):
ipsec = "IPsec"
vnet2_vnet = "Vnet2Vnet"
express_route = "ExpressRoute"
vpn_client = "VPNClient"
class NetworkOperationStatus(Enum):
in_progress = "InProgress"
succeeded = "Succeeded"
failed = "Failed"
|
[
"[email protected]"
] | |
0fe2a3ee5bcbf151df129e38ff5051b969889aca
|
d9dcbd9f4dc60ab752670d2b7025c2da05f6d69d
|
/study_day12_flask01/15_hook.py
|
61dfd8866cf5d20895859f744a5ca530dfbbfdc9
|
[] |
no_license
|
chenliang15405/python-learning
|
14c7e60c794026b1f2dadbbbe82f63e4745b0c23
|
6de32a1c9b729e9528b45c080e861b3da352f858
|
refs/heads/master
| 2020-08-28T12:21:07.544254 | 2020-01-04T10:49:50 | 2020-01-04T10:49:50 | 217,696,366 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 763 |
py
|
"""
请求的钩子
"""
from flask import Flask, request
app = Flask(__name__)
@app.route("/hello")
def index():
print("hello 执行")
return "login success"
# 相当于程序启动之后在处理第一个请求的时候执行的函数
@app.before_first_request
def index():
print("第一次请求处理前执行")
@app.before_request
def index():
print("每次请求之前都被执行")
@app.after_request
def index():
print("每次请求之后都执行,出现异常则不执行")
@app.teardown_request
def index():
# 就算请求的路由不存在,也会执行这个函数
print(request.path)
print("每次请求之后执行,无论是否出现异常,都执行")
if __name__ == '__main__':
app.run()
|
[
"[email protected]"
] | |
4d3956aca08cd84cabb584e92a9c96a95ef34502
|
11cf40946c55b47886cfe8777916a17db82c2309
|
/ex8.py
|
717dbf1941b429dd3f54602f98d5e4661d89267e
|
[] |
no_license
|
dalalsunil1986/python_the_hard_way_exercises
|
fc669bf2f823a4886f0de717d5f1ca0d0233f6af
|
bc329999490dedad842e23e8447623fd0321ffe0
|
refs/heads/master
| 2023-05-03T01:35:24.097087 | 2021-05-16T00:43:56 | 2021-05-16T00:43:56 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 281 |
py
|
formatter = "{} {} {} {}"
print(formatter.format(1, 2, 3, 4))
print(formatter.format("one", "two", "three", "four"))
print(formatter.format(formatter, formatter, formatter, formatter))
print(formatter.format(
"Try your",
"Own text",
"Maybe a",
"Or some bs"
))
|
[
"[email protected]"
] | |
bf8de6800a12c7d01677b1d90a2bcfdcc875683f
|
c68c841c67f03ab8794027ff8d64d29356e21bf1
|
/Sort Letters by Case.py
|
df083f821551643b58d7653b6921c678258e3104
|
[] |
no_license
|
jke-zq/my_lintcode
|
430e482bae5b18b59eb0e9b5b577606e93c4c961
|
64ce451a7f7be9ec42474f0b1164243838077a6f
|
refs/heads/master
| 2020-05-21T20:29:11.236967 | 2018-06-14T15:14:55 | 2018-06-14T15:14:55 | 37,583,264 | 8 | 2 | null | null | null | null |
UTF-8
|
Python
| false | false | 593 |
py
|
class Solution:
"""
@param chars: The letters array you should sort.
"""
def sortLetters(self, chars):
# write your code here
if not chars:
return None
length = len(chars)
left, pivot, right = 0, 0, length - 1
while left <= right:
if chars[left].islower():
chars[pivot], chars[left] = chars[left], chars[pivot]
pivot += 1
left += 1
else:
chars[left], chars[right] = chars[right], chars[left]
right -= 1
|
[
"[email protected]"
] | |
787c2274a31c79dfdceb6628ae8aab2f7590a368
|
630e5fa4fec4cee4b6936eec74a726550406c11f
|
/test/functional/rpc_bip38.py
|
93dfb7a50712e55599f4be7defa4821459115c3a
|
[
"MIT"
] |
permissive
|
crypTuron/PengolinCoin-Core
|
4d815d25de927d42dc890379d15738ee728c525e
|
3d6c66dd930110075ff44ee6f5a4364c533becd7
|
refs/heads/master
| 2022-11-24T21:17:56.271853 | 2020-07-23T13:49:52 | 2020-07-23T13:49:52 | 282,408,670 | 0 | 0 |
MIT
| 2020-07-25T09:04:22 | 2020-07-25T09:04:21 | null |
UTF-8
|
Python
| false | false | 1,016 |
py
|
#!/usr/bin/env python3
# Copyright (c) 2018 The PENGOLINCOIN developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test RPC commands for BIP38 encrypting and decrypting addresses."""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal
class Bip38Test(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 2
def run_test(self):
password = 'test'
address = self.nodes[0].getnewaddress()
privkey = self.nodes[0].dumpprivkey(address)
self.log.info('encrypt address %s' % (address))
bip38key = self.nodes[0].bip38encrypt(address, password)['Encrypted Key']
self.log.info('decrypt bip38 key %s' % (bip38key))
assert_equal(self.nodes[1].bip38decrypt(bip38key, password)['Address'], address)
if __name__ == '__main__':
Bip38Test().main()
|
[
"[email protected]"
] | |
030e52259d44d34774c35c42d1d85544d7bbead2
|
0f7e18a483a44352dfac27137b8d351416f1d1bb
|
/tools/extract_gif.py
|
2954d57a2760b14fc8ed5596e03e11684e3c682c
|
[] |
no_license
|
rinoshinme/slim_finetune
|
b5ec4ed53a2d6c15dfa5b4cfb73677ccb58a4aa6
|
1e465e3faff668e65cc873828057365114d4cfb1
|
refs/heads/master
| 2022-11-07T21:02:38.253001 | 2022-11-02T14:48:45 | 2022-11-02T14:48:45 | 199,089,723 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 676 |
py
|
"""
Extract image frames from gif files.
"""
import cv2
import os
def read_gif(gif_file, write_folder, name_prefix):
capture = cv2.VideoCapture(gif_file)
cnt = 1
while True:
ret, frame = capture.read()
if not ret:
break
save_name = os.path.join(write_folder, '%s_%06d.jpg' % (name_prefix, cnt))
cv2.imwrite(save_name, frame)
cnt += 1
if __name__ == '__main__':
gif_folder = r'D:\data\21cn_baokong\bad_format'
fnames = os.listdir(gif_folder)
for name in fnames:
gif_path = os.path.join(gif_folder, name)
prefix = name.split('.')[0]
read_gif(gif_path, gif_folder, prefix)
|
[
"[email protected]"
] | |
9a303d5a18b1917d5e0ff10d6430ce6a4b6bd086
|
3b9b4049a8e7d38b49e07bb752780b2f1d792851
|
/src/tools/perf/page_sets/blink_memory_mobile.py
|
40b5f134886c79490da62c0fdd3e8fdc1c01ea0c
|
[
"BSD-3-Clause",
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-2.0-only",
"LicenseRef-scancode-unknown",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
webosce/chromium53
|
f8e745e91363586aee9620c609aacf15b3261540
|
9171447efcf0bb393d41d1dc877c7c13c46d8e38
|
refs/heads/webosce
| 2020-03-26T23:08:14.416858 | 2018-08-23T08:35:17 | 2018-09-20T14:25:18 | 145,513,343 | 0 | 2 |
Apache-2.0
| 2019-08-21T22:44:55 | 2018-08-21T05:52:31 | null |
UTF-8
|
Python
| false | false | 5,080 |
py
|
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
from telemetry.page import page as page_module
from telemetry.page import shared_page_state
from telemetry import story
from page_sets.login_helpers import google_login
DUMP_WAIT_TIME = 3
class BlinkMemoryMobilePage(page_module.Page):
def __init__(self, url, page_set, name):
super(BlinkMemoryMobilePage, self).__init__(
url=url, page_set=page_set, name=name,
shared_page_state_class=shared_page_state.SharedMobilePageState,
credentials_path='data/credentials.json')
self.archive_data_file = 'data/blink_memory_mobile.json'
def _DumpMemory(self, action_runner, phase):
with action_runner.CreateInteraction(phase):
action_runner.Wait(DUMP_WAIT_TIME)
action_runner.ForceGarbageCollection()
action_runner.SimulateMemoryPressureNotification('critical')
action_runner.Wait(DUMP_WAIT_TIME)
if not action_runner.tab.browser.DumpMemory():
logging.error('Unable to get a memory dump for %s.', self.name)
def RunPageInteractions(self, action_runner):
action_runner.ScrollPage()
self._DumpMemory(action_runner, 'scrolled')
class TheVergePage(BlinkMemoryMobilePage):
COMMENT_LINK_SELECTOR = '.show_comments_link'
def __init__(self, page_set):
super(TheVergePage, self).__init__(
'http://www.theverge.com/2015/8/11/9133883/taylor-swift-spotify-discover-weekly-what-is-going-on',
page_set=page_set,
name='TheVerge')
def RunPageInteractions(self, action_runner):
action_runner.WaitForElement(selector=TheVergePage.COMMENT_LINK_SELECTOR)
action_runner.ExecuteJavaScript(
'window.location.hash = "comments"')
action_runner.TapElement(
selector=TheVergePage.COMMENT_LINK_SELECTOR)
action_runner.WaitForJavaScriptCondition(
'window.Chorus.Comments.collection.length > 0')
super(TheVergePage, self).RunPageInteractions(action_runner)
class FacebookPage(BlinkMemoryMobilePage):
def __init__(self, page_set):
super(FacebookPage, self).__init__(
'https://facebook.com/barackobama',
page_set=page_set,
name='Facebook')
def RunNavigateSteps(self, action_runner):
super(FacebookPage, self).RunNavigateSteps(action_runner)
action_runner.WaitForJavaScriptCondition(
'document.getElementById("u_0_c") !== null &&'
'document.body.scrollHeight > window.innerHeight')
class GmailPage(BlinkMemoryMobilePage):
def __init__(self, page_set):
super(GmailPage, self).__init__(
'https://mail.google.com/mail/',
page_set=page_set,
name='Gmail')
def RunNavigateSteps(self, action_runner):
google_login.LoginGoogleAccount(action_runner, 'google',
self.credentials_path)
super(GmailPage, self).RunNavigateSteps(action_runner)
# Needs to wait for navigation to handle redirects.
action_runner.WaitForNavigate()
action_runner.WaitForElement(selector='#apploadingdiv')
action_runner.WaitForJavaScriptCondition(
'document.querySelector("#apploadingdiv").style.opacity == "0"')
class BlinkMemoryMobilePageSet(story.StorySet):
"""Key mobile sites for Blink memory reduction."""
def __init__(self):
super(BlinkMemoryMobilePageSet, self).__init__(
archive_data_file='data/blink_memory_mobile.json',
cloud_storage_bucket=story.PARTNER_BUCKET)
# Why: High rate of Blink's memory consumption rate.
self.AddStory(BlinkMemoryMobilePage(
'https://www.pinterest.com',
page_set=self,
name='Pinterest'))
self.AddStory(FacebookPage(self))
# TODO(bashi): Enable TheVergePage. http://crbug.com/522381
# self.AddStory(TheVergePage(self))
# Why: High rate of Blink's memory comsumption rate on low-RAM devices.
self.AddStory(BlinkMemoryMobilePage(
'http://en.m.wikipedia.org/wiki/Wikipedia',
page_set=self,
name='Wikipedia (1 tab) - delayed scroll start',))
self.AddStory(BlinkMemoryMobilePage(
url='http://www.reddit.com/r/programming/comments/1g96ve',
page_set=self,
name='Reddit'))
self.AddStory(BlinkMemoryMobilePage(
'https://en.blog.wordpress.com/2012/09/04/freshly-pressed-editors-picks-for-august-2012/',
page_set=self,
name='Wordpress'))
# Why: Renderer memory usage is high.
self.AddStory(BlinkMemoryMobilePage(
'http://worldjournal.com/',
page_set=self,
name='Worldjournal'))
# Why: Key products.
self.AddStory(GmailPage(page_set=self))
self.AddStory(BlinkMemoryMobilePage(
'http://googlewebmastercentral.blogspot.com/2015/04/rolling-out-mobile-friendly-update.html?m=1',
page_set=self,
name='Blogger'))
self.AddStory(BlinkMemoryMobilePage(
'https://plus.google.com/app/basic/110031535020051778989/posts?source=apppromo',
page_set=self,
name='GooglePlus'))
|
[
"[email protected]"
] | |
c3d90ec27fcc681bfa880229fd4e3c3d7269f3d8
|
9de3cd1f8d66e223b7f193776376147136321b30
|
/tests/test_cookie_storage.py
|
80d9dbd52236af389425acd1c41c63ce277620ad
|
[
"Apache-2.0"
] |
permissive
|
kolko/aiohttp_session
|
223b5eaf8c291407f289e20efe692a0afef31bca
|
8df78b3d7bd5623f82ff8171c9d947107421f4ce
|
refs/heads/master
| 2021-01-18T09:43:10.928082 | 2015-08-06T16:15:51 | 2015-08-06T16:15:51 | 40,311,233 | 0 | 0 | null | 2015-08-06T15:06:58 | 2015-08-06T15:06:58 | null |
UTF-8
|
Python
| false | false | 5,099 |
py
|
import asyncio
import json
import socket
import unittest
from aiohttp import web, request
from aiohttp_session import (Session, session_middleware,
get_session, SimpleCookieStorage)
class TestSimleCookieStorage(unittest.TestCase):
def setUp(self):
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(None)
self.srv = None
self.handler = None
def tearDown(self):
self.loop.run_until_complete(self.handler.finish_connections())
self.srv.close()
self.loop.close()
def find_unused_port(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 0))
port = s.getsockname()[1]
s.close()
return port
@asyncio.coroutine
def create_server(self, method, path, handler=None):
middleware = session_middleware(SimpleCookieStorage())
app = web.Application(middlewares=[middleware], loop=self.loop)
if handler:
app.router.add_route(method, path, handler)
port = self.find_unused_port()
handler = app.make_handler()
srv = yield from self.loop.create_server(
handler, '127.0.0.1', port)
url = "http://127.0.0.1:{}".format(port) + path
self.handler = handler
self.srv = srv
return app, srv, url
def make_cookie(self, data):
value = json.dumps(data)
return {'AIOHTTP_SESSION': value}
def test_create_new_sesssion(self):
@asyncio.coroutine
def handler(request):
session = yield from get_session(request)
self.assertIsInstance(session, Session)
self.assertTrue(session.new)
self.assertFalse(session._changed)
self.assertEqual({}, session)
return web.Response(body=b'OK')
@asyncio.coroutine
def go():
_, _, url = yield from self.create_server('GET', '/', handler)
resp = yield from request('GET', url, loop=self.loop)
self.assertEqual(200, resp.status)
self.loop.run_until_complete(go())
def test_load_existing_sesssion(self):
@asyncio.coroutine
def handler(request):
session = yield from get_session(request)
self.assertIsInstance(session, Session)
self.assertFalse(session.new)
self.assertFalse(session._changed)
self.assertEqual({'a': 1, 'b': 2}, session)
return web.Response(body=b'OK')
@asyncio.coroutine
def go():
_, _, url = yield from self.create_server('GET', '/', handler)
resp = yield from request(
'GET', url,
cookies=self.make_cookie({'a': 1, 'b': 2}),
loop=self.loop)
self.assertEqual(200, resp.status)
self.loop.run_until_complete(go())
def test_change_sesssion(self):
@asyncio.coroutine
def handler(request):
session = yield from get_session(request)
session['c'] = 3
return web.Response(body=b'OK')
@asyncio.coroutine
def go():
_, _, url = yield from self.create_server('GET', '/', handler)
resp = yield from request(
'GET', url,
cookies=self.make_cookie({'a': 1, 'b': 2}),
loop=self.loop)
self.assertEqual(200, resp.status)
morsel = resp.cookies['AIOHTTP_SESSION']
self.assertEqual({'a': 1, 'b': 2, 'c': 3}, eval(morsel.value))
self.assertTrue(morsel['httponly'])
self.assertEqual('/', morsel['path'])
self.loop.run_until_complete(go())
def test_clear_cookie_on_sesssion_invalidation(self):
@asyncio.coroutine
def handler(request):
session = yield from get_session(request)
session.invalidate()
return web.Response(body=b'OK')
@asyncio.coroutine
def go():
_, _, url = yield from self.create_server('GET', '/', handler)
resp = yield from request(
'GET', url,
cookies=self.make_cookie({'a': 1, 'b': 2}),
loop=self.loop)
self.assertEqual(200, resp.status)
self.assertEqual(
'Set-Cookie: AIOHTTP_SESSION="{}"; httponly; Path=/'.upper(),
resp.cookies['AIOHTTP_SESSION'].output().upper())
self.loop.run_until_complete(go())
def test_dont_save_not_requested_session(self):
@asyncio.coroutine
def handler(request):
return web.Response(body=b'OK')
@asyncio.coroutine
def go():
_, _, url = yield from self.create_server('GET', '/', handler)
resp = yield from request(
'GET', url,
cookies=self.make_cookie({'a': 1, 'b': 2}),
loop=self.loop)
self.assertEqual(200, resp.status)
self.assertNotIn('AIOHTTP_SESSION', resp.cookies)
self.loop.run_until_complete(go())
|
[
"[email protected]"
] | |
9d4365826dd9af614ce9b518bc6de82921605311
|
621a865f772ccbab32471fb388e20b620ebba6b0
|
/compile/gameserver/data/scripts/quests/378_MagnificentFeast/__init__.py
|
b971073fd517a5f3915abefa119d21a16ab52a08
|
[] |
no_license
|
BloodyDawn/Scions_of_Destiny
|
5257de035cdb7fe5ef92bc991119b464cba6790c
|
e03ef8117b57a1188ba80a381faff6f2e97d6c41
|
refs/heads/master
| 2021-01-12T00:02:47.744333 | 2017-04-24T06:30:39 | 2017-04-24T06:30:39 | 78,662,280 | 0 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,714 |
py
|
# Magnificent Feast - v0.1 by DrLecter (adapted for L2JLisvus by roko91)
import sys
from net.sf.l2j.gameserver.model.quest import State
from net.sf.l2j.gameserver.model.quest import QuestState
from net.sf.l2j.gameserver.model.quest.jython import QuestJython as JQuest
qn = "378_MagnificentFeast"
#NPC
RANSPO = 7594
#ITEMS
WINE_15,WINE_30,WINE_60 = range(5956,5959)
SCORE = 4421
RP_SALAD,RP_SAUCE,RP_STEAK = range(1455,1458)
RP_DESSERT = 5959
#REWARDS
REWARDS={
9:[847,1,5700],
10:[846,2,0],
12:[909,1,25400],
17:[846,2,1200],
18:[879,1,6900],
20:[890,2,8500],
33:[879,1,8100],
34:[910,1,0],
36:[848,1,2200],
}
class Quest (JQuest) :
def __init__(self,id,name,descr): JQuest.__init__(self,id,name,descr)
def onEvent (self,event,st) :
htmltext = event
score = st.getInt("score")
cond = st.getInt("cond")
if event == "7594-2.htm" and cond == 0 :
st.set("cond","1")
st.setState(STARTED)
st.playSound("ItemSound.quest_accept")
elif event == "7594-4a.htm" :
if st.getQuestItemsCount(WINE_15) and cond == 1 :
st.takeItems(WINE_15,1)
st.set("cond","2")
st.set("score",str(score+1))
else :
htmltext = "7594-4.htm"
elif event == "7594-4b.htm" :
if st.getQuestItemsCount(WINE_30) and cond == 1 :
st.takeItems(WINE_30,1)
st.set("cond","2")
st.set("score",str(score+2))
else :
htmltext = "7594-4.htm"
elif event == "7594-4c.htm" :
if st.getQuestItemsCount(WINE_60) and cond == 1 :
st.takeItems(WINE_60,1)
st.set("cond","2")
st.set("score",str(score+4))
else :
htmltext = "7594-4.htm"
elif event == "7594-6.htm" :
if st.getQuestItemsCount(SCORE) and cond == 2 :
st.takeItems(SCORE,1)
st.set("cond","3")
else :
htmltext = "7594-5.htm"
elif event == "7594-8a.htm" :
if st.getQuestItemsCount(RP_SALAD) and cond == 3 :
st.takeItems(RP_SALAD,1)
st.set("cond","4")
st.set("score",str(score+8))
else :
htmltext = "7594-8.htm"
elif event == "7594-8b.htm" :
if st.getQuestItemsCount(RP_SAUCE) and cond == 3 :
st.takeItems(RP_SAUCE,1)
st.set("cond","4")
st.set("score",str(score+16))
else :
htmltext = "7594-8.htm"
elif event == "7594-8c.htm" :
if st.getQuestItemsCount(RP_STEAK) and cond == 3 :
st.takeItems(RP_STEAK,1)
st.set("cond","4")
st.set("score",str(score+32))
else :
htmltext = "7594-8.htm"
return htmltext
def onTalk (self,npc,st):
htmltext = "no-quest.htm"
npcId = npc.getNpcId()
id = st.getState()
cond=st.getInt("cond")
if cond == 0 :
if st.getPlayer().getLevel() >= 20 :
htmltext = "7594-1.htm"
else:
htmltext = "7594-0.htm"
st.exitQuest(1)
elif cond == 1 :
htmltext = "7594-3.htm"
elif cond == 2 :
if st.getQuestItemsCount(SCORE) :
htmltext = "7594-5a.htm"
else :
htmltext = "7594-5.htm"
elif cond == 3 :
htmltext = "7594-7.htm"
elif cond == 4 :
score = st.getInt("score")
if st.getQuestItemsCount(RP_DESSERT) and score in REWARDS.keys() :
item,qty,adena=REWARDS[score]
st.giveItems(item,qty)
if adena :
st.giveItems(57,adena)
st.takeItems(RP_DESSERT,1)
st.playSound("ItemSound.quest_finish")
htmltext = "7594-10.htm"
st.exitQuest(1)
else :
htmltext = "7594-9.htm"
return htmltext
QUEST = Quest(378,qn,"Magnificent Feast")
CREATED = State('Start', QUEST)
STARTED = State('Started', QUEST)
QUEST.setInitialState(CREATED)
QUEST.addStartNpc(RANSPO)
QUEST.addTalkId(RANSPO)
|
[
"[email protected]"
] | |
551fbca4a6614d91516633237c0818a95fb45e7d
|
986630b72263dc5db7acb2d617d989111bc23649
|
/urbanizze/map/migrations/0006_terreno_setor.py
|
29d7b9ccb761a532bcf7f9d2fab2d7b746bb9e42
|
[] |
no_license
|
marcellobenigno/urbanizze
|
afbef6d45077ed93e0edd3abf21d167561659914
|
ca11fa55846030a75e8d4815e13dcd1df89ff421
|
refs/heads/master
| 2022-08-13T03:55:32.269185 | 2019-08-08T10:33:42 | 2019-08-08T10:33:42 | 201,235,674 | 1 | 2 | null | 2021-12-13T20:07:21 | 2019-08-08T10:31:30 |
JavaScript
|
UTF-8
|
Python
| false | false | 510 |
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-20 01:55
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('map', '0005_setor'),
]
operations = [
migrations.AddField(
model_name='terreno',
name='setor',
field=models.CharField(default='Setor 04', max_length=50, verbose_name='setor'),
preserve_default=False,
),
]
|
[
"[email protected]"
] | |
56104be7b888315ad95f9167b9242fd41724b8e4
|
c93c88d7e45cfcf05822c701a1c1dafee8153347
|
/projects/cs102/circle_of_squares.py
|
fd97d939c1fb1f0196448c0b8b062ffd70ff92aa
|
[] |
no_license
|
timisenman/python
|
b7c09f6377e9a28787fce7b0ade6cab499691524
|
9ea6b6605bd78b11b981ca26a4b9b43abe449713
|
refs/heads/master
| 2020-05-21T22:46:50.502488 | 2017-01-18T22:54:23 | 2017-01-18T22:54:23 | 63,548,164 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 983 |
py
|
#A Circle of Squares
#Either creates a draw square function,
#and rotate it 10 degrees 36 times.
import turtle
def draw_square(a_turtle):
for i in range(1,5):
a_turtle.forward(100)
a_turtle.right(90)
def draw_art():
window = turtle.Screen()
window.bgcolor("blue")
brad = turtle.Turtle()
brad.shape("turtle")
brad.color("white")
brad.speed(10)
for i in range(1,37):
draw_square(brad)
brad.right(10)
brad.right(630)
print("Square done")
## angie = turtle.Turtle()
## angie.shape("turtle")
## angie.color("yellow")
## angie.speed(2)
## angie.circle(100)
## print("Circle drawn")
##
## bro = turtle.Turtle()
## bro.shape("turtle")
## bro.color("green")
## bro.speed(2)
## bro.left(90)
## bro.forward(100)
## bro.left(90)
## bro.forward(100)
## bro.left(135)
## bro.forward(141.42)
## print("Triangle done")
window.exitonclick()
draw_art()
|
[
"[email protected]"
] | |
5d02379f98ac637617a3f89c3ac250ecf7787fbd
|
52b5773617a1b972a905de4d692540d26ff74926
|
/.history/knapsack_20200708153620.py
|
dd426fbe9706b3c9e39d8c8e2e1af773190273a4
|
[] |
no_license
|
MaryanneNjeri/pythonModules
|
56f54bf098ae58ea069bf33f11ae94fa8eedcabc
|
f4e56b1e4dda2349267af634a46f6b9df6686020
|
refs/heads/master
| 2022-12-16T02:59:19.896129 | 2020-09-11T12:05:22 | 2020-09-11T12:05:22 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 656 |
py
|
def Knap(a,b,w):
# declare an empty dictionary
newArr = []
for i,j in zip(a,b):
smallArr = []
smallArr.append(i)
smallArr.append(j)
newArr.append(smallArr)
i = 0
# at position 0 is the weight and at position 1 is the value
# goal is to find highest value but not greater than W
while i < len(newArr):
if (newArr[i][0] + newArr[i+1][0]) <= w:
value = newArr[i][1] + newArr[i+1][1]
print('value',value ,'>',)
if value > newArr[i][1] + newArr[i+1][1]:
print(value)
i +=1
Knap([10,20,30],[60,100,120],220)
|
[
"[email protected]"
] | |
27f38e0cf34c7a458c77862ed021f69b1081d219
|
9adea4131921ae4b8c94e6e20c8dcd5efa8f5f4a
|
/src/group_by.py
|
585b07ad5374f384b3db8715b75f8af318fac5fe
|
[
"BSD-3-Clause"
] |
permissive
|
ferhatcicek/minifold
|
33f447133601c299c9ddf6e7bfaa888f43c999fd
|
00c5e912e18a713b0496bcb869f5f6af4f3d40c9
|
refs/heads/master
| 2022-12-15T05:58:04.541226 | 2020-09-25T16:55:52 | 2020-09-25T16:55:52 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,689 |
py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# This file is part of the minifold project.
# https://github.com/nokia/minifold
__author__ = "Marc-Olivier Buob"
__maintainer__ = "Marc-Olivier Buob"
__email__ = "[email protected]"
__copyright__ = "Copyright (C) 2018, Nokia"
__license__ = "BSD-3"
from .connector import Connector
from .hash import to_hashable
from .query import Query, ACTION_READ
from .values_from_dict import ValuesFromDictFonctor
def group_by_impl(fonctor :ValuesFromDictFonctor, entries :list) -> dict:
ret = dict()
for entry in entries:
key = fonctor(entry)
if len(key) == 1:
(key,) = key
key = to_hashable(key)
if key not in ret.keys(): ret[key] = list()
ret[key].append(entry)
return ret
def group_by(attributes :list, entries :list) -> list:
fonctor = ValuesFromDictFonctor(attributes)
return group_by_impl(fonctor, entries)
class GroupByConnector(Connector):
def __init__(self, attributes :list, child):
super().__init__()
self.m_fonctor = ValuesFromDictFonctor(attributes)
self.m_child = child
@property
def child(self):
return self.m_child
def attributes(self, object :str):
return set(self.m_fonctor.attributes)
def query(self, q :Query) -> list:
super().query(q)
return self.answer(
q,
group_by_impl(
self.m_fonctor,
self.m_child.query(q)
)
)
def __str__(self) -> str:
return "GROUP BY %s" % ", ".join(self.m_fonctor.attributes)
|
[
"[email protected]"
] | |
d202ffe04150297400e04709fcc09d24982baf93
|
8d402df39c18eba7e1c86c762f205c944357c5df
|
/www/gallery/sidebar.py
|
40830ea74ad141050c9cf4d414e8d9b5a387a0f1
|
[
"BSD-3-Clause"
] |
permissive
|
brython-dev/brython
|
87cc023e25550dec9ce459ba68774189f33712b6
|
b33958bff0e8c7a280babc30232dc389a2500a7a
|
refs/heads/master
| 2023-09-04T04:49:29.156209 | 2023-09-01T06:36:08 | 2023-09-01T06:36:08 | 24,046,239 | 6,569 | 625 |
BSD-3-Clause
| 2023-07-05T06:13:32 | 2014-09-15T06:58:21 |
Python
|
UTF-8
|
Python
| false | false | 236 |
py
|
x=0
from browser.html import A,B,BR
print('A',A)
from os import *
def menu(title,links):
# links is a list of tuples (name,href)
res = B(title)
for _name,href in links:
res += BR()+A(_name,href=href)
return res
|
[
"[email protected]"
] | |
53e62f8d8703c493130f1759cf7ee0c205c4f15c
|
d396aa3495407069935ebab3faf870ad87025014
|
/python-leetcode/剑指offer/tree/剑指 Offer 55 - I. 二叉树的深度.py
|
36b475c95dd52bc934243fe9103e8b69f9f96341
|
[] |
no_license
|
qwjaskzxl/For-OJ
|
4d3b2f873cf11c5f9ddb74c4b91b4b78cccc3afa
|
1fe6e5099d95fff2dcfc503951ff6e311202919b
|
refs/heads/master
| 2021-12-25T21:17:44.232567 | 2021-08-05T14:01:59 | 2021-08-05T14:01:59 | 175,966,016 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,156 |
py
|
pass
'''
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
提示:
节点总数 <= 10000
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root: return 0
MAX = 0
def dfs(node, depth):
nonlocal MAX
if not node:
return
if depth > MAX:
MAX = depth
if node.left: dfs(node.left, depth + 1)
if node.right: dfs(node.right, depth + 1)
dfs(root, 1)
return MAX
class Solution_666:
def maxDepth(self, root: TreeNode) -> int:
if not root: return 0
return max(self.maxDepth(root.left),
self.maxDepth(root.right)) \
+ 1
|
[
"[email protected]"
] | |
6950bb2514c10a37f69d8268d2a1bcae8b0f65e0
|
f0257428fed2a5f10950ee52e88a0f6811120323
|
/book_study/book_chapter4/tuple.py
|
8b984479ddcedf9425ce141e5f6f5ccf6b3c92c8
|
[] |
no_license
|
tata-LY/python
|
454d42cc8f6db9a1450966aba4af6894e1b59b78
|
55d13b7f61cbb87ff3f272f596cd5b8c53b807c5
|
refs/heads/main
| 2023-04-08T19:31:57.945506 | 2021-04-19T05:39:17 | 2021-04-19T05:39:17 | 328,880,464 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 284 |
py
|
#!/usr/bin/env python3
# _*_coding:utf-8_*_
# by liuyang
tuple1 = (1,100)
print(tuple1)
print(tuple1[0])
#tuple1[0] = 10 #元组不允许修改
#print(tuple1)
for i in tuple1:
print(i)
tuple1 = ('liuyang', 'zhangjuan') # 不允许修改,可以重新定义
print(tuple1)
|
[
"[email protected]"
] | |
22f0a214ee1dca65b2464ec11b94e429d66e79cc
|
78eb766321c7ed3236fb87bb6ac8547c99d0d1a4
|
/oneYou2/pages/migrations/0001_initial.py
|
8aaa7b7e731d48ae75dd6fe64a29f8b282817fdc
|
[] |
no_license
|
danmorley/nhs-example
|
9d7be76116ed962248e1f7e287355a6870534f5d
|
ae4b5f395d3518ee17ef89348ed756c817e0c08c
|
refs/heads/master
| 2022-12-13T02:13:18.484448 | 2019-02-28T11:05:31 | 2019-02-28T11:05:31 | 203,353,840 | 1 | 0 | null | 2022-12-07T04:29:46 | 2019-08-20T10:30:15 |
Python
|
UTF-8
|
Python
| false | false | 1,087 |
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-02-06 14:59
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import wagtail.core.blocks
import wagtail.core.fields
import wagtail.images.blocks
class Migration(migrations.Migration):
initial = True
dependencies = [
('wagtailcore', '0040_page_draft_title'),
]
operations = [
migrations.CreateModel(
name='OneYou2Page',
fields=[
('page_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='wagtailcore.Page')),
('body', wagtail.core.fields.StreamField((('heading', wagtail.core.blocks.CharBlock(classname='full title')), ('paragraph', wagtail.core.blocks.RichTextBlock()), ('image', wagtail.images.blocks.ImageChooserBlock())))),
],
options={
'abstract': False,
},
bases=('wagtailcore.page',),
),
]
|
[
"[email protected]"
] | |
6148f29660770166eb2b88bd95268e8ebb855c58
|
eff5cd25fa442b70491262bada0584eaaf8add46
|
/tfx/tools/cli/testdata/test_pipeline_airflow_2.py
|
324d6b0cfbc2ed928677e8a5bbc8c1e5c375d2ac
|
[
"Apache-2.0"
] |
permissive
|
fsx950223/tfx
|
c58e58a85e6de6e9abcb8790acbf36424b5b2029
|
527fe2bab6e4f62febfe1a2029358fabe55f418c
|
refs/heads/master
| 2021-01-04T12:12:51.010090 | 2020-01-26T04:43:14 | 2020-01-26T04:43:14 | 240,543,231 | 1 | 0 |
Apache-2.0
| 2020-02-14T15:48:12 | 2020-02-14T15:48:11 | null |
UTF-8
|
Python
| false | false | 3,007 |
py
|
# Lint as: python2, python3
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Pipeline for testing CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import datetime
import os
from tfx.components.example_gen.csv_example_gen.component import CsvExampleGen
from tfx.components.schema_gen.component import SchemaGen
from tfx.components.statistics_gen.component import StatisticsGen
from tfx.orchestration import pipeline
from tfx.orchestration.airflow.airflow_dag_runner import AirflowDagRunner
from tfx.orchestration.airflow.airflow_dag_runner import AirflowPipelineConfig
from tfx.utils.dsl_utils import csv_input
# This example assumes that the taxi data is stored in ~/taxi/data and the
# taxi utility function is in ~/taxi. Feel free to customize this as needed.
_taxi_root = os.path.join(os.environ['HOME'], 'taxi')
_data_root = os.path.join(_taxi_root, 'data/simple')
# Directory and data locations. This example assumes all of the chicago taxi
# example code and metadata library is relative to $HOME, but you can store
# these files anywhere on your local filesystem.
_tfx_root = os.path.join(os.environ['HOME'], 'tfx')
_pipeline_root = os.path.join(_tfx_root, 'pipelines')
_metadata_db_root = os.path.join(_tfx_root, 'metadata')
_log_root = os.path.join(_tfx_root, 'logs')
# Airflow-specific configs; these will be passed directly to airflow
_airflow_config = {
'schedule_interval': None,
'start_date': datetime.datetime(2019, 1, 1),
}
def _create_pipeline():
"""Implements the chicago taxi pipeline with TFX."""
examples = csv_input(_data_root)
# Brings data into the pipeline or otherwise joins/converts training data.
example_gen = CsvExampleGen(input=examples)
# Computes statistics over data for visualization and example validation.
statistics_gen = StatisticsGen(examples=example_gen.outputs['examples'])
# Generates schema based on statistics files.
infer_schema = SchemaGen(statistics=statistics_gen.outputs['statistics'])
return pipeline.Pipeline(
pipeline_name='chicago_taxi_simple',
pipeline_root=_pipeline_root,
components=[
example_gen, statistics_gen, infer_schema
],
enable_cache=True,
metadata_db_root=_metadata_db_root,
)
# Airflow checks 'DAG' keyword for finding the dag.
airflow_pipeline = AirflowDagRunner(AirflowPipelineConfig(_airflow_config)).run(
_create_pipeline())
|
[
"[email protected]"
] | |
d6cdeb85c2c728cec647a482d4b7f3bb21bb0366
|
a80047f86b96367c75fd24a43be67bb8202645aa
|
/tailor/models.py
|
00f95b7fe8b02f9d3e439941c5eebce2bbfdddc3
|
[
"MIT"
] |
permissive
|
Albert-Byrone/Tailor_Hub
|
84deaee04809c56bb4d7638dfa800e434936c82a
|
0ab4402302d03f261ff00af79f84b62cbd241a27
|
refs/heads/master
| 2022-12-09T14:18:01.392545 | 2019-12-23T10:26:44 | 2019-12-23T10:26:44 | 224,847,452 | 0 | 0 |
MIT
| 2022-12-08T03:18:46 | 2019-11-29T12:10:07 |
Python
|
UTF-8
|
Python
| false | false | 6,060 |
py
|
from django.db import models
from django.contrib.auth.models import User
from django.shortcuts import reverse
from pyuploadcare.dj.models import ImageField
from django.db.models.signals import post_save
from django.dispatch import receiver
import datetime as datetime
from django_countries.fields import CountryField
from django.db.models import Q
CATEGORY_CHOICES=(
('SU','Suits'),
('TR','Trousers'),
('CO','Coats'),
('DR','Dresses')
)
LABEL_CHOICES=(
('P','primary'),
('S','secondary'),
('D','danger')
)
class Profile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE,related_name='profile')
prof_pic = models.ImageField(upload_to='images/',default='./img/avator.png')
bio = models.TextField(max_length=50,default='this is my bio')
name = models.CharField(blank=True,max_length=120)
contact =models.PositiveIntegerField(null=True,blank=True)
email = models.EmailField()
location = models.CharField(max_length=60, blank=True)
stripe_customer_id = models.CharField(max_length=50, blank=True, null=True)
one_click_purchasing = models.BooleanField(default=False)
def __str__(self):
return f'{self.user.username} Profile'
@receiver(post_save,sender=User)
def create_user_profile(sender,instance,created,**kwargs):
if created:
userprofile = Profile.objects.create(user=instance)
@receiver(post_save,sender=User)
def save_user_profile(sender,instance,created,**kwargs):
instance.profile.save()
def save_profile(self):
return self.save()
def delete_profile(self):
return self.delete()
@classmethod
def search_profile(cls,name):
return cls.objects.filter(user__username__icontains=name).all()
class Item(models.Model):
title = models.CharField(max_length=200)
price = models.FloatField()
discount_price = models.FloatField(null=True,blank=True,default="0")
category = models.CharField(choices=CATEGORY_CHOICES,max_length=2,default="SU")
label = models.CharField(choices=LABEL_CHOICES,max_length=1,default="P")
photo = models.ImageField(null=True,blank=True)
description = models.TextField(null=True,blank=True)
user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='posts')
created = models.DateTimeField(auto_now_add=True, null=True)
def get_all_comments(self):
return self.comments.all()
@classmethod
def search_term(cls,searchterm):
search = Item.objects.filter(Q(title__icontains=searchterm)|Q(description__icontains=searchterm)|Q(category__icontains=searchterm))
return search
def __str__(self):
return f"{self.title}"
class Comment(models.Model):
comment = models.TextField()
item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='comments')
user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='comments')
created = models.DateTimeField(auto_now_add=True, null=True)
class OrderItem(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
item = models.ForeignKey(Item,on_delete=models.CASCADE)
is_ordered = models.BooleanField(default=False)
quantity = models.IntegerField(default=1)
def __str__(self):
return f"{self.quantity} of {self.item.title}"
def get_total_price(self):
return self.quantity * self.item.price
def get_total_discount_price(self):
return self.quantity * self.item.discount_price
def get_amount_saved(self):
return self.get_total_price() - self.get_total_discount_price()
def get_final_price(self):
if self.item.discount_price:
return self.get_total_discount_price()
return self.get_total_price()
class Order(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
ref_code = models.CharField(max_length=30)
is_ordered = models.BooleanField(default=False)
items = models.ManyToManyField(OrderItem)
start_date = models.DateTimeField(auto_now_add=True)
ordered_date = models.DateTimeField()
billing_address = models.ForeignKey('BillingAddress',on_delete=models.SET_NULL,null=True,blank=True)
payment = models.ForeignKey('Payment',on_delete=models.SET_NULL,null=True,blank=True)
coupon = models.ForeignKey('Coupon',on_delete=models.SET_NULL,null=True,blank=True)
being_delivered = models.BooleanField(default=False)
received = models.BooleanField(default=False)
refund_requested = models.BooleanField(default=False)
refund_approved = models.BooleanField(default=False)
def __str__(self):
return f"{ self.user.username }"
def get_total(self):
total = 0
for order_item in self.items.all():
total += order_item.get_final_price()
if self.coupon:
total -= self.coupon.amount
return total
class BillingAddress(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
street_address = models.CharField(max_length=50)
apartment_address=models.CharField(max_length=50)
country = CountryField(multiple=False,default="Kenya")
zipcode = models.CharField(max_length=50)
def __str__(self):
return f"{self.user.username }"
class Payment(models.Model):
stripe_charge_id = models.CharField(max_length=50)
user = models.ForeignKey(User,on_delete=models.SET_NULL,blank=True,null=True)
amount= models.FloatField()
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{ self.user.username }"
class Coupon(models.Model):
code = models.CharField(max_length=15)
amount = models.FloatField(default=50)
def __str__(self):
return f"{self.code }"
class Refund(models.Model):
order = models.ForeignKey(Order,on_delete=models.CASCADE)
reason = models.TextField()
accepted = models.BooleanField(default=False)
email = models.EmailField()
def __str__(self):
return f"{ self.pk }"
|
[
"[email protected]"
] | |
c16d87aad5c12e73552775d7063b510229c7d2b4
|
781e2692049e87a4256320c76e82a19be257a05d
|
/all_data/exercism_data/python/word-count/c9dbb4f567ab4afa840dedb35209b154.py
|
3ac8cb50e479178794591a5bbba3d8776dab6ff1
|
[] |
no_license
|
itsolutionscorp/AutoStyle-Clustering
|
54bde86fe6dbad35b568b38cfcb14c5ffaab51b0
|
be0e2f635a7558f56c61bc0b36c6146b01d1e6e6
|
refs/heads/master
| 2020-12-11T07:27:19.291038 | 2016-03-16T03:18:00 | 2016-03-16T03:18:42 | 59,454,921 | 4 | 0 | null | 2016-05-23T05:40:56 | 2016-05-23T05:40:56 | null |
UTF-8
|
Python
| false | false | 220 |
py
|
"""
Solution for "Word Count" Exercise
"""
def word_count(input):
result = {}
words = input.replace('\n',' ').split(' ')
for word in words:
if word != '':
result[word] = result.get(word,0) + 1
return result
|
[
"[email protected]"
] | |
60fcc7583e7a4666ee84df1b89aa0de7c824794d
|
5c724d6e03e4194680c793718a4f72a58ca66bb1
|
/app/migrations/0015_auto_20180903_2010.py
|
75587dd9dfbf783469020f2e266a255f975a8bff
|
[] |
no_license
|
tigrezhito1/bat
|
26002de4540bb4eac2751a31171adc45687f4293
|
0ea6b9b85e130a201c21eb6cbf09bc21988d6443
|
refs/heads/master
| 2020-05-02T07:13:06.936015 | 2019-03-26T15:04:17 | 2019-03-26T15:04:17 | 177,812,144 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 604 |
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2018-09-03 20:10
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0014_auto_20180903_1946'),
]
operations = [
migrations.AlterField(
model_name='produccion',
name='fecha',
field=models.DateTimeField(default=datetime.datetime(2018, 9, 3, 20, 10, 30, 268737), editable=False, help_text='Fecha de recepci\xf3n de la llamada (No se puede modificar)'),
),
]
|
[
"[email protected]"
] | |
f4cb702bb909488b44205a7c3c85860429401cc4
|
0737b583899d7d5ddcbdda49731046036d65d998
|
/sven/settings.py
|
746ef6ac71a5df61f46113c3869cf2e519f9fb90
|
[] |
no_license
|
martolini/sven_admin
|
71b8b6e84e0eae3d7e971a62e3715efac708b160
|
610183b2d995b1d1f6b1946c13e9b4c9070ef26f
|
refs/heads/master
| 2021-01-25T04:58:00.067439 | 2014-02-25T22:04:25 | 2014-02-25T22:04:25 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 6,190 |
py
|
# Django settings for sven project.
import os
import socket
DEBUG = 'cauchy' not in socket.gethostname()
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', '[email protected]'),
)
MANAGERS = ADMINS
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
if DEBUG:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'dev.db', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
STATIC_ROOT = ''
MEDIA_ROOT = os.path.join(BASE_DIR, 'files/uploads')
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'svenquiz', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': 'sven',
'PASSWORD': 'svenadmin',
'HOST': 'localhost', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
STATIC_ROOT = '/opt/svenv/static'
MEDIA_ROOT = '/opt/svenv/uploads'
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ['*']
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_URL = '/uploads/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'ald-9%v)kc*#$@hip$kpr6&tv_1h*$snl)p67_lvpag+1+phq&'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'sven.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'sven.wsgi.application'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'sven.app',
'sven.app.quiz',
'south',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
|
[
"[email protected]"
] | |
9fdef289488f09abcc2b7641aa8a537ae0231dd7
|
e70d0bcc547d63b338ff51c253aa95d78ea99992
|
/xdl/test/python/unit_test/ps_ops/test_ps_pull_op.py
|
dfa1f106fecb5690866aa4d7d8629b0e15c3b2d8
|
[
"Apache-2.0"
] |
permissive
|
niumeng07/x-deeplearning
|
2513f7ba823521c40e0346284f5dd0aca5562e40
|
6d3bc3ad4996ab8938c56d8a834af07a04dc2f67
|
refs/heads/master
| 2020-04-12T23:06:24.447833 | 2019-07-06T16:06:16 | 2019-07-06T16:06:16 | 162,808,758 | 2 | 0 |
Apache-2.0
| 2018-12-22T12:18:01 | 2018-12-22T12:17:59 | null |
UTF-8
|
Python
| false | false | 1,377 |
py
|
# Copyright (C) 2016-2018 Alibaba Group Holding Limited
#
# 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 xdl
import unittest
import numpy as np
from xdl.python.lib.datatype import *
from xdl.python.lib.graph import execute
class TestPsPullOp(unittest.TestCase):
def test_all(self):
var = xdl.Variable(name="w", dtype=DataType.int32, shape=[4], initializer=xdl.Ones())
execute(xdl.variable_registers())
execute(xdl.global_initializers())
op = xdl.ps_pull_op(var_name="w", var_type="index", dtype=DataType.int32)
ret = execute(op)
self.assertTrue((ret == np.array([1,1,1,1])).all())
def suite():
return unittest.TestLoader().loadTestsFromTestCase(TestPsPullOp)
if __name__ == '__main__':
unittest.TextTestRunner().run(suite())
|
[
"[email protected]"
] | |
95b462c1589ad5fcc2afbb3b460ed427d4606ddf
|
ef8d6ba2afe24cd981eeb92624e838b6acc98166
|
/src/ckanext-delineate/setup.py
|
4b2815902ac1b31eff768239e15632773f5b8dd6
|
[
"BSD-3-Clause"
] |
permissive
|
CI-WATER/portal
|
cd68cd8f514d10092faea3e78d4421819c9714c3
|
c61660c8389c7af82517cbd0154bc83f9737c4d1
|
refs/heads/master
| 2016-09-05T10:40:10.721184 | 2014-07-01T17:43:06 | 2014-07-01T17:43:06 | 20,502,671 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 751 |
py
|
from setuptools import setup, find_packages
version = '0.1'
setup(
name='ckanext-delineate',
version=version,
description="Watershed delineation extension",
long_description="""\
""",
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='',
author='Pabitra Dash',
author_email='[email protected]',
url='',
license='',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
namespace_packages=['ckanext', 'ckanext.delineate'],
include_package_data=True,
zip_safe=False,
install_requires=[
# -*- Extra requirements: -*-
],
entry_points=\
"""
[ckan.plugins]
# Add plugins here, eg
watershed_delineate=ckanext.delineate.plugin:DelineateWatershedPlugins
""",
)
|
[
"[email protected]"
] | |
29ade0802ba7f753dde50457d3d040b9d9b4e45a
|
a16feb303b7599afac19a89945fc2a9603ae2477
|
/Simple_Python/standard/traceback/traceback_6.py
|
98c71ab419e8207fcac4ff823ee242f3b6713f45
|
[] |
no_license
|
yafeile/Simple_Study
|
d75874745ce388b3d0f9acfa9ebc5606a5745d78
|
c3c554f14b378b487c632e11f22e5e3118be940c
|
refs/heads/master
| 2021-01-10T22:08:34.636123 | 2015-06-10T11:58:59 | 2015-06-10T11:58:59 | 24,746,770 | 0 | 2 | null | null | null | null |
UTF-8
|
Python
| false | false | 263 |
py
|
#! /usr/bin/env/python
# -*- coding:utf-8 -*-
import traceback
import sys
from traceback_1 import call_function
def f():
traceback.print_stack(file=sys.stdout)
print 'Calling f() directly:'
f()
print
print 'Calling f() from 3 levels deep:'
call_function(f)
|
[
"[email protected]"
] | |
22df3a45ebed1aaa000d917da4cf9f6d77c8ad8e
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p04001/s037589622.py
|
245a5174bd7db200bf673123ca5d544e43c7f7dc
|
[] |
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 | 332 |
py
|
#!/usr/bin python3
# -*- coding: utf-8 -*-
def main():
S = input()
l = len(S)-1
ret = 0
for i in range(2**l):
fs = S[0]
for j in range(l):
if (i>>j & 1) == 1:
fs += '+'
fs += S[j+1]
ret += eval(fs)
print(ret)
if __name__ == '__main__':
main()
|
[
"[email protected]"
] | |
0150ee4b951d7aa98d33671a60f4da5d924e1da8
|
2de33ba731066a63352080dd19da1e4582bb00c4
|
/collective.project/collective/project/browser/create_iteration.py
|
d3c03e2dcb7ff08becb20002dd3249c618cfcb4f
|
[] |
no_license
|
adam139/plonesrc
|
58f48e7cdfc8fbed7398011c40649f095df10066
|
cbf20045d31d13cf09d0a0b2a4fb78b96c464d20
|
refs/heads/master
| 2021-01-10T21:36:44.014240 | 2014-09-09T04:28:04 | 2014-09-09T04:28:04 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 4,139 |
py
|
from zope import interface, schema
from z3c.form import form, field, button
from plone.app.z3cform.layout import wrap_form
from collective.project import projectMessageFactory as _
from collective.project.bbb import getSite
from zope.schema import vocabulary
from zope.interface import directlyProvides
from zope.schema.interfaces import IVocabularyFactory
import datetime
import calendar
projectsField = schema.Choice(
title=u'Projects',
description=u'Projects field.',
vocabulary='projects_vocab')
def breadcrumbs(context, project):
results = []
path = list(project.getObject().getPhysicalPath())[2:]
for i in range(len(path)):
results.append(context.restrictedTraverse('/'.join(path)).Title())
path.pop()
return ' > '.join(results)
class CreateIterationSchema(interface.Interface):
iteration = schema.TextLine(
title=_(u"Iteration"),
default=_(unicode(datetime.datetime.today().strftime('%B %Y'))))
projects = schema.Set(
title=u'Project(s)',
value_type=projectsField,
)
class CreateIterationForm(form.Form):
fields = field.Fields(CreateIterationSchema)
ignoreContext = True # don't use context to get widget data
label = _(u"Iteration tool")
description = _(u"Create iteration for selected projects")
def deactivate_iteration(self, action, data):
wftool = self.context.portal_workflow
iterations = find_iterations()
for iteration in iterations:
if data['iteration']:
data_iter = data['iteration']
new_iter = data_iter.lower().replace(' ', '-')
iter = iteration.getObject()
if not unicode(iter.id) == new_iter: # Don't deactive the current iter
if wftool.getInfoFor(iter, 'review_state') == 'active':
wftool.doActionFor(iter,'deactivate')
def create_iteration(self, action, data):
if data['iteration']:
data_iter = data['iteration']
new_iter = data_iter.lower().replace(' ', '-')
projects = find_projects()
for project in projects:
proj = project.getObject()
if proj in data['projects']:
try:
proj.invokeFactory('iteration', new_iter)
except:
print "Cannot create iteration %s for project %s." % (new_iter, proj.absolute_url())
try:
iter_new = proj[new_iter]
iter_new.setTitle(data_iter)
iter_new.start = startDate()
iter_new.stop = stopDate()
iter_new.reindexObject()
except:
print "Cannot create iteration %s for project %s." % (new_iter, proj.absolute_url())
@button.buttonAndHandler(u'Create')
def handleApply(self, action):
data, errors = self.extractData()
if errors:
self.status = form.EditForm.formErrorsMessage
else:
self.create_iteration(action, data)
self.deactivate_iteration(action, data)
def projectsDict(context):
projects = {}
for p in find_projects():
obj = p.getObject()
bc = breadcrumbs(context,p)
projects[bc] = obj
return projects
def projectsVocab(context):
projects = projectsDict(context)
items = sorted(projects.items())
return vocabulary.SimpleVocabulary.fromItems(items)
def find_iterations():
site = getSite()
return site.portal_catalog(portal_type='iteration')
def find_projects():
site = getSite()
return site.portal_catalog(portal_type='project')
def startDate():
# start on first day of current month
now = datetime.datetime.now()
first_day = datetime.datetime(now.year, now.month, 1)
return first_day
def stopDate():
# stop in one month
now = datetime.datetime.now()
last_day = calendar.monthrange(now.year, now.month)[1]
return datetime.datetime(now.year, now.month, last_day)
directlyProvides(projectsVocab, IVocabularyFactory)
CreateIteration = wrap_form(CreateIterationForm)
|
[
"[email protected]"
] | |
c6b2508756ca483742fc681caa459b0b1fe7fff9
|
9743d5fd24822f79c156ad112229e25adb9ed6f6
|
/xai/brain/wordbase/verbs/_wounder.py
|
b0d6cd04f474aad1a04a22fbffe4505de907b214
|
[
"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 | 233 |
py
|
from xai.brain.wordbase.verbs._wound import _WOUND
#calss header
class _WOUNDER(_WOUND, ):
def __init__(self,):
_WOUND.__init__(self)
self.name = "WOUNDER"
self.specie = 'verbs'
self.basic = "wound"
self.jsondata = {}
|
[
"[email protected]"
] | |
73b384d0b1fb7908b2521c4f150f93c076b807c7
|
10d17864a685c025bb77959545f74b797f1d6077
|
/capitulo 07/07.22.py
|
d7274f669aa67ce98579dc96a66e3b781eec34c2
|
[] |
no_license
|
jcicerof/IntroducaoPython
|
02178d2dfcaa014587edbd3090c517089ccef7c2
|
02e619c7c17e74acdc3268fbfae9ab624a3601dd
|
refs/heads/master
| 2020-04-24T18:12:21.422079 | 2019-02-23T05:14:43 | 2019-02-23T05:14:43 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 623 |
py
|
##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2019
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Terceira edição - Janeiro/2019 - ISBN 978-85-7522-718-3
# Site: http://python.nilo.pro.br/
#
# Arquivo: listagem3\capítulo 07\07.22.py
# Descrição:
##############################################################################
"771".isdigit()
"10.4".isdigit()
"+10".isdigit()
"-5".isdigit()
|
[
"[email protected]"
] | |
a15ba967a5a20d5c51a3fe4bd4b1b7ee046e37de
|
350db570521d3fc43f07df645addb9d6e648c17e
|
/0779_K-th_Symbol_in_Grammar/solution_test.py
|
954e62fd402ddafba1bf568523536c189f2aedf3
|
[] |
no_license
|
benjaminhuanghuang/ben-leetcode
|
2efcc9185459a1dd881c6e2ded96c42c5715560a
|
a2cd0dc5e098080df87c4fb57d16877d21ca47a3
|
refs/heads/master
| 2022-12-10T02:30:06.744566 | 2022-11-27T04:06:52 | 2022-11-27T04:06:52 | 236,252,145 | 1 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 378 |
py
|
'''
779. K-th Symbol in Grammar
Level: Medium
https://leetcode.com/problems/k-th-symbol-in-grammar
'''
import unittest
class TestSum(unittest.TestCase):
def test_sum(self):
self.assertEqual(sum([1, 2, 3]), 6, "Should be 6")
def test_sum_tuple(self):
self.assertEqual(sum((1, 2, 2)), 6, "Should be 6")
if __name__ == '__main__':
unittest.main()
|
[
"[email protected]"
] | |
64899c99b053884b463b2aca741431e307f7b480
|
1919fc2555dbcb6b865fdef0cc44c56c6c47e2f0
|
/chapter_7/demo_7_2.py
|
8b2b373f88eeeae54cc30d598f1dd6d869f9e330
|
[] |
no_license
|
ender8848/the_fluent_python
|
10f8dd98fcf206b04ea6d34f47ad5e35f896a3ac
|
058d59f6a11da34e23deb228e24a160d907f7643
|
refs/heads/master
| 2022-12-19T07:51:51.908127 | 2019-01-17T09:53:33 | 2019-01-17T09:53:33 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,781 |
py
|
'''
装饰器的一个关键特性是,它们在被装饰的函数定义之后立即运行。
这通常是在导入时(即 Python 加载模块时) ,
如示例 7-2 中的 demo_7_2.py 模块所示。
'''
# registry 保存被 @register 装饰的函数引用
registry = []
# register 的参数是一个函数
def register(func):
print('running register(%s)' % func)
registry.append(func)
return func
@register
def f1():
print('running f1()')
@register
def f2():
print('running f2()')
def f3():
print('running f3()')
def main():
print('running main()')
print('registry ->', registry)
f1()
f2()
f3()
if __name__ == '__main__':
main()
'''
running register(<function f1 at 0x1081ad268>)
running register(<function f2 at 0x1095c99d8>)
running main()
registry -> [<function f1 at 0x1081ad268>, <function f2 at 0x1095c99d8>]
running f1()
running f2()
running f3()
'''
'''
注意,register 在模块中其他函数之前运行(两次) 。
调用 register 时,传给它的参数是被装饰的函数,例如 <function f1 at 0x100631bf8>。
加载模块后,registry 中有两个被装饰函数的引用:f1 和 f2。
这两个函数,以及 f3,只在 main 明确调用它们时才执行。
如果导入 demo_7_2.py 模块(不作为脚本运行) ,
输出如下:
>>> import registration
running register(<function f1 at 0x10063b1e0>)
running register(<function f2 at 0x10063b268>)
此时查看 registry 的值,得到的输出如下:
>>> registration.registry
[<function f1 at 0x10063b1e0>, <function f2 at 0x10063b268>]
示例 7-2 主要想强调,函数装饰器在导入模块时立即执行,而被装饰的函数只在明确调用时运行。
这突出了 Python 程序员所说的导入时和运行时之间的区别
'''
|
[
"[email protected]"
] | |
de9f1199dc5aaa7e1cc8da79229dc61e059a54e2
|
25e2d5bb03c5b2534880ab41fb7de82d815f83da
|
/menpo/landmark/labels/__init__.py
|
36cab907dbfd7bbb95e2c5c10a432ae9e3e2fea5
|
[
"BSD-3-Clause"
] |
permissive
|
justusschock/menpo
|
f4c4a15b62eab17f06387c5772af2699d52a9419
|
d915bec26de64a5711b96be75cd145661a32290e
|
refs/heads/master
| 2020-04-06T18:08:26.397844 | 2019-03-09T20:54:07 | 2019-03-09T20:54:07 | 157,687,031 | 0 | 0 |
NOASSERTION
| 2018-11-15T09:39:03 | 2018-11-15T09:39:03 | null |
UTF-8
|
Python
| false | false | 612 |
py
|
from .base import labeller
from .human import *
from .car import (
car_streetscene_20_to_car_streetscene_view_0_8,
car_streetscene_20_to_car_streetscene_view_1_14,
car_streetscene_20_to_car_streetscene_view_2_10,
car_streetscene_20_to_car_streetscene_view_3_14,
car_streetscene_20_to_car_streetscene_view_4_14,
car_streetscene_20_to_car_streetscene_view_5_10,
car_streetscene_20_to_car_streetscene_view_6_14,
car_streetscene_20_to_car_streetscene_view_7_8)
from .bounding_box import (bounding_box_to_bounding_box,
bounding_box_mirrored_to_bounding_box)
|
[
"[email protected]"
] | |
27a2982791e485a8d4a48f5bf1b30eb87d869ecc
|
d45b08745ab3f1e951485fa6b9f905be65f71da4
|
/programmers/kakao20_경주로건설.py
|
9bc2872919783233501f1b27d53f832c1fc7caf3
|
[] |
no_license
|
HYUNMIN-HWANG/Algorithm_practice
|
d0a82e73a735e22a70c98fd4882b66929061bd6c
|
96b70fbea42ca11881546531fa6a9486e9a5289f
|
refs/heads/main
| 2023-04-25T05:40:24.126757 | 2021-05-08T13:42:56 | 2021-05-08T13:42:56 | 324,109,498 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,983 |
py
|
from collections import deque
def solution(board):
n = len(board)
visited = [[1000000 for _ in range(n)] for _ in range(n)]
ds = [[-1, 0], [1, 0], [0, 1], [0, -1]]
q = deque()
q.append((0, 0, 0, -1))
visited[0][0] = 0
while q:
y, x, c, t = q.popleft()
for i in range(4):
ay, ax = y + ds[i][0], x + ds[i][1]
if 0 <= ay < n and 0 <= ax < n and not board[ay][ax]:
if t == i or t == -1:
if visited[ay][ax] >= c + 100:
visited[ay][ax] = c + 100
q.append((ay, ax, c + 100, i))
elif t != i:
if visited[ay][ax] >= c + 600:
visited[ay][ax] = c + 600
q.append((ay, ax, c + 600, i))
answer = visited[n - 1][n - 1]
return answer
# 위에 꺼 참고한 나의 풀이
from collections import deque
def solution(board):
queue = deque()
queue.append((0,0,0,-1)) # x, y, cost, 방향
n = len(board[0])
visited = [[1000000] * n for _ in range(n)]
visited[0][0] = 0
dx = [-1, 1, 0, 0]
dy = [0, 0, 1, -1]
while queue :
x, y, c, t = queue.popleft()
for i in range(4) :
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < n and 0 <= ny < n and not board[nx][ny] :
if t == i or t == -1 : # 방향이 같다. 직선거리
if visited[nx][ny] >= c + 100 : # 최소 가격으로 갱신하기 위함
visited[nx][ny] = c + 100
queue.append((nx, ny, c + 100, i))
elif t != i : # 방향이 달라짐. 곡선거리
if visited[nx][ny] >= c + 600 :
visited[nx][ny] = c + 600
queue.append((nx, ny, c + 600, i))
answer = visited[n-1][n-1]
return answer
|
[
"[email protected]"
] | |
81b071b194eaf7cf41f099b4b2ae69ce0fdb01f6
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p03168/s984146914.py
|
d29e8d5cf735e05031e772be32479e5b3e032425
|
[] |
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 | 271 |
py
|
n = int(input())
ns = list(map(float, input().split()))
dp = [[0 for j in range(n+1)] for i in range(n+1)]
dp[0][0] = 1
for i in range(1,n+1):
for j in range(0, i + 1):
dp[i][j] = dp[i-1][j] * (1-ns[i-1]) + dp[i-1][j-1] * ns[i-1]
print(sum(dp[-1][(n+1)//2:]))
|
[
"[email protected]"
] | |
37cb1a55bf2943e3cb7f46d64c52de8169b903f0
|
11459f6d05c7091537570a63bb2654b3d3a5440c
|
/mlprodict/plotting/plotting_validate_graph.py
|
f30922b8ca4cda3cd369f447e8fb26caa3a256dd
|
[
"MIT"
] |
permissive
|
xhochy/mlprodict
|
663e6ac21ae913d5dff59cfab938fc62f59d1c79
|
22ab05af3ff4a67f4390af1c44e349efa454f0d5
|
refs/heads/master
| 2023-08-11T00:53:24.133020 | 2021-09-24T15:52:46 | 2021-09-24T15:52:46 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 7,540 |
py
|
"""
@file
@brief Functions to help visualizing performances.
"""
import numpy
import pandas
def _model_name(name):
"""
Extracts the main component of a model, removes
suffixes such ``Classifier``, ``Regressor``, ``CV``.
@param name string
@return shorter string
"""
if name.startswith("Select"):
return "Select"
if name.startswith("Nu"):
return "Nu"
modif = 1
while modif > 0:
modif = 0
for suf in ['Classifier', 'Regressor', 'CV', 'IC',
'Transformer']:
if name.endswith(suf):
name = name[:-len(suf)]
modif += 1
return name
def plot_validate_benchmark(df):
"""
Plots a graph which summarizes the performances of a benchmark
validating a runtime for :epkg:`ONNX`.
@param df output of function @see fn summary_report
@return fig, ax
.. plot::
from logging import getLogger
from pandas import DataFrame
import matplotlib.pyplot as plt
from mlprodict.onnxrt.validate import enumerate_validated_operator_opsets, summary_report
from mlprodict.tools.plotting import plot_validate_benchmark
logger = getLogger('skl2onnx')
logger.disabled = True
rows = list(enumerate_validated_operator_opsets(
verbose=0, models={"LinearRegression"}, opset_min=11,
runtime=['python', 'onnxruntime1'], debug=False,
benchmark=True, n_features=[None, 10]))
df = DataFrame(rows)
piv = summary_report(df)
fig, ax = plot_validate_benchmark(piv)
plt.show()
"""
import matplotlib.pyplot as plt
if 'n_features' not in df.columns:
df["n_features"] = numpy.nan # pragma: no cover
if 'runtime' not in df.columns:
df['runtime'] = '?' # pragma: no cover
fmt = "{} [{}-{}|{}] D{}"
df["label"] = df.apply(
lambda row: fmt.format(
row["name"], row["problem"], row["scenario"],
row['optim'], row["n_features"]).replace("-default|", "-**]"), axis=1)
df = df.sort_values(["name", "problem", "scenario", "optim",
"n_features", "runtime"],
ascending=False).reset_index(drop=True).copy()
indices = ['label', 'runtime']
values = [c for c in df.columns
if 'N=' in c and '-min' not in c and '-max' not in c]
try:
df = df[indices + values]
except KeyError as e: # pragma: no cover
raise RuntimeError(
"Unable to find the following columns {}\nin {}".format(
indices + values, df.columns)) from e
if 'RT/SKL-N=1' not in df.columns:
raise RuntimeError( # pragma: no cover
"Column 'RT/SKL-N=1' is missing, benchmark was probably not run.")
na = df["RT/SKL-N=1"].isnull()
dfp = df[~na]
runtimes = list(sorted(set(dfp['runtime'])))
final = None
for rt in runtimes:
sub = dfp[dfp.runtime == rt].drop('runtime', axis=1).copy()
col = list(sub.columns)
for i in range(1, len(col)):
col[i] += "__" + rt
sub.columns = col
if final is None:
final = sub
else:
final = final.merge(sub, on='label', how='outer')
# let's add average and median
ncol = (final.shape[1] - 1) // len(runtimes)
if len(runtimes) + 1 > final.shape[0]:
dfp_legend = final.iloc[:len(runtimes) + 1, :].copy()
while dfp_legend.shape[0] < len(runtimes) + 1:
dfp_legend = pandas.concat([dfp_legend, dfp_legend[:1]])
else:
dfp_legend = final.iloc[:len(runtimes) + 1, :].copy()
rleg = dfp_legend.copy()
dfp_legend.iloc[:, 1:] = numpy.nan
rleg.iloc[:, 1:] = numpy.nan
for r, runt in enumerate(runtimes):
sli = slice(1 + ncol * r, 1 + ncol * r + ncol)
cm = final.iloc[:, sli].mean().values
dfp_legend.iloc[r + 1, sli] = cm
rleg.iloc[r, sli] = final.iloc[:, sli].median()
dfp_legend.iloc[r + 1, 0] = "avg_" + runt
rleg.iloc[r, 0] = "med_" + runt
dfp_legend.iloc[0, 0] = "------"
rleg.iloc[-1, 0] = "------"
# sort
final = final.sort_values('label', ascending=False).copy()
# add global statistics
final = pandas.concat([rleg, final, dfp_legend]).reset_index(drop=True)
# graph beginning
total = final.shape[0] * 0.45
fig, ax = plt.subplots(1, len(values), figsize=(14, total),
sharex=False, sharey=True)
x = numpy.arange(final.shape[0])
subh = 1.0 / len(runtimes)
height = total / final.shape[0] * (subh + 0.1)
decrt = {rt: height * i for i, rt in enumerate(runtimes)}
colors = {rt: c for rt, c in zip(
runtimes, ['blue', 'orange', 'cyan', 'yellow'])}
# draw lines between models
vals = final.iloc[:, 1:].values.ravel()
xlim = [min(0.5, min(vals)), max(2, max(vals))]
while i < final.shape[0] - 1:
i += 1
label = final.iloc[i, 0]
if '[' not in label:
continue
prev = final.iloc[i - 1, 0]
if '[' not in label:
continue # pragma: no cover
label = label.split()[0]
prev = prev.split()[0]
if _model_name(label) == _model_name(prev):
continue
blank = final.iloc[:1, :].copy()
blank.iloc[0, 0] = '------'
blank.iloc[0, 1:] = xlim[0]
final = pandas.concat([final[:i], blank, final[i:]])
i += 1
final = final.reset_index(drop=True).copy()
x = numpy.arange(final.shape[0])
done = set()
for c in final.columns[1:]:
place, runtime = c.split('__')
if hasattr(ax, 'shape'):
index = values.index(place)
if (index, runtime) in done:
raise RuntimeError( # pragma: no cover
"Issue with column '{}'\nlabels={}\nruntimes={}\ncolumns="
"{}\nvalues={}\n{}".format(
c, list(final.label), runtimes, final.columns, values, final))
axi = ax[index]
done.add((index, runtime))
else:
if (0, runtime) in done: # pragma: no cover
raise RuntimeError(
"Issue with column '{}'\nlabels={}\nruntimes={}\ncolumns="
"{}\nvalues={}\n{}".format(
c, final.label, runtimes, final.columns, values, final))
done.add((0, runtime)) # pragma: no cover
axi = ax # pragma: no cover
if c in final.columns:
yl = final.loc[:, c]
xl = x + decrt[runtime] / 2
axi.barh(xl, yl, label=runtime, height=height,
color=colors[runtime])
axi.set_title(place)
def _plot_axis(axi, x, xlim):
axi.plot([1, 1], [0, max(x)], 'g-')
axi.plot([2, 2], [0, max(x)], 'r--')
axi.set_xlim(xlim)
axi.set_xscale('log')
axi.set_ylim([min(x) - 2, max(x) + 1])
def _plot_final(axi, x, final):
axi.set_yticks(x)
axi.set_yticklabels(final['label'])
if hasattr(ax, 'shape'):
for i in range(len(ax)): # pylint: disable=C0200
_plot_axis(ax[i], x, xlim)
ax[min(ax.shape[0] - 1, 2)].legend()
_plot_final(ax[0], x, final)
else: # pragma: no cover
_plot_axis(ax, x, xlim)
_plot_final(ax, x, final)
ax.legend()
fig.subplots_adjust(left=0.25)
return fig, ax
|
[
"[email protected]"
] | |
ab25cc9d4cab4c0e131e57540685f03f68c4b4f0
|
2e682fd72e3feaa70e3f7bf2a3b83c50d783ec02
|
/PyTorch/built-in/nlp/Scaling-nmt_for_Pytorch/fairseq/criterions/label_smoothed_cross_entropy_with_ctc.py
|
f2e8cdf3bfe0caea99125c6f9607dff9495891cf
|
[
"GPL-1.0-or-later",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
Ascend/ModelZoo-PyTorch
|
4c89414b9e2582cef9926d4670108a090c839d2d
|
92acc188d3a0f634de58463b6676e70df83ef808
|
refs/heads/master
| 2023-07-19T12:40:00.512853 | 2023-07-17T02:48:18 | 2023-07-17T02:48:18 | 483,502,469 | 23 | 6 |
Apache-2.0
| 2022-10-15T09:29:12 | 2022-04-20T04:11:18 |
Python
|
UTF-8
|
Python
| false | false | 3,403 |
py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
from dataclasses import dataclass, field
import torch
import torch.nn.functional as F
from fairseq import utils
from fairseq.logging import metrics
from fairseq.criterions import register_criterion
from fairseq.criterions.label_smoothed_cross_entropy import (
LabelSmoothedCrossEntropyCriterion,
LabelSmoothedCrossEntropyCriterionConfig,
)
from fairseq.data.data_utils import lengths_to_mask
@dataclass
class LabelSmoothedCrossEntropyWithCtcCriterionConfig(
LabelSmoothedCrossEntropyCriterionConfig
):
ctc_weight: float = field(default=1.0, metadata={"help": "weight for CTC loss"})
@register_criterion(
"label_smoothed_cross_entropy_with_ctc",
dataclass=LabelSmoothedCrossEntropyWithCtcCriterionConfig,
)
class LabelSmoothedCrossEntropyWithCtcCriterion(LabelSmoothedCrossEntropyCriterion):
def __init__(
self,
task,
sentence_avg,
label_smoothing,
ignore_prefix_size,
report_accuracy,
ctc_weight,
):
super().__init__(
task, sentence_avg, label_smoothing, ignore_prefix_size, report_accuracy
)
self.ctc_weight = ctc_weight
def forward(self, model, sample, reduce=True):
net_output = model(**sample["net_input"])
loss, nll_loss = self.compute_loss(model, net_output, sample, reduce=reduce)
ctc_loss = torch.tensor(0.0).type_as(loss)
if self.ctc_weight > 0.0:
ctc_lprobs, ctc_lens = model.get_ctc_output(net_output, sample)
ctc_tgt, ctc_tgt_lens = model.get_ctc_target(sample)
ctc_tgt_mask = lengths_to_mask(ctc_tgt_lens)
ctc_tgt_flat = ctc_tgt.masked_select(ctc_tgt_mask)
reduction = "sum" if reduce else "none"
ctc_loss = (
F.ctc_loss(
ctc_lprobs,
ctc_tgt_flat,
ctc_lens,
ctc_tgt_lens,
reduction=reduction,
zero_infinity=True,
)
* self.ctc_weight
)
loss += ctc_loss
sample_size = (
sample["target"].size(0) if self.sentence_avg else sample["ntokens"]
)
logging_output = {
"loss": utils.item(loss.data),
"nll_loss": utils.item(nll_loss.data),
"ctc_loss": utils.item(ctc_loss.data),
"ntokens": sample["ntokens"],
"nsentences": sample["target"].size(0),
"sample_size": sample_size,
}
if self.report_accuracy:
n_correct, total = self.compute_accuracy(model, net_output, sample)
logging_output["n_correct"] = utils.item(n_correct.data)
logging_output["total"] = utils.item(total.data)
return loss, sample_size, logging_output
@classmethod
def reduce_metrics(cls, logging_outputs) -> None:
super().reduce_metrics(logging_outputs)
loss_sum = sum(log.get("ctc_loss", 0) for log in logging_outputs)
sample_size = sum(log.get("sample_size", 0) for log in logging_outputs)
metrics.log_scalar(
"ctc_loss", loss_sum / sample_size / math.log(2), sample_size, round=3
)
|
[
"[email protected]"
] | |
d1f546681794e6a313737c2b6c0ecc037fcc1921
|
a79c9afff9afea0c64ce8efac5683bde4ef7eeb8
|
/apps/app_two/urls.py
|
46e912dd7bc1de957131647bfdebb35d948d591d
|
[] |
no_license
|
kswelch53/login_registration
|
82e8a865125e903efbc624a3b7e3c5a4b6f98a60
|
364cfae780fe9f7e39c11dbe9e53e684d0798f5d
|
refs/heads/master
| 2021-05-12T08:48:04.707930 | 2018-01-13T00:11:50 | 2018-01-13T00:11:50 | 117,300,189 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 165 |
py
|
from django.conf.urls import url, include
from . import views
urlpatterns = [
# root route to index method in app_two
url(r'^$', views.index, name='index'),
]
|
[
"[email protected]"
] | |
1367392cb579fabd31cd0a289627c57077a7bda2
|
a53998e56ee06a96d59d97b2601fd6ec1e4124d7
|
/基础课/jichu/day19/multiple_inherit.py
|
97a196a49966ef3c0d0f854d88f992a637e776cf
|
[] |
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 | 308 |
py
|
class Car:
def run(self,speed):
print('汽车以',speed,'公里/小时的速度行驶')
class Plane:
def fly(self,height):
print('飞机以海拔',height,'米的高度飞行')
class PlaneCar(Car,Plane):
'''PlaneCar为飞行汽车类'''
p1 = PlaneCar()
p1.fly(10000)
p1.run(300)
|
[
"[email protected]"
] | |
e7e90eb396092cbfdd8804bdc98e246f49e58d27
|
f2e70de60adb32014fc718647e00e221687c4055
|
/openacademy/models/models.py
|
18977c7d29a89790deb59ee8d4506deae8805181
|
[] |
no_license
|
fawad4bros/Odoo13_employe_info
|
6a28f929cda1a3cb2c1ba1b665ba9565df3d2e37
|
40dd51c011726f49b331f29ffc2f7445877e5624
|
refs/heads/master
| 2023-04-05T10:01:42.591943 | 2021-04-04T06:58:47 | 2021-04-04T06:58:47 | 352,701,402 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 2,569 |
py
|
# -*- coding: utf-8 -*-
from odoo import models, fields, api, exceptions
class Course(models.Model):
_name = 'openacademy.course'
_description = 'OpenAcademy Courses'
name = fields.Char(string="Title", required=True, help="Name of the Course")
description = fields.Text()
responsible_id = fields.Many2one('res.users', ondelete='set null', string="Responsible", index=True)
session_ids = fields.One2many('openacademy.session','course_id',string="Sessions")
_sql_constraints = [
('name_description_check',
'CHECK(name != description)',
"The title of the course should not be the description"),
('name_unique',
'UNIQUE(name)',
"The course title must be unique"),
]
class Session(models.Model):
_name = 'openacademy.session'
_description = "OpenAcademy Sessions"
name = fields.Char(required=True)
start_date = fields.Date(default=fields.Date.today)
duration = fields.Float(digits=(6, 2), help="Duration in days")
seats = fields.Integer(string="Number of seats")
active = fields.Boolean(default=True)
instructor_id = fields.Many2one('res.partner', string="Instructor")
course_id = fields.Many2one('openacademy.course', ondelete='cascade', string="Course", required=True)
attendee_ids = fields.Many2many('res.partner',string="Attendees")
taken_seats = fields.Float(string="Taken seats", compute='_taken_seats')
@api.depends('seats', 'attendee_ids')
def _taken_seats(self):
for r in self:
if not r.seats:
r.taken_seats= 0.0
else:
r.taken_seats = 100.0 * len(r.attendee_ids) / r.seats
@api.onchange('seats', 'attendee_ids')
def _verify_valid_seats(self):
if self.seats < 0:
return {
'warning': {
'title': "Incorrect 'seats' value",
'message': "The number of available seats may not be negative",
},
}
if self.seats < len(self.attendee_ids):
return {
'warning': {
'title': "Too many attendees",
'message': "Increase seats or remove excess attendees",
},
}
@api.constrains('instructor_id','attendee_ids')
def _check_instructor_not_in_attendees(self):
for r in self:
if r.instructor_id and r.instructor_id in r.attendee_ids:
raise exceptions.ValidationError("A session's instructor can't be an attendee")
|
[
"[email protected]"
] | |
b5c67701e84dfa41e36333c8a985bf9e72b01b6a
|
5ad6b1b7fead932860d7a1f5d1281c339ca4d487
|
/papermerge/contrib/admin/migrations/0001_initial.py
|
d389247d6f2852eb8cd071971030e581fc0c895c
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"GPL-3.0-only"
] |
permissive
|
zhiliangpersonal/papermerge
|
da51fc7c6674a53e1c007e2eb70e5cc05de5da9e
|
56c10c889e1db4760a3c47f2374a63ec12fcec3b
|
refs/heads/master
| 2022-12-18T15:20:42.747194 | 2020-09-28T05:09:32 | 2020-09-28T05:09:32 | 299,205,072 | 1 | 0 |
Apache-2.0
| 2020-09-28T06:04:35 | 2020-09-28T06:04:34 | null |
UTF-8
|
Python
| false | false | 1,256 |
py
|
# Generated by Django 3.0.8 on 2020-08-28 11:48
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='LogEntry',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('message', models.TextField()),
('level', models.PositiveIntegerField(choices=[(10, 'Debug'), (20, 'Info'), (30, 'Warning'), (40, 'Error'), (50, 'Critical')], default=20)),
('action_time', models.DateTimeField(default=django.utils.timezone.now, editable=False, verbose_name='action time')),
('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'log entry',
'verbose_name_plural': 'log entries',
'ordering': ('-action_time',),
},
),
]
|
[
"[email protected]"
] | |
34757da4411d0823effcccd1a88b96cea9eb401a
|
1ef536d93c6616f9793e57a9ebc6b44248d50202
|
/Unit of Measure/models/res_partner.py
|
6d1e384ef6259b088b57ea48681fdce6824c20e1
|
[] |
no_license
|
mohamed4185/Express
|
157f21f8eba2b76042f4dbe09e4071e4411342ac
|
604aa39a68bfb41165549d605d40a27b9251d742
|
refs/heads/master
| 2022-04-12T17:04:05.407820 | 2020-03-09T14:02:17 | 2020-03-09T14:02:17 | 246,014,712 | 1 | 3 | null | null | null | null |
UTF-8
|
Python
| false | false | 461 |
py
|
# -*- coding: utf-8 -*-
from odoo import api, fields ,models
from odoo.exceptions import ValidationError
import logging
_logger = logging.getLogger(__name__)
class ResPartner(models.Model):
_inherit="uom.category"
measure_type = fields.Selection([
('unit', 'Units'),
('weight', 'Weight'),
('time', 'Time'),
('length', 'Length'),
('volume', 'Volume'),
], string="نوع وحدة القياس")
|
[
"[email protected]"
] | |
c38a872e6e6ae5b1d7edc0e1731ec393f49a556d
|
a0241ddd6feb1236740c4b57f86b4e2b9c812ffe
|
/userdata/models/beirat.py
|
ee4cada6ca3852e198c2996ce9b2dd941e739f94
|
[] |
no_license
|
patta42/website
|
0a08d4b11c49020acefaf8f8cca30982ca2afa50
|
72d2e136272e0ed23f74080697d16eb9bc692ac3
|
refs/heads/master
| 2021-06-10T16:30:51.292679 | 2021-04-24T06:27:02 | 2021-04-24T06:27:02 | 151,085,343 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,722 |
py
|
from django.db import models
from django.utils.translation import gettext as _
from website.models import TranslatedField
from userdata.models import StaffUser
class BeiratGroups(models.Model):
title_de = models.CharField(
max_length = 128,
verbose_name = 'Gruppe innerhalb des Beirats (deutsch)'
)
title_en = models.CharField(
max_length = 128,
verbose_name = 'Gruppe innerhalb des Beirats (english)'
)
order = models.IntegerField(
verbose_name = 'Anzeigeposition in der Beiratsliste'
)
has_sub_groups = models.BooleanField(
default = False,
help_text = _('Ist diese Gruppe in Untergruppen nach Bereichen unterteilt?')
)
title = TranslatedField('title_en', 'title_de')
def __str__(self):
return self.title
class Beirat2StaffRelation(models.Model):
beirat_group = models.ForeignKey(
BeiratGroups,
on_delete = models.CASCADE
)
member = models.ForeignKey(
StaffUser,
on_delete = models.CASCADE,
null = True,
blank = True
)
is_surrogate = models.BooleanField(
default = False,
help_text = _('Is this Beitrat member surrogate?')
)
is_head = models.BooleanField(
default = False,
help_text = _('Is the member head of the Beirat')
)
faculty_group = models.CharField(
max_length = 64,
choices = (
('natural', _('Natural Sciences')),
('engineering', _('Engineering')),
('medicine', _('Medicine'))
),
blank = True,
null = True
)
def __str__(self):
return '{} ({})'.format(str(self.member), str(self.beirat_group))
|
[
"[email protected]"
] | |
7bc22ff7aaf4908fbac56962aad200eb123b3427
|
59522e46a73630181f19251b8bfef90e497c2f82
|
/coop_cms/management/commands/create_db_password.py
|
5e1a63ab5f5a28fa874530f70fdb8939143577be
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
ljean/coop_cms
|
9befe74edda007686007f8566cd2555856099ae8
|
9e6c70afb61b57dc0326fbb64f9d6b19c04f48a1
|
refs/heads/master
| 2023-07-11T16:02:35.945029 | 2023-06-30T12:16:26 | 2023-06-30T12:16:26 | 5,846,409 | 3 | 5 |
NOASSERTION
| 2019-08-30T10:55:02 | 2012-09-17T19:53:56 |
Python
|
UTF-8
|
Python
| false | false | 409 |
py
|
# -*- coding: utf-8 -*-
from getpass import getpass
from django.core.management.base import BaseCommand
from django.conf import settings
from ...secrets import set_db_password
class Command(BaseCommand):
help = 'Generates a password DB'
def handle(self, *args, **options):
db_password = getpass("password?")
set_db_password(settings.BASE_DIR, settings.SECRET_KEY, db_password)
|
[
"[email protected]"
] | |
a3abb973df7c49c23f085d85ce66b4a6df1246d2
|
781e2692049e87a4256320c76e82a19be257a05d
|
/all_data/exercism_data/python/gigasecond/f02e9fb37a7446a1af9ca9e795c77365.py
|
e490967c96d68ba8fa7ac4318031d539f832a649
|
[] |
no_license
|
itsolutionscorp/AutoStyle-Clustering
|
54bde86fe6dbad35b568b38cfcb14c5ffaab51b0
|
be0e2f635a7558f56c61bc0b36c6146b01d1e6e6
|
refs/heads/master
| 2020-12-11T07:27:19.291038 | 2016-03-16T03:18:00 | 2016-03-16T03:18:42 | 59,454,921 | 4 | 0 | null | 2016-05-23T05:40:56 | 2016-05-23T05:40:56 | null |
UTF-8
|
Python
| false | false | 135 |
py
|
from datetime import timedelta
def add_gigasecond(dateTimeObj):
gigasecond=10**9
return dateTimeObj + timedelta(0,gigasecond)
|
[
"[email protected]"
] | |
a2bfd5334ad964b8fe2f5c3addb9d88084f31e5b
|
0d9b75fee49b37038a10e467c39cf75c9cf4d5ae
|
/OpenCV_learn/code_030/opencv_030.py
|
d4195aea4d2a004c17e47d6166072a6ffa2427bc
|
[] |
no_license
|
MachineLP/OpenCV-
|
743a5fcfc3f300ccb135f869e2f048cb5fdcd02a
|
f3da4feb71c20d2e8bc426eb5a4e2e61a2fd4a75
|
refs/heads/master
| 2023-03-23T15:31:22.985413 | 2023-03-08T09:33:28 | 2023-03-08T09:33:28 | 178,887,816 | 104 | 51 | null | null | null | null |
UTF-8
|
Python
| false | false | 657 |
py
|
import cv2 as cv
import numpy as np
src = cv.imread("./test.png")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)
blur_op = np.ones([5, 5], dtype=np.float32)/25.
shape_op = np.array([[0, -1, 0],
[-1, 5, -1],
[0, -1, 0]], np.float32)
grad_op = np.array([[1, 0],[0, -1]], dtype=np.float32)
dst1 = cv.filter2D(src, -1, blur_op)
dst2 = cv.filter2D(src, -1, shape_op)
dst3 = cv.filter2D(src, cv.CV_32F, grad_op)
dst3 = cv.convertScaleAbs(dst3)
cv.imshow("blur=5x5", dst1);
cv.imshow("shape=3x3", dst2);
cv.imshow("gradient=2x2", dst3);
cv.waitKey(0)
cv.destroyAllWindows()
|
[
"[email protected]"
] | |
02bf8fdde14c3aac9ce51f353f4387eeb79001e6
|
e627d47d5102bd68c2012501aa120833b9271da7
|
/aws_api/core/models.py
|
89508d58bf7297df0d5b42ee5c50cbd82b4d8508
|
[] |
no_license
|
aayushgupta97/django-km
|
5ba275d1f85eaaf8bc052e47d2b6b6f1a5e4cf90
|
d34cd4f8637718044832d9baeecee86df5e821a5
|
refs/heads/master
| 2023-01-02T18:12:31.384634 | 2020-10-24T09:21:50 | 2020-10-24T09:21:50 | 298,391,389 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 912 |
py
|
from django.db import models
from django.contrib.auth.models import User
from jsonfield import JSONField
# Create your models here.
class AWSCredentials(models.Model):
access_key = models.CharField(max_length=128)
secret_key = models.CharField(max_length=512)
account_id = models.CharField(max_length=40)
default_region = models.CharField(max_length=32, default='us-east-1')
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.account_id
class EC2(models.Model):
instance_id = models.CharField(max_length=255, blank=False)
instance_type = models.CharField(max_length=255, blank=False)
state = models.BooleanField()
instance_data = JSONField(null=True)
credentials = models.ForeignKey(AWSCredentials, null=False, on_delete=models.CASCADE)
def __str__(self):
return f"{self.instance_id} {self.credentials}"
|
[
"[email protected]"
] | |
d17ce8802fa93c39c6b0c878618591c8e9e54804
|
f9d564f1aa83eca45872dab7fbaa26dd48210d08
|
/huaweicloud-sdk-eihealth/huaweicloudsdkeihealth/v1/model/list_workflow_statistic_request.py
|
15c6ff0b1d99414e34d6ff1f3f4a86a7a12c7a08
|
[
"Apache-2.0"
] |
permissive
|
huaweicloud/huaweicloud-sdk-python-v3
|
cde6d849ce5b1de05ac5ebfd6153f27803837d84
|
f69344c1dadb79067746ddf9bfde4bddc18d5ecf
|
refs/heads/master
| 2023-09-01T19:29:43.013318 | 2023-08-31T08:28:59 | 2023-08-31T08:28:59 | 262,207,814 | 103 | 44 |
NOASSERTION
| 2023-06-22T14:50:48 | 2020-05-08T02:28:43 |
Python
|
UTF-8
|
Python
| false | false | 3,669 |
py
|
# coding: utf-8
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ListWorkflowStatisticRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'eihealth_project_id': 'str'
}
attribute_map = {
'eihealth_project_id': 'eihealth_project_id'
}
def __init__(self, eihealth_project_id=None):
"""ListWorkflowStatisticRequest
The model defined in huaweicloud sdk
:param eihealth_project_id: 医疗智能体平台项目ID,您可以在EIHealth平台单击所需的项目名称,进入项目设置页面查看。
:type eihealth_project_id: str
"""
self._eihealth_project_id = None
self.discriminator = None
self.eihealth_project_id = eihealth_project_id
@property
def eihealth_project_id(self):
"""Gets the eihealth_project_id of this ListWorkflowStatisticRequest.
医疗智能体平台项目ID,您可以在EIHealth平台单击所需的项目名称,进入项目设置页面查看。
:return: The eihealth_project_id of this ListWorkflowStatisticRequest.
:rtype: str
"""
return self._eihealth_project_id
@eihealth_project_id.setter
def eihealth_project_id(self, eihealth_project_id):
"""Sets the eihealth_project_id of this ListWorkflowStatisticRequest.
医疗智能体平台项目ID,您可以在EIHealth平台单击所需的项目名称,进入项目设置页面查看。
:param eihealth_project_id: The eihealth_project_id of this ListWorkflowStatisticRequest.
:type eihealth_project_id: str
"""
self._eihealth_project_id = eihealth_project_id
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
import simplejson as json
if six.PY2:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)
def __repr__(self):
"""For `print`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ListWorkflowStatisticRequest):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
[
"[email protected]"
] | |
9e8d73095336a9aec74a9c50d0d0e8418c3ee1fa
|
72863e7278f4be8b5d63d999144f9eaec3e7ec48
|
/venv/lib/python2.7/site-packages/libmproxy/console/window.py
|
69d5e242cd0f379d95e9b2ce08e66ce6ea7d6a88
|
[
"MIT"
] |
permissive
|
sravani-m/Web-Application-Security-Framework
|
6e484b6c8642f47dac94e67b657a92fd0dbb6412
|
d9f71538f5cba6fe1d8eabcb26c557565472f6a6
|
refs/heads/master
| 2020-04-26T11:54:01.334566 | 2019-05-03T19:17:30 | 2019-05-03T19:17:30 | 173,532,718 | 3 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,189 |
py
|
import urwid
from . import signals
class Window(urwid.Frame):
def __init__(self, master, body, header, footer, helpctx):
urwid.Frame.__init__(
self,
urwid.AttrWrap(body, "background"),
header = urwid.AttrWrap(header, "background") if header else None,
footer = urwid.AttrWrap(footer, "background") if footer else None
)
self.master = master
self.helpctx = helpctx
signals.focus.connect(self.sig_focus)
def sig_focus(self, sender, section):
self.focus_position = section
def mouse_event(self, *args, **kwargs):
# args: (size, event, button, col, row)
k = super(self.__class__, self).mouse_event(*args, **kwargs)
if not k:
if args[1] == "mouse drag":
signals.status_message.send(
message = "Hold down shift, alt or ctrl to select text.",
expire = 1
)
elif args[1] == "mouse press" and args[2] == 4:
self.keypress(args[0], "up")
elif args[1] == "mouse press" and args[2] == 5:
self.keypress(args[0], "down")
else:
return False
return True
def keypress(self, size, k):
k = super(self.__class__, self).keypress(size, k)
if k == "?":
self.master.view_help(self.helpctx)
elif k == "c":
if not self.master.client_playback:
signals.status_prompt_path.send(
self,
prompt = "Client replay",
callback = self.master.client_playback_path
)
else:
signals.status_prompt_onekey.send(
self,
prompt = "Stop current client replay?",
keys = (
("yes", "y"),
("no", "n"),
),
callback = self.master.stop_client_playback_prompt,
)
elif k == "i":
signals.status_prompt.send(
self,
prompt = "Intercept filter",
text = self.master.state.intercept_txt,
callback = self.master.set_intercept
)
elif k == "o":
self.master.view_options()
elif k == "Q":
raise urwid.ExitMainLoop
elif k == "q":
signals.pop_view_state.send(self)
elif k == "S":
if not self.master.server_playback:
signals.status_prompt_path.send(
self,
prompt = "Server replay path",
callback = self.master.server_playback_path
)
else:
signals.status_prompt_onekey.send(
self,
prompt = "Stop current server replay?",
keys = (
("yes", "y"),
("no", "n"),
),
callback = self.master.stop_server_playback_prompt,
)
else:
return k
|
[
"[email protected]"
] | |
72a814435d4159ba19a2c548b890a43020e942c8
|
f68cd225b050d11616ad9542dda60288f6eeccff
|
/testscripts/RDKB/component/PAM/TS_PAM_GetProcessNumberOfEntries.py
|
173f02eb2b3d59f3694789afc506cc744abebd56
|
[
"Apache-2.0"
] |
permissive
|
cablelabs/tools-tdkb
|
18fb98fadcd169fa9000db8865285fbf6ff8dc9d
|
1fd5af0f6b23ce6614a4cfcbbaec4dde430fad69
|
refs/heads/master
| 2020-03-28T03:06:50.595160 | 2018-09-04T11:11:00 | 2018-09-05T00:24:38 | 147,621,410 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 5,419 |
py
|
##########################################################################
# If not stated otherwise in this file or this component's Licenses.txt
# file the following copyright and licenses apply:
#
# Copyright 2016 RDK Management
#
# 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.
##########################################################################
'''
<?xml version="1.0" encoding="UTF-8"?><xml>
<id/>
<version>5</version>
<name>TS_PAM_GetProcessNumberOfEntries</name>
<primitive_test_id/>
<primitive_test_name>pam_GetParameterValues</primitive_test_name>
<primitive_test_version>1</primitive_test_version>
<status>FREE</status>
<synopsis>This testcase returns the no: of processes running in the device</synopsis>
<groups_id/>
<execution_time>1</execution_time>
<long_duration>false</long_duration>
<remarks/>
<skip>false</skip>
<box_types>
<box_type>RPI</box_type>
<box_type>Emulator</box_type>
<box_type>Broadband</box_type>
</box_types>
<rdk_versions>
<rdk_version>RDKB</rdk_version>
</rdk_versions>
<test_cases>
<test_case_id>TC_PAM_89</test_case_id>
<test_objective>To get the no: of processes running in the device</test_objective>
<test_type>Positive</test_type>
<test_setup>Emulator,XB3</test_setup>
<pre_requisite>1.Ccsp Components in DUT should be in a running state that includes component under test Cable Modem
2.TDK Agent should be in running state or invoke it through StartTdk.sh script</pre_requisite>
<api_or_interface_used>None</api_or_interface_used>
<input_parameters>Json Interface:
API Name
pam_GetParameterValues
Input:
ParamName -
Device.DeviceInfo.ProcessStatus.ProcessNumberOfEntries</input_parameters>
<automation_approch>1.Function which needs to be tested will be configured in Test Manager GUI.
2.Python Script will be generated by Test Manager with provided arguments in configure page.
3.TM will load the PAM library via Test agent
4.From python script, invoke pam_GetParameterValues() stub function to get the number of processes running.
5.pam stub function will call the ssp_getParameterValue() function of tdk component.
6.Responses from the pam stub function will be logged in Agent Console log.
7.pam stub will validate the actual result with the expected result and send the result status to Test Manager.
8.Test Manager will publish the result in GUI as PASS/FAILURE based on the response from pam stub.</automation_approch>
<except_output>CheckPoint 1:
The output should be logged in the Agent console/Component log
CheckPoint 2:
Stub function result should be success and should see corresponding log in the agent console log
CheckPoint 3:
TestManager GUI will publish the result as PASS in Execution/Console page of Test Manager</except_output>
<priority>High</priority>
<test_stub_interface>None</test_stub_interface>
<test_script>TS_PAM_GetProcessNumberOfEntries</test_script>
<skipped>No</skipped>
<release_version/>
<remarks/>
</test_cases>
<script_tags/>
</xml>
'''
#import statement
import tdklib;
#Test component to be tested
obj = tdklib.TDKScriptingLibrary("pam","RDKB");
#IP and Port of box, No need to change,
#This will be replaced with correspoing Box Ip and port while executing script
ip = <ipaddress>
port = <port>
obj.configureTestCase(ip,port,'TS_PAM_GetProcessNumberOfEntries');
#Get the result of connection with test component and STB
loadmodulestatus =obj.getLoadModuleResult();
print "[LIB LOAD STATUS] : %s" %loadmodulestatus ;
if "SUCCESS" in loadmodulestatus.upper():
#Set the result status of execution
obj.setLoadModuleStatus("SUCCESS");
tdkTestObj = obj.createTestStep('pam_GetParameterValues');
tdkTestObj.addParameter("ParamName","Device.DeviceInfo.ProcessStatus.ProcessNumberOfEntries");
expectedresult="SUCCESS";
#Execute the test case in STB
tdkTestObj.executeTestCase(expectedresult);
actualresult = tdkTestObj.getResult();
details = tdkTestObj.getResultDetails();
if expectedresult in actualresult:
#Set the result status of execution
tdkTestObj.setResultStatus("SUCCESS");
print "TEST STEP 1: Get the number of processes";
print "EXPECTED RESULT 1: Should get the number of processes";
print "ACTUAL RESULT 1: No of Processes %s" %details;
#Get the result of execution
print "[TEST EXECUTION RESULT] : SUCCESS"
else:
tdkTestObj.setResultStatus("FAILURE");
print "TEST STEP 1: Get the number of processes";
print "EXPECTED RESULT 1: Should get the number of processes";
print "ACTUAL RESULT 1: Failure in getting the number of processes. Details : %s" %details;
print "[TEST EXECUTION RESULT] : FAILURE";
obj.unloadModule("pam");
else:
print "Failed to load pam module";
obj.setLoadModuleStatus("FAILURE");
print "Module loading failed";
|
[
"[email protected]"
] | |
1e3202d244ebfff9dd6bcecadaa71c32fb40e2fd
|
709bd5f2ecc69a340da85f6aed67af4d0603177e
|
/saleor/product/migrations/0073_auto_20181010_0729.py
|
b6435a6d48c72a8b3723f876f1995998d63fc51b
|
[
"BSD-3-Clause"
] |
permissive
|
Kenstogram/opensale
|
41c869ee004d195bd191a1a28bf582cc6fbb3c00
|
5102f461fa90f2eeb13b9a0a94ef9cb86bd3a3ba
|
refs/heads/master
| 2022-12-15T02:48:48.810025 | 2020-03-10T02:55:10 | 2020-03-10T02:55:10 | 163,656,395 | 8 | 0 |
BSD-3-Clause
| 2022-12-08T01:31:09 | 2018-12-31T09:30:41 |
Python
|
UTF-8
|
Python
| false | false | 1,129 |
py
|
# Generated by Django 2.1.2 on 2018-10-10 12:29
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('product', '0072_auto_20180925_1048'),
]
operations = [
migrations.AddField(
model_name='attribute',
name='product_type',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='temp_product_attributes', to='product.ProductType'),
),
migrations.AddField(
model_name='attribute',
name='product_variant_type',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='temp_variant_attributes', to='product.ProductType'),
),
migrations.AlterField(
model_name='attribute',
name='name',
field=models.CharField(max_length=50),
),
migrations.AlterField(
model_name='attribute',
name='slug',
field=models.SlugField(),
),
]
|
[
"[email protected]"
] | |
8b0c025a56778453f144197d06f980ed00737458
|
af8f0d50bb11279c9ff0b81fae97f754df98c350
|
/src/book/api/views/category.py
|
3037b5486bcde77e4a473f50e746cb978cc99220
|
[
"Apache-2.0"
] |
permissive
|
DmytroKaminskiy/ltt
|
592ed061efe3cae169a4e01f21d2e112e58714a1
|
d08df4d102e678651cd42928e2343733c3308d71
|
refs/heads/master
| 2022-12-18T09:56:36.077545 | 2020-09-20T15:57:35 | 2020-09-20T15:57:35 | 292,520,616 | 0 | 0 |
Apache-2.0
| 2020-09-20T15:49:58 | 2020-09-03T09:09:26 |
HTML
|
UTF-8
|
Python
| false | false | 513 |
py
|
from book.api.serializers.category import CategorySerializer
from book.models import Category
from rest_framework import generics
__all__ = [
'ListCreateCategoryView',
'RetrieveCategoryView',
]
class ListCreateCategoryView(generics.ListCreateAPIView):
serializer_class = CategorySerializer
queryset = Category.objects.all().order_by('-id')
class RetrieveCategoryView(generics.RetrieveAPIView):
queryset = Category.objects.all().order_by('-id')
serializer_class = CategorySerializer
|
[
"[email protected]"
] | |
3eebded3e51926fff9c1f76a81b7786c011c7547
|
8aa1b94626402c0c614128d6061edb771dad05cf
|
/e100/e017.py
|
b24dd8c62dd7fb877ccffbdbd147ff7d80e27ed6
|
[] |
no_license
|
netfj/Project_Stu02
|
31e76c1b656ee74c54cae2185821dec7ccf50401
|
afc1b26b7c586fd6979ab574c7d357a6b9ef4d29
|
refs/heads/master
| 2023-03-13T22:24:40.364167 | 2021-02-23T09:53:31 | 2021-02-23T09:53:31 | 341,506,093 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 631 |
py
|
#coding:utf-8
"""
@info: 题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
@author:NetFj @software:PyCharm @file:e017.py @time:2018/11/1.16:45
"""
# c='0'
# while c != '':
# c = input('Input a string:')
c='abc1 2 3 4 5 6[(@#$)]'
y,k,s,q =0,0,0,0
for x in c:
if x.isalpha():y+=1
elif x.isspace():k+=1
elif x.isdigit(): s += 1
else: q+=1
print(y,k,s,q)
y,k,s,q =0,0,0,0
for n in range(0,len(c)):
if c[n].isalpha():
y += 1
elif c[n].isspace():
k += 1
elif c[n].isdigit():
s += 1
else:
q += 1
print(y, k, s, q)
|
[
"[email protected]"
] | |
ab6b6c52579d74e382ce37f2ebe8f535a24dbc3f
|
15f321878face2af9317363c5f6de1e5ddd9b749
|
/solutions_python/Problem_59/455.py
|
3e6cea92b28872ec185a3a22fdbde19106c357b6
|
[] |
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 | 2,472 |
py
|
#! /usr/bin/env python
import sys
f = file(sys.argv[1])
lines = [ln.strip() for ln in f.readlines()]
T = int(lines[0])
print('%s contains %i (T) test cases' % (sys.argv[1],T))
cases = []
ind = 1
for i in range(T):
#print(lines[ind], lines[ind].split(' '))
n,m = [int(k) for k in lines[ind].split(' ')]
#print(n,m)
ind = ind + 1
dirsExisting = lines[ind:ind+n]
ind = ind + n
dirsToBeCreated = lines[ind:ind+m]
ind = ind + m
cases.append([dirsExisting, dirsToBeCreated])
print(cases)
class directoryNode:
def __init__(self, name, parent, level):
self.name = name
self.parent = parent
self.level = level
self.folders = []
def has_folder(self, fname):
return any([folder.name == fname for folder in self.folders])
def create_folder(self, fname):
self.folders.append(directoryNode(fname,self,self.level+1))
def get_folder(self, fname):
return self.folders[[folder.name == fname for folder in self.folders].index(True)]
def __repr__(self):
return repr(self.parent) + '/' + self.name
def directoryProblem(iDirs, mDirs):
directoryRoot = directoryNode('',None,0)
def mkdirs(dirsClean):
creations = 0
currentDir = directoryRoot
dirs = sorted(dirsClean)
currentFolders = []
for d in dirs:
folders = d.split('/')[1:]
#print('d,folders',d,folders)
j = 0
while j < min(len(folders),len(currentFolders)) and folders[j] == currentFolders[j]:
j = j + 1
# rolling back required dirs
while len(currentFolders) > j:
currentDir = currentDir.parent
del currentFolders[-1]
#print('currentDir, currentFolders',currentDir, currentFolders)
for fold in folders[j:]:
if not currentDir.has_folder(fold):
currentDir.create_folder(fold)
creations = creations + 1
currentDir = currentDir.get_folder(fold)
currentFolders = folders
return creations
c1 = mkdirs(iDirs)
c2 = mkdirs(mDirs)
return c2
results = []
for t in range(T):
print('case %i of %i' % (t+1,T))
print(cases[t])
res = directoryProblem(*cases[t])
results.append('Case #%i: %i' % (t+1,res))
print(results[-1])
f = file(sys.argv[1].replace('.in','.out'),'w')
f.write('\n'.join(results))
f.close()
|
[
"[email protected]"
] | |
043e9fa6f520efc3819ea417696518a68ba03ca1
|
7769cb512623c8d3ba96c68556b2cea5547df5fd
|
/configs/cascade_mask_rcnn_x101_64x4d_fpn_1x.py
|
80a5ed6a2b31ff06816ce74d04570d82517229a0
|
[
"MIT"
] |
permissive
|
JialeCao001/D2Det
|
0e49f4c76e539d574e46b02f278242ca912c31ea
|
a76781ab624a1304f9c15679852a73b4b6770950
|
refs/heads/master
| 2022-12-05T01:00:08.498629 | 2020-09-04T11:33:26 | 2020-09-04T11:33:26 | 270,723,372 | 312 | 88 |
MIT
| 2020-07-08T23:53:23 | 2020-06-08T15:37:35 |
Python
|
UTF-8
|
Python
| false | false | 8,061 |
py
|
# model settings
model = dict(
type='CascadeRCNN',
num_stages=3,
pretrained='open-mmlab://resnext101_64x4d',
backbone=dict(
type='ResNeXt',
depth=101,
groups=64,
base_width=4,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
style='pytorch'),
neck=dict(
type='FPN',
in_channels=[256, 512, 1024, 2048],
out_channels=256,
num_outs=5),
rpn_head=dict(
type='RPNHead',
in_channels=256,
feat_channels=256,
anchor_scales=[8],
anchor_ratios=[0.5, 1.0, 2.0],
anchor_strides=[4, 8, 16, 32, 64],
target_means=[.0, .0, .0, .0],
target_stds=[1.0, 1.0, 1.0, 1.0],
loss_cls=dict(
type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0),
loss_bbox=dict(type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=1.0)),
bbox_roi_extractor=dict(
type='SingleRoIExtractor',
roi_layer=dict(type='RoIAlign', out_size=7, sample_num=2),
out_channels=256,
featmap_strides=[4, 8, 16, 32]),
bbox_head=[
dict(
type='SharedFCBBoxHead',
num_fcs=2,
in_channels=256,
fc_out_channels=1024,
roi_feat_size=7,
num_classes=81,
target_means=[0., 0., 0., 0.],
target_stds=[0.1, 0.1, 0.2, 0.2],
reg_class_agnostic=True,
loss_cls=dict(
type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0),
loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)),
dict(
type='SharedFCBBoxHead',
num_fcs=2,
in_channels=256,
fc_out_channels=1024,
roi_feat_size=7,
num_classes=81,
target_means=[0., 0., 0., 0.],
target_stds=[0.05, 0.05, 0.1, 0.1],
reg_class_agnostic=True,
loss_cls=dict(
type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0),
loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)),
dict(
type='SharedFCBBoxHead',
num_fcs=2,
in_channels=256,
fc_out_channels=1024,
roi_feat_size=7,
num_classes=81,
target_means=[0., 0., 0., 0.],
target_stds=[0.033, 0.033, 0.067, 0.067],
reg_class_agnostic=True,
loss_cls=dict(
type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0),
loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0))
],
mask_roi_extractor=dict(
type='SingleRoIExtractor',
roi_layer=dict(type='RoIAlign', out_size=14, sample_num=2),
out_channels=256,
featmap_strides=[4, 8, 16, 32]),
mask_head=dict(
type='FCNMaskHead',
num_convs=4,
in_channels=256,
conv_out_channels=256,
num_classes=81,
loss_mask=dict(
type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)))
# model training and testing settings
train_cfg = dict(
rpn=dict(
assigner=dict(
type='MaxIoUAssigner',
pos_iou_thr=0.7,
neg_iou_thr=0.3,
min_pos_iou=0.3,
ignore_iof_thr=-1),
sampler=dict(
type='RandomSampler',
num=256,
pos_fraction=0.5,
neg_pos_ub=-1,
add_gt_as_proposals=False),
allowed_border=0,
pos_weight=-1,
debug=False),
rpn_proposal=dict(
nms_across_levels=False,
nms_pre=2000,
nms_post=2000,
max_num=2000,
nms_thr=0.7,
min_bbox_size=0),
rcnn=[
dict(
assigner=dict(
type='MaxIoUAssigner',
pos_iou_thr=0.5,
neg_iou_thr=0.5,
min_pos_iou=0.5,
ignore_iof_thr=-1),
sampler=dict(
type='RandomSampler',
num=512,
pos_fraction=0.25,
neg_pos_ub=-1,
add_gt_as_proposals=True),
mask_size=28,
pos_weight=-1,
debug=False),
dict(
assigner=dict(
type='MaxIoUAssigner',
pos_iou_thr=0.6,
neg_iou_thr=0.6,
min_pos_iou=0.6,
ignore_iof_thr=-1),
sampler=dict(
type='RandomSampler',
num=512,
pos_fraction=0.25,
neg_pos_ub=-1,
add_gt_as_proposals=True),
mask_size=28,
pos_weight=-1,
debug=False),
dict(
assigner=dict(
type='MaxIoUAssigner',
pos_iou_thr=0.7,
neg_iou_thr=0.7,
min_pos_iou=0.7,
ignore_iof_thr=-1),
sampler=dict(
type='RandomSampler',
num=512,
pos_fraction=0.25,
neg_pos_ub=-1,
add_gt_as_proposals=True),
mask_size=28,
pos_weight=-1,
debug=False)
],
stage_loss_weights=[1, 0.5, 0.25])
test_cfg = dict(
rpn=dict(
nms_across_levels=False,
nms_pre=1000,
nms_post=1000,
max_num=1000,
nms_thr=0.7,
min_bbox_size=0),
rcnn=dict(
score_thr=0.05,
nms=dict(type='nms', iou_thr=0.5),
max_per_img=100,
mask_thr_binary=0.5))
# dataset settings
dataset_type = 'CocoDataset'
data_root = 'data/coco/'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_bbox=True, with_mask=True),
dict(type='Resize', img_scale=(1333, 800), keep_ratio=True),
dict(type='RandomFlip', flip_ratio=0.5),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks']),
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=(1333, 800),
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img']),
])
]
data = dict(
imgs_per_gpu=2,
workers_per_gpu=2,
train=dict(
type=dataset_type,
ann_file=data_root + 'annotations/instances_train2017.json',
img_prefix=data_root + 'train2017/',
pipeline=train_pipeline),
val=dict(
type=dataset_type,
ann_file=data_root + 'annotations/instances_val2017.json',
img_prefix=data_root + 'val2017/',
pipeline=test_pipeline),
test=dict(
type=dataset_type,
ann_file=data_root + 'annotations/instances_val2017.json',
img_prefix=data_root + 'val2017/',
pipeline=test_pipeline))
evaluation = dict(interval=1, metric=['bbox', 'segm'])
# optimizer
optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2))
# learning policy
lr_config = dict(
policy='step',
warmup='linear',
warmup_iters=500,
warmup_ratio=1.0 / 3,
step=[8, 11])
checkpoint_config = dict(interval=1)
# yapf:disable
log_config = dict(
interval=50,
hooks=[
dict(type='TextLoggerHook'),
# dict(type='TensorboardLoggerHook')
])
# yapf:enable
# runtime settings
total_epochs = 12
dist_params = dict(backend='nccl')
log_level = 'INFO'
work_dir = './work_dirs/cascade_mask_rcnn_x101_64x4d_fpn_1x'
load_from = None
resume_from = None
workflow = [('train', 1)]
|
[
"[email protected]"
] | |
dba1a03904559ee7acc59f6c910257a5156bf9d0
|
52c4444b7a8e1a313d847ba5f0474f5a429be4bd
|
/celescope/fusion/multi_fusion.py
|
b82cd4bece7083905eb8b0e0063018ff9117df0c
|
[
"MIT"
] |
permissive
|
JING-XINXING/CeleScope
|
98d0d018f3689dbe355679c1b8c06f8d796c296d
|
d401e01bdf15c8eeb71bddede484ed8d4f189dcd
|
refs/heads/master
| 2023-05-07T11:47:04.133216 | 2021-05-28T10:14:53 | 2021-05-28T10:14:53 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 999 |
py
|
from celescope.fusion.__init__ import __ASSAY__
from celescope.tools.multi import Multi
class Multi_fusion(Multi):
def star_fusion(self, sample):
step = 'star_fusion'
cmd_line = self.get_cmd_line(step, sample)
fq = f'{self.outdir_dic[sample]["cutadapt"]}/{sample}_clean_2.fq{self.fq_suffix}'
cmd = (
f'{cmd_line} '
f'--fq {fq} '
)
self.process_cmd(cmd, step, sample, m=self.args.starMem, x=self.args.thread)
def count_fusion(self, sample):
step = 'count_fusion'
cmd_line = self.get_cmd_line(step, sample)
bam = f'{self.outdir_dic[sample]["star_fusion"]}/{sample}_Aligned.sortedByCoord.out.bam'
cmd = (
f'{cmd_line} '
f'--bam {bam} '
f'--match_dir {self.col4_dict[sample]} '
)
self.process_cmd(cmd, step, sample, m=15, x=1)
def main():
multi = Multi_fusion(__ASSAY__)
multi.run()
if __name__ == '__main__':
main()
|
[
"[email protected]"
] | |
85f6ba445f50885725cedabb538b5da28dee1645
|
90c6262664d013d47e9a3a9194aa7a366d1cabc4
|
/tests/opcodes/cases/test_pexec_253.py
|
18a5dd1216b31de8c9699b42ce6666fe9b9aae87
|
[
"MIT"
] |
permissive
|
tqtezos/pytezos
|
3942fdab7aa7851e9ea81350fa360180229ec082
|
a4ac0b022d35d4c9f3062609d8ce09d584b5faa8
|
refs/heads/master
| 2021-07-10T12:24:24.069256 | 2020-04-04T12:46:24 | 2020-04-04T12:46:24 | 227,664,211 | 1 | 0 |
MIT
| 2020-12-30T16:44:56 | 2019-12-12T17:47:53 |
Python
|
UTF-8
|
Python
| false | false | 820 |
py
|
from unittest import TestCase
from tests import abspath
from pytezos.repl.interpreter import Interpreter
from pytezos.michelson.converter import michelson_to_micheline
from pytezos.repl.parser import parse_expression
class OpcodeTestpexec_253(TestCase):
def setUp(self):
self.maxDiff = None
self.i = Interpreter(debug=True)
def test_opcode_pexec_253(self):
res = self.i.execute(f'INCLUDE "{abspath("opcodes/contracts/pexec.tz")}"')
self.assertTrue(res['success'])
res = self.i.execute('RUN 38 14')
self.assertTrue(res['success'])
exp_val_expr = michelson_to_micheline('52')
exp_val = parse_expression(exp_val_expr, res['result']['storage'].type_expr)
self.assertEqual(exp_val, res['result']['storage']._val)
|
[
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.