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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0ac18fe3f7edb520beebb06692cc97b23e5356d0 | f78ddd04ac900bfe670ae841ad8b05fbd6fd305d | /collective/powertoken/view/tests/base.py | 0115392663f1379ff88738dbe412242f5028fa2c | [] | no_license | RedTurtle/collective.powertoken.view | 9b0f0ca53ae9c09258f71b95d0ef2ec90b12e88d | 0a5bc89b78918d9319d4e73adc12cf42d42b11da | refs/heads/master | 2022-12-24T10:12:31.102480 | 2012-02-15T14:38:41 | 2012-02-15T14:38:41 | 3,111,637 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,673 | py | # -*- coding: utf-8 -*-
from Products.Five import zcml
from Products.Five import fiveconfigure
#from Testing import ZopeTestCase as ztc
from Products.PloneTestCase import PloneTestCase as ptc
from Products.PloneTestCase.layer import onsetup
@onsetup
def setup_product():
"""Set up additional products and ZCML required to test this product.
The @onsetup decorator causes the execution of this body to be deferred
until the setup of the Plone site testing layer.
"""
# Load the ZCML configuration for this package and its dependencies
fiveconfigure.debug_mode = True
import collective.powertoken.core
import collective.powertoken.view
zcml.load_config('configure.zcml', collective.powertoken.core)
zcml.load_config('configure.zcml', collective.powertoken.view)
fiveconfigure.debug_mode = False
# We need to tell the testing framework that these products
# should be available. This can't happen until after we have loaded
# the ZCML.
#ztc.installPackage('collective.powertoken')
# provideAdapter(
# TestPowerActionProvider,
# (IContentish,
# IHTTPRequest),
# provides=IPowerActionProvider,
# name='foo'
# )
# The order here is important: We first call the deferred function and then
# let PloneTestCase install it during Plone site setup
setup_product()
#ptc.setupPloneSite(products=['collective.powertoken.view'])
ptc.setupPloneSite()
class TestCase(ptc.PloneTestCase):
"""Base class used for test cases
"""
class FunctionalTestCase(ptc.FunctionalTestCase):
"""Test case class used for functional (doc-)tests
"""
| [
"luca@keul.it"
] | luca@keul.it |
41187baa2e786d43ecffa07d0bba00d160a1cf24 | 597d8b96c8796385b365f79d7a134f828e414d46 | /pythonTest/cn/sodbvi/exercise/example076.py | 022d87cbffcbf48924dbd4c82812d553518ea222 | [] | no_license | glorysongglory/pythonTest | a938c0184c8a492edeba9237bab1c00d69b0e5af | ed571d4c240fccfb4396e2890ad922726daa10a0 | refs/heads/master | 2021-01-21T11:39:35.657552 | 2019-08-14T02:49:26 | 2019-08-14T02:49:26 | 52,493,444 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 503 | py | #!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
Created on 2016年1月12日
@author: sodbvi
'''
def peven(n):
i = 0
s = 0.0
for i in range(2,n + 1,2):
s += 1.0 / i
return s
def podd(n):
s = 0.0
for i in range(1, n + 1,2):
s += 1 / i
return s
def dcall(fp,n):
s = fp(n)
return s
if __name__ == '__main__':
n = int(raw_input('input a number:\n'))
if n % 2 == 0:
sum = dcall(peven,n)
else:
sum = dcall(podd,n)
print sum | [
"317878410@qq.com"
] | 317878410@qq.com |
197169cda56b3bbb7963e86ddffa917b376e09b7 | 48bb4a0dbb361a67b88b7c7532deee24d70aa56a | /codekata/diftwostr.py | 7bc3823d1a60fba9ace83be0cf3bc0c788ab2075 | [] | no_license | PRAMILARASI/GUVI | 66080a80400888263d511138cb6ecd37540507c7 | 6a30a1d0a3f4a777db895f0b3adc8b0ac90fd25b | refs/heads/master | 2022-01-28T08:54:07.719735 | 2019-06-24T15:57:05 | 2019-06-24T15:57:05 | 191,355,070 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 556 | py | s=input()
r=input()
ga=[]
if (s.isalpha() or " " in s) and (r.isalpha() or " " in r):
s=list(s.split(" "))
r=list(r.split(" "))
for i in s:
if s.count(i) > r.count(i) and i not in g:
ga.append(i)
for i in r:
if r.count(i)>s.count(i) and i not in ga:
ga.append(i)
print(*ga)
else:
for i in s:
if s.count(i)>r.count(i) and i not in g:
ga.append(i)
for j in r:
if r.count(j)>s.count(j) and j not in ga:
ga.append(j)
print(*ga)
| [
"noreply@github.com"
] | PRAMILARASI.noreply@github.com |
b0a7b8d41e7a3721214629851ac2f43b60da1a3a | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/nouns/_decadence.py | e45ac2d2bb3034736876e778afd0265ab221b42d | [
"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 | 321 | py |
#calss header
class _DECADENCE():
def __init__(self,):
self.name = "DECADENCE"
self.definitions = [u'low moral standards and behaviour: ']
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.specie = 'nouns'
def run(self, obj1 = [], obj2 = []):
return self.jsondata
| [
"xingwang1991@gmail.com"
] | xingwang1991@gmail.com |
2783c24639ee36365aef4ca759ece83577cf2167 | a5dacc8ea7dba732c6884a18775317dd7c59a6d6 | /examples/cull-idle/jupyterhub_config.py | 2de8f424989a3a5da8e62e5c27381aabb3c47ecf | [
"BSD-3-Clause"
] | permissive | richmoore1962/jupyterhub | de7b995d5a4d57a471bfed9ac96de3176cfa4c5f | 5d7e0080553a2255e13980aee7249afb141b154e | refs/heads/master | 2022-12-23T11:03:30.989101 | 2017-11-03T09:31:46 | 2017-11-03T09:31:46 | 109,429,441 | 0 | 0 | NOASSERTION | 2020-09-20T20:33:13 | 2017-11-03T18:25:32 | Python | UTF-8 | Python | false | false | 194 | py | # run cull-idle as a service
c.JupyterHub.services = [
{
'name': 'cull-idle',
'admin': True,
'command': 'python cull_idle_servers.py --timeout=3600'.split(),
}
]
| [
"benjaminrk@gmail.com"
] | benjaminrk@gmail.com |
5f21d3d4219a6206895837a13333cb428c0e6212 | dc51e4714820d991e7d0e94b3e9eac4dbc67eea7 | /project/utils/auth.py | 18f86a9f587e9c86950a9f1d5416c4b9d61403b5 | [] | no_license | ruoxiaojie/Django | 537d27abe9ebb85e0dfc69585f318a87e7514a70 | 92b88600953cd4ff743032cab3d4785437c949e0 | refs/heads/master | 2021-01-15T22:18:56.033883 | 2018-03-09T06:15:46 | 2018-03-09T06:15:46 | 99,894,862 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 387 | py | #!/usr/bin/python
#Author:xiaojie
# -*- coding:utf-8 -*-
from django.shortcuts import HttpResponse,redirect
def Auth(func):
def wrapper(request,*args,**kwargs):
session_dict = request.session.get('user_info')
if session_dict:
res = func(request,*args,**kwargs)
return res
else:
return redirect('/login')
return wrapper | [
"475030894@qq.com"
] | 475030894@qq.com |
9d58e38063f9ca3c1fa93866836158614af67dbb | 0bb49acb7bb13a09adafc2e43e339f4c956e17a6 | /OpenAssembler/Gui/AttributeEditor/attributeEditor.py | 0fa595c533f6ab79ea8d3ca02c021437b4ec8084 | [] | no_license | all-in-one-of/openassembler-7 | 94f6cdc866bceb844246de7920b7cbff9fcc69bf | 69704d1c4aa4b1b99f484c8c7884cf73d412fafe | refs/heads/master | 2021-01-04T18:08:10.264830 | 2010-07-02T10:50:16 | 2010-07-02T10:50:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,152 | py | # #####################################################################################
#
# OpenAssembler V3
# Owner: Laszlo Mates
# Email: laszlo.mates@gmail.com
# Date: 2009.06.04
#
# #####################################################################################
from PyQt4 import QtCore, QtGui
from Gui.OAS_Window.oas_attribute_string import Ui_oas_attribute_widget
class attributeEditor(Ui_oas_attribute_widget):
def loadAttributes(self,attributeset,nodeSet):
self.inAE=attributeset
if self.oas_splitter.sizes()[1]==0:
self.oas_splitter.setSizes([700,300])
self.oas_nodeName.setText(self.inAE["name"])
self.oas_attribute_nodetype.setText(self.inAE["nodetype"])
QtCore.QObject.disconnect(self.oas_attribute_cache, QtCore.SIGNAL("stateChanged(int)"),self.nodeSettingE)
if str(self.inAE["nodesettings"]["_do_cache"])=="True":
self.oas_attribute_cache.setChecked(True)
else:
self.oas_attribute_cache.setChecked(False)
QtCore.QObject.connect(self.oas_attribute_cache, QtCore.SIGNAL("stateChanged(int)"),self.nodeSettingE)
sortedinputs=[]
for key in self.inAE["inputs"].keys():
sortedinputs.append(key)
sortedinputs.sort()
for ins in sortedinputs:
sts=self.connectionCollector.getConnectionID(self.inAE["ID"],ins)
if sts==[]:
status="free"
else:
status="connected"
varT=self.inAE["inputs"][ins]["variable_type"]
sablock=QtGui.QWidget(self.oas_attribute_area)
Ui_oas_attribute_widget().setupUi(sablock,str(ins),self.inAE["inputs"][ins]["value"],status,varT,nodeSet)
self.place_to_widgets.addWidget(sablock)
self.inAE["widget"][str(ins)]=sablock
for ins in self.inAE["extras"].keys():
status="free"
varT=self.inAE["extras"][ins]["variable_type"]
sablock=QtGui.QWidget(self.oas_attribute_area)
Ui_oas_attribute_widget().setupUi(sablock,str(ins),self.inAE["extras"][ins]["value"],status,varT,nodeSet)
self.place_to_widgets.addWidget(sablock)
self.inAE["widget"][str(ins)]=sablock
def cleanAttributes(self):
self.inAE={}
self.oas_attribute_nodetype.setText("empty")
self.oas_attribute_cache.setChecked(False)
self.oas_nodeName.setText("") | [
"laszlo.mates@732492aa-5b49-0410-a19c-07a6d82ec771"
] | laszlo.mates@732492aa-5b49-0410-a19c-07a6d82ec771 |
f46481c123eee2c7b164413ece213c6de9a666b1 | a32c2ee4e6b2b1c6f8db02320c4bd50b17940af5 | /modules/TIMCardHolderAddFriends/TIMCardHolderAddFriends.py | 086b16f65630f26fa39058f13b7086328fafb33d | [] | no_license | wszg5/studyGit | 93d670884d4cba7445c4df3a5def8085e5bf9ac0 | bebfc90bc38689990c2ddf52e5a2f7a02649ea00 | refs/heads/master | 2020-04-05T02:55:17.367722 | 2018-11-07T06:01:03 | 2018-11-07T06:01:03 | 156,494,390 | 2 | 2 | null | null | null | null | UTF-8 | Python | false | false | 4,566 | py | # coding:utf-8
from uiautomator import Device
from Repo import *
import os, time, datetime, random
from zservice import ZDevice
class TIMCardHolderAddFriends:
def __init__(self):
self.repo = Repo()
def action(self, d, z, args):
cate_id = args["repo_number_cate_id"]
collect_count = int(args['collect_count']) # 要扫描多少人
count = self.repo.GetNumber(cate_id, 0, collect_count)
d.server.adb.cmd("shell", "am force-stop com.tencent.tim").communicate() # 强制停止
d.server.adb.cmd("shell",
"am start -n com.tencent.tim/com.tencent.mobileqq.activity.SplashActivity").wait() # 拉起来
d(index=2, className='android.widget.FrameLayout').click()
d(text='名片夹', className='android.widget.TextView').click()
if d(text='设置我的名片', className='android.widget.TextView').exists:
d(text='设置我的名片', className='android.widget.TextView').click()
d(text='添加我的名片', className='android.widget.TextView').click()
d(text='从相册选择', className='android.widget.TextView').click()
time.sleep(1)
d(index=0, className='android.widget.ImageView').click()
d(text='确定', className='android.widget.Button').click()
time.sleep(2)
d(text='完成', className='android.widget.TextView').click()
time.sleep(3)
self.collectData(count)
else:
self.collectData(count)
if (args["time_delay"]):
time.sleep(int(args["time_delay"]))
def collectData(self,count):
d(text='我的名片', className='android.widget.TextView').click()
print (count)
for i in range(0,len(count)/3 + 1):
for j in range(0,3):
if j == 0:
d(text='编辑', className='android.widget.TextView').click()
d(text='添加手机号', className='android.widget.TextView').click()
d(text='添加手机号', className='android.widget.TextView').click()
if len(count)>=i*3+j+1:
print (count[i * 3 + j])
d(text='填写号码', className='android.widget.EditText', index=j).set_text(count[i * 3 + j])
else:
break
if j==2:
d(text='完成', className='android.widget.TextView').click()
for k in range(0,3):
if k == 0:
str = d.info # 获取屏幕大小等信息
height = str["displayHeight"]
width = str["displayWidth"]
d.swipe(width / 2, height * 5 / 6, width / 2, height / 4)
time.sleep(3)
if d(index=2, className='android.widget.LinearLayout').child(index=k, className='android.widget.RelativeLayout').child(index=2, className='android.widget.TextView').exists:
d(index=2, className='android.widget.LinearLayout').child(index=k, className='android.widget.RelativeLayout').child(text='加好友', className='android.widget.Button').click()
# 加好友需要补充
# ************
# ************
# ************
# ************
# ************
# ************
# ************
# ************
# ************
# ************
# ************
else:
print ('结束扫描')
d(text='编辑', className='android.widget.TextView').click()
for k in range(0, 3):
d(className='android.widget.RelativeLayout', index=4).child(className='android.widget.EditText',index=k).clear_text()
d(text='完成', className='android.widget.TextView').click()
break
def getPluginClass():
return TIMCardHolderAddFriends
if __name__ == "__main__":
clazz = getPluginClass()
o = clazz()
d = Device("HT57FSK00089")
# material=u'有空聊聊吗'
z = ZDevice("HT57FSK00089")
d.server.adb.cmd("shell", "ime set com.zunyun.qk/.ZImeService").communicate()
args = {"repo_number_cate_id": "43", "add_count": "9", "time_delay": "3"}; # cate_id是仓库号,length是数量
o.action(d, z, args) | [
"you@example.com"
] | you@example.com |
d03d5c855680e1b6fa3515be40d126c7e532e244 | 943dca755b940493a8452223cfe5daa2fb4908eb | /abc116/c.py | 5267dea5164cda9c07be495dd9a9df3f46b7cd66 | [] | no_license | ymsk-sky/atcoder | 5e34556582763b7095a5f3a7bae18cbe5b2696b2 | 36d7841b70b521bee853cdd6d670f8e283d83e8d | refs/heads/master | 2023-08-20T01:34:16.323870 | 2023-08-13T04:49:12 | 2023-08-13T04:49:12 | 254,348,518 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 236 | py | n=int(input())
hs=list(map(int,input().split()))
c=0
m=max(hs)
while not m==0:
b=0
for i,h in enumerate(hs):
if h==m:
if not b==m:
c+=1
hs[i]-=1
b=h
m=max(hs)
print(c)
| [
"ymsk.sky.95@gmail.com"
] | ymsk.sky.95@gmail.com |
b6bc653644bc26cd60b6afcceabe021e4f545686 | 9c368c9fe78a2dd186daeed2d0714651c1c27d66 | /absorption/ml_project/analyse_spectra/more_plotting/plot_phase_space_ssfr_split.py | c2c1475a8e26d8ca760a0dee52ded9982b0a0c6f | [] | no_license | sarahappleby/cgm | 5ff2121919e36b10069692f71fb1dc03f3678462 | 656bf308771dd3ff2f8c2e77107cdc14507c7ce7 | refs/heads/master | 2023-01-24T03:10:01.610418 | 2023-01-20T11:04:31 | 2023-01-20T11:04:31 | 160,820,718 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,599 | py | import matplotlib.pyplot as plt
import matplotlib.colors as colors
from mpl_toolkits.axes_grid1 import make_axes_locatable
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np
import h5py
import pygad as pg
import sys
plt.rc('text', usetex=True)
plt.rc('font', family='serif', size=13)
def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100, alpha=1.):
cmap_list = cmap(np.linspace(minval, maxval, n))
cmap_list[:, -1] = alpha
new_cmap = colors.LinearSegmentedColormap.from_list('trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),
cmap_list)
return new_cmap
def quench_thresh(z): # in units of yr^-1
return -1.8 + 0.3*z -9.
def ssfr_type_check(ssfr_thresh, ssfr):
sf_mask = (ssfr >= ssfr_thresh)
gv_mask = (ssfr < ssfr_thresh) & (ssfr > ssfr_thresh -1)
q_mask = ssfr == -14.0
return sf_mask, gv_mask, q_mask
if __name__ == '__main__':
model = sys.argv[1]
wind = sys.argv[2]
snap = sys.argv[3]
cmap = plt.get_cmap('Greys')
cmap = truncate_colormap(cmap, 0.0, .6)
lines = ["H1215", "MgII2796", "CII1334", "SiIII1206", "CIV1548", "OVI1031"]
plot_lines = [r'${\rm HI}1215$', r'${\rm MgII}2796$', r'${\rm CII}1334$',
r'${\rm SiIII}1206$', r'${\rm CIV}1548$', r'${\rm OVI}1031$']
x = [0.75, 0.69, 0.73, 0.705, 0.71, 0.71]
cbar_ticks = [[12, 13, 14, 15, 16], [11, 12, 13, 14], [12, 13, 14], [11, 12, 13, 14], [12, 13, 14], [12, 13, 14],]
#chisq_lim = [4.5, 63.1, 20.0, 70.8, 15.8, 4.5] limits with old fitting procedure
chisq_lim = [4., 50., 15.8, 39.8, 8.9, 4.5]
width = 0.007
height = 0.1283
vertical_position = [0.76, 0.632, 0.504, 0.373, 0.247, 0.1175]
vertical_position = [0.7516, 0.623, 0.495, 0.366, 0.238, 0.11]
horizontal_position = 0.9
inner_outer = [[0.25, 0.5, 0.75], [1.0, 1.25]]
rho_labels = ['Inner CGM', 'Outer CGM']
ssfr_labels = ['Star forming', 'Green valley', 'Quenched']
N_min = [12., 11., 12., 11., 12., 12.]
snapfile = f'/disk04/sapple/data/samples/{model}_{wind}_{snap}.hdf5'
s = pg.Snapshot(snapfile)
redshift = s.redshift
rho_crit = float(s.cosmology.rho_crit(z=redshift).in_units_of('g/cm**3'))
cosmic_rho = rho_crit * float(s.cosmology.Omega_b)
quench = quench_thresh(redshift)
delta_fr200 = 0.25
min_fr200 = 0.25
nbins_fr200 = 5
fr200 = np.arange(min_fr200, (nbins_fr200+1)*delta_fr200, delta_fr200)
phase_space_file = f'/disk04/sapple/data/samples/{model}_{wind}_{snap}_phase_space.h5'
with h5py.File(phase_space_file, 'r') as hf:
rho_overdensity_temp_hist2d = hf['rho_delta_temp'][:]
rho_overdensity_bins = hf['rho_delta_bins'][:]
temp_bins = hf['temp_bins'][:]
plot_dir = '/disk04/sapple/cgm/absorption/ml_project/analyse_spectra/plots/'
sample_dir = f'/disk04/sapple/data/samples/'
with h5py.File(f'{sample_dir}{model}_{wind}_{snap}_galaxy_sample.h5', 'r') as sf:
gal_ids = sf['gal_ids'][:]
mass = sf['mass'][:]
ssfr = sf['ssfr'][:]
# ssfr split, all fr200
fig, ax = plt.subplots(len(lines), 3, figsize=(9.7, 13), sharey='row', sharex='col')
for l, line in enumerate(lines):
results_file = f'/disk04/sapple/data/normal/results/{model}_{wind}_{snap}_fit_lines_{line}.h5'
all_Z = []
all_T = []
all_rho = []
all_N = []
all_chisq = []
all_ids = []
for i in range(len(fr200)):
with h5py.File(results_file, 'r') as hf:
all_T.extend(hf[f'log_T_{fr200[i]}r200'][:])
all_rho.extend(hf[f'log_rho_{fr200[i]}r200'][:])
all_N.extend(hf[f'log_N_{fr200[i]}r200'][:])
all_chisq.extend(hf[f'chisq_{fr200[i]}r200'][:])
all_ids.extend(hf[f'ids_{fr200[i]}r200'][:])
all_T = np.array(all_T)
all_rho = np.array(all_rho)
all_N = np.array(all_N)
all_chisq = np.array(all_chisq)
all_ids = np.array(all_ids)
mask = (all_N > N_min[l]) * (all_chisq < chisq_lim[l])
all_T = all_T[mask]
all_delta_rho = all_rho[mask] - np.log10(cosmic_rho)
all_ids = all_ids[mask]
all_N = all_N[mask]
idx = np.array([np.where(gal_ids == j)[0] for j in all_ids]).flatten()
all_mass = mass[idx]
all_ssfr = ssfr[idx]
sf_mask, gv_mask, q_mask = ssfr_type_check(quench, all_ssfr)
for i in range(3):
ax[l][i].imshow(np.log10(rho_overdensity_temp_hist2d), extent=(rho_overdensity_bins[0], rho_overdensity_bins[-1], temp_bins[0], temp_bins[-1]),
cmap=cmap)
if line == 'H1215':
im = ax[l][0].scatter(all_delta_rho[sf_mask], all_T[sf_mask], c=all_N[sf_mask], cmap='magma', s=1, vmin=N_min[l], vmax=16)
im = ax[l][1].scatter(all_delta_rho[gv_mask], all_T[gv_mask], c=all_N[gv_mask], cmap='magma', s=1, vmin=N_min[l], vmax=16)
im = ax[l][2].scatter(all_delta_rho[q_mask], all_T[q_mask], c=all_N[q_mask], cmap='magma', s=1, vmin=N_min[l], vmax=16)
else:
im = ax[l][0].scatter(all_delta_rho[sf_mask], all_T[sf_mask], c=all_N[sf_mask], cmap='magma', s=1, vmin=N_min[l], vmax=15)
im = ax[l][1].scatter(all_delta_rho[gv_mask], all_T[gv_mask], c=all_N[gv_mask], cmap='magma', s=1, vmin=N_min[l], vmax=15)
im = ax[l][2].scatter(all_delta_rho[q_mask], all_T[q_mask], c=all_N[q_mask], cmap='magma', s=1, vmin=N_min[l], vmax=15)
for i in range(3):
ax[l][i].set_xlim(-1, 5)
ax[l][i].set_ylim(3, 7)
cax = plt.axes([horizontal_position, vertical_position[l], width, height])
cbar = fig.colorbar(im, cax=cax, label=r'${\rm log }(N / {\rm cm}^{-2})$')
cbar.set_ticks(cbar_ticks[l])
ax[l][0].annotate(plot_lines[l], xy=(x[l], 0.85), xycoords='axes fraction', fontsize=12, bbox=dict(boxstyle="round", fc="w", lw=0.75))
if l == 0:
for i in range(3):
ax[l][i].set_title(ssfr_labels[i])
if l == len(lines)-1:
for i in range(3):
ax[l][i].set_xlabel(r'${\rm log }\Delta$')
ax[l][0].set_yticks([3, 4, 5, 6, 7])
else:
ax[l][0].set_yticks([4, 5, 6, 7])
ax[l][0].set_ylabel(r'${\rm log } (T / {\rm K})$')
fig.subplots_adjust(wspace=0., hspace=0.)
plt.savefig(f'{plot_dir}{model}_{wind}_{snap}_deltaTN_ssfr_split_chisqion.png')
plt.close()
| [
"sarahappleby20@gmail.com"
] | sarahappleby20@gmail.com |
27d97928b393f307f4e44f2cc3e0f270f71ffb57 | f1dc351b5e493bb4480f21b3a7704b9a56bb7e47 | /lego/apps/restricted/tests/test_utils.py | 30c36d42e11672b18b4bc8b8a7b26ee54bce7396 | [
"MIT"
] | permissive | andrinelo/lego | 8437d830f2b534687687d302e78ab5d34172a81b | 9b53c8fe538d9107b980a70e2a21fb487cc3b290 | refs/heads/master | 2020-03-10T01:56:41.997044 | 2018-04-11T16:09:41 | 2018-04-11T16:09:41 | 129,123,416 | 0 | 0 | MIT | 2018-04-11T16:34:22 | 2018-04-11T16:34:22 | null | UTF-8 | Python | false | false | 1,246 | py | from django.conf import settings
from lego.apps.restricted.parser import EmailParser, ParserMessageType
from lego.apps.restricted.utils import get_mail_token
from lego.utils.test_utils import BaseTestCase
from .utils import read_file
class EmailTokenTestCase(BaseTestCase):
def test_parse_valid_message(self):
"""Try to parse a valid message and make sure ve remove the token payload"""
raw_message = read_file(f'{settings.BASE_DIR}/apps/restricted/fixtures/emails/valid.txt')
parser = EmailParser(raw_message, 'test@test.com', ParserMessageType.STRING)
message = parser.parse()
payloads = len(message.get_payload())
token = get_mail_token(message)
self.assertEquals('test_token', token)
self.assertEquals(len(message.get_payload()), payloads - 1)
def test_parse_message_no_token(self):
"""Parsing a message with no token has no effect, the function returns None"""
raw_message = read_file(f'{settings.BASE_DIR}/apps/restricted/fixtures/emails/no_token.txt')
parser = EmailParser(raw_message, 'test@test.com', ParserMessageType.STRING)
message = parser.parse()
token = get_mail_token(message)
self.assertIsNone(token)
| [
"eirik@sylliaas.no"
] | eirik@sylliaas.no |
829f0239757ec9d128bbd27819f875217a449fd9 | f59b30d52433903ef8cd0a15db8ae0287c89d4e2 | /Python/libraries/recognizers-number/recognizers_number/number/__init__.py | fcdd5ac467fff37e2a9dafd4c8d5781da2912f02 | [
"MIT"
] | permissive | tellarin/Recognizers-Text | 4965c928bcbe6bbd83ec15441ab880239b6370f9 | ff019a69e9cb64de862c94b08125baaaf832ed25 | refs/heads/master | 2022-11-22T10:56:13.482434 | 2019-12-16T17:30:41 | 2019-12-16T17:30:41 | 96,207,365 | 2 | 0 | MIT | 2019-12-17T05:50:58 | 2017-07-04T10:43:16 | C# | UTF-8 | Python | false | false | 249 | py | from .models import *
from .extractors import *
from .parsers import *
from .english import *
from .spanish import *
from .chinese import *
from .french import *
from .japanese import *
from .number_recognizer import *
from .parser_factory import *
| [
"tellarin@gmail.com"
] | tellarin@gmail.com |
fb0b9424ecde134faf0417e0c5e185342354c25b | 53e0b0616ece7867b1d37d755fd034e5b3d5ebe5 | /Easy/937. Reorder Data in Log Files/solution (1).py | 6f88cdf8f90632966920efaff690919c9bae4d7f | [
"MIT"
] | permissive | czs108/LeetCode-Solutions | a7a29b90ad330d8d4bd73b5d0d243dc5b4121bc9 | fc4ef8aed90614e2e4ad39fa1c9eec5881b7b5f5 | refs/heads/master | 2023-03-03T09:55:51.045837 | 2023-02-20T23:39:15 | 2023-02-20T23:39:15 | 237,709,633 | 4 | 1 | null | null | null | null | UTF-8 | Python | false | false | 356 | py | # 937. Reorder Data in Log Files
class Solution:
# Sorting by Keys
def reorderLogFiles(self, logs: list[str]) -> list[str]:
def get_key(log: list[str]) -> tuple:
id, content = log.split(" ", maxsplit=1)
return (0, content, id) if content[0].isalpha() else (1, None, None)
return sorted(logs, key=get_key) | [
"chenzs108@outlook.com"
] | chenzs108@outlook.com |
0aec8b543a666ebec07ee8d1f7de9f7df6ae0aa3 | 6710c52d04e17facbc9fb35a7df313f7a2a7bd53 | /0496. Next Greater Element I.py | 81a83b3a6afa832fca1c54f9dee831ff8ecb2cb3 | [] | no_license | pwang867/LeetCode-Solutions-Python | 535088fbe747a453360457728cc22cf336020bd2 | 188befbfb7080ba1053ee1f7187b177b64cf42d2 | refs/heads/master | 2022-11-13T16:20:28.211707 | 2020-06-28T06:01:14 | 2020-06-28T06:01:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,903 | py | # use descreasing stack, time/space O(n)
class Solution(object):
def nextGreaterElement(self, findNums, nums):
"""
:type findNums: List[int]
:type nums: List[int]
:rtype: List[int]
"""
# findNums is a subset of nums
# using stack
stack = [] # numbers stored inside stack will be descending
next_greater = {} # {number in findNums: its nextGreaterElement}
for num in nums:
while stack and stack[-1] < num:
next_greater[stack.pop()] = num
stack.append(num)
ans = []
for num in findNums: # subset
ans.append(next_greater.get(num, -1))
return ans
"""
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.
The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.
Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
For number 1 in the first array, the next greater number for it in the second array is 3.
For number 2 in the first array, there is no next greater number for it in the second array, so output -1.
Example 2:
Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
For number 2 in the first array, the next greater number for it in the second array is 3.
For number 4 in the first array, there is no next greater number for it in the second array, so output -1.
Note:
All elements in nums1 and nums2 are unique.
The length of both nums1 and nums2 would not exceed 1000.
"""
| [
"wzhou007@ucr.edu"
] | wzhou007@ucr.edu |
0b1491be7cb19a099088b52747a39f61a0ac1a3f | 951a84f6fafa763ba74dc0ad6847aaf90f76023c | /PythonLearning/c15.py | 6564d10808d0f33742e95d0a46ea1ab568e6afe4 | [] | no_license | SakuraGo/leetcodepython3 | 37258531f1994336151f8b5c8aec5139f1ba79f8 | 8cedddb997f4fb6048b53384ac014d933b6967ac | refs/heads/master | 2020-09-27T15:55:28.353433 | 2020-02-15T12:00:02 | 2020-02-15T12:00:02 | 226,550,406 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 276 | py | import t.t1.c9
print("~~~~~~~~~C15~~~~~~~~~")
print("name:",__name__) ##名字
print("package:"+ (__package__ or "package不属于任何包")) ## 所属包
print("doc:",__doc__) ## 模块注释
print("file:",__file__) ##物理路径
vvv = 23 if 3>5 else 35
print(vvv) | [
"452681917@qq.com"
] | 452681917@qq.com |
fda206922f8d0287b1b159050f65d979846ea8ad | c9f54e1a2e11a033b53b4f12564c7b87c5ce1a4a | /one_time/hidden_units.py | 0788a78f5a75634b5a6eb773e44b1b85d12ced5d | [] | no_license | mikewycklendt/dcadventures | b2e5e38ed53a698bb3c18c5b332df424540a18e3 | 542f90c3cce859416de14e40bdebf6a8cddcf67a | refs/heads/master | 2023-06-10T17:00:33.380125 | 2021-06-21T20:38:25 | 2021-06-21T20:38:25 | 290,849,079 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 572 | py |
@app.route('/table/db')
def table_db_columns_create():
name = 'Time Rank'
entry = Unit(time=True, name=name, hide=True )
db.session.add(entry)
db.session.commit()
name = 'Distance Rank'
entry = Unit(distance=True, name=name, hide=True )
db.session.add(entry)
db.session.commit()
name = 'Speed Rank'
entry = Unit(speed=True, name=name, hide=True )
db.session.add(entry)
db.session.commit()
results = db.session.query(Unit).filter_by(hide=True).all()
for result in results:
print (result.id)
print (result.name)
return ('Unit Ranks db added')
| [
"mikewycklendt@gmail.com"
] | mikewycklendt@gmail.com |
d18a5ff31839e9598493723bd5c0347c58ecfd44 | ccf94dcb6b1500fcbbd56964ae8c4832a496b8b3 | /python/baiduads-sdk-auto/test/test_get_media_packages_response_wrapper.py | 7431508715bab9f2bef9fbf745fb5efc555b45d5 | [
"Apache-2.0"
] | permissive | baidu/baiduads-sdk | 24c36b5cf3da9362ec5c8ecd417ff280421198ff | 176363de5e8a4e98aaca039e4300703c3964c1c7 | refs/heads/main | 2023-06-08T15:40:24.787863 | 2023-05-20T03:40:51 | 2023-05-20T03:40:51 | 446,718,177 | 16 | 11 | Apache-2.0 | 2023-06-02T05:19:40 | 2022-01-11T07:23:17 | Python | UTF-8 | Python | false | false | 1,104 | py | """
dev2 api schema
'dev2.baidu.com' api schema # noqa: E501
Generated by: https://openapi-generator.tech
"""
import sys
import unittest
import baiduads
from baiduads.common.model.api_response_header import ApiResponseHeader
from baiduads.searchfeed.model.get_media_packages_response_wrapper_body import GetMediaPackagesResponseWrapperBody
globals()['ApiResponseHeader'] = ApiResponseHeader
globals()['GetMediaPackagesResponseWrapperBody'] = GetMediaPackagesResponseWrapperBody
from baiduads.searchfeed.model.get_media_packages_response_wrapper import GetMediaPackagesResponseWrapper
class TestGetMediaPackagesResponseWrapper(unittest.TestCase):
"""GetMediaPackagesResponseWrapper unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testGetMediaPackagesResponseWrapper(self):
"""Test GetMediaPackagesResponseWrapper"""
# FIXME: construct object with mandatory attributes with example values
# model = GetMediaPackagesResponseWrapper() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
| [
"jiangyuan04@baidu.com"
] | jiangyuan04@baidu.com |
14145e52b961975903bfd44a7d99be0c2f3207d0 | cf149421eb604826dc4757bc4fa1ac524b44476b | /pyscene/gradient/by_value.py | 1581fa003c44ce1b7fb7437f2d07eb90cef50cef | [] | no_license | Windspar/PyScene | 60e903106905b6eaff640dfde08d8bb447353ab5 | 004a274326f1aac06da04e3f5a663374da618a64 | refs/heads/master | 2021-09-07T11:05:41.362873 | 2018-02-22T01:31:12 | 2018-02-22T01:31:12 | 113,268,309 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,915 | py | import numpy as np
import pygame
from .base import RGBA_FORMULA, pure_color
class HSL:
H = 0
HUE = 0
S = 1
SAT = 1
SATURATION = 1
L = 2
LUM = 2
LIGHT = 2
LIGHTNESS = 2
class RGB:
R = 0
RED = 0
G = 1
GREEN = 1
B = 2
BLUE = 2
class HSV:
H = 0
HUE = 0
S = 1
SAT = 1
SATURATION = 1
V = 2
VALUE = 2
def by_value(horizontal, value, color, value_begin, value_end, decimal, flip):
length = value_end - value_begin
if horizontal:
surface = pygame.Surface((1, length))
else:
surface = pygame.Surface((length, 1))
surface = surface.convert_alpha()
surface_array = pygame.surfarray.pixels2d(surface)
np_color = color
for val in range(value_begin, value_end):
pos = val - value_begin
np_color[value] = val
if horizontal:
surface_array[0][pos] = decimal(np_color)
else:
surface_array[pos][0] = decimal(np_color)
if flip:
if horizontal:
surface = pygame.transform.flip(surface, False, True)
else:
surface = pygame.transform.flip(surface, True, False)
return surface
def hsl_by_value(horizontal, value, color, offset_begin, offset_end, flip=False):
color = np.array(pure_color(color).hsla)
base = int(color[value] + 0.5)
if base - offset_begin < 0:
offset_begin = base
else:
offset_begin = base - offset_begin
if value == 0:
if base + offset_end > 360:
offset_end = 360 - base
else:
offset_end = base + offset_end
else:
if base + offset_end > 100:
offset_end = 100 - base
else:
offset_end = base + offset_end
def decimal(color):
pcolor = pygame.Color(0,0,0)
pcolor.hsla = color
return np.sum(np.array(pcolor, int) << RGBA_FORMULA)
return by_value(horizontal, value, color, offset_begin, offset_end, decimal, flip)
def hsv_by_value(horizontal, value, color, offset_begin, offset_end, flip=False):
color = np.array(pure_color(color).hsva)
base = color[value]
if base - offset_begin < 0:
offset_begin = base
if value == 0:
if base + offset_end > 360:
offset_end = 360 - base
else:
if base + offset_end > 100:
offset_end = 100 - base
def decimal(color):
pcolor = pygame.Color(0,0,0)
pcolor.hsva = color
return np.sum(np.array(pcolor, int) << RGBA_FORMULA)
return by_value(horizontal, value, color, offset_begin, offset_end, decimal, flip)
def rgb_by_value(horizontal, value, color, value_begin, value_end, flip=False):
color = np.array(pure_color(color))
def decimal(color):
return np.sum(color.astype(int) << RGBA_FORMULA)
return by_value(horizontal, value, color, value_begin, value_end, decimal, flip)
| [
"kdrakemagi@gmail.com"
] | kdrakemagi@gmail.com |
6bb9e9709cd46995967059850e6158cce9302c2d | 24381845fe5e8b8a774d74911e2f07bcd1a00190 | /azure-iot-provisioning-servicesdk/azure/iot/provisioning/servicesdk/protocol/models/__init__.py | 87d86af26eeff8f238fba3eec4bb42462abddc84 | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | permissive | noopkat/azure-iot-sdk-python-preview | 94b3b29497b80e1dac6471ae906d8491f018b12d | f51733e9d3424c33ed86d51e214b20c843716763 | refs/heads/master | 2020-04-30T03:07:37.445782 | 2019-03-18T18:42:15 | 2019-03-18T18:42:15 | 176,579,084 | 6 | 0 | MIT | 2019-03-19T18:53:43 | 2019-03-19T18:53:43 | null | UTF-8 | Python | false | false | 4,016 | py | # coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
try:
from .provisioning_service_error_details_py3 import (
ProvisioningServiceErrorDetails,
ProvisioningServiceErrorDetailsException,
)
from .device_capabilities_py3 import DeviceCapabilities
from .device_registration_state_py3 import DeviceRegistrationState
from .tpm_attestation_py3 import TpmAttestation
from .x509_certificate_info_py3 import X509CertificateInfo
from .x509_certificate_with_info_py3 import X509CertificateWithInfo
from .x509_certificates_py3 import X509Certificates
from .x509_ca_references_py3 import X509CAReferences
from .x509_attestation_py3 import X509Attestation
from .symmetric_key_attestation_py3 import SymmetricKeyAttestation
from .attestation_mechanism_py3 import AttestationMechanism
from .metadata_py3 import Metadata
from .twin_collection_py3 import TwinCollection
from .initial_twin_properties_py3 import InitialTwinProperties
from .initial_twin_py3 import InitialTwin
from .reprovision_policy_py3 import ReprovisionPolicy
from .custom_allocation_definition_py3 import CustomAllocationDefinition
from .individual_enrollment_py3 import IndividualEnrollment
from .enrollment_group_py3 import EnrollmentGroup
from .bulk_enrollment_operation_py3 import BulkEnrollmentOperation
from .bulk_enrollment_operation_error_py3 import BulkEnrollmentOperationError
from .bulk_enrollment_operation_result_py3 import BulkEnrollmentOperationResult
from .query_specification_py3 import QuerySpecification
except (SyntaxError, ImportError):
from .provisioning_service_error_details import (
ProvisioningServiceErrorDetails,
ProvisioningServiceErrorDetailsException,
)
from .device_capabilities import DeviceCapabilities
from .device_registration_state import DeviceRegistrationState
from .tpm_attestation import TpmAttestation
from .x509_certificate_info import X509CertificateInfo
from .x509_certificate_with_info import X509CertificateWithInfo
from .x509_certificates import X509Certificates
from .x509_ca_references import X509CAReferences
from .x509_attestation import X509Attestation
from .symmetric_key_attestation import SymmetricKeyAttestation
from .attestation_mechanism import AttestationMechanism
from .metadata import Metadata
from .twin_collection import TwinCollection
from .initial_twin_properties import InitialTwinProperties
from .initial_twin import InitialTwin
from .reprovision_policy import ReprovisionPolicy
from .custom_allocation_definition import CustomAllocationDefinition
from .individual_enrollment import IndividualEnrollment
from .enrollment_group import EnrollmentGroup
from .bulk_enrollment_operation import BulkEnrollmentOperation
from .bulk_enrollment_operation_error import BulkEnrollmentOperationError
from .bulk_enrollment_operation_result import BulkEnrollmentOperationResult
from .query_specification import QuerySpecification
__all__ = [
"ProvisioningServiceErrorDetails",
"ProvisioningServiceErrorDetailsException",
"DeviceCapabilities",
"DeviceRegistrationState",
"TpmAttestation",
"X509CertificateInfo",
"X509CertificateWithInfo",
"X509Certificates",
"X509CAReferences",
"X509Attestation",
"SymmetricKeyAttestation",
"AttestationMechanism",
"Metadata",
"TwinCollection",
"InitialTwinProperties",
"InitialTwin",
"ReprovisionPolicy",
"CustomAllocationDefinition",
"IndividualEnrollment",
"EnrollmentGroup",
"BulkEnrollmentOperation",
"BulkEnrollmentOperationError",
"BulkEnrollmentOperationResult",
"QuerySpecification",
]
| [
"noreply@github.com"
] | noopkat.noreply@github.com |
d956d330feab1a324f7948bdcbc9d48882bd40a8 | bbcce934ac20249a006580915aa61b72f8521544 | /G5_template.py | 7c966f89352d288441e458325d0c88a33e15da29 | [] | no_license | SanjuktaBhatt/G11_Projects | 6225a51cb653001af46a859ab578efba30ce7d79 | 435163bc26b759b4a185a2f4cce3d228c47cbf43 | refs/heads/main | 2023-06-19T18:58:54.684729 | 2021-07-22T08:37:56 | 2021-07-22T08:37:56 | 382,996,090 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 618 | py | import pygame
import random
pygame.init()
WHITE = (255,255,255)
DARKBLUE = (36,90,190)
LIGHTBLUE = (0,176,240)
RED = (255,0,0)
ORANGE = (255,100,0)
YELLOW = (255,255,0)
COLOR=[WHITE,DARKBLUE,LIGHTBLUE,RED,ORANGE,YELLOW]
size = (400, 400)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Project C5")
#Create "carryOn" variable and set to true
#Begin the while loop
#Iterate through each event
#Identify is user has quit
#change "carryOn" to False
discolight_color=random.choice(COLOR)
screen.fill(discolight_color)
pygame.display.flip()
pygame.quit()
| [
"noreply@github.com"
] | SanjuktaBhatt.noreply@github.com |
f25b22df40286f6b6c2b5f938e282191d7e00fa2 | 313110e3a0d01adb562e40f73d9c6fc32c74e0ca | /inventory/migrations/0004_auto_20210327_0821.py | be019a0d3e9d95fa0f6820c8f05625773f08f086 | [] | no_license | prabaldeshar/erp-project | e911ac447aab9ede39567fb82275bbbf0357932e | 31762cf765d1aee21623033c963147d69219ba56 | refs/heads/main | 2023-03-29T19:29:18.689599 | 2021-04-07T15:19:14 | 2021-04-07T15:19:14 | 344,389,239 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 408 | py | # Generated by Django 3.1.7 on 2021-03-27 08:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('inventory', '0003_auto_20210310_1630'),
]
operations = [
migrations.AlterField(
model_name='productcategory',
name='parent',
field=models.IntegerField(blank=True, null=True),
),
]
| [
"prabaldeshar@gmail.com"
] | prabaldeshar@gmail.com |
44168503a255ef0073c8a1d1da7327f6fbd4ce70 | 78f54f911d47019da0deeeb6579c7e9e65bb8d21 | /src/process/models/base/operation/DefinitionBase.py | c35aa1747e8905cbff9dd2e3bdbd0e7a6be6e07e | [
"MIT"
] | permissive | jedicontributors/pythondataintegrator | 02f8ae1a50cf5ddd85341da738c24aa6a320c442 | 3e877b367ab9b20185476128ec053db41087879f | refs/heads/main | 2023-06-15T07:37:13.313988 | 2021-07-03T15:46:43 | 2021-07-03T15:46:43 | 354,021,102 | 0 | 0 | MIT | 2021-07-03T15:46:44 | 2021-04-02T13:03:12 | Python | UTF-8 | Python | false | false | 849 | py | from models.base.EntityBase import EntityBase
from infrastructor.json.BaseConverter import BaseConverter
@BaseConverter.register
class DefinitionBase(EntityBase):
def __init__(self,
Name: str = None,
Version: int = None,
Content: str = None,
IsActive: bool = None,
DataOperations = [],
DataIntegrations = [],
DataOperationJobExecutions = [],
*args, **kwargs):
super().__init__(*args, **kwargs)
self.DataOperationJobExecutions = DataOperationJobExecutions
self.DataIntegrations = DataIntegrations
self.DataOperations = DataOperations
self.Name: str = Name
self.Version: int = Version
self.Content: str = Content
self.IsActive: bool = IsActive
| [
"ahmetcagriakca@gmail.com"
] | ahmetcagriakca@gmail.com |
70fef156091609d8d1b6faba71b19d8d7e5d3ee8 | b8d208679a3a3b16960eecd92dd3dd5ce78f8e7f | /setup.py | dac804bcf98486f6b1a18f1dc210f95a471dea12 | [
"BSD-3-Clause"
] | permissive | jessicalumian/distillerycats | e509bdd5fbb8062931938d7f952058d0c5775851 | 67ac76b21397255af604d8bf4aad2eb7889dc88c | refs/heads/main | 2023-05-03T22:10:44.999734 | 2021-05-24T16:14:36 | 2021-05-24T16:14:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,905 | py | from setuptools import setup, find_packages
# read the contents of your README file
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, "README.md"), encoding="utf-8") as f:
long_description = f.read()
CLASSIFIERS = [
"Environment :: Console",
"Environment :: MacOS X",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: BSD License",
"Natural Language :: English",
"Operating System :: POSIX :: Linux",
"Operating System :: MacOS :: MacOS X",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Topic :: Scientific/Engineering :: Bio-Informatics",
]
setup(
name = 'distillerycats',
description="Find disease associations across metagenomes with k-mers using sourmash, and then recover pangenomic accessory elements using spacegraphcats.",
url="https://github.com/dib-lab/distillerycats",
author="Taylor Reiter, N. Tessa Pierce and C. Titus Brown",
author_email="tereiter@ucdavis.edu,ntpierce@gmail.com,titus@idyll.org",
license="BSD 3-clause",
packages = find_packages(),
classifiers = CLASSIFIERS,
entry_points = {'console_scripts': ['distillerycats = distillerycats.__main__:main']},
include_package_data=True,
package_data = { "distillerycats": ["Snakefile", "*.yaml", "*.yml", "*.ipynb"] },
setup_requires = [ "setuptools>=38.6.0",
'setuptools_scm',
'setuptools_scm_git_archive',
'pytest-runner'],
use_scm_version = {"write_to": "distillerycats/version.py"},
install_requires = ['snakemake>=6.3.0', 'click>=8', 'pandas'],
tests_require=["pytest>=5.1.2", "pytest-dependency"],
long_description=long_description,
long_description_content_type="text/markdown",
)
| [
"ntpierce@gmail.com"
] | ntpierce@gmail.com |
781083edd3afb79a9b9fbac3d4156eaf5378e226 | f16886292a92b113f901bfd757a909854e713431 | /dd/__init__.py | 926c384fe50d4d3bbbeaa08fb2ee3e041c13208c | [] | no_license | WilliamMayor/distorteddecade | a224132aa4396d26b740415bac9ea4830c4c0c0c | 9e6cfc651a44eb1f32ba300f8954f6694de87bf1 | refs/heads/master | 2021-01-02T15:35:12.418862 | 2015-06-06T18:13:51 | 2015-06-06T18:13:51 | 25,695,400 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 798 | py | import os
from flask import Flask
from blueprints import admin, public
from assets import assets
from login import manager
from models import db, bcrypt
import logging
from logging import StreamHandler
def create_app():
app = Flask(__name__)
file_handler = StreamHandler()
app.logger.setLevel(logging.DEBUG)
app.logger.addHandler(file_handler)
app.config.from_object('dd.config')
for k in app.config:
v = os.environ.get(k, None)
if v is not None:
app.config[k] = v
app.config['SQLALCHEMY_DATABASE_URI'] = app.config['DATABASE_URL']
assets.init_app(app)
manager.init_app(app)
db.init_app(app)
bcrypt.init_app(app)
app.register_blueprint(admin, url_prefix='/admin')
app.register_blueprint(public)
return app
| [
"mail@williammayor.co.uk"
] | mail@williammayor.co.uk |
8725d49f69e07e80693171c657e35320b01b2f6d | a712ec2940aa6a2fa51da6392ae1fb7b1ba8ce40 | /setup.py | b77b6ede0f4085fce861f415b26ea1e28f1756c1 | [] | no_license | adam139/emc.policy | 511366acd3cd70a26e12bdecae8e890704362340 | bace3cec2cf7dbcf387d34ac3b22799e650e5dd0 | refs/heads/master | 2022-05-08T21:35:15.736156 | 2022-01-10T09:05:43 | 2022-01-10T09:05:43 | 47,091,992 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,376 | py | from setuptools import setup, find_packages
import os
version = '2.0'
setup(name='emc.policy',
version=version,
description="A plone5 website policy package for emc project",
long_description=open("README.txt").read() + "\n" +
open(os.path.join("docs", "HISTORY.txt")).read(),
# Get more strings from
# http://pypi.python.org/pypi?:action=list_classifiers
classifiers=[
"Framework :: Plone",
"Programming Language :: Python",
],
keywords='python plone',
author='Adam tang',
author_email='568066794@qq.com',
url='https://github.com/collective/',
license='GPL',
packages=find_packages(exclude=['ez_setup']),
namespace_packages=['emc'],
include_package_data=True,
zip_safe=False,
install_requires=[
'setuptools',
'Products.CMFPlone',
'collective.autopermission',
'z3c.jbot',
'z3c.unconfigure',
'collective.wtf',
'collective.monkeypatcher',
'collective.filepreviewbehavior',
# -*- Extra requirements: -*-
],
extras_require={
'test': ['plone.app.testing',]
},
entry_points="""
# -*- Entry points: -*-
[z3c.autoinclude.plugin]
target = plone
""",
)
| [
"yuejun.tang@gmail.com"
] | yuejun.tang@gmail.com |
384d4adc895d76bbf6dea63d7d3703e61a53f8c6 | 7262a3c12297e853f72d0c0db2c9ca0f65d2115b | /Automation/page_locators/imdb.py | 2bdd74bb839a1086727e0fa301c734f0b06e0fe6 | [] | no_license | pavankumarag/navi | 6ae77b1d26a8e2ee31ee18ea35d54823bd26a1cb | 7a05ea1e3cfe3d339cbb3047948d7d370739fc51 | refs/heads/master | 2021-01-02T06:57:23.181001 | 2020-02-14T06:17:53 | 2020-02-14T06:17:53 | 239,538,111 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 597 | py | from selenium.webdriver.common.by import By
class Imdb:
IMDB_SEARCH = By.XPATH, "//input[@placeholder='Search IMDb']"
SELECT_DIRECTOR = By.XPATH, "//li//div[text()='Steven Spielberg']"
GET_DIRECTION_DETAILS = By.XPATH, "//td[contains(@class, 'name-overview')]//a[@href='#director']"
GET_PRODUCER_DETAILS = By.XPATH, "//td[contains(@class, 'name-overview')]//a[@href='#producer']"
ALL_MOVIES = By.XPATH, "//div[@data-category='director']//following-sibling::div"
EVERY_MOVIE_NAME =By.XPATH, "//div[@data-category='director']//following-sibling::div/div[contains(@class,'filmo-row')][%d]/b/a" | [
"pavan.govindraj@nutanix.com"
] | pavan.govindraj@nutanix.com |
6e7eebbf4a4ec6e46a966d3ee419978748a8cb27 | 529792835d99e8f19afbc123a09b3c7920a024d5 | /space_invaders/__main__.py | 280d82477400ca6ab3cd2e7b5db605118bf665a9 | [] | no_license | tt-n-walters/python-thursday | fe39213f5ba267fbf9c501f1ea925253a034a8d4 | 6aaff5b5e3cb567b75a7ca8e5ad422303f54060e | refs/heads/master | 2020-12-23T21:22:42.112977 | 2020-03-12T19:08:12 | 2020-03-12T19:08:12 | 237,278,906 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 981 | py | import arcade
from player import Player
class SpaceInvaders(arcade.Window):
def __init__(self):
super().__init__(800, 600, "Space Invaders")
self.player = Player(self.width / 2, self.height * 0.1)
def on_key_press(self, symbol, modifiers):
if symbol == arcade.key.ESCAPE:
arcade.close_window()
if symbol == arcade.key.A:
self.player.move_left()
if symbol == arcade.key.D:
self.player.move_right()
def on_key_release(self, symbol, modifiers):
if symbol == arcade.key.A:
self.player.stop()
if symbol == arcade.key.D:
self.player.stop()
def on_draw(self):
arcade.start_render()
self.player.draw()
def on_update(self, time):
self.player.update()
if __name__ == "__main__":
from sys import argv
from os import chdir
chdir(argv[0].rpartition("/")[0])
SpaceInvaders()
arcade.run()
| [
"nico.walters@techtalents.es"
] | nico.walters@techtalents.es |
00fccce3734b11b4909c02dc597c81c60d9c8e91 | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_014/ch164_2020_06_22_14_35_35_738838.py | 0ade4746644b61691e840b595e7b7a32fd220af8 | [] | no_license | gabriellaec/desoft-analise-exercicios | b77c6999424c5ce7e44086a12589a0ad43d6adca | 01940ab0897aa6005764fc220b900e4d6161d36b | refs/heads/main | 2023-01-31T17:19:42.050628 | 2020-12-16T05:21:31 | 2020-12-16T05:21:31 | 306,735,108 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 290 | py | def traduz (lista_ing, ing_para_port):
lista_port = []
i = 0
while i < len(lista_ing):
for palavra_ing in ing_para_port.keys():
if palavra_ing == lista_ing[i]:
lista_port.append(ing_para_port[palavra_ing])
i += 1
return lista_port | [
"you@example.com"
] | you@example.com |
90b0873478e89f1b576399d52041d83d4f8238dd | 163bbb4e0920dedd5941e3edfb2d8706ba75627d | /Code/CodeRecords/2962/60632/270495.py | 42c9a572b669dda8b1dd54444c3567f603ecce28 | [] | no_license | AdamZhouSE/pythonHomework | a25c120b03a158d60aaa9fdc5fb203b1bb377a19 | ffc5606817a666aa6241cfab27364326f5c066ff | refs/heads/master | 2022-11-24T08:05:22.122011 | 2020-07-28T16:21:24 | 2020-07-28T16:21:24 | 259,576,640 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 284 | py | n, p = map(int, input().split(' '))
key = list(map(str, input().split(' ')))
for i in range(n):
tmp = key[i][-3:]
key[i] = [ord(tmp[j])-ord('A') for j in range(3)]
val = 0
for j in range(3):
val += key[i][2-j] * int(pow(32, j))
key[i] = val % p
print(key)
| [
"1069583789@qq.com"
] | 1069583789@qq.com |
67d4c41d2f15933810af28140432f8c215daa312 | 8acbd7fcfe1bcf94e4e895e58ac5c81f8ed13741 | /logindjango/urls.py | 4c3c68c03abc8254f5dada8c9dfad97689615c85 | [] | no_license | Rajangupta09/School-beta | 440af5d5d078a46036cfa3c50865f980c5ff1ace | 3ca6ca9992d2b47bcfe1762beb8c88609d519ea5 | refs/heads/master | 2022-12-07T19:42:19.562804 | 2020-08-04T09:53:04 | 2020-08-04T09:53:04 | 284,509,100 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,475 | py |
from django.contrib import admin
from django.urls import path
from django.conf.urls import include
from django.conf import settings
from django.conf.urls.static import static
import accounts.views as account_view
urlpatterns = [
path('admin/', admin.site.urls),
path('', account_view.login, name="login"),
path('auth/', include('accounts.urls')),
path('studentForm/', include('form.urls')),
path('marks/', include('markssection.urls')),
path('dashboard/', include('dashboard.urls')),
path('empForm/', include('employeeform.urls')),
path('classForm/', include('classform.urls')),
path('attendence/', include('attendence.urls')),
path('homework/', include('homework.urls')),
path('notice/', include('notice.urls')),
path('thought/', include('dailythought.urls')),
path('newsletter/', include('newsletter.urls')),
path('schoolinfo/', include('schoolinfo.urls')),
path('holiday/', include('holiday.urls')),
path('fees/', include('fees.urls')),
path('feeReport/', include('feereport.urls')),
path('transport/', include('transport.urls')),
path('visitor/', include('visitors.urls')),
path('leave/', include('leave.urls')),
path('gallery/', include('gallery.urls')),
path('timetable/', include('timetable.urls')),
path('api/', include('rest_api.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| [
"rjnkumar05@gmail.com"
] | rjnkumar05@gmail.com |
2f520bd3b6b313173985892d867dcf64be36af6a | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /third_party/WebKit/Source/build/scripts/make_media_features.py | 54d96901113dd71893195d9d4389b8f107851a99 | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | Python | false | false | 1,324 | py | #!/usr/bin/env python
# Copyright 2014 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 media_feature_symbol
import in_generator
import template_expander
import name_utilities
import sys
class MakeMediaFeaturesWriter(in_generator.Writer):
defaults = {
'Conditional': None, # FIXME: Add support for Conditional.
'RuntimeEnabled': None,
'ImplementedAs': None,
}
filters = {
'symbol': media_feature_symbol.getMediaFeatureSymbolWithSuffix(''),
'to_macro_style': name_utilities.to_macro_style,
}
default_parameters = {
'namespace': '',
'export': '',
}
def __init__(self, in_file_path):
super(MakeMediaFeaturesWriter, self).__init__(in_file_path)
self._outputs = {
('MediaFeatures.h'): self.generate_header,
}
self._template_context = {
'namespace': '',
'export': '',
'entries': self.in_file.name_dictionaries,
}
@template_expander.use_jinja('MediaFeatures.h.tmpl', filters=filters)
def generate_header(self):
return self._template_context
if __name__ == '__main__':
in_generator.Maker(MakeMediaFeaturesWriter).main(sys.argv)
| [
"enrico.weigelt@gr13.net"
] | enrico.weigelt@gr13.net |
193d45a64aa8c10d15e3bff1fe15b1fdea4b440c | c167d1618c1df50de21238a00d4168505dce868f | /0x0A-python-inheritance/6-base_geometry.py | f666928f53bb510d1e7df03101098d47fd1de7a1 | [] | no_license | keen-s/alx-higher_level_programming | 8201845d7142bfdcbfa603fa3d135e3fabbe2bf2 | 7a70051b8cf89441f034c4886f51a99ae85e4f34 | refs/heads/main | 2023-08-12T18:23:30.985481 | 2021-10-18T20:48:29 | 2021-10-18T20:48:29 | 403,688,815 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 259 | py | #!/usr/bin/python3
"""A class based on 5-base_geometry.py"""
class BaseGeometry:
"""A class"""
def area(self):
""" A public instance method that raises
an exception
"""
raise Exception("area() is not implemented")
| [
"keen_spe@DESKTOP-C7LRBS8.localdomain"
] | keen_spe@DESKTOP-C7LRBS8.localdomain |
c7d25be25b084123be9f503b4dc69a84f322d9d1 | d76e8c5e7853b145b2c084975cadd0e4f29943f1 | /lib/bloggertool/commands/browse.py | fd3cde8a0673dbc98206c4d686146d1b6099ede0 | [
"MIT"
] | permissive | asvetlov/bloggertool | 57ab7408d6a7624f7d44ccc60de3761e7524935c | 7c145f66aa22f4124e8b1d198bc93ff703fa72b4 | refs/heads/master | 2021-03-12T20:16:56.014541 | 2015-03-29T09:54:36 | 2015-03-29T09:54:36 | 19,406,280 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,879 | py | # commands/browse.py
# Copyright (C) 2011-2014 Andrew Svetlov
# andrew.svetlov@gmail.com
#
# This module is part of BloggerTool and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from textwrap import dedent
import webbrowser
from bloggertool.notify import Notifier
from bloggertool.str_util import T, a
from bloggertool.exceptions import ConfigError
from .basecommand import BaseCommand
class OpenCommand(BaseCommand):
NAME = 'open'
HELP = "Open browser with local html output for post."
DESCR = dedent("""\
Open browser with local html output for post
""")
require_interactive = True
@classmethod
def fill_parser(cls, parser):
parser.add_argument('file', help="md file to link with")
parser.add_argument('--always', default=False, action='store_true',
help="Always regenerate html files")
parser.add_argument('--serve', default=False, action='store_true',
help=T("""
Loop forever waiting for source file change,
updating html as reaction
"""))
def __init__(self, args):
self.file = args.file
self.always = args.always
self.serve = args.serve
def run(self):
config = self.config
post = config.post_by_path(self.file)
if not post:
self.log.error("MD file '%s' is not registered", self.file)
return
if config.interactive is None and self.serve:
raise ConfigError(a("""
Cannot process --serve in interactive mode.
Specify either --force or --no-clobber
"""))
post.refresh_html(self.always)
abs_path = config.fs.abs_path(post.nice_html_path)
self.log.info("Opening '%s'", abs_path)
webbrowser.open('file:///' + abs_path)
if self.serve:
notifier = Notifier(config.fs.root)
notifier.add(config.fs.abs_path(post.file),
post.refresh_html, force=False)
self.log.info(T("Run serve loop"))
notifier.loop()
class ROpenCommand(BaseCommand):
NAME = 'ropen'
HELP = "Open browser with remote html output for post."
DESCR = dedent("""\
Open browser with remote html output for post
""")
@classmethod
def fill_parser(cls, parser):
parser.add_argument('file', help="md file to link with")
def __init__(self, args):
self.file = args.file
def run(self):
config = self.config
post = config.post_by_path(self.file)
if not post:
self.log.error("MD file '%s' is not registered", self.file)
return
self.log.info("Opening '%s'", post.link)
webbrowser.open(post.link)
| [
"andrew.svetlov@gmail.com"
] | andrew.svetlov@gmail.com |
da98e4bb53e067d4f151787d8ffd0e33a97109ae | f23fda62b1335182e0a59764c83680401c32c1b8 | /API_EX_PrtyPrinted/settings.py | 699115e70e992756d10182dcfdfe325d5ba38cd4 | [] | no_license | brrbaral/DjagoRESTLanguages | 2798aa087e0607ed5afe68141ec80965a7f47c36 | 07601986ce5976268bb86d8d7e8e4e4fecd912ea | refs/heads/master | 2023-01-10T16:53:06.515318 | 2020-11-11T03:52:46 | 2020-11-11T03:52:46 | 311,851,241 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,309 | py | """
Django settings for API_EX_PrtyPrinted project.
Generated by 'django-admin startproject' using Django 2.0.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '!459cd@qoo2xvc+^z1teyz9@p*2ying(^cf=kdh@bp7+7)eh@o'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'languages',
'rest_framework',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'API_EX_PrtyPrinted.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'API_EX_PrtyPrinted.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
REST_FRAMEWORK={
#THIS IS A TUPLE SO , AFTER ITEMS
'DEFAULT_PERMISSION_CLASSES':('rest_framework.permissions.IsAuthenticatedOrReadOnly',)
}
| [
"brr.baral@gmail.com"
] | brr.baral@gmail.com |
a8dde743a40b22f756722ef65d395379ba3c280d | f1c20d0836f4815b81c895ffe22a29005db3746d | /backend/main/wsgi.py | 55aa3e2e2e988c5c5affb5d4806a1c97c8ae1eb1 | [] | no_license | pavelm2007/leadersofdigital_2020_04 | 6ceacf0858ea46bd73c5a0e0ab120cae802e85bd | 0132d1b3361518b109b0632daaf13ed8e849192d | refs/heads/main | 2023-04-04T21:12:54.890040 | 2021-04-17T20:37:02 | 2021-04-17T20:37:02 | 358,649,475 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 398 | py | """
WSGI config for main project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings.production")
application = get_wsgi_application()
| [
"pavelm2007@yandex.ru"
] | pavelm2007@yandex.ru |
cef6047ec940823cb0576c6bf724bb9d4e71612f | 549d11c89ce5a361de51f1e1c862a69880079e3c | /feiji/testss.py | 0a2fa1c42bfbdea0b87652b6085ffd6b503f8b1f | [] | no_license | BaldSuperman/workspace | f304845164b813b2088d565fe067d5cb1b7cc120 | 4835757937b700963fdbb37f75a5e6b09db97535 | refs/heads/master | 2020-08-01T15:32:02.593251 | 2019-09-26T08:04:50 | 2019-09-26T08:04:50 | 211,034,750 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 172 | py | import pygame
from feiji.plane_Sprite import *
screen = pygame.display.set_mode(SCREEN_RECT.size)
while True:
for even in pygame.event.get():
print(even.type)
| [
"you@example.com"
] | you@example.com |
a89d752f30f6424ebd44fad015341ca5ff2fb94b | 178766cfa5b4a4785a900595278889ed8a828c90 | /blog/migrations/0011_rename_user_author_author.py | 7c1813b1f639eb0fbbb4c61c013dc6d2806ec67a | [] | no_license | ShahadatShuvo/django_blog_app | 0a48fd03b1ab585a08ae41bea40dd905771f7093 | 13c5d98c73fd65ad7353d83ca065344a2811c694 | refs/heads/master | 2023-06-05T08:11:40.479944 | 2021-06-26T18:55:12 | 2021-06-26T18:55:12 | 376,760,411 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 365 | py | # Generated by Django 3.2.4 on 2021-06-26 14:25
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0010_rename_author_author_user'),
]
operations = [
migrations.RenameField(
model_name='author',
old_name='user',
new_name='author',
),
]
| [
"shahadat@baiust.edu.bd"
] | shahadat@baiust.edu.bd |
b216d42b41d02698e713dca93ca58a36287b9f1c | 03dfcd4bd41ff9ba76e67895e96a9794ad003a31 | /sandbox/problems/l2q6.py | 3f72d83401c659405f22bde75a2cff7ae09c26ae | [] | no_license | gittygitgit/python-sandbox | 71ca68fcc90745931737f7aeb61306ac3417ce60 | 3b3e0eaf4edad13aabe51eb3258ebe9e6b951c67 | refs/heads/master | 2021-01-19T02:41:17.047711 | 2018-11-22T18:07:15 | 2018-11-22T18:07:15 | 39,742,770 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 987 | py | #!/usr/bin/python
'''
Question:
Write a program that calculates and prints the value according to the given formula:
Q = Square root of [(2 * C * D)/H]
Following are the fixed values of C and H:
C is 50. H is 30.
D is the variable whose values should be input to your program in a comma-separated sequence.
Example
Let us assume the following comma separated input sequence is given to the program:
100,150,180
The output of the program should be:
18,22,24
Hints:
If the output received is in decimal form, it should be rounded off to its nearest value (for example, if the output received is 26.0, it should be printed as 26)
In case of input data being supplied to the question, it should be assumed to be a console input.
'''
import math
def calculate(x):
C = 50
H = 30
l=x.split(",")
r=[];
for i in l:
v=math.sqrt((2*C*int(i)) / H)
r.append(str(int(math.floor(v))))
print ",".join(r)
v=raw_input("Enter comma-separated input sequence.");
calculate(v);
| [
"grudkowm@Michaels-Air-2.fios-router.home"
] | grudkowm@Michaels-Air-2.fios-router.home |
9dd0cdef10c7a872c03294c15a2d2ac2174cea62 | 90df9cbc8d15b0bd08ceb7fc42088021efbdfbe1 | /projectile.py | 0ef350a3367ca4d77503f15f70ae673e3c2e05cb | [
"MIT"
] | permissive | whaleygeek/variable_duty_cycle | bef0ef9dbba99fd508cbb47a2b8befc0f958f855 | 82c197f7c79c2074b7f0eacac1686aa8e28a9a21 | refs/heads/master | 2021-01-20T01:45:36.806435 | 2017-04-27T12:55:35 | 2017-04-27T12:55:35 | 89,324,831 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,300 | py | # projectile.py 25/04/2017 D.J.Whale
#
# A Python implementation of the Variable Duty Cycle algorithm
# implementing a simple projectile plotter
#
# Idea from:
# https://archive.org/stream/byte-magazine-1981-10/1981_10_BYTE_06-10_Local_Networks#page/n389/mode/2up
# Original Pseudo Code
# C horizontal duty counter
# D vertical duty counter
# H horizontal duty cycle (velocity)
# V vertical duty cycle (velocity)
# M duty master
# C := C - H
# if C < 0
# then do
# <move projectile one cell to the right>
# C := C + M
# end
# D := D - V
# if D < 0
# then do
# <move projectile one cell up>
# D := C + M #NOTE: should be D := D + M??
# end
# else if D >= M #NOTE: indentation fixed from original code
# then do
# <move projectile one cell down>
# D := D - M
# end
# <decrease V by a fixed amount>
from Timer import Timer
try:
ask = raw_input # python2
except AttributeError:
ask = input #python3
duty_counter_h = 0 # C
duty_counter_v = 0 # D
duty_cycle_h = 45 # H horizontal velocity (rightwards direction)
duty_cycle_v = 125 # V vertical velocity (75 in upwards direction)
v_adjust = -1 # amount to adjust V by each time round loop
duty_master = 125 # M
x = 0 # x position of projectile
y = 0 # y position of projectile
LOOP_RATE = None # run the loop as fast as possible
timer = Timer(LOOP_RATE)
screen = None
def output(x,y):
global screen
if screen is None:
from screen import Screen
screen = Screen()
screen.start()
screen.plot(x, screen.height - y)
while y >= 0: # stop when projectile hits ground
timer.wait()
# VDC#1 for x movement
duty_counter_h -= duty_cycle_h
if duty_counter_h < 0:
x += 1 # move one cell to the right
duty_counter_h += duty_master
# VDC#2 for y movement
duty_counter_v -= duty_cycle_v
if duty_counter_v < 0:
y += 1 # move one cell up
duty_counter_v += duty_master
elif duty_counter_v >= duty_master:
y -= 1 # move one cell down
duty_counter_v -= duty_master
# vertical velocity adustment due to gravity
duty_cycle_v += v_adjust
#print(duty_cycle_v)
output(x*5, y*5)
ask("finished?")
# END
| [
"david@thinkingbinaries.com"
] | david@thinkingbinaries.com |
16d10155454d78b274b64a76eebdc6f731152e65 | 109a830aad476305f029274d75e28bec8b54f597 | /venv/bin/django-admin | 1608e243708e9f7fa2a64226ea036f01a70824c7 | [] | no_license | Dapucla/EP | 53b156088046abfd6833eba95dc4393ebeb93f4e | 9368032b4b289b20ec1bdf0033d3fe199223d200 | refs/heads/master | 2023-06-19T08:02:55.984888 | 2021-07-11T22:52:24 | 2021-07-11T22:52:24 | 330,009,437 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 331 | #!/Users/daniilalekseev/PycharmProjects/DevicesOnlineShop/ENG-PROJECT/venv/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from django.core.management import execute_from_command_line
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(execute_from_command_line())
| [
"dapcula08@yandex.ru"
] | dapcula08@yandex.ru | |
f5d774828824bb6b08702b8147a2b8fef9436add | 4c992ca9bb41383ec3a9c7dc7a1e4204ef6cb850 | /publicdata/censusreporter/series.py | e211e540e6e3d1318fa8fb6cb525d1ea0e75569b | [
"MIT"
] | permissive | rkiyengar/publicdata | f72d19d5d2821707d7a84c232cb66fb6686801db | 8fddc1a460716a3d54a7504c82376c083a0af014 | refs/heads/master | 2021-08-28T15:14:33.113145 | 2017-12-12T15:11:46 | 2017-12-12T15:11:46 | 113,387,497 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,995 | py | # Copyright (c) 2017 Civic Knowledge. This file is licensed under the terms of the
# MIT License, included in this distribution as LICENSE
"""
"""
from pandas import DataFrame, Series
import numpy as np
from six import string_types
import numpy as np
from six import string_types
class CensusSeries(Series):
_metadata = ['schema', 'parent_frame']
@property
def _constructor(self):
return CensusSeries
@property
def _constructor_expanddim(self):
from .dataframe import CensusDataFrame
return CensusDataFrame
@property
def title(self): # b/c the _metadata elements aren't created until assigned
try:
return self._title
except AttributeError:
return None
@title.setter
def title(self, v):
self._title = v
@property
def census_code(self):
return self.name
@property
def census_index(self):
raise NotImplementedError
@property
def census_title(self):
return self.title
@property
def col_position(self):
raise NotImplementedError
def __init__(self, data=None, index=None, dtype=None, name=None, copy=False, fastpath=False):
super(CensusSeries, self).__init__(data, index, dtype, name, copy, fastpath)
@property
def m90(self):
if self.census_code.endswith('_m90'):
return self
else:
return self.parent_frame[self.census_code+'_m90'].astype('float')
@property
def estimate(self):
"""Return the estimate value, for either an estimate column or a margin column. """
if self.census_code.endswith('_m90'):
return self.parent_frame[self.census_code.replace('_m90','')].astype('float')
else:
return self
@property
def value(self):
"""Synonym for estimate()"""
if self.census_code.endswith('_m90'):
return self.parent_frame[self.census_code.replace('_m90','')].astype('float')
else:
return self
@property
def se(self):
"""Return a standard error series, computed from the 90% margins"""
return self.m90 / 1.645
@property
def rse(self):
"""Return the relative standard error for a column"""
return ( (self.se / self.value) * 100).replace([np.inf, -np.inf], np.nan)
@property
def m95(self):
"""Return a standard error series, computed from the 90% margins"""
return self.se * 1.96
@property
def m99(self):
"""Return a standard error series, computed from the 90% margins"""
return self.se * 2.575
def sum_m90(self, *cols):
""""""
# See the ACS General Handbook, Appendix A, "Calculating Margins of Error for Derived Estimates".
# (https://www.census.gov/content/dam/Census/library/publications/2008/acs/ACSGeneralHandbook.pdf)
# for a guide to these calculations.
return np.sqrt(sum(self.m90 ** 2))
| [
"eric@civicknowledge.com"
] | eric@civicknowledge.com |
72dc2fa92097e059528253cd249e8a5adaa613ad | 52b5773617a1b972a905de4d692540d26ff74926 | /.history/linkedlist_20200623140505.py | 3fbc3a13dbff9fdaff5799ef81ca03724a251395 | [] | 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 | 1,510 | py | # Linked List implementation
# implements the node type
# stores a single data field ---> val
class Node(object):
def __init__(self,val):
self.val = val
self.next = None
def get_data(self):
return self.val
def set_data(self,val):
self.val = val
def get_next(self):
return self.next
def set_next(self,next):
self.next = next
class LinkedList(object):
def __init__(self,head=None):
self.head = head
self.count = 0
def get_count(self):
return self.count
def insert(self,data):
# insert a new node
new_node = Node(data)
# point the new node to the current head
new_node.set_next(self.head)
# set head as the new node
self.head = new_node
self.count +=1
def find(self,val):
# Find the first element with a given value
item = self.head
# we check if item is not none and equal to the val we are looking for
while item !=None:
if item.get_data() == val:
return item
else:
item.get_next()
return None
def deleteAt(self,idx):
# to delete an item at a given index
if idx > self.count-1:
return
def dump_list(self):
tempnode = self.head
while tempnode != None:
print("Node: ",tempnode.get_data())
tempnode = tempnode.get_next()
# create a linked
| [
"mary.jereh@gmail.com"
] | mary.jereh@gmail.com |
0ea6c1d03a86d7ca86b5f5f804c1422b102cb628 | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/verbs/_spites.py | d2c6c8a7bc2b2a2463e64b4751f5d767476db7b2 | [
"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 | 231 | py |
from xai.brain.wordbase.verbs._spite import _SPITE
#calss header
class _SPITES(_SPITE, ):
def __init__(self,):
_SPITE.__init__(self)
self.name = "SPITES"
self.specie = 'verbs'
self.basic = "spite"
self.jsondata = {}
| [
"xingwang1991@gmail.com"
] | xingwang1991@gmail.com |
037699b5f44d1f196eb5a8aac2be877a7d4491f3 | 089b396be42accf7dedd6a935b8cb29d43f25e2c | /core/urls.py | d30152bfd637967c2d79e3491e09b842841d8b8f | [
"MIT"
] | permissive | edgarslabans/django-ajax-xhr_nio | b4dcce4b9d5d73a60e912cc0cc926e5c78f737ba | b33ab12fc17a3fb98812c12259f97525f3746bd2 | refs/heads/main | 2023-08-22T21:16:28.266245 | 2023-08-22T11:38:48 | 2023-08-22T11:38:48 | 681,173,754 | 0 | 0 | MIT | 2023-08-21T12:35:21 | 2023-08-21T12:35:19 | null | UTF-8 | Python | false | false | 416 | py | from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path
from todos.views import home, todo, todos
urlpatterns = [
path('admin/', admin.site.urls),
path('todos/<int:todoId>/', todo, name="todo"),
path('todos/', todos, name="todos"),
path('', home),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
| [
"hermanmu@gmail.com"
] | hermanmu@gmail.com |
b531a7e2091cb595f280d47d3bef514cc6dba92b | ec030fab06dab9a94835a5d308fb8411111be0b4 | /myprintgoogle.py | 47bb714ad8cd0381fa217c1d8dcc3361b5b82582 | [] | no_license | mortadagzar/Python_Kivy_MobileApps | e464319cb7825c57bbfb44f95b4aca15e3734988 | d941a8d2da00a2420a47b07224e3ed876698ea23 | refs/heads/master | 2020-04-08T03:35:51.097417 | 2019-03-08T05:17:07 | 2019-03-08T05:17:07 | 158,982,437 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 453 | py | from google.cloud import storage
def upload_blob(bucket_name, source_file_name, destination_blob_name):
"""Uploads a file to the bucket."""
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(destination_blob_name)
blob.upload_from_filename(source_file_name)
print('File {} uploaded to {}.'.format(
source_file_name,
destination_blob_name))
print("its google")
| [
"mortadagzar@gmail.com"
] | mortadagzar@gmail.com |
33d73097852c91a54cb2e24f3a6ee3f6e61acb17 | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/127/usersdata/174/36355/submittedfiles/ex11.py | 6ab9a8927f2e4d904e182bedbdc3a5c7e569d9e1 | [] | 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 | 473 | py | # -*- coding: utf-8 -*-
d1 = float(input('Dia:'))
m1 = float(input('Mes:'))
a1 = float(input('Ano:'))
d2 = float(input('Dia:'))
m2 = float(input('Mes:'))
a2 = float(input('Ano:'))
if a1>a2:
print ('DATA 1')
elif a1<a2:
print ('DATA 2')
else:
if m1>m2:
print('DATA 1')
elif m1<m2:
print('DATA 2')
else:
if d1>d2:
print('DATA 1')
elif d1<d2:
print('DATA 2')
else:
print('IGUAIS') | [
"rafael.mota@ufca.edu.br"
] | rafael.mota@ufca.edu.br |
11f9cc4c53607b22d92b19a8e39858302b699a6c | 7b3711d4c6d7284255ba0270d49d120f984bf7c6 | /problems/1456_maximum_number_of_vowels_in_a_substring_of_given_length.py | b8c1ee441ba0fe9a18e4fc45c9b3521258e986f6 | [] | no_license | loganyu/leetcode | 2d336f30feb55379aaf8bf0273d00e11414e31df | 77c206305dd5cde0a249365ce7591a644effabfc | refs/heads/master | 2023-08-18T09:43:10.124687 | 2023-08-18T00:44:51 | 2023-08-18T00:44:51 | 177,875,222 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,042 | py | '''
Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k.
Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'.
Example 1:
Input: s = "abciiidef", k = 3
Output: 3
Explanation: The substring "iii" contains 3 vowel letters.
Example 2:
Input: s = "aeiou", k = 2
Output: 2
Explanation: Any substring of length 2 contains 2 vowels.
Example 3:
Input: s = "leetcode", k = 3
Output: 2
Explanation: "lee", "eet" and "ode" contain 2 vowels.
Constraints:
1 <= s.length <= 105
s consists of lowercase English letters.
1 <= k <= s.length
'''
class Solution:
def maxVowels(self, s: str, k: int) -> int:
vowels = {'a', 'e', 'i', 'o', 'u'}
count = 0
for i in range(k):
count += int(s[i] in vowels)
answer = count
for i in range(k, len(s)):
count += int(s[i] in vowels)
count -= int(s[i - k] in vowels)
answer = max(answer, count)
return answer
| [
"yu.logan@gmail.com"
] | yu.logan@gmail.com |
597713e0d9f271c187c3ffd7c3cec16228a0eb6d | 7390417d66411000e18156bf3ec6389f3a4aa3dc | /website/feature_importances_correlations/between_targets/page.py | 173578411f3867740fbdfbd59855634900e31e2d | [
"MIT"
] | permissive | HMS-AgeVSSurvival/Website | fb911e10eedd3212f1440e57a97061a50cc4e33d | 298000aee6ab951a7f90e6bb4ca4716997a0398b | refs/heads/main | 2023-07-26T06:23:39.064024 | 2021-09-14T09:15:27 | 2021-09-14T09:15:27 | 388,773,530 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,560 | py | from website.app import APP
import dash_bootstrap_components as dbc
import dash_html_components as html
from dash.dependencies import Input, Output
from website.feature_importances_correlations.between_targets.tabs.all_categories import get_all_categories
from website.feature_importances_correlations.between_targets.tabs.custom_categories import get_custom_categories
@APP.callback(
Output("tab_content_feature_importances_correlations_between_targets", "children"),
Input("tab_manager_feature_importances_correlations_between_targets", "active_tab"),
)
def _fill_tab(
active_tab,
):
if active_tab == "feature_importances_correlations_between_targets_custom_categories":
return get_custom_categories()
else: # active_tab == "feature_importances_correlations_between_targets_all_categories":
return get_all_categories()
LAYOUT = html.Div(
[
dbc.Tabs(
[
dbc.Tab(
label="Custom categories",
tab_id="feature_importances_correlations_between_targets_custom_categories",
),
dbc.Tab(
label="All categories", tab_id="feature_importances_correlations_between_targets_all_categories"
),
],
id="tab_manager_feature_importances_correlations_between_targets",
active_tab="feature_importances_correlations_between_targets_custom_categories",
),
html.Div(id="tab_content_feature_importances_correlations_between_targets"),
]
)
| [
"theo.vincent@eleves.enpc.fr"
] | theo.vincent@eleves.enpc.fr |
deb0389d1cc707e4fbb2f91c535f9f8f36f9d5dc | 1b554b6c970ba31bffae8434611e307770fa2e95 | /lof/generator.py | e32c81ea71f3ccd889b232fb83343ac33986dba4 | [
"MIT"
] | permissive | mkaraev/lof | 0d1821b04b0137d982638276e5d6fdb06c7d3441 | 19be33d1283842069af0dd0776027b24676aac5e | refs/heads/main | 2023-06-25T07:09:51.701689 | 2021-07-24T22:10:26 | 2021-07-24T22:10:26 | 389,283,255 | 0 | 0 | MIT | 2021-07-25T07:00:12 | 2021-07-25T07:00:12 | null | UTF-8 | Python | false | false | 2,993 | py | import importlib
import json
from typing import Callable, Dict, Optional
from fastapi import FastAPI, Request, Response
from fastapi.responses import JSONResponse
def create_route(endpoint: Dict, handler: Callable, method: str, app: FastAPI):
method = getattr(app, method)
@method(endpoint)
async def _method(request: Request, response: Response):
_handler = handler.split(".")
module = ".".join(_handler[0:-1])
_handler = _handler[-1]
my_module = importlib.import_module(module)
_handler = getattr(my_module, _handler)
event = await prepare_api_gateway_event(request)
result = _handler(event, {})
status_code = result.get("statusCode") or result.get("status_code") or 200
if result.get("body"):
content = result.get("body")
else:
content = result
for header, value in result.get("headers", {}).items():
response.headers[header] = value
if status_code == 204:
response = Response(status_code=status_code)
else:
response = JSONResponse(
content=content, status_code=status_code, headers=response.headers
)
return response
def get_query_params(multi_params: Optional[Dict]) -> Dict:
params = {}
if multi_params:
for param in multi_params:
params[param] = multi_params[param][-1]
return params
def get_multi_value_params(url: str) -> Dict:
"""extract parmas from url for multiqueryParams"""
url = str(url).split("/")[-1]
params = url.split("?")[-1]
params = params.split("&")
multi_query_params = {}
if len(params) == 1:
params = []
for param in params:
name, value = param.split("=")
if not multi_query_params.get(name):
multi_query_params[name] = [value]
else:
multi_query_params[name].append(value)
if not multi_query_params:
multi_query_params = None
return multi_query_params
async def prepare_api_gateway_event(request: Request) -> Request:
body = None
try:
body = await request.json()
except Exception:
pass
multi_params = get_multi_value_params(request.url)
headers = {}
for header in request.headers.items():
headers[header[0]] = header[1]
event = {
"resource": str(request.base_url),
"path": str(request.url),
"httpMethod": request.method,
"requestContext": {
"resourcePath": "/",
"httpMethod": request.method,
"path": str(request.base_url),
},
"headers": headers,
"multiValueHeaders": None,
"queryStringParameters": get_query_params(multi_params),
"multiValueQueryStringParameters": multi_params,
"pathParameters": request.path_params,
"stageVariables": None,
"body": json.dumps(body),
"isBase64Encoded": False,
}
return event
| [
"xnuinside@gmail.com"
] | xnuinside@gmail.com |
e724b791e0662abba8b8bc7979733f388d1ca514 | 0fccee4c738449f5e0a8f52ea5acabf51db0e910 | /genfragments/ThirteenTeV/SUSYGluGlu/SUSYGluGluToBBHTohhTo2Tau2B_M-300_TuneCUETP8M1_13TeV-pythia8_filter_cfi.py | 352f91727e0d5853e6653e614b6f39233fbe62da | [] | no_license | cms-sw/genproductions | f308ffaf3586c19b29853db40e6d662e937940ff | dd3d3a3826343d4f75ec36b4662b6e9ff1f270f4 | refs/heads/master | 2023-08-30T17:26:02.581596 | 2023-08-29T14:53:43 | 2023-08-29T14:53:43 | 11,424,867 | 69 | 987 | null | 2023-09-14T12:41:28 | 2013-07-15T14:18:33 | Python | UTF-8 | Python | false | false | 4,945 | py | import FWCore.ParameterSet.Config as cms
from Configuration.Generator.Pythia8CommonSettings_cfi import *
from Configuration.Generator.Pythia8CUEP8M1Settings_cfi import *
generator = cms.EDFilter("Pythia8GeneratorFilter",
pythiaPylistVerbosity = cms.untracked.int32(1),
filterEfficiency = cms.untracked.double(1.0),
pythiaHepMCVerbosity = cms.untracked.bool(False),
comEnergy = cms.double(13000.0),
crossSection = cms.untracked.double(518.3),
maxEventsToPrint = cms.untracked.int32(1),
PythiaParameters = cms.PSet(
pythia8CommonSettingsBlock,
pythia8CUEP8M1SettingsBlock,
processParameters = cms.vstring('Higgs:useBSM = on',
'HiggsBSM:gg2H2bbbar = on',
'35:m0 = 300',
'25:m0 = 125',
'35:onMode = off',
'35:onIfMatch = 25 25',
'25:onMode = off',
'25:onIfMatch = 5 -5',
'25:onIfMatch = 15 -15'
),
parameterSets = cms.vstring('pythia8CommonSettings',
'pythia8CUEP8M1Settings',
'processParameters')
)
)
bbgenfilter = cms.EDFilter("MCMultiParticleFilter",
Status = cms.vint32(23, 23),
src = cms.InputTag('generator'),
ParticleID = cms.vint32(5, -5),
PtMin = cms.vdouble(0, 0),
NumRequired = cms.int32(1),
EtaMax = cms.vdouble(9999, 9999),
AcceptMore = cms.bool(True)
)
tautaugenfilter = cms.EDFilter("MCMultiParticleFilter",
Status = cms.vint32(23, 23),
src = cms.InputTag('generator'),
ParticleID = cms.vint32(15, -15),
PtMin = cms.vdouble(0,0),
NumRequired = cms.int32(1),
EtaMax = cms.vdouble(9999, 9999),
AcceptMore = cms.bool(True)
)
ProductionFilterSequence = cms.Sequence(generator + bbgenfilter + tautaugenfilter)
configurationMetadata = cms.untracked.PSet(
version = cms.untracked.string('\$Revision$'),
name = cms.untracked.string('\$Source$'),
annotation = cms.untracked.string('bbH (H->hh->tautaubb), 13TeV, mH = 300GeV, filtered. TuneCUETP8M1')
)
| [
"Yuta.Takahashi@cern.ch"
] | Yuta.Takahashi@cern.ch |
44e0524543acf5ef0dae068943b35982c863e360 | 9ecf55bf2601e0d4f74e71f4903d2fd9e0871fd6 | /my_seg_keras/v2_unet_street/test_generator.py | bdf7e240c0cac4b018e854ff41d915a48e308ba9 | [] | no_license | qq191513/mySeg | 02bc9803cde43907fc5d96dc6a6a6371f2bef6fe | 4337e6a0ca50b8ccbf6ed9b6254f2aec814b24db | refs/heads/master | 2020-04-10T09:57:37.811133 | 2019-06-26T08:21:23 | 2019-06-26T08:21:23 | 160,951,962 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,395 | py | import numpy as np
import matplotlib.pyplot as plt
from v1 import config as cfg
import time
from data_process.use_generator import imageSegmentationGenerator
def split_batch_to_pic_list(img):
#一个batch_size的四维张量图片分割成一组列表图片(三维)
batch_size = img.shape[0]
img_list = np.split(img,batch_size,axis=0)
for index,img in enumerate(img_list):
img = np.squeeze(img,axis=0)
img_list[index] = img
return img_list
def plt_imshow_data(data):
#调成标准格式和标准维度,免得爆BUG
data = np.asarray(data)
if data.ndim == 3:
if data.shape[2] == 1:
data = data[:, :, 0]
plt.imshow(data)
plt.show()
time.sleep(2)
def plt_imshow_two_pics(data_1,data_2):
#调成标准格式和标准维度,免得爆BUG
data_1 = np.asarray(data_1)
if data_1.ndim == 3:
if data_1.shape[2] == 1:
data_1 = data_1[:, :, 0]
data_2 = np.asarray(data_2)
if data_2.ndim == 3:
if data_2.shape[2] == 1:
data_2 = data_2[:, :, 0]
plt.subplot(1, 2, 1)
plt.imshow(data_1)
plt.subplot(1, 2, 2)
plt.imshow(data_2)
plt.show()
def seg_vec_to_pic(seg_vec,restore_pic_shape,colors,n_classes):
#长度为w * h * n_classes的向量转w * h * 3的图片,随机生成颜色
seg_img = np.zeros(shape=restore_pic_shape)
the_shape = restore_pic_shape
w, h = the_shape[0],the_shape[1]
seg_vec = seg_vec.reshape((w, h, -1)) #w * h * n_classes 做成(w ,h ,n_classes)
# 共n_classes层,每层都弄一种颜色
for c in range(n_classes):
seg_img[:, :, 0] += (seg_vec[:, :, c] * (colors[c][0])).astype('uint8')
seg_img[:, :, 1] += (seg_vec[:, :, c] * (colors[c][1])).astype('uint8')
seg_img[:, :, 2] += (seg_vec[:, :, c] * (colors[c][2])).astype('uint8')
seg_img = seg_img / 255.0
seg_img = seg_img.astype('float32')
return seg_img
def use_generator_to_show(images_path , segs_path , batch_size,
n_classes , input_height , input_width , output_height , output_width):
batch_size_n = 0 #取第batch_size_n张图片观察
plt.figure()
colors = [(np.random.randint(0, 255), np.random.randint(0, 255), np.random.randint(0, 255)) for _ in
range(n_classes)]
#使用Generator,返回一个batch_size的 im_fn和seg_fn
for im_fn , seg_vec in imageSegmentationGenerator(images_path , segs_path , batch_size,
n_classes , input_height , input_width , output_height , output_width):
pics_group = split_batch_to_pic_list(im_fn) #batchsize切成图片列表
pic = pics_group[batch_size_n] #取第batch_size_n张图片观察
# plt_imshow_data(pic) #用plt显示
print('img shape: ',im_fn.shape)
print('seg shape: ',seg_vec.shape)
seg_vec = split_batch_to_pic_list(seg_vec) # batchsize切成图片列表
seg_vec = seg_vec[batch_size_n] # 取第batch_size_n张图片观察
seg_img = seg_vec_to_pic(seg_vec,pic.shape,colors,n_classes)
plt_imshow_two_pics(pic,seg_img) #用plt显示
time.sleep(1)
print('train dataset')
use_generator_to_show(cfg.train_images , cfg.train_annotations , cfg.train_batch_size,
cfg.n_classes, cfg.input_shape[0], cfg.input_shape[1], cfg.output_shape[0],cfg.output_shape[1])
# print('valid dataset')
# use_generator_to_show(cfg.val_images , cfg.val_annotations , cfg.train_batch_size,
# cfg.n_classes , cfg.input_height , cfg.input_width , cfg.output_height , cfg.output_width)
| [
"1915138054@qq.com"
] | 1915138054@qq.com |
1920bee1faeb280feb1f63b7b78c650bc8c772d4 | 2b29095a4f8a60e6ad2f09dd257dc8a9ceb04ebd | /misfits/tools/smooth/__init__.py | 2658ea2efa922b41405685907facd4a792e93f0c | [] | no_license | sholmbo/misfits | f82601cdf5778c4ea57c3d9fed8aea3cd3b641f9 | e34a0ba0b62948840a6bcb1c28d340b8c613dd66 | refs/heads/master | 2023-02-25T13:17:48.670735 | 2021-02-02T15:12:12 | 2021-02-02T15:30:11 | 277,625,987 | 0 | 1 | null | 2021-02-02T15:18:35 | 2020-07-06T19:04:35 | Python | UTF-8 | Python | false | false | 132 | py | from .lowpass import LowPass
from .boxcar import Boxcar
from .gaussian import Gaussian
from .smoothingspline import SmoothingSpline
| [
"simonholmbo@gmail.com"
] | simonholmbo@gmail.com |
9a9bc9fac9a12e1a306ff9724f080209bd2e6cf5 | cc9a6fa4012c58f66d735e20486b9a1df877d1b7 | /Strings/Integer To Roman.py | 6ce9d5509a8706b487d0cf4902e31d2557ad5670 | [] | no_license | sharmaji27/InterviewBit-Problems | 6e5acb6d45296b60df8632a02b0aa272dcde8f28 | 09054fdab0350a86268cfe5eb55edc2071067b2b | refs/heads/master | 2023-08-27T23:08:34.003883 | 2021-10-20T05:33:46 | 2021-10-20T05:33:46 | 265,551,578 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,129 | py | '''
Given an integer A, convert it to a roman numeral, and return a string corresponding to its roman numeral version
Note : This question has a lot of scope of clarification from the interviewer. Please take a moment to think of all the needed clarifications and see the expected response using “See Expected Output” For the purpose of this question, https://projecteuler.net/about=roman_numerals has very detailed explanations.
Input Format
The only argument given is integer A.
Output Format
Return a string denoting roman numeral version of A.
Constraints
1 <= A <= 3999
For Example
Input 1:
A = 5
Output 1:
"V"
Input 2:
A = 14
Output 2:
"XIV"
'''
class Solution:
# @param A : integer
# @return a strings
def intToRoman(self, A):
I = ['','I','II','III','IV','V','VI','VII','VIII','IX','X']
X = ['','X','XX','XXX','XL','L','LX','LXX','LXXX','XC','C']
C = ['','C','CC','CCC','CD','D','DC','DCC','DCCC','CM','M']
M = ['','M','MM','MMM']
return(M[A//1000] + C[(A%1000)//100] + X[(A%100)//10] + I[A%10]) | [
"asharma70420@gmail.com"
] | asharma70420@gmail.com |
505ecf386e4dc812d1ffee11c7b7ce8a2b19b3fa | 28f088b5356e66780c4bad204564bff92f910f02 | /src/python/pants/base/exception_sink_integration_test.py | bdbc6b8ff6855afb1a1bf2eb685a4f9e39400f25 | [
"Apache-2.0"
] | permissive | wonlay/pants | 57dcd99f82cdb2e37fcb7c563ec2bccf797ee7b7 | 53c66503b6898e83c9c9596e56cde5ad9ed6a0d3 | refs/heads/master | 2023-03-06T03:23:08.602817 | 2022-05-05T23:41:32 | 2022-05-05T23:41:32 | 24,695,709 | 0 | 0 | Apache-2.0 | 2023-03-01T11:59:58 | 2014-10-01T21:15:29 | Python | UTF-8 | Python | false | false | 4,970 | py | # Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
import re
import signal
import time
from pathlib import Path
from typing import List, Tuple
import pytest
from pants.base.build_environment import get_buildroot
from pants.base.exception_sink import ExceptionSink
from pants.testutil.pants_integration_test import run_pants_with_workdir
from pants.util.dirutil import read_file
from pants_test.pantsd.pantsd_integration_test_base import PantsDaemonIntegrationTestBase
pytestmark = pytest.mark.platform_specific_behavior
def lifecycle_stub_cmdline() -> List[str]:
# Load the testprojects pants-plugins to get some testing tasks and subsystems.
testproject_backend_src_dir = os.path.join(
get_buildroot(), "testprojects/pants-plugins/src/python"
)
testproject_backend_pkg_name = "test_pants_plugin"
lifecycle_stub_cmdline = [
"--no-pantsd",
f"--pythonpath=+['{testproject_backend_src_dir}']",
f"--backend-packages=+['{testproject_backend_pkg_name}']",
# This task will always raise an exception.
"lifecycle-stub-goal",
]
return lifecycle_stub_cmdline
def get_log_file_paths(workdir: str, pid: int) -> Tuple[str, str]:
pid_specific_log_file = ExceptionSink.exceptions_log_path(for_pid=pid, in_dir=workdir)
assert os.path.isfile(pid_specific_log_file)
shared_log_file = ExceptionSink.exceptions_log_path(in_dir=workdir)
assert os.path.isfile(shared_log_file)
assert pid_specific_log_file != shared_log_file
return (pid_specific_log_file, shared_log_file)
def assert_unhandled_exception_log_matches(pid: int, file_contents: str) -> None:
regex_str = f"""\
timestamp: ([^\n]+)
process title: ([^\n]+)
sys\\.argv: ([^\n]+)
pid: {pid}
Exception caught: \\([^)]*\\)
(.|\n)*
Exception message:.*
"""
assert re.match(regex_str, file_contents)
def assert_graceful_signal_log_matches(pid: int, signum, signame, contents: str) -> None:
regex_str = """\
timestamp: ([^\n]+)
process title: ([^\n]+)
sys\\.argv: ([^\n]+)
pid: {pid}
Signal {signum} \\({signame}\\) was raised\\. Exiting with failure\\.
""".format(
pid=pid, signum=signum, signame=signame
)
assert re.search(regex_str, contents)
def test_logs_unhandled_exception(tmp_path: Path) -> None:
pants_run = run_pants_with_workdir(
lifecycle_stub_cmdline(),
workdir=tmp_path.as_posix(),
# The backtrace should be omitted when --print-stacktrace=False.
print_stacktrace=False,
extra_env={"_RAISE_EXCEPTION_ON_IMPORT": "True"},
)
pants_run.assert_failure()
regex = "exception during import!"
assert re.search(regex, pants_run.stderr)
pid_specific_log_file, shared_log_file = get_log_file_paths(tmp_path.as_posix(), pants_run.pid)
assert_unhandled_exception_log_matches(pants_run.pid, read_file(pid_specific_log_file))
assert_unhandled_exception_log_matches(pants_run.pid, read_file(shared_log_file))
class ExceptionSinkIntegrationTest(PantsDaemonIntegrationTestBase):
hermetic = False
def test_dumps_logs_on_signal(self):
"""Send signals which are handled, but don't get converted into a KeyboardInterrupt."""
signal_names = {
signal.SIGQUIT: "SIGQUIT",
signal.SIGTERM: "SIGTERM",
}
for (signum, signame) in signal_names.items():
with self.pantsd_successful_run_context() as ctx:
ctx.runner(["help"])
pid = ctx.checker.assert_started()
os.kill(pid, signum)
time.sleep(5)
# Check that the logs show a graceful exit by signal.
pid_specific_log_file, shared_log_file = get_log_file_paths(ctx.workdir, pid)
assert_graceful_signal_log_matches(
pid, signum, signame, read_file(pid_specific_log_file)
)
assert_graceful_signal_log_matches(pid, signum, signame, read_file(shared_log_file))
def test_dumps_traceback_on_sigabrt(self):
# SIGABRT sends a traceback to the log file for the current process thanks to
# faulthandler.enable().
with self.pantsd_successful_run_context() as ctx:
ctx.runner(["help"])
pid = ctx.checker.assert_started()
os.kill(pid, signal.SIGABRT)
time.sleep(5)
# Check that the logs show an abort signal and the beginning of a traceback.
pid_specific_log_file, shared_log_file = get_log_file_paths(ctx.workdir, pid)
regex_str = """\
Fatal Python error: Aborted
Thread [^\n]+ \\(most recent call first\\):
"""
assert re.search(regex_str, read_file(pid_specific_log_file))
# faulthandler.enable() only allows use of a single logging file at once for fatal tracebacks.
assert "" == read_file(shared_log_file)
| [
"noreply@github.com"
] | wonlay.noreply@github.com |
fffdf977cf0f7526c91b672b614f4123a1b4ffb7 | 992969b8b0beb53bf884938ae20f5d56bb3878f2 | /rules/taxonomic_classification/Snakefile | cfeaba79fdeb1f60bd767ff30569e1b24c9ae5ba | [
"BSD-3-Clause"
] | permissive | dahak-metagenomics/taco-taxonomic-classification | c6f0120e7d5e979c03d4c6d0778756960f46e593 | 854cae4f1b2427746a1faa6a0e0aefbfb11c5523 | refs/heads/master | 2020-03-12T21:29:04.347344 | 2018-05-03T16:47:32 | 2018-05-03T16:47:32 | 130,829,061 | 0 | 0 | BSD-3-Clause | 2018-12-16T03:00:58 | 2018-04-24T09:23:14 | Python | UTF-8 | Python | false | false | 298 | import utils
include: "taxonomic_classification.settings"
include: "biocontainers.rule"
include: "sourmash_sbt.rule"
include: "calculate_signatures.rule"
include: "trimmed_data.rule"
include: "kaiju.rule"
include: "kaiju2krona.rule"
include: "filter_taxa.rule"
include: "krona_visualization.rule"
| [
"charlesreid1@gmail.com"
] | charlesreid1@gmail.com | |
49ac68fcf23d7d889d0bd59ad259e4465769c696 | 1dae87abcaf49f1d995d03c0ce49fbb3b983d74a | /programs/subroutines/Feshbach ramp10ms 0-47A.sub.py | 393291c0239b4dbeeb5ba83566e5ced7dd8e41ea | [] | no_license | BEC-Trento/BEC1-data | 651cd8e5f15a7d9848f9921b352e0830c08f27dd | f849086891bc68ecf7447f62962f791496d01858 | refs/heads/master | 2023-03-10T19:19:54.833567 | 2023-03-03T22:59:01 | 2023-03-03T22:59:01 | 132,161,998 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,992 | py | prg_comment = ""
prg_version = "0.5.1"
def program(prg, cmd):
prg.add(0, "Delta 1 Current", 0.000000)
prg.add(1000, "Delta 1 Current", 0.470000)
prg.add(2000, "Delta 1 Current", 0.940000)
prg.add(3000, "Delta 1 Current", 1.410000)
prg.add(4000, "Delta 1 Current", 1.880000)
prg.add(5000, "Delta 1 Current", 2.350000)
prg.add(6000, "Delta 1 Current", 2.820000)
prg.add(7000, "Delta 1 Current", 3.290000)
prg.add(8000, "Delta 1 Current", 3.760000)
prg.add(9000, "Delta 1 Current", 4.230000)
prg.add(10000, "Delta 1 Current", 4.700000)
prg.add(11000, "Delta 1 Current", 5.170000)
prg.add(12000, "Delta 1 Current", 5.640000)
prg.add(13000, "Delta 1 Current", 6.110000)
prg.add(14000, "Delta 1 Current", 6.580000)
prg.add(15000, "Delta 1 Current", 7.050000)
prg.add(16000, "Delta 1 Current", 7.520000)
prg.add(17000, "Delta 1 Current", 7.990000)
prg.add(18000, "Delta 1 Current", 8.460000)
prg.add(19000, "Delta 1 Current", 8.930000)
prg.add(20000, "Delta 1 Current", 9.400000)
prg.add(21000, "Delta 1 Current", 9.870000)
prg.add(22000, "Delta 1 Current", 10.340000)
prg.add(23000, "Delta 1 Current", 10.810000)
prg.add(24000, "Delta 1 Current", 11.280000)
prg.add(25000, "Delta 1 Current", 11.750000)
prg.add(26000, "Delta 1 Current", 12.220000)
prg.add(27000, "Delta 1 Current", 12.690000)
prg.add(28000, "Delta 1 Current", 13.160000)
prg.add(29000, "Delta 1 Current", 13.630000)
prg.add(30000, "Delta 1 Current", 14.100000)
prg.add(31000, "Delta 1 Current", 14.570000)
prg.add(32000, "Delta 1 Current", 15.040000)
prg.add(33000, "Delta 1 Current", 15.510000)
prg.add(34000, "Delta 1 Current", 15.980000)
prg.add(35000, "Delta 1 Current", 16.450000)
prg.add(36000, "Delta 1 Current", 16.920000)
prg.add(37000, "Delta 1 Current", 17.390000)
prg.add(38000, "Delta 1 Current", 17.860000)
prg.add(39000, "Delta 1 Current", 18.330000)
prg.add(40000, "Delta 1 Current", 18.800000)
prg.add(41000, "Delta 1 Current", 19.270000)
prg.add(42000, "Delta 1 Current", 19.740000)
prg.add(43000, "Delta 1 Current", 20.210000)
prg.add(44000, "Delta 1 Current", 20.680000)
prg.add(45000, "Delta 1 Current", 21.150000)
prg.add(46000, "Delta 1 Current", 21.620000)
prg.add(47000, "Delta 1 Current", 22.090000)
prg.add(48000, "Delta 1 Current", 22.560000)
prg.add(49000, "Delta 1 Current", 23.030000)
prg.add(50000, "Delta 1 Current", 23.500000)
prg.add(51000, "Delta 1 Current", 23.970000)
prg.add(52000, "Delta 1 Current", 24.440000)
prg.add(53000, "Delta 1 Current", 24.910000)
prg.add(54000, "Delta 1 Current", 25.380000)
prg.add(55000, "Delta 1 Current", 25.850000)
prg.add(56000, "Delta 1 Current", 26.320000)
prg.add(57000, "Delta 1 Current", 26.790000)
prg.add(58000, "Delta 1 Current", 27.260000)
prg.add(59000, "Delta 1 Current", 27.730000)
prg.add(60000, "Delta 1 Current", 28.200000)
prg.add(61000, "Delta 1 Current", 28.670000)
prg.add(62000, "Delta 1 Current", 29.140000)
prg.add(63000, "Delta 1 Current", 29.610000)
prg.add(64000, "Delta 1 Current", 30.080000)
prg.add(65000, "Delta 1 Current", 30.550000)
prg.add(66000, "Delta 1 Current", 31.020000)
prg.add(67000, "Delta 1 Current", 31.490000)
prg.add(68000, "Delta 1 Current", 31.960000)
prg.add(69000, "Delta 1 Current", 32.430000)
prg.add(70000, "Delta 1 Current", 32.900000)
prg.add(71000, "Delta 1 Current", 33.370000)
prg.add(72000, "Delta 1 Current", 33.840000)
prg.add(73000, "Delta 1 Current", 34.310000)
prg.add(74000, "Delta 1 Current", 34.780000)
prg.add(75000, "Delta 1 Current", 35.250000)
prg.add(76000, "Delta 1 Current", 35.720000)
prg.add(77000, "Delta 1 Current", 36.190000)
prg.add(78000, "Delta 1 Current", 36.660000)
prg.add(79000, "Delta 1 Current", 37.130000)
prg.add(80000, "Delta 1 Current", 37.600000)
prg.add(81000, "Delta 1 Current", 38.070000)
prg.add(82000, "Delta 1 Current", 38.540000)
prg.add(83000, "Delta 1 Current", 39.010000)
prg.add(84000, "Delta 1 Current", 39.480000)
prg.add(85000, "Delta 1 Current", 39.950000)
prg.add(86000, "Delta 1 Current", 40.420000)
prg.add(87000, "Delta 1 Current", 40.890000)
prg.add(88000, "Delta 1 Current", 41.360000)
prg.add(89000, "Delta 1 Current", 41.830000)
prg.add(90000, "Delta 1 Current", 42.300000)
prg.add(91000, "Delta 1 Current", 42.770000)
prg.add(92000, "Delta 1 Current", 43.240000)
prg.add(93000, "Delta 1 Current", 43.710000)
prg.add(94000, "Delta 1 Current", 44.180000)
prg.add(95000, "Delta 1 Current", 44.650000)
prg.add(96000, "Delta 1 Current", 45.120000)
prg.add(97000, "Delta 1 Current", 45.590000)
prg.add(98000, "Delta 1 Current", 46.060000)
prg.add(99000, "Delta 1 Current", 46.530000)
prg.add(100000, "Delta 1 Current", 47.000000)
return prg
| [
"carmelo.mordini@unitn.it"
] | carmelo.mordini@unitn.it |
bc770e9ab63ca5279016744344e0868a658a80a9 | 257bd63361aa846ffdacdc15edaecf84c6364e78 | /psou2/pyanal1/apack1/ex7_t-test.py | 0753bfe9b286ee0d0bd0745aa8b0a95a5414b8f0 | [] | no_license | gom4851/hcjeon | 86dcfd05ce47a13d066f13fe187d6a63142fb9fe | 59a00ca9499f30e50127bb16eb510553e88ace43 | refs/heads/master | 2020-06-04T23:16:08.632278 | 2019-01-15T09:54:08 | 2019-01-15T09:54:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,682 | py | '''
Created on 2018. 11. 29.
두 집단일 때
남녀의 성적, A반과 B반의 키, 경기도와 충청도의 소득 따위의 서로 독립인 두 집단에서 얻은 표본을 독립표본(two sample)이라고 한다.
실습) 남녀 두 집단 간 파이썬 시험의 평균 차이 검정
Male = [75, 85, 100, 72.5, 86.5]
female = [63.2, 76, 52, 100, 70]
'''
from scipy import stats
import pandas as pd
from numpy import average
from pandas.io.parsers import read_csv
# 귀무가설 : 남녀 두 집단 간 파이썬 시험의 평균에 차이가 없다.
# 대립가설 : 남녀 두 집단 간 파이썬 시험의 평균에 차이가 있다.
male = [75, 85, 100, 72.5, 86.5]
female = [63.2, 76, 52, 100, 70]
two_sam = stats.ttest_ind(male, female) # ttest_ind : 집단이 두개일 때 사용. 두 개의 표본에 대한 t 검정.
#two_sam = stats.ttest_ind(male, female, equal_var=True)
print(two_sam)
# T값(검정통계량) : statistic=1.233193127514512, p-value=0.2525076844853278
t, p = two_sam
print('t검정통계량 : {}, p-value : {}'.format(t, p))
# p-value 0.2525 > 0.05 이므로 귀무가설 채택.
print('여 : ', average(female))
print('남 : ', average(male))
print('**' * 30)
'''
실습) 두 가지 교육방법에 따른 평균시험 점수에 대한 검정 수행 two_sample.csv'
'''
data = pd.read_csv("../testdata/two_sample.csv")
print(data.head())
df = data[['method', 'score']]
print(df.head())
#귀무가설 : 두 가지 교육방법에 따른 평균시험 점수에 차이가 없다.
#대립가설 : 두 가지 교육방법에 따른 평균시험에 점수에 차이가 있다.
m1 = df[df['method'] == 1] # 교육방법 1
m2 = df[df['method'] == 2] # 교육방법 2
score1 = m1['score'] # 교육방법 1 점수
score2 = m2['score'] # 교육방법 2 점수
#print('score1')
#print('score2')
# sco1 = score1.fillna())
sco1 = score1.fillna(score1.mean()) # 평균으로 NaN을 대체
sco2 = score2.fillna(score2.mean())
#print(sco2)
# 정규성 확인 : 히스토그램, shapiro()
result = stats.ttest_ind(sco1, sco2)
p, v = result
print('t검정통계량 : {}, p-value : {}'.format(p, v))
# t검정통계량 : -0.1964, p-value : 0.8450.
# p-value : 0.8450 > 0.05 이므로 귀무가설 채택.
print("**" * 30)
'''
* 서로 대응인 두 집단의 평균 차이 검정(paired samples t-test)
처리 이전과 처리 이후를 각각의 모집단으로 판단하여, 동일한 관찰 대상으로부터 처리 이전과 처리 이후를 1:1로
대응시킨 두 집단으로 부터의 표본을 대응표본(paired sample)이라고 한다.
대응인 두 집단의 평균 비교는 동일한 관찰 대상으로부터 처리 이전의 관찰과 이후의 관찰을 비교하여 영향을 미친 정도를 밝히는데 주로 사용하고 있다.
집단 간 비교가 아니므로 등분산 검정을 할 필요가 없다.
실습) 복부 수술 전 9명의 몸무게와 복부 수술 후 몸무게 변화
baseline = [67.2, 67.4, 71.5, 77.6, 86.0, 89.1, 59.5, 81.9, 105.5]
follow_up = [62.4, 64.6, 70.4, 62.6, 80.1, 73.2, 58.2, 71.0, 101.0]
'''
import numpy as np
import seaborn as sns
import matplotlib.pylab as plt
import scipy as sp
# 그냥 랜덤 값으로 해봄..?
np.random.seed(0)
x1 = np.random.normal(100, 10, 100)
x2 = np.random.normal(97, 10, 100)
#print(x1)
# 히스토그램으로 정규성 확인을 위해
sns.distplot(x1, kde=False, fit=sp.stats.norm)
sns.distplot(x2, kde=False, fit=sp.stats.norm)
#plt.show()
print(stats.ttest_rel(x1, x2))
# 실습) 복부 수술 전 9명의 몸무게와 복부 수술 후 몸무게 변화
baseline = [67.2, 67.4, 71.5, 77.6, 86.0, 89.1, 59.5, 81.9, 105.5]
follow_up = [62.4, 64.6, 70.4, 62.6, 80.1, 73.2, 58.2, 71.0, 101.0]
# 귀무가설 : 복부 수술 전/후 몸무게의 차이가 없다.
# 대립가설 : 복부 수술 전/후 몸무게의 차이가 있다.
paird_sam = stats.ttest_rel(baseline, follow_up)
print('t검정통계량 : %.5f, p-value : %.5f'%paird_sam)
# t검정통계량 : 3.66812, p-value : 0.00633
# p-value : 0.00633 < 0.05 이므로 귀무가설 기각.
print("**" * 30)
'''
추론통계 분석 중 비율검정
- 비율검정 특징
: 집단의 비율이 어떤 특정한 값과 같은지를 검증.
: 비율 차이 검정 통계량을 바탕으로 귀무가설의 기각여부를 결정.
'''
'''
# one-sample
A회사에는 100명 중에 45명이 흡연을 한다. 국가 통계를 보니 국민 흡연율은 35%라고 한다. 비율이 같냐?
'''
# 귀무가설 : 국민 흡연률 35%와 비율이 같다.
# 대립가설 : 국민 흡연률 35%와 비율이 다르다.
from statsmodels.stats.proportion import proportions_ztest # 정규표현식에서 x의 값을 z로..?
count = np.array([45]) # 해당 수
nobs = np.array([100]) # 전체 수
val = 0.35 # 비율
#print(count)
z, p = proportions_ztest(count, nobs, val) # proportions_ztest : 추론통계 분석에서 비율검정할 때 씀.
print('z값 : ', z)
print('p-value : ', p)
# 해석 : p-value : 0.04442318 < 0.05 이므로 귀무가설 기각. 비율이 다름.
print("**" * 30)
'''
# two-sample
A회사 사람들 300명 중 100명이 커피를 마시고, B회사 사람들 400명 중 170명이 커피를 마셨다.비율이 같냐?
'''
# 귀무가설 : A회사와 B회사에 사람들이 커피를 마시는 비율은 같다.
# 대립가설 : A회사와 B회사에 사람들이 커피를 마시는 비율은 다르다.
count = np.array([100, 170]) # 해당 수.
nobs = np.array([300, 400]) # 전체 수.
z, p = proportions_ztest(count, nobs, value=0)
print('z값 : ', z)
print('p-value : ', p)
# 해석 : p-value : 0.013 < 0.05 이므로 귀무가설 기각. 비율이 다름. | [
"wer104@naver.com"
] | wer104@naver.com |
9d600cce89991aa6203255279e0ca1a38c358019 | 9dda81fb80905226b10e69d4c20f72533f2b68bd | /word4u/settings.py | 428f2f62207b14eda69e375e388e9fc7056bd2e4 | [] | no_license | SardarDawar/graphicStore-ecommerce | 2c610d6ef4e62d98659bf98d3d80af3d1926aa3f | 1d9208d27e4ba69bedf7a34b7e54bcc540d26438 | refs/heads/master | 2023-02-02T13:45:31.335032 | 2020-12-15T18:52:43 | 2020-12-15T18:52:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,231 | py | """
Django settings for word4u project.
Generated by 'django-admin startproject' using Django 3.1.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'd*mwv+8mla!+u^kze0!o3l#qlfjd(%z&!-=svuhzqwy!m8)8rw'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'home',
'products',
'personalise',
'bag',
'checkout',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'word4u.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
os.path.join(BASE_DIR, 'templates', 'allauth'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'bag.context_processors.cart',
],
},
},
]
AUTHENTICATION_BACKENDS = [
# Needed to login by username in Django admin, regardless of `allauth`
'django.contrib.auth.backends.ModelBackend',
# `allauth` specific authentication methods, such as login by e-mail
'allauth.account.auth_backends.AuthenticationBackend',
]
SITE_ID = 1
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
ACCOUNT_AUTHENTICATION_METHOD = 'username_email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
ACCOUNT_SIGNUP_EMAIL_ENTER_TWICE = True
ACCOUNT_USERNAME_MIN_LENGTH = 4
LOGIN_URL = '/accounts/login/'
LOGIN_REDIRECT_URL = '/'
WSGI_APPLICATION = 'word4u.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
BUNDLE_DISCOUNT_THRESHOLD = 29.99
##### Cart Session ######
CART_SESSION_ID = 'cart' | [
"dawarsardar786@gmail.com"
] | dawarsardar786@gmail.com |
044ee99b8b988b65ecbc2c2dec1ecf70dd5fdc3e | 4f7319f90b9ea3bfdae13a59885b917db6037164 | /utils.py | 25d30a4ee9fd42b0e27142b1d9901d93f4fa377a | [] | no_license | DmytroKaminskiy/hillel-git | c78eb3b52b0a827527421cb2fef6e09eebf23e6d | d42f7d8f441333f83cfe5e57b7aa744737891acc | refs/heads/main | 2023-02-12T01:16:55.017896 | 2021-01-14T19:26:23 | 2021-01-14T19:26:23 | 323,099,692 | 0 | 0 | null | 2020-12-24T19:20:24 | 2020-12-20T15:10:59 | Python | UTF-8 | Python | false | false | 4,124 | py | def generate_password(length: int) -> str:
"""
generate password with given length
Homework
функция должна возвращать строку из случайных символов заданной длины.
"""
return ''
def encrypt_message(message: str) -> str:
"""
encrypt message
зашифровать сообщение по алгоритму.
Сместить каждый символ по ASCII таблице на заданное рассояние.
"""
key = 2
return ''.join(
chr(num + key)
for num in map(ord, message)
)
def lucky_number(ticket: str) -> bool:
"""
lucky number (tram ticket)
667766 - is lucky (6 + 6 + 7 == 7 + 6 + 6)
сумма первых трех числе должна равняться сумме последних трех чисел
"""
return True
def fizz_buzz(num: int) -> str:
"""
fizz buzz
усли число, кратно трем, программа должна выводить слово «Fizz»,
а вместо чисел, кратных пяти — слово «Buzz».
Если число кратно и 3, и 5, то программа должна выводить слово «FizzBuzz»
в остальных случаях число как строку
"""
return ''
def password_is_strong(password) -> bool:
"""
is password is strong
(has number, char, lowercase, uppercase, at least length is 10)
вернуть True если пароль надежный
Праметры:
1. Пароль должен содержать как минимум одну цифру
2. Пароль должен содержать как минимум один сивол в нижнем регистре
3. Пароль должен содержать как минимум один сивол в верхнем регистре
4. Пароль должен быть как минимум 10 символов
"""
return True
def number_is_prime(num: int) -> bool:
"""
number is prime
на вход принимаем число
вернуть True если число является простым
https://ru.wikipedia.org/wiki/%D0%9F%D1%80%D0%BE%D1%81%D1%82%D0%BE%D0%B5_%D1%87%D0%B8%D1%81%D0%BB%D0%BE#:~:text=2%2C%203%2C%205%2C%207,%D1%87%D0%B8%D1%81%D0%BB%D0%B0%20%D0%B1%D1%8B%D1%82%D1%8C%20%D0%BF%D1%80%D0%BE%D1%81%D1%82%D1%8B%D0%BC%20%D0%BD%D0%B0%D0%B7%D1%8B%D0%B2%D0%B0%D0%B5%D1%82%D1%81%D1%8F%20%D0%BF%D1%80%D0%BE%D1%81%D1%82%D0%BE%D1%82%D0%BE%D0%B9.
"""
return True
def decrypt_message(message: str) -> str:
"""
decrypt message
функция обратная encrypt_message
Расшифровать сообщение по заданному ключу
"""
return ''
def volume_of_sphere(radius: float) -> float:
"""
Volume of a Sphere
на вход принимаем радиус сферы.
Необходимо рассчитать объем сферы и округлить результат до двух знаков после точки
round to 2 places
"""
return 0.0
def days_diff(start_date: ..., end_date: ...) -> int:
"""
calculate number of days between two dates.
найти разницу между двумя датами
"""
return 0
def prs(client_choice: str) -> bool:
"""
paper rock scissors
принимаем значение от клиента из списка значений (например ['p', 'r', 's'])
сгенерировать случайный выбор на сервере
реализовать игру в камень-ножницы-бумага между клиент-сервер
"""
return True
def integer_as_roman(integer: int) -> str:
"""
***
integer to Roman Number
вывести значение в виде римского числа
"""
return ''
if __name__ == '__main__':
assert encrypt_message('Dima') == 'Fkoc'
| [
"dmytro.kaminskyi92@gmail.com"
] | dmytro.kaminskyi92@gmail.com |
16479781a6eaec6b633cfb0c482675ebfec21d1c | f1fe131614660a04e4fe4ad27b5183ffe2b2a6e4 | /2020/22a.py | adf2ab439b15c787a0786490d4ad786d1b4b22f6 | [
"MIT"
] | permissive | msullivan/advent-of-code | 5873228d562c1069d6516ee99943013bc91c4caa | e52c93e2ffa1e598f23e6d0e356b54c5e82ee61d | refs/heads/master | 2023-01-04T07:14:46.367051 | 2023-01-03T19:04:12 | 2023-01-03T19:04:12 | 47,717,709 | 9 | 4 | MIT | 2022-12-07T19:39:52 | 2015-12-09T20:41:00 | Python | UTF-8 | Python | false | false | 721 | py | #!/usr/bin/env python3
import sys
import re
def extract(s):
return [int(x) for x in re.findall(r'-?\d+', s)]
def main(args):
data = [x.strip().split('\n') for x in sys.stdin.read().split('\n\n')]
# data = [s.strip() for s in sys.stdin]
d1 = [int(x) for x in data[0][1:]]
d2 = [int(x) for x in data[1][1:]]
while d1 and d2:
x1 = d1.pop(0)
x2 = d2.pop(0)
if x1 > x2:
d1.append(x1)
d1.append(x2)
else:
d2.append(x2)
d2.append(x1)
print(d1, d2)
xs = list(reversed(d1 + d2))
s = 0
for i, x in enumerate(xs):
s += (i+1)*x
print(s)
if __name__ == '__main__':
sys.exit(main(sys.argv))
| [
"sully@msully.net"
] | sully@msully.net |
951f0b687ce2c59a9cbbd6d74b48fae3832ff058 | 77311ad9622a7d8b88707d7cee3f44de7c8860cb | /res/scripts/client/gui/miniclient/lobby/header/account_popover.py | f40f37a1d090fd11f2dd1dc02f387086e216e1ab | [] | no_license | webiumsk/WOT-0.9.14-CT | 9b193191505a4560df4e872e022eebf59308057e | cfe0b03e511d02c36ce185f308eb48f13ecc05ca | refs/heads/master | 2021-01-10T02:14:10.830715 | 2016-02-14T11:59:59 | 2016-02-14T11:59:59 | 51,606,676 | 0 | 0 | null | null | null | null | WINDOWS-1250 | Python | false | false | 2,474 | py | # 2016.02.14 12:38:06 Střední Evropa (běžný čas)
# Embedded file name: scripts/client/gui/miniclient/lobby/header/account_popover.py
from gui.Scaleform.locale.MINICLIENT import MINICLIENT
from gui.shared.utils.functions import makeTooltip
from helpers import aop
from helpers.i18n import makeString as _ms
class ClanBtnsUnavailableAspect(aop.Aspect):
def atReturn(self, cd):
original_return_value = cd.returned
warnTooltip = makeTooltip(None, None, None, _ms(MINICLIENT.ACCOUNTPOPOVER_WARNING))
original_return_value['btnTooltip'] = warnTooltip
original_return_value['requestInviteBtnTooltip'] = warnTooltip
original_return_value['searchClanTooltip'] = warnTooltip
original_return_value['isOpenInviteBtnEnabled'] = False
original_return_value['isSearchClanBtnEnabled'] = False
original_return_value['btnEnabled'] = False
return original_return_value
class MyClanInvitesBtnUnavailableAspect(aop.Aspect):
def atReturn(self, cd):
original_return_value = cd.returned
original_return_value['inviteBtnTooltip'] = makeTooltip(None, None, None, _ms(MINICLIENT.ACCOUNTPOPOVER_WARNING))
original_return_value['inviteBtnEnabled'] = False
return original_return_value
class ClanBtnsUnavailable(aop.Pointcut):
def __init__(self):
aop.Pointcut.__init__(self, 'gui.Scaleform.daapi.view.lobby.header.AccountPopover', 'AccountPopover', '_getClanBtnsParams', aspects=(ClanBtnsUnavailableAspect,))
class MyClanInvitesBtnUnavailable(aop.Pointcut):
def __init__(self):
aop.Pointcut.__init__(self, 'gui.Scaleform.daapi.view.lobby.header.AccountPopover', 'AccountPopover', '_getMyInvitesBtnParams', aspects=(MyClanInvitesBtnUnavailableAspect,))
class CrewButtonStatusAspect(aop.Aspect):
def atCall(self, cd):
cd.avoid()
return {'isEnabled': False,
'disabledTooltip': _ms('#menu:header/account/popover/crew_button/disabledTooltip')}
class CrewButtonStatusPointcut(aop.Pointcut):
def __init__(self):
aop.Pointcut.__init__(self, 'gui.Scaleform.daapi.view.lobby.header.AccountPopover', 'AccountPopover', '_crewDataButtonStatus', aspects=(CrewButtonStatusAspect,))
# okay decompyling c:\Users\PC\wotsources\files\originals\res\scripts\client\gui\miniclient\lobby\header\account_popover.pyc
# decompiled 1 files: 1 okay, 0 failed, 0 verify failed
# 2016.02.14 12:38:06 Střední Evropa (běžný čas)
| [
"info@webium.sk"
] | info@webium.sk |
560fd9677d919732ed6f5c0c072bed734de5e606 | 626b14ce13986b6d5e03143e151004247659625a | /Day66-75/code/myutils.py | e013c27a881545e2cececd53c451c5dc84ae478a | [] | no_license | Focavn/Python-100-Days | c7586ecf7ae3f1fd42f024558bb998be23ee9df8 | d8de6307aeff9fe31fd752bd7725b9cc3fbc084b | refs/heads/master | 2021-08-08T17:57:02.025178 | 2020-09-17T11:58:04 | 2020-09-17T11:58:04 | 220,427,144 | 0 | 0 | null | 2019-11-08T08:59:43 | 2019-11-08T08:59:41 | null | UTF-8 | Python | false | false | 202 | py | from functools import wraps
def coroutine(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
gen = fn(*args, **kwargs)
next(gen)
return gen
return wrapper
| [
"Focavn@users.github.com"
] | Focavn@users.github.com |
72653be3b07d719ad692e5faa92e16a8f3b42b58 | 9adc810b07f7172a7d0341f0b38088b4f5829cf4 | /experiments/ashvin/icml2020/process_data/consolidate.py | ce20ffe52de5597a4618268be84969ec69785382 | [
"MIT"
] | permissive | Asap7772/railrl_evalsawyer | 7ee9358b5277b9ddf2468f0c6d28beb92a5a0879 | baba8ce634d32a48c7dfe4dc03b123e18e96e0a3 | refs/heads/main | 2023-05-29T10:00:50.126508 | 2021-06-18T03:08:12 | 2021-06-18T03:08:12 | 375,810,557 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,393 | py | import pickle
import glob
import numpy as np
def print_stats(data):
returns = []
path_lengths = []
print("num trajectories", len(data))
for path in data:
rewards = path["rewards"]
returns.append(np.sum(rewards))
path_lengths.append(len(rewards))
print("returns")
print("min", np.min(returns))
print("max", np.max(returns))
print("mean", np.mean(returns))
print("std", np.std(returns))
print("path lengths")
print("min", np.min(path_lengths))
print("max", np.max(path_lengths))
print("mean", np.mean(path_lengths))
print("std", np.std(path_lengths))
# input_patterns = [
# "/home/ashvin/data/s3doodad/ashvin/icml2020/hand/pen/demo-bc1/run5/id0/video_*.p",
# ]
# output_file = "/home/ashvin/data/s3doodad/demos/icml2020/hand/pen_bc1.npy"
# input_patterns = [
# "/home/ashvin/data/s3doodad/ashvin/icml2020/hand/pen/demo-bc5/run0/id*/video_*.p",
# ]
# output_file = "/home/ashvin/data/s3doodad/demos/icml2020/hand/pen_bc2.npy"
# input_patterns = [
# "/home/ashvin/data/s3doodad/ashvin/icml2020/hand/pen/demo-bc5/run4/id*/video_*.p",
# ]
# output_file = "/home/ashvin/data/s3doodad/demos/icml2020/hand/pen_bc3.npy"
# input_patterns = [
# "/home/ashvin/data/s3doodad/ashvin/icml2020/hand/pen/demo-bc5/run4/id*/video_*vae.p",
# ]
# output_file = "/home/ashvin/data/s3doodad/demos/icml2020/hand/pen_bc3_vae.npy"
# input_patterns = [
# "/home/ashvin/data/s3doodad/ashvin/icml2020/hand/pen/demo-bc5/run4/id*/video_*env.p",
# ]
# output_file = "/home/ashvin/data/s3doodad/demos/icml2020/hand/pen_bc3_env.npy"
# input_patterns = [
# "/home/ashvin/data/s3doodad/ashvin/icml2020/hand/pen/demo-bc5/run6/id*/video_*vae.p",
# ]
# output_file = "/home/ashvin/data/s3doodad/demos/icml2020/hand/pen_bc4_vae.npy"
# input_patterns = [
# "/home/ashvin/data/s3doodad/ashvin/icml2020/hand/door/demo-bc5/run2/id*/video_*.p",
# ]
# output_file = "/home/ashvin/data/s3doodad/demos/icml2020/hand/door_bc1.npy"
# input_patterns = [
# "/home/ashvin/data/s3doodad/ashvin/icml2020/hand/hammer/demo-bc1/run0/id*/video_*.p",
# ]
# output_file = "/home/ashvin/data/s3doodad/demos/icml2020/hand/hammer_bc1.npy"
# input_patterns = [
# "/home/ashvin/data/s3doodad/ashvin/icml2020/hand/relocate/demo-bc1/run0/id*/video_*.p",
# ]
# output_file = "/home/ashvin/data/s3doodad/demos/icml2020/hand/relocate_bc1.npy"
# input_patterns = [
# "/home/ashvin/data/s3doodad/ashvin/icml2020/hand/door/bc/bc-data1/run0/id*/video_*.p",
# ]
# output_file = "/home/ashvin/data/s3doodad/demos/icml2020/hand/door_bc2.npy"
input_patterns = [
"/media/ashvin/data2/s3doodad/ashvin/rfeatures/rlbench/open-drawer-vision3/td3bc-with-state3/run0/id0/video_*_vae.p",
]
output_file = "/home/ashvin/data/s3doodad/demos/icml2020/rlbench/rlbench_bc1.npy"
data = []
for pattern in input_patterns:
for file in glob.glob(pattern):
d = pickle.load(open(file, "rb"))
print(file, len(d))
for path in d: # for deleting image observations
for i in range(len(path["observations"])):
ob = path["observations"][i]
keys = list(ob.keys())
for key in keys:
if key != "state_observation":
del ob[key]
data.extend(d)
pickle.dump(data, open(output_file, "wb"))
print(output_file)
print_stats(data)
| [
"alexanderkhazatsky@gmail.com"
] | alexanderkhazatsky@gmail.com |
d955f629b3a6c204796080da55b86f3e501fa3d8 | 3312b5066954cbf96c79ef3e1f3d582b31ebc5ae | /colegend/events/migrations/0003_auto_20161127_1814.py | dd7c171af96b65ca770497884530df6b420a88a0 | [] | no_license | Eraldo/colegend | d3f3c2c37f3bade7a3a1e10d307d49db225fe7f5 | 2e7b9d27887d7663b8d0d1930c2397c98e9fa1fc | refs/heads/master | 2021-01-16T23:32:09.245967 | 2020-10-07T12:12:14 | 2020-10-07T12:12:14 | 21,119,074 | 4 | 2 | null | null | null | null | UTF-8 | Python | false | false | 779 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-27 17:14
from __future__ import unicode_literals
import colegend.cms.blocks
from django.db import migrations
import wagtail.core.blocks
import wagtail.core.fields
class Migration(migrations.Migration):
dependencies = [
('events', '0002_auto_20160711_2253'),
]
operations = [
migrations.AlterField(
model_name='eventspage',
name='content',
field=wagtail.core.fields.StreamField((('heading', colegend.cms.blocks.HeadingBlock()), ('rich_text', colegend.cms.blocks.RichTextBlock()), ('image', colegend.cms.blocks.ImageBlock()), ('embed', colegend.cms.blocks.EmbedBlock()), ('html', wagtail.core.blocks.RawHTMLBlock())), blank=True),
),
]
| [
"eraldo@eraldo.org"
] | eraldo@eraldo.org |
3294f3bed75b66731462f43071b989c78c1010b7 | a0801d0e7325b31f0383fc68517e208680bb36d6 | /ProjectEuler/142.py | 85d8bf0fe2a06c44ae1c87bb45a122ac7a0c6bae | [] | no_license | conormccauley1999/CompetitiveProgramming | bd649bf04438817c7fa4755df2c2c7727273b073 | a7e188767364be40f625612af3d16182f2d8d4de | refs/heads/master | 2023-05-14T13:19:32.678134 | 2023-05-11T16:07:33 | 2023-05-11T16:07:33 | 179,089,010 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 586 | py | MX = 1000000
squares = set([n * n for n in range(1, MX)])
for i in range(1, MX):
s1 = i * i
for j in range(1, i):
s2 = j * j
s3 = s1 - s2
if s3 not in squares: continue
for k in range(1, j):
s4 = k * k
s5 = s1 - s4
s6 = s2 - s5
if s5 not in squares or s6 not in squares: continue
x = (s1 + s6) // 2
y = (s3 + s5) // 2
z = (s2 - s4) // 2
if all(s in squares for s in [x+y,x-y,x+z,x-z,y+z,y-z]):
print(x + y + z)
quit()
| [
"conormccauley1999@gmail.com"
] | conormccauley1999@gmail.com |
9acd75923def0033845f2bee8b1a89f62688789c | 0486b6ccf883e9cd7a24bbd89b5420e7de2172b9 | /DRF Study Material/Django REST Code/gs1/api/migrations/0001_initial.py | 3f7e085f4200f8573144c16f9a572d21f27b04b6 | [] | no_license | ajitexl/restfrmaework | 2980203d7faa6c8364288283758d32c8f2a37817 | 9ab203748e623516365d9924dcc68acc786a66e1 | refs/heads/main | 2023-02-03T08:52:00.672047 | 2020-12-10T09:50:51 | 2020-12-10T09:50:51 | 320,222,997 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 619 | py | # Generated by Django 3.1.1 on 2020-10-08 15:51
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Student',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('roll', models.IntegerField()),
('city', models.CharField(max_length=100)),
],
),
]
| [
"you@example.com"
] | you@example.com |
2d71ffa6cfe0c24d3bfbca19a207ee4695593d52 | c6057a6cc2cf02aa6b9aa877402e84b9cb0bf596 | /commands.py | 3a15d2dbb00813a78c73f9957bd202d12eb83de3 | [] | no_license | DollaR84/HotSound | 372b3e7bd585fa1dc14e31d9fbd0364f7293e1ce | a969f2faac6dfef3b12f69960052f33f77c0de61 | refs/heads/master | 2023-03-25T18:20:56.941975 | 2020-04-08T07:55:08 | 2020-04-08T07:55:08 | 351,373,891 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,502 | py | """
Commands for graphical interface.
Created on 12.02.2020
@author: Ruslan Dolovanyuk
"""
import webbrowser
from dialogs.dialogs import About
from dialogs.dialogs import Message
from linker import Linker
from player import Player
import version
import wx
class Commands:
"""Helper class, contains command for bind events, menu and buttons."""
def __init__(self, drawer):
"""Initialization commands class."""
self.drawer = drawer
self.phrases = self.drawer.phrases
self.message = Message(self.drawer)
self.linker = Linker()
self.player = Player()
self.config = self.drawer.config
self.config.get_outputs = self.player.get_outputs
self.player.config = self.config
self.wildcard = 'Wave files (*.wav)|*.wav|' \
'All files (*.*)|*.*'
self.__mods = [
wx.WXK_CONTROL,
wx.WXK_SHIFT,
wx.WXK_ALT,
wx.WXK_WINDOWS_LEFT,
wx.WXK_WINDOWS_RIGHT,
wx.WXK_WINDOWS_MENU,
]
self.set_window()
def set_window(self):
"""Set size and position window from saving data."""
self.drawer.SetPosition(self.config.get_pos())
self.drawer.SetSize(self.config.get_size())
self.drawer.Layout()
def donate(self, event):
"""Run donate hyperlink in browser."""
webbrowser.open(self.config.donate_url)
def about(self, event):
"""Run about dialog."""
About(
self.drawer,
self.phrases.about.title,
self.phrases.about.name,
version.VERSION,
self.phrases.about.author
).ShowModal()
def close(self, event):
"""Close event for button close."""
self.drawer.Close(True)
def close_window(self, event):
"""Close window event."""
self.config.set_pos(self.drawer.GetScreenPosition())
self.config.set_size(self.drawer.GetSize())
self.config.close()
self.linker.close()
self.player.close()
self.drawer.Destroy()
def options(self, event):
"""Run settings dialog."""
self.config.open_settings(self.drawer)
def get_path_file(self):
"""Return path wave file."""
path = ''
file_dlg = wx.FileDialog(self.drawer, self.phrases.titles.choice_file, '', '', self.wildcard, style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
if wx.ID_OK == file_dlg.ShowModal():
path = file_dlg.GetPath()
file_dlg.Destroy()
return path
def process(self, event):
"""Main process eventer for button."""
keycode = event.GetKeyCode()
if not keycode in self.__mods:
if event.CmdDown() and event.ShiftDown():
self.linker.del_link(keycode)
self.drawer.data.SetValue(self.linker.get_all_links())
self.drawer.Layout()
elif event.CmdDown():
path = self.get_path_file()
if path != '':
self.linker.set_link(keycode, path)
self.drawer.data.SetValue(self.linker.get_all_links())
self.drawer.Layout()
else:
path = self.linker.get_link(keycode)
if path is not None:
self.player.play(path)
event.Skip()
| [
"cooler84@ukr.net"
] | cooler84@ukr.net |
f131821fc8232df89ad26250894a2c7c8d50ae4a | 8ef8e6818c977c26d937d09b46be0d748022ea09 | /cv/detection/autoassign/pytorch/mmdet/core/bbox/coder/base_bbox_coder.py | 0872bf008b42d3e9056ce17ea135c7d8ba18c92a | [
"Apache-2.0"
] | permissive | Deep-Spark/DeepSparkHub | eb5996607e63ccd2c706789f64b3cc0070e7f8ef | 9d643e88946fc4a24f2d4d073c08b05ea693f4c5 | refs/heads/master | 2023-09-01T11:26:49.648759 | 2023-08-25T01:50:18 | 2023-08-25T01:50:18 | 534,133,249 | 7 | 6 | Apache-2.0 | 2023-03-28T02:54:59 | 2022-09-08T09:07:01 | Python | UTF-8 | Python | false | false | 514 | py | # Copyright (c) OpenMMLab. All rights reserved.
from abc import ABCMeta, abstractmethod
class BaseBBoxCoder(metaclass=ABCMeta):
"""Base bounding box coder."""
def __init__(self, **kwargs):
pass
@abstractmethod
def encode(self, bboxes, gt_bboxes):
"""Encode deltas between bboxes and ground truth boxes."""
@abstractmethod
def decode(self, bboxes, bboxes_pred):
"""Decode the predicted bboxes according to prediction and base
boxes."""
| [
"jia.guo@iluvatar.ai"
] | jia.guo@iluvatar.ai |
4dad4fd1062e9275b9c9a467a5b2a23d31a1b62d | 3d06eeebdd598efba25d29d7e3d03d90ede1bfbd | /15_lesson(django)/itProger/blog/migrations/0001_initial.py | 2f69d752487a523064c5052cc3a50ad5bc00220d | [] | no_license | duk1edev/itproger | 58bdd16088dec7864585d318935b118ce584874d | 786f94fff6d816f3f978bd8c24c3d985ffd5ffb2 | refs/heads/master | 2021-01-02T02:43:32.684100 | 2020-03-28T18:10:25 | 2020-03-28T18:10:25 | 239,443,309 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 897 | py | # Generated by Django 3.0.4 on 2020-03-13 23:17
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='News',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100)),
('text', models.TextField()),
('date', models.DateTimeField(default=django.utils.timezone.now)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| [
"duk1e.ptc.ua@yandex.ru"
] | duk1e.ptc.ua@yandex.ru |
d8f2a9320c7bf9881c95e4b343f6339d2052933b | bd02997a44218468b155eda45dd9dd592bb3d124 | /baekjoon_2146_3.py | b09cb7e0c56e5b92cbe28541d979b1e838604d8d | [] | no_license | rheehot/ProblemSolving_Python | 88b1eb303ab97624ae6c97e05393352695038d14 | 4d6dc6aea628f0e6e96530646c66216bf489427f | refs/heads/master | 2023-02-13T03:30:07.039231 | 2021-01-04T06:04:11 | 2021-01-04T06:04:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,968 | py | '''
Problem Solving Baekjoon 2146_3
Author: Injun Son
Date: Dec 21, 2020
'''
import sys
sys.setrecursionlimit(10 ** 6)
from collections import deque
N = int(input())
graph = [list(map(int, input().split())) for _ in range(N)]
check = [[False] * N for _ in range(N)]
dx = [-1, 0, 0, 1]
dy = [0, 1, -1, 0]
ans = sys.maxsize
count = 1
def print_board(board):
for i in range(N):
for j in range(N):
print(board[i][j], end=" ")
print("")
# 각 섬에 번호를 붙여줘서 그룹핑하는 함수
def dfs(y, x):
global count
check[y][x] = True
graph[y][x] = count
for i in range(4):
ny, nx = y + dy[i], x + dx[i]
if ny < 0 or ny >= N or nx < 0 or nx >= N:
continue
if check[ny][nx] == False and graph[ny][nx]:
dfs(ny, nx)
def bfs(z):
global ans
dist = [[-1] * N for _ in range(N)]
q = deque()
for i in range(N): # 섬들의 위치 모두 큐에 저장
for j in range(N):
if graph[i][j] == z:
q.append([i, j])
dist[i][j] = 0
while q:
y, x = q.popleft()
for i in range(4):
ny, nx = y + dy[i], x + dx[i]
if ny < 0 or ny >= N or nx < 0 or nx >= N:
continue
# 다른 섬에 도착한 경우
if graph[ny][nx] > 0 and graph[ny][nx] != z:
ans = min(ans, dist[y][x])
return
# 만약 바다이고, 간척 사업도 안된 곳이라면 새로 거리를 더해준다
if graph[ny][nx] == 0 and dist[ny][nx] == -1:
dist[ny][nx] = dist[y][x] + 1
q.append([ny, nx])
for i in range(N):
for j in range(N):
if check[i][j] == False and graph[i][j] == 1:
dfs(i, j)
count += 1
# 각각의 섬에 대하여 bfs로 간척을 하여 다른 섬에 도달한다
for i in range(1, count):
bfs(i)
print(ans)
| [
"ison@sfu.ca"
] | ison@sfu.ca |
b1a25edd516630842446acf3d6b63f6392f82110 | 41249d7d4ca9950b9c6fee89bf7e2c1929629767 | /results/lmg_optimizations_50spins_criticalpoint_diffConstraints_20200617/script_lmg_crab4freq_neldermead_bound08_fixedInitialPoints_tf2.py | 3d216507ee0ed4e33aa36db3e1ff63d419d92a85 | [
"MIT"
] | permissive | lucainnocenti/ultrafast-critical-ground-state-preparation-2007.07381 | f739b3baad1d2aadda576303bb0bbe9d48ec204a | 29f80dcf914096555cee9bc2e18249a2c95d6a50 | refs/heads/master | 2022-11-22T00:44:09.998199 | 2020-07-21T08:35:28 | 2020-07-21T08:35:28 | 281,237,037 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,596 | py | import os
import sys
import numpy as np
import pandas as pd
import logging
if '../../' not in sys.path:
sys.path.append('../../')
import src.optimization as optimization
import src.protocol_ansatz as protocol_ansatz
from src.utils import autonumber_filename, basic_logger_configuration
output_file_name = os.path.basename(__file__)[7:-3] + '.csv'
output_file_name = autonumber_filename(output_file_name)
basic_logger_configuration(filename=output_file_name[:-3] + 'log')
logging.info('Output file name will be "{}"'.format(output_file_name))
# ------ start optimization
num_frequencies = 4
protocol = protocol_ansatz.CRABProtocolAnsatz(num_frequencies=num_frequencies)
protocol.generate_rnd_frequencies_each_tf = False
for idx in range(num_frequencies):
protocol.hyperpars['nuk' + str(idx + 1)] = 0
protocol.fill_hyperpar_value(y0=0, y1=1)
results = optimization.find_best_protocol(
problem_specification=dict(
model='lmg',
model_parameters=dict(num_spins=50),
task=dict(initial_intensity=0, final_intensity=1)
),
optimization_specs=dict(
protocol=protocol,
protocol_options=dict(num_frequencies=num_frequencies),
optimization_method='Nelder-Mead',
parameters_constraints=[-8, 8],
initial_parameters=[0] * (2 * num_frequencies),
optimization_options=dict(maxiter=1e5, maxfev=1e5,
xatol=1e-8, fatol=1e-8, adaptive=True)
),
other_options=dict(
scan_times=np.linspace(0.01, 2, 100)
)
)
# ------ save results to file
results.to_csv(output_file_name)
| [
"lukeinnocenti@gmail.com"
] | lukeinnocenti@gmail.com |
931f4d5d28fbb6cd5865f176db4d037f806c9964 | d86e9d59784097a7262fa9337585a36bd58a6d29 | /cvxbenchmarks/lib/data/epsilon/epopt/problems/robust_pca.py | d0cb3237223924c12733872e4563a3ff724d0b0c | [] | no_license | nishi951/cvxbenchmarks | 2ae36e75c42c8bd35fafac98bad5d9d88168bd68 | 932141d8e4e929860011bf25c41e941e2f8fbd76 | refs/heads/master | 2021-01-11T07:23:32.260811 | 2018-09-15T22:23:14 | 2018-09-15T22:23:14 | 62,177,196 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 472 | py | import cvxpy as cp
import numpy as np
import scipy.sparse as sp
def create(n, r=10, density=0.1):
np.random.seed(0)
L1 = np.random.randn(n,r)
L2 = np.random.randn(r,n)
L0 = L1.dot(L2)
S0 = sp.rand(n, n, density)
S0.data = 10*np.random.randn(len(S0.data))
M = L0 + S0
lam = 0.1
L = cp.Variable(n, n)
S = cp.Variable(n, n)
f = cp.norm(L, "nuc") + lam*cp.norm1(S)
C = [L + S == M]
return cp.Problem(cp.Minimize(f), C)
| [
"nishimuramarky@yahoo.com"
] | nishimuramarky@yahoo.com |
8982bb30bc58de5af180ccd22ab752d94dcc2df1 | c50cf19707ecf44c8e15acf0e994d288fe4f01a7 | /addition/migrations/0005_auto_20160420_1600.py | dbc95f4b80f196cabb9c51f3bd641a0ee163e56f | [
"MIT"
] | permissive | JeremyParker/idlecars-backend | ee5981356c60161dee05c22e01e5c913e73083c0 | 819cce48e4679d61164b238b81dab0e4d51b8afa | refs/heads/master | 2021-03-16T04:29:43.287760 | 2018-03-03T23:16:02 | 2018-03-03T23:16:02 | 31,734,223 | 3 | 1 | null | null | null | null | UTF-8 | Python | false | false | 533 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('addition', '0004_addition_created_time'),
]
operations = [
migrations.RemoveField(
model_name='addition',
name='defensive_cert_image',
),
migrations.AddField(
model_name='addition',
name='ssn',
field=models.CharField(max_length=9, blank=True),
),
]
| [
"github@jeremyparker.org"
] | github@jeremyparker.org |
6fe457cbf36eb7f66a569eb0d932fb84baac199e | 1e9c67785cd2a07fbd12b63bd93a2eba2272f237 | /gcn1/parameters.py | 90f131240639bd833f76ced834fd592e8188d5d6 | [] | no_license | monisha-jega/mmd | 2975d0f77bce4db38795fa201f515f35498f0eb3 | d4f9d2c94409c2877ff5a5a2242e7e7ed2f87921 | refs/heads/master | 2022-07-20T17:01:39.043859 | 2020-05-16T23:31:35 | 2020-05-16T23:31:35 | 264,543,426 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,170 | py | # train_dir = "/scratch/scratch2/monishaj/dataset/v1/valid/"
# val_dir = "/scratch/scratch2/monishaj/dataset/v1/valid/"
# test_dir = "/scratch/scratch2/monishaj/dataset/v1/test/"
# data_dump_dir = "/scratch/scratch2/monishaj/image_data_dump_SN/"
# model_dump_dir = "/scratch/scratch2/monishaj/image_model_dump_SN/"
# #Must contain ImageUrlToIndex.pkl and annoy.ann
# annoy_dir = '/scratch/scratch2/monishaj/image_annoy_index/'
# #Word embeddings file
# embed_file = '../../GoogleNews-vectors-negative300.bin'
train_dir = "../../dataset/v1/train/"
val_dir = "../../dataset/v1/valid/"
test_dir = "../../dataset/v1/test/"
data_dump_dir = "data_dump/"
model_dump_dir = "model_dump/"
#Must contain ImageUrlToIndex.pkl and annoy.ann
annoy_dir = '../../raw_catalog/image_annoy_index/'
#Word embeddings file
embed_file = '../../GoogleNews-vectors-negative300.bin'
start_word = "</s>"
start_word_id = 0
end_word = "</e>"
end_word_id = 1
pad_word = "<pad>"
pad_word_id = 2
unk_word = "<unk>"
unk_word_id = 3
max_dialogue_len = max_context_len = 20 #Time steps for dialogue (Number of utterances in a dialogue)
#max_dialogue_len is used while preprocessing data, while max_context_len is used during training
max_utter_len = 30 #Time steps for utterance (Number of words in a utterance)
num_neg_images_sample = 100 #Number of negative images to train against
num_neg_images_use = 5 #Number of negative images to test against
num_images_in_context = 5
num_nodes = max_context_len * (1 + num_images_in_context)
word_embedding_size = 300
image_size = 4096
image_embedding_size = 512
cell_state_size = 512
gcn_layer1_out_size = 500
batch_size = 10 #best value - 64
vocab_freq_cutoff = 4 #best value - 4
learning_rate=0.0004 #best value - 0.0004
max_gradient_norm = 0.1 #best value - 0.1
epochs = 10 #best value - Early stopping
use_random_neg_images = False #If True, random images are sampled for negative images used in read_data_*.py)
use_images = False #If False, will use 0s for image instead of loading from annoy file
restore_trained = False #If True, will restore latest model from checkpoint | [
"monishaj@Monishas-MacBook-Pro.local"
] | monishaj@Monishas-MacBook-Pro.local |
13f35bebc83121ef7c3b39ca0bd9121a7e9981ce | d09c6ff7114f69a9326883c5b9fcc70fa994e8a2 | /_pycharm_skeletons/renderdoc/GLFBO.py | 22543193e763b3990fca10ebdc726c68f718ce92 | [
"MIT"
] | permissive | Lex-DRL/renderdoc-py-stubs | 3dd32d23c0c8219bb66387e6078244cff453cd83 | 75d280e4f500ded506f3315a49fc432b37ab4fa6 | refs/heads/master | 2020-08-22T16:55:39.336657 | 2019-11-03T01:21:26 | 2019-11-03T01:21:26 | 216,441,308 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,703 | py | # encoding: utf-8
# module renderdoc
# from P:\1-Scripts\_Python\Py-Autocomplete\renderdoc.pyd
# by generator 1.146
# no doc
# imports
import enum as __enum
from .SwigPyObject import SwigPyObject
class GLFBO(SwigPyObject):
""" Describes the contents of a framebuffer object. """
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __hash__(self, *args, **kwargs): # real signature unknown
""" Return hash(self). """
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
colorAttachments = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""The list of :class:`GLAttachment` with the framebuffer color attachments."""
depthAttachment = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""The :class:`GLAttachment` with the framebuffer depth attachment."""
drawBuffers = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""The list of draw buffer indices into the :data:`colorAttachments` attachment list."""
readBuffer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""The read buffer index in the :data:`colorAttachments` attachment list."""
resourceId = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""The :class:`ResourceId` of the framebuffer."""
stencilAttachment = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""The :class:`GLAttachment` with the framebuffer stencil attachment."""
this = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
thisown = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
__dict__ = None # (!) real value is ''
| [
"drl.i3x@gmail.com"
] | drl.i3x@gmail.com |
82d0e61c36c862b9836cbf9fa197313ee1b5d21a | 5a0488b1e1b3cb9423ab5537598cd2e927deada1 | /com/kute/date/caltime.py | 28d7f63207063afa069969fede799cf1ce8f4878 | [] | no_license | dajima/purepythontest | c276796a90ded77cc033b717a01425a64c5fe729 | 1e0c446f9f6d2bf1f38ab2aafec5af914cf66293 | refs/heads/master | 2021-06-07T04:15:34.450197 | 2016-11-03T14:27:28 | 2016-11-03T14:27:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 858 | py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = 'kute'
# __mtime__ = '16/7/31 17:04'
"""
计算函数执行时间 装饰器
"""
from functools import wraps
import time
def perf_counter(function):
@wraps(function)
def _caltime(*args, **kwargs):
start = time.perf_counter()
result = function(*args, **kwargs)
end = time.perf_counter()
print("The function[%s] use total time is %s s." % (function.__name__, end - start))
return result
return _caltime
def process_time(function):
@wraps(function)
def _caltime(*args, **kwargs):
start = time.process_time()
result = function(*args, **kwargs)
end = time.process_time()
print("The function[%s] use total time is %s s." % (function.__name__, (end - start)))
return result
return _caltime
| [
"kutekute00@gmail.com"
] | kutekute00@gmail.com |
f834ec50bc964f06617f54a3c83792264173427b | ec1fad1e16d24f51987acba26c1b4014cbed0e96 | /python/xgbserver/xgbserver/__main__.py | 8d64b763e7a79c82e256e3e7e49deb18ca3d2197 | [
"Apache-2.0"
] | permissive | Jeffwan/kfserving | 4127b811fd9b778903c0c7572b0bc687e1997efd | 47a6303173dab27b157ca77c72d62b847d099d21 | refs/heads/master | 2020-06-05T03:06:11.606236 | 2019-10-06T01:47:10 | 2019-10-06T01:47:10 | 192,292,123 | 0 | 0 | Apache-2.0 | 2019-06-17T06:59:43 | 2019-06-17T06:59:41 | null | UTF-8 | Python | false | false | 1,289 | py | # Copyright 2019 kubeflow.org.
#
# 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 kfserving
import argparse
from xgbserver import XGBoostModel
DEFAULT_MODEL_NAME = "default"
DEFAULT_LOCAL_MODEL_DIR = "/tmp/model"
parser = argparse.ArgumentParser(parents=[kfserving.server.parser]) #pylint:disable=c-extension-no-member
parser.add_argument('--model_dir', required=True,
help='A URI pointer to the model directory')
parser.add_argument('--model_name', default=DEFAULT_MODEL_NAME,
help='The name that the model is served under.')
args, _ = parser.parse_known_args()
if __name__ == "__main__":
model = XGBoostModel(args.model_name, args.model_dir)
model.load()
kfserving.KFServer().start([model]) #pylint:disable=c-extension-no-member
| [
"k8s-ci-robot@users.noreply.github.com"
] | k8s-ci-robot@users.noreply.github.com |
63a925ca4475c05114f2fa5a5e84e1cfd5c070e2 | 3432efd194137e1d0cb05656eb547c9992229f02 | /test1014/other/5.py | 2163452ba68ab81662362b7241b90f2aba765a8c | [] | no_license | zhanganxia/other_code | 31747d7689ae1e91fcf3f9f758df130246e7d495 | 8d09d9d0b6d6a1a9b8755487f926ac6fafd761fa | refs/heads/master | 2021-09-04T02:22:38.632685 | 2018-01-14T15:37:14 | 2018-01-14T15:37:14 | 107,007,482 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 296 | py | #encoding=utf-8
a=input("请输入第一个数:")
b=input("请输入第二个数:")
c=input("请输入第三个数:")
d=input("请输入第四个数:")
e=input("请输入第五个数:")
num1=int(a)
num2=int(b)
num3=int(c)
num4=int(d)
num5=int(e)
sum=num1+num2+num3+num4+num5
print (sum) | [
"kk@kk.rhel.cc"
] | kk@kk.rhel.cc |
c971d3ead94eb08032a310c9abc1c648f30c516b | 7e69c60c23fce92463c78774b5968d3320c715c9 | /django_covid/django_covid/wsgi.py | b570b88fa5b444fdc628f862febd2e87d82a55f9 | [] | no_license | hwet-j/Python | 5128d114cf7257067f68cfb1db502e4f762ac8cc | 3e6f36be665932588a576f44ebb0107a4f350613 | refs/heads/master | 2023-04-08T17:52:31.607225 | 2021-04-17T05:25:02 | 2021-04-17T05:25:02 | 353,336,473 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 417 | py | """
WSGI config for django_covid project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_covid.settings')
application = get_wsgi_application()
| [
"ghlckd5424@gmail.com"
] | ghlckd5424@gmail.com |
1acb6d67a1ae657f90c2e4402322ec6d567f9adc | 32c56293475f49c6dd1b0f1334756b5ad8763da9 | /google-cloud-sdk/lib/third_party/kubernetes/client/models/v1_network_policy_port.py | 85bb6625d011a03814dc504e0395a5ee14e54a4d | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
] | permissive | bopopescu/socialliteapp | b9041f17f8724ee86f2ecc6e2e45b8ff6a44b494 | 85bb264e273568b5a0408f733b403c56373e2508 | refs/heads/master | 2022-11-20T03:01:47.654498 | 2020-02-01T20:29:43 | 2020-02-01T20:29:43 | 282,403,750 | 0 | 0 | MIT | 2020-07-25T08:31:59 | 2020-07-25T08:31:59 | null | UTF-8 | Python | false | false | 3,880 | py | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen
https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.14.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class V1NetworkPolicyPort(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_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.
"""
swagger_types = {'port': 'object', 'protocol': 'str'}
attribute_map = {'port': 'port', 'protocol': 'protocol'}
def __init__(self, port=None, protocol=None):
"""
V1NetworkPolicyPort - a model defined in Swagger
"""
self._port = None
self._protocol = None
self.discriminator = None
if port is not None:
self.port = port
if protocol is not None:
self.protocol = protocol
@property
def port(self):
"""
Gets the port of this V1NetworkPolicyPort.
The port on the given protocol. This can either be a numerical or named
port on a pod. If this field is not provided, this matches all port
names and numbers.
:return: The port of this V1NetworkPolicyPort.
:rtype: object
"""
return self._port
@port.setter
def port(self, port):
"""
Sets the port of this V1NetworkPolicyPort.
The port on the given protocol. This can either be a numerical or named
port on a pod. If this field is not provided, this matches all port
names and numbers.
:param port: The port of this V1NetworkPolicyPort.
:type: object
"""
self._port = port
@property
def protocol(self):
"""
Gets the protocol of this V1NetworkPolicyPort.
The protocol (TCP, UDP, or SCTP) which traffic must match. If not
specified, this field defaults to TCP.
:return: The protocol of this V1NetworkPolicyPort.
:rtype: str
"""
return self._protocol
@protocol.setter
def protocol(self, protocol):
"""
Sets the protocol of this V1NetworkPolicyPort.
The protocol (TCP, UDP, or SCTP) which traffic must match. If not
specified, this field defaults to TCP.
:param protocol: The protocol of this V1NetworkPolicyPort.
:type: str
"""
self._protocol = protocol
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_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:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, V1NetworkPolicyPort):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| [
"jonathang132298@gmail.com"
] | jonathang132298@gmail.com |
20af141d1a5395d48a83884c91f1a07c01b172f3 | 2734b77a68f6d7e22e8b823418ad1c59fe1a34af | /opengever/core/upgrades/20190415161809_add_nightly_jobs_settings/upgrade.py | 110a092ff386b9a2072439d981ca1fcc3b5104cd | [] | no_license | 4teamwork/opengever.core | 5963660f5f131bc12fd0a5898f1d7c8f24a5e2b1 | a01bec6c00d203c21a1b0449f8d489d0033c02b7 | refs/heads/master | 2023-08-30T23:11:27.914905 | 2023-08-25T14:27:15 | 2023-08-25T14:27:15 | 9,788,097 | 19 | 8 | null | 2023-09-14T13:28:56 | 2013-05-01T08:28:16 | Python | UTF-8 | Python | false | false | 187 | py | from ftw.upgrade import UpgradeStep
class AddNightlyJobsSettings(UpgradeStep):
"""Add nightly jobs settings.
"""
def __call__(self):
self.install_upgrade_profile()
| [
"niklaus.johner@4teamwork.ch"
] | niklaus.johner@4teamwork.ch |
6582416d65803d8038c2fe7b1d4310ac23d17dbb | 51a936439315f892e0cb4db33ca4c9a6e60c127e | /app/controllers/stats.py | c9eed0785e6d36128393c21c43595b08435aa2ba | [
"MIT"
] | permissive | june07/packagecontrol.io | a27dfcb797f396027bcafa29392db6cf3fef80c2 | 9f5eb7e3392e6bc2ad979ad32d3dd27ef9c00b20 | refs/heads/master | 2023-02-21T15:41:54.903531 | 2021-08-14T01:14:52 | 2021-08-14T01:15:07 | 172,954,020 | 1 | 0 | NOASSERTION | 2019-02-27T16:51:47 | 2019-02-27T16:51:46 | null | UTF-8 | Python | false | false | 354 | py | from datetime import datetime, timedelta
from bottle import route
from ..models import system_stats
from ..render import render
@route('/stats', name='stats')
def stats_controller():
data = system_stats.fetch('1 days')
data['date'] = datetime.utcnow().replace(hour=0, minute=0, second=0) - timedelta(days=2)
return render('stats', data)
| [
"will@wbond.net"
] | will@wbond.net |
7d5a8a1bee2752016f38cb31f378a9bf78332833 | 6c174c0cbff5f3403d8034a13c2b8cefff2dd364 | /dfttapptest/database/cookie/jira.py | d8fe5f60dc94c88c89b05e93d14e1e6114387d28 | [] | no_license | xiaominwanglast/uiautomator | 0416e217538527c02e544e559b2d996554b10b20 | 7ce47cda6ac03b7eb707929dd2e0428132ff255f | refs/heads/master | 2021-09-12T12:37:54.286397 | 2018-04-16T10:03:57 | 2018-04-16T10:03:57 | 106,253,765 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 751 | py | #coding:utf-8
import urllib
import requests
data={'os_username':'wangxiaomin',
'os_password':'wang12345',
'os_destination':'',
'user_role':'',
'atl_token':'',
'login':'Log In'}
url='http://jira.dfshurufa.com/login.jsp'
session=requests.Session()
header={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.6 Safari/537.36',}
session.post(url=url,headers=header,data=data,timeout=3)
rq=session.get('http://jira.dfshurufa.com/issues/?jql=project%20%3D%20TTAND%20AND%20issuetype%20%3D%20%E7%BC%BA%E9%99%B7%20AND%20status%20in%20(Open%2C%20Reopened)%20AND%20resolution%20%3D%20Unresolved%20ORDER%20BY%20priority%20DESC%2C%20updated%20DESC',headers=header)
print rq.text
| [
"2274052689@qq.com"
] | 2274052689@qq.com |
7b6e633b612a2474b21935d9902db2f20a237d70 | 0c7d7b24a8d453fc1a9c2f27a08f3c4cfa46ec3b | /recipes/sota/2019/raw_lm_corpus/get_gb_books_by_id.py | 7e6b484fc9636ef947b6756f67c42d7b1bb9bece | [
"BSD-3-Clause",
"MIT"
] | permissive | piEYj/wav2letter | e6ae462eeeb6a4374f8280c8fa15d8f194c60215 | 49fbb1392e69b5194c077df9847505ec995b4e3d | refs/heads/main | 2023-09-06T01:08:48.837731 | 2021-11-12T14:13:41 | 2021-11-12T14:15:15 | 444,344,109 | 1 | 0 | NOASSERTION | 2022-01-04T08:37:19 | 2022-01-04T08:37:19 | null | UTF-8 | Python | false | false | 1,059 | py | import argparse
import os
import sys
from multiprocessing.pool import ThreadPool
from gutenberg.acquire import load_etext
from gutenberg.cleanup import strip_headers
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def get_one_book(book_id, outdir):
eprint("Getting book with id", book_id)
text = strip_headers(load_etext(book_id)).strip()
newpath = os.path.join(outdir, str(book_id) + ".body.txt")
with open(newpath, "w") as outfile:
outfile.write(text)
def main():
parser = argparse.ArgumentParser("Grabs Gutenberg books by ID from a file")
parser.add_argument("--idfile", type=str, required=True)
parser.add_argument("--outdir", type=str, required=True)
args = parser.parse_args()
if not os.path.exists(args.idfile):
raise RuntimeError("idfile not found")
with open(args.idfile, "r") as infile:
ids = [(int(line.strip()), args.outdir) for line in infile]
pool = ThreadPool(80)
pool.starmap(get_one_book, ids)
if __name__ == "__main__":
main()
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
6a87d1e1ce9879012a9742449f94015df579147d | 62e45255088abb536e9ea6fcbe497e83bad171a0 | /ippython/funciones_es_par.py | 055dff2bfd12db09351dbd03b0618033e06494a5 | [] | no_license | jmery24/python | a24f562c8d893a97a5d9011e9283eba948b8b6dc | 3e35ac9c9efbac4ff20374e1dfa75a7af6003ab9 | refs/heads/master | 2020-12-25T21:56:17.063767 | 2015-06-18T04:59:05 | 2015-06-18T04:59:05 | 36,337,473 | 0 | 0 | null | 2015-05-27T02:26:54 | 2015-05-27T02:26:54 | null | UTF-8 | Python | false | false | 201 | py | # -*- coding: utf-8 -*-
"""
Created on Sun May 26 11:21:03 2013
@author: daniel
"""
def es_par(num):
return num % 2 == 0
numero = int(raw_input('Escribe un numero: '))
print es_par(numero)
| [
"danmery@gmail.com"
] | danmery@gmail.com |
dfa30680a49a5312290d890edacd03c8a0e44fe5 | f576f0ea3725d54bd2551883901b25b863fe6688 | /sdk/resources/azure-mgmt-msi/azure/mgmt/msi/v2022_01_31_preview/__init__.py | 785d352dea5bec33c870f80744d1867b9bcd5b90 | [
"LicenseRef-scancode-generic-cla",
"MIT",
"LGPL-2.1-or-later"
] | permissive | Azure/azure-sdk-for-python | 02e3838e53a33d8ba27e9bcc22bd84e790e4ca7c | c2ca191e736bb06bfbbbc9493e8325763ba990bb | refs/heads/main | 2023-09-06T09:30:13.135012 | 2023-09-06T01:08:06 | 2023-09-06T01:08:06 | 4,127,088 | 4,046 | 2,755 | MIT | 2023-09-14T21:48:49 | 2012-04-24T16:46:12 | Python | UTF-8 | Python | false | false | 925 | 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 ._managed_service_identity_client import ManagedServiceIdentityClient
from ._version import VERSION
__version__ = VERSION
try:
from ._patch import __all__ as _patch_all
from ._patch import * # pylint: disable=unused-wildcard-import
except ImportError:
_patch_all = []
from ._patch import patch_sdk as _patch_sdk
__all__ = [
"ManagedServiceIdentityClient",
]
__all__.extend([p for p in _patch_all if p not in __all__])
_patch_sdk()
| [
"noreply@github.com"
] | Azure.noreply@github.com |
01c36473b6a401d07cf95dce5655f46b3112326f | af5a8f872cd8d689c3646376ce80dc69a0bce7b4 | /Chapter03/04-flaskdemo.py | 73defb37af61ae8cdc8e2f50acd8a07cee5fb352 | [
"MIT"
] | permissive | PacktPublishing/NGINX-Cookbook | de66c1544d8baac5a8794d7f6a2fe30f6e3a7a45 | 2cd497d6899388e3bd0721d4e64be428acc7d168 | refs/heads/master | 2023-02-06T06:29:57.001116 | 2023-01-30T08:30:16 | 2023-01-30T08:30:16 | 101,969,140 | 34 | 28 | null | null | null | null | UTF-8 | Python | false | false | 218 | py | from flask import Flask
application = Flask(__name__)
@application.route("/")
def hello():
return "<h1>Demo via Nginx with uWSGI!</h1>"
if __name__ == "__main__":
application.run(host='127.0.0.1', port=9001)
| [
"noreply@github.com"
] | PacktPublishing.noreply@github.com |
4081b31cf2708adf515b0cd0051c0277648bb564 | 61699615fab0e91c7dd72d5eff6cd7326e83703c | /python/zheng_ze.py | 53c0db168c6c79b4b7656a9be74ffc164644cb3d | [] | no_license | ftZHOU/Pronostics-sportifs | b85cae26068c9bc5f9a95c821b907382d2e64386 | a9384f0ba8e41a4fb0ec049c37c97f30aec45e49 | refs/heads/master | 2021-08-07T14:44:16.267738 | 2017-11-08T10:42:51 | 2017-11-08T10:42:51 | 109,962,567 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 850 | py | import urllib2
import re
request = urllib2.Request("http://www.soccerstats.com/latest.asp?league=france")
try:
response = urllib2.urlopen(request)
content = response.read()
#print content
table3 = "<td height='22'>.*?<a href='team\.asp\?league.*?op'>(.*?)</a>.*?<font color='green'>(.*?)</font>.*?<td align='center'>(.*?)</TD>.*?<td align='center'>(.*?)</TD>.*?<td align='center'>(.*?)</TD>.*?<font color='blue'>(.*?)</font>.*?<font color='red'>(.*?)</font>.*?<td align='center'>(.*?)</TD>.*?b>(.*?)</b>"
pattern = re.compile(table3,re.S)
items = re.findall(pattern,content)
#print items
for item in items:
print "team name:"+item[0]+"\n","GP:"+item[1],"W:"+item[2],"D:"+item[3],"L:"+item[4],"G:"+item[5],"F:"+item[6]
except urllib2.HTTPError,e:
print e.code
except urllib2.URLError, e:
print e.reason
| [
"ftzhou@outlook.com"
] | ftzhou@outlook.com |
139ac0068a4db76318adde21dbdcaaf837d4d4e5 | 2da72c9f9bbb0b5db33710cddbdee28503e5a606 | /udacity/artificialIntelligenceForRobots/search3 2.py | 3de6f54a8632bb7795501af3baee00dc13da130d | [] | no_license | gddickinson/python_code | 2e71fb22b929cb26c2a1456b11dc515af048c441 | dbb20e171fb556e122350fb40e12cc76adbb9a66 | refs/heads/master | 2022-10-26T15:20:40.709820 | 2022-10-11T16:06:27 | 2022-10-11T16:06:27 | 44,060,963 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,732 | py | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 13 07:19:53 2016
@author: George
"""
# -----------
# User Instructions:
#
# Modify the the search function so that it becomes
# an A* search algorithm as defined in the previous
# lectures.
#
# Your function should return the expanded grid
# which shows, for each element, the count when
# it was expanded or -1 if the element was never expanded.
#
# If there is no path from init to goal,
# the function should return the string 'fail'
# ----------
grid = [[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0]]
heuristic = [[9, 8, 7, 6, 5, 4],
[8, 7, 6, 5, 4, 3],
[7, 6, 5, 4, 3, 2],
[6, 5, 4, 3, 2, 1],
[5, 4, 3, 2, 1, 0]]
init = [0, 0]
goal = [len(grid)-1, len(grid[0])-1]
cost = 1
delta = [[-1, 0 ], # go up
[ 0, -1], # go left
[ 1, 0 ], # go down
[ 0, 1 ]] # go right
delta_name = ['^', '<', 'v', '>']
def search(grid,init,goal,cost,heuristic):
# ----------------------------------------
# modify the code below
# ----------------------------------------
closed = [[0 for col in range(len(grid[0]))] for row in range(len(grid))]
closed[init[0]][init[1]] = 1
expand = [[-1 for col in range(len(grid[0]))] for row in range(len(grid))]
action = [[-1 for col in range(len(grid[0]))] for row in range(len(grid))]
x = init[0]
y = init[1]
g = 0
f = 0
open = [[f, g, x, y]]
found = False # flag that is set when search is complete
resign = False # flag set if we can't find expand
count = 0
while not found and not resign:
if len(open) == 0:
resign = True
return "Fail"
else:
open.sort()
open.reverse()
next = open.pop()
x = next[2]
y = next[3]
g = next[1]
f = next[0]
expand[x][y] = count
count += 1
if x == goal[0] and y == goal[1]:
found = True
else:
for i in range(len(delta)):
x2 = x + delta[i][0]
y2 = y + delta[i][1]
if x2 >= 0 and x2 < len(grid) and y2 >=0 and y2 < len(grid[0]):
if closed[x2][y2] == 0 and grid[x2][y2] == 0:
g2 = g + cost
f = g2 + heuristic[x2][y2]
open.append([f,g2, x2, y2])
closed[x2][y2] = 1
return expand
test = (search(grid,init,goal,cost, heuristic))
for i in range(len(test)):
print(test[i]) | [
"george.dickinson@gmail.com"
] | george.dickinson@gmail.com |
71980b6881124f741b4171304de8cf80c36a24c4 | ca8f2b28353e449c10cf520ee1d7d946163c211e | /grammar.py | 1fc7139d3b904220028cf69091fef1a34921e07f | [
"MIT"
] | permissive | zwytop/nlp-2017 | e42452d53279fbe4d1af279b3ad5b165a01b1ccb | ecdefc6dc179ef73c981b793673056804f37db51 | refs/heads/master | 2021-01-23T05:18:33.126936 | 2017-02-09T10:57:21 | 2017-02-09T10:57:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 472 | py | import nltk
from nltk.draw.tree import TreeView
groucho_grammar = nltk.CFG.fromstring("""
S -> NP VP
PP -> P NP
NP -> Det Nom
Nom -> N | Adj Nom
VP -> V NP | VP PP
Det -> 'the'
Adj -> 'little' | 'fine' | 'fat'
N -> 'brook' | 'trout' | 'bear'
V -> 'saw'
P -> 'in'
""")
sent = 'the little bear saw the fine fat trout in the brook'.split(' ')
parser = nltk.ChartParser(groucho_grammar)
for tree in parser.parse(sent):
TreeView(tree)._cframe.print_to_file('grammar.ps') | [
"scottyugochang@hotmail.com"
] | scottyugochang@hotmail.com |
2fbbba64e4146809c447436783d5bf7bf23032fb | 4d83e8ec852194a811cb18cfb3f4b13bd298216e | /egs/word/run_trf_neural_sa.py | 36b556740118a3faa7047edeb89ad4a445848c96 | [] | no_license | peternara/TRF-NN-Tensorflow | 9961dd41195476dd143d45607c8558cae558337e | 0b235bebdbfe285873c3bef8e62fe475e13ea70a | refs/heads/master | 2021-08-31T16:31:46.097523 | 2017-12-22T03:01:20 | 2017-12-22T03:01:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,639 | py | import tensorflow as tf
import os
import sys
import numpy as np
from base import *
from lm import *
from trf.sa import *
import task
class Opt(trf.DefaultOps):
def __init__(self, trf_model):
super().__init__(trf_model, *task.get_nbest())
self.per_epoch = 0.1
self.next_epoch = 0
self.out_logz = os.path.join(trf_model.logdir, 'logz.dbg')
def run(self, step, epoch):
super().run(step, epoch)
if epoch > self.next_epoch:
self.next_epoch += self.per_epoch
with self.m.time_recoder.recode('true_logz'):
true_logz = self.m.true_logz(5)
nce_logz = self.m.norm_const.get_logz()
with open(self.out_logz, 'at') as f:
f.write('step={} epoch={:.2f}'.format(step, epoch) + '\n')
f.write('nce= ' + ' '.join(['{:.2f}'.format(i) for i in nce_logz]) + '\n')
f.write('true= ' + ' '.join(['{:.2f}'.format(i) for i in true_logz]) + '\n')
def create_config(data):
config = trf.Config(data)
config.chain_num = 100
config.multiple_trial = 10
config.sample_batch_size = 100
# config.auxiliary_model = 'lstm'
config.auxiliary_config.embedding_size = 32
config.auxiliary_config.hidden_size = 32
config.auxiliary_config.hidden_layers = 1
config.auxiliary_config.batch_size = 100
config.auxiliary_config.step_size = 10
config.auxiliary_config.learning_rate = 1.0
config.lr_feat = lr.LearningRateEpochDelay(1e-3)
config.lr_net = lr.LearningRateEpochDelay(1e-3)
config.lr_logz = lr.LearningRateEpochDelay(0.1)
config.opt_feat_method = 'adam'
config.opt_net_method = 'adam'
config.opt_logz_method = 'sgd'
# feat config
# config.feat_config.feat_type_file = '../../tfcode/feat/g4.fs'
config.feat_config = None
# neural config
config.net_config.update(task.get_config_rnn(config.vocab_size))
config.net_config.cnn_skip_connection = False
return config
def create_name(config):
return str(config)
def main(_):
data = reader.Data().load_raw_data(reader.word_raw_dir(),
add_beg_token='</s>', add_end_token='</s>',
add_unknwon_token=None,
max_length=None)
# create config
config = create_config(data)
# config.net_config.only_train_weight = True
# create log dir
logdir = 'trf_sa/' + create_name(config)
# prepare the log dir
wb.prepare_log_dir(logdir, 'trf.log')
config.print()
data.write_vocab(logdir + '/vocab.txt')
data.write_data(data.datas[1], logdir + '/valid.id')
data.write_data(data.datas[2], logdir + '/test.id')
m = trf.TRF(config, data, logdir=logdir, device='/gpu:0')
nce_pretrain_model_path = 'trf_nce/trf_nce10_e16_cnn_(1to5)x16_(3x16)x3_relu_noise2gram/trf.mod'
sv = tf.train.Supervisor(logdir=os.path.join(logdir, 'logs'),
global_step=m.global_step)
sv.summary_writer.add_graph(tf.get_default_graph()) # write the graph to logs
session_config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False)
session_config.gpu_options.allow_growth = True
with sv.managed_session(config=session_config) as session:
with session.as_default():
# m.restore_nce_model(nce_pretrain_model_path)
# m.save()
m.train(operation=Opt(m))
if __name__ == '__main__':
tf.app.run(main=main)
| [
"wb.th08@gmail.com"
] | wb.th08@gmail.com |
43ed3032a9d6d8aa4d915e1207566ac1933f96b9 | d93fe0484fc3b32c8fd9b33cc66cfd636a148ec4 | /Codeforces/ECR67/probD.py | ebbfe5197c9987bb04c7865a228eb39eb2b6054b | [] | no_license | wattaihei/ProgrammingContest | 0d34f42f60fa6693e04c933c978527ffaddceda7 | c26de8d42790651aaee56df0956e0b206d1cceb4 | refs/heads/master | 2023-04-22T19:43:43.394907 | 2021-05-02T13:05:21 | 2021-05-02T13:05:21 | 264,400,706 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,609 | py | # instead of AVLTree
class BITbisect():
def __init__(self, max):
self.max = max
self.data = [0]*(self.max+1)
# 0からiまでの区間和
# 立っているビットを下から処理
def query_sum(self, i):
s = 0
while i > 0:
s += self.data[i]
i -= i & -i
return s
# i番目の要素にxを足す
# 覆ってる区間すべてに足す
def add(self, i, x):
while i <= self.max:
self.data[i] += x
i += i & -i
def insert(self, x):
self.add(x, 1)
def delete(self, x):
self.add(x, -1)
def count(self, x):
return self.query_sum(x) - self.query_sum(x-1)
def length(self):
return self.query_sum(self.max)
# 下からc番目(0-indexed)の数
# O(log(N))
def search(self, c):
c += 1
s = 0
ind = 0
l = self.max.bit_length()
for i in reversed(range(l)):
if ind + (1<<i) <= self.max:
if s + self.data[ind+(1<<i)] < c:
s += self.data[ind+(1<<i)]
ind += (1<<i)
if ind == self.max:
return False
return ind + 1
def bisect_right(self, x):
return self.query_sum(x)
def bisect_left(self, x):
if x == 1:
return 0
return self.query_sum(x-1)
# listみたいに表示
def display(self):
print('inside BIT:', end=' ')
for x in range(1, self.max+1):
if self.count(x):
c = self.count(x)
for _ in range(c):
print(x, end=' ')
print()
import sys
input = sys.stdin.readline
Q = int(input())
Query = []
for _ in range(Q):
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
Query.append((N, A, B))
for N, A, B in Query:
bitA = BITbisect(N)
bitB = BITbisect(N)
ans = 'YES'
for i in range(N):
a, b = A[i], B[i]
if bitA.length() == 0 and bitB.length() == 0:
if a == b: continue
if bitB.count(b) > 0:
bitB.delete(b)
else:
bitA.insert(b)
if bitA.count(a) > 0:
bitA.delete(a)
else:
bitB.insert(a)
#print(i)
#bitA.display()
#bitB.display()
if bitA.length() != 0 or bitB.length() != 0:
if i == N-1:
ans = 'NO'
elif B[i] > B[i+1]:
ans = 'NO'
break
print(ans) | [
"wattaihei.rapyuta@gmail.com"
] | wattaihei.rapyuta@gmail.com |
75f8d91434a9301e13f3e2bbbdec53876240c65a | 5626d2c289e6cc3752f43a0f98c45dd914b9acc8 | /shaura/testing.py | 2b02deb282fc698b96617f58fc10e74d1dbb74f6 | [] | no_license | datakurre/shaura | b9e100b99d19789f69900dbb192bc6a57a7bbd43 | b26aef07c880134e780f4e5fbd851c37414273b2 | refs/heads/master | 2020-04-11T03:33:53.301674 | 2011-09-14T07:35:32 | 2011-09-14T07:35:32 | 2,376,328 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,260 | py | # -*- coding: utf-8 -*-
"""zope.testrunner layers"""
from pyramid import testing
class PyramidLayer(object):
@classmethod
def setUp(cls):
cls.config = testing.setUp()
import pyramid_zcml
cls.config.include(pyramid_zcml)
cls.config.load_zcml("shaura:configure.zcml")
@classmethod
def tearDown(cls):
testing.tearDown()
@classmethod
def testSetUp(cls):
pass
@classmethod
def testTearDown(cls):
pass
from shaura import testing_volatile
class VolatileLayer(PyramidLayer):
@classmethod
def setUp(cls):
cls.config.load_zcml("shaura:testing_volatile.zcml")
@classmethod
def tearDown(cls):
pass
@classmethod
def testSetUp(cls):
testing_volatile.DATASTORE.clear()
@classmethod
def testTearDown(cls):
pass
from shaura import testing_app
class VolatileAppLayer(VolatileLayer):
@classmethod
def setUp(cls):
cls.config.load_zcml("shaura:testing_app.zcml")
cls.config._set_root_factory(testing_app.Application)
@classmethod
def tearDown(cls):
pass
@classmethod
def testSetUp(cls):
pass
@classmethod
def testTearDown(cls):
pass
| [
"asko.soukka@iki.fi"
] | asko.soukka@iki.fi |
f3b7d8ddea426fbb7199f1006c6b2961567bed88 | 294767ff9d1190726a82931e0ac16db83eebc3f6 | /chaospy/quad/interface.py | b2191e296f5f3b8125bd53237b24f9c44b8b0ebf | [
"MIT"
] | permissive | FKShi/chaospy | 30ee2d4eac07f1ff713480aba6304726bcacae7d | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | refs/heads/master | 2020-05-22T00:52:20.353874 | 2019-04-21T11:24:54 | 2019-04-21T11:24:54 | 186,181,921 | 1 | 0 | null | 2019-05-11T21:14:04 | 2019-05-11T21:14:04 | null | UTF-8 | Python | false | false | 2,787 | py | """Frontend for the generation of quadrature rules."""
import inspect
import numpy as np
from scipy.misc import comb
from . import collection, sparse_grid
def generate_quadrature(
order, domain, accuracy=100, sparse=False, rule="C",
composite=1, growth=None, part=None, normalize=False, **kws
):
"""
Numerical quadrature node and weight generator.
Args:
order (int):
The order of the quadrature.
domain (numpy.ndarray, Dist):
If array is provided domain is the lower and upper bounds (lo,up).
Invalid if gaussian is set. If Dist is provided, bounds and nodes
are adapted to the distribution. This includes weighting the nodes
in Clenshaw-Curtis quadrature.
accuracy (int):
If gaussian is set, but the Dist provieded in domain does not
provide an analytical TTR, ac sets the approximation order for the
descitized Stieltje's method.
sparse (bool):
If True used Smolyak's sparse grid instead of normal tensor product
grid.
rule (str):
Rule for generating abscissas and weights. Either done with
quadrature rules, or with random samples with constant weights.
composite (int):
If provided, composite quadrature will be used. Value determines
the number of domains along an axis. Ignored in the case
gaussian=True.
normalize (bool):
In the case of distributions, the abscissas and weights are not
tailored to a distribution beyond matching the bounds. If True, the
samples are normalized multiplying the weights with the density of
the distribution evaluated at the abscissas and normalized
afterwards to sum to one.
growth (bool):
If True sets the growth rule for the composite quadrature rule to
exponential for Clenshaw-Curtis quadrature.
"""
from ..distributions.baseclass import Dist
isdist = isinstance(domain, Dist)
if isdist:
dim = len(domain)
else:
dim = np.array(domain[0]).size
rule = rule.lower()
if len(rule) == 1:
rule = collection.QUAD_SHORT_NAMES[rule]
quad_function = collection.get_function(
rule,
domain,
normalize,
growth=growth,
composite=composite,
accuracy=accuracy,
)
if sparse:
order = np.ones(len(domain), dtype=int)*order
abscissas, weights = sparse_grid.sparse_grid(quad_function, order, dim)
else:
abscissas, weights = quad_function(order)
assert len(weights) == abscissas.shape[1]
assert len(abscissas.shape) == 2
return abscissas, weights
| [
"jonathf@gmail.com"
] | jonathf@gmail.com |
e47fcc515260d699c5c1d37e0c345d4381a585b3 | 89a90707983bdd1ae253f7c59cd4b7543c9eda7e | /python_cookbook/11/simple_authentication_of_clients/server.py | b9b26c99523a936203b19bd4f1f7b7feff3a071e | [] | no_license | timothyshull/python_reference_code | 692a7c29608cadfd46a6cc409a000023e95b9458 | f3e2205dd070fd3210316f5f470d371950945028 | refs/heads/master | 2021-01-22T20:44:07.018811 | 2017-03-17T19:17:22 | 2017-03-17T19:17:22 | 85,346,735 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 607 | py | from socket import socket, AF_INET, SOCK_STREAM
from auth import server_authenticate
secret_key = b'peekaboo'
def echo_handler(client_sock):
if not server_authenticate(client_sock, secret_key):
client_sock.close()
return
while True:
msg = client_sock.recv(8192)
if not msg:
break
client_sock.sendall(msg)
def echo_server(address):
s = socket(AF_INET, SOCK_STREAM)
s.bind(address)
s.listen(5)
while True:
c, a = s.accept()
echo_handler(c)
print('Echo server running on port 18000')
echo_server(('', 18000))
| [
"timothyshull@gmail.com"
] | timothyshull@gmail.com |
4f620f7dd7a21de6a7e18e9191a7dfa62aa79cf0 | dc905bec7c109d82f26bdeca5cd1d503ecfa77c6 | /utils/getSize.py | 2d439cb5b44c6377e3dfc9306ae2e2e73331b160 | [
"MIT"
] | permissive | chjz1024/USTC-CS-Courses-Resource | d739c7b7b07dbc0b15d456b952dd3572df872cde | 605d0e704102328aa447a9365446cae45f382d14 | refs/heads/master | 2023-03-17T03:28:31.293403 | 2019-01-09T03:14:30 | 2019-01-09T03:14:30 | 163,499,702 | 0 | 0 | MIT | 2018-12-29T09:53:27 | 2018-12-29T09:53:27 | null | UTF-8 | Python | false | false | 826 | py | # coding: utf-8
import os
import sys
def formatSize(size):
s = 'BKMGTP'
ct = 0
while size>=(1<<ct):
ct+=10
if ct>=10: ct-=10
return '{sz:.2f}{a}'.format(sz=size/(1<<ct),a=s[ct//10])
def getSize(path='.'):
if os.path.isdir(path):
gen = os.walk(path)
li = []
for root, dirs, files in gen:
for f in files:
sz = os.path.getsize(os.path.join(root ,f))
li.append(sz)
#li.insert(('.',sum(i[1] for i in li)),0)
#size = [f'{i[0]}: {formatSize(i[1])}' for i in li]
return formatSize(sum(li))
else:
return formatSize(os.path.getsize(path))
if __name__ == "__main__":
items = sys.argv[1:]
for i in items:
print('{i}: {sz}'.format(i=i,sz =getSize(i)))
| [
"zhuheqin1@gmail.com"
] | zhuheqin1@gmail.com |
f8ff84248a0fd4517e75554fa1ca11928afacd36 | 71cc62fe3fec8441794a725b7ce3037dc2723107 | /ifreewallpapers/apps/profile/templatetags/avatars.py | 8ed24bb18b20fe8d253a62fe106b8a5cb16962dd | [] | no_license | tooxie/django-ifreewallpapers | bda676dc5a6c45329ad6763862fe696b3e0c354b | 75d8f41a4c6aec5c1091203823c824c4223674a6 | refs/heads/master | 2020-05-21T12:50:36.907948 | 2011-01-19T04:28:33 | 2011-01-19T04:28:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,993 | py | # coding=UTF-8
from profile import settings as _settings
from profile.models import Profile, Avatar
# import Image
# from PythonMagick import Image
from utils.TuxieMagick import Image
from django.conf import settings
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from django.template.defaultfilters import slugify
from django.template import Library, Node, TemplateSyntaxError, Variable
from os import path, makedirs
import time
register = Library()
class ResizedThumbnailNode(Node):
def __init__(self, width, height, user, default):
try:
self.width = int(width)
except:
self.width = Variable(width)
try:
self.height = int(height)
except:
self.height = Variable(height)
if not user:
self.username = 'user'
else:
self.username = user
self.default = default
def get_user(self, context):
return Variable(self.username).resolve(context)
def sizes_ok(self, with_original=False):
if with_original:
orig_width = self.orig_width
orig_height = self.orig_height
else:
orig_width, orig_height = _settings.DEFAULT_AVATAR_SIZE
orig_height = _settings.DEFAULT_AVATAR_SIZE[1]
return self.width >= orig_width and self.height >= orig_height
def both_sides_equals(self, fname):
return self.orig_width == self.orig_height
def resize(self, orig='', dest=''):
if not path.exists(orig):
# print orig, 'does not exists'
return None
if path.exists(dest):
# print dest, 'already exists'
return True
if not dest:
dest = orig
self.orig.scale(self.width, self.height)
if self.orig.write(dest):
# print 'resizing done, returning...'
return self.as_url(dest)
else:
print ' *** ERROR *** '
return None # damn! Close but no cigar...
def get_file(self, profile=None):
default = False
file_name = None
# username = slugify(profile.user.username)
file_root = _settings.AVATARS_DIR
# La diferencia entre self.default y default es que el primero indica
# que tengo que devolver el avatar por defecto, mientras que el segundo
# marca si estoy devolviendo el avatar por defecto o no.
if self.default:
default = True
else:
if profile is not None:
# Este try es por si en profile.avatar existe una relación a un
# avatar que no existe en la tabla de avatars.
try:
if profile.avatar:
file_name = profile.avatar.name
except:
profile.avatar = None
profile.save()
default = True
if not file_name or not path.exists(path.join(file_root, file_name)):
file_name = _settings.DEFAULT_AVATAR
default = True
avatar_file = path.join(file_root, file_name)
self.orig = Image(avatar_file)
self.orig_width = self.orig.size().width()
self.orig_height = self.orig.size().height()
if not self.sizes_ok(with_original=True):
if default:
file_name = file_name[file_name.rfind('/')+1:]
file_name = '%(width)i-%(name)s' % \
{'width': self.width, 'name': file_name}
new_avatar = path.join(file_root, file_name)
else:
new_avatar = '' # Hack alert!
self.resize(avatar_file, new_avatar)
return (file_name, default)
def as_url(self, path):
from profile.avatars import path_to_url
return path_to_url(path)
def render(self, context):
try:
# If size is not an int, then it's a Variable, so try to resolve it.
if not isinstance(self.width, int):
self.width = int(self.width.resolve(context))
self.user = self.get_user(context)
except Exception, e:
print e
return '' # just die...
profile = self.user.get_profile()
if not profile:
return ''
file_root = _settings.AVATARS_DIR
file_name, defaulting = self.get_file(profile)
file_path = path.join(file_root, file_name)
return self.as_url(path.join(file_root, file_name))
@register.tag('avatar')
def Thumbnail(parser, token):
bits = token.contents.split()
username, default = None, False
width, height = _settings.DEFAULT_AVATAR_SIZE
if len(bits) == 2:
if bits[1] == 'default':
default = True
else:
username = bits[1]
elif len(bits) == 3:
username = bits[1]
default = bits[2]
return ResizedThumbnailNode(width, height, username, default)
| [
"alvaro@mourino.net"
] | alvaro@mourino.net |
1d03f8ab19d1108f3100cb736df9f97204ba0258 | a90e5b2f4cf3a3919bd082296834c9f0efa99b71 | /code/python/invertTree.py | dd798d65bced2df2badc5643ff9ec2179c1500cd | [] | no_license | yjshiki/leetcode | c6330e53fa3db463909787ca882a702e4952a2a1 | 628e732c15afe1da7f3aa690bbbc27866fcb1188 | refs/heads/master | 2020-06-05T00:38:54.136840 | 2020-05-14T04:29:25 | 2020-05-14T04:29:25 | 192,253,725 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 484 | py | class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
res = root
stack = []
while root or stack:
if root:
stack.append(root)
root = root.left
else:
root = stack.pop()
root.left, root.right = root.right, root.left
root = root.left
return res
| [
"noreply@github.com"
] | yjshiki.noreply@github.com |
ccb373ceffa902e5f1e9bd4adf964c88e6abf2b0 | db5f520bf54122c11640a964bb50a47a6aeef8d6 | /readthedocs/projects/search_indexes.py | 8ec2d7a8b109aa106b5e28111a3eaf86fc2645aa | [
"MIT"
] | permissive | jasongrlicky/readthedocs.org | 4f0f74e2ffc3647f68349aa68dbac5b80633c742 | 538e9312527c085e665c101d66d37ba44b64e88e | refs/heads/master | 2020-12-25T10:08:35.805404 | 2011-06-24T18:52:10 | 2011-06-24T18:52:10 | 1,416,718 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,767 | py | # -*- coding: utf-8-*-
import os
import codecs
import BeautifulSoup
from django.utils.html import strip_tags
from haystack.indexes import *
from haystack import site
from projects.models import File, ImportedFile, Project
class ProjectIndex(SearchIndex):
text = CharField(document=True, use_template=True)
author = CharField(model_attr='user')
title = CharField(model_attr='name')
description = CharField(model_attr='description')
repo_type = CharField(model_attr='repo_type')
class FileIndex(SearchIndex):
text = CharField(document=True, use_template=True)
author = CharField(model_attr='project__user', faceted=True)
project = CharField(model_attr='project__name', faceted=True)
title = CharField(model_attr='heading')
#Should prob make a common subclass for this and FileIndex
class ImportedFileIndex(SearchIndex):
text = CharField(document=True)
author = CharField(model_attr='project__user', faceted=True)
project = CharField(model_attr='project__name', faceted=True)
title = CharField(model_attr='name')
def prepare_text(self, obj):
try:
full_path = obj.project.rtd_build_path()
to_read = os.path.join(full_path, obj.path.lstrip('/'))
content = codecs.open(to_read, encoding="utf-8", mode='r').read()
bs = BeautifulSoup.BeautifulSoup(content)
soup = bs.find("div", {"class": "document"})
return strip_tags(soup).replace(u'¶', '')
except (AttributeError, IOError) as e:
if 'full_path' in locals():
print "%s not found: %s " % (full_path, e)
#obj.delete()
site.register(File, FileIndex)
site.register(ImportedFile, ImportedFileIndex)
site.register(Project, ProjectIndex)
| [
"eric@ericholscher.com"
] | eric@ericholscher.com |
c6bed9b93e57f2c5b784b15df3dd9cb422697a7a | ba7640cffff3085f045d69f37735de0f759e66c3 | /__init__.py | 487deef5265afc2b0d3dd4e984777a3440475805 | [
"Apache-2.0"
] | permissive | luoqingfu/reudom | f5e88292a7e8cdbb372340795bc5ec5c85a26931 | 3c52ff4aa2cd772260bbf3575f2844d76bc2f16a | refs/heads/master | 2020-12-07T13:23:29.972584 | 2019-12-24T14:57:05 | 2019-12-24T14:57:05 | 232,730,930 | 1 | 0 | Apache-2.0 | 2020-01-09T05:38:10 | 2020-01-09T05:38:09 | null | UTF-8 | Python | false | false | 1,333 | py | #!/usr/bin/python
#
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from .running.test_runner import main
from .case import TestCase
from .testdata import ddt, ddt_class
from .skip import skip
from requests import request
from requests import *
from unittest import TestCase
from Crypto.Cipher import AES
from Crypto import *
from Crypto import Cipher, Hash, Protocol, PublicKey, Random, SelfTest, Signature, Util
from .CryptoAES.aesEncrypt import aesCrypt
__author__ = "Barry"
__version__ = "1.1.6"
__description__ = "Automated testing framework based on requests and unittest interface."
| [
"2652612315@qq.com"
] | 2652612315@qq.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.