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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d0074cf34faa97e409587457b3a55e2e27a680b9
|
e4e1223e28a47bee5c47f3b08e05276996bb3694
|
/example/context.py
|
101cbd0c816dc15c5e05434adbb53d99e805564c
|
[
"BSD-3-Clause"
] |
permissive
|
ecarreras/subcmd
|
891bc108ea713a2e2f78dfde9a2e7f2661f3c847
|
ee0475b82da7125909c6a6828eee115d20e6193c
|
refs/heads/master
| 2020-12-25T04:18:09.850340
| 2012-08-28T09:09:52
| 2012-08-28T09:09:52
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,682
|
py
|
#
## BEGIN LICENSE BLOCK
#
# Copyright (c) <2012>, Raul Perez <repejota@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the <organization> nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
## END LICENSE BLOCK
#
import sys
import os
sys.path.insert(0, os.path.abspath('..'))
|
[
"repejota@gmail.com"
] |
repejota@gmail.com
|
e7ed20584cd2a3e9120547bf256c89a97295ec0d
|
1a949f20cafe328c5ad145659903e8dc5d974a76
|
/subjects/admin.py
|
70f7ea47f0a4e6dd08a1ec643b007f0d733a30c9
|
[] |
no_license
|
Fabricourt/plotx
|
7154be9153ab532796a16a1de3125276913fca97
|
b2a526d4a9236217978a48a997b3b425cd40c0a9
|
refs/heads/master
| 2022-12-11T18:57:36.631087
| 2020-07-07T17:22:50
| 2020-07-07T17:22:50
| 230,000,109
| 0
| 1
| null | 2022-12-08T03:27:54
| 2019-12-24T20:25:39
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 458
|
py
|
from django.contrib import admin
from .models import *
class SubjectAdmin(admin.ModelAdmin):
list_display = ('subject_name', 'created_by', 'is_published', )
list_display_links = ('subject_name',)
list_filter = ('subject_name', 'created_by',)
list_editable = ('is_published',)
search_fields = ('subject_name', 'created_by', )
prepopulated_fields = {"slug": ('subject_name',)}
list_per_page = 25
admin.site.register(Subject, SubjectAdmin)
|
[
"mfalme2030@gmail.com"
] |
mfalme2030@gmail.com
|
632b44110f8d17e5a87f2169f16492724791a409
|
2c4ba5a56b7a3d3e1c286b678eb8068f51c23046
|
/week2/3-Simple-Algorithms/solutions/first_n_perfect.py
|
388005a98408f01742f75b53102ab5c4f146e5ab
|
[] |
no_license
|
OgnyanPenkov/Programming0-1
|
3b69757bd803814585d77479fc987a0ee92d0390
|
8078f316ea2b81216c21cf78e7cf1afc17f54846
|
refs/heads/master
| 2021-01-21T15:12:20.814368
| 2015-10-07T18:16:39
| 2015-10-07T18:16:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 925
|
py
|
# Проблемът на тази задача е, че не знаем горната граница на интервала
# Например, не знае първите 4 перфектни числа в какъв интервал са
# За това подхождаме по следния начин - while True:
# За всяко число +1 гледаме дали е перфектно
# Aко намерим перфектно, намаляваме търснеата бройка с 1
# Когато търсената бройка стане 0, приключваме
n = input("Enter n: ")
n = int(n)
start = 6
while True:
divisors_sum = 0
divisor = 1
while divisor < start:
if start % divisor == 0:
divisors_sum += divisor
divisor += 1
if divisors_sum == start:
print(start)
n = n - 1
if n == 0:
break
start += 1
|
[
"radorado@hackbulgaria.com"
] |
radorado@hackbulgaria.com
|
7393ed5275df359c4798e683f9f52f70ea73ee36
|
5fd4707876cac0a4ca3b14af9a936301c45b5599
|
/02_数据结构/fp_15_一个谜题.py
|
12cd3f9686732f4027c53318216d150dbc7debc7
|
[] |
no_license
|
xuelang201201/FluentPython
|
5b0d89bfc6ee1238ad77db9955ec7e8417b418b8
|
7cbedf7c780c2a9e0edac60484f2ad4c385e1dbd
|
refs/heads/master
| 2022-04-26T21:49:16.923214
| 2020-04-27T01:27:50
| 2020-04-27T01:27:50
| 258,290,957
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 671
|
py
|
# 一个关于+=的谜题
t = (1, 2, [30, 40])
t[2] += [50, 60]
# 到底会发生下面4中情况中的哪一种?
# a. t变成 (1, 2, [30, 40, 50, 60])。
# b. 因为 tuple 不支持对它的元素赋值,所以会抛出 TypeError 异常。
# c. 以上两个都不是。
# d. a 和 b 都是对的。
# 在终端中运行:没人料到的结果:t[2] 被改动了,但是也有异常抛出
# t
# TypeError Traceback (most recent call last)
# <ipython-input-2-d877fb0e9d36> in <module>
# ----> 1 t[2] += [50, 60]
#
# TypeError: 'tuple' object does not support item assignment
# t
# (1, 2, [30, 40, 50, 60])
# 所以答案是 d
|
[
"xuelang201201@gmail.com"
] |
xuelang201201@gmail.com
|
bdea5739deb6de4ea45ee5a8b9375074d1bd4a56
|
c1e31f49a59beb6089328d09040f6f48d2e12cde
|
/lib/python2.7/exportfits.py
|
8ac16bd8a03a5dfb2e656ce6285ff75d901e1e57
|
[
"Python-2.0"
] |
permissive
|
kernsuite-debian/casalite
|
3d81761e0d8ae497f97ea242e98d4357618a7591
|
b620981f14f4ba5b77f347f649cd2c16d498db04
|
refs/heads/master
| 2021-06-22T16:22:51.765703
| 2021-02-25T13:28:05
| 2021-02-25T13:28:05
| 80,822,139
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,655
|
py
|
#
# This file was generated using xslt from its XML file
#
# Copyright 2009, Associated Universities Inc., Washington DC
#
import sys
import os
from casac import *
import string
from taskinit import casalog
from taskinit import xmlpath
#from taskmanager import tm
import task_exportfits
def exportfits(imagename='', fitsimage='', velocity=False, optical=False, bitpix=-32, minpix=0, maxpix=-1, overwrite=False, dropstokes=False, stokeslast=True, history=True, dropdeg=False):
"""Convert a CASA image to a FITS file
FOR MORE INFORMATION, SEE THE TASK PAGES OF EXPORTFITS IN CASA DOCS:
https://casa.nrao.edu/casadocs/
"""
#
# The following is work around to avoid a bug with current python translation
#
mytmp = {}
mytmp['imagename'] = imagename
mytmp['fitsimage'] = fitsimage
mytmp['velocity'] = velocity
mytmp['optical'] = optical
mytmp['bitpix'] = bitpix
mytmp['minpix'] = minpix
mytmp['maxpix'] = maxpix
mytmp['overwrite'] = overwrite
mytmp['dropstokes'] = dropstokes
mytmp['stokeslast'] = stokeslast
mytmp['history'] = history
mytmp['dropdeg'] = dropdeg
pathname='file://' + xmlpath( ) + '/'
trec = casac.utils().torecord(pathname+'exportfits.xml')
casalog.origin('exportfits')
if trec.has_key('exportfits') and casac.utils().verify(mytmp, trec['exportfits']) :
result = task_exportfits.exportfits(imagename, fitsimage, velocity, optical, bitpix, minpix, maxpix, overwrite, dropstokes, stokeslast, history, dropdeg)
else :
result = False
return result
|
[
"gijs@pythonic.nl"
] |
gijs@pythonic.nl
|
568bc42695dfdf14190d884be35c1c4afa43689f
|
d1ac66f9a935fd5515a16a1cc8d4dae0104ea0fe
|
/src/check_structures.py
|
3c3fea7183213683e377187b6fdf992c82b42c34
|
[
"MIT"
] |
permissive
|
chemspacelab/meltingpoint
|
8b1b1f5a7e6f45fee82c2e8d55db2df29c6ae0bc
|
e3d8eb61fcb5fa5c9c2a1a03852216e4e625a9c9
|
refs/heads/master
| 2020-08-30T06:08:17.739191
| 2020-04-17T11:18:32
| 2020-04-17T11:18:32
| 218,285,755
| 5
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,068
|
py
|
import qml
from chemhelp import cheminfo
import numpy as np
from rdkit import Chem
import sys
args = sys.argv[1:]
filename = args[0]
molobjs = cheminfo.read_sdffile(filename)
for i, molobj in enumerate(molobjs):
molobj = next(molobjs)
# stat = cheminfo.molobj_optimize(molobj)
# print(stat)
dist = Chem.rdmolops.Get3DDistanceMatrix(molobj)
np.fill_diagonal(dist, 10.0)
min_dist = np.min(dist)
if min_dist < 0.01:
print(i, min_dist)
smi = cheminfo.molobj_to_smiles(molobj)
molobj = cheminfo.conformationalsearch(smi)
dist = Chem.rdmolops.Get3DDistanceMatrix(molobj)
np.fill_diagonal(dist, 10.0)
min_dist = np.min(dist)
print(smi)
print(min_dist)
# atoms, coord = cheminfo.molobj_to_xyz(molobj)
# atoms = list(atoms)
# many_atoms = [atoms]
# mbtypes = qml.representations.get_slatm_mbtypes(many_atoms)
# rep = qml.representations.generate_slatm(coord, atoms, mbtypes)
# print(cheminfo.molobj_to_smiles(molobj))
# print(rep.mean())
|
[
"jimmy@charnley.dk"
] |
jimmy@charnley.dk
|
dae39314521542665f7fe4ce4c6605824fa4d40c
|
728e57a80995d7be98d46295b780d0b433c9e62a
|
/src/rewriter/rewriter.gyp
|
1566c15345faf46401995133dcfc423cc15a2523
|
[
"Apache-2.0",
"MIT",
"BSD-3-Clause",
"GPL-1.0-or-later"
] |
permissive
|
SNQ-2001/Mozc-for-iOS
|
7936bfd9ff024faacfd2d96af3ec15a2000378a1
|
45b0856ed8a22d5fa6b4471548389cbde4abcf10
|
refs/heads/master
| 2023-03-17T22:19:15.843107
| 2014-10-04T05:48:29
| 2014-10-04T05:48:42
| 574,371,060
| 0
| 0
|
Apache-2.0
| 2022-12-05T06:48:07
| 2022-12-05T06:48:06
| null |
UTF-8
|
Python
| false
| false
| 4,492
|
gyp
|
# Copyright 2010-2014, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
{
'variables': {
'relative_dir': 'rewriter',
'gen_out_dir': '<(SHARED_INTERMEDIATE_DIR)/<(relative_dir)',
},
'targets': [
{
'target_name': 'rewriter',
'type': 'static_library',
'sources': [
'<(gen_out_dir)/embedded_collocation_data.h',
'<(gen_out_dir)/embedded_collocation_suppression_data.h',
'<(gen_out_dir)/emoji_rewriter_data.h',
'<(gen_out_dir)/emoticon_rewriter_data.h',
'<(gen_out_dir)/reading_correction_data.h',
'<(gen_out_dir)/single_kanji_rewriter_data.h',
'<(gen_out_dir)/symbol_rewriter_data.h',
'<(gen_out_dir)/usage_rewriter_data.h',
'calculator_rewriter.cc',
'collocation_rewriter.cc',
'collocation_util.cc',
'correction_rewriter.cc',
'command_rewriter.cc',
'date_rewriter.cc',
'dice_rewriter.cc',
'dictionary_generator.cc',
'embedded_dictionary.cc',
'emoji_rewriter.cc',
'emoticon_rewriter.cc',
'english_variants_rewriter.cc',
'focus_candidate_rewriter.cc',
'fortune_rewriter.cc',
'language_aware_rewriter.cc',
'normalization_rewriter.cc',
'number_compound_util.cc',
'number_rewriter.cc',
'remove_redundant_candidate_rewriter.cc',
'rewriter.cc',
'single_kanji_rewriter.cc',
'symbol_rewriter.cc',
'transliteration_rewriter.cc',
'unicode_rewriter.cc',
'usage_rewriter.cc',
'user_boundary_history_rewriter.cc',
'user_dictionary_rewriter.cc',
'user_segment_history_rewriter.cc',
'variants_rewriter.cc',
'version_rewriter.cc',
'zipcode_rewriter.cc',
],
'dependencies': [
'../base/base.gyp:base',
'../base/base.gyp:config_file_stream',
'../composer/composer.gyp:composer',
'../config/config.gyp:character_form_manager',
'../config/config.gyp:config_handler',
'../config/config.gyp:config_protocol',
'../converter/converter_base.gyp:conversion_request',
'../converter/converter_base.gyp:immutable_converter',
'../data_manager/data_manager.gyp:user_pos_manager',
'../dictionary/dictionary.gyp:dictionary',
'../dictionary/dictionary_base.gyp:pos_matcher',
'../session/session_base.gyp:session_protocol',
'../storage/storage.gyp:storage',
'../usage_stats/usage_stats_base.gyp:usage_stats',
'calculator/calculator.gyp:calculator',
'rewriter_base.gyp:gen_rewriter_files#host',
],
'xcode_settings' : {
'SDKROOT': 'iphoneos',
'IPHONEOS_DEPLOYMENT_TARGET': '7.0',
'ARCHS': '$(ARCHS_UNIVERSAL_IPHONE_OS)',
},
'conditions':[
['target_platform=="Android"', {
'sources!': [
'<(gen_out_dir)/usage_rewriter_data.h',
'usage_rewriter.cc',
],
}],
]
},
],
}
|
[
"kishikawakatsumi@mac.com"
] |
kishikawakatsumi@mac.com
|
0cc9f793bbbacb2d71d1f077caac1470878e96ee
|
badb121a8c72debc539e7b9caf17b5c4cd875897
|
/setup.py
|
d788bb0448c2f1d68b5d93911c2598c8b73aeadc
|
[
"MIT"
] |
permissive
|
shlpu/DeepNeuro
|
8721e1f83b30031a422e6cf112c31879edfa0feb
|
6b239942589d1b05e2384019c442508f5d02beb3
|
refs/heads/master
| 2020-03-16T07:12:25.128910
| 2018-04-10T22:32:29
| 2018-04-10T22:32:29
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,506
|
py
|
"""DeepNeuro: A deep learning python package for neuroimaging data.
Created by the Quantitative Tumor Imaging Lab at the Martinos Center
(Harvard-MIT Program in Health, Sciences, and Technology / Massachussets General Hospital).
"""
DOCLINES = __doc__.split("\n")
import sys
from setuptools import setup, find_packages
from codecs import open
from os import path
if sys.version_info[:2] < (2, 7):
raise RuntimeError("Python version 2.7 or greater required.")
setup(
name = 'deepneuro',
# packages = ['qtim_tools'], # this must be the same as the name above
version = '0.1.1',
description = DOCLINES[0],
packages = find_packages(),
entry_points = {
"console_scripts": ['segment_gbm = deepneuro.pipelines.Segment_GBM.cli:main',
'skull_strip = deepneuro.pipelines.Skull_Stripping.cli:main'],
},
author = 'Andrew Beers',
author_email = 'abeers@mgh.harvard.edu',
url = 'https://github.com/QTIM-Lab/DeepNeuro', # use the URL to the github repo
download_url = 'https://github.com/QTIM-Lab/DeepNeuro/tarball/0.1.1',
keywords = ['neuroimaging', 'neuroncology', 'neural networks', 'neuroscience', 'neurology', 'deep learning', 'fmri', 'pet', 'mri', 'dce', 'dsc', 'dti', 'machine learning', 'computer vision', 'learning', 'keras', 'theano', 'tensorflow', 'nfiti', 'nrrd', 'dicom'],
install_requires=['keras', 'pydicom', 'pynrrd', 'nibabel', 'numpy', 'scipy', 'scikit-image==0.12.3'],
classifiers = [],
)
|
[
"andrew_beers@alumni.brown.edu"
] |
andrew_beers@alumni.brown.edu
|
54b5f9999727867f92c0a86ef38bb2f8502bf5aa
|
56fc8fe58ec8d576ec857f19a8adc43b49e19125
|
/DjangoDrf/DjangoDrf/urls.py
|
c75f1d5a486221814c1b64622ac12621ad0426fc
|
[] |
no_license
|
Qpigzhu/Drf
|
53ae3dfd7d2715ea49bbfca02ada1a9239cb25a2
|
e4faa165a81abe8e641b992b6f86cc46cb01ac16
|
refs/heads/master
| 2022-12-13T16:30:33.868771
| 2018-12-12T02:34:11
| 2018-12-12T02:34:11
| 161,421,986
| 0
| 0
| null | 2022-12-08T01:20:24
| 2018-12-12T02:32:20
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 2,253
|
py
|
"""DjangoDrf URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include,re_path
from django.views.static import serve
import xadmin
from rest_framework.documentation import include_docs_urls
from rest_framework.routers import DefaultRouter
from rest_framework_jwt.views import obtain_jwt_token
from .settings import MEDIA_ROOT
from goods.views import GoodsList,CategoryViewset
from users.views import SmsCodeView,UserView
#使用router注册Url
router = DefaultRouter()
router.register('goods',GoodsList,base_name="GoodsList")
# 配置Category的url
router.register('categorys', CategoryViewset, base_name="categories")
#发送验证码
router.register("code",SmsCodeView,base_name="sms_code")
#用户
router.register("users",UserView,base_name="users")
urlpatterns = [
# path('admin/', admin.site.urls),
#rest_framewor的Url,方便测试
path('api-auth/', include('rest_framework.urls')),
#xadmin后台Url
path('xadmin/', xadmin.site.urls),
# 富文本相关url
path('ueditor/', include('DjangoUeditor.urls')),
# 处理图片显示的url,使用Django自带serve,传入参数告诉它去哪个路径找,我们有配置好的路径MEDIAROOT
re_path('media/(?P<path>.*)', serve, {"document_root": MEDIA_ROOT}),
#rest_framework自动化文档,1.11版本中注意此处前往不要加$符号
path('docs/',include_docs_urls(title='mtianyan生鲜超市文档')),
#食品列表
# path('goods/',GoodsList.as_view(),name="食品列表"),
#使用router注册Url
path('', include(router.urls)),
#使用jwt来登录
path('login/',obtain_jwt_token),
]
|
[
"331103418@qq.com"
] |
331103418@qq.com
|
4fdd0d8c6ae5710146751a450372bd9c6f5b06d7
|
1934761958bbb6082beebe887af36d7579d73fd5
|
/sandbox/test_concatenation.py
|
e25fa9c7ed94080b29d6fbe34cc88e58924e3439
|
[
"MIT"
] |
permissive
|
sjoerdapp/tacoma
|
92d16e0beb93a3fc0dd0a745bccc35e050fa5dbe
|
3c63d51e2b9b021f95a6945716f50b557dd41d52
|
refs/heads/master
| 2020-04-10T14:01:22.713198
| 2018-12-07T17:10:09
| 2018-12-07T17:10:09
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,403
|
py
|
import tacoma as tc
print("===== edge_lists => edge_lists =====")
L = tc.edge_lists()
L.N = 4
L.t = [0.0,1.0,2.0]
L.tmax = 3.0
L.edges = [
[
(0,1)
],
[
(1,2), (0,2)
],
[
(0,1)
],
]
L2 = tc.edge_lists()
L2.N = 4
L2.t = [0.0,1.0,2.0]
L2.tmax = 3.0
L2.edges = [
[
(3,1)
],
[
(3,2), (0,2)
],
]
new = tc.concatenate([L,L2,L])
print(new.N)
print(new.t)
print(new.tmax)
print(new.edges)
print("===== edge_changes => edge_changes =====")
C = tc.edge_changes()
C.N = 4
C.edges_initial = [ (0,1) ]
C.t0 = 1.0
C.tmax = 3.0
C.t = [ 2.0, ]
C.edges_in = [
[
(1,2), (0,2)
],
]
C.edges_out = [
[
(0,1)
],
]
C2 = tc.edge_changes()
C2.N = 4
C2.edges_initial = [ (3,1) ]
C2.t0 = 1.0
C2.tmax = 3.0
C2.t = [ 2.0, ]
C2.edges_in = [
[
(3,2), (0,2)
],
]
C2.edges_out = [
[
(3,1)
],
]
new = tc.concatenate([C,C2,C])
print(new.N)
print(new.t0)
print(new.t)
print(new.tmax)
print(new.edges_initial)
print(new.edges_in)
print(new.edges_out)
|
[
"benjaminfrankmaier@gmail.com"
] |
benjaminfrankmaier@gmail.com
|
75b3a9895a158f61870ce7f6948ee8c615166ebf
|
ad1fc1783487a70b3b10e9d3927cd864d15a6056
|
/pytablewriter/style/__init__.py
|
01aa4c10be5158f44fcc371276ce1231fe78cce7
|
[
"MIT"
] |
permissive
|
Diwahars/pytablewriter
|
ea1d53669d7f0507c35332cb296fc9c0015473d0
|
6275405d75cb091c9e225e278b0d1230736fb9e8
|
refs/heads/master
| 2020-04-16T09:41:39.070414
| 2019-01-09T13:38:03
| 2019-01-09T13:38:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 321
|
py
|
# encoding: utf-8
from __future__ import absolute_import
from ._font import FontSize, FontWeight
from ._style import Align, Style, ThousandSeparator
from ._styler import (
HtmlStyler,
LatexStyler,
NullStyler,
TextStyler,
MarkdownStyler,
ReStructuredTextStyler,
)
from dataproperty import Format
|
[
"tsuyoshi.hombashi@gmail.com"
] |
tsuyoshi.hombashi@gmail.com
|
0f9324881116da5ccc6d95e209e3b1eca52c64cb
|
d0bdf444c71b724ecfd59b5bc6850962c56494cb
|
/labs/07-resampling_and_the_bootstrap/tests/q0_2.py
|
cb757a625b8c22fcb31df3b7f2d4ca35b9ab74d6
|
[] |
no_license
|
ucsd-ets/dsc10-su20-public
|
10e3d0ff452b337f222baee330fe60d1465b0071
|
38787e6cc3e6210b4cc8a46350e5120845971c9f
|
refs/heads/master
| 2022-12-13T23:28:20.512649
| 2020-09-03T19:28:06
| 2020-09-03T19:28:06
| 275,905,339
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 356
|
py
|
test = {
'hidden': False,
'name': '0.2',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
>>> p_50 == 76
True
""",
'hidden': False,
'locked': False
}
],
'scored': True,
'setup': '',
'teardown': '',
'type': 'doctest'
}
]
}
|
[
"eldridgejm@gmail.com"
] |
eldridgejm@gmail.com
|
911268cc7033fdb9e4f5dfa358b0e1e352f93e23
|
ae39044997354b7270c6f35957bdd5efdcfbd2ee
|
/21.类.py/carse.py
|
c25056e3efde01e2d06ef62660cd80b401ed2c88
|
[] |
no_license
|
text007/learngit
|
a2a7d8c872f17103a388f77370dcd07d6eb477c9
|
6f3429ecab51f738a99b2ec6637cd21603f48ec4
|
refs/heads/master
| 2020-06-18T13:18:34.563100
| 2019-10-08T13:08:09
| 2019-10-08T13:08:09
| 156,345,863
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,057
|
py
|
'''一个类'''
# 导入另外一个类
from cars import Car
class Battery(): # 定义一个类
def __init__(self, battery_size = 70): # 定义一个方法,传入一个形参,如果没有传入参数值,则默认值
self.battery_size = battery_size # 初始化
def describe_battery(self): # 定义一个方法
print(str(self.battery_size)) # 打印
def get_range(self): # 定义一个方法
if self.battery_size == 70: # 当
range = 240
elif self.battery_size == 85: # 当
range = 270
message = 'T ' + str(range)
message += ' m'
print(message) # 打印
class ElectricCar(Car): # 定义子类,()中必须包含父类名称
def __init__(self, make, model, year): # 接受创建父类实例所需信息
# 初始化父类属性
# super():特殊方法;将父类与子类关联
super().__init__(make, model, year)
self.battery = Battery() # 子类包含这个属性,父类不包含
|
[
"jzheng@qumitech.local"
] |
jzheng@qumitech.local
|
4ed203fe5bd61e1e611d29326dfa8157d106a3bd
|
292726345fae67a78771477e164441a716e0c22b
|
/setup.py
|
90234c02a27b4334d60238f950aa900379015c21
|
[] |
no_license
|
anirban89/mypackage
|
d9bf8c7b0d2cc9dbd4ac4b5493cd650bf390f8a7
|
7b38e6db6c9e60cf2edb2b34ebe649ec3b7f0737
|
refs/heads/master
| 2021-01-13T02:26:17.878874
| 2014-10-02T00:29:34
| 2014-10-02T00:29:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 132
|
py
|
from setuptools import setup
setup(
name = 'mypackage',
version = 0.1,
packages = ['mypackage'],
install_requires = ['numpy']
)
|
[
"anirbancnha@gmail.com"
] |
anirbancnha@gmail.com
|
f705ee4bc444b70f5af055fe8b3972fe83329f2c
|
8a6c18088c50bc782df58e176663114d91ffc47c
|
/src/teams/migrations/0048_auto_20180814_1950.py
|
c59f9f8cb4135dcc034d5f69b80569efbd596119
|
[
"BSD-3-Clause"
] |
permissive
|
flummer/bornhack-website
|
14cc55f34b85740d32567d6a3934e865f2549381
|
c40f225f0993a6edd25dc608de1f6467f7d8e5a1
|
refs/heads/master
| 2020-04-29T13:23:44.167064
| 2019-05-12T15:30:01
| 2019-05-12T15:30:01
| 176,167,685
| 0
| 0
|
BSD-3-Clause
| 2019-03-17T22:19:27
| 2019-03-17T22:19:27
| null |
UTF-8
|
Python
| false
| false
| 359
|
py
|
# Generated by Django 2.1 on 2018-08-14 17:50
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('teams', '0047_taskcomment'),
]
operations = [
migrations.RenameField(
model_name='taskcomment',
old_name='content',
new_name='comment',
),
]
|
[
"valberg@orn.li"
] |
valberg@orn.li
|
07151db73c571183b2efe81f155b7ee8f4d0d5aa
|
9b8e2992a38f591032997b5ced290fe1acc3ad94
|
/untitled1.py
|
5168631138eec406cbc548e97cca8ab1abb1401a
|
[] |
no_license
|
girishdhegde/aps-2020
|
c694443c10d0d572c8022dad5a6ce735462aaa51
|
fb43d8817ba16ff78f93a8257409d77dbc82ced8
|
refs/heads/master
| 2021-08-08T04:49:18.876187
| 2021-01-02T04:46:20
| 2021-01-02T04:46:20
| 236,218,152
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,329
|
py
|
import cv2
import numpy as np
def dense():
global cap,currentframe
if denseflag==1:
x=currentframe
x1=x-100
y1=x+100
count=x1
cap.set(1,x1)
ret, frame1 = cap.read()
prvs = cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY)
while(count<y1):
ret, frame2 = cap.read()
next1 = cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY)
flow = cv2.calcOpticalFlowFarneback(prvs,next1, None, 0.5, 3, 15, 3, 5, 1.2, 0)
a=flow[0]
a=np.sum(np.square(a))
b=flow[1]
b=np.sum(np.square(b))
z=np.sqrt(a+b)
data.append([count,z])
print(count)
#cv2.imshow('frame1',frame1)
#k = cv2.waitKey(30) & 0xff
#if k == 27:
# break
prvs = next1
count+=1
List = [data[f][1] for f in range(len(data))]
high=List.index(max(List))
print(high)
cap.set(1,data[high][0])
currentframe = data[high][0]
ret, frame1 = cap.read()
cv2.destroyAllWindows()
cv2.imshow('frame',frame1)
else :
print("Check mark optical flow")
temp=[]
data=[]
def left():
global currentframe,high,List,temp,cap
if denseflag==1:
if(high!=0):
temp=[List[f] for f in range(0,high)]
high=temp.index(max(temp))
high=List.index(temp[high])
print(data[high][0])
cap.set(1,data[high][0])
currentframe = data[high][0]
ret, frame1 = cap.read()
cv2.destroyAllWindows()
cv2.imshow('frame',frame1)
else:
print("Go right")
else :
print("Check mark optical flow")
def right():
global high,List,cap,currentframe
if denseflag==1:
if(high!=199):
temp=[List[f] for f in range(high+1,200)]
high=temp.index(max(temp))
high=List.index(temp[high])
print(data[high][0])
cap.set(1,data[high][0])
currentframe = data[high][0]
ret, frame1 = cap.read()
cv2.destroyAllWindows()
cv2.imshow('frame',frame1)
else:
print("Go left")
else :
print("Check mark optical flow")
|
[
"girsihdhegde12499@gmail.com"
] |
girsihdhegde12499@gmail.com
|
5294c57910e749afa0feb0dc04adc4fd5fdc14aa
|
a7685d315e6616cc2b6d43587bb19ead4324fb2a
|
/cci_salesman/wizard/extract_participations.py
|
11c7dc952971d632537da32cf14d109bdf728a5d
|
[] |
no_license
|
philmervdm/modules_cci_odoo8
|
472ea68de409e876722413afdd873d6a7827744e
|
603144219a86e805f7603cfafc0fb05a78166eef
|
refs/heads/master
| 2021-01-09T20:02:58.326569
| 2017-05-06T15:45:03
| 2017-05-06T15:45:03
| 60,332,279
| 2
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,601
|
py
|
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
# $Id$
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import wizard
import pooler
import datetime
def _club_active_participations(self, cr, uid, data, context):
club_id = data['id']
# cr.execute('SELECT p.id FROM cci_club_participation as p, cci_club_participation_state as s WHERE p.group_id = %s AND ( p.date_out is null OR p.date_out > %s ) #AND p.state_id = s.id AND s.current', (club_id, datetime.date.today() ))
# res = cr.fetchall()
# part_ids = [x[0] for x in res]
# value = {
# 'domain': [('id', 'in', part_ids)],
# 'name': 'Active Participations',
# 'view_type': 'form',
# 'view_mode': 'tree,form',
# 'res_model': 'cci_club.participation',
# 'context': {},
# 'type': 'ir.actions.act_window'
# }
# THE FOLLOWING WAY IS MORE DYNAMIC
value = {
'domain': [('group_id', '=', club_id),('state_id.current','=',True),'|',('date_out','=',False),('date_out','>',datetime.date.today().strftime('%Y-%m-%d') )],
'name': 'Active Participations',
'view_type': 'form',
'view_mode': 'tree,form',
'res_model': 'cci_club.participation',
'context': {},
'type': 'ir.actions.act_window'
}
return value
class wizard_club_active_participations(wizard.interface):
states = {
'init': {
'actions': [],
'result': {
'type': 'action',
'action': _club_active_participations,
'state': 'end'
}
},
}
wizard_club_active_participations("wizard_cci_club_active_participations")
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
[
"philmer@ccilvn.be"
] |
philmer@ccilvn.be
|
37aad6a8d126f7a2f34d49e6e6fd4bddd5f08cb1
|
7f529df5381361874d51c8cb7d8678e088dbe71d
|
/aea/protocols/default/__init__.py
|
52e51b51e36ef3b50d6e1ccddf33b0782f9c9c80
|
[
"Apache-2.0"
] |
permissive
|
cyenyxe/agents-aea
|
914546708ce3e2e913ce1bb48bc8928289738c9a
|
c2aec9127028ae13def3f69fbc80d35400de1565
|
refs/heads/master
| 2021-01-07T05:36:27.879856
| 2020-02-07T19:28:01
| 2020-02-07T19:28:01
| 241,594,907
| 0
| 0
|
Apache-2.0
| 2020-03-05T14:53:54
| 2020-02-19T10:35:49
| null |
UTF-8
|
Python
| false
| false
| 872
|
py
|
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ------------------------------------------------------------------------------
"""This module contains the support resources for the default protocol."""
|
[
"david.minarsch@googlemail.com"
] |
david.minarsch@googlemail.com
|
125494d60a6fda1d0624163876564440784178ed
|
f8666599b83d34c861651861cc7db5b3c434fc87
|
/plotly/validators/carpet/baxis/tickformatstop/_name.py
|
8ff0b7a47aa7b5fed8b166c536845b675ff38361
|
[
"MIT"
] |
permissive
|
mode/plotly.py
|
8b66806e88c9f1820d478bab726f0bea81884432
|
c5a9ac386a40df2816e6c13264dadf14299401e4
|
refs/heads/master
| 2022-08-26T00:07:35.376636
| 2018-09-26T19:08:54
| 2018-09-26T19:19:31
| 60,372,968
| 1
| 1
|
MIT
| 2019-11-13T23:03:22
| 2016-06-03T19:34:55
|
Python
|
UTF-8
|
Python
| false
| false
| 492
|
py
|
import _plotly_utils.basevalidators
class NameValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name='name',
parent_name='carpet.baxis.tickformatstop',
**kwargs
):
super(NameValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop('edit_type', 'calc'),
role=kwargs.pop('role', 'style'),
**kwargs
)
|
[
"noreply@github.com"
] |
mode.noreply@github.com
|
d15d67d65624be46de1b72401f49d991cdb8c86e
|
f9d564f1aa83eca45872dab7fbaa26dd48210d08
|
/huaweicloud-sdk-projectman/huaweicloudsdkprojectman/v4/model/batch_delete_iterations_v4_request.py
|
49a9950000cd6af7e35e6cdf50daf4cd5933de11
|
[
"Apache-2.0"
] |
permissive
|
huaweicloud/huaweicloud-sdk-python-v3
|
cde6d849ce5b1de05ac5ebfd6153f27803837d84
|
f69344c1dadb79067746ddf9bfde4bddc18d5ecf
|
refs/heads/master
| 2023-09-01T19:29:43.013318
| 2023-08-31T08:28:59
| 2023-08-31T08:28:59
| 262,207,814
| 103
| 44
|
NOASSERTION
| 2023-06-22T14:50:48
| 2020-05-08T02:28:43
|
Python
|
UTF-8
|
Python
| false
| false
| 4,126
|
py
|
# coding: utf-8
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class BatchDeleteIterationsV4Request:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'project_id': 'str',
'body': 'BatchDeleteIterationsV4RequestBody'
}
attribute_map = {
'project_id': 'project_id',
'body': 'body'
}
def __init__(self, project_id=None, body=None):
"""BatchDeleteIterationsV4Request
The model defined in huaweicloud sdk
:param project_id: devcloud项目的32位id
:type project_id: str
:param body: Body of the BatchDeleteIterationsV4Request
:type body: :class:`huaweicloudsdkprojectman.v4.BatchDeleteIterationsV4RequestBody`
"""
self._project_id = None
self._body = None
self.discriminator = None
self.project_id = project_id
if body is not None:
self.body = body
@property
def project_id(self):
"""Gets the project_id of this BatchDeleteIterationsV4Request.
devcloud项目的32位id
:return: The project_id of this BatchDeleteIterationsV4Request.
:rtype: str
"""
return self._project_id
@project_id.setter
def project_id(self, project_id):
"""Sets the project_id of this BatchDeleteIterationsV4Request.
devcloud项目的32位id
:param project_id: The project_id of this BatchDeleteIterationsV4Request.
:type project_id: str
"""
self._project_id = project_id
@property
def body(self):
"""Gets the body of this BatchDeleteIterationsV4Request.
:return: The body of this BatchDeleteIterationsV4Request.
:rtype: :class:`huaweicloudsdkprojectman.v4.BatchDeleteIterationsV4RequestBody`
"""
return self._body
@body.setter
def body(self, body):
"""Sets the body of this BatchDeleteIterationsV4Request.
:param body: The body of this BatchDeleteIterationsV4Request.
:type body: :class:`huaweicloudsdkprojectman.v4.BatchDeleteIterationsV4RequestBody`
"""
self._body = body
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
import simplejson as json
if six.PY2:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)
def __repr__(self):
"""For `print`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, BatchDeleteIterationsV4Request):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
[
"hwcloudsdk@huawei.com"
] |
hwcloudsdk@huawei.com
|
740028a049c72a4eb04c08359edfac9f378d6525
|
c0340c511cff5b40b4681c4d3238d807624c0323
|
/models/corpus_reader/corpusIterator.py
|
9ae01c2a3c9b76ef214d4727d895cd74c0b05141
|
[] |
no_license
|
m-hahn/grammar-optim
|
5fa7ade47d2ad91f517c887ee2c65af24059069d
|
07a1a80692a504bcafc8120a21c4dc9066b495ee
|
refs/heads/master
| 2022-08-30T06:54:42.749264
| 2022-08-05T12:09:28
| 2022-08-05T12:09:28
| 156,456,167
| 13
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,334
|
py
|
import os
import random
import sys
header = ["index", "word", "lemma", "posUni", "posFine", "morph", "head", "dep", "_", "_"]
def readUDCorpus(language, partition):
basePaths = ["/u/scr/mhahn/grammar-optim_ADDITIONAL/corpora/"]
files = []
while len(files) == 0:
if len(basePaths) == 0:
print("No files found")
raise IOError
basePath = basePaths[0]
del basePaths[0]
files = os.listdir(basePath)
files = list(filter(lambda x:x.startswith("UD_"+language), files))
data = []
for name in files:
if "Sign" in name:
print("Skipping "+name)
continue
assert ("Sign" not in name)
if "Chinese-CFL" in name:
print("Skipping "+name)
continue
suffix = name[len("UD_"+language):]
subDirectory =basePath+"/"+name
subDirFiles = os.listdir(subDirectory)
partitionHere = partition
candidates = list(filter(lambda x:"-ud-"+partitionHere+"." in x and x.endswith(".conllu"), subDirFiles))
if len(candidates) == 0:
print("Did not find "+partitionHere+" file in "+subDirectory)
continue
if len(candidates) == 2:
candidates = list(filter(lambda x:"merged" in x, candidates))
assert len(candidates) == 1, candidates
try:
dataPath = subDirectory+"/"+candidates[0]
with open(dataPath, "r") as inFile:
newData = inFile.read().strip().split("\n\n")
assert len(newData) > 1
data = data + newData
except IOError:
print("Did not find "+dataPath)
assert len(data) > 0, (language, partition, files)
print >> sys.stderr, "Read "+str(len(data))+ " sentences from "+str(len(files))+" "+partition+" datasets."
return data
class CorpusIterator():
def __init__(self, language, partition="train", storeMorph=False, splitLemmas=False, shuffleData=True, shuffleDataSeed=None, splitWords=False):
assert not splitLemmas
self.splitLemmas = splitLemmas
self.splitWords = splitWords
assert not self.splitWords
self.storeMorph = storeMorph
data = readUDCorpus(language, partition)
if shuffleData:
if shuffleDataSeed is None:
random.shuffle(data)
else:
random.Random(shuffleDataSeed).shuffle(data)
self.data = data
self.partition = partition
self.language = language
assert len(data) > 0, (language, partition)
def permute(self):
random.shuffle(self.data)
def length(self):
return len(self.data)
def processSentence(self, sentence):
sentence = list(map(lambda x:x.split("\t"), sentence.split("\n")))
result = []
for i in range(len(sentence)):
# print sentence[i]
if sentence[i][0].startswith("#"):
continue
if "-" in sentence[i][0]: # if it is NUM-NUM
continue
if "." in sentence[i][0]:
continue
sentence[i] = dict([(y, sentence[i][x]) for x, y in enumerate(header)])
sentence[i]["head"] = int(sentence[i]["head"])
sentence[i]["index"] = int(sentence[i]["index"])
sentence[i]["word"] = sentence[i]["word"].lower()
if self.splitLemmas:
sentence[i]["lemmas"] = sentence[i]["lemma"].split("+")
if self.storeMorph:
sentence[i]["morph"] = sentence[i]["morph"].split("|")
if self.splitWords:
sentence[i]["words"] = sentence[i]["word"].split("_")
sentence[i]["dep"] = sentence[i]["dep"].lower()
if self.language == "LDC2012T05" and sentence[i]["dep"] == "hed":
sentence[i]["dep"] = "root"
if self.language == "LDC2012T05" and sentence[i]["dep"] == "wp":
sentence[i]["dep"] = "punct"
result.append(sentence[i])
# print sentence[i]
return result
def getSentence(self, index):
result = self.processSentence(self.data[index])
return result
def iterator(self, rejectShortSentences = False):
for sentence in self.data:
if len(sentence) < 3 and rejectShortSentences:
continue
yield self.processSentence(sentence)
|
[
"mhahn29@gmail.com"
] |
mhahn29@gmail.com
|
27c7fe3ed3a9f243315dd8256f5390ab76485e06
|
e81576012330e6a6024d14f3e241f88ca34b73cd
|
/python_code/vnev/Lib/site-packages/jdcloud_sdk/services/mps/apis/GetNotificationRequest.py
|
49630052bdeca358968876ff0e2634d9dd20ad88
|
[
"MIT"
] |
permissive
|
Ureimu/weather-robot
|
eba6a84147755aa83c941a306bac1a7c4e95e23e
|
7634195af388538a566ccea9f8a8534c5fb0f4b6
|
refs/heads/master
| 2021-01-15T07:23:42.274413
| 2020-03-23T02:30:19
| 2020-03-23T02:30:19
| 242,912,896
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,222
|
py
|
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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.
#
# NOTE: This class is auto generated by the jdcloud code generator program.
from jdcloud_sdk.core.jdcloudrequest import JDCloudRequest
class GetNotificationRequest(JDCloudRequest):
"""
获取媒体处理通知
"""
def __init__(self, parameters, header=None, version="v1"):
super(GetNotificationRequest, self).__init__(
'/regions/{regionId}/notification', 'GET', header, version)
self.parameters = parameters
class GetNotificationParameters(object):
def __init__(self, regionId, ):
"""
:param regionId: region id
"""
self.regionId = regionId
|
[
"a1090693441@163.com"
] |
a1090693441@163.com
|
578ab4564ac917e59f31823eb1d6cfb9f28fc608
|
2f98aa7e5bfc2fc5ef25e4d5cfa1d7802e3a7fae
|
/python/python_21885.py
|
8917a8ab7563dc2340287d482527305078ed27d8
|
[] |
no_license
|
AK-1121/code_extraction
|
cc812b6832b112e3ffcc2bb7eb4237fd85c88c01
|
5297a4a3aab3bb37efa24a89636935da04a1f8b6
|
refs/heads/master
| 2020-05-23T08:04:11.789141
| 2015-10-22T19:19:40
| 2015-10-22T19:19:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 136
|
py
|
# Making a call to a Chef server from Windows PE
> perl Configure VC-WIN32 no-asm no-shared
> ms\do_ms
> nmake -f ms\ntdll.mak
|
[
"ubuntu@ip-172-31-7-228.us-west-2.compute.internal"
] |
ubuntu@ip-172-31-7-228.us-west-2.compute.internal
|
4fcebeee0e3e255674d7dfda68f199803b482d48
|
c7e9ec5ce6627f6f68bab1b86a27a4516595154d
|
/maintenance/06migratedeletes.py
|
c9d6b4ad448306f6ddbcd4e2633be4ec2113805c
|
[] |
no_license
|
michaelcrubenstein/consentrecords
|
7b79e82c9ad4b5efcfbb44a50ff1d4cadf7180e2
|
992fe78c68d1d5c083f9e2cc0e3e9aa24363b93d
|
refs/heads/master
| 2021-01-23T19:28:13.807809
| 2018-07-03T16:10:34
| 2018-07-03T16:10:34
| 41,223,029
| 1
| 1
| null | 2018-07-03T16:10:35
| 2015-08-22T20:21:26
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 1,765
|
py
|
# Migrate translation objects to translation types.
import datetime
import django
import tzlocal
import getpass
import sys
from django.db import transaction
from django.contrib.auth import authenticate
from django.db.models import F
from django.db.models import Count
from consentrecords.models import TransactionState, Terms, Instance, Value, DeletedValue, DeletedInstance
from consentrecords.models import UserInfo, NameList
from consentrecords.models import AccessRecord
from consentrecords import pathparser
if __name__ == "__main__":
django.setup()
timezoneoffset = -int(tzlocal.get_localzone().utcoffset(datetime.datetime.now()).total_seconds()/60)
if len(sys.argv) > 1:
username = sys.argv[1]
else:
username = input('Email Address: ')
password = getpass.getpass("Password: ")
user = authenticate(username=username, password=password)
if not user:
raise ValueError("user was not authenticated")
with transaction.atomic():
transactionState = TransactionState(user, timezoneoffset)
Terms.initialize(transactionState)
i = Instance.objects.filter(deletedinstance__isnull=False).count()
j = Value.objects.filter(deletedvalue__isnull=False).count()
for x in Instance.objects.filter(deletedinstance__isnull=False):
x.deleteTransaction = x.deletedinstance.transaction
x.save()
for x in Value.objects.filter(deletedvalue__isnull=False):
x.deleteTransaction = x.deletedvalue.transaction
x.save()
print("migrate %s instances" % i)
print("migrate %s values" % j)
input('Confirm transaction: ')
print("Complete.")
|
[
"michaelcrubenstein@gmail.com"
] |
michaelcrubenstein@gmail.com
|
0c35e06c4e5be85693d075e16977c37d18936c4b
|
14aab11a9bd38acaaf3ed959ce736a3e1f1e3bad
|
/contrast/4/p4/mininet/delay.py
|
dc4aa0dd140d190cd83feac0ad77c10c8e299be3
|
[] |
no_license
|
chenyuchuting0912/SwitchML
|
4eae7d3a3f40c93156ebf039e34df67df430c286
|
d24ee879b3feadf308b4fdf52d090d0d21d1ee80
|
refs/heads/master
| 2020-06-03T17:41:13.993330
| 2020-01-09T02:39:47
| 2020-01-09T02:39:47
| 191,668,879
| 4
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,623
|
py
|
#!/usr/bin/python
from mininet.net import Mininet
from mininet.node import Controller, RemoteController, OVSController
from mininet.node import CPULimitedHost, Host, Node
from mininet.node import OVSKernelSwitch, UserSwitch
from mininet.node import IVSSwitch
from mininet.cli import CLI
from mininet.log import setLogLevel, info
from mininet.link import TCLink, Intf
from subprocess import call
def myNetwork():
net = Mininet( topo=None,
build=False,
ipBase='10.0.0.0/8')
info( '*** Adding controller\n' )
info( '*** Add switches\n')
s1 = net.addSwitch('s1', cls=OVSKernelSwitch)
info( '*** Add hosts\n')
h2 = net.addHost('h2', cls=Host, ip='10.0.0.2', defaultRoute=None)
h3 = net.addHost('h3', cls=Host, ip='10.0.0.3', defaultRoute=None)
h1 = net.addHost('h1', cls=Host, ip='10.0.0.1', defaultRoute=None)
info( '*** Add links\n')
h3s1 = {'bw':10,'delay':'5ms','loss':0,'max_queue_size':1000}
net.addLink(h3, s1, cls=TCLink , **h3s1)
h1s1 = {'bw':10,'delay':'5ms','loss':0,'max_queue_size':1000}
net.addLink(h1, s1, cls=TCLink , **h1s1)
h2s1 = {'bw':10,'delay':'5ms','loss':0,'max_queue_size':1000}
net.addLink(h2, s1, cls=TCLink , **h2s1)
info( '*** Starting network\n')
net.build()
info( '*** Starting controllers\n')
for controller in net.controllers:
controller.start()
info( '*** Starting switches\n')
net.get('s1').start([])
info( '*** Post configure switches and hosts\n')
CLI(net)
net.stop()
if __name__ == '__main__':
setLogLevel( 'info' )
myNetwork()
|
[
"18227357674@163.com"
] |
18227357674@163.com
|
045862281c288c88f92463538e884c0427ee8453
|
d41d18d3ea6edd2ec478b500386375a8693f1392
|
/plotly/validators/choropleth/_reversescale.py
|
8af580fb6748504b61ef7f5ef3b1ef25f5da02e4
|
[
"MIT"
] |
permissive
|
miladrux/plotly.py
|
38921dd6618650d03be9891d6078e771ffccc99a
|
dbb79e43e2cc6c5762251537d24bad1dab930fff
|
refs/heads/master
| 2020-03-27T01:46:57.497871
| 2018-08-20T22:37:38
| 2018-08-20T22:37:38
| 145,742,203
| 1
| 0
|
MIT
| 2018-08-22T17:37:07
| 2018-08-22T17:37:07
| null |
UTF-8
|
Python
| false
| false
| 431
|
py
|
import _plotly_utils.basevalidators
class ReversescaleValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(
self, plotly_name='reversescale', parent_name='choropleth', **kwargs
):
super(ReversescaleValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type='calc',
role='style',
**kwargs
)
|
[
"adam.kulidjian@gmail.com"
] |
adam.kulidjian@gmail.com
|
1f84f12505ff59602d122001d005785a8f5bce8d
|
adbedf9626c52748aa048f2b17c18d25262b4d56
|
/robot_framework_baseline_comparator/BaselineComparator/html_baseline.py
|
34eefcebeb0891f7888d2198c466c78c88472e5c
|
[] |
no_license
|
sanjitroy1992/robot_framework_custom_libraries
|
3ef91ea6d4705215f86c83d276d67ce7c5af673a
|
e5fde8f428a4d46d5cacb2c5369f9c59529f5c91
|
refs/heads/master
| 2022-11-06T09:11:02.148601
| 2020-06-29T09:35:46
| 2020-06-29T09:35:46
| 274,330,471
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,893
|
py
|
from Libraries.Common.BaselineComparator.HTMLTBodyComparator import HTMLBodyComparator
from Libraries.Common.BaselineComparator.HTMLTBodyComparator import HTMLFooterComparator
from Libraries.Common.BaselineComparator.HTMLTBodyComparator import HTMLHeaderComparator
from Libraries.Utilities import ReportBuilder
from itertools import zip_longest
import lxml.html
class HTMLBaseline(object):
def __init__(self):
self.success = True
self.error_msgs = set()
@staticmethod
def convert_csv_to_html(header, body):
table = lxml.html.fromstring('<table>')
header_lxml = HTMLBaseline._list_to_tbody(header)
body_lxml = HTMLBaseline._list_to_tbody(body)
table.append(header_lxml)
table.append(body_lxml)
return lxml.html.tostring(table, encoding='unicode')
@staticmethod
def _list_to_tbody(list_of_rows):
tbody = lxml.html.fromstring('<tbody>')
for row in list_of_rows:
tr = lxml.html.fromstring('<tr>')
for cell_text in row:
td = lxml.html.fromstring('<td>')
if cell_text is None:
td.text = "missed_or_extra_cell"
else:
td.text = cell_text.strip()
tr.append(td)
tbody.append(tr)
return tbody
def _open_file(self, baseline_file):
with open(baseline_file, "rb") as f:
return f.read()
def compare_html_pivot_baseline_to_application(self, baseline, app):
self.success = True
self.error_msgs = set()
report = ReportBuilder()
tbody, thead = self._prepare_table_for_pivot(report)
app, baseline = self._prepere_lxml_baseline_and_app(app, baseline)
self._compare_pivot_upper_part(app, baseline, report, thead)
self._compare_pivot_lower_part(app, baseline, report, tbody)
return self.success, self.error_msgs
def _compare_pivot_lower_part(self, app, baseline, report, tbody):
for row_left, row_right in zip_longest(self._compare_pivot_part(app, baseline, report, 3),
self._compare_pivot_part(app, baseline, report, 4)):
self._merge_pivot_parts(report, row_left, row_right, tbody)
def _merge_pivot_parts(self, report, row_left, row_right, tbody):
if row_left is None:
row_left = report.create_row()
td = report.create_td()
row_left.append(td)
right_tds = row_right.getchildren()
for td in right_tds:
row_left.append(td)
tbody.append(row_left)
def _compare_pivot_upper_part(self, app, baseline, report, thead):
for row_left, row_right in zip_longest(self._compare_pivot_part(app, baseline, report, 1),
self._compare_pivot_part(app, baseline, report, 2)):
self._merge_pivot_parts(report, row_left, row_right, thead)
def _prepere_lxml_baseline_and_app(self, app, baseline):
baseline = lxml.html.fromstring(baseline)
app = lxml.html.fromstring(app)
for tr in baseline.xpath(r".//tr[not(.//td[text()])]"):
tr.drop_tree()
for tr in app.xpath(r".//tr[not(.//td[text()])]"):
tr.drop_tree()
return app, baseline
def _prepare_table_for_pivot(self, report):
table = report.create_table()
thead = report.create_thead()
tbody = report.create_tbody()
table.append(thead)
table.append(tbody)
return tbody, thead
def _compare_pivot_part(self, app, baseline, report, index):
baseline_lxml = baseline.xpath('.//td[@id="no-boarder{}"]'.format(index))[0]
application_lxml = app.xpath('.//td[@id="no-boarder{}"]'.format(index))[0]
body_comparator = HTMLBodyComparator(baseline_lxml, application_lxml)
comparison = list(body_comparator.icompare())
self.success = self.success and body_comparator.success
self.error_msgs.update(body_comparator.error_msgs)
return comparison
def compare_html_baseline_to_app(self, baseline, app, skip_columns_names=None, sort_column_names=None,
key_column_names=None, missing_columns=None):
table_comparison = self._compare_table_to_baseline(baseline, app, skip_columns_names,
sort_column_names, key_column_names, missing_columns)
print("*HTML* {}".format(table_comparison))
return self.success, self.messages
def _compare_table_to_baseline(self, baseline, app, skip_columns_names=None, sort_column_names=None,
key_column_names=None, missing_columns=[]):
report = ReportBuilder()
table = report.create_table()
app, baseline = self._prepere_lxml_baseline_and_app(app, baseline)
baseline_header = [i.text_content() for i in
baseline.xpath(".//tbody")[0].xpath(".//tr")[0].xpath(".//td[not(@id)]")]
if missing_columns:
missing_columns_index = [baseline_header.index(i) for i in missing_columns]
else:
missing_columns_index = None
header_comparator = HTMLHeaderComparator(self._get_tbody_by_index(baseline, 0),
self._get_tbody_by_index(app, 0),
skip_columns_names,
key_column_names
)
body_comparator = HTMLBodyComparator(self._get_tbody_by_index(baseline, 1),
self._get_tbody_by_index(app, 1),
header_comparator.get_columns_indexes(skip_columns_names),
header_comparator.get_columns_indexes(sort_column_names),
header_comparator.get_columns_indexes(key_column_names),
baseline_header,
missing_columns_index
)
footer_comparator = HTMLFooterComparator(self._get_tbody_by_index(baseline, 2),
self._get_tbody_by_index(app, 2),
header_comparator.get_columns_indexes(skip_columns_names)
)
header_comparison = header_comparator.compare()
body_comparison, unique_key_found = body_comparator.compare()
if unique_key_found:
header_comparator = HTMLHeaderComparator(self._get_tbody_by_index(baseline, 0),
self._get_tbody_by_index(app, 0),
skip_columns_names,
key_column_names=unique_key_found
)
header_comparison = header_comparator.compare()
footer_comparison = footer_comparator.compare()
table.append(header_comparison)
table.append(body_comparison)
table.append(footer_comparison)
self.success = all([header_comparator.success, body_comparator.success, footer_comparator.success])
self.messages = set()
self.messages.update(header_comparator.error_msgs, body_comparator.error_msgs, footer_comparator.error_msgs)
return report
@staticmethod
def _get_tbody_by_index(app, index):
try:
app_part = app.xpath(".//tbody")[index]
except IndexError:
app_part = lxml.html.fromstring("<p></p>")
return app_part
|
[
"sanjit.roy@finastra.com"
] |
sanjit.roy@finastra.com
|
277537b8ae7e47142a220286372b6306e21c780c
|
a024fe3b05dd320a7860165dd72ebd832ce6e484
|
/account_cajas/models/payment_group.py
|
833df438839be2ce04c80b1330df47f33925d155
|
[] |
no_license
|
acostaw/erp_odoo
|
97d02a675908e441cf8e1ba4e3dcbc62691f8dec
|
2437997b650c9fdbf6a6f007c0a1fea2aab018e2
|
refs/heads/main
| 2023-04-19T14:52:48.877851
| 2021-04-22T18:40:07
| 2021-04-22T18:40:07
| 360,644,871
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,102
|
py
|
from odoo import fields, api, models, exceptions
class PaymentGroup(models.Model):
_inherit = 'grupo_account_payment.payment.group'
caja_session_id = fields.Many2one(
'account.caja.session', string="Sesión de caja")
def get_sesion(self):
sesion = self.env['account.caja.session'].search(
[('company_id', '=', self.company_id.id or self.env.user.company_id.id), ('user_id', '=', self.env.user.id), ('state', '=', 'proceso')])
return sesion
def button_confirmar(self):
for i in self:
for j in i.payment_ids:
caja = i.get_sesion().caja_id
if j.journal_id.id not in caja.journal_ids.ids:
raise exceptions.ValidationError('No se puede crear una linea de pago en el diario %s, el mismo no está habilitado para ésta caja.' %j.journal_id.name)
super(PaymentGroup, i).button_confirmar()
for j in i.payment_ids:
sesion = i.get_sesion()
for s in sesion.statement_ids.filtered(lambda x: x.journal_id == j.journal_id):
monto = j.amount
if i.payment_type == 'outbound':
monto = monto*-1
s.write(
{'line_ids': [(0, 0, {'journal_entry_ids': [(6, 0, j.move_line_ids.filtered(lambda z:z.debit > 0).ids)], 'date': fields.Date.today(), 'name': i.name, 'partner_id':i.partner_id.id, 'amount':monto,'payment_id':j.id})]})
@api.model
def create(self, vals):
if vals.get('payment_type') == 'inbound':
session = self.get_sesion()
if session:
vals['caja_session_id'] = session.id
else:
raise exceptions.ValidationError(
'No existe ninguna sesión de caja abierta para el usuario %s. Antes debe abrir una.' % (self.env.user.name))
return super(PaymentGroup, self).create(vals)
def button_cancelar(self):
for i in self:
if i.payment_type == 'inbound':
if i.caja_session_id and i.caja_session_id.state in ['proceso', 'cierre']:
super(PaymentGroup, i).button_cancelar()
for payment in i.payment_ids:
for st in i.caja_session_id.statement_ids:
lines = st.line_ids.filtered(
lambda l: l.payment_id == payment)
if lines:
lines.unlink()
if i.caja_session_id.state == 'cierre' and st.journal_id.type == 'bank':
st.write(
{'balance_end_real': st.balance_end_real-payment.amount})
return
else:
raise exceptions.ValidationError(
'Sólo se puede cancelar un recibo si su sesión de caja está abierta o en proceso de cierre.')
else:
super(PaymentGroup, i).button_cancelar()
|
[
"wacosta@INTN.GOV.PY"
] |
wacosta@INTN.GOV.PY
|
0f7ba2626ddb918345b5b65b7b33821c1416ba0d
|
63daf225819636397fda6ef7e52783331c27f295
|
/cbb/taobao/top/api/rest/WangwangEserviceNewevalsGetRequest.py
|
6ec015f4437fc789e6fe969e968f93ce8d6d80c1
|
[] |
no_license
|
cash2one/language-Python
|
e332ecfb4e9321a11407b29987ee64d44e552b15
|
8adb4f2fd2f023f9cc89b4edce1da5f71a3332ab
|
refs/heads/master
| 2021-06-16T15:15:08.346420
| 2017-04-20T02:44:16
| 2017-04-20T02:44:16
| 112,173,361
| 1
| 0
| null | 2017-11-27T09:08:57
| 2017-11-27T09:08:57
| null |
UTF-8
|
Python
| false
| false
| 370
|
py
|
'''
Created by auto_sdk on 2014.03.24
'''
from top.api.base import RestApi
class WangwangEserviceNewevalsGetRequest(RestApi):
def __init__(self,domain='gw.api.taobao.com',port=80):
RestApi.__init__(self,domain, port)
self.btime = None
self.etime = None
self.query_ids = None
def getapiname(self):
return 'taobao.wangwang.eservice.newevals.get'
|
[
"a@ie9.org"
] |
a@ie9.org
|
d948e6f2cea3277ef12bf61e893e539a196cdc75
|
ae326c4e6a2b2d5b67fa8d175249ef90f6a3021a
|
/leo/external/npyscreen/wgbutton.py
|
3c3864dccecbf6a1b774d0f84bc4e561b11aed17
|
[
"MIT"
] |
permissive
|
frakel/leo-editor
|
f95e6c77d60485d80fddfbeaf35db961cf691177
|
b574118ee3b7ffe8344fa0d00dac603096117ac7
|
refs/heads/master
| 2020-03-28T10:40:24.621077
| 2018-10-23T14:39:31
| 2018-10-23T14:39:31
| 148,132,817
| 0
| 0
|
MIT
| 2018-09-10T09:40:18
| 2018-09-10T09:40:18
| null |
UTF-8
|
Python
| false
| false
| 4,629
|
py
|
#@+leo-ver=5-thin
#@+node:ekr.20170428084207.524: * @file ../external/npyscreen/wgbutton.py
#!/usr/bin/python
#@+others
#@+node:ekr.20170428084207.525: ** Declarations
import curses
import locale
# import weakref
from . import npysGlobalOptions as GlobalOptions
# from . import wgwidget as widget
from . import wgcheckbox as checkbox
#@+node:ekr.20170428084207.526: ** class MiniButton
class MiniButton(checkbox._ToggleControl):
DEFAULT_CURSOR_COLOR = None
#@+others
#@+node:ekr.20170428084207.527: *3* __init__
def __init__(self, screen, name='Button', cursor_color=None, *args, **keywords):
self.encoding = 'utf-8'
self.cursor_color = cursor_color or self.__class__.DEFAULT_CURSOR_COLOR
if GlobalOptions.ASCII_ONLY or locale.getpreferredencoding() == 'US-ASCII':
self._force_ascii = True
else:
self._force_ascii = False
self.name = self.safe_string(name)
self.label_width = len(name) + 2
super(MiniButton, self).__init__(screen, *args, **keywords)
if 'color' in keywords:
self.color = keywords['color']
else:
self.color = 'CONTROL'
#@+node:ekr.20170428084207.528: *3* calculate_area_needed
def calculate_area_needed(self):
return 1, self.label_width+2
#@+node:ekr.20170428084207.529: *3* MiniButton.update
def update(self, clear=True):
if clear: self.clear()
if self.hidden:
self.clear()
return False
if self.value and self.do_colors():
self.parent.curses_pad.addstr(self.rely, self.relx, '>', self.parent.theme_manager.findPair(self))
self.parent.curses_pad.addstr(self.rely, self.relx+self.width-1, '<', self.parent.theme_manager.findPair(self))
elif self.value:
self.parent.curses_pad.addstr(self.rely, self.relx, '>')
self.parent.curses_pad.addstr(self.rely, self.relx+self.width-1, '<')
if self.editing:
button_state = curses.A_STANDOUT
else:
button_state = curses.A_NORMAL
button_name = self.name
if isinstance(button_name, bytes):
button_name = button_name.decode(self.encoding, 'replace')
button_name = button_name.center(self.label_width)
if self.do_colors():
if self.cursor_color:
if self.editing:
button_attributes = self.parent.theme_manager.findPair(self, self.cursor_color)
else:
button_attributes = self.parent.theme_manager.findPair(self, self.color)
else:
button_attributes = self.parent.theme_manager.findPair(self, self.color) | button_state
else:
button_attributes = button_state
self.add_line(self.rely, self.relx+1,
button_name,
self.make_attributes_list(button_name, button_attributes),
self.label_width
)
#@-others
#@+node:ekr.20170428084207.530: ** class MiniButtonPress
class MiniButtonPress(MiniButton):
# NB. The when_pressed_function functionality is potentially dangerous. It can set up
# a circular reference that the garbage collector will never free.
# If this is a risk for your program, it is best to subclass this object and
# override when_pressed_function instead. Otherwise your program will leak memory.
#@+others
#@+node:ekr.20170428084207.531: *3* __init__
def __init__(self, screen, when_pressed_function=None, *args, **keywords):
super(MiniButtonPress, self).__init__(screen, *args, **keywords)
self.when_pressed_function = when_pressed_function
#@+node:ekr.20170428084207.532: *3* set_up_handlers
def set_up_handlers(self):
'''MiniButtonPress.set_up_handlers.'''
super(MiniButtonPress, self).set_up_handlers()
self.handlers.update({
curses.ascii.NL: self.h_toggle,
curses.ascii.CR: self.h_toggle,
})
#@+node:ekr.20170428084207.533: *3* destroy
def destroy(self):
self.when_pressed_function = None
del self.when_pressed_function
#@+node:ekr.20170428084207.534: *3* h_toggle
def h_toggle(self, ch):
self.value = True
self.display()
if self.when_pressed_function:
self.when_pressed_function()
else:
self.whenPressed()
self.value = False
self.display()
#@+node:ekr.20170428084207.535: *3* whenPressed
def whenPressed(self):
pass
#@-others
#@-others
#@@language python
#@@tabwidth -4
#@-leo
|
[
"edreamleo@gmail.com"
] |
edreamleo@gmail.com
|
cbec1b9899516b898ddf2b75425a155a5e2e9388
|
5aa80aab7a75d76b0aa838bf8f74a276a12c876e
|
/src/dns/scripts/del_virtual_dns.py
|
d01e287f11d833d931e334fea48bc13f10915239
|
[
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
tungstenfabric/tf-controller
|
83b6d58afadb5697b540b5345711a5b2af90d201
|
f825fde287f4eb2089aba2225ca73eeab3888040
|
refs/heads/master
| 2023-08-28T02:56:27.329584
| 2023-08-20T12:15:38
| 2023-08-20T12:31:34
| 231,070,970
| 55
| 29
|
Apache-2.0
| 2023-07-23T01:38:17
| 2019-12-31T10:24:38
|
C++
|
UTF-8
|
Python
| false
| false
| 2,811
|
py
|
#!/usr/bin/python
#
#Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import object
import sys
import argparse
from six.moves import configparser
from provision_dns import DnsProvisioner
from requests.exceptions import ConnectionError
class DelVirtualDns(object):
def __init__(self, args_str = None):
self._args = None
if not args_str:
args_str = ' '.join(sys.argv[1:])
self._parse_args(args_str)
try:
dp_obj = DnsProvisioner(self._args.admin_user, self._args.admin_password,
self._args.admin_tenant_name,
self._args.api_server_ip, self._args.api_server_port)
except ConnectionError:
print('Connection to API server failed ')
return
dp_obj.del_virtual_dns(self._args.fq_name)
#end __init__
def _parse_args(self, args_str):
'''
Eg. python del_virtual_dns.py --fq_name default-domain:vdns1
'''
# Source any specified config/ini file
# Turn off help, so we print all options in response to -h
conf_parser = argparse.ArgumentParser(add_help = False)
args, remaining_argv = conf_parser.parse_known_args(args_str.split())
defaults = {
'api_server_ip' : '127.0.0.1',
'api_server_port' : '8082',
'admin_user': None,
'admin_password': None,
'admin_tenant_name': None
}
# Don't surpress add_help here so it will handle -h
parser = argparse.ArgumentParser(
# Inherit options from config_parser
parents=[conf_parser],
# print script description with -h/--help
description=__doc__,
# Don't mess with format of description
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.set_defaults(**defaults)
parser.add_argument("--fq_name", help = "Fully qualified Virtual DNS Name")
parser.add_argument("--api_server_ip", help = "IP address of api server")
parser.add_argument("--api_server_port", help = "Port of api server")
parser.add_argument("--admin_user", help = "Name of keystone admin user")
parser.add_argument("--admin_password", help = "Password of keystone admin user")
parser.add_argument("--admin_tenant_name", help = "Tenamt name for keystone admin user")
self._args = parser.parse_args(remaining_argv)
#end _parse_args
# end class DelVirtualDns
def main(args_str = None):
DelVirtualDns(args_str)
#end main
if __name__ == "__main__":
main()
|
[
"andrey-mp@yandex.ru"
] |
andrey-mp@yandex.ru
|
51f512a009d612d8737cedcd92ab98789dd019e2
|
13f5984be7be77852e4de29ab98d5494a7fc6767
|
/LeetCode/029两数相除.py
|
1156923f619001bb4fb9a6633818ed77385df8ac
|
[] |
no_license
|
YuanXianguo/Python-Interview-Master
|
4252514763fc3f563d9b94e751aa873de1719f91
|
2f73786e8c51dbd248341559de171e18f67f9bf2
|
refs/heads/master
| 2020-11-26T18:14:50.190812
| 2019-12-20T02:18:03
| 2019-12-20T02:18:03
| 229,169,825
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,793
|
py
|
"""
给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。
返回被除数 dividend 除以除数 divisor 得到的商。
"""
def divide(dividend, divisor):
if dividend > 0 and divisor > 0 or dividend < 0 and divisor < 0:
sign = 1 # 判断是否异号
else:
sign = -1
m = 1 # 记录当前除数是原除数的倍数
cnt = 0 # 记数
dd, dr = abs(dividend), abs(divisor)
while dd >= abs(divisor):
if dd < dr: # 如果当前除数太大,就重置除数
dr = abs(divisor)
m = 1
dd -= dr
cnt += m
dr <<= 1 # 除数扩大为2倍
m <<= 1 # 更新倍数
if sign == - 1: # 如果异号
cnt = -cnt
if cnt < -pow(2, 31) or cnt > pow(2, 31) - 1:
cnt = pow(2, 31) - 1
return cnt
class Solution:
def divide(self, dividend: int, divisor: int):
n = 1
cnt = 0
tmp_ds = abs(divisor)
tmp_dd = abs(dividend)
while tmp_dd >= abs(divisor):
tmp_dd -= tmp_ds
cnt += n
tmp_ds += tmp_ds # 更新除数和倍数
n += n
if tmp_dd < tmp_ds: # 重置除数和倍数
tmp_ds = abs(divisor)
n = 1
if (dividend > 0 and divisor > 0) or (dividend < 0 and divisor < 0):
sign = 1
else:
sign = -1
if sign < 0:
cnt = - cnt
if not - pow(2, 31) <= cnt <= pow(2, 31) - 1:
cnt = pow(2, 31) - 1
return cnt
if __name__ == '__main__':
print(divide(10, 3))
print(divide(10, 2))
print(divide(-1, -1))
print(divide(-1, 1))
print(divide(10, -2))
print(divide(10, -3))
|
[
"736913978@qq.com"
] |
736913978@qq.com
|
27d2228fcf7d6359ffa01c55e6fa92812d23a53d
|
c7a6f8ed434c86b4cdae9c6144b9dd557e594f78
|
/ECE364/.PyCharm40/system/python_stubs/348993582/gtk/gdk/EventMask.py
|
d9b44af804a2c42a9f51aefc54aa18bc8e118408
|
[] |
no_license
|
ArbalestV/Purdue-Coursework
|
75d979bbe72106975812b1d46b7d854e16e8e15e
|
ee7f86145edb41c17aefcd442fa42353a9e1b5d1
|
refs/heads/master
| 2020-08-29T05:27:52.342264
| 2018-04-03T17:59:01
| 2018-04-03T17:59:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,178
|
py
|
# encoding: utf-8
# module gtk.gdk
# from /usr/lib64/python2.6/site-packages/gtk-2.0/bonobo/ui.so
# by generator 1.136
# no doc
# imports
from exceptions import Warning
import gio as __gio
import gobject as __gobject
import gobject._gobject as __gobject__gobject
import pango as __pango
import pangocairo as __pangocairo
class EventMask(__gobject.GFlags):
# no doc
def __init__(self, *args, **kwargs): # real signature unknown
pass
__weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""list of weak references to the object (if defined)"""
__dict__ = None # (!) real value is ''
__flags_values__ = {
2: 2,
4: 4,
8: 8,
16: 16,
32: 32,
64: 64,
128: 128,
256: 256,
512: 512,
1024: 1024,
2048: 2048,
4096: 4096,
8192: 8192,
16384: 16384,
32768: 32768,
65536: 65536,
131072: 131072,
262144: 262144,
524288: 524288,
1048576: 1048576,
2097152: 2097152,
4194302: 4194302,
}
__gtype__ = None # (!) real value is ''
|
[
"pkalita@princeton.edu"
] |
pkalita@princeton.edu
|
16ea2edf996fdde207855365be0fe52b0d5e8b2d
|
05b0162d5ee7ab74f71ad4f21d5188a8735dfaef
|
/plugins/modules/telemetry_info.py
|
bda5b2c9f1557fd1446ffb91c4bca170ffd1fd56
|
[
"MIT"
] |
permissive
|
steinzi/ansible-ise
|
567b2e6d04ce3ca6fbdbb6d0f15cd1913a1e215a
|
0add9c8858ed8e0e5e7219fbaf0c936b6d7cc6c0
|
refs/heads/main
| 2023-06-25T15:28:22.252820
| 2021-07-23T14:21:40
| 2021-07-23T14:21:40
| 388,820,896
| 0
| 0
|
MIT
| 2021-07-23T14:03:07
| 2021-07-23T14:03:06
| null |
UTF-8
|
Python
| false
| false
| 2,955
|
py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Cisco Systems
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: telemetry_info
short_description: Information module for Telemetry Info
description:
- Get all Telemetry Info.
- Get Telemetry Info by id.
version_added: '1.0.0'
author: Rafael Campos (@racampos)
options:
id:
description:
- Id path parameter.
type: str
page:
description:
- Page query parameter. Page number.
type: int
size:
description:
- Size query parameter. Number of objects returned per page.
type: int
filter:
description:
- >
Filter query parameter. <br/> **Simple filtering** should be available through the filter query string
parameter. The structure of a filter is a triplet of field operator and value separated with dots. More than
one filter can be sent. The logical operator common to ALL filter criteria will be by default AND, and can
be changed by using the "filterType=or" query string parameter. Each resource Data model description should
specify if an attribute is a filtered field. <br/> Operator | Description <br/>
------------|----------------- <br/> EQ | Equals <br/> NEQ | Not Equals <br/> GT | Greater Than <br/> LT |
Less Then <br/> STARTSW | Starts With <br/> NSTARTSW | Not Starts With <br/> ENDSW | Ends With <br/> NENDSW
| Not Ends With <br/> CONTAINS | Contains <br/> NCONTAINS | Not Contains <br/>.
type: list
filterType:
description:
- >
FilterType query parameter. The logical operator common to ALL filter criteria will be by default AND, and
can be changed by using the parameter.
type: str
requirements:
- ciscoisesdk
seealso:
# Reference by Internet resource
- name: Telemetry Info reference
description: Complete reference of the Telemetry Info object model.
link: https://ciscoisesdk.readthedocs.io/en/latest/api/api.html#v3-0-0-summary
"""
EXAMPLES = r"""
- name: Get all Telemetry Info
cisco.ise.telemetry_info:
ise_hostname: "{{ise_hostname}}"
ise_username: "{{ise_username}}"
ise_password: "{{ise_password}}"
ise_verify: "{{ise_verify}}"
page: 1
size: 20
filter: []
filterType: AND
register: result
- name: Get Telemetry Info by id
cisco.ise.telemetry_info:
ise_hostname: "{{ise_hostname}}"
ise_username: "{{ise_username}}"
ise_password: "{{ise_password}}"
ise_verify: "{{ise_verify}}"
id: string
register: result
"""
RETURN = r"""
ise_response:
description: A dictionary or list with the response returned by the Cisco ISE Python SDK
returned: always
type: dict
sample: >
{
"id": "string",
"status": "string",
"deploymentId": "string",
"udiSN": "string",
"link": {
"rel": "string",
"href": "string",
"type": "string"
}
}
"""
|
[
"wastorga@altus.co.cr"
] |
wastorga@altus.co.cr
|
d4c171602f31cd1882324afc4197bdd92fee1638
|
ee4f7d4a0d81e902520b339dd77e5960014fa339
|
/migrations/versions/bf3e0c0e76b8_.py
|
41ff51012432dcaffd146da5ebd531869980da86
|
[] |
no_license
|
davejonesbkk/flask_by_example
|
96b8865fa9ab31f0887412ef152de221bf7661f3
|
9d9fad6afc85ed4cdbbd2f583029a3c29e2d035f
|
refs/heads/master
| 2016-09-12T20:56:51.007430
| 2016-05-08T04:39:56
| 2016-05-08T04:39:56
| 58,139,690
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 849
|
py
|
"""empty message
Revision ID: bf3e0c0e76b8
Revises: None
Create Date: 2016-05-07 13:52:41.241555
"""
# revision identifiers, used by Alembic.
revision = 'bf3e0c0e76b8'
down_revision = None
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('results',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('url', sa.String(), nullable=True),
sa.Column('result_all', postgresql.JSON(), nullable=True),
sa.Column('result_no_stop_words', postgresql.JSON(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('results')
### end Alembic commands ###
|
[
"davejonesbkk@gmail.com"
] |
davejonesbkk@gmail.com
|
a412918ce5dcec8fee3151308724b448fd5d6002
|
433ca57245fe15afd309323e82f3bdf3287b4831
|
/core/migrations/0008_auto_20160307_2140.py
|
62fda1323eb7db7c7c2c7350624efb31a595440e
|
[] |
no_license
|
greenteamer/ceiling-django
|
db5170faada0f1582c744fa28c638e8671dc2ab9
|
b4a469ae7d2ce6ed36ae51af60633de1fdb43ea4
|
refs/heads/master
| 2020-04-09T19:01:40.273226
| 2018-12-05T14:39:15
| 2018-12-05T14:39:15
| 160,531,789
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,360
|
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-03-07 21:40
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0007_auto_20160307_2129'),
]
operations = [
migrations.CreateModel(
name='Partners',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50, verbose_name='\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435 \u043a\u043e\u043c\u043f\u0430\u043d\u0438\u0438')),
('logo', models.ImageField(blank=True, null=True, upload_to='partners', verbose_name='\u043b\u043e\u0433\u043e\u0442\u0438\u043f \u043a\u043e\u043c\u043f\u0430\u043d\u0438\u0438')),
],
options={
'verbose_name': '\u041f\u0430\u0440\u0442\u043d\u0435\u0440',
'verbose_name_plural': '\u041f\u0430\u0440\u0442\u043d\u0435\u0442\u044b',
},
),
migrations.AlterField(
model_name='review',
name='photo',
field=models.ImageField(blank=True, null=True, upload_to='reviews', verbose_name='\u0424\u043e\u0442\u043e \u043a\u043b\u0438\u0435\u043d\u0442\u0430'),
),
]
|
[
"greenteamer@bk.ru"
] |
greenteamer@bk.ru
|
b5b8943bbb5130ddcfdefa25858db25f6cc56290
|
1166cad08dd1b57ce5a48721fac9c3c58426c431
|
/pyBlackScholesAnalytics/example_options_IV.py
|
76e281499403f56f0972f935f50a534b04a368c3
|
[] |
no_license
|
gabrielepompa88/IT-For-Business-And-Finance-2019-20
|
411956bc1999b1bc3a83494ac23e5d32cb6bf263
|
7c0ecab93a13ebcd62de0d00615320fee0af6bb4
|
refs/heads/master
| 2021-07-16T09:49:41.808308
| 2021-03-07T12:35:37
| 2021-03-07T12:35:37
| 241,672,404
| 6
| 6
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,627
|
py
|
"""
Created by: Gabriele Pompa (gabriele.pompa@gmail.com)
File: example_options_IV.py
Created on Tue Jul 14 2020 - Version: 1.0
Description:
This script shows usage of PlainVanillaOption and DigitalOption classes to
compute of Black-Scholes implied volatility surfaces for plain-vanilla and
digital option contracts.
"""
import numpy as np
import pandas as pd
import warnings
from market.market import MarketEnvironment
from options.options import PlainVanillaOption, DigitalOption
warnings.filterwarnings("ignore")
def option_factory(mkt_env, plain_or_digital, option_type):
option_dispatcher = {
"plain_vanilla": {"call": PlainVanillaOption(mkt_env),
"put": PlainVanillaOption(mkt_env, option_type="put")
},
"digital": {"call": DigitalOption(mkt_env),
"put": DigitalOption(mkt_env, option_type="put")
}
}
return option_dispatcher[plain_or_digital][option_type]
def main():
#
# Black-Scholes implied volatility calculation with user-defined 'sigma'
# parameter surface, used to evaluate the quality of the implied volatility
# calculation.
#
# output format: pd.DataFrame
np_output = False
# default market environment
market_env = MarketEnvironment()
print(market_env)
# define option style and type
opt_style = "plain_vanilla" # "digital"
opt_type = "call" # "call" # "put"
option = option_factory(market_env, opt_style, opt_type)
print(option)
# K
K_vector = [50, 75, 100, 125, 150]
# tau: a date-range of 5 valuation dates between t and T-10d
n = 6
valuation_date = option.get_t()
expiration_date = option.get_T()
t_vector = pd.date_range(start=valuation_date,
end=expiration_date-pd.Timedelta(days=25),
periods=n)
# sigma (qualitatively reproducing the smile)
k, tau = np.meshgrid(K_vector, option.time_to_maturity(t=t_vector))
sigma_grid_K = 0.01 + ((k - 100)**2)/(100*k)/tau
# pricing parameters
param_dict = {"S": 100,
"K": K_vector,
"t": t_vector,
"sigma": sigma_grid_K,
"r": 0.01,
"np_output": np_output}
print("Parameters:")
print("S: {}".format(param_dict["S"]))
print("K: {}".format(param_dict["K"]))
print("t: {}".format(param_dict["t"]))
print("sigma: \n{}".format(param_dict["sigma"]))
print("r: {}\n".format(param_dict["r"]))
# expected implied volatility: is the 'sigma' parameter with which the
# target price has been generated
expected_IV = pd.DataFrame(data=param_dict["sigma"],
columns=K_vector,
index=t_vector)
expected_IV.rename_axis('K', axis = 'columns', inplace=True)
expected_IV.rename_axis('t', axis = 'rows', inplace=True)
print("\nExpected Kxt Implied volatiltiy Surface: \n", expected_IV)
#
# Without target_price in input: param_dict['sigma'] parameter is
# used to construct target price, used in minimization
#
print("\n--- WITHOUT target_price in input ---\n")
# newton method
param_dict["minimization_method"] = "Newton"
newton_IV = option.implied_volatility(**param_dict)
RMSE_newton = np.sqrt(np.nanmean((newton_IV - expected_IV)**2))
RMSRE_newton = np.sqrt(np.nanmean(((newton_IV - expected_IV)/expected_IV)**2))
print("\nImplied Volatility - Newton method - Metrics (NaN excluded): RMSE={:.1E}, RMSRE={:.1E}:\n"\
.format(RMSE_newton, RMSRE_newton), newton_IV)
# Least=Squares method
param_dict["minimization_method"] = "Least-Squares"
ls_IV = option.implied_volatility(**param_dict)
RMSE_ls = np.sqrt(np.nanmean((ls_IV - expected_IV)**2))
RMSRE_ls = np.sqrt(np.nanmean(((ls_IV - expected_IV)/expected_IV)**2))
print("\nImplied Volatility - Least-Squares constrained method - Metrics (NaN excluded): RMSE={:.1E}, RMSRE={:.1E}:\n"\
.format(RMSE_ls, RMSRE_ls), ls_IV)
#
# With target_price in input: target_price, but no param_dict['sigma'],
# is used in minimization.
#
print("\n--- WITH target_price in input ---\n")
# compute target price
target_price = option.price(**param_dict)
print("\nTarget Price in input: \n", target_price)
# Add target_price to parameters dictionary:
param_dict['target_price'] = target_price
# newton method
param_dict["minimization_method"] = "Newton"
newton_IV = option.implied_volatility(**param_dict)
RMSE_newton = np.sqrt(np.nanmean((newton_IV - expected_IV)**2))
RMSRE_newton = np.sqrt(np.nanmean(((newton_IV - expected_IV)/expected_IV)**2))
print("\nImplied Volatility - Newton method - Metrics (NaN excluded): RMSE={:.1E}, RMSRE={:.1E}:\n"\
.format(RMSE_newton, RMSRE_newton), newton_IV)
# Least=Squares method
param_dict["minimization_method"] = "Least-Squares"
ls_IV = option.implied_volatility(**param_dict)
RMSE_ls = np.sqrt(np.nanmean((ls_IV - expected_IV)**2))
RMSRE_ls = np.sqrt(np.nanmean(((ls_IV - expected_IV)/expected_IV)**2))
print("\nImplied Volatility - Least-Squares constrained method - Metrics (NaN excluded): RMSE={:.1E}, RMSRE={:.1E}:\n"\
.format(RMSE_ls, RMSRE_ls), ls_IV)
#----------------------------- usage example ---------------------------------#
if __name__ == "__main__":
main()
|
[
"gabriele.pompa@gmail.com"
] |
gabriele.pompa@gmail.com
|
20837687ebe33143cbbc0a6ecf06987128e7ddcd
|
e5d83ede8521027b05d9b91c43be8cab168610e6
|
/0x0F-python-object_relational_mapping/11-model_state_insert.py
|
3b320438e74aeaf232b7feb9798f734e04f290b2
|
[] |
no_license
|
Danielo814/holbertonschool-higher_level_programming
|
8918c3a6a9c136137761d47c5162b650708dd5cd
|
832b692529198bbee44d2733464aedfe650bff7e
|
refs/heads/master
| 2020-03-28T11:09:00.343055
| 2019-02-22T03:33:54
| 2019-02-22T03:33:54
| 148,181,433
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 658
|
py
|
#!/usr/bin/python3
"""
'11-model_state_insert' module, uses sqlalchemy to list state
objects from a database
"""
if __name__ == '__main__':
from model_state import Base, State
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import sys
engine = create_engine("mysql+mysqldb://{}:{}@localhost/{}"
.format(sys.argv[1], sys.argv[2], sys.argv[3]))
Base.metadata.create_all(bind=engine)
Session = sessionmaker(bind=engine)
session = Session()
state = State(name="Louisiana")
session.add(state)
session.commit()
print("{}".format(state.id))
session.close()
|
[
"211@holbertonschool.com"
] |
211@holbertonschool.com
|
59c36e7a733d2586f940c8d7f2cda193587e2e64
|
321b4ed83b6874eeb512027eaa0b17b0daf3c289
|
/631/631.design-excel-sum-formula.233766026.Accepted.leetcode.py
|
43c751d9a3847fbc50be93236347e9397d60a780
|
[] |
no_license
|
huangyingw/submissions
|
7a610613bdb03f1223cdec5f6ccc4391149ca618
|
bfac1238ecef8b03e54842b852f6fec111abedfa
|
refs/heads/master
| 2023-07-25T09:56:46.814504
| 2023-07-16T07:38:36
| 2023-07-16T07:38:36
| 143,352,065
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,185
|
py
|
class Excel(object):
def _indices(self, r, c):
return [r - 1, ord(c) - ord("A")]
def __init__(self, H, W):
rows, cols = self._indices(H, W)
self.excel = [[0 for _ in range(cols + 1)] for _ in range(rows + 1)]
def set(self, r, c, v):
r, c, = self._indices(r, c)
self.excel[r][c] = v
def get(self, r, c):
r, c = self._indices(r, c)
return self.get_i(r, c)
def get_i(self, r, c):
contents = self.excel[r][c]
if isinstance(contents, int):
return contents
total = 0
for cells in contents:
cell_range = cells.split(":")
r1, c1 = self._indices(int(cell_range[0][1:]), cell_range[0][0])
if len(cell_range) == 1:
r2, c2 = r1, c1
else:
r2, c2 = self._indices(int(cell_range[1][1:]), cell_range[1][0])
for row in range(r1, r2 + 1):
for col in range(c1, c2 + 1):
total += self.get_i(row, col)
return total
def sum(self, r, c, strs):
r, c = self._indices(r, c)
self.excel[r][c] = strs
return self.get_i(r, c)
|
[
"huangyingw@gmail.com"
] |
huangyingw@gmail.com
|
365ceaa7222b7532942e6aad67b9545a9a634088
|
65c3e7139829829dd1410228e17f85c285ab0706
|
/Aniyom Ebenezer/phase 1/python 2 basis/Day_25_Challenge_Solution/Question 5 Solution.py
|
5ceac0d832e2fe6730aa996bf1728961909326a7
|
[
"MIT"
] |
permissive
|
eaniyom/python-challenge-solutions
|
167e9d897d0a72f1e264ff2fed0e4cc5541b0164
|
21f91e06421afe06b472d391429ee2138c918c38
|
refs/heads/master
| 2022-11-24T02:57:39.920755
| 2020-08-05T09:23:04
| 2020-08-05T09:23:04
| 277,686,791
| 1
| 0
|
MIT
| 2020-07-07T01:31:00
| 2020-07-07T01:30:59
| null |
UTF-8
|
Python
| false
| false
| 686
|
py
|
"""
From Wikipedia:
An isogram (also known as a "nonpattern word") is a logological term for a word or phrase without a repeating letter. It is also used by some people to mean a word or phrase in which each letter appears the same number of times, not necessarily just once. Conveniently, the word itself is an isogram in both senses of the word, making it autological.
Write a Python program to check whether a given string is an "isogram" or not.
Sample Output:
False
True
True
False
"""
def check_isogram(str1):
return len(str1) == len(set(str1.lower()))
print(check_isogram("w3resource"))
print(check_isogram("w3r"))
print(check_isogram("Python"))
print(check_isogram("Java"))
|
[
"eaniyom@gmail.com"
] |
eaniyom@gmail.com
|
7a592cdf6a9b54e598ddd17945122d921db69bb3
|
7548c8efccb43b1d8daec719bd7d8ad4a4d03630
|
/Check Completeness of a Binary Tree/Leetcode_958.py
|
0a338ef629921b6783c50f373af6e33940a2e591
|
[] |
no_license
|
arw2019/AlgorithmsDataStructures
|
fdb2d462ded327857d72245721d3c9677ba1617b
|
9164c21ab011c90944f844e3c359093ce6180223
|
refs/heads/master
| 2023-02-17T11:50:07.418705
| 2021-01-19T19:37:17
| 2021-01-19T19:37:17
| 204,222,584
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 492
|
py
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def isCompleteTree(self, root: TreeNode) -> bool:
levelOrder = [root]
i = 0
while levelOrder[i]:
levelOrder.append(levelOrder[i].left)
levelOrder.append(levelOrder[i].right)
i += 1
return not any(levelOrder[i:])
|
[
"noreply@github.com"
] |
arw2019.noreply@github.com
|
743fb306d02fdd8647e4e3fdc698e0da32610bad
|
f13acd0d707ea9ab0d2f2f010717b35adcee142f
|
/upsolve/ABC/abc077/c/main.py
|
0d82c8873315de4343231f2620a0fa633e717d3a
|
[
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] |
permissive
|
KATO-Hiro/AtCoder
|
126b9fe89fa3a7cffcbd1c29d42394e7d02fa7c7
|
bf43320bc1af606bfbd23c610b3432cddd1806b9
|
refs/heads/master
| 2023-08-18T20:06:42.876863
| 2023-08-17T23:45:21
| 2023-08-17T23:45:21
| 121,067,516
| 4
| 0
|
CC0-1.0
| 2023-09-14T21:59:38
| 2018-02-11T00:32:45
|
Python
|
UTF-8
|
Python
| false
| false
| 1,196
|
py
|
# -*- coding: utf-8 -*-
from bisect import bisect_left, bisect_right
from typing import List
def bisect_lt(sorted_array: List[int], value: int):
"""Find the largest element < x and its index, or None if it doesn't exist."""
if sorted_array[0] < value:
index: int = bisect_left(sorted_array, value) - 1
return index, sorted_array[index]
return None, None
def bisect_gt(sorted_array: List[int], value: int):
"""Find the smallest element > x and its index, or None if it doesn't exist."""
if sorted_array[-1] > value:
index: int = bisect_right(sorted_array, value)
return index, sorted_array[index]
return None, None
def main():
import sys
input = sys.stdin.readline
n = int(input())
a = sorted(list(map(int, input().split())))
b = sorted(list(map(int, input().split())))
c = sorted(list(map(int, input().split())))
# bを固定して、aとcを二分探索
ans = 0
for bi in b:
i, _ = bisect_lt(a, bi)
j, _ = bisect_gt(c, bi)
if i is None or j is None:
continue
ans += (i + 1) * (n - j)
print(ans)
if __name__ == "__main__":
main()
|
[
"k.hiro1818@gmail.com"
] |
k.hiro1818@gmail.com
|
78a0851ea9299d16a556f87dd0545a5c9477d748
|
21dfcc44840cb94058bcd014946f2a38fbf30c54
|
/scripts/EmuSo.py
|
d0f8e85d777d129c382cb83107cca556152999c8
|
[
"SGI-B-2.0",
"MIT",
"Libpng",
"BSD-3-Clause",
"LicenseRef-scancode-glut",
"Zlib",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"Unlicense"
] |
permissive
|
nigels-com/regal
|
819a74deeeac00860bcb6f21c3e59ccad1b78448
|
3f1a06d5c098339d30221c9e999640e4c5437a0b
|
refs/heads/master
| 2020-12-14T16:19:29.701418
| 2015-10-18T08:57:48
| 2015-10-18T08:58:56
| 9,986,650
| 2
| 3
| null | 2014-07-12T07:28:49
| 2013-05-10T17:35:20
|
C++
|
UTF-8
|
Python
| false
| false
| 3,670
|
py
|
#!/usr/bin/python -B
soFormulae = {
# TODO
'GenSamplers' : {
'entries' : [ 'glGenSamplers' ],
'impl' : [ '_context->so->GenSamplers( ${arg0plus} );' ],
},
'DeleteSamplers' : {
'entries' : [ 'glDeleteSamplers' ],
'impl' : [ '_context->so->DeleteSamplers( ${arg0plus} );' ],
},
'IsSampler' : {
'entries' : [ 'glIsSampler' ],
'impl' : [ 'return _context->so->IsSampler( ${arg0} );' ],
},
'BindSampler' : {
'entries' : [ 'glBindSampler' ],
'impl' : [ '_context->so->BindSampler( ${arg0plus} );' ],
},
'GetSamplerParameterv' : {
'entries' : [ 'glGetSamplerParameter(I|)(u|)(f|i)v' ],
'impl' : [
'RegalAssert(_context);',
'if ( !_context->so->GetSamplerParameterv( *_context, ${arg0plus} )) {',
' _context->dispatcher.emulation.glGetSamplerParameter${m1}${m2}${m3}v( ${arg0plus} );',
'}',
]
},
'SamplerParameter' : {
'entries' : [ 'glSamplerParameter(I|)(u|)(f|i)(v|)' ],
'impl' : [
'RegalAssert(_context);',
'if ( !_context->so->SamplerParameter${m4}( *_context, ${arg0plus} )) {',
' _context->dispatcher.emulation.glSamplerParameter${m1}${m2}${m3}${m4}( ${arg0plus} );',
'}',
]
},
'ActiveTexture' : {
'entries' : [ 'glActiveTexture(ARB|)' ],
'impl' : [
'RegalAssert(_context);',
'if ( !_context->so->ActiveTexture( *_context, ${arg0plus} ) ) {',
' _context->dispatcher.emulation.glActiveTexture( ${arg0plus} );',
'}',
]
},
'GenTextures' : {
'entries' : [ 'glGenTextures' ],
'impl' : [
'RegalAssert(_context);',
'_context->so->GenTextures( *_context, ${arg0plus} );'
],
},
'DeleteTextures' : {
'entries' : [ 'glDeleteTextures' ],
'prefix' : [
'RegalAssert(_context);',
'_context->so->DeleteTextures( *_context, ${arg0plus} );'
],
},
'BindTexture' : {
'entries' : [ 'glBindTexture' ],
'impl' : [
'RegalAssert(_context);',
'if ( !_context->so->BindTexture( *_context, ${arg0plus} ) ) {',
' _context->dispatcher.emulation.glBindTexture( ${arg0plus} );',
'}',
]
},
'TexParameter' : {
'entries' : [ 'glTexParameter(I|)(u|)(f|i)(v|)(EXT|)' ],
'impl' : [
'RegalAssert(_context);',
'if ( !_context->so->TexParameter${m4}( *_context, ${arg0plus} ) ) {',
' _context->dispatcher.emulation.glTexParameter${m1}${m2}${m3}${m4}( ${arg0plus} );',
'}',
]
},
'GetTexParameterv' : {
'entries' : [ 'glGetTexParameter(I|)(u|)(f|i)v' ],
'impl' : [
'RegalAssert(_context);',
'if ( !_context->so->GetTexParameterv( *_context, ${arg0plus} ) ) {',
' _context->dispatcher.emulation.glGetTexParameter${m1}${m2}${m3}v( ${arg0plus} );',
'}',
]
},
'Get' : {
'entries' : [ 'glGet(Double|Float|Integer|Integer64)v' ],
'impl' : [
'if ( !_context->so->Get( ${arg0plus} ) ) {',
' _context->dispatcher.emulation.glGet${m1}v( ${arg0plus} );',
'}',
]
},
'PreDraw' : {
'entries' : [ 'gl(Multi|)Draw(Range|)(Arrays|Element|Elements)(Instanced|Indirect|BaseVertex|InstancedBaseVertex|Array|)(ARB|EXT|AMD|ATI|APPLE|)' ],
'prefix' : [
'RegalAssert(_context);',
'_context->so->PreDraw( *_context );',
],
},
}
|
[
"nigels@users.sourceforge.net"
] |
nigels@users.sourceforge.net
|
0e2bbbc4a67fd094f67dd7d060888036adf62cba
|
030aef4b13a29246ef21342efea9b26f5620f0b0
|
/code/SWEA/1859_백만장자_프로젝트.py
|
757a273af12d8f69c335f163cf7e6678348557f7
|
[] |
no_license
|
kyeah01/Problem_Solving
|
d70049efb72d09c4ea07a8dba9144d482857b36a
|
efec0486ec07843e085abf4e66cdf694fdde104b
|
refs/heads/master
| 2021-07-03T14:28:56.001123
| 2020-09-23T17:37:42
| 2020-09-23T17:37:42
| 176,175,363
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 308
|
py
|
T = int(input())
for tc in range(1, T+1):
N = int(input())
days = list(map(int, input().split()))
max_index = N-(days[::-1].index(max(days))+1)
ans = 0
# max_index까지 값을 구해야함
for i in range(max_index):
ans += max(days) - days[i]
if ans < 0:
ans = 0
|
[
"kyeah01@gmail.com"
] |
kyeah01@gmail.com
|
570430474d734ea45b7b4bf3c1ec9a6489e26a5b
|
a05716cdf916edb42efdcec4fd10c65bdd043f3d
|
/elasticsearch/_async/client/monitoring.py
|
2f7b570d21a89b3af2d569d08af6dd9e023b1547
|
[
"Apache-2.0"
] |
permissive
|
mesejo/elasticsearch-py
|
0a30e104f3f4e6b2426c1eb01ba51e5d86efab14
|
041a433de263482e306b3855ab67b93c03978966
|
refs/heads/master
| 2022-11-11T11:57:44.792382
| 2020-06-23T18:36:32
| 2020-06-23T18:36:32
| 274,199,907
| 0
| 0
|
Apache-2.0
| 2020-06-22T17:20:49
| 2020-06-22T17:20:49
| null |
UTF-8
|
Python
| false
| false
| 1,494
|
py
|
# Licensed to Elasticsearch B.V under one or more agreements.
# Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information
from .utils import NamespacedClient, query_params, _make_path, SKIP_IN_PATH, _bulk_body
class MonitoringClient(NamespacedClient):
@query_params("interval", "system_api_version", "system_id")
async def bulk(self, body, doc_type=None, params=None, headers=None):
"""
Used by the monitoring features to send monitoring data.
`<https://www.elastic.co/guide/en/elasticsearch/reference/master/monitor-elasticsearch-cluster.html>`_
:arg body: The operation definition and data (action-data
pairs), separated by newlines
:arg doc_type: Default document type for items which don't
provide one
:arg interval: Collection interval (e.g., '10s' or '10000ms') of
the payload
:arg system_api_version: API Version of the monitored system
:arg system_id: Identifier of the monitored system
"""
if body in SKIP_IN_PATH:
raise ValueError("Empty value passed for a required argument 'body'.")
body = _bulk_body(self.transport.serializer, body)
return await self.transport.perform_request(
"POST",
_make_path("_monitoring", doc_type, "bulk"),
params=params,
headers=headers,
body=body,
)
|
[
"sethmichaellarson@gmail.com"
] |
sethmichaellarson@gmail.com
|
4f6e98d736958850f3715a80606ca28c7eabddf4
|
f3b233e5053e28fa95c549017bd75a30456eb50c
|
/tyk2_input/43/43-31_wat_20Abox/set_1ns_equi_m.py
|
eeadbfffcabc77af30b8d082f6dcced30aacc839
|
[] |
no_license
|
AnguseZhang/Input_TI
|
ddf2ed40ff1c0aa24eea3275b83d4d405b50b820
|
50ada0833890be9e261c967d00948f998313cb60
|
refs/heads/master
| 2021-05-25T15:02:38.858785
| 2020-02-18T16:57:04
| 2020-02-18T16:57:04
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 923
|
py
|
import os
dir = '/mnt/scratch/songlin3/run/tyk2/L43/wat_20Abox/ti_one-step/43_31/'
filesdir = dir + 'files/'
temp_equiin = filesdir + 'temp_equi_m.in'
temp_pbs = filesdir + 'temp_1ns_equi_m.pbs'
lambd = [ 0.00922, 0.04794, 0.11505, 0.20634, 0.31608, 0.43738, 0.56262, 0.68392, 0.79366, 0.88495, 0.95206, 0.99078]
for j in lambd:
os.system("rm -r %6.5f" %(j))
os.system("mkdir %6.5f" %(j))
os.chdir("%6.5f" %(j))
os.system("rm *")
workdir = dir + "%6.5f" %(j) + '/'
#equiin
eqin = workdir + "%6.5f_equi_m.in" %(j)
os.system("cp %s %s" %(temp_equiin, eqin))
os.system("sed -i 's/XXX/%6.5f/g' %s" %(j, eqin))
#PBS
pbs = workdir + "%6.5f_1ns_equi.pbs" %(j)
os.system("cp %s %s" %(temp_pbs, pbs))
os.system("sed -i 's/XXX/%6.5f/g' %s" %(j, pbs))
#top
os.system("cp ../43-31_merged.prmtop .")
os.system("cp ../0.5_equi_0_3.rst .")
#submit pbs
os.system("qsub %s" %(pbs))
os.chdir(dir)
|
[
"songlin3@msu.edu"
] |
songlin3@msu.edu
|
44ea4283cb706f70dc5b653285510c61915d9fcb
|
931a3304ea280d0a160acb87e770d353368d7d7d
|
/vendor/swagger_client/models/get_characters_character_id_mail_labels_ok.py
|
c6952fb75c441a4204eea1c255bb24fb9afe18e6
|
[] |
no_license
|
LukeS5310/Broadsword
|
c44786054e1911a96b02bf46fe4bdd0f5ad02f19
|
3ba53d446b382c79253dd3f92c397cca17623155
|
refs/heads/master
| 2021-09-08T00:05:26.296092
| 2017-10-24T07:01:48
| 2017-10-24T07:01:48
| 105,143,152
| 0
| 1
| null | 2017-11-03T14:29:38
| 2017-09-28T12:03:19
|
Python
|
UTF-8
|
Python
| false
| false
| 4,288
|
py
|
# coding: utf-8
"""
EVE Swagger Interface
An OpenAPI for EVE Online
OpenAPI spec version: 0.6.2
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class GetCharactersCharacterIdMailLabelsOk(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, labels=None, total_unread_count=None):
"""
GetCharactersCharacterIdMailLabelsOk - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'labels': 'list[GetCharactersCharacterIdMailLabelsLabel]',
'total_unread_count': 'int'
}
self.attribute_map = {
'labels': 'labels',
'total_unread_count': 'total_unread_count'
}
self._labels = labels
self._total_unread_count = total_unread_count
@property
def labels(self):
"""
Gets the labels of this GetCharactersCharacterIdMailLabelsOk.
labels array
:return: The labels of this GetCharactersCharacterIdMailLabelsOk.
:rtype: list[GetCharactersCharacterIdMailLabelsLabel]
"""
return self._labels
@labels.setter
def labels(self, labels):
"""
Sets the labels of this GetCharactersCharacterIdMailLabelsOk.
labels array
:param labels: The labels of this GetCharactersCharacterIdMailLabelsOk.
:type: list[GetCharactersCharacterIdMailLabelsLabel]
"""
self._labels = labels
@property
def total_unread_count(self):
"""
Gets the total_unread_count of this GetCharactersCharacterIdMailLabelsOk.
total_unread_count integer
:return: The total_unread_count of this GetCharactersCharacterIdMailLabelsOk.
:rtype: int
"""
return self._total_unread_count
@total_unread_count.setter
def total_unread_count(self, total_unread_count):
"""
Sets the total_unread_count of this GetCharactersCharacterIdMailLabelsOk.
total_unread_count integer
:param total_unread_count: The total_unread_count of this GetCharactersCharacterIdMailLabelsOk.
:type: int
"""
if total_unread_count is not None and total_unread_count < 0:
raise ValueError("Invalid value for `total_unread_count`, must be a value greater than or equal to `0`")
self._total_unread_count = total_unread_count
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, GetCharactersCharacterIdMailLabelsOk):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
|
[
"cyberlibertyx@gmail.com"
] |
cyberlibertyx@gmail.com
|
ef3f05716502649f5e7d9ddc4e67ec5912e7270a
|
3851d5eafcc5fd240a06a7d95a925518412cafa0
|
/Django_Code/gs28/gs28/asgi.py
|
e1f1a15c27ff9ec6f8b42b0f1666ea6af01dd283
|
[] |
no_license
|
Ikshansaleem/DjangoandRest
|
c0fafaecde13570ffd1d5f08019e04e1212cc2f3
|
0ccc620ca609b4ab99a9efa650b5893ba65de3c5
|
refs/heads/master
| 2023-01-31T04:37:57.746016
| 2020-12-10T06:27:24
| 2020-12-10T06:27:24
| 320,180,735
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 401
|
py
|
"""
ASGI config for gs28 project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gs28.settings')
application = get_asgi_application()
|
[
"ikshan3108@gmail.com"
] |
ikshan3108@gmail.com
|
56658b1b204f9655fbd8f8276cc516986cabee06
|
3e6dffad73b8d5024024b52b044c57a05e7e9655
|
/assets/2019-11-30/commondb_server.py
|
6b08cb78bef355870da187cefdbe820cdc3509bc
|
[
"MIT"
] |
permissive
|
dhilipsiva/talks
|
07f33b162d8db6e20e3d5974576d71c273629187
|
05581b6b8fdd0598d4ffed4bf75204d718719ed9
|
refs/heads/master
| 2022-08-05T12:27:39.932612
| 2022-07-21T07:43:36
| 2022-07-21T07:43:36
| 68,734,565
| 5
| 3
|
MIT
| 2021-07-30T11:24:12
| 2016-09-20T17:05:44
|
Python
|
UTF-8
|
Python
| false
| false
| 1,022
|
py
|
from concurrent.futures import ThreadPoolExecutor
import grpc
from grpc_opentracing.grpcext import intercept_server
from grpc_opentracing import open_tracing_server_interceptor
from github_pb2 import Reply
from utils import get_config, wait_for_termination
from github_pb2_grpc import CommonDBServicer, add_CommonDBServicer_to_server
class CommonDB(CommonDBServicer):
def GetCommonData(self, request, context):
print(request, context)
return Reply(msg='commondb')
def serve():
config = get_config('commondb-server')
tracer = config.initialize_tracer()
tracer_interceptor = open_tracing_server_interceptor(
tracer, log_payloads=True)
server = grpc.server(ThreadPoolExecutor(max_workers=10))
server = intercept_server(server, tracer_interceptor)
add_CommonDBServicer_to_server(CommonDB(), server)
server.add_insecure_port('[::]:50053')
server.start()
wait_for_termination()
server.stop(0)
tracer.close()
if __name__ == '__main__':
serve()
|
[
"dhilipsiva@pm.me"
] |
dhilipsiva@pm.me
|
678a035115b9bab5ee37b4008fa8b1f71d3795dc
|
91b80ef798cbcdaab7f6ae0be994f5a3b12f1515
|
/198.py
|
155ed9d04a687a65692c489eeaa6c5e9ef28c808
|
[] |
no_license
|
luckkyzhou/leetcode
|
13377565a1cc2c7861601ca5d55f6b83c63d490e
|
43bcf65d31f1b729ac8ca293635f46ffbe03c80b
|
refs/heads/master
| 2021-06-21T11:26:06.114096
| 2021-03-24T21:06:15
| 2021-03-24T21:06:15
| 205,568,339
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 271
|
py
|
from typing import List
class Solution:
def rob(self, nums: List[int]) -> int:
prevMax = 0
curMax = 0
for num in nums:
temp = curMax
curMax = max(prevMax + num, curMax)
prevMax = temp
return curMax
|
[
"luckky_zhou@163.com"
] |
luckky_zhou@163.com
|
10b521f82bc66ef9eca34617899ca120391d14d3
|
00820b522cc16bf996f1ef44a94a2f31989c4065
|
/abc/abc144/c.py
|
6932b9a69d517fcc35addc7fce7e72fb3b8071b0
|
[] |
no_license
|
yamato1992/at_coder
|
6dffd425163a37a04e37507743a15f67b29239fc
|
6e0ec47267ed3cae62aebdd3d149f6191fdcae27
|
refs/heads/master
| 2020-08-31T11:17:03.500616
| 2020-06-12T15:45:58
| 2020-06-12T15:45:58
| 218,678,043
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 200
|
py
|
import math
INF = 1e12
n = int(input())
cnt = INF
m = math.sqrt(n)
for i in range(1, math.ceil(m) + 1):
if n % i == 0:
j = n // i
cnt = min(cnt, i + j - 2)
else:
continue
print(cnt)
|
[
"yamato.mitsui.orleans@gmail.com"
] |
yamato.mitsui.orleans@gmail.com
|
917ee557f9fe287f3752878d2f57f0990122fb69
|
ba0a2b0d2d1534443ea34320675aadfa378457b6
|
/OA/Akuna/QAkuna_Order Marketing.py
|
dbf97a7359f5393adf302b66732ef5fea9e7cc95
|
[] |
no_license
|
Luolingwei/LeetCode
|
73abd58af116f3ec59fd6c76f662beb2a413586c
|
79d4824879d0faed117eee9d99615cd478432a14
|
refs/heads/master
| 2021-08-08T17:45:19.215454
| 2021-06-17T17:03:15
| 2021-06-17T17:03:15
| 152,186,910
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,571
|
py
|
import json
import copy
from collections import defaultdict
# Implement the class below, keeping the constructor's signature unchanged; it should take no arguments.
class Company:
def __init__(self, name):
self.name = name
self.own = 0
self.sell = 0
self.buy = 0
def __eq__(self, other):
return self.name == other.name
def __hash__(self):
return hash(self.name)
def __str__(self):
return self.name
def __repr__(self):
return self.name
class MarkingPositionMonitor:
def __init__(self):
self.companies = {}
self.orders = {}
def on_event(self, message):
event = json.loads(message)
if event["type"] == "NEW":
company_name = event["symbol"]
order_id = event["order_id"]
self.orders[order_id] = event
# create company instance in dict if not exist.
if company_name not in self.companies:
self.companies[company_name] = Company(company_name)
# immediately change the quantity.
if event["side"] == "SELL":
self.companies[company_name].sell += int(event["quantity"])
# new order to buy does not affect marking postion.
if event["side"] == "BUY":
self.companies[company_name].buy += int(event["quantity"])
return self.companies[company_name].own - self.companies[company_name].sell
if event["type"] == "ORDER_REJECT":
# read the history order message detail from order_id
order_id = event["order_id"]
order_detail = self.orders[order_id]
company_name = order_detail["symbol"]
if order_detail["type"] == "NEW":
# immediately change sell quantity
if order_detail["side"] == "SELL":
self.companies[company_name].sell -= int(order_detail["quantity"])
if order_detail["side"] == "BUY":
self.companies[company_name].buy -= int(order_detail["quantity"])
return self.companies[company_name].own - self.companies[company_name].sell
if event["type"] == "ORDER_ACK":
order_id = event["order_id"]
order_detail = self.orders[order_id]
company_name = order_detail["symbol"]
# acknowledge order, no further action need to take though.
if order_detail["side"] == "SELL":
pass
if order_detail["side"] == "BUY":
pass
return self.companies[company_name].own - self.companies[company_name].sell
if event["type"] == "CANCEL":
# try to cancel stated; no immediate effect.
order_id = event["order_id"]
order_detail = self.orders[order_id]
company_name = order_detail["symbol"]
if order_detail["type"] == "NEW":
if order_detail["side"] == "SELL":
pass
if order_detail["side"] == "BUY":
pass
return self.companies[company_name].own - self.companies[company_name].sell
if event["type"] == "CANCEL_ACK":
# cancellation acknowledged; the order is no longer in the market; immediate effect.
order_id = event["order_id"]
order_detail = self.orders[order_id]
company_name = order_detail["symbol"]
if order_detail["type"] == "NEW":
# immediately change the quantity; immediate effect.
if order_detail["side"] == "SELL":
self.companies[company_name].sell -= int(order_detail["quantity"])
if order_detail["side"] == "BUY":
self.companies[company_name].buy -= int(order_detail["quantity"])
return self.companies[company_name].own - self.companies[company_name].sell
if event["type"] == "CANCEL_REJECT":
# reject cancellation; no effect.
order_id = event["order_id"]
order_detail = self.orders[order_id]
company_name = order_detail["symbol"]
if order_detail["type"] == "NEW":
if order_detail["side"] == "SELL":
pass
if order_detail["side"] == "BUY":
pass
return self.companies[company_name].own - self.companies[company_name].sell
if event["type"] == "FILL":
order_id = event["order_id"]
order_detail = self.orders[order_id]
company_name = order_detail["symbol"]
if order_detail["type"] == "NEW":
if "filled_quantity" not in order_detail:
order_detail["filled_quantity"] = 0
if order_detail["side"] == "SELL":
order_detail["filled_quantity"] = event["filled_quantity"]
if order_detail["side"] == "BUY":
self.companies[company_name].own -= order_detail["filled_quantity"] # minus bought quantity from this order
order_detail["filled_quantity"] = event["filled_quantity"]
self.companies[company_name].own += order_detail["filled_quantity"] # add current bought quantity from this order
return self.companies[company_name].own - self.companies[company_name].sell
return 0 # return 0 for not handled operations
def assertEqual(a, b):
if a != b:
print("False! ", a, b)
else:
print(a)
|
[
"564258080@qq.com"
] |
564258080@qq.com
|
7c4624679b56a92e566f8525561a6d268d4791f7
|
e0b81ac782cb6b5b96f49914ac5707971d31d5b4
|
/week14/todo_list/main/urls.py
|
0f9b60b7a5903820284a2eb17db67cb3f931aec3
|
[] |
no_license
|
balnur00/djangoSpring2020
|
33ba23472715aa143e2a9b1ff785730c2778a1fd
|
ca3500875a339601a44dc105bc946d72e4d143eb
|
refs/heads/master
| 2021-09-29T05:44:34.941331
| 2020-04-21T10:26:29
| 2020-04-21T10:26:29
| 237,578,070
| 0
| 0
| null | 2021-09-22T19:45:38
| 2020-02-01T07:19:09
|
Python
|
UTF-8
|
Python
| false
| false
| 692
|
py
|
from rest_framework.routers import DefaultRouter
from django.urls import path
from main import viewsets
from .views import BusTaskListApiView, BusTaskListDetailApiView, BusTaskApiView, BusTaskDetailApiView, ReceiverApiView
urlpatterns = [
path('business/', BusTaskListApiView.as_view()),
path('business/<int:pk>/', BusTaskListDetailApiView.as_view()),
path('business/<int:pk>/tasks/', BusTaskApiView.as_view()),
path('business/<int:pk2>/tasks/<int:pk>/', BusTaskDetailApiView.as_view()),
path('receiver/', ReceiverApiView.as_view()),
]
router = DefaultRouter()
router.register(r'lists', viewsets.PersonalTaskListViewSet, basename='lists')
urlpatterns += router.urls
|
[
"balnur00@mail.ru"
] |
balnur00@mail.ru
|
76c2be24cd3471acd4c320fa2ff5671d516aa254
|
49ba5356bdc5df7dd9803b56fe507c5164a90716
|
/unique-number-of-occurrences/solution.py
|
8947b64feeaba863e1fa0f2965c3530126347f56
|
[] |
no_license
|
uxlsl/leetcode_practice
|
d80ad481c9d8ee71cce0f3c66e98446ced149635
|
d8ed762d1005975f0de4f07760c9671195621c88
|
refs/heads/master
| 2021-04-25T18:12:28.136504
| 2020-03-11T07:54:15
| 2020-03-11T07:54:15
| 121,472,384
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 321
|
py
|
class Solution(object):
def uniqueOccurrences(self, arr):
"""
:type arr: List[int]
:rtype: bool
"""
m = {}
for i in arr:
if i in m:
m[i] += 1
else:
m[i] = 1
return len(m.values()) == len(set(m.values()))
|
[
"linsl2018@163.com"
] |
linsl2018@163.com
|
c7473e0b86b77ea6781aa54b3063668f7f9695b3
|
846c067f53006d18caa467997b2143ae4df50519
|
/config/config.py
|
efbc2a7e2fd6de4de26c10e551251379b239c5c8
|
[] |
no_license
|
radusuciu/dancealytics
|
7e791d9732c8a19f3b6df2f61bb2837360cf4c65
|
7246ab8a32f2b7cbf7a42e08605e58c4a61b8a38
|
refs/heads/master
| 2022-12-13T23:12:54.065740
| 2017-07-14T02:21:49
| 2017-07-14T02:21:49
| 97,040,963
| 0
| 0
| null | 2022-12-08T00:01:27
| 2017-07-12T18:38:53
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 1,377
|
py
|
"""Main configuration file for project."""
import yaml
import os
import pathlib
PROJECT_NAME = 'dancealytics'
PROJECT_HOME_PATH = pathlib.Path(os.path.realpath(__file__)).parents[1]
# debug is true by default
DEBUG = bool(os.getenv('DEBUG', True))
_secrets_path = PROJECT_HOME_PATH.joinpath('config', 'secrets.yml')
_override_path = PROJECT_HOME_PATH.joinpath('config', 'secrets.override.yml')
# get our secrets
with _secrets_path.open() as f:
_SECRETS = yaml.load(f)
# provide a mechanism for overriding some secrets
if _override_path.is_file():
with _override_path.open() as f:
_SECRETS.update(yaml.load(f))
class _Config(object):
"""Holds flask configuration to be consumed by Flask's from_object method."""
# SQLAlchemy
SQLALCHEMY_DATABASE_URI = 'sqlite:////{}/dancealytics.db'.format(str(PROJECT_HOME_PATH))
SQLALCHEMY_TRACK_MODIFICATIONS = False
# Flask
DEBUG = False
SECRET_KEY = _SECRETS['flask']['SECRET_KEY']
JSONIFY_PRETTYPRINT_REGULAR = False
# External APIs
SPOTIFY_CLIENT_ID = _SECRETS['spotify']['CLIENT_ID']
SPOTIFY_CLIENT_SECRET = _SECRETS['spotify']['CLIENT_SECRET']
SPOTIFY_REDIRECT_URI = _SECRETS['spotify']['REDIRECT_URI']
class _DevelopmentConfig(_Config):
"""Configuration for development environment."""
DEBUG = True
config = _DevelopmentConfig if DEBUG else _Config
|
[
"radusuciu@gmail.com"
] |
radusuciu@gmail.com
|
cec3a985e7ce8c9aa91b159664568dd89362fb14
|
ab621c65fc91f5194c4032d68e750efaa5f85682
|
/docline_sequence/models/sale.py
|
56ef1d787c8c291ba4c97ac9796b71da170e942c
|
[] |
no_license
|
pabi2/pb2_addons
|
a1ca010002849b125dd89bd3d60a54cd9b9cdeef
|
e8c21082c187f4639373b29a7a0905d069d770f2
|
refs/heads/master
| 2021-06-04T19:38:53.048882
| 2020-11-25T03:18:24
| 2020-11-25T03:18:24
| 95,765,121
| 6
| 15
| null | 2022-10-06T04:28:27
| 2017-06-29T10:08:49
|
Python
|
UTF-8
|
Python
| false
| false
| 874
|
py
|
# -*- coding: utf-8 -*-
from openerp import models, api, SUPERUSER_ID
from .common import DoclineCommon, DoclineCommonSeq
class SaleOrder(DoclineCommon, models.Model):
_inherit = 'sale.order'
@api.multi
@api.constrains('order_line')
def _check_docline_seq(self):
for order in self:
self._compute_docline_seq('sale_order_line',
'order_id', order.id)
return True
class SaleOrderLine(DoclineCommonSeq, models.Model):
_inherit = 'sale.order.line'
def init(self, cr):
""" On module update, recompute all documents """
self.pool.get('sale.order').\
_recompute_all_docline_seq(cr, SUPERUSER_ID,
'sale_order',
'sale_order_line',
'order_id')
|
[
"kittiu@gmail.com"
] |
kittiu@gmail.com
|
5f9bd3f574357e4086032aec7e61d62623341ce2
|
c59b91482ea23003e055688fdbfb409a6b99c8da
|
/qanta/guesser/nn.py
|
c36167748e721fbb6530602b0284bbe0f77a6c37
|
[
"MIT"
] |
permissive
|
nadesai/qb
|
83a3618227e87fef46680fade3a168585aebb889
|
f2dd64499eb66ae409f08eb9f762d4a6b0a7feda
|
refs/heads/master
| 2021-08-24T15:13:23.959664
| 2017-12-08T15:28:33
| 2017-12-08T15:28:33
| 112,909,453
| 0
| 0
| null | 2017-12-03T07:40:36
| 2017-12-03T07:40:35
| null |
UTF-8
|
Python
| false
| false
| 4,823
|
py
|
from typing import Set, Dict, List
import random
import numpy as np
import os
import pickle
from qanta.util.io import safe_open
from qanta.config import conf
from qanta import logging
log = logging.get(__name__)
def create_embeddings(vocab: Set[str], expand_glove=False, mask_zero=False):
"""
Create embeddings
:param vocab: words in the vocabulary
:param expand_glove: Whether or not to expand embeddings past pre-trained ones
:param mask_zero: if True, then 0 is reserved as a sequence length mask (distinct from UNK)
:return:
"""
embeddings = []
embedding_lookup = {}
with open(conf['word_embeddings']) as f:
i = 0
line_number = 0
n_bad_embeddings = 0
if mask_zero:
emb = np.zeros((conf['embedding_dimension']))
embeddings.append(emb)
embedding_lookup['MASK'] = i
i += 1
for l in f:
splits = l.split()
word = splits[0]
if word in vocab:
try:
emb = [float(n) for n in splits[1:]]
except ValueError:
n_bad_embeddings += 1
continue
embeddings.append(emb)
embedding_lookup[word] = i
i += 1
line_number += 1
n_embeddings = i
log.info('Loaded {} embeddings'.format(n_embeddings))
log.info('Encountered {} bad embeddings that were skipped'.format(n_bad_embeddings))
mean_embedding = np.array(embeddings).mean(axis=0)
if expand_glove:
embed_dim = len(embeddings[0])
words_not_in_glove = vocab - set(embedding_lookup.keys())
for w in words_not_in_glove:
emb = np.random.rand(embed_dim) * .08 * 2 - .08
embeddings.append(emb)
embedding_lookup[w] = i
i += 1
log.info('Initialized an additional {} embeddings not in dataset'.format(i - n_embeddings))
log.info('Total number of embeddings: {}'.format(i))
embeddings = np.array(embeddings)
embed_with_unk = np.vstack([embeddings, mean_embedding, mean_embedding])
embedding_lookup['UNK'] = i
embedding_lookup['EOS'] = i + 1
return embed_with_unk, embedding_lookup
def convert_text_to_embeddings_indices(words: List[str], embedding_lookup: Dict[str, int], random_unk_prob=0):
"""
Convert a list of word tokens to embedding indices
:param words:
:param embedding_lookup:
:param mentions:
:return:
"""
w_indices = []
for w in words:
if w in embedding_lookup:
w_indices.append(embedding_lookup[w])
if random_unk_prob > 0 and random.random() < random_unk_prob:
w_indices.append(embedding_lookup['UNK'])
else:
w_indices.append(embedding_lookup['UNK'])
return w_indices
def tf_format(x_data: List[List[int]], max_len: int, zero_index: int):
"""
Pad with elements until it has max_len or shorten it until it has max_len. When padding insert
the zero index so it doesn't contribute anything
:param x_data:
:param max_len:
:param zero_index:
:return:
"""
for i in range(len(x_data)):
row = x_data[i]
while len(row) < max_len:
row.append(zero_index)
x_data[i] = x_data[i][:max_len]
return x_data
def create_load_embeddings_function(we_tmp_target, we_target, logger):
def load_embeddings(vocab=None, root_directory='', expand_glove=True, mask_zero=False):
if os.path.exists(we_tmp_target):
logger.info('Loading word embeddings from tmp cache')
with safe_open(we_tmp_target, 'rb') as f:
return pickle.load(f)
elif os.path.exists(os.path.join(root_directory, we_target)):
logger.info('Loading word embeddings from restored cache')
with safe_open(os.path.join(root_directory, we_target), 'rb') as f:
return pickle.load(f)
else:
if vocab is None:
raise ValueError('To create fresh embeddings a vocab is needed')
with safe_open(we_tmp_target, 'wb') as f:
logger.info('Creating word embeddings and saving to cache')
embed_and_lookup = create_embeddings(vocab, expand_glove=expand_glove, mask_zero=mask_zero)
pickle.dump(embed_and_lookup, f)
return embed_and_lookup
return load_embeddings
def compute_n_classes(labels: List[str]):
return len(set(labels))
def compute_max_len(training_data):
return max([len(' '.join(sentences).split()) for sentences in training_data[0]])
def compute_lengths(x_data):
return np.array([max(1, len(x)) for x in x_data])
|
[
"ski.rodriguez@gmail.com"
] |
ski.rodriguez@gmail.com
|
0c3bfbea643ac9fd23c1c480c171e9ec77ba22e6
|
0191140830e827ddfde9300d5cc5962018a7bac1
|
/celauco/migrations/0001_initial.py
|
9423288d3a9aaa9dec80cbf2469bbfe1324ef34e
|
[] |
no_license
|
NicolleLouis/LouisNicolle
|
d816a60f30d92a9c2bc1b6ef6443c477505bf1bc
|
b99ae034d58afce5670d0b2fb0e5f3ce57bf1449
|
refs/heads/master
| 2023-08-17T20:37:29.024430
| 2021-09-13T14:26:02
| 2021-09-13T14:26:02
| 291,709,252
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 794
|
py
|
# Generated by Django 3.2.4 on 2021-09-11 17:26
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Board',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('turn_number', models.IntegerField(blank=True, null=True)),
('board_string_representation', models.TextField(blank=True, null=True)),
('number_infected', models.IntegerField(blank=True, null=True)),
('number_healthy', models.IntegerField(blank=True, null=True)),
('number_immune', models.IntegerField(blank=True, null=True)),
],
),
]
|
[
"louisxnicolle@gmail.com"
] |
louisxnicolle@gmail.com
|
391053f155a0c7fe44b5bdddb2c4f93f2fa2dd38
|
1c91439673c898c2219ee63750ea05ff847faee1
|
/configs/vision_transformer/vit-large-p16_ft-64xb64_in1k-384.py
|
5be99188bfe0fbbce2de927c9d9c55ed74131d2f
|
[
"Apache-2.0"
] |
permissive
|
ChenhongyiYang/GPViT
|
d7ba7f00d5139a989a999664ab0874c5c9d53d4d
|
2b8882b2da41d4e175fe49a33fcefad1423216f4
|
refs/heads/main
| 2023-06-08T00:10:07.319078
| 2023-05-26T15:52:54
| 2023-05-26T15:52:54
| 577,075,781
| 78
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,140
|
py
|
_base_ = [
'../_base_/models/vit-large-p16.py',
'../_base_/datasets/imagenet_bs64_pil_resize_autoaug.py',
'../_base_/schedules/imagenet_bs4096_AdamW.py',
'../_base_/default_runtime.py'
]
model = dict(backbone=dict(img_size=384))
img_norm_cfg = dict(
mean=[127.5, 127.5, 127.5], std=[127.5, 127.5, 127.5], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='RandomResizedCrop', size=384, backend='pillow'),
dict(type='RandomFlip', flip_prob=0.5, direction='horizontal'),
dict(type='Normalize', **img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(type='ToTensor', keys=['gt_label']),
dict(type='Collect', keys=['img', 'gt_label'])
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='Resize', size=(384, -1), backend='pillow'),
dict(type='CenterCrop', crop_size=384),
dict(type='Normalize', **img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img'])
]
data = dict(
train=dict(pipeline=train_pipeline),
val=dict(pipeline=test_pipeline),
test=dict(pipeline=test_pipeline),
)
|
[
"chenhongyiyang@Chenhongyis-MacBook-Pro.local"
] |
chenhongyiyang@Chenhongyis-MacBook-Pro.local
|
fc60af11b3d368c537f0f4df6d74171c61349d76
|
364edc98a05ddecf5ad7b7614d2a35a95d19705b
|
/rxpy/subject.py
|
02dcecc1bc9be7f5921fc1486dee19a05d51b19c
|
[] |
no_license
|
as950118/outsource
|
f7f10b5ba62487da8ccddd894aaedc8af48e9d50
|
05a9f654aa222f4da4ce9c4902dde094c9d158d0
|
refs/heads/master
| 2022-12-21T00:18:45.405708
| 2020-02-03T15:53:16
| 2020-02-03T15:53:16
| 193,331,277
| 0
| 0
| null | 2022-12-06T22:38:00
| 2019-06-23T09:50:33
|
HTML
|
UTF-8
|
Python
| false
| false
| 401
|
py
|
from rx import Observable, Observer
from rx.subjects import Subject
class PrintObserver(Observer):
def on_next(self, value):
print("Value :", value)
def on_error(self, error):
print("Error :", error)
def on_completed(self):
print("Completed")
subject = Subject()
subject.subscribe(PrintObserver())
for i in range(10):
subject.on_next(i)
subject.on_completed()
|
[
"na_qa@icloud.com"
] |
na_qa@icloud.com
|
a76cca19fa4d0bfcf0f465ae0c1bec1dce41ed75
|
c824722d02a36f888f74bf60455361a2a1fe5212
|
/rnacentral_pipeline/rnacentral/genes/methods/singletons.py
|
23f128344be241778a004c7535b3cea245c45a8c
|
[
"GPL-1.0-or-later",
"Apache-2.0",
"Artistic-1.0-Perl",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
RNAcentral/rnacentral-import-pipeline
|
d1b52291fc083470d75cf400b10792e1613662db
|
4505f748f9a932ffe4663c16b6c81574e4c04178
|
refs/heads/master
| 2023-08-31T23:37:29.744476
| 2023-04-11T11:10:48
| 2023-04-11T11:10:48
| 29,351,993
| 5
| 0
|
Apache-2.0
| 2023-07-12T13:58:10
| 2015-01-16T14:34:15
|
Python
|
UTF-8
|
Python
| false
| false
| 1,074
|
py
|
# -*- coding: utf-8 -*-
"""
Copyright [2009-2021] EMBL-European Bioinformatics Institute
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 logging
from rnacentral_pipeline.rnacentral.genes.data import State, LocationInfo, Context
from .common_filter import filter
LOGGER = logging.getLogger(__name__)
class SingletonMethod:
def handle_location(self, state: State, context: Context, location: LocationInfo):
if filter(state, context, location):
return
LOGGER.debug("Adding singleton cluster of %s", location.id)
state.add_singleton_cluster(location)
|
[
"bsweeney@ebi.ac.uk"
] |
bsweeney@ebi.ac.uk
|
ec68fcbdad6e89265b1e12e9341ad203211a2bb2
|
283bbf2ce575ea72010e9823907285b08d20fce4
|
/breathecode/services/slack/commands/cohort.py
|
2836ed2bf671bb37af7aab2ef7b781a00670daf5
|
[] |
no_license
|
AnMora/apiv2
|
c084ffcb4ff5b7a0a01dac8fca26f4f4c37aad97
|
fa3b3f0ce4a069facdecd18e133c7b4222a0004a
|
refs/heads/master
| 2023-05-19T23:00:34.257230
| 2021-06-08T21:17:56
| 2021-06-08T21:17:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,379
|
py
|
import os
from breathecode.admissions.models import Cohort, CohortUser
from ..decorator import command
from ..utils import to_string
"""
Possible parameters for this command:
- users: Array of user slack_ids mentioned inside the slack command text content
- user_id: Slack user ID of the message author
- team_id: Slack team_id where the message was posted
- channel_id: Slack channel_id where the message was posted
- text: Content of the slack channel
"""
@command(only='staff')
def execute(channel_id, **context):
response = {
"blocks": []
}
response["blocks"].append(render_cohort(channel_id=channel_id))
return response
def render_cohort(channel_id):
cohort = Cohort.objects.filter(slackchannel__slack_id=channel_id).first()
if cohort is None:
raise Exception(f"Cohort was not found as slack channel, make sure the channel name matches the cohort slug")
teachers = CohortUser.objects.filter(cohort=cohort, role__in=['TEACHER','ASSISTANT'])
return {
"type": "section",
"text": {
"type": "mrkdwn",
"text": f"""
*Cohort name:* {cohort.name}
*Start Date*: {cohort.kickoff_date}
*End Date*: {cohort.ending_date}
*Current day:*: {cohort.current_day}
*Stage:* {cohort.stage}
*Teachers:* {', '.join([cu.user.first_name + ' ' + cu.user.last_name for cu in teachers])}
"""
}
}
|
[
"aalejo@gmail.com"
] |
aalejo@gmail.com
|
c435f6f9e7b20dc1af9c920cba94abff9c3cc1da
|
799fee946fa3f4773cb1340bb36af5b465fdc570
|
/tests/test_models/test_body_models/test_utils.py
|
98127bf148f16a4805906a814f7a689e4be4c29c
|
[
"Apache-2.0"
] |
permissive
|
open-mmlab/mmhuman3d
|
8c534d3c252f68f2d14d3e67fe67bfbccadfad36
|
9431addec32f7fbeffa1786927a854c0ab79d9ea
|
refs/heads/main
| 2023-08-31T13:30:59.894842
| 2023-07-10T02:32:20
| 2023-07-10T02:32:20
| 432,877,190
| 966
| 139
|
Apache-2.0
| 2023-08-31T08:49:16
| 2021-11-29T02:10:31
|
Python
|
UTF-8
|
Python
| false
| false
| 4,440
|
py
|
import torch
from mmhuman3d.models.body_models.builder import build_body_model
from mmhuman3d.models.body_models.utils import (
batch_transform_to_camera_frame,
transform_to_camera_frame,
)
from mmhuman3d.utils.transforms import ee_to_rotmat
def test_transform_to_camera_frame():
# initialize body model
body_model = build_body_model(
dict(
type='SMPL',
keypoint_src='smpl_45',
keypoint_dst='smpl_45',
model_path='data/body_models/smpl',
))
# generate random values
random_transl = torch.rand((1, 3))
random_rotation = torch.rand((1, 3))
random_rotmat = ee_to_rotmat(random_rotation)
random_extrinsic = torch.eye(4)
random_extrinsic[:3, :3] = random_rotmat
random_extrinsic[:3, 3] = random_transl
random_global_orient = torch.rand((1, 3))
random_body_pose = torch.rand((1, 69))
random_transl = torch.rand((1, 3))
random_betas = torch.rand((1, 10))
random_output = body_model(
global_orient=random_global_orient,
body_pose=random_body_pose,
transl=random_transl,
betas=random_betas)
random_joints = random_output['joints']
random_pelvis = random_joints[:, 0, :]
# transform params
transformed_global_orient, transformed_transl = \
transform_to_camera_frame(
global_orient=random_global_orient.numpy().squeeze(), # (3, )
transl=random_transl.numpy().squeeze(), # (3, )
pelvis=random_pelvis.numpy().squeeze(), # (3, )
extrinsic=random_extrinsic.numpy().squeeze() # (4, 4)
)
transformed_output = body_model(
global_orient=torch.tensor(transformed_global_orient.reshape(1, 3)),
transl=torch.tensor(transformed_transl.reshape(1, 3)),
body_pose=random_body_pose,
betas=random_betas)
transformed_joints = transformed_output['joints']
# check validity
random_joints = random_joints.squeeze() # (45, 3)
random_joints = torch.cat([random_joints, torch.ones(45, 1)],
dim=1) # (45, 4)
test_joints = torch.einsum('ij,kj->ki', random_extrinsic,
random_joints) # (45, 4)
test_joints = test_joints[:, :3] # (45, 3)
assert torch.allclose(transformed_joints, test_joints, atol=1e-6)
def test_batch_transform_to_camera_frame():
# batch size
N = 2
# initialize body model
body_model = build_body_model(
dict(
type='SMPL',
keypoint_src='smpl_45',
keypoint_dst='smpl_45',
model_path='data/body_models/smpl',
))
# generate random values
random_transl = torch.rand((1, 3))
random_rotation = torch.rand((1, 3))
random_rotmat = ee_to_rotmat(random_rotation)
random_extrinsic = torch.eye(4)
random_extrinsic[:3, :3] = random_rotmat
random_extrinsic[:3, 3] = random_transl
random_global_orient = torch.rand((N, 3))
random_body_pose = torch.rand((N, 69))
random_transl = torch.rand((N, 3))
random_betas = torch.rand((N, 10))
random_output = body_model(
global_orient=random_global_orient,
body_pose=random_body_pose,
transl=random_transl,
betas=random_betas)
random_joints = random_output['joints']
random_pelvis = random_joints[:, 0, :]
# transform params
transformed_global_orient, transformed_transl = \
batch_transform_to_camera_frame(
global_orient=random_global_orient.numpy(), # (N, 3)
transl=random_transl.numpy(), # (N, 3)
pelvis=random_pelvis.numpy(), # (N, 3)
extrinsic=random_extrinsic.numpy() # (4, 4)
)
transformed_output = body_model(
global_orient=torch.tensor(transformed_global_orient.reshape(N, 3)),
transl=torch.tensor(transformed_transl.reshape(N, 3)),
body_pose=random_body_pose,
betas=random_betas)
transformed_joints = transformed_output['joints']
# check validity
random_joints = random_joints # (N, 45, 3)
random_joints = torch.cat(
[random_joints, torch.ones(N, 45, 1)], dim=2) # (N, 45, 4)
test_joints = torch.einsum('ij,bkj->bki', random_extrinsic,
random_joints) # (N, 45, 4)
test_joints = test_joints[:, :, :3] # (N, 45, 3)
assert torch.allclose(transformed_joints, test_joints, atol=1e-6)
|
[
"noreply@github.com"
] |
open-mmlab.noreply@github.com
|
f6e74ba49764c4245f61beabf3c6737993b74fa6
|
057d662a83ed85897e9906d72ea90fe5903dccc5
|
/.PyCharmCE2019.2/system/python_stubs/-1247971762/gi/_gi/FunctionInfo.py
|
08fe51300b7b7b03f1451dd70de9ae5fb449ad8f
|
[] |
no_license
|
Karishma00/AnsiblePractice
|
19a4980b1f6cca7b251f2cbea3acf9803db6e016
|
932558d48869560a42ba5ba3fb72688696e1868a
|
refs/heads/master
| 2020-08-05T00:05:31.679220
| 2019-10-04T13:07:29
| 2019-10-04T13:07:29
| 212,324,468
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 928
|
py
|
# encoding: utf-8
# module gi._gi
# from /usr/lib/python3/dist-packages/gi/_gi.cpython-37m-x86_64-linux-gnu.so
# by generator 1.147
# no doc
# imports
from gobject import (GBoxed, GEnum, GFlags, GInterface, GParamSpec, GPointer,
GType, Warning)
import gi as __gi
import gobject as __gobject
class FunctionInfo(__gi.CallableInfo):
# no doc
def get_flags(self, *args, **kwargs): # real signature unknown
pass
def get_property(self, *args, **kwargs): # real signature unknown
pass
def get_symbol(self, *args, **kwargs): # real signature unknown
pass
def get_vfunc(self, *args, **kwargs): # real signature unknown
pass
def is_constructor(self, *args, **kwargs): # real signature unknown
pass
def is_method(self, *args, **kwargs): # real signature unknown
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
|
[
"karishma11198@gmail.com"
] |
karishma11198@gmail.com
|
38cd0029c788bca9efbf7774f3d7caafaafcf326
|
a66b7da9b7d04e1fea8669bb736b92f87e49b030
|
/tests/django18_sqlite3_backend/base.py
|
f7efd2e03cbdfa0e9838ed984b10d342fdd24a4d
|
[
"MIT"
] |
permissive
|
zebuline/django-perf-rec
|
5e8e4ff2e690e326618cb4abf9ed25a67c16843b
|
e0bed464976b113df5cb58205a847b3d8e81b27f
|
refs/heads/master
| 2020-04-09T07:38:49.180825
| 2018-12-02T15:41:50
| 2018-12-02T15:41:50
| 152,588,701
| 0
| 0
|
MIT
| 2018-10-11T12:33:25
| 2018-10-11T12:33:44
| null |
UTF-8
|
Python
| false
| false
| 429
|
py
|
# -*- coding:utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from django.db.backends.sqlite3.base import DatabaseWrapper as OrigDatabaseWrapper
from .operations import DatabaseOperations
class DatabaseWrapper(OrigDatabaseWrapper):
def __init__(self, *args, **kwargs):
super(DatabaseWrapper, self).__init__(*args, **kwargs)
self.ops = DatabaseOperations(self)
|
[
"adam@adamj.eu"
] |
adam@adamj.eu
|
3636b76404a69947dae29bd528db4ccab84c8469
|
315450354c6ddeda9269ffa4c96750783963d629
|
/CMSSW_7_0_4/src/TotemRawData/RawToDigi/python/.svn/text-base/ExampleClustering.py.svn-base
|
08efb09d86301e6ce3a10a1cf864bd0d73f76826
|
[] |
no_license
|
elizamelo/CMSTOTEMSim
|
e5928d49edb32cbfeae0aedfcf7bd3131211627e
|
b415e0ff0dad101be5e5de1def59c5894d7ca3e8
|
refs/heads/master
| 2021-05-01T01:31:38.139992
| 2017-09-12T17:07:12
| 2017-09-12T17:07:12
| 76,041,270
| 0
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,113
|
import FWCore.ParameterSet.Config as cms
process = cms.Process("RealDataMonitorXML")
# minimum of logs
#process.load("Configuration.TotemCommon.LoggerMax_cfi")
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(20000)
)
# input of raw data
process.source = cms.Source("RawDataSource",
verbosity = cms.untracked.uint32(1),
eventsToCheck = cms.uint32(6),
skipCorruptedEvents = cms.bool(False),
performChecks = cms.bool(False),
fileNames = cms.vstring('TotemRawData/RawToDigi/python/run_151.vmea')
)
process.o1 = cms.OutputModule("PoolOutputModule",
fileName = cms.untracked.string('file:TotemRawData/RawToDigi/python/run_151_BeforeHit20000.root'),
outputCommands = cms.untracked.vstring('drop TotemRawEvent_*_*_*','keep T2DetIdT2DigiVfatTotemDigiCollection_*_*_*','keep *_*_*T2VfatInformation*_*','keep T1T2Tracks_*_*_*','keep T2Hits_*_*_*','keep T2Roads_*_*_*','keep T2DetIdT2Clustersstdmap_*_*_*','keep T2DetIdT2StripDigiTotemDigiCollection_*_*_*','keep T2DetIdT2PadDigiTotemDigiCollection_*_*_*')
)
#process.dump = cms.EDAnalyzer("EventContentAnalyzer")
#T2GeoMapIP5_4quarter_cmssw.xml
#T2MapIP5_D3_D2_NewFormatBIS.xml
#Load T2 vfat mapping
process.DAQInformationSourceXML = cms.ESSource("DAQInformationSourceXML",
xmlFileName = cms.string('TotemRawData/RawToDigi/python/T2GeoMapIP5_4quarter_vmea_Full.xml')
# xmlFileName = cms.string('TotemRawData/RawToDigi/python/T2GeoMapIP5_4quarter_vmea_cmssw.xml')
)
# outputCommands = cms.untracked.vstring('drop TotemRawEvent_*_*_*')
# Fill T2 digi and vfat object
process.RawToDigi = cms.EDProducer("T2XMLDataDigiProducer",
verbosity = cms.untracked.uint32(10)
)
#process.T2Hits.Cl1MaxPad =20
#process.T2Hits.Cl1MaxStrip =20
#process.T2Hits.IncludeClass0Hits = True
process.load("RecoTotemT1T2.T2MakeCluster.T2MakeCluster_cfi")
#process.p = cms.Path(process.RawToDigi)
process.p = cms.Path(process.RawToDigi*process.T2MCl)
#*process.dqm1 *process.T2Hits*process.T2RoadColl*process.T2TrackColl2
process.outpath = cms.EndPath(process.o1)
|
[
"eliza@cern.ch"
] |
eliza@cern.ch
|
|
95ea081218c6d5f432695b3b8e6be76adf492fb5
|
8ef8e6818c977c26d937d09b46be0d748022ea09
|
/cv/ocr/dbnet/pytorch/dbnet_cv/__init__.py
|
65b6016ceb237276f13baab4fba2ab2a8c266426
|
[
"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
| 373
|
py
|
# Copyright (c) OpenMMLab. All rights reserved.
# flake8: noqa
# from .arraymisc import *
from .fileio import *
from .image import *
from .utils import *
from .version import *
# from .video import *
# from .visualization import *
# The following modules are not imported to this level, so dbnet_cv may be used
# without PyTorch.
# - runner
# - parallel
# - op
# - device
|
[
"yongle.wu@iluvatar.com"
] |
yongle.wu@iluvatar.com
|
9028e75eec7c52e5c1103aa926a2fa0661cfce5a
|
18239524612cf572bfeaa3e001a3f5d1b872690c
|
/clients/keto/python/ory_keto_client/models/ory_access_control_policy_roles.py
|
cff6965d729259b822fa0830da11454472db44ab
|
[
"Apache-2.0"
] |
permissive
|
simoneromano96/sdk
|
2d7af9425dabc30df830a09b26841fb2e8781bf8
|
a6113d0daefbbb803790297e4b242d4c7cbbcb22
|
refs/heads/master
| 2023-05-09T13:50:45.485951
| 2021-05-28T12:18:27
| 2021-05-28T12:18:27
| 371,689,133
| 0
| 0
|
Apache-2.0
| 2021-05-28T12:11:41
| 2021-05-28T12:11:40
| null |
UTF-8
|
Python
| false
| false
| 3,658
|
py
|
# coding: utf-8
"""
ORY Keto
A cloud native access control server providing best-practice patterns (RBAC, ABAC, ACL, AWS IAM Policies, Kubernetes Roles, ...) via REST APIs. # noqa: E501
The version of the OpenAPI document: v0.0.0-alpha.37
Contact: hi@ory.sh
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from ory_keto_client.configuration import Configuration
class OryAccessControlPolicyRoles(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'body': 'list[OryAccessControlPolicyRole]'
}
attribute_map = {
'body': 'Body'
}
def __init__(self, body=None, local_vars_configuration=None): # noqa: E501
"""OryAccessControlPolicyRoles - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._body = None
self.discriminator = None
if body is not None:
self.body = body
@property
def body(self):
"""Gets the body of this OryAccessControlPolicyRoles. # noqa: E501
The request body. in: body type: array # noqa: E501
:return: The body of this OryAccessControlPolicyRoles. # noqa: E501
:rtype: list[OryAccessControlPolicyRole]
"""
return self._body
@body.setter
def body(self, body):
"""Sets the body of this OryAccessControlPolicyRoles.
The request body. in: body type: array # noqa: E501
:param body: The body of this OryAccessControlPolicyRoles. # noqa: E501
:type: list[OryAccessControlPolicyRole]
"""
self._body = body
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.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, OryAccessControlPolicyRoles):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, OryAccessControlPolicyRoles):
return True
return self.to_dict() != other.to_dict()
|
[
"noreply@github.com"
] |
simoneromano96.noreply@github.com
|
3292558238a1c314f6d4aa4e1d50871f9b3a95ab
|
b40d1a26ea04a19ec0da7bf55db84b7ee36cc898
|
/algoexpert.io/python/KMP_Algorithm.py
|
f64b7085b85fe4297668d29e69091911d3e79cbb
|
[
"MIT"
] |
permissive
|
partho-maple/coding-interview-gym
|
5e8af7d404c28d4b9b52e5cffc540fd51d8025cf
|
20ae1a048eddbc9a32c819cf61258e2b57572f05
|
refs/heads/master
| 2022-09-11T16:36:01.702626
| 2022-03-14T08:39:47
| 2022-03-14T08:39:47
| 69,802,909
| 862
| 438
|
MIT
| 2022-08-18T06:42:46
| 2016-10-02T14:51:31
|
Python
|
UTF-8
|
Python
| false
| false
| 660
|
py
|
def knuthMorrisPrattAlgorithm(string, substring):
pattern = buildPattern(substring)
return doesMatch(string, substring, pattern)
def buildPattern(substring):
pattern = [-1 for _ in substring]
j, i = 0, 1
while i < len(substring):
if substring[i] == substring[j]:
pattern[i] = j
i += 1
j += 1
elif j > 0:
j = pattern[j - 1] + 1
else:
i += 1
return pattern
def doesMatch(string, substring, pattern):
i, j = 0, 0
while i + len(substring) - j <= len(string):
if string[i] == substring[j]:
if j == len(substring) - 1:
return True
i += 1
j += 1
elif j > 0:
j = pattern[j - 1] + 1
else:
i += 1
return False
|
[
"partho.biswas@aurea.com"
] |
partho.biswas@aurea.com
|
5c28515d3b5ab34c658293847d5bf7e618fa2754
|
3856c34baa38949498840ba1489c180964cbac6a
|
/Day4/ansiblevault/inheritance.py
|
ee797d43a0128e7af40f3c1a13979701b82f8d59
|
[] |
no_license
|
vinodhmvm/ansibledockertraining
|
ffcb9c459fefe18507f81982e052c1880558715b
|
e28f42b5a09f96fc12f0b3044d617eca80aba154
|
refs/heads/master
| 2020-03-16T22:01:47.512777
| 2018-05-11T10:10:10
| 2018-05-11T10:10:10
| 133,023,943
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,570
|
py
|
class Parent1:
def __init__(self):
print("Paren1 Inside Constructor")
self.__privateData1 = 100
self._protectedData1 = 200
self.publicData1 = 300
def setValues(self, val1, val2, val3):
self.__privateData1 = val1
self._protectedData1 = val2
self.publicData1 = val3
def printValues(self):
print("Value of private data is" + str(self.__privateData1))
print("Value of protected data" + str(self._protectedData1))
print("Value of public data" + str(self.publicData1))
class Parent2:
def __init__(self):
print("Paren2 Inside Constructor")
self.__privateData2 = 400
self._protectedData2 = 500
self.publicData2 = 600
def setValues(self, val1, val2, val3):
self.__privateData2 = val1
self._protectedData2 = val2
self.publicData2 = val3
def printValues(self):
print("Value of private data is" + str(self.__privateData2))
print("Value of protected data" + str(self._protectedData2))
print("Value of public data" + str(self.publicData2))
class Child(Parent1, Parent2):
def __init__(self):
Parent1.__init__(self)
Parent2.__init__(self)
def main():
obj1 = Child()
print("Value of member variables before calling setValus function")
obj1.printValues()
print("Attempt to read public variable directly " ,obj1.publicData1)
print("Attempt to read protected variable directly ", obj1._protectedData2)
#print("Attempt to read private variable directly ", obj1.__privateData)
main()
|
[
"root@localhost.localdomain"
] |
root@localhost.localdomain
|
33207db912f627bcbaa44baf0ad4edf3f56c2638
|
0bda1f543ef3be8cd12a4709d44da95bc68ba507
|
/exs/mundo_3/python/075.py
|
f084fa0ca20c97ee710e02bcaf5c37a615eba6ae
|
[
"MIT"
] |
permissive
|
BearingMe/exercicios-CeV
|
e5a18e897a725cd8a7a86fd0473dc2d66ee39771
|
d65a022041af81a161ae7c98b24a0896e6bb4a5e
|
refs/heads/master
| 2023-04-13T09:51:33.449706
| 2023-03-29T19:51:43
| 2023-03-29T19:51:43
| 519,369,091
| 1
| 0
|
MIT
| 2022-07-29T23:00:45
| 2022-07-29T23:00:45
| null |
UTF-8
|
Python
| false
| false
| 803
|
py
|
"""
Desafio 075
Problema: Desenvolva um programa que leia quatro valores pelo teclado
e guarde-os em uma tupla.
No final, mostre:
A) Quantas vezes apareceu o valor 9;
B) Em que posição foi digitado o primeiro valor 3;
C) Quais foram os números pares.
Resolução do problema:
"""
# Inserindo valores na tupla
valores = tuple(int(input(f'Digite o {cont + 1}º valor: ')) for cont in range(4))
print(f'\nO valor 9 apareceu: {valores.count(9)} vezes')
if valores.count(3) != 0:
print(f'O valor 3 apareceu na {valores.index(3) + 1}º posição')
else:
print('O valor 3 não foi digitado em nenhuma posição')
print('Os valores pares digitados: ', end='')
for numero in valores:
if numero % 2 == 0:
print(numero, end=' ')
|
[
"50463866+matheusfelipeog@users.noreply.github.com"
] |
50463866+matheusfelipeog@users.noreply.github.com
|
3a56ab23accce20fe1187c8bc32ac64f54145555
|
5ecdac376b2f43272910c2429288297c4302b459
|
/65.py
|
cfafb6ab114b86be196304563f0f57c813d73120
|
[] |
no_license
|
higher68/lang_process
|
c8ff7963ea2824e9387a982bf9ec1d28d91b467e
|
8b644b9a6f2ffa65e4358adb6e942c8b234a905f
|
refs/heads/master
| 2020-03-21T08:01:42.432014
| 2018-10-08T14:47:07
| 2018-10-08T14:47:07
| 138,314,719
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,734
|
py
|
##!!!!!!!!!!exercute 64.py and setup testdb!!!!!!!!!!!!!
##!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!11
import json
from pymongo import MongoClient # mongodbへのクエリをだす
from bson.objectid import ObjectId
def support_ObjectId(obj):
'''json.dumps()でObjectIdを処理するための関数
ObjectIdはjsonエンコードできない型なので、文字列型に変換する
戻り値:
ObjectIdから変換した文字列
'''
if isinstance(obj, ObjectId):
return str(obj) # 文字列として扱う
raise TypeError(repr(obj) + " is not JSON serializable")
# MongoDBのデータベースtestdbのコレクションartistにアクセス
client = MongoClient() # mongoclientのインスタンス作成
db = client.testdb # mongodb内のデータベースの一つ、testdbを呼び出している
collection = db.artist # databese内にあるコレクション〜rdbでいうテーブル〜を呼び出す
# rdb:リレーショナルデータベース
# rdbは全てのデータをテーブルというデータ形式で表現
# https://employment.en-japan.com/engineerhub/entry/2017/11/22/110000
# 検索
# collectionはfindで検索可能
# collection.findはcursorオブジェクトを返す
for i, doc in enumerate(collection.find({'name': 'Queen'}), start=1):
# 整形して表示
print('{}件目の内容:\n{}'.format(i,
json.dumps(
doc, indent='\t', ensure_ascii=False,
sort_keys=True, default=support_ObjectId
)
))
# jsonのエンコーダー:json.dumps() 辞書をjson形式の文字列として出力
# 引数を指定して整形可能
# json.load() jsonファイルを辞書として読み込む
|
[
"hatiro7code@gmail.com"
] |
hatiro7code@gmail.com
|
cd400a68fac11c77858bc6409ccc7da10a5332b8
|
b26674cda3264ad16af39333d79a700b72587736
|
/corehq/util/mixin.py
|
4c0450bc10c880dc787cec04f29c0a71f4f55d22
|
[] |
no_license
|
tlwakwella/commcare-hq
|
2835206d8db84ff142f705dbdd171e85579fbf43
|
a3ac7210b77bea6c2d0392df207d191496118872
|
refs/heads/master
| 2021-01-18T02:07:09.268150
| 2016-03-24T14:12:49
| 2016-03-24T14:12:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,058
|
py
|
import uuid
class UUIDGeneratorException(Exception):
pass
class UUIDGeneratorMixin(object):
"""
Automatically generates uuids on __init__ if not generated yet.
To use: Add this mixin to your model as the left-most class being inherited from
and list all field names in UUIDS_TO_GENERATE to generate uuids for.
NOTE: Where possible, a UUIDField should be used instead of this mixin. But
this is needed in cases where migrating a char field to a UUIDField is
not possible because some of the existing uuids don't match the
UUIDField format constraints.
"""
def __init__(self, *args, **kwargs):
super(UUIDGeneratorMixin, self).__init__(*args, **kwargs)
field_names = getattr(self, 'UUIDS_TO_GENERATE', [])
if not field_names:
raise UUIDGeneratorException("Expected UUIDS_TO_GENERATE to not be empty")
for field_name in field_names:
value = getattr(self, field_name)
if not value:
setattr(self, field_name, uuid.uuid4().hex)
|
[
"gcapalbo@dimagi.com"
] |
gcapalbo@dimagi.com
|
57eda055023149e7acd1f892a5d03da7db1cfc98
|
3485ceeca2dcb96e5fc10d353a8ca18a9b0d54af
|
/legacy_examples/exp_concat_visual_bpr.py
|
490764d84236ec822e47259593dedd4492a6dfb8
|
[
"Apache-2.0"
] |
permissive
|
Yuan-T-Xuan/openrec
|
2d82cfa7ee4448744e70aa607d981ddb312f74ee
|
925cff19225874144f839aae30c304df32cc4b1d
|
refs/heads/master
| 2020-03-11T17:46:07.472963
| 2018-10-16T01:53:31
| 2018-10-16T01:53:31
| 116,905,600
| 1
| 0
|
Apache-2.0
| 2018-03-06T00:44:03
| 2018-01-10T03:54:54
|
Python
|
UTF-8
|
Python
| false
| false
| 1,561
|
py
|
import os
import sys
sys.path.append(os.getcwd())
from openrec.legacy import ImplicitModelTrainer
from openrec.legacy.utils import ImplicitDataset
from openrec.legacy.recommenders import ConcatVisualBPR
from openrec.legacy.utils.evaluators import AUC
from openrec.legacy.utils.samplers import PairwiseSampler
from config import sess_config
import dataloader
raw_data = dataloader.load_tradesy()
batch_size = 1000
test_batch_size = 100
item_serving_size = 1000
display_itr = 10000
train_dataset = ImplicitDataset(raw_data['train_data'], raw_data['max_user'], raw_data['max_item'], name='Train')
val_dataset = ImplicitDataset(raw_data['val_data'], raw_data['max_user'], raw_data['max_item'], name='Val')
test_dataset = ImplicitDataset(raw_data['test_data'], raw_data['max_user'], raw_data['max_item'], name='Test')
model = ConcatVisualBPR(batch_size=batch_size, max_user=raw_data['max_user'], max_item=raw_data['max_item'], item_serving_size=item_serving_size,
dim_embed=20, dim_ve=10, item_f_source=raw_data['item_features'], l2_reg=None, sess_config=sess_config)
sampler = PairwiseSampler(batch_size=batch_size, dataset=train_dataset, num_process=5)
model_trainer = ImplicitModelTrainer(batch_size=batch_size, test_batch_size=test_batch_size, item_serving_size=item_serving_size,
train_dataset=train_dataset, model=model, sampler=sampler)
auc_evaluator = AUC()
model_trainer.train(num_itr=int(1e5), display_itr=display_itr, eval_datasets=[val_dataset, test_dataset],
evaluators=[auc_evaluator], num_negatives=1000)
|
[
"ylongqi@gmail.com"
] |
ylongqi@gmail.com
|
dca90dedaf030321cc01173965bf0a98d9e611f8
|
e0980f704a573894350e285f66f4cf390837238e
|
/.history/flex/models_20201029145653.py
|
c271e0bdba6e0a3670289d00d9c26ad51349a930
|
[] |
no_license
|
rucpata/WagtailWebsite
|
28008474ec779d12ef43bceb61827168274a8b61
|
5aa44f51592f49c9a708fc5515ad877c6a29dfd9
|
refs/heads/main
| 2023-02-09T15:30:02.133415
| 2021-01-05T14:55:45
| 2021-01-05T14:55:45
| 303,961,094
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,333
|
py
|
from django.db import models
from wagtail.core.models import Page
from wagtail.core.fields import StreamField
from wagtail.admin.edit_handlers import StreamFieldPanel
from wagtail.snippets.blocks import SnippetChooserBlock
from wagtail.core import blocks as wagtail_blocks
from streams import blocks
from home.models import new_table_options
class FlexPage(Page):
body = StreamField([
('title', blocks.TitleBlock()),
('cards', blocks.CardsBlock()),
('image_and_text', blocks.ImageAndTextBlock()),
('cta', blocks.CallToActionBlock()),
('testimonial', SnippetChooserBlock(
target_model='testimonials.Testimonial',
template = 'streams/testimonial_block.html'
)),
('pricing_table', blocks.PricingTableBlock(
table_options=new_table_options,
)),
('richtext_with_title', blocks.RichTextWithTitleBlock()),
#('richtext', wagtail_blocks.RichTextBlock(
# template = 'streams/simple_richtext_block.html',
# features = ['bold', 'italic', 'ol', 'ul', 'link']
#)),
], null=True, blank=True)
content_panels = Page.content_panels + [
StreamFieldPanel('body'),
]
class Meta:
verbose_name = 'Flex (misc) page'
verbose_name_plural = 'Flex (misc) pages'
|
[
"rucinska.patrycja@gmail.com"
] |
rucinska.patrycja@gmail.com
|
99028d394ffee3ec6127b4af8b4a21e4dac6cbe7
|
a5d0a0499dd069c555080c8cefc2434304afead4
|
/BOJ/2953.py
|
18289777d1ae4372c43d03089f4dc700f78adb42
|
[] |
no_license
|
devjinius/algorithm
|
9bdf9afc021249b188d6930cf9d71f9147325d9f
|
007fa6346a19868fbbc05eefd50848babb5f1cca
|
refs/heads/master
| 2020-05-04T06:08:32.827207
| 2019-07-31T02:39:39
| 2019-07-31T02:39:39
| 178,999,456
| 1
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 962
|
py
|
# 백준알고리즘 2953번
# https://www.acmicpc.net/problem/2953
# 문제
# 각 참가자가 얻은 점수는 다른 사람이 평가해 준 점수의 합이다. 이 쇼의 우승자는 가장 많은 점수를 얻은 사람이 된다.
# 각 참가자가 얻은 평가 점수가 주어졌을 때, 우승자와 그의 점수를 구하는 프로그램을 작성하시오.
# 입력
# 총 다섯 개 줄에 각 참가자가 얻은 네 개의 평가 점수가 공백으로 구분되어 주어진다. 첫 번째 참가자부터 다섯 번째 참가자까지 순서대로 주어진다. 항상 우승자가 유일한 경우만 입력으로 주어진다.
# 출력
# 첫째 줄에 우승자의 번호와 그가 얻은 점수를 출력한다.
# 반환값
# 없음
def solution():
score = []
for _ in range(5):
score.append(sum(map(int, input().split(" "))))
maxScore = max(score)
print(f'{score.index(maxScore)+1} {maxScore}')
solution()
|
[
"eugenekang94@gmail.com"
] |
eugenekang94@gmail.com
|
f129c103ade98b9c151721146c3cefac3efbbb39
|
7c2a976cce8c2b32d644b079c9c5fa3199373491
|
/list_qsort.py
|
e5f38565187224fc079d5e0652fb6f166feab9d3
|
[
"Apache-2.0"
] |
permissive
|
xartisan/Algo
|
f7bbf8627a4cfcc43d952f34482b5691cfd1fbf6
|
6ba61c84f9f111ba6c71ec4d7ce41ee8734d590d
|
refs/heads/master
| 2021-04-12T08:41:32.261209
| 2018-05-17T23:11:31
| 2018-05-17T23:11:31
| 126,271,781
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 700
|
py
|
# quicksort algorithms for linked list
class ListNode:
def __init__(self, val, next=None):
self.val = val
self.next = next
def __repr__(self):
rv = str(self.val)
if self.next:
rv = rv + ' -> ' + repr(self.next)
return rv
def qsort(start, end=None):
if start is end or start.next is end:
return
pivot = start.val
last = start
cur = start.next
# partition
while cur is not end:
if cur.val <= pivot:
last = last.next
cur.val, last.val = last.val, cur.val
cur = cur.next
start.val, last.val = last.val, start.val
qsort(start, last)
qsort(last.next, end)
|
[
"codeartisan@outlook.com"
] |
codeartisan@outlook.com
|
be605463e4ac1976451faca56113a86d84a55e52
|
d66818f4b951943553826a5f64413e90120e1fae
|
/hackerrank/Algorithms/Halloween Sale/test.py
|
833625794fb188739df4943a47e9facfcbea19f1
|
[
"MIT"
] |
permissive
|
HBinhCT/Q-project
|
0f80cd15c9945c43e2e17072416ddb6e4745e7fa
|
19923cbaa3c83c670527899ece5c3ad31bcebe65
|
refs/heads/master
| 2023-08-30T08:59:16.006567
| 2023-08-29T15:30:21
| 2023-08-29T15:30:21
| 247,630,603
| 8
| 1
|
MIT
| 2020-07-22T01:20:23
| 2020-03-16T06:48:02
|
Python
|
UTF-8
|
Python
| false
| false
| 301
|
py
|
import unittest
import solution
class TestQ(unittest.TestCase):
def test_case_0(self):
self.assertEqual(solution.howManyGames(20, 3, 6, 80), 6)
def test_case_1(self):
self.assertEqual(solution.howManyGames(20, 3, 6, 85), 7)
if __name__ == '__main__':
unittest.main()
|
[
"hbinhct@gmail.com"
] |
hbinhct@gmail.com
|
948fd7847c5cd59d02192e55b5ce7af68fdce4c5
|
aa265e03e73f718d4008cfe30ada7ee32c852eec
|
/other/cf_2015_morning_easy_b.py
|
3e3d8ddb67e1f17d63dff6d77afb83b3bb7f17fe
|
[
"MIT"
] |
permissive
|
ryosuke0825/atcoder_python
|
4fb9de9733cd9ef41c2ad9ad38b3f190f49d3ad5
|
52d037d0bc9ef2c721bf2958c1c2ead558cb0cf5
|
refs/heads/master
| 2023-03-11T22:47:56.963089
| 2023-03-05T01:21:06
| 2023-03-05T01:21:06
| 181,768,029
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 168
|
py
|
N = int(input())
S = input()
if N % 2 != 0:
print(-1)
exit(0)
half = N//2
ans = 0
for i in range(half):
if S[i] != S[i+half]:
ans += 1
print(ans)
|
[
"ayakobon@gmail.com"
] |
ayakobon@gmail.com
|
e43f804556ee3049d4fcaffe0a2c595238467584
|
0fa3ad9a3d14c4b7a6cb44833795449d761b3ffd
|
/day08_all/day08/exercise04.py
|
387bae00da3fef78a90100f8c8541ac5fb94018b
|
[] |
no_license
|
dalaAM/month-01
|
3426f08237a895bd9cfac029117c70b50ffcc013
|
e4b4575ab31c2a2962e7c476166b4c3fbf253eab
|
refs/heads/master
| 2022-11-22T23:49:43.037014
| 2020-07-24T07:37:35
| 2020-07-24T07:37:35
| 282,154,216
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 748
|
py
|
"""
参照下列代码,定义函数,计算斤量.
day02/exercise08
# total_weight = int(input("请输入多少两:"))
# number_jin = total_weight // 16
# number_liang = total_weight % 16
# print("结果为:" + str(number_jin) + "斤" + str(number_liang) + "两")
"""
def calculation_weight(total_weight):
"""
计算斤两
:param total_weight:
:return:
"""
number_jin = total_weight // 16
number_liang = total_weight % 16
return number_jin, number_liang
# tuple_result = calculation_weight(100)
# print("结果为:" + str(tuple_result[0]) + "斤" + str(tuple_result[1]) + "两")
jin, liang = calculation_weight(100)
print("结果为:" + str(jin) + "斤" + str(liang) + "两")
|
[
"1105504468@qq.com"
] |
1105504468@qq.com
|
9481bf27e9bd8c47d6a4ad24719e8ac76919e8b2
|
87d5b21265c381104de8f45aa67842a4adc880eb
|
/96. Unique Binary Search Trees.py
|
26dbb55326d8f87010e034de603ebc359adae505
|
[] |
no_license
|
MYMSSENDOG/leetcodes
|
ac047fe0d951e0946740cb75103fc94aae967166
|
8a52a417a903a0742034161471a084bc1e494d68
|
refs/heads/master
| 2020-09-23T16:55:08.579319
| 2020-09-03T19:44:26
| 2020-09-03T19:44:26
| 225,543,895
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 363
|
py
|
from tree_node_lib import *
class Solution:
def numTrees(self, n: int) -> int:
dp = [0]*(n+1)
dp[0] = 1
if n == 0:
return 0
else:
for i in range(1,n+1):
for j in range(i):
dp[i] += dp[j] * dp[i-j-1]
return dp[n]
sol = Solution()
n = 5
print(sol.numTrees(n))
|
[
"fhqmtkfkd@naver.com"
] |
fhqmtkfkd@naver.com
|
60653133ec457b24ba0b502d0d5d416b5464ac9e
|
d807627695b0be66f5b666a0a7292e74b4168af0
|
/tests/server/util.py
|
f0589cc4579dc662a2f1f0aa55977e9451e996a4
|
[] |
no_license
|
evvaletov/balsam
|
fc61c57c09807b2047d9fdc601929137749cb1e3
|
b0c908706ccb7aee2f01cae81da7a64272b29767
|
refs/heads/main
| 2023-08-10T16:39:20.546564
| 2021-09-02T17:35:35
| 2021-09-02T17:35:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,725
|
py
|
from fastapi import status
from fastapi.encoders import jsonable_encoder
class BalsamTestClient:
def __init__(self, client):
self._client = client
@property
def headers(self):
return self._client.headers
def check_stat(self, expect_code, response):
if expect_code is None:
return
if isinstance(expect_code, (list, tuple)):
assert response.status_code in expect_code, response.text
else:
assert response.status_code == expect_code, response.text
def get(self, url, check=status.HTTP_200_OK, **kwargs):
"""GET kwargs become URL query parameters (e.g. /?site=3)"""
response = self._client.get(url, params=kwargs)
self.check_stat(check, response)
return response.json()
def post_form(self, url, check=status.HTTP_201_CREATED, **kwargs):
response = self._client.post(url, data=kwargs)
self.check_stat(check, response)
return response.json()
def post(self, url, check=status.HTTP_201_CREATED, **kwargs):
response = self._client.post(url, json=jsonable_encoder(kwargs))
self.check_stat(check, response)
return response.json()
def bulk_post(self, url, list_data, check=status.HTTP_201_CREATED):
response = self._client.post(url, json=jsonable_encoder(list_data))
self.check_stat(check, response)
return response.json()
def put(self, url, check=status.HTTP_200_OK, **kwargs):
response = self._client.put(url, json=jsonable_encoder(kwargs))
self.check_stat(check, response)
return response.json()
def bulk_put(self, url, payload, check=status.HTTP_200_OK, **kwargs):
response = self._client.put(url, json=payload, params=kwargs)
self.check_stat(check, response)
return response.json()
def patch(self, url, check=status.HTTP_200_OK, **kwargs):
response = self._client.patch(url, json=jsonable_encoder(kwargs))
self.check_stat(check, response)
return response.json()
def bulk_patch(self, url, list_data, check=status.HTTP_200_OK):
response = self._client.patch(url, json=jsonable_encoder(list_data))
self.check_stat(check, response)
return response.json()
def delete(self, url, check=status.HTTP_204_NO_CONTENT):
response = self._client.delete(url)
self.check_stat(check, response)
return response.json()
def bulk_delete(self, url, check=status.HTTP_204_NO_CONTENT, **kwargs):
response = self._client.delete(url, params=kwargs)
self.check_stat(check, response)
return response.json()
def create_site(
client,
hostname="baz",
path="/foo",
transfer_locations={},
check=status.HTTP_201_CREATED,
):
return client.post(
"/sites/",
hostname=hostname,
path=path,
transfer_locations=transfer_locations,
check=check,
)
def create_app(
client,
site_id,
class_path="demo.SayHello",
check=status.HTTP_201_CREATED,
parameters=None,
transfers=None,
):
if parameters is None:
parameters = {
"name": {"required": True},
"N": {"required": False, "default": 1},
}
if transfers is None:
transfers = {
"hello-input": {
"required": False,
"direction": "in",
"local_path": "hello.yml",
"description": "Input file for SayHello",
}
}
return client.post(
"/apps/",
site_id=site_id,
class_path=class_path,
parameters=parameters,
transfers=transfers,
check=check,
)
|
[
"msalim@anl.gov"
] |
msalim@anl.gov
|
cd2e4f6d7aacbf6a2ac1b9a15e8fecf67de1ad0d
|
25ebc03b92df764ff0a6c70c14c2848a49fe1b0b
|
/daily/20170928/example_marshmallow/00extend.py
|
af0aa4d3cf26db1f738db90211a4fc60cc7001be
|
[] |
no_license
|
podhmo/individual-sandbox
|
18db414fafd061568d0d5e993b8f8069867dfcfb
|
cafee43b4cf51a321f4e2c3f9949ac53eece4b15
|
refs/heads/master
| 2023-07-23T07:06:57.944539
| 2023-07-09T11:45:53
| 2023-07-09T11:45:53
| 61,940,197
| 6
| 0
| null | 2022-10-19T05:01:17
| 2016-06-25T11:27:04
|
Python
|
UTF-8
|
Python
| false
| false
| 347
|
py
|
from marshmallow import Schema, fields
class S(Schema):
v = fields.Integer(required=True)
print(S().load({"v": 10}))
print(S().load({"v": 10, "extra": "extra"}))
print("----------------------------------------")
s = S()
s.fields["extra"] = fields.String(required=True)
print(s.load({"v": 10}))
print(s.load({"v": 10, "extra": "extra"}))
|
[
"ababjam61+github@gmail.com"
] |
ababjam61+github@gmail.com
|
4de008b82491430f5dd198909206a566a8046d33
|
3fc01457951a956d62f5e8cc0a8067f6796ee200
|
/misago/threads/views/list.py
|
1c38a3fb6308fac9b4d19fcc80f54dd524234a8b
|
[] |
no_license
|
kinsney/education
|
8bfa00d699a7e84701a8d49af06db22c384e0e8d
|
48f832f17c2df7b64647b3db288abccf65868fe6
|
refs/heads/master
| 2021-05-04T01:15:03.078130
| 2016-12-04T03:18:20
| 2016-12-04T03:18:20
| 71,164,542
| 3
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,752
|
py
|
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import Http404
from django.shortcuts import render
from django.views.generic import View
from ..viewmodels import (
PrivateThreadsCategory, ThreadsCategory, ThreadsRootCategory,
ForumThreads, PrivateThreads)
class ListBase(View):
category = None
threads = None
template_name = None
def get(self, request, list_type=None, **kwargs):
try:
page = int(request.GET.get('page', 0))
except (ValueError, TypeError):
raise Http404()
category = self.get_category(request, **kwargs)
threads = self.get_threads(request, category, list_type, page)
frontend_context = self.get_frontend_context(request, category, threads)
request.frontend_context.update(frontend_context)
template_context = self.get_template_context(request, category, threads)
return render(request, self.template_name, template_context)
def get_category(self, request, **kwargs):
return self.category(request, **kwargs)
def get_threads(self, request, category, list_type, page):
return self.threads(request, category, list_type, page)
def get_frontend_context(self, request, category, threads):
context = self.get_default_frontend_context()
context.update(category.get_frontend_context())
context.update(threads.get_frontend_context())
return context
def get_default_frontend_context(self):
return {}
def get_template_context(self, request, category, threads):
context = self.get_default_template_context()
context.update(category.get_template_context())
context.update(threads.get_template_context())
return context
def get_default_template_context(self):
return {}
class ForumThreads(ListBase):
category = ThreadsRootCategory
threads = ForumThreads
template_name = 'misago/threadslist/threads.html'
def get_default_frontend_context(self):
return {
'THREADS_API': reverse('misago:api:thread-list'),
'MERGE_THREADS_API': reverse('misago:api:thread-merge'),
}
class CategoryThreads(ForumThreads):
category = ThreadsCategory
template_name = 'misago/threadslist/category.html'
def get_category(self, request, **kwargs):
category = super(CategoryThreads, self).get_category(request, **kwargs)
if not category.level:
raise Http404() # disallow root category access
return category
class PrivateThreads(ListBase):
category = PrivateThreadsCategory
threads = PrivateThreads
template_name = 'misago/threadslist/private_threads.html'
|
[
"kinsney@bupt.edu.cn"
] |
kinsney@bupt.edu.cn
|
b63caf64a7adfc33fa4412914bdfd400318a63eb
|
e42a61b7be7ec3412e5cea0ffe9f6e9f34d4bf8d
|
/a10sdk/core/waf/waf_xml_schema.py
|
a6c1a7ac3aab778fc54295f60cf1cc95b76dda52
|
[
"Apache-2.0"
] |
permissive
|
amwelch/a10sdk-python
|
4179565afdc76cdec3601c2715a79479b3225aef
|
3e6d88c65bd1a2bf63917d14be58d782e06814e6
|
refs/heads/master
| 2021-01-20T23:17:07.270210
| 2015-08-13T17:53:23
| 2015-08-13T17:53:23
| 40,673,499
| 0
| 0
| null | 2015-08-13T17:51:35
| 2015-08-13T17:51:34
| null |
UTF-8
|
Python
| false
| false
| 1,289
|
py
|
from a10sdk.common.A10BaseClass import A10BaseClass
class XmlSchema(A10BaseClass):
"""Class Description::
Manage XML-Schema files.
Class xml-schema supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param uuid: {"description": "uuid of the object", "format": "string", "minLength": 1, "modify-not-allowed": 1, "optional": true, "maxLength": 64, "type": "string"}
:param max_filesize: {"description": "Set maximum XML-Schema file size (Maximum file size in KBytes, default is 32K)", "partition-visibility": "shared", "default": 32, "optional": true, "format": "number", "maximum": 256, "minimum": 16, "type": "number"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
URL for this object::
`https://<Hostname|Ip address>//axapi/v3/waf/xml-schema`.
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.required=[]
self.b_key = "xml-schema"
self.a10_url="/axapi/v3/waf/xml-schema"
self.DeviceProxy = ""
self.uuid = ""
self.max_filesize = ""
for keys, value in kwargs.items():
setattr(self,keys, value)
|
[
"doug@parksidesoftware.com"
] |
doug@parksidesoftware.com
|
7063bba9a5ccd6af262eae54a272ea3d37aa2445
|
6ab31b5f3a5f26d4d534abc4b197fe469a68e8e5
|
/tests/beta_tests/test_required_data_2.py
|
48b091de71469858c02437d9e115177357e086c4
|
[
"MIT"
] |
permissive
|
mveselov/CodeWars
|
e4259194bfa018299906f42cd02b8ef4e5ab6caa
|
1eafd1247d60955a5dfb63e4882e8ce86019f43a
|
refs/heads/master
| 2021-06-09T04:17:10.053324
| 2017-01-08T06:36:17
| 2017-01-08T06:36:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,473
|
py
|
import unittest
from katas.beta.required_data_2 import given_nth_value
class RequiredData2TestCase(unittest.TestCase):
def setUp(self):
self.list_1 = [3, 3, -1, 10, 6, 8, -5, 4, 22, 31, 34, -16, -16, 8, 8]
self.list_2 = [3, 3, -1, 10, 6, 8, -5, 'Yes', 4, 22, 31]
self.list_3 = [3, 3, -1, 10, 6, 8, -5, 4, 22, 31]
def test_equals(self):
self.assertEqual(given_nth_value(self.list_1, 5, 'min'), 4)
def test_equals_2(self):
self.assertEqual(given_nth_value(self.list_1, 6, 'max'), 6)
def test_equals_3(self):
self.assertEqual(given_nth_value(self.list_1, 13, 'max'), 'No way')
def test_equals_4(self):
self.assertEqual(given_nth_value(self.list_2, 4, 'max'),
'Invalid entry list')
def test_equals_5(self):
self.assertEqual(given_nth_value([], 4, 'max'),
'No values in the array')
def test_equals_6(self):
self.assertEqual(given_nth_value(self.list_3, 2, 'mix'),
'Valid entries: \'max\' or \'min\'')
def test_equals_7(self):
self.assertEqual(given_nth_value(self.list_3, 2, 'MaX'), 22)
def test_equals_8(self):
self.assertEqual(given_nth_value(self.list_1, -1, 'max'),
'Incorrect value for k')
def test_equals_9(self):
self.assertEqual(given_nth_value(self.list_1, 'string', 2),
'Incorrect value for k')
|
[
"the-zebulan@users.noreply.github.com"
] |
the-zebulan@users.noreply.github.com
|
bd39e76f31f1c24a51b416369db58b831e6dfd68
|
9f13c7be7e88d2486076db0b89a215ab900fea1a
|
/main/apps/core/tests/test_views.py
|
2211728d9e898097fa1eadd09d136514d1880520
|
[] |
no_license
|
truhlik/reimpay
|
534664d2e506f39ec6b0edea471e7cfbad179c3b
|
ac8291dc8a0ac543283ee10aecd32deba24a1641
|
refs/heads/main
| 2023-08-10T16:45:55.283272
| 2021-10-06T19:00:15
| 2021-10-06T19:00:15
| 414,333,776
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,091
|
py
|
import datetime
from django.test import Client
from django.urls import reverse
from django.utils import timezone
from model_bakery import baker
from rest_framework.test import APITestCase
from main.apps.users import constants as user_constatnts
class CoreViewsTestCase(APITestCase):
def setUp(self) -> None:
super(CoreViewsTestCase, self).setUp()
self.c1 = baker.make('companies.Company')
self.c2 = baker.make('companies.Company')
self.user_admin = baker.make('users.User', role=user_constatnts.USER_ROLE_ADMIN, company=self.c1)
self.user_cra = baker.make('users.User', role=user_constatnts.USER_ROLE_CRA, company=self.c1)
self.user_admin_other_company = baker.make('users.User', role=user_constatnts.USER_ROLE_ADMIN, company=self.c2)
self.user_cra_other_company = baker.make('users.User', role=user_constatnts.USER_ROLE_CRA, company=self.c2)
self.study1 = baker.make('studies.Study', company=self.c1)
self.study2 = baker.make('studies.Study', company=self.c1)
self.cb1 = baker.make('credit.CreditBalance', study=self.study1)
self.cb2 = baker.make('credit.CreditBalance', study=self.study2)
self.cb3 = baker.make('credit.CreditBalance')
self.site = baker.make('studies.Site', study=self.study1, cra=self.user_cra)
def do_auth_admin(self):
self.client.force_authenticate(user=self.user_admin)
def do_auth_admin_other_company(self):
self.client.force_authenticate(user=self.user_admin_other_company)
def do_auth_cra(self):
self.client.force_authenticate(user=self.user_cra)
def do_auth_cra_other_company(self):
self.client.force_authenticate(user=self.user_cra_other_company)
# def test_list_only_for_authenticated_failed(self):
# """ Otestuju, že Study endpointy vyžadují přihlášeného uživatele. """
#
# r = self.client.get(reverse('topup-list'))
# self.assertEqual(401, r.status_code)
#
# def test_list_only_for_authenticated_success(self):
# """ Otestuju, že Study endpointy vyžadují přihlášeného uživatele. """
#
# self.do_auth_cra_other_company()
# r = self.client.get(reverse('topup-list'))
# self.assertEqual(200, r.status_code)
def test_retrieve_finance(self):
self.do_auth_admin()
r = self.client.get(reverse('finance-detail', args=(self.study1.id, )))
self.assertEqual(200, r.status_code)
for k in ['actual_balance', 'paid', 'remaining_visits', 'avg_visit_value', 'exp_budget_need']:
self.assertIn(k, r.data.keys())
def test_retrieve_finance_by_cra(self):
self.do_auth_cra()
r = self.client.get(reverse('finance-detail', args=(self.study1.id, )))
self.assertEqual(200, r.status_code)
for k in ['actual_balance', 'paid', 'remaining_visits', 'avg_visit_value', 'exp_budget_need']:
self.assertIn(k, r.data.keys())
def test_doctor_login_view(self):
patient = baker.make('studies.Patient', number='1', site__pin='2')
data = {
'patient_number': 1,
'site_pin': 2,
}
client = Client()
r = client.post(reverse('doctor-login'), data=data)
self.assertEqual(200, r.status_code)
self.assertEqual('/app/#/patient/{}/'.format(patient.id), r.json()['redirect_to'])
session = client.session
dt = datetime.datetime.fromisoformat(session["patients"][str(patient.id)])
self.assertTrue(dt > timezone.now())
def test_retrieve_stats(self):
self.do_auth_admin()
r = self.client.get(reverse('finance-stats', args=(self.study1.id, )))
self.assertEqual(200, r.status_code)
for k in ['stats']:
self.assertIn(k, r.data.keys())
def test_retrieve_stats_by_cra(self):
self.do_auth_cra()
r = self.client.get(reverse('finance-stats', args=(self.study1.id, )))
self.assertEqual(200, r.status_code)
for k in ['stats']:
self.assertIn(k, r.data.keys())
|
[
"lubos@endevel.cz"
] |
lubos@endevel.cz
|
2200eada0e86c8efa83ef9570debe0a0a5d506eb
|
8b9638839818331df2637cf389d38d541c2b94ed
|
/SSWW_fitting/n5_Asimov_Dataset_fitting/n0_Asimov_DatasetMaking.py
|
795663ef59a8f12f9a0f05eedb919b7f3b4d9d2c
|
[] |
no_license
|
PKUHEPEWK/DNN
|
015bb5f862f6ee0363f8671890339469ef7aa76b
|
ad500137441b2f0a55bf462830aca42d9c9d6710
|
refs/heads/master
| 2020-03-25T01:34:54.253383
| 2019-01-29T07:56:26
| 2019-01-29T07:56:26
| 143,244,572
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,606
|
py
|
from ROOT import *
from math import sqrt
import sys, os, math
#from root_numpy import *
import numpy as np
sys.path.append("/Users/leejunho/Desktop/git/python3Env/group_study/project_pre/func")
from c0_READ_PATH_FILE_ROOT import read_file_name_root
class Asimov_Dataset:
def __init__(self,infileLL,infileTTTL):
self.tfileLL = TFile(infileLL,"READ")
self.tfileTTTL = TFile(infileTTTL,"READ")
return
def Make_AsimovData(self,NLLTarget,NTTTLTarget,BinNum=20):
TreeLL = self.tfileLL.Get("tree"); TreeTTTL = self.tfileTTTL.Get("tree")
EntriesLL = TreeLL.GetEntries(); print("Total Entry of Tree LL :",EntriesLL)
EntriesTTTL = TreeTTTL.GetEntries(); print("Total Entry of Tree TTTL :",EntriesTTTL)
LL_scale = NLLTarget/EntriesLL; TTTL_scale = NTTTLTarget/EntriesTTTL
print("Scale Factor on each LL event :",LL_scale); print("Scale Factor on each TTTL event :",TTTL_scale)
#cv = TCanvas("cv","cv",1200,900);
OF = TFile("Asimov_Dataset.root","RECREATE")
lep1pt_hist = TH1D("lep1pt_data","lep1pt_data",BinNum,20,650);
dphijj_hist = TH1D("dphijj_data","dphijj_data",BinNum,-0.5,3.5);
detajj_hist = TH1D("detajj_data","detajj_data",BinNum,2,10);
jet1pt_hist = TH1D("jet1pt_data","jet1pt_data",BinNum,20,800);
lep1pt_hist_LL = TH1D("lep1pt_LL","lep1pt_LL",BinNum,20,650);
dphijj_hist_LL = TH1D("dphijj_LL","dphijj_LL",BinNum,-0.5,3.5);
detajj_hist_LL = TH1D("detajj_LL","detajj_LL",BinNum,2,10);
jet1pt_hist_LL = TH1D("jet1pt_LL","jet1pt_LL",BinNum,20,800);
lep1pt_hist_TTTL = TH1D("lep1pt_TTTL","lep1pt_TTTL",BinNum,20,650);
dphijj_hist_TTTL = TH1D("dphijj_TTTL","dphijj_TTTL",BinNum,-0.5,3.5);
detajj_hist_TTTL = TH1D("detajj_TTTL","detajj_TTTL",BinNum,2,10);
jet1pt_hist_TTTL = TH1D("jet1pt_TTTL","jet1pt_TTTL",BinNum,20,800);
'''
LL_lep1pt_array = tree2array(TreeLL, branches='lep1pt')
LL_lep1pt_array_min = np.amin(LL_lep1pt_array); LL_lep1pt_array_max = np.amax(LL_lep1pt_array);
LL_dphijj_array = tree2array(TreeLL, branches='dphijj')
LL_dphijj_array_min = np.amin(LL_dphijj_array); LL_dphijj_array_max = np.amax(LL_dphijj_array);
TTTL_lep1pt_array = tree2array(TreeTTTL, branches='lep1pt')
TTTL_lep1pt_array_min = np.amin(TTTL_lep1pt_array); TTTL_lep1pt_array_max = np.amax(TTTL_lep1pt_array);
LL_lep1pt_array = tree2array(TreeLL, branches='lep1pt')
LL_lep1pt_array_min = np.amin(LL_lep1pt_array); LL_lep1pt_array_max = np.amax(LL_lep1pt_array);
'''
print("Rotation on TreeLL, Filling Histogram")
for i in range(EntriesLL):
if i%50000==0: print("Now looping", i," of Total",EntriesLL);
TreeLL.GetEntry(i)
lep1pt_hist.Fill(eval("TreeLL.lep1pt"),LL_scale)
dphijj_hist.Fill(eval("TreeLL.dphijj"),LL_scale)
detajj_hist.Fill(eval("TreeLL.detajj"),LL_scale)
jet1pt_hist.Fill(eval("TreeLL.jet1pt"),LL_scale)
lep1pt_hist_LL.Fill(eval("TreeLL.lep1pt"))
dphijj_hist_LL.Fill(eval("TreeLL.dphijj"))
detajj_hist_LL.Fill(eval("TreeLL.detajj"))
jet1pt_hist_LL.Fill(eval("TreeLL.jet1pt"))
print("Rotation on TreeTTTL, Filling Histogram")
for i in range(EntriesTTTL):
if i%50000==0: print("Now looping", i," of Total",EntriesTTTL);
TreeTTTL.GetEntry(i)
lep1pt_hist.Fill(eval("TreeTTTL.lep1pt"),TTTL_scale)
dphijj_hist.Fill(eval("TreeTTTL.dphijj"),TTTL_scale)
detajj_hist.Fill(eval("TreeTTTL.detajj"),TTTL_scale)
jet1pt_hist.Fill(eval("TreeTTTL.jet1pt"),TTTL_scale)
lep1pt_hist_TTTL.Fill(eval("TreeTTTL.lep1pt"))
dphijj_hist_TTTL.Fill(eval("TreeTTTL.dphijj"))
detajj_hist_TTTL.Fill(eval("TreeTTTL.detajj"))
jet1pt_hist_TTTL.Fill(eval("TreeTTTL.jet1pt"))
print("Resetting error-bar on each bin")
for i in range(BinNum):
temp_content_error = sqrt(lep1pt_hist.GetBinContent(i+1))
lep1pt_hist.SetBinError(i+1, temp_content_error)
temp_content_error = sqrt(dphijj_hist.GetBinContent(i+1))
dphijj_hist.SetBinError(i+1, temp_content_error)
temp_content_error = sqrt(detajj_hist.GetBinContent(i+1))
detajj_hist.SetBinError(i+1, temp_content_error)
temp_content_error = sqrt(jet1pt_hist.GetBinContent(i+1))
jet1pt_hist.SetBinError(i+1, temp_content_error)
OF.Write()
OF.Close()
return
def Append_MC(self):
return
def main():
infileLL = "/Users/leejunho/Desktop/git/PKUHEP/DNN/SSWW_split_input/result/for_LL_TTTL_compare/SS_250M_cut_LL.root" #FIXME
infileTTTL = "/Users/leejunho/Desktop/git/PKUHEP/DNN/SSWW_split_input/result/for_LL_TTTL_compare/SS_250M_cut_TTTL.root" #FIXME
BinNum = 20 #FIXME
XSec = 0.17864 #pb #FIXME
Lumi = 3000000 #pb-1 == 10^-3 *fb-1 #FIXME
eff_sel = 0.015944 #FIXME
eff_LL = 0.04503 #FIXME
NTotTarget = XSec*Lumi*eff_sel;
NLLTarget = NTotTarget*eff_LL; NTTTLTarget = NTotTarget*(1-eff_LL)
print("Targetting LL Event number :",NLLTarget)
print("Targetting TTTL Event number :",NTTTLTarget)
Asimov = Asimov_Dataset(infileLL=infileLL,infileTTTL=infileTTTL)
Asimov.Make_AsimovData(NLLTarget,NTTTLTarget,BinNum)
if __name__=="__main__":
main()
|
[
"skyblue1293@naver.com"
] |
skyblue1293@naver.com
|
ba0d414f75ba433e54bc79826218257d4eb70aa8
|
5785d7ed431b024dd910b642f10a6781df50e4aa
|
/revise-daily/arjuna-vishwamitra-abhimanyu/educative/5-medium-subsets/4_permutation_case_sensitive.py
|
f355280b9cad1e435f0ad603dc1e781b88acf6e7
|
[] |
no_license
|
kashyapa/interview-prep
|
45d77324446da34d99bf8efedb3544b367b5523e
|
7060c090c40602fb9c4778eace2078e1b51e235b
|
refs/heads/master
| 2023-07-28T13:12:49.515299
| 2021-09-06T14:33:25
| 2021-09-06T14:33:25
| 403,706,510
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 465
|
py
|
def permutation_swapcase(str):
# abcd, Abcd, aBcd, ABcd, abCd, AbCd, aBCd, ABCd, abcD, AbcD, aBcD, ABcD, abCD, AbCD, aBCD, ABCD
perms = []
perms.append(str)
for i in range(len(str)):
n = len(perms)
if str[i].isalpha():
for j in range(n):
new_perm = perms[j]
chs = list(new_perm)
chs[i] = chs[i].swapcase()
perms.append("".join(new_perm))
return perms
|
[
"schandra2@godaddy.com"
] |
schandra2@godaddy.com
|
87f0fffaab7bc21ca9eeed785b838ae66c278d13
|
e10a6d844a286db26ef56469e31dc8488a8c6f0e
|
/robust_loss/util.py
|
e16e1d6560e238c6a2ba80982aec7983c748cf1f
|
[
"Apache-2.0",
"CC-BY-4.0"
] |
permissive
|
Jimmy-INL/google-research
|
54ad5551f97977f01297abddbfc8a99a7900b791
|
5573d9c5822f4e866b6692769963ae819cb3f10d
|
refs/heads/master
| 2023-04-07T19:43:54.483068
| 2023-03-24T16:27:28
| 2023-03-24T16:32:17
| 282,682,170
| 1
| 0
|
Apache-2.0
| 2020-07-26T15:50:32
| 2020-07-26T15:50:31
| null |
UTF-8
|
Python
| false
| false
| 5,609
|
py
|
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Helper functions."""
import numpy as np
import tensorflow.compat.v2 as tf
def log_safe(x):
"""The same as tf.math.log(x), but clamps the input to prevent NaNs."""
return tf.math.log(tf.minimum(x, tf.cast(3e37, x.dtype)))
def log1p_safe(x):
"""The same as tf.math.log1p(x), but clamps the input to prevent NaNs."""
return tf.math.log1p(tf.minimum(x, tf.cast(3e37, x.dtype)))
def exp_safe(x):
"""The same as tf.math.exp(x), but clamps the input to prevent NaNs."""
return tf.math.exp(tf.minimum(x, tf.cast(87.5, x.dtype)))
def expm1_safe(x):
"""The same as tf.math.expm1(x), but clamps the input to prevent NaNs."""
return tf.math.expm1(tf.minimum(x, tf.cast(87.5, x.dtype)))
def inv_softplus(y):
"""The inverse of tf.nn.softplus()."""
return tf.where(y > 87.5, y, tf.math.log(tf.math.expm1(y)))
def logit(y):
"""The inverse of tf.nn.sigmoid()."""
return -tf.math.log(1. / y - 1.)
def affine_sigmoid(real, lo=0, hi=1):
"""Maps reals to (lo, hi), where 0 maps to (lo+hi)/2."""
if not lo < hi:
raise ValueError('`lo` (%g) must be < `hi` (%g)' % (lo, hi))
alpha = tf.sigmoid(real) * (hi - lo) + lo
return alpha
def inv_affine_sigmoid(alpha, lo=0, hi=1):
"""The inverse of affine_sigmoid(., lo, hi)."""
if not lo < hi:
raise ValueError('`lo` (%g) must be < `hi` (%g)' % (lo, hi))
real = logit((alpha - lo) / (hi - lo))
return real
def affine_softplus(real, lo=0, ref=1):
"""Maps real numbers to (lo, infinity), where 0 maps to ref."""
if not lo < ref:
raise ValueError('`lo` (%g) must be < `ref` (%g)' % (lo, ref))
shift = inv_softplus(tf.cast(1., real.dtype))
scale = (ref - lo) * tf.nn.softplus(real + shift) + lo
return scale
def inv_affine_softplus(scale, lo=0, ref=1):
"""The inverse of affine_softplus(., lo, ref)."""
if not lo < ref:
raise ValueError('`lo` (%g) must be < `ref` (%g)' % (lo, ref))
shift = inv_softplus(tf.cast(1., scale.dtype))
real = inv_softplus((scale - lo) / (ref - lo)) - shift
return real
def students_t_nll(x, df, scale):
"""The NLL of a Generalized Student's T distribution (w/o including TFP)."""
return 0.5 * ((df + 1.) * tf.math.log1p(
(x / scale)**2. / df) + tf.math.log(df)) + tf.math.log(
tf.abs(scale)) + tf.math.lgamma(
0.5 * df) - tf.math.lgamma(0.5 * df + 0.5) + 0.5 * np.log(np.pi)
# A constant scale that makes tf.image.rgb_to_yuv() volume preserving.
_VOLUME_PRESERVING_YUV_SCALE = 1.580227820074
def rgb_to_syuv(rgb):
"""A volume preserving version of tf.image.rgb_to_yuv().
By "volume preserving" we mean that rgb_to_syuv() is in the "special linear
group", or equivalently, that the Jacobian determinant of the transformation
is 1.
Args:
rgb: A tensor whose last dimension corresponds to RGB channels and is of
size 3.
Returns:
A scaled YUV version of the input tensor, such that this transformation is
volume-preserving.
"""
return _VOLUME_PRESERVING_YUV_SCALE * tf.image.rgb_to_yuv(rgb)
def syuv_to_rgb(yuv):
"""A volume preserving version of tf.image.yuv_to_rgb().
By "volume preserving" we mean that rgb_to_syuv() is in the "special linear
group", or equivalently, that the Jacobian determinant of the transformation
is 1.
Args:
yuv: A tensor whose last dimension corresponds to scaled YUV channels and is
of size 3 (ie, the output of rgb_to_syuv()).
Returns:
An RGB version of the input tensor, such that this transformation is
volume-preserving.
"""
return tf.image.yuv_to_rgb(yuv / _VOLUME_PRESERVING_YUV_SCALE)
def image_dct(image):
"""Does a type-II DCT (aka "The DCT") on axes 1 and 2 of a rank-3 tensor."""
dct_y = tf.transpose(
a=tf.signal.dct(image, type=2, norm='ortho'), perm=[0, 2, 1])
dct_x = tf.transpose(
a=tf.signal.dct(dct_y, type=2, norm='ortho'), perm=[0, 2, 1])
return dct_x
def image_idct(dct_x):
"""Inverts image_dct(), by performing a type-III DCT."""
dct_y = tf.signal.idct(
tf.transpose(dct_x, perm=[0, 2, 1]), type=2, norm='ortho')
image = tf.signal.idct(
tf.transpose(dct_y, perm=[0, 2, 1]), type=2, norm='ortho')
return image
def compute_jacobian(f, x):
"""Computes the Jacobian of function `f` with respect to input `x`."""
x = tf.convert_to_tensor(x)
with tf.GradientTape(persistent=True) as tape:
tape.watch(x)
vec = lambda x: tf.reshape(x, [-1])
jacobian = tf.stack(
[vec(tape.gradient(vec(f(x))[d], x)) for d in range(tf.size(x))])
return jacobian
def get_resource_as_file(path):
"""A uniform interface for internal/open-source files."""
class NullContextManager(object):
def __init__(self, dummy_resource=None):
self.dummy_resource = dummy_resource
def __enter__(self):
return self.dummy_resource
def __exit__(self, *args):
pass
return NullContextManager('./' + path)
def get_resource_filename(path):
"""A uniform interface for internal/open-source filenames."""
return './' + path
|
[
"copybara-worker@google.com"
] |
copybara-worker@google.com
|
0aba4c835bf050bf8a957d653f0f795cc8df0b45
|
518bf342bc4138982af3e2724e75f1d9ca3ba56c
|
/solutions/1589. Maximum Sum Obtained of Any Permutation/1589.py
|
788bf7675e89f00c8c36280ac9384a28a4918035
|
[
"MIT"
] |
permissive
|
walkccc/LeetCode
|
dae85af7cc689882a84ee5011f0a13a19ad97f18
|
a27be41c174565d365cbfe785f0633f634a01b2a
|
refs/heads/main
| 2023-08-28T01:32:43.384999
| 2023-08-20T19:00:45
| 2023-08-20T19:00:45
| 172,231,974
| 692
| 302
|
MIT
| 2023-08-13T14:48:42
| 2019-02-23T15:46:23
|
C++
|
UTF-8
|
Python
| false
| false
| 507
|
py
|
class Solution:
def maxSumRangeQuery(self, nums: List[int], requests: List[List[int]]) -> int:
kMod = 1_000_000_007
ans = 0
# count[i] := # of times nums[i] has been requested
count = [0] * len(nums)
for start, end in requests:
count[start] += 1
if end + 1 < len(nums):
count[end + 1] -= 1
for i in range(1, len(nums)):
count[i] += count[i - 1]
for num, c in zip(sorted(nums), sorted(count)):
ans += num * c
ans %= kMod
return ans
|
[
"me@pengyuc.com"
] |
me@pengyuc.com
|
4d98fe655147a64f31dce19a2237de013034d925
|
9419861577102f31261bcd5d0c365a8c8362c54d
|
/firstproject/urls.py
|
04fe0109a96dbcb862d69932f9ce4d8a6332f710
|
[] |
no_license
|
16LeeSeul/django_wordcount
|
f09ae855406cf767e0555191385a22e07218a8ba
|
01d195298de0cd03390d397d01ccb2e79b8fd593
|
refs/heads/master
| 2020-04-17T23:25:44.141771
| 2019-01-22T17:16:19
| 2019-01-22T17:16:19
| 167,034,940
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 365
|
py
|
from django.contrib import admin
from django.urls import path
import wordcount.views
urlpatterns = [
path('admin/', admin.site.urls),
path('', wordcount.views.home, name="home"),
path('about/', wordcount.views.about, name="about"),
path('result/', wordcount.views.result, name="result"),
path('index/', wordcount.views.index, name="index"),
]
|
[
"YOUR@EMAIL.com"
] |
YOUR@EMAIL.com
|
0d6b5e20427885b3ea44219bd165433b76358e41
|
f62955f9f78fc0ebc84d2f58118a012edc3317b9
|
/.eggs/scikit_learn-0.19.1-py2.7-linux-x86_64.egg/sklearn/decomposition/cdnmf_fast.py
|
4d8deb50edc2ac72da6186c62a71462b276a2247
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
wouterkessels/PREDICTFastr
|
31aa5de9b0a85613af7e961297c13be2c19d3dfc
|
2ac3a34b4d43e6a88684e79fd14d5c3f02d27eb6
|
refs/heads/master
| 2021-04-03T05:21:20.425482
| 2018-05-14T07:57:40
| 2018-05-14T07:57:40
| 124,414,878
| 0
| 0
| null | 2018-03-08T16:00:55
| 2018-03-08T16:00:54
| null |
UTF-8
|
Python
| false
| false
| 286
|
py
|
def __bootstrap__():
global __bootstrap__, __loader__, __file__
import sys, pkg_resources, imp
__file__ = pkg_resources.resource_filename(__name__, 'cdnmf_fast.so')
__loader__ = None; del __bootstrap__, __loader__
imp.load_dynamic(__name__,__file__)
__bootstrap__()
|
[
"m.starmans@erasmusmc.nl"
] |
m.starmans@erasmusmc.nl
|
82e2d74564a2c116c8172cf12c9f4aae74c1cf6c
|
324ec5647849f97418c91151e4e1d1953d2d9257
|
/account_dashboard_bokeh/__manifest__.py
|
efb0b7a4ced07a7c134122ea173cb32a2235bc73
|
[] |
no_license
|
MarcosCommunity/marcos_community_addons
|
84ab9ae7639b1d77ad36a167786160f54e0ef409
|
7adeceea5c12129baad36c037ff188cbccc98e2f
|
refs/heads/10.0
| 2020-04-04T07:27:54.837381
| 2017-10-10T01:44:17
| 2017-10-10T01:44:18
| 45,713,685
| 15
| 15
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,690
|
py
|
# -*- coding: utf-8 -*-
##############################################################################
#
# iFenSys Software Solutions Pvt. Ltd.
# Copyright (C) 2017 iFenSys Software Solutions(<http://www.ifensys.com>).
# you can modify it under the terms of the GNU LESSER
# GENERAL PUBLIC LICENSE (LGPL v3), Version 3.
#
# It is forbidden to publish, distribute, sublicense, or sell copies
# of the Software or modified copies of the Software.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU LESSER GENERAL PUBLIC LICENSE (LGPL v3) for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# GENERAL PUBLIC LICENSE (LGPL v3) along with this program.
# If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Accounting Dashboard Bokeh Charts',
'version': '10.0.0.1',
'category':'Accounting',
'summary': 'Accounting Dashboard Bokeh Charts',
'author':'iFenSys Software Solutions Pvt. Ltd',
'company':'iFenSys Software Solutions Pvt. Ltd',
'website': 'http://www.ifensys.com',
'depends': ['base','product','account'],
'data': [
'views/templates.xml',
'data/dashboard_demo.xml',
'data/dashboard_data.xml',
'views/html_template_views.xml',
'views/menus.xml',
],
'qweb': ['static/src/xml/*.xml'],
'images': ['static/description/banner.png'],
'installable': True,
'auto_install': False,
}
|
[
"eneldoserrata@gmail.com"
] |
eneldoserrata@gmail.com
|
5f530fb04413e8fe54b09e163502f22247cc0074
|
21b50b70ab307adfa39b9932b826f4de1b5e7786
|
/posts/urls.py
|
60d16029df27881878cb78d0c32dad61d9264664
|
[] |
no_license
|
kamral/drf1
|
080da165852fb2e7247c3298c03f26f96a76046a
|
f78aea6e39aa0aa6b66bb094c583286970fe14b9
|
refs/heads/main
| 2023-01-20T04:45:41.676653
| 2020-11-26T15:57:08
| 2020-11-26T15:57:08
| 316,277,381
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 192
|
py
|
from django.urls import path
from .views import PostListApiView,PostDetailApiView
urlpatterns=[
path('', PostListApiView.as_view()),
path('<int:pk>/', PostDetailApiView.as_view()),
]
|
[
"kamral010101@gmail.com"
] |
kamral010101@gmail.com
|
a82e2ff00c8f70e65e2c5564da32ab9055065709
|
39988ca6b376a37fe115816d6e707c4e7ea0b077
|
/reproducibilityPackages/independenceStudy/cuibm/gridIndependence/Re2000AoA35/plotForceCoefficientsCompareATol.py
|
6fc2b7a0aa8a39ee7e310044a2b9ecc90c862db6
|
[
"CC-BY-4.0",
"CC-BY-3.0",
"MIT"
] |
permissive
|
mljack/snake-repro
|
beddb77e1a892e126005cb4a8843365214d84ec9
|
f594d975fd2ba00a66b90877a4f7bd7596838fc8
|
refs/heads/master
| 2023-03-18T16:24:37.684519
| 2020-05-10T17:34:03
| 2020-05-10T17:34:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,569
|
py
|
"""
Compares the instantaneous force coefficients obtained on the coarse mesh
(h=0.006) using a different absolute tolerance (1.0E-05 and 1.0E-06) as exit
criterion for the Poisson solver.
The velocity solver is solved with an absolute tolerance of 1.0E-16 (machine
accuracy).
This script generates the figure `forceCoefficientsCompareATol.png` saved in the
same directory.
"""
import os
import warnings
from matplotlib import pyplot
import snake
from snake.cuibm.simulation import CuIBMSimulation
if snake.__version__ != '0.1.2':
warnings.warn('The figures were originally created with snake-0.1.2, '+
'you are using snake-{}'.format(snake.__version__))
# Computes the mean force coefficients from the cuIBM simulation
# with grid-spacing h=0.006 in the uniform region and atol=1.0E-06 for the
# Poisson solver.
# The force coefficients are averaged between 32 and 64 time-units.
simulation_directory = os.path.join(os.path.dirname(__file__),
'h0.006_vatol16_patol6_dt0.0002')
simulation = CuIBMSimulation(description='atol=1.0E-06',
directory=simulation_directory)
simulation.read_forces()
simulation.get_mean_forces(limits=[32.0, 64.0])
# Computes the mean force coefficients from the cuIBM simulation
# with grid-spacing h=0.006 in the uniform region and atol=1.0E-05 for the
# Poisson solver.
# The force coefficients are averaged between 32 and 64 time-units.
simulation_directory = os.path.join(os.path.dirname(__file__),
'h0.006_vatol16_patol5_dt0.0002')
simulation2 = CuIBMSimulation(description='atol=1.0E-05',
directory=simulation_directory)
simulation2.read_forces()
simulation2.get_mean_forces(limits=[32.0, 64.0])
# Creates a table with the time-averaged force coefficients.
dataframe = simulation.create_dataframe_forces(display_coefficients=True,
coefficient=2.0)
dataframe2 = simulation2.create_dataframe_forces(display_coefficients=True,
coefficient=2.0)
dataframe = dataframe.append([dataframe2])
print(dataframe)
# Plots the instantaneous force coefficients from the simulation using shifted
# markers and from the simulation using exact markers.
fig, ax = pyplot.subplots(figsize=(6, 4))
ax.grid(True, zorder=0)
ax.set_xlabel('non-dimensional time-unit')
ax.set_ylabel('force coefficients')
ax.plot(simulation.forces[0].times, 2.0*simulation.forces[0].values,
label='$C_d$ - $atol = 10^{-6}$',
color='#377eb8',
linestyle='-',
linewidth=2,
zorder=10)
ax.plot(simulation2.forces[0].times, 2.0*simulation2.forces[0].values,
label='$C_d$ - $atol = 10^{-5}$',
color='#111111',
linestyle='-',
linewidth=1,
zorder=11)
ax.plot(simulation.forces[1].times, 2.0*simulation.forces[1].values,
label='$C_l$ - $atol = 10^{-6}$',
color='#ff7f00',
linewidth=2,
linestyle='-',
zorder=10)
ax.plot(simulation2.forces[1].times, 2.0*simulation2.forces[1].values,
label='$C_l$ - $atol = 10^{-5}$',
color='#111111',
linestyle=':',
linewidth=2,
zorder=11)
ax.axis([0.0, 80.0, 0.75, 3.5])
ax.legend(ncol=2, loc='upper right')
file_path = os.path.join(os.path.dirname(__file__),
'forceCoefficientsCompareATol.png')
pyplot.savefig(file_path,
bbox_inches='tight',
format='png',
dpi=300)
|
[
"mesnardo@gwu.edu"
] |
mesnardo@gwu.edu
|
d47f5cff2feae7651c928e07fc84f08ff20b1a9b
|
8661524d0aab2ec62a0443d843cd2810a5d06201
|
/tiendadj/tienda/tienda/urls.py
|
b15dad841c769079d032df88bdae517ce5bd6541
|
[] |
no_license
|
Garavirod/Django-DRF-Projects
|
e8fbfbbd86f09862ac4ae48cb7f9c46b9360978a
|
93ba2a5f59dbbe2c2c440abc89c6cd473b59fc4c
|
refs/heads/master
| 2023-01-13T13:06:06.647724
| 2020-11-23T19:28:12
| 2020-11-23T19:28:12
| 289,785,572
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,202
|
py
|
"""tienda URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, re_path, include
urlpatterns = [
path('admin/', admin.site.urls),
# users app urls path
re_path('',include('applications.users.urls')),
# product app urls path
re_path('',include('applications.producto.urls')),
# venta app url path
re_path('',include('applications.venta.urls')),
# Colors path with routers and viewset
re_path('', include('applications.producto.routers')),
# Venta path with routers and viewset
re_path('',include('applications.venta.routers'))
]
|
[
"rodrigogarciaavila26@gmail.com"
] |
rodrigogarciaavila26@gmail.com
|
2bd53bae47464d656701a6fdfb49ed469fb6bbfe
|
b15d2787a1eeb56dfa700480364337216d2b1eb9
|
/samples/cli/accelbyte_py_sdk_cli/iam/_delete_client_by_namespace.py
|
66c47c09ba25715164ca03371181b603b5a439d1
|
[
"MIT"
] |
permissive
|
AccelByte/accelbyte-python-sdk
|
dedf3b8a592beef5fcf86b4245678ee3277f953d
|
539c617c7e6938892fa49f95585b2a45c97a59e0
|
refs/heads/main
| 2023-08-24T14:38:04.370340
| 2023-08-22T01:08:03
| 2023-08-22T01:08:03
| 410,735,805
| 2
| 1
|
MIT
| 2022-08-02T03:54:11
| 2021-09-27T04:00:10
|
Python
|
UTF-8
|
Python
| false
| false
| 2,268
|
py
|
# Copyright (c) 2021 AccelByte Inc. All Rights Reserved.
# This is licensed software from AccelByte Inc, for limitations
# and restrictions contact your company contract manager.
#
# Code generated. DO NOT EDIT!
# template_file: python-cli-command.j2
# AGS Iam Service (6.2.0)
# pylint: disable=duplicate-code
# pylint: disable=line-too-long
# pylint: disable=missing-function-docstring
# pylint: disable=missing-module-docstring
# pylint: disable=too-many-arguments
# pylint: disable=too-many-branches
# pylint: disable=too-many-instance-attributes
# pylint: disable=too-many-lines
# pylint: disable=too-many-locals
# pylint: disable=too-many-public-methods
# pylint: disable=too-many-return-statements
# pylint: disable=too-many-statements
# pylint: disable=unused-import
import json
import yaml
from typing import Optional
import click
from .._utils import login_as as login_as_internal
from .._utils import to_dict
from accelbyte_py_sdk.api.iam import (
delete_client_by_namespace as delete_client_by_namespace_internal,
)
from accelbyte_py_sdk.api.iam.models import RestErrorResponse
@click.command()
@click.argument("client_id", type=str)
@click.option("--namespace", type=str)
@click.option("--login_as", type=click.Choice(["client", "user"], case_sensitive=False))
@click.option("--login_with_auth", type=str)
@click.option("--doc", type=bool)
def delete_client_by_namespace(
client_id: str,
namespace: Optional[str] = None,
login_as: Optional[str] = None,
login_with_auth: Optional[str] = None,
doc: Optional[bool] = None,
):
if doc:
click.echo(delete_client_by_namespace_internal.__doc__)
return
x_additional_headers = None
if login_with_auth:
x_additional_headers = {"Authorization": login_with_auth}
else:
login_as_internal(login_as)
result, error = delete_client_by_namespace_internal(
client_id=client_id,
namespace=namespace,
x_additional_headers=x_additional_headers,
)
if error:
raise Exception(f"DeleteClientByNamespace failed: {str(error)}")
click.echo(yaml.safe_dump(to_dict(result), sort_keys=False))
delete_client_by_namespace.operation_id = "DeleteClientByNamespace"
delete_client_by_namespace.is_deprecated = True
|
[
"elmernocon@gmail.com"
] |
elmernocon@gmail.com
|
62ead87a73ff1561c12a3a6a489e0494f0c0c0b8
|
3f09e77f169780968eb4bd5dc24b6927ed87dfa2
|
/src/Problems/Trapping_Rain_Water.py
|
790695e2d95e041b9c6897137e6540ec4299a717
|
[] |
no_license
|
zouyuanrenren/Leetcode
|
ad921836256c31e31cf079cf8e671a8f865c0660
|
188b104b81e6c73792f7c803c0fa025f9413a484
|
refs/heads/master
| 2020-12-24T16:59:12.464615
| 2015-01-19T21:59:15
| 2015-01-19T21:59:15
| 26,719,111
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,023
|
py
|
'''
Created on 19 Jan 2015
@author: Yuan
'''
'''
This problem has several solutions.
Solutoin1:
1. find the peak of the array.
2. for each bar to the left of the peak, if the tallest to its left is MAX, then it can hold MAX-bar water.
3. for each bar to the right of the peak, if the tallest to its right is MAX, then it can hold MAX-bar water.
Solution2 is to use a stack. Need to add later.
'''
class Solution1:
# @param A, a list of integers
# @return an integer
def trap(self, A):
total = 0
if len(A) == 0:
return 0
peak = 0
for index in range(0, len(A)):
if A[index] > A[peak]:
peak = index
pre = A[0]
for index in range(0, peak):
pre = max(pre, A[index])
total += pre-A[index]
pre = A[len(A)-1]
index = len(A)-1
while index > peak:
pre = max(pre, A[index])
total += pre-A[index]
index -= 1
return total
|
[
"y.ren@abdn.ac.uk"
] |
y.ren@abdn.ac.uk
|
562b6ccf75ce533f7d45cd5c3e35c161c0f06b56
|
7438ed5bda477e728fd075d8aba69a4ee43cbe83
|
/day_04/json_ex/json_ex01.py
|
05adb2c4821a47893079dd8e8f067e52b83645fe
|
[] |
no_license
|
mindful-ai/18012021PYLVC
|
b2717846a905400c2462eb4dd293aa3a7a48a86f
|
2facc19fb433e3e15d1195fb2b75eea3bffd097a
|
refs/heads/main
| 2023-02-18T22:40:38.112663
| 2021-01-22T12:52:47
| 2021-01-22T12:52:47
| 330,656,405
| 1
| 2
| null | 2021-01-22T17:28:23
| 2021-01-18T12:17:10
|
Python
|
UTF-8
|
Python
| false
| false
| 145
|
py
|
import pandas as pd
data = pd.read_json('http://api.population.io/1.0/population/India/today-and-tomorrow/?format = json')
print(data)
|
[
"noreply@github.com"
] |
mindful-ai.noreply@github.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.