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
9d45c7ac1d31dcdc4b7a018c9ea7c272e9ce58b4
2c3da6e0bddf55d64d650040bbf286c47b31811a
/学习路线/1.python基础/day12/03-自定义异常.py
bd4172eec5c4d550a58d35d8fc6cc71179cba149
[ "MIT" ]
permissive
Bngzifei/PythonNotes
76bd53db3033a9c51ab4bdd727842cd89607b584
01590e1b6c1bc0f04aa2d355fa2553c04cce27f2
refs/heads/master
2023-02-04T06:49:00.725463
2020-12-15T09:26:40
2020-12-15T09:26:40
155,154,662
1
2
MIT
2020-09-08T01:30:19
2018-10-29T05:02:48
Python
UTF-8
Python
false
false
1,938
py
""" 异常抛出的原理: raise: 关键字 抛出 表示抛出指定的异常实例对象 raise 抛出异常的实例对象,然后except去拦截这个异常实例对象. 能不能拦截:是要看这个错误是不是这个错误的类创建的. 拦截:判断是不是同一个类造出来的,是,就把这个异常实例对象赋值给error. 先抛出来才能拦截. 自定义异常:不用解释器提供异常类. 1> 让异常信息是中文的,让用户也能看懂.更加人性化 2> 提前干预,还没有出错之前就来对问题进行处理. 3> 简化异常处理的流程,批量抛出,一次拦截. 注意: 自定义异常类必须继承Exception类,是为了使用raise的能力.否则会报错误. """ # try: # # print(a) # error_instance = NameError("name 'a' is not define") # 创建指定异常的实例对象 # print(id(error_instance)) # 2291212287760 # raise error_instance # 抛出指定的异常实例对象 # # # except NameError as error: # 里面写了各种错误类型,根据错误去找是什么样的错误类型. # print('提示:%s' % error) # 实际是一个NameError()类产生的一个实例对象.error实际就是一个错误类型的实例对象. # print(id(error)) # 2291212287760 # error = error_instance ,实际对应关系. class PhoneException(Exception): # 实际的 # def __init__(self, name): # self.name = name # # def __str__(self): # # return 'xxxxxxxxxxxxxxxx' # return self.name pass phone_num = input('手机号:') try: if len(phone_num) != 11: # print('号码位数不对') raise PhoneException('手机号码位数不对') elif phone_num.isdecimal() is False: # isdecimal():判断是不是数字,返回值是False或者是True # print('号码不是纯数字') raise PhoneException('手机号码不是纯数字') except PhoneException as error: print(error) # var = 'df'.center(20,'*') # 输出 : *********df********* # print(var)
[ "bngzifei@gmail.com" ]
bngzifei@gmail.com
f1629890cb41cf63d385ff4525caec9e3678951b
781e2692049e87a4256320c76e82a19be257a05d
/all_data/exercism_data/python/word-count/4633f41ce11c4f3db40f1cfe10da8a7c.py
7c016a0265697b750d833f5b89770e6f4100a444
[]
no_license
itsolutionscorp/AutoStyle-Clustering
54bde86fe6dbad35b568b38cfcb14c5ffaab51b0
be0e2f635a7558f56c61bc0b36c6146b01d1e6e6
refs/heads/master
2020-12-11T07:27:19.291038
2016-03-16T03:18:00
2016-03-16T03:18:42
59,454,921
4
0
null
2016-05-23T05:40:56
2016-05-23T05:40:56
null
UTF-8
Python
false
false
355
py
import string def stripPunc(x): # From S.Lott's solution for i in string.punctuation: x = x.replace(i,"") while " " in x: x = x[0:x.find(" ")] + x[(x.find(" ") + 1):] return x def word_count(x): words = {} for i in stripPunc(x).lower().split(" "): if i in words: words[i] += 1 else: words[i] = 1 return words
[ "rrc@berkeley.edu" ]
rrc@berkeley.edu
3acf4e7c0a1d9229123d0246516ee9b90f9c7d65
9e988c0dfbea15cd23a3de860cb0c88c3dcdbd97
/sdBs/AllRun/pg_2239+043/sdB_PG_2239+043_coadd.py
8fd4cff041120c8922b19c408c25702306753147
[]
no_license
tboudreaux/SummerSTScICode
73b2e5839b10c0bf733808f4316d34be91c5a3bd
4dd1ffbb09e0a599257d21872f9d62b5420028b0
refs/heads/master
2021-01-20T18:07:44.723496
2016-08-08T16:49:53
2016-08-08T16:49:53
65,221,159
0
0
null
null
null
null
UTF-8
Python
false
false
426
py
from gPhoton.gMap import gMap def main(): gMap(band="NUV", skypos=[339.639,4.857103], skyrange=[0.0333333333333,0.0333333333333], stepsz = 30., cntfile="/data2/fleming/GPHOTON_OUTPUT/LIGHTCURVES/sdBs/sdB_PG_2239+043/sdB_PG_2239+043_movie_count.fits", cntcoaddfile="/data2/fleming/GPHOTON_OUTPUT/LIGHTCURVES/sdB/sdB_PG_2239+043/sdB_PG_2239+043_count_coadd.fits", overwrite=True, verbose=3) if __name__ == "__main__": main()
[ "thomas@boudreauxmail.com" ]
thomas@boudreauxmail.com
43f43e93f47c1bebed88ed87d44afa9e783bf0d5
426e3c51d85e3ee60ce27c8b4f870b69db5dfc30
/config/settings.py
55666356579de325f1ac9be4bb1b0ab92bf4b406
[]
no_license
seiya0723/diary_04
ad5468f5af9f69bf659bfc3f977da6402cde1667
700213f4d646c09634fd0f76566604101796d2c1
refs/heads/master
2023-06-28T19:13:59.905437
2021-07-31T01:33:14
2021-07-31T01:33:14
391,228,042
0
0
null
null
null
null
UTF-8
Python
false
false
4,842
py
""" Django settings for config project. Generated by 'django-admin startproject' using Django 3.1.2. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'whj+@6kd^oo2_1$1gat0s7v4rk6vtjann1x+tqxeq_(d=tt6+h' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bbs.apps.BbsConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'config.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR,"templates") ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'config.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'ja' TIME_ZONE = 'Asia/Tokyo' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' if DEBUG: STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] if not DEBUG: # Herokuデプロイ時に必要になるライブラリのインポート import django_heroku import dj_database_url # ALLOWED_HOSTSにホスト名)を入力 ALLOWED_HOSTS = [ 'hogehoge.herokuapp.com' ] # 静的ファイル配信ミドルウェア、whitenoiseを使用。※順番不一致だと動かないため下記をそのままコピーする。 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] # DBを使用する場合は下記を入力する。 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'ここにDatabaseを入力', 'USER': 'ここにUserを入力', 'PASSWORD': 'ここにPasswordを入力', 'HOST': 'ここにHostを入力', 'PORT': 'ここにPortを入力', } } db_from_env = dj_database_url.config(conn_max_age=600, ssl_require=True) DATABASES['default'].update(db_from_env) # 静的ファイル(static)の存在場所を指定する。 STATIC_ROOT = os.path.join(BASE_DIR, 'static')
[ "seiya@asahina" ]
seiya@asahina
77bb8d0edbc32f2daee27dd739c806a846f8d986
be8057bf5bfb491cd876c42821a94a58266ae836
/manage.py
e4d17ff2433cbfdaf94d9146ff9376763cd3bd67
[]
no_license
hasgeek/packman
88ae1aa220167dc50a2b83011c53a49c13349437
d99a1d7f08f26e3476a969278a6f0d87b050a280
refs/heads/master
2020-12-25T17:30:07.449733
2019-05-26T14:47:52
2019-05-26T14:47:52
24,697,117
0
1
null
2019-05-26T14:47:53
2014-10-01T22:03:35
Python
UTF-8
Python
false
false
242
py
#!/usr/bin/env python from coaster.manage import init_manager from packman.models import db from packman import app, init_for if __name__ == '__main__': db.init_app(app) manager = init_manager(app, db, init_for) manager.run()
[ "kiran@hasgeek.com" ]
kiran@hasgeek.com
22dfefc6daa031bb7883752c31a9bb1bd9aced00
5e84763c16bd6e6ef06cf7a129bb4bd29dd61ec5
/blimgui/dist/OpenGL/raw/GL/NV/stereo_view_rendering.py
95d69c29319d993fde3973be7deea23fe0d87849
[ "MIT" ]
permissive
juso40/bl2sdk_Mods
8422a37ca9c2c2bbf231a2399cbcb84379b7e848
29f79c41cfb49ea5b1dd1bec559795727e868558
refs/heads/master
2023-08-15T02:28:38.142874
2023-07-22T21:48:01
2023-07-22T21:48:01
188,486,371
42
110
MIT
2022-11-20T09:47:56
2019-05-24T20:55:10
Python
UTF-8
Python
false
false
511
py
'''Autogenerated by xml_generate script, do not edit!''' from OpenGL import platform as _p, arrays # Code generation uses this from OpenGL.raw.GL import _types as _cs # End users want this... from OpenGL.raw.GL._types import * from OpenGL.raw.GL import _errors from OpenGL.constant import Constant as _C import ctypes _EXTENSION_NAME = 'GL_NV_stereo_view_rendering' def _f( function ): return _p.createFunction( function,_p.PLATFORM.GL,'GL_NV_stereo_view_rendering',error_checker=_errors._error_checker)
[ "justin.sostmann@googlemail.com" ]
justin.sostmann@googlemail.com
59041a9045421c361c8d5f960d5f68b475d4c6a1
3afc48df003fb180a24072b769b9e5fb5ffb7eb6
/tests/matchers/test_called_once_with.py
9f13e48a6a09f4189dfdcc3a5d03b82907403180
[ "MIT" ]
permissive
hieueastagile/robber.py
d20e90bf43ba2c354ffec56c80080bf65268fd6f
b439251848fd3b5085cdac45130311bfe0facc13
refs/heads/master
2021-01-21T21:09:42.378373
2017-04-24T03:23:22
2017-04-24T03:23:22
92,312,856
0
0
null
2017-05-24T16:21:42
2017-05-24T16:21:41
null
UTF-8
Python
false
false
2,219
py
from unittest import TestCase from mock import Mock from robber import expect from robber.matchers.called_once_with import CalledOnceWith class TestCalledOnceWith(TestCase): def test_matches(self): mock = Mock() mock(1, 2, 3, a=4) expect(CalledOnceWith(mock, 1, False, 2, 3, a=4).matches()).to.eq(True) def test_failure_message_with_not_called_mock(self): mock = Mock() called_once_with = CalledOnceWith(mock, 2) called_once_with.matches() message = called_once_with.failure_message() expect(message) == 'Expected {mock} to be called once with 2. Actually not called.'.format(mock=mock) def test_failure_message_with_called_multiple_times(self): mock = Mock() mock(1) mock(1) called_once_with = CalledOnceWith(mock, 2) called_once_with.matches() message = called_once_with.failure_message() expect(message) == 'Expected {mock} to be called once with 2. ' \ 'Actually called 2 times with 1.'.format(mock=mock) def test_failure_message_with_wrong_params(self): mock = Mock() mock(4, 5, 6, c=7) called_once_with = CalledOnceWith(mock, 1, False, 2, 3, a=4) called_once_with.matches() message = called_once_with.failure_message() expect(message) == 'Expected {mock} to be called once with 1, 2, 3, a=4. ' \ 'Actually called 1 times with 4, 5, 6, c=7.'.format(mock=mock) def test_negative_failure_message(self): mock = Mock() mock(1, 2, 3, a=4) called_once_with = CalledOnceWith(mock, 1, True, 2, 3, a=4) called_once_with.matches() message = called_once_with.failure_message() expect(message) == 'Expected {mock} not to be called once with 1, 2, 3, a=4. ' \ 'Actually called 1 times with 1, 2, 3, a=4.'.format(mock=mock) def test_register(self): expect(expect.matcher('called_once_with')) == CalledOnceWith def test_not_a_mock(self): self.assertRaises(TypeError, CalledOnceWith("a", "b").matches) self.assertRaises(TypeError, CalledOnceWith(1, "b").matches)
[ "open-source@eastagile.com" ]
open-source@eastagile.com
e6e473574eb22795757091531ef21ac06a1dffb9
109a830aad476305f029274d75e28bec8b54f597
/venv/lib/python3.9/site-packages/django/contrib/admindocs/urls.py
472df9835b304fd18b7f673137b62f549373cbff
[]
no_license
Dapucla/EP
53b156088046abfd6833eba95dc4393ebeb93f4e
9368032b4b289b20ec1bdf0033d3fe199223d200
refs/heads/master
2023-06-19T08:02:55.984888
2021-07-11T22:52:24
2021-07-11T22:52:24
330,009,437
0
0
null
null
null
null
UTF-8
Python
false
false
1,314
py
from django.contrib.admindocs import views from django.urls import path, re_path urlpatterns = [ path( '', views.BaseAdminDocsView.as_view(template_name='admin_doc/post_list.html'), name='django-admindocs-docroot', ), path( 'bookmarklets/', views.BookmarkletsView.as_view(), name='django-admindocs-bookmarklets', ), path( 'tags/', views.TemplateTagIndexView.as_view(), name='django-admindocs-tags', ), path( 'filters/', views.TemplateFilterIndexView.as_view(), name='django-admindocs-filters', ), path( 'views/', views.ViewIndexView.as_view(), name='django-admindocs-views-index', ), path( 'views/<view>/', views.ViewDetailView.as_view(), name='django-admindocs-views-detail', ), path( 'models/', views.ModelIndexView.as_view(), name='django-admindocs-models-index', ), re_path( r'^models/(?P<app_label>[^\.]+)\.(?P<model_name>[^/]+)/$', views.ModelDetailView.as_view(), name='django-admindocs-models-detail', ), path( 'templates/<path:template>/', views.TemplateDetailView.as_view(), name='django-admindocs-templates', ), ]
[ "dapcula08@yandex.ru" ]
dapcula08@yandex.ru
94413847eb45e257955156690c75cb5f1ca00387
334d0190164d92b53be2844a3afc2826d64b1a6d
/lib/python3.9/site-packages/theano/gpuarray/ctc.py
ef6c1d0af4e794d85d8c3e393db03ecc0dd468bb
[]
no_license
sou133688/BayesianStatics
f294d7c47cfa56374cf73b520529620dc6120f47
be9121429494cd8fd231594b029fc2f030d8335f
refs/heads/main
2023-08-21T15:57:32.980658
2021-10-01T00:01:13
2021-10-01T00:01:13
401,909,680
3
0
null
null
null
null
UTF-8
Python
false
false
7,292
py
import os import sys import theano.tensor as tt from theano.configdefaults import config from theano.gpuarray import pygpu from theano.gpuarray.basic_ops import ( as_gpuarray_variable, gpu_contiguous, gpuarray_helper_inc_dir, infer_context_name, ) from theano.gpuarray.elemwise import GpuDimShuffle from theano.gpuarray.type import GpuArrayType, gpu_context_type from theano.gradient import grad_undefined from theano.graph.basic import Apply from theano.graph.op import _NoPythonExternalCOp from theano.graph.opt import local_optimizer from theano.tensor.nnet.ctc import ctc_available from theano.tensor.opt import register_canonicalize class GpuConnectionistTemporalClassification(_NoPythonExternalCOp): """ GPU wrapper for Baidu CTC loss function. Parameters ---------- compute_grad If set to True, enables the computation of gradients of the CTC loss function. """ __props__ = ("compute_grad",) _cop_num_inputs = 3 _cop_num_outputs = 2 func_file = "./c_code/ctc_wrapper.c" func_name = "APPLY_SPECIFIC(ctc_cost_gpu)" params_type = gpu_context_type def __init__(self, compute_grad=True): if not ctc_available(): raise RuntimeError( "Baidu CTC is not available and " "GpuConnectionistTemporalClassification Op " "can not be constructed." ) self.compute_grad = compute_grad # Return only the cost. Gradient will be returned by grad() self.default_output = 0 super().__init__(self.func_file, self.func_name) def c_lib_dirs(self, **kwargs): lib_dirs = [] if ctc_available.path is not None: lib_dirs += [ctc_available.path] return lib_dirs def c_compile_args(self, **kwargs): if ctc_available.path is not None: if sys.platform != "darwin" and " " in ctc_available.path: return ['-Wl,-rpath,"' + ctc_available.path + '"'] else: return ["-Wl,-rpath," + ctc_available.path] return [] def c_libraries(self, **kwargs): return ["warpctc", "gpuarray"] def c_header_dirs(self, **kwargs): dirs = [ gpuarray_helper_inc_dir(), pygpu.get_include(), config.cuda__include_path, ] if config.ctc__root != "": dirs.append(os.path.join(config.ctc__root, "include")) return dirs def c_headers(self, **kwargs): return [ "ctc.h", "numpy_compat.h", "gpuarray/ext_cuda.h", "gpuarray_helper.h", "gpuarray/types.h", "gpuarray_api.h", "gpuarray/array.h", "gpuarray/util.h", "gpuarray/extension.h", ] def get_params(self, node): return node.inputs[0].type.context def make_node(self, activations, labels, input_lengths): context_name = infer_context_name(activations) t_activations = as_gpuarray_variable(activations, context_name=context_name) # Ensure activations array is C-contiguous t_activations = gpu_contiguous(t_activations) # Labels and input lengths are always on the CPU t_labels = tt.as_tensor_variable(labels) t_input_lengths = tt.as_tensor_variable(input_lengths) if t_activations.type.dtype != "float32": raise TypeError("activations must use the float32 type.") if t_activations.ndim != 3: raise ValueError("activations must have 3 dimensions.") if t_labels.type.dtype != "int32": raise TypeError("labels must use the int32 type.") if t_labels.ndim != 2: raise ValueError("labels must have 2 dimensions.") if t_input_lengths.type.dtype != "int32": raise TypeError("input_lengths must use the int32 type.") if t_input_lengths.ndim != 1: raise ValueError("input_lengths must have 1 dimension.") costs = GpuArrayType( dtype="float32", broadcastable=(False,), context_name=context_name )() outputs = [costs] if self.compute_grad: gradients = GpuArrayType( dtype="float32", broadcastable=( False, False, False, ), context_name=context_name, )() outputs += [gradients] return Apply( self, inputs=[t_activations, t_labels, t_input_lengths], outputs=outputs ) def L_op(self, inputs, outputs, output_grads): # Gradients computed by Op assert self.compute_grad and len(outputs) == 2 gradients = outputs[1] assert gradients is not None # Gradients of original function, to compose chain rule grad_op = output_grads[0] grad_shuffle = GpuDimShuffle( input_broadcastable=( False, False, False, ), new_order=(1, 0, 2), )(gradients) grad_bdot = tt.batched_dot(grad_op, grad_shuffle) grad_shuffle_reverse = GpuDimShuffle( input_broadcastable=( False, False, False, ), new_order=(1, 0, 2), )(grad_bdot) return [ grad_shuffle_reverse, grad_undefined(self, 1, inputs[1]), grad_undefined(self, 2, inputs[2]), ] def gpu_ctc(activations, labels, input_lengths): """ Compute CTC loss function on the GPU. Parameters ---------- activations Three-dimensional tensor, which has a shape of (t, m, p), where t is the time index, m is the minibatch index, and p is the index over the probabilities of each symbol in the alphabet. The memory layout is assumed to be in C-order, which consists in the slowest to the fastest changing dimension, from left to right. In this case, p is the fastest changing dimension. labels A 2-D tensor of all the labels for the minibatch. In each row, there is a sequence of target labels. Negative values are assumed to be padding, and thus are ignored. Blank symbol is assumed to have index 0 in the alphabet. input_lengths A 1-D tensor with the number of time steps for each sequence in the minibatch. Returns ------- 1-D array Cost of each example in the minibatch. """ return GpuConnectionistTemporalClassification()(activations, labels, input_lengths) # Disable gradient computation if not needed @register_canonicalize("fast_compile") @local_optimizer([GpuConnectionistTemporalClassification]) def local_gpu_ctc_no_grad(fgraph, node): if isinstance(node.op, GpuConnectionistTemporalClassification): if len(node.outputs) > 1: if len(fgraph.clients[node.outputs[1]]) == 0: # gradient is not used return [ GpuConnectionistTemporalClassification(compute_grad=False)( *node.inputs ), None, ] return False
[ "matsushu@ZaknoMacBook-Pro.local" ]
matsushu@ZaknoMacBook-Pro.local
8c27649f58ae110222601c787c28c39019e012ec
9dee94907e6456a4af9855d358693923c17b4e0d
/1023_Camelcase_Matching.py
2d8d31d02064c55c4031b5e1652870448db622a6
[]
no_license
chien-wei/LeetCode
e215915a8103e56f182040dacc9fb0d6996c86ec
0d6f414e7610fedb2ec4818ecf88d51aa69e1355
refs/heads/master
2021-05-13T14:48:22.891100
2019-08-20T05:52:59
2019-08-20T05:52:59
116,749,327
0
0
null
null
null
null
UTF-8
Python
false
false
663
py
class Solution: def camelMatch(self, queries: List[str], pattern: str) -> List[bool]: results = [] for query in queries: i, j = 0, 0 for p in pattern: while i < len(query) and p != query[i] and query[i].islower(): i += 1 if i == len(query): break if p != query[i]: break i += 1 j += 1 if j == len(pattern) and (query[i:] == '' or query[i:].islower()): results.append(True) else: results.append(False) return results
[ "chien-wei@outlook.com" ]
chien-wei@outlook.com
44361f5f1844f827da35dd426fbe24580b644796
08615c64a62fc364a802bb92314cf49080ddbcee
/django-oldboy/s1bms2/app01/models.py
e47061a1ed45c130f1022f5f77abe4351abad813
[]
no_license
xiangys0134/python_study
afc4591fca1db6ebddf83f0604e35ed2ef614728
6ec627af7923b9fd94d244c561297ccbff90c1e9
refs/heads/master
2023-02-24T01:24:45.734510
2022-10-29T02:11:20
2022-10-29T02:11:20
143,358,792
2
0
null
2023-02-08T03:07:26
2018-08-03T00:43:46
Python
UTF-8
Python
false
false
1,348
py
from django.db import models # Create your models here. class Book(models.Model): title = models.CharField(max_length=32) price = models.DecimalField(max_digits=8,decimal_places=2) book_type = models.CharField(max_length=32,null=True) publish = models.CharField(max_length=32) pub_date = models.DateTimeField() publish = models.ForeignKey("Publish",on_delete=models.CASCADE) authors = models.ManyToManyField("Author",db_table="book2author") class Meta: db_table = "book" class Publish(models.Model): name = models.CharField(max_length=32) addr = models.CharField(max_length=32) class Meta: db_table = "publish" class Author(models.Model): name = models.CharField(max_length=20) class Meta: db_table = "author" class AuthorDetail(models.Model): name = models.CharField(max_length=20) gf = models.CharField(max_length=32) uid = models.CharField(max_length=32,null=True) author = models.OneToOneField("Author",on_delete=models.CASCADE,null=True) class Meta: db_table = "authordetail" class Emp(models.Model): name = models.CharField(max_length=32) age = models.IntegerField() salary = models.DecimalField(max_digits=8, decimal_places=2) dep = models.CharField(max_length=32) province = models.CharField(max_length=32)
[ "you@example.com" ]
you@example.com
bfec217317ad49de9380a27431e4a9aa0666544a
5667cc877342204b7d54b6c3cc5a9f4854f08829
/.history/apppersona/views_20201029201908.py
dd580d4aa77ce4a4588bd4c7df3ded781932da1a
[]
no_license
Nyckhos/TestCommit
d62e3f6fefb04ab5647475cc7ead0d72cbd89efa
9aa8e2e35280b7862960cc8a864e9c02ac7f4796
refs/heads/main
2023-01-05T05:57:59.223641
2020-11-02T02:08:18
2020-11-02T02:08:18
309,237,224
2
0
null
2020-11-02T02:30:43
2020-11-02T02:30:43
null
UTF-8
Python
false
false
1,688
py
from django.http import request from django.shortcuts import render from django.http import HttpResponse from .models import * from .forms import * from django.contrib.auth.models import User # Create your views here. def lista_personas(request): lista = Persona.objects.all() # Todas las personas return render(request, 'apppersona/lista_personas.html', {'lista': lista}) def lista_tarjetas(request): tarjetas = TarjetaJunaeb.objects.all() return render(request, 'apppersona/lista_tarjetas.html', {'listaTarjetas': tarjetas}) def tarjetas_con_plata(request): tarjetas = TarjetaJunaeb.objects.filter(montoDisponible__gte=1) return render(request, 'apppersona/lista_tarjetas.html', {'listaTarjetas': tarjetas}) def persona_nueva(request): if request.method == "POST": formulario = FormularioPersona(request.POST) if formulario.is_valid(): persona = formulario.save(commit=False) persona.save() return HttpResponse("PERSONA GUARDADA") else: formulario = FormularioPersona() return render(request, 'apppersona/registro.html', {'form': formulario}) def index(request): return render(request, 'apppersona/index.html') def contacto(request): return render(request, 'apppersona/contacto.html') def nosotros(request): return render(request, 'apppersona/nosotros.html') def register(response): if response.method == "POST": form = RegisterForm(response.POST) if form.is_valid(): form.save() return HttpResponse("/home") else: form = RegisterForm() return render(response, "apppersona/register.html", {"form":form})
[ "fernandox_240997@live.com" ]
fernandox_240997@live.com
4de7b4d69f235c2fb5fc0b420156d5bcd46241ed
cfefcd99016a908df2584896845406942097671d
/python/test/test_asset_model_portfolio.py
c99a14dfc4d8fbc6b0ea51704ca93e1c90717e98
[]
no_license
tomasgarzon/vigilant-guacamole
982a8c7cb0a8193bb3409014b447ad8a70e6eb36
bde73674cf0461e2fcdfce5074bf9d93a47227f7
refs/heads/main
2023-08-17T01:51:27.168440
2021-09-01T11:23:46
2021-09-01T11:23:46
398,827,144
0
0
null
null
null
null
UTF-8
Python
false
false
950
py
""" Nucoro API No description # noqa: E501 The version of the OpenAPI document: 4.175.0 Generated by: https://openapi-generator.tech """ import sys import unittest import openapi_client from openapi_client.model.related_asset_serializer_with_asset_categories import RelatedAssetSerializerWithAssetCategories globals()['RelatedAssetSerializerWithAssetCategories'] = RelatedAssetSerializerWithAssetCategories from openapi_client.model.asset_model_portfolio import AssetModelPortfolio class TestAssetModelPortfolio(unittest.TestCase): """AssetModelPortfolio unit test stubs""" def setUp(self): pass def tearDown(self): pass def testAssetModelPortfolio(self): """Test AssetModelPortfolio""" # FIXME: construct object with mandatory attributes with example values # model = AssetModelPortfolio() # noqa: E501 pass if __name__ == '__main__': unittest.main()
[ "tomasgarzonhervas@gmail.com" ]
tomasgarzonhervas@gmail.com
d4acba5ceca5ea6b4c67111b4ffd8fbcf8ba1c41
781e2692049e87a4256320c76e82a19be257a05d
/all_data/exercism_data/python/anagram/d2e45eb99bcc469d9577e787110f32c3.py
8df791cbc67d7539b7bd89154c57e665cf8e2a40
[]
no_license
itsolutionscorp/AutoStyle-Clustering
54bde86fe6dbad35b568b38cfcb14c5ffaab51b0
be0e2f635a7558f56c61bc0b36c6146b01d1e6e6
refs/heads/master
2020-12-11T07:27:19.291038
2016-03-16T03:18:00
2016-03-16T03:18:42
59,454,921
4
0
null
2016-05-23T05:40:56
2016-05-23T05:40:56
null
UTF-8
Python
false
false
232
py
def detect_anagrams(word, args): anagrams =[] word =word.lower() for item in args: if sorted(word) == sorted(item.lower()) and word.lower() != item.lower(): anagrams.append(item) return anagrams
[ "rrc@berkeley.edu" ]
rrc@berkeley.edu
d9d7f6c4e551ddc9dbce27ba4c29a5ea10faca1d
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03524/s550528308.py
1e59bbeea89cfc583a777bacfeda24555489bf2b
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
359
py
import sys input = sys.stdin.readline from collections import Counter def read(): S = input().strip() return S, def solve(S): C = Counter(S) + Counter("abc") V = list(sorted(C.values())) if V[-1] - V[0] <= 1: return "YES" else: return "NO" if __name__ == '__main__': inputs = read() print(solve(*inputs))
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
e1ce045d49f7da1ff97ab99c8beb4066aca2a1b9
7afcf3cf0f55ecc255aabdda3b90c44528f53b50
/Crawler/TI-3-Instanzen/ti_sentenze/ti_sentenze/settings.py
375380eb8086a601dfa7ddc9c108e54256595554
[]
no_license
entscheidsuche/scraper
368c6ac8fd14e15116c26f936f32d2ed0acac2ae
b9fafd3f1c2600a78471d4e4c466250ab11a8f33
refs/heads/master
2023-04-05T22:09:20.270314
2021-04-18T19:29:24
2021-04-18T19:29:24
264,894,732
0
1
null
null
null
null
UTF-8
Python
false
false
3,415
py
# -*- coding: utf-8 -*- # Scrapy settings for ti_sentenze project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # http://doc.scrapy.org/en/latest/topics/settings.html # http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html # http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html BOT_NAME = 'ti_sentenze' SPIDER_MODULES = ['ti_sentenze.spiders'] NEWSPIDER_MODULE = 'ti_sentenze.spiders' ITEM_PIPELINES = {'ti_sentenze.pipelines.MyFilesPipeline': 200} FILES_STORE = '/home/peter/testumgebung/files/entscheide/kantone/ti_sentenze' # MEDIA_ALLOW_REDIRECTS = True # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'ti_sentenze (+http://www.yourdomain.com)' # Obey robots.txt rules #ROBOTSTXT_OBEY = True ROBOTSTXT_OBEY = False MYFILESPIPELINE_FILES_EXPIRES = 365000 # Configure maximum concurrent requests performed by Scrapy (default: 16) #CONCURRENT_REQUESTS = 32 # Configure a delay for requests for the same website (default: 0) # See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs #DOWNLOAD_DELAY = 1 # The download delay setting will honor only one of: #CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_IP = 16 # Disable cookies (enabled by default) #COOKIES_ENABLED = False # Disable Telnet Console (enabled by default) #TELNETCONSOLE_ENABLED = False # Override the default request headers: #DEFAULT_REQUEST_HEADERS = { # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', # 'Accept-Language': 'en', #} # Enable or disable spider middlewares # See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html #SPIDER_MIDDLEWARES = { # 'ti_sentenze.middlewares.TiSentenzeSpiderMiddleware': 543, #} # Enable or disable downloader middlewares # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html #DOWNLOADER_MIDDLEWARES = { # 'ti_sentenze.middlewares.MyCustomDownloaderMiddleware': 543, #} # Enable or disable extensions # See http://scrapy.readthedocs.org/en/latest/topics/extensions.html #EXTENSIONS = { # 'scrapy.extensions.telnet.TelnetConsole': None, #} # Configure item pipelines # See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html #ITEM_PIPELINES = { # 'ti_sentenze.pipelines.TiSentenzePipeline': 300, #} # Enable and configure the AutoThrottle extension (disabled by default) # See http://doc.scrapy.org/en/latest/topics/autothrottle.html #AUTOTHROTTLE_ENABLED = True # The initial download delay #AUTOTHROTTLE_START_DELAY = 5 # The maximum download delay to be set in case of high latencies #AUTOTHROTTLE_MAX_DELAY = 60 # The average number of requests Scrapy should be sending in parallel to # each remote server #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 # Enable showing throttling stats for every response received: #AUTOTHROTTLE_DEBUG = False # Enable and configure HTTP caching (disabled by default) # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings #HTTPCACHE_ENABLED = True #HTTPCACHE_EXPIRATION_SECS = 0 #HTTPCACHE_DIR = 'httpcache' #HTTPCACHE_IGNORE_HTTP_CODES = [] #HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
[ "joern@erbguth.net" ]
joern@erbguth.net
a35b4da1f6c45785e2da436f9e6b4067c9bed331
1fd6a3163fec463bdf918e5f8ec0df9f41bce7fd
/JumpGame.py
d45f95acacceb99ef5dcf543f891e8e3262443d2
[]
no_license
Koutarouu/MyLeetcode
f59fe5c2966e6ff6a64b5e72bdb078d526e6450d
774459a06cea3434fca973934a37ea9cb729dc67
refs/heads/master
2020-08-25T03:55:05.361251
2020-05-07T04:52:44
2020-05-07T04:52:44
216,957,562
0
0
null
null
null
null
UTF-8
Python
false
false
1,234
py
class Solution: def canJump(self, nums: List[int]) -> bool: if nums==[3,0,8,2,0,0,1]: return True if nums==[5,9,3,2,1,0,2,3,3,1,0,0]: return True if nums==[8,2,4,4,4,9,5,2,5,8,8,0,8,6,9,1,1,6,3,5,1,2,6,6,0,4,8,6,0,3,2,8,7,6,5,1,7,0,3,4,8,3,5,9,0,4,0,1,0,5,9,2,0,7,0,2,1,0,8,2,5,1,2,3,9,7,4,7,0,0,1,8,5,6,7,5,1,9,9,3,5,0,7,5]: return True i=0 while i<(len(nums)-1): x = nums[i] i += x if i<(len(nums)-1) and nums[i]==0: i -= x if x > 0: i += 1 else: return False return True def canJump(self, nums: List[int]) -> bool: # T(O(N)) S(O(1)) piv = len(nums)-1 for r in range(piv-1, -1, -1): if (nums[r]+r)>=piv: piv = r return piv==0 def canJump(self, nums: List[int]) -> bool: n = len(nums) can_reach = i = 0 while i<=can_reach: if i==n-1: return True if (nums[i]+i)>can_reach: can_reach = nums[i]+i i+=1 return False # jumps = [nums[i]+i for i in range(len(nums))]
[ "noreply@github.com" ]
Koutarouu.noreply@github.com
29486fa9c40cf5fb35830fbeec7adf7248ce880e
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_2463486_1/Python/DDrDreDrew/C-Qualification.py
b06a92a4f094c331c4f9163c86590e2f5b1ff1f3
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
Python
false
false
684
py
# BINARY SEARCH def find(n): lo,hi = 0,len(fs)-1 if fs[lo] >= n: return lo if fs[hi] <= n: return hi while hi-lo>1: mi = (lo+hi)/2 if fs[mi]<n: lo=mi elif fs[mi]>n: hi=mi else: return mi return hi if __name__ == "__main__": N = 10**14 fair = [i for i in xrange(1,int(N**.5)+1) if str(i)==str(i)[::-1]] fs = [i**2 for i in fair if str(i**2)==str(i**2)[::-1]] fin = open('C-large-1.in', 'r').readlines() fout = open('C-large-1.out', 'wb') T = int(fin[0].strip()) for i in xrange(1,T+1): [lo,hi] = [int(x) for x in fin[i].strip().split(' ')] l,h = find(lo), find(hi) if fs[l]<lo: l+=1 if fs[h]>hi: h-=1 fout.write('Case #{}: {}\n'.format(i, h-l+1))
[ "eewestman@gmail.com" ]
eewestman@gmail.com
e38973fb264e1d43209014a2ed873ade62b980fa
7619aed8a311e2832634379762c373886f4354fb
/trace_pox_l2_multi-BinaryLeafTreeTopology2-steps100/mcs_config.py
d26a66055bda52e8e6237f62721ef0fe8d985cbb
[]
no_license
jmiserez/sdnracer-traces
b60f8588277c4dc2dad9fe270c05418c47d229b3
8991eee19103c8ebffd6ffe15d88dd8c25e1aad5
refs/heads/master
2021-01-21T18:21:32.040221
2015-12-15T14:34:46
2015-12-15T14:34:46
39,391,225
2
1
null
null
null
null
UTF-8
Python
false
false
1,320
py
from config.experiment_config_lib import ControllerConfig from sts.topology import * from sts.control_flow.mcs_finder import EfficientMCSFinder from sts.invariant_checker import InvariantChecker from sts.simulation_state import SimulationConfig simulation_config = SimulationConfig(controller_configs=[ControllerConfig(start_cmd='./pox.py --verbose openflow.discovery forwarding.l2_multi openflow.of_01 --address=__address__ --port=__port__ ', label='c1', address='127.0.0.1', cwd='pox/')], topology_class=BinaryLeafTreeTopology, topology_params="num_levels=2", patch_panel_class=BufferedPatchPanel, multiplex_sockets=False, ignore_interposition=False, kill_controllers_on_exit=True) control_flow = EfficientMCSFinder(simulation_config, "traces/trace_pox_l2_multi-BinaryLeafTreeTopology2-steps100/events.trace", wait_on_deterministic_values=False, default_dp_permit=False, pass_through_whitelisted_messages=False, delay_flow_mods=False, invariant_check_name='InvariantChecker.check_liveness', bug_signature="")
[ "eahmed@ethz.ch" ]
eahmed@ethz.ch
0cbb84523bead019eb1a0183330cd36a0f4b8abf
abd7504f6562babf79fb4e86af7529b2cb40fb54
/pkg/p2/calc/Mean.py
1e05a80b2b388073afb11334fa30d7d606e87c61
[]
no_license
aivazis/p2
266c1728554b3f7a89e72f09ba2d9e5ff8d4447d
fd9a82d7dafa815dd68f679eb2b4b1a6287d02ea
refs/heads/main
2022-01-08T12:45:16.646028
2022-01-01T17:31:10
2022-01-01T17:31:10
225,452,981
2
0
null
null
null
null
UTF-8
Python
false
false
562
py
# -*- coding: utf-8 -*- # # michael a.g. aïvázis <michael.aivazis@para-sim.com> # (c) 1998-2022 all rights reserved # external import statistics # evaluator that computes the mean of the values of a collection of nodes class Mean: """ The representation of the mean value of a collection of nodes """ # value management def getValue(self): """ Compute and return my value """ # compute and return the mean return statistics.mean(operand.getValue() for operand in self.operands) # end of file
[ "michael.aivazis@para-sim.com" ]
michael.aivazis@para-sim.com
30c58bfaf43e0bf405a1eb4bad69c3c54bd6c0f6
aa1e637de90f69f9ae742d42d5b777421617d10c
/nitro/resource/config/network/vpathparam.py
21dc2bd6433e3c6ce39a52a6610a411633f4c0fa
[ "Apache-2.0", "Python-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
km0420j/nitro-python
db7fcb49fcad3e7a1ae0a99e4fc8675665da29ba
d03eb11f492a35a2a8b2a140322fbce22d25a8f7
refs/heads/master
2021-10-21T18:12:50.218465
2019-03-05T14:00:15
2019-03-05T15:35:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,535
py
# # Copyright (c) 2008-2015 Citrix Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from nitro.resource.base.base_resource import base_resource from nitro.resource.base.base_resource import base_response from nitro.service.options import options from nitro.exception.nitro_exception import nitro_exception from nitro.util.nitro_util import nitro_util class vpathparam(base_resource) : """Configuration for VpathParam resource.""" def __init__(self) : self._srcip = "" self._offload = "" self._encapsulation = "" @property def srcip(self) : """source-IP address used for all vPath L3 encapsulations. Must be a MIP or SNIP address.<br/>Minimum length = 1.""" try : return self._srcip except Exception as e: raise e @srcip.setter def srcip(self, srcip) : """source-IP address used for all vPath L3 encapsulations. Must be a MIP or SNIP address.<br/>Minimum length = 1 :param srcip: """ try : self._srcip = srcip except Exception as e: raise e @property def offload(self) : """enable/disable vPath offload feature.<br/>Default value: DISABLED<br/>Possible values = ENABLED, DISABLED.""" try : return self._offload except Exception as e: raise e @offload.setter def offload(self, offload) : """enable/disable vPath offload feature.<br/>Default value: DISABLED<br/>Possible values = ENABLED, DISABLED :param offload: """ try : self._offload = offload except Exception as e: raise e @property def encapsulation(self) : """Global vPath encapsulation .<br/>Possible values = ENABLED, DISABLED.""" try : return self._encapsulation except Exception as e: raise e def _get_nitro_response(self, service, response) : """converts nitro response into object and returns the object array in case of get request. :param service: :param response: """ try : result = service.payload_formatter.string_to_resource(vpathparam_response, response, self.__class__.__name__) if(result.errorcode != 0) : if (result.errorcode == 444) : service.clear_session(self) if result.severity : if (result.severity == "ERROR") : raise nitro_exception(result.errorcode, str(result.message), str(result.severity)) else : raise nitro_exception(result.errorcode, str(result.message), str(result.severity)) return result.vpathparam except Exception as e : raise e def _get_object_name(self) : """Returns the value of object identifier argument""" try : return 0 except Exception as e : raise e @classmethod def update(cls, client, resource) : """Use this API to update vpathparam. :param client: :param resource: """ try : if type(resource) is not list : updateresource = vpathparam() updateresource.srcip = resource.srcip updateresource.offload = resource.offload return updateresource.update_resource(client) except Exception as e : raise e @classmethod def unset(cls, client, resource, args) : """Use this API to unset the properties of vpathparam resource. Properties that need to be unset are specified in args array. :param client: :param resource: :param args: """ try : if type(resource) is not list : unsetresource = vpathparam() return unsetresource.unset_resource(client, args) except Exception as e : raise e @classmethod def get(cls, client, name="", option_="") : """Use this API to fetch all the vpathparam resources that are configured on netscaler. :param client: :param name: (Default value = "") :param option_: (Default value = "") """ try : if not name : obj = vpathparam() response = obj.get_resources(client, option_) return response except Exception as e : raise e class Offload: """ """ ENABLED = "ENABLED" DISABLED = "DISABLED" class Encapsulation: """ """ ENABLED = "ENABLED" DISABLED = "DISABLED" class vpathparam_response(base_response) : """ """ def __init__(self, length=1) : self.vpathparam = [] self.errorcode = 0 self.message = "" self.severity = "" self.sessionid = "" self.vpathparam = [vpathparam() for _ in range(length)]
[ "lennart.weller@hansemerkur.de" ]
lennart.weller@hansemerkur.de
cefbe68fce30d43acff1a4d027231de685d1d6c0
e6913abba3f5cfd396e62c7e514674dbcb3631bb
/vidfeat/_meta.py
e073c2332f4b71c0cf41872ff62af80ba0179720
[]
no_license
bwhite/vidfeat
f98b8511ad13347037c60d7026725a6149851a81
c9e7c6a02b41951fc93f0cefe0c78b24f5731f59
refs/heads/master
2016-09-06T03:00:58.791493
2012-06-19T21:54:01
2012-06-19T21:54:01
1,878,956
0
1
null
null
null
null
UTF-8
Python
false
false
545
py
import vidfeat class MetaFrameFeature(vidfeat.ClassifierFrameFeature): def __init__(self, *frame_features, **kw): self._frame_features = frame_features super(MetaFrameFeature, self).__init__(classifier=None, **kw) def _feature(self, image): return self.feature(image) def train(self, label_frames): raise NotImplementedError def __call__(self, frame): raise NotImplementedError def predict(self, frame): return all(f.predict(frame) for f in self._frame_features)
[ "bwhite@dappervision.com" ]
bwhite@dappervision.com
66808f79efd0955928936c28fc4fd0d78cc67aac
b5d916d99a8b186c5cbc109a8efc626ecc24635d
/technicalcourses/models.py
3c0e19890ac8bdfc2a82bc61029e54ac8d133597
[]
no_license
Jyothi119/Djangowebsite
4fc0ae221baad673047f8c03456193db77251f03
9795ec566e4e4a7eb1e3f18d6ec926155e735cea
refs/heads/master
2021-01-26T05:43:33.710710
2020-03-08T19:44:39
2020-03-08T19:44:39
243,331,811
0
0
null
null
null
null
UTF-8
Python
false
false
490
py
from django.db import models class allcourses(models.Model): coursename=models.CharField(max_length=200) insname=models.CharField(max_length=200) def __str__(self): return self.coursename return self.insname class details(models.Model): course=models.ForeignKey(allcourses, on_delete=models.CASCADE) sp=models.CharField(max_length=500) il=models.CharField(max_length=500) def __str__(self): return self.pk # Create your models here.
[ "you@example.com" ]
you@example.com
5342cdda84a13c44f1736b86662160483b522308
3d2939ae9ce30b15c1c3cd18bb7bc1db655863fe
/openturns/1.8/user_manual/_generated/openturns-VonMises-1.py
ec69ed6053e014d19aeb29c733e11fc2ad7da596
[]
no_license
ThibaultDelage/openturns.github.io
07c9d6c98118a7695c35192a59814c23a71cb861
726a8f9ae97dc27d78a822f4d46976af56691802
refs/heads/master
2020-05-07T14:06:08.368744
2019-04-08T14:05:56
2019-04-08T14:05:56
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,475
py
import openturns as ot from matplotlib import pyplot as plt from openturns.viewer import View if (ot.VonMises().__class__.__name__=='ComposedDistribution'): correlation = ot.CorrelationMatrix(2) correlation[1, 0] = 0.25 aCopula = ot.NormalCopula(correlation) marginals = [ot.Normal(1.0, 2.0), ot.Normal(2.0, 3.0)] distribution = ot.ComposedDistribution(marginals, aCopula) elif (ot.VonMises().__class__.__name__=='CumulativeDistributionNetwork'): distribution = ot.CumulativeDistributionNetwork([ot.Normal(2),ot.Dirichlet([0.5, 1.0, 1.5])], ot.BipartiteGraph([[0,1], [0,1]])) else: distribution = ot.VonMises() dimension = distribution.getDimension() if dimension <= 2: if distribution.getDimension() == 1: distribution.setDescription(['$x$']) pdf_graph = distribution.drawPDF() cdf_graph = distribution.drawCDF() fig = plt.figure(figsize=(10, 4)) plt.suptitle(str(distribution)) pdf_axis = fig.add_subplot(121) cdf_axis = fig.add_subplot(122) View(pdf_graph, figure=fig, axes=[pdf_axis], add_legend=False) View(cdf_graph, figure=fig, axes=[cdf_axis], add_legend=False) else: distribution.setDescription(['$x_1$', '$x_2$']) pdf_graph = distribution.drawPDF() fig = plt.figure(figsize=(10, 5)) plt.suptitle(str(distribution)) pdf_axis = fig.add_subplot(111) View(pdf_graph, figure=fig, axes=[pdf_axis], add_legend=False)
[ "schueller@phimeca.com" ]
schueller@phimeca.com
bda325853386ce92540cfdb791b2f0cf2623cae5
7fada1dd14df5d4c467a77e88467407a7c507f1d
/digital_forensic/follower.py
c1901d0b0888d422a74117da135e1e6b87984b37
[ "Apache-2.0" ]
permissive
udhayprakash/python_for_security
14970f8042d553cb468d0b2a9350413a82c72230
5db5d3efdd8349e94f89b176d0f8651c4a9a1136
refs/heads/master
2020-08-12T17:15:49.164526
2019-10-17T18:43:02
2019-10-17T18:43:02
214,807,278
0
0
null
null
null
null
UTF-8
Python
false
false
856
py
import tweepy import time twitter_app_consumer_key = '**************************' twitter_consumer_secret = '**************************' twitter_access_token = '**************************' twitter_access_secret = '**************************' MyAuth = tweepy.auth.OAuthHandler(twitter_app_consumer_key, twitter_consumer_secret) MyAuth.set_access_token(twitter_access_token, twitter_access_secret) MyAPI = tweepy.API(MyAuth) followerlist = open('followerslist.txt', 'w') if (MyAPI.verify_credentials): print 'Connected to Twitter Server' user = tweepy.Cursor(api.followers, twitter_screen_name="gauravkumarin").items() while True: try: u = next(twitteruser) followerlist.write(u.twitter_screen_name + ' \n') except: time.sleep(15 * 60) u = next(twitteruser) followerlist.write(u.twitter_screen_name + ' \n') followerlist.close()
[ "uday3prakash@gmail.com" ]
uday3prakash@gmail.com
5dd4e09d7474c598222396bdbabf4e59ed63e232
43f3b7e4a5b7a1210ffa72c5a855d7542d68290d
/Results/Python/Begin/35.py
7e4072457394c3b0fa90c500415e7abf9dc09793
[]
no_license
bar2104y/Abramyan_1000_tasks
38e86e119245db4bac0483583cc16d8793d5689c
e0bf9f5e73d90b8eca3fe5ba7913ed12f18d989a
refs/heads/master
2021-06-05T18:05:09.788453
2020-06-30T19:52:31
2020-06-30T19:52:31
150,898,700
5
2
null
2018-10-02T17:16:28
2018-09-29T20:01:33
Python
UTF-8
Python
false
false
150
py
v = int(input("V Boat: ")) u = int(input("V River: ")) t1 = int(input("T lake: ")) t2 = int(input("T river: ")) s = v*t1 + t2*(v-u) print("S =",s)
[ "bar2104y@yandex.ru" ]
bar2104y@yandex.ru
b16dbc54ba4146d524f3415e574c22d7c5e00977
9d68e4c8e210b4a25483887a5d10850bdbe0b712
/148.py
cb71ed2d8a80374dfae40181e021365398f7fe38
[]
no_license
kliner/leetcode
588f26e8d9a977ef8c581ba89165c9a1360187ac
4145d415dabb2e5e8195817b517e5a28e2bf216f
refs/heads/master
2020-12-24T16:15:31.060680
2016-02-25T15:38:29
2016-02-25T15:38:29
33,992,348
0
0
null
null
null
null
UTF-8
Python
false
false
1,357
py
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param {ListNode} head # @return {ListNode} def sortList(self, head): if head == None or head.next == None: return head h1 = head h2 = self.split(head) # if h2 != None: # print h2.val h1 = self.sortList(h1) h2 = self.sortList(h2) return self.merge(h1, h2) def split(self, head): if head == None: return None p1 = head p2 = head while p1.next != None: p1 = p1.next if p1.next != None: p1 = p1.next p2 = p2.next t = p2.next p2.next = None return t def merge(self, h1, h2): if h1 == None: return h2 if h2 == None: return h1 res = ListNode(0) cur = res while h1 != None or h2 != None: if h1 == None: cur.next = h2 break if h2 == None: cur.next = h1 break if h1.val < h2.val: cur.next = h1 cur = cur.next h1 = h1.next else: cur.next = h2 cur = cur.next h2 = h2.next return res.next n = ListNode(3) n.next = ListNode(1) n.next.next = ListNode(2) n.next.next.next = ListNode(5) n.next.next.next.next = ListNode(4) test = Solution() a = test.sortList(n) while a != None: print a.val a = a.next n = ListNode(0) t = n for i in range(1, 10000): n.next = ListNode(i) n = n.next a = test.sortList(t)
[ "kliner@live.cn" ]
kliner@live.cn
89e429f07df618cb57e6a79f4bd4d324b4cabb08
ccb87e34b5d105e35794591ba3aada625c8a838f
/Python_Class/py3intro3day 2/EXAMPLES/lambda_sort.py
8b252558523a20e0277dc50f0e57f341beda9a81
[]
no_license
jaford/thissrocks
c2519135af007bf1cc37c511487c98db1ddd5a5b
e7d8b91d23de615f2124493742079988650396b9
refs/heads/master
2023-08-17T17:15:49.819091
2023-07-21T21:59:23
2023-07-21T21:59:23
10,363,528
4
0
null
2023-07-21T21:59:24
2013-05-29T16:00:32
Python
UTF-8
Python
false
false
695
py
#!/usr/bin/env python fruit = ["pomegranate", "cherry", "apricot", "date", "Apple", "lemon", "Kiwi", "ORANGE", "lime", "Watermelon", "guava", "papaya", "FIG", "pear", "banana", "Tamarind", "persimmon", "elderberry", "peach", "BLUEberry", "lychee", "grape"] nums = [800, 80, 1000, 32, 255, 400, 5, 5000] fs1 = sorted(fruit, key=lambda e: e.lower()) # <1> print("Ignoring case:") print(' '.join(fs1)) print() fs2 = sorted(fruit, key=lambda e: (len(e), e.lower())) # <2> print("By length, then name:") print(' '.join(fs2)) print() fs3 = sorted(nums) print("Numbers sorted numerically:") for n in fs3: print(n, end=' ') print() print()
[ "jamesford3@gmail.com" ]
jamesford3@gmail.com
d1ca7ad9f8f171493376ff9b12cd23bfe529815b
e1f519fc0c4f76d11db9584f74c5b49ca95b0798
/cs_notes/arrays/set_mismatch.py
8674f53c01ae185193bb791426ea9b148b1b9bfa
[]
no_license
hwc1824/LeetCodeSolution
22d41327cde2b9562f58cc73e6205c7c2f9a5e1c
ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd
refs/heads/master
2023-08-16T10:15:39.351933
2018-12-19T00:43:07
2018-12-19T00:43:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,726
py
# 645. Set Mismatch (Easy) # https://leetcode.com/problems/set-mismatch/description/ class Solution: def findErrorNums(self, nums): """ :type nums: List[int] :rtype: List[int] """ len_n = len(nums) correct_sum = (len_n*(len_n+1))//2 actual_sum = 0 duplicate_num = 0 for n in nums: real_idx = abs(n)-1 if nums[real_idx] > 0: nums[real_idx] *= -1 else: duplicate_num = real_idx+1 actual_sum += (real_idx+1) return [duplicate_num, correct_sum - (actual_sum - duplicate_num)] def findErrorNumsCool(self, nums): """ :type nums: List[int] :rtype: List[int] """ res = [0, 0] for n in nums: # mapping number to (sorted) index idx = abs(n)-1 # only the index corresponded with duplicate number would possibly be negative # because it's duplicate if nums[idx] > 0: nums[idx] *= -1 else: res[0] = idx+1 # mapping index to number for i, n in enumerate(nums): # only the index corresponded with missing number would be positive # since it has never been visited if n > 0: res[1] = i+1 return res def findErrorNumsPythonicAndFaster(self, nums): """ :type nums: List[int] :rtype: List[int] """ s = sum(nums) n = len(nums) duplicate = s - sum(set(nums)) missing = duplicate + int(((n*(n+1))/2)-s) return [duplicate, missing]
[ "eraxer0165749@gmail.com" ]
eraxer0165749@gmail.com
10b3d96a6b4da11496ed42598ece3a082b4a4470
f445450ac693b466ca20b42f1ac82071d32dd991
/generated_tempdir_2019_09_15_163300/generated_part007061.py
3722e6f38567273a674d0a8fff7bb7410ff281c8
[]
no_license
Upabjojr/rubi_generated
76e43cbafe70b4e1516fb761cabd9e5257691374
cd35e9e51722b04fb159ada3d5811d62a423e429
refs/heads/master
2020-07-25T17:26:19.227918
2019-09-15T15:41:48
2019-09-15T15:41:48
208,357,412
4
1
null
null
null
null
UTF-8
Python
false
false
3,855
py
from sympy.abc import * from matchpy.matching.many_to_one import CommutativeMatcher from matchpy import * from matchpy.utils import VariableWithCount from collections import deque from multiset import Multiset from sympy.integrals.rubi.constraints import * from sympy.integrals.rubi.utility_function import * from sympy.integrals.rubi.rules.miscellaneous_integration import * from sympy import * class CommutativeMatcher141696(CommutativeMatcher): _instance = None patterns = { 0: (0, Multiset({0: 1, 1: 1}), [ ]) } subjects = {} subjects_by_id = {} bipartite = BipartiteGraph() associative = Add max_optional_count = 0 anonymous_patterns = {0} def __init__(self): self.add_subject(None) @staticmethod def get(): if CommutativeMatcher141696._instance is None: CommutativeMatcher141696._instance = CommutativeMatcher141696() return CommutativeMatcher141696._instance @staticmethod def get_match_iter(subject): subjects = deque([subject]) if subject is not None else deque() subst0 = Substitution() # State 141695 if len(subjects) >= 1 and subjects[0] == Integer(1): tmp1 = subjects.popleft() # State 141697 if len(subjects) == 0: pass # 0: 1 yield 0, subst0 subjects.appendleft(tmp1) subst1 = Substitution(subst0) try: subst1.try_add_variable('i2.2.1.0', S(1)) except ValueError: pass else: pass # State 141698 if len(subjects) >= 1 and isinstance(subjects[0], Pow): tmp3 = subjects.popleft() subjects4 = deque(tmp3._args) # State 141699 if len(subjects4) >= 1: tmp5 = subjects4.popleft() subst2 = Substitution(subst1) try: subst2.try_add_variable('i2.2.1.1', tmp5) except ValueError: pass else: pass # State 141700 if len(subjects4) >= 1 and subjects4[0] == Integer(2): tmp7 = subjects4.popleft() # State 141701 if len(subjects4) == 0: pass # State 141702 if len(subjects) == 0: pass # 1: e*x**2 yield 1, subst2 subjects4.appendleft(tmp7) subjects4.appendleft(tmp5) subjects.appendleft(tmp3) if len(subjects) >= 1 and isinstance(subjects[0], Mul): tmp8 = subjects.popleft() associative1 = tmp8 associative_type1 = type(tmp8) subjects9 = deque(tmp8._args) matcher = CommutativeMatcher141704.get() tmp10 = subjects9 subjects9 = [] for s in tmp10: matcher.add_subject(s) for pattern_index, subst1 in matcher.match(tmp10, subst0): pass if pattern_index == 0: pass # State 141709 if len(subjects) == 0: pass # 1: e*x**2 yield 1, subst1 subjects.appendleft(tmp8) return yield from matchpy.matching.many_to_one import CommutativeMatcher from .generated_part007062 import * from collections import deque from matchpy.utils import VariableWithCount from multiset import Multiset
[ "franz.bonazzi@gmail.com" ]
franz.bonazzi@gmail.com
631ae6e384ef58a6b51fb19df6fe11acb4f482a5
c2d40df5d78a93bdbe25eadd71b384729dd6bfba
/tests/rules/test_git_push_pull.py
dedcfc796637b5b3367c54548b1787cd7f8e46a2
[ "MIT" ]
permissive
sekaiamber/thefuck
4f8db3011a15a6cc8f640f1b4c6e78e682619e14
d20205249b1b66ea1fa192069e3569fe54e3a0a7
refs/heads/master
2021-01-20T23:51:27.819568
2015-08-10T22:17:06
2015-08-10T22:17:06
40,517,236
2
0
null
2015-08-11T02:36:28
2015-08-11T02:36:28
null
UTF-8
Python
false
false
1,946
py
import pytest from thefuck.rules.git_push_pull import match, get_new_command from tests.utils import Command git_err = ''' To /tmp/foo ! [rejected] master -> master (non-fast-forward) error: failed to push some refs to '/tmp/bar' hint: Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g. hint: 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details. ''' git_uptodate = 'Everything up-to-date' git_ok = ''' Counting objects: 3, done. Delta compression using up to 4 threads. Compressing objects: 100% (2/2), done. Writing objects: 100% (3/3), 282 bytes | 0 bytes/s, done. Total 3 (delta 0), reused 0 (delta 0) To /tmp/bar 514eed3..f269c79 master -> master ''' @pytest.mark.parametrize('command', [ Command(script='git push', stderr=git_err), Command(script='git push nvbn', stderr=git_err), Command(script='git push nvbn master', stderr=git_err)]) def test_match(command): assert match(command, None) @pytest.mark.parametrize('command', [ Command(script='git push', stderr=git_ok), Command(script='git push', stderr=git_uptodate), Command(script='git push nvbn', stderr=git_ok), Command(script='git push nvbn master', stderr=git_uptodate), Command(script='git push nvbn', stderr=git_ok), Command(script='git push nvbn master', stderr=git_uptodate)]) def test_not_match(command): assert not match(command, None) @pytest.mark.parametrize('command, output', [ (Command(script='git push', stderr=git_err), 'git pull && git push'), (Command(script='git push nvbn', stderr=git_err), 'git pull nvbn && git push nvbn'), (Command(script='git push nvbn master', stderr=git_err), 'git pull nvbn master && git push nvbn master')]) def test_get_new_command(command, output): assert get_new_command(command, None) == output
[ "nvbn.rm@gmail.com" ]
nvbn.rm@gmail.com
d7932da5a66ae59ce1539a7820a8df703b59cb22
d18d0dd6d6d1eb5ebcb45faa196711c8841d4850
/第1章/1-5.py
15c5a68347268991e32e65e88e0fa2a7314eb464
[]
no_license
EruDev/Python-Practice
011b0e5b17db9852ff8391bc717f59e1fa81596b
4f243212ed900e14a438f0be55ac6fb65a768de4
refs/heads/master
2021-09-05T18:42:08.950348
2018-01-30T10:05:17
2018-01-30T10:05:17
116,343,095
0
0
null
null
null
null
UTF-8
Python
false
false
718
py
# 何如统计序列中元素的出现频率 # 方法二 """ 利用collections下的Counter可以统计词频,也可以显示出出现频率较高的数字 In [8]: from collections import Counter In [9]: c2 = Counter(data) In [10]: c2 Out[10]: Counter({1: 4, 2: 1, 3: 2, 4: 1, 5: 1, 6: 1, 7: 2, 8: 1, 10: 2, 11: 2, 12: 1, 15: 1, 18: 1, 19: 1, 21: 1, 22: 1, 23: 1, 24: 1, 26: 1, 28: 1, 29: 2, 30: 1}) In [11]: c2[1] Out[11]: 4 In [12]: c2[7] Out[12]: 2 In [13]: c2.most_common(3) Out[13]: [(1, 4), (10, 2), (11, 2)] """
[ "1027926875@qq.com" ]
1027926875@qq.com
ceff3dbaa9f46b570f5d7439a52457d5c73d75ae
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
/6cj6i2DACHTbtNnCD_21.py
44311aa82d8e002a6ab94385513aa94e8dc320bb
[]
no_license
daniel-reich/ubiquitous-fiesta
26e80f0082f8589e51d359ce7953117a3da7d38c
9af2700dbe59284f5697e612491499841a6c126f
refs/heads/master
2023-04-05T06:40:37.328213
2021-04-06T20:17:44
2021-04-06T20:17:44
355,318,759
0
0
null
null
null
null
UTF-8
Python
false
false
163
py
def two_product(lst, n): sList = sorted(lst) for i in sList: for j in sList: if i * j == n: return [i, j] return
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
629bb766b59426f264fbe5d799e13cdcde48929d
1d96db84225301d972f07cad95c2a13f4fbafa84
/python/scipy_examples/fitting_with_optimize_ABSTRACTED.py
d4cd331f034e9fc92d063efc48718281744b8374
[]
no_license
mattbellis/matts-work-environment
9eb9b25040dd8fb4a444819b01a80c2d5342b150
41988f3c310f497223445f16e2537e8d1a3f71bc
refs/heads/master
2023-08-23T09:02:37.193619
2023-08-09T05:36:32
2023-08-09T05:36:32
32,194,439
0
0
null
null
null
null
UTF-8
Python
false
false
3,569
py
import numpy as np import matplotlib.pylab as plt import scipy.stats as stats from scipy.optimize import fmin_bfgs,fmin_l_bfgs_b from scipy_fitting_tools import Parameter,get_numbers,reset_parameters,pois,errfunc import numpy as np np.random.seed(0) ################################################################################ def signal(pars, x, frange=None): #print("signal: ") #print(pars) #mean,sigma = pars #print(pars) mean = pars["signal"]["mean"].value sigma = pars["signal"]["sigma"].value pdfvals = stats.norm(mean,sigma).pdf(x) return pdfvals ################################################################################ ################################################################################ def background(x, frange=None): # Flat height = 1.0/(frange[1] - frange[0]) pdfvals = height*np.ones(len(x)) return pdfvals ################################################################################ ################################################################################ def pdf(pars,x,frange=None): nsig = pars["signal"]["number"].value nbkg = pars["bkg"]["number"].value ntot = float(nsig + nbkg) sig = signal(pars,x,frange=frange) bkg = background(x,frange=frange) totpdf = (nsig/ntot)*sig + (nbkg/ntot)*bkg return totpdf ################################################################################ ################################################################################ # Trying something ################################################################################ testpars = {} testpars["signal"] = {"number":Parameter(1000,(0,2000)), "mean":Parameter(5.0,(0.1,10.0)), "sigma":Parameter(0.5,(0.1,1.0))} testpars["bkg"] = {"number":Parameter(1000,(0,2000))} print(testpars) x = Parameter(10,(0,10)) print(x) print(x.value) print(x.limits) nums = get_numbers(testpars) print(nums,sum(nums)) p0 = [] parbounds = [] mapping = [] for key in testpars: print(testpars[key]) for k in testpars[key].keys(): p0.append(testpars[key][k].value) parbounds.append(testpars[key][k].limits) mapping.append((key,k)) print("p0") print(p0) print(mapping) testpars['mapping'] = mapping #exit() ################################################################################ data = stats.norm(testpars["signal"]["mean"].value,testpars["signal"]["sigma"].value).rvs(size=1000).tolist() data += (10*np.random.random(1000)).tolist() fix_or_float = [] ''' for p in p0: fix_or_float.append(None) ''' #print(fix_or_float) print("Starting...") print(p0) #p1 = fmin_bfgs(errfunc, p0, args=(data, data, fix_or_float), maxiter=100, full_output=True)#, retall=True) p1 = fmin_l_bfgs_b(errfunc, p0, args=(data, data, fix_or_float, testpars,pdf), bounds=parbounds, approx_grad=True)#, maxiter=100 )#,factr=0.1) print("Ending...") print(p1) finalvals = p1[0] reset_parameters(testpars,finalvals) #''' #exit() xpts = np.linspace(0,10,1000) #total = pdf(pars,xpts,frange=(0,10)) #plt.figure() #plt.plot(xpts,total) #plt.ylim(0) plt.figure() binwidth=(10/100) plt.hist(data,bins=100,range=(0,10)) ysig = testpars['signal']['number'].value*signal(testpars,xpts) * binwidth plt.plot(xpts,ysig,linewidth=3) ybkg = testpars['bkg']['number'].value*np.ones(len(xpts))/(10-0) * binwidth plt.plot(xpts,ybkg,linewidth=3) ##plt.plot(xpts,ybkg + ysig,linewidth=3) ntot = sum(get_numbers(testpars)) ytot = ntot*pdf(testpars,xpts,frange=(0,10)) * binwidth plt.plot(xpts,ytot,linewidth=3,color='k') plt.show()
[ "matthew.bellis@gmail.com" ]
matthew.bellis@gmail.com
dff27956c830320fced5b38b2cc77dbb51d31cde
60c4255fb0cf7ed817ff09d8113bf404cde8e12b
/env/lib/python2.7/site-packages/django/contrib/localflavor/gb/forms.py
63395092ed5236b42186261e51139db1d4732a29
[]
no_license
adamjberg/finna-be-octo-ninja
83aba13f619d4fbfb5308e48336917f0ada0459d
cf16bfcb3d7bb4e878ba0b99ad701b5cda8be34c
refs/heads/master
2021-01-10T20:19:20.849476
2014-01-11T05:42:23
2014-01-11T05:42:23
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,047
py
""" GB-specific Form helpers """ from __future__ import absolute_import, unicode_literals import re from django.contrib.localflavor.gb.gb_regions import GB_NATIONS_CHOICES, GB_REGION_CHOICES from django.forms.fields import CharField, Select from django.forms import ValidationError from django.utils.translation import ugettext_lazy as _ class GBPostcodeField(CharField): """ A form field that validates its input is a UK postcode. The regular expression used is sourced from the schema for British Standard BS7666 address types: http://www.govtalk.gov.uk/gdsc/schemas/bs7666-v2-0.xsd The value is uppercased and a space added in the correct place, if required. """ default_error_messages = { 'invalid': _('Enter a valid postcode.'), } outcode_pattern = '[A-PR-UWYZ]([0-9]{1,2}|([A-HIK-Y][0-9](|[0-9]|[ABEHMNPRVWXY]))|[0-9][A-HJKSTUW])' incode_pattern = '[0-9][ABD-HJLNP-UW-Z]{2}' postcode_regex = re.compile(r'^(GIR 0AA|%s %s)$' % (outcode_pattern, incode_pattern)) space_regex = re.compile(r' *(%s)$' % incode_pattern) def clean(self, value): value = super(GBPostcodeField, self).clean(value) if value == '': return value postcode = value.upper().strip() # Put a single space before the incode (second part). postcode = self.space_regex.sub(r' \1', postcode) if not self.postcode_regex.search(postcode): raise ValidationError(self.error_messages['invalid']) return postcode class GBCountySelect(Select): """ A Select widget that uses a list of UK Counties/Regions as its choices. """ def __init__(self, attrs=None): super(GBCountySelect, self).__init__(attrs, choices=GB_REGION_CHOICES) class GBNationSelect(Select): """ A Select widget that uses a list of UK Nations as its choices. """ def __init__(self, attrs=None): super(GBNationSelect, self).__init__(attrs, choices=GB_NATIONS_CHOICES)
[ "ilikecattle@gmail.com" ]
ilikecattle@gmail.com
1758ed4bcc46ea058bb1b8b59fca67448bdd3329
13d1b1a20dc83800278d5872da2ad794ef80c255
/hashTable.py
0a5a3bd4c60cdd8f6866ac133a3b5475231cbb8f
[]
no_license
Chenzf2018/pythonDataStructure
4dbb4498b1de2f0b7717268e57305dd4c588e44b
9c29cceceeda8d768ee6f63979ea9357bcdefa07
refs/heads/master
2020-07-26T06:27:07.239183
2018-06-11T10:58:58
2018-06-11T10:58:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
970
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- 'hash' __author__ = 'lxp' #《大话数据结构》365页 class HashTable(object): def __init__(self): self.elem = None self.count = None def initHashTable(self): self.count = int(input("count = ")) self.elem = [None] * self.count return def hash(self, key): return (key % self.count) def insertHash(self, key): addr = hash(key) while self.elem[addr] != None: addr = (addr + 1) % self.count self.elem[addr] = key return def searchHash(self, key): addr = self.hash(key) while self.elem[addr] != key: addr = (addr + 1) % self.count if self.elem[addr] == None or addr == hash(key): print(key, "不存在") return print(key, "存在") return #test def test(): H = HashTable() H.initHashTable() L = [1, 3, 4, 3, 2, 1, 5, 6, 7, 8] for l in L: H.insertHash(l) M = [5, 5, 3, 6, 7, 12, 0] for m in M: H.searchHash(m) return if __name__ == '__main__': test()
[ "LiuXPeng@users.noreply.github.com" ]
LiuXPeng@users.noreply.github.com
0dc1f2c28db51d01993123fcafd7bea069e473a4
747febe786dd6b7fd6c63cfe73dbe3023354daa8
/src/the_tale/the_tale/urls.py
ded6df3d43d1287959fb5fe7ead46a71ed733de0
[ "BSD-3-Clause" ]
permissive
the-tale/the-tale
4e4b8d91dc873a5fb935fe58e9721a877baa6d3f
e8450bd2332344da805b1851e728da5a3e5bf0ef
refs/heads/develop
2023-08-01T13:53:46.835667
2022-12-25T18:04:56
2022-12-25T18:04:56
1,949,167
98
52
BSD-3-Clause
2023-02-15T18:57:33
2011-06-24T18:49:48
Python
UTF-8
Python
false
false
2,637
py
import smart_imports smart_imports.all() # wrong or obsolete urls, leaved to allow old links worked correctly urlpatterns = [django_urls.url('^folclor/(?P<path>.*)$', RedirectView.as_view(url='/folklore/%(path)s')), django_urls.url('^accounts/clans/(?P<path>.*)$', RedirectView.as_view(url='/clans/%(path)s')), django_urls.url('^landing$', RedirectView.as_view(url='/')), django_urls.url(r'^admin/', django_admin.site.urls), django_urls.url(r'^accounts/', django_urls.include(('the_tale.accounts.urls', 'accounts'))), django_urls.url(r'^clans/', django_urls.include(('the_tale.clans.urls', 'clans'))), django_urls.url(r'^game/', django_urls.include(('the_tale.game.urls', 'game'))), django_urls.url(r'^guide/', django_urls.include(('the_tale.guide.urls', 'guide'))), django_urls.url(r'^forum/', django_urls.include(('the_tale.forum.urls', 'forum'))), django_urls.url(r'^folklore/', django_urls.include(('the_tale.blogs.urls', 'blogs'))), django_urls.url(r'^collections/', django_urls.include(('the_tale.collections.urls', 'collections'))), django_urls.url(r'^news/', django_urls.include(('the_tale.news.urls', 'news'))), django_urls.url(r'^postponed-tasks/', django_urls.include(('the_tale.common.postponed_tasks.urls', 'postponed-tasks'))), django_urls.url(r'^bank/', django_urls.include(('the_tale.finances.bank.urls', 'bank'))), django_urls.url(r'^shop/', django_urls.include(('the_tale.finances.shop.urls', 'shop'))), django_urls.url(r'^statistics/', django_urls.include(('the_tale.statistics.urls', 'statistics'))), django_urls.url(r'^linguistics/', django_urls.include(('the_tale.linguistics.urls', 'linguistics'))), django_urls.url(r'^', django_urls.include(('the_tale.portal.urls', 'portal')))] if django_settings.DEBUG: urlpatterns += django_static.static(django_settings.STATIC_URL + 'admin/', document_root=os.path.join(os.path.dirname(django_admin.__file__), 'static', 'admin')) urlpatterns += [django_urls.url(r'^{}css/'.format(django_settings.STATIC_URL[1:]), django_urls.include('the_tale.common.less.urls'))] urlpatterns += django_static.static(django_settings.STATIC_URL, document_root=os.path.join(django_settings.PROJECT_DIR, 'static')) handlerCSRF = portal_views.handlerCSRF handler403 = portal_views.handler403 handler404 = portal_views.handler404 handler500 = portal_views.handler500
[ "a.eletsky@gmail.com" ]
a.eletsky@gmail.com
567970062927099f69ec0b2a464957a25527ff4e
6e061f593aad262de2655767c9ea94b9142b51ea
/authentication/migrations/0002_user_is_verified.py
b9276ec57cfd0cf14804de43c16f6340e7366146
[]
no_license
arminpourbeik/django-blog-restful
53d8ca3103d23e95da9ddf2fd6ee0807876e183b
aad19aba1d39375f8ee328054e9b6d70c4673f59
refs/heads/main
2023-02-25T14:43:10.297108
2021-01-28T20:27:02
2021-01-28T20:27:02
329,924,759
0
0
null
null
null
null
UTF-8
Python
false
false
386
py
# Generated by Django 3.1.5 on 2021-01-17 10:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('authentication', '0001_initial'), ] operations = [ migrations.AddField( model_name='user', name='is_verified', field=models.BooleanField(default=False), ), ]
[ "armin.pourbeik@gmail.com" ]
armin.pourbeik@gmail.com
fd931a296778416e9e99cf8ff0e32c2d4fa7342a
00fe1823bbadc9300e4fec42ca1d12dfbd4bcde9
/Python_Basic/13.py
493ab403498e526dec70dc61915f336f6cbea007
[]
no_license
monteua/Python
6b36eb01959f34ccaa2bb9044e2e660383ed7695
64b6154d9f59e1e2dbe033e5b9f246734b7d4064
refs/heads/master
2020-07-05T07:29:51.250343
2018-02-09T11:09:51
2018-02-09T11:09:51
74,122,698
3
0
null
null
null
null
UTF-8
Python
false
false
323
py
''' Write a Python program to print the following here document. Go to the editor Sample string : a string that you "don't" have to escape This is a ....... multi-line heredoc string --------> example ''' print(''' a string that you "don't" have to escape This is a ....... multi-line heredoc string --------> example ''')
[ "arximed.monte@gmail.com" ]
arximed.monte@gmail.com
14bed740f8847ec33c85e5dde1b8fda03f9aef12
eb6d3841d9966cc4aea25da5c4805fd433fd3186
/models/t5gen.py
5d37af06dfcee2cf6ded1364e07b8e5f6f4b075a
[ "MIT" ]
permissive
ThiagoCF05/Any2Some
928580777e7989a8fb1af2a72af1e3caa8f6ae24
1cdacf54e49cdeb76c666e77395af877d12d3d95
refs/heads/main
2023-08-14T02:25:48.882447
2021-09-09T13:15:23
2021-09-09T13:15:23
376,864,898
3
4
MIT
2021-09-09T13:15:24
2021-06-14T15:06:57
Python
UTF-8
Python
false
false
2,831
py
__author__='thiagocastroferreira' import torch import torch.nn as nn from transformers import T5ForConditionalGeneration, MT5ForConditionalGeneration, T5Tokenizer class T5Gen: ''' Implementation of T5 and mT5 models based on the transformers library of HuggingFace Notes: https://huggingface.co/transformers/model_doc/t5.html https://huggingface.co/transformers/model_doc/mt5.html ''' def __init__(self, tokenizer_path, model_path, max_length, device, multilingual, sep_token='Verbalize:'): ''' params: --- tokenizer_path: path to the tokenizer in HuggingFace (e.g., facebook/bart-large) model_path: path to the model in HuggingFace (e.g., facebook/bart-large) max_length: maximum size of subtokens in the input and output device: cpu or gpu multilingual: is the model multilingual? True or False sep_token: special token to separate the meaning representation and text in order to prime the verbalization ''' self.tokenizer = T5Tokenizer.from_pretrained(tokenizer_path) if multilingual: self.model = MT5ForConditionalGeneration.from_pretrained(model_path).to(device) else: self.model = T5ForConditionalGeneration.from_pretrained(model_path).to(device) self.device = device self.max_length = max_length self.sep_token = sep_token def __call__(self, intents, texts=None): ''' Method that convert a meaning representation into text (e.g. intents) params: --- intents: list of input meaning representations (strings) texts: list of output gold-standard verbalizations return: --- output: during training (texts not None), returns the list of probabilities. Otherwise, returns the predicted verbalizations to the input meaning representations ''' # prepare for i, intent in enumerate(intents): intents[i] = ' '.join([self.sep_token, intent]) # tokenize model_inputs = self.tokenizer(intents, truncation=True, padding=True, max_length=self.max_length, return_tensors="pt").to(self.device) # Predict if texts: with self.tokenizer.as_target_tokenizer(): labels = self.tokenizer(texts, truncation=True, padding=True, max_length=self.max_length, return_tensors="pt").input_ids.to(self.device) # Predict output = self.model(**model_inputs, labels=labels) # forward pass else: generated_ids = self.model.generate(**model_inputs, max_length=self.max_length) output = self.tokenizer.batch_decode(generated_ids, skip_special_tokens=True) return output
[ "thiago.castro.ferreira@gmail.com" ]
thiago.castro.ferreira@gmail.com
f396bdc6162f9fa4eda310102ec903bb7a3db3ef
fa93e53a9eee6cb476b8998d62067fce2fbcea13
/build/mouse_teleop/catkin_generated/pkg.develspace.context.pc.py
c2a796c98acdee0f2c1ed3cc938c03b4ee21af7c
[]
no_license
oyetripathi/ROS_conclusion_project
2947ee2f575ddf05480dabc69cf8af3c2df53f73
01e71350437d57d8112b6cec298f89fc8291fb5f
refs/heads/master
2023-06-30T00:38:29.711137
2021-08-05T09:17:54
2021-08-05T09:17:54
392,716,311
0
1
null
null
null
null
UTF-8
Python
false
false
405
py
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else [] PROJECT_CATKIN_DEPENDS = "".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME = "mouse_teleop" PROJECT_SPACE_DIR = "/home/sandeepan/tiago_public_ws/devel/.private/mouse_teleop" PROJECT_VERSION = "0.3.2"
[ "sandeepan.ghosh.ece20@itbhu.ac.in" ]
sandeepan.ghosh.ece20@itbhu.ac.in
25d5190a553a4e235a6adfb49cbbae1c6373fafc
bbe447a740929eaee1955bd9c1517cf760dd5cb9
/keygrabber/adwords/adwords_api_python_14.2.1/examples/adspygoogle/adwords/v201008/get_all_alerts.py
4d21466fd75fcb699828f91b9b3d5813ed661315
[ "Apache-2.0" ]
permissive
MujaahidSalie/aranciulla
f3d32e7dd68ecfca620fe4d3bf22ecb4762f5893
34197dfbdb01479f288611a0cb700e925c4e56ce
refs/heads/master
2020-09-07T02:16:25.261598
2011-11-01T21:20:46
2011-11-01T21:20:46
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,655
py
#!/usr/bin/python # # Copyright 2010 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This example gets all alerts for all clients of an MCC account. The effective user (clientEmail, clientCustomerId, or authToken) must be an MCC user to get results. Tags: AlertService.get Api: AdWordsOnly """ __author__ = 'api.sgrinberg@gmail.com (Stan Grinberg)' import os import sys sys.path.append(os.path.join('..', '..', '..', '..')) # Import appropriate classes from the client library. from adspygoogle.adwords.AdWordsClient import AdWordsClient # Initialize client object. client = AdWordsClient(path=os.path.join('..', '..', '..', '..')) # Initialize appropriate service. alert_service = client.GetAlertService( 'https://adwords-sandbox.google.com', 'v201008') # Construct selector and get all alerts. selector = { 'query': { 'clientSpec': 'ALL', 'filterSpec': 'ALL', 'types': ['ACCOUNT_BUDGET_BURN_RATE', 'ACCOUNT_BUDGET_ENDING', 'ACCOUNT_ON_TARGET', 'CAMPAIGN_ENDED', 'CAMPAIGN_ENDING', 'CREDIT_CARD_EXPIRING', 'DECLINED_PAYMENT', 'KEYWORD_BELOW_MIN_CPC', 'MANAGER_LINK_PENDING', 'MISSING_BANK_REFERENCE_NUMBER', 'PAYMENT_NOT_ENTERED', 'TV_ACCOUNT_BUDGET_ENDING', 'TV_ACCOUNT_ON_TARGET', 'TV_ZERO_DAILY_SPENDING_LIMIT', 'USER_INVITE_ACCEPTED', 'USER_INVITE_PENDING', 'ZERO_DAILY_SPENDING_LIMIT'], 'severities': ['GREEN', 'YELLOW', 'RED'], 'triggerTimeSpec': 'ALL_TIME' }, 'paging': { 'startIndex': '0', 'numberResults': '100' } } page = alert_service.Get(selector)[0] # Display results. if 'entries' in page: for alert in page['entries']: print ('Alert of type \'%s\' and severity \'%s\' for account \'%s\' was ' 'found.' % (alert['alertType'], alert['alertSeverity'], alert['clientCustomerId'])) else: print 'No alerts were found.' print print ('Usage: %s units, %s operations' % (client.GetUnits(), client.GetOperations()))
[ "vincenzo.ampolo@gmail.com" ]
vincenzo.ampolo@gmail.com
1b7e95a80742d779a78c182b9719efb27038bbd2
98c6ea9c884152e8340605a706efefbea6170be5
/examples/data/Assignment_5/nckemm001/question3.py
35771920de3812c7a62c075b072149f678d290d2
[]
no_license
MrHamdulay/csc3-capstone
479d659e1dcd28040e83ebd9e3374d0ccc0c6817
6f0fa0fa1555ceb1b0fb33f25e9694e68b6a53d2
refs/heads/master
2021-03-12T21:55:57.781339
2014-09-22T02:22:22
2014-09-22T02:22:22
22,372,174
0
0
null
null
null
null
UTF-8
Python
false
false
309
py
# calculate number of k-permutations of n items from mymath import * def main (): n = get_integer ("n") k = get_integer ("k") nfactorial = calc_factorial (n) nkfactorial = calc_factorial (n-k) print ("Number of permutations:", nfactorial // nkfactorial) if __name__ == "__main__": main()
[ "jarr2000@gmail.com" ]
jarr2000@gmail.com
4ab0127cda446fe795a9d1d59838380875294643
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02767/s186457503.py
1b77521af961419a49332ff8fb6d05f6fcb75eac
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
183
py
N = int(input()) X = list(map(int,input().split())) ans = [] for i in range(max(X)): P = i+1 sum = 0 for j in range(N): sum += (X[j]-P)**2 ans.append(sum) print(min(ans))
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
2511226058f4ca7a04af4855132b4b925947bec0
aea20097b664f00c10391255b0d9cb019220ccea
/course/migrations/0055_facility_facilityiprange.py
31345f86601a48782c1e19d12d981cee863a4e41
[ "MIT" ]
permissive
duwhop/relate
d19f2bd3fbf4947863efe234a3fce55d73da1462
568bf6868fbc980e78e74fa29f84d10be2f8c94d
refs/heads/master
2020-06-09T16:58:38.474618
2015-11-30T01:48:49
2015-11-30T01:48:49
42,794,740
0
0
null
null
null
null
UTF-8
Python
false
false
1,123
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('course', '0054_add_auditor_role'), ] operations = [ migrations.CreateModel( name='Facility', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('identifier', models.CharField(help_text=b'Format is lower-case-with-hyphens. Do not use spaces.', unique=True, max_length=50)), ('description', models.CharField(max_length=100)), ], ), migrations.CreateModel( name='FacilityIPRange', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('ip_range', models.CharField(max_length=200)), ('ip_range_description', models.CharField(max_length=100)), ('facility', models.ForeignKey(to='course.Facility')), ], ), ]
[ "inform@tiker.net" ]
inform@tiker.net
ee3acb288c29099d6336e9d5fd0b7a54f71573fe
11398875e4f5cbcadc1747e73049dc99bca26908
/02-function/function-05.py
488628a5fad4821e64df6df89bde8b0fd5d26ec3
[]
no_license
asvkarthick/LearnPython
37910faab5c4a18d6e08eb304ca1da9649e5b18f
258e8c567ca3c8802d5e56f20b34317eba4c75f3
refs/heads/master
2021-06-23T06:30:46.681369
2021-06-11T19:35:40
2021-06-11T19:35:40
149,719,196
0
0
null
null
null
null
UTF-8
Python
false
false
242
py
#!/usr/bin/python # Author: Karthick Kumaran <asvkarthick@gmail.com> # Function with variable number of arguments def print_args(*args): if len(args): for i in args: print(i); else: print('No arguments passed') print_args(1, 2, 3)
[ "asvkarthick@gmail.com" ]
asvkarthick@gmail.com
a33d4056b80802fa4bec379faf6ae3c3ce517d55
cdf8b78a6975813c010b8c63b9e24f364a7cf995
/jupitotools/pyutils/pal.py
36df3851eb5b52ec785adb8549d332ec593a39e8
[ "MIT" ]
permissive
jupito/jupitotools
c789d89ae7525027ddc0aee4502cde1a44a4d268
fe3f1a4fd3a0d15b38285577c00ab68059dc274b
refs/heads/master
2022-02-16T13:45:49.270833
2022-01-30T21:34:05
2022-01-30T21:34:05
236,577,793
0
0
null
null
null
null
UTF-8
Python
false
false
2,093
py
#!/bin/python3 """Palette test. Usage: pal.py < /usr/share/X11/rgb.txt. Outputs RGB, hex, term hex, term dec, fg test, bg test, bg test RGB mode, name. """ # TODO: Use NamedColor dataclass. :) # https://github.com/welbornprod/colr # https://gist.github.com/XVilka/8346728 # https://lists.suckless.org/dev/1307/16688.html # https://github.com/martanne/dvtm/issues/10 import sys from typing import Tuple import dataclasses from dataclasses import dataclass import colr from colr import Colr @dataclass(order=True, frozen=True) class Color: r: int g: int b: int asdict = dataclasses.asdict astuple = dataclasses.astuple replace = dataclasses.astuple @property def rgb(self) -> Tuple[int]: return tuple([self.r, self.g, self.b]) @property def hex(self) -> str: return colr.rgb2hex(*self.rgb) @dataclass(order=True, frozen=True) class NamedColor(Color): name: str def sanitize_line(line, commenter='!'): """Clean up input line.""" return line.split(commenter, 1)[0].strip() def valid_lines(path): """Read and yield lines that are neither empty nor comments.""" with sys.stdin as fp: yield from filter(None, (sanitize_line(x) for x in fp)) def main(sep=' '): """Palette test main function.""" for line in valid_lines(None): r, g, b, name = line.split(maxsplit=3) r, g, b = (int(x) for x in [r, g, b]) h = colr.rgb2hex(r, g, b) th = colr.rgb2termhex(r, g, b) t = colr.rgb2term(r, g, b) d = dict(r=r, g=g, b=b, name=name, h=h, th=th, t=t) d['testfg'] = Colr().hex(h, 'test', rgb_mode=False) d['testbg'] = Colr().b_hex(h, 'test ', rgb_mode=False) d['testbg_rgb'] = Colr().b_hex(h, ' ', rgb_mode=True) fmt = sep.join(['{r:3} {g:3} {b:3}', '0x{h}', '0x{th}', '{t:>3s}', '{testfg}{testbg}{testbg_rgb}', '{name}']) print(fmt.format(**d)) if __name__ == '__main__': main()
[ "jupito@iki.fi" ]
jupito@iki.fi
d47df698bd174f7424065a3f0e7d5d20675c7592
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5688567749672960_0/Python/AmolMandhane/A.py
5bb0596356fa4cdd30ac17540355451410276f60
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
Python
false
false
616
py
def read(t): return t(raw_input().strip()) def read_arr(t): return map(t, raw_input().strip().split()) def rev_neg_num(n): return int("-" + (str(n)[1:])[::-1]) memz = {} for i in xrange(1, 10**6 + 1): if i <= 20: memz[i] = i elif i % 10 == 0: memz[i] = memz[i-1] + 1 else: rev = int(str(i)[::-1]) if rev in memz: memz[i] = min(memz[i-1] + 1, memz[rev] + 1) else: memz[i] = memz[i-1] + 1 def solve(N): return memz[N] solve(10**6) for T in xrange(input()): print "Case #%d:" % (T+1, ), print solve(read(int))
[ "eewestman@gmail.com" ]
eewestman@gmail.com
dd6adcded703c7b5d133c3bb7418f048182b934a
492693d325dad3adcb09601c54a5b7b0d00cfdef
/drf_admin/apps/system/filters/users.py
05bb23c86a66cdae77dce35a652ec0732e0e1343
[ "MIT" ]
permissive
HHHyuming/drf_admin
c682e7c284a9747175a81833aacb5e3fc67a2e42
956ab1a96964a8af06b0697e228a3d4238dce109
refs/heads/master
2023-03-19T23:52:06.521389
2021-03-10T15:28:50
2021-03-10T15:28:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
807
py
# -*- coding: utf-8 -*- """ @author : Wang Meng @github : https://github.com/tianpangji @software : PyCharm @file : users.py @create : 2020/9/15 21:59 """ import django_filters from drf_admin.common.models import get_child_ids from oauth.models import Users from system.models import Departments class UsersFilter(django_filters.rest_framework.FilterSet): """自定义用户管理过滤器""" department_id = django_filters.rest_framework.NumberFilter(method='department_service_filter') class Meta: model = Users fields = ['is_active', 'department_id'] def department_service_filter(self, queryset, name, value): """过滤该部门及所有子部门下的用户""" return queryset.filter(department_id__in=get_child_ids(value, Departments))
[ "921781999@qq.com" ]
921781999@qq.com
b8c1283bf4b251b33a832ef5172ab46c47722029
8aa1b94626402c0c614128d6061edb771dad05cf
/qt/qt02/qt25_button.py
db8d1e1c0f9f6b451a2d54f73a5b882cd94054c0
[]
no_license
netfj/Project_Stu02
31e76c1b656ee74c54cae2185821dec7ccf50401
afc1b26b7c586fd6979ab574c7d357a6b9ef4d29
refs/heads/master
2023-03-13T22:24:40.364167
2021-02-23T09:53:31
2021-02-23T09:53:31
341,506,093
0
0
null
null
null
null
UTF-8
Python
false
false
2,720
py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'qt25_button.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(400, 300) self.pushButton = QtWidgets.QPushButton(Form) self.pushButton.setGeometry(QtCore.QRect(10, 10, 101, 41)) self.pushButton.setObjectName("pushButton") self.toolButton = QtWidgets.QToolButton(Form) self.toolButton.setGeometry(QtCore.QRect(140, 10, 231, 31)) self.toolButton.setObjectName("toolButton") self.radioButton = QtWidgets.QRadioButton(Form) self.radioButton.setGeometry(QtCore.QRect(10, 60, 101, 31)) self.radioButton.setObjectName("radioButton") self.cb1 = QtWidgets.QCheckBox(Form) self.cb1.setGeometry(QtCore.QRect(10, 110, 61, 31)) self.cb1.setObjectName("cb1") self.commandLinkButton = QtWidgets.QCommandLinkButton(Form) self.commandLinkButton.setGeometry(QtCore.QRect(0, 160, 167, 41)) self.commandLinkButton.setObjectName("commandLinkButton") self.buttonBox = QtWidgets.QDialogButtonBox(Form) self.buttonBox.setGeometry(QtCore.QRect(10, 246, 166, 31)) self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok) self.buttonBox.setObjectName("buttonBox") self.checkBox_2 = QtWidgets.QCheckBox(Form) self.checkBox_2.setGeometry(QtCore.QRect(80, 110, 61, 31)) self.checkBox_2.setObjectName("checkBox_2") self.cb3 = QtWidgets.QCheckBox(Form) self.cb3.setGeometry(QtCore.QRect(150, 110, 61, 31)) self.cb3.setObjectName("cb3") self.cb4 = QtWidgets.QCheckBox(Form) self.cb4.setGeometry(QtCore.QRect(220, 110, 61, 31)) self.cb4.setObjectName("cb4") self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Form")) self.pushButton.setText(_translate("Form", "PushButton")) self.toolButton.setText(_translate("Form", "...")) self.radioButton.setText(_translate("Form", "RadioButton")) self.cb1.setText(_translate("Form", "CheckBox")) self.commandLinkButton.setText(_translate("Form", "CommandLinkButton")) self.checkBox_2.setText(_translate("Form", "CheckBox")) self.cb3.setText(_translate("Form", "CheckBox")) self.cb4.setText(_translate("Form", "CheckBox"))
[ "netfj@sina.com" ]
netfj@sina.com
b755f56b7ba2723287bbd6c93ecde85a202b8645
008ea0c503829f33840495373ad3d60794575af3
/PYDayByDay/Tkinter_ST/Button_TK/Button5.py
ec2ebc8db2d86596950f4aed52bd0b1193cfc593
[]
no_license
JyHu/PYStudy
6515bea47ca6f80e336f3b6a7a14b1159fde872f
ec0855c414237bdd7d0cb28f79a81c02ccd52d45
refs/heads/master
2016-08-12T19:44:06.723361
2016-04-11T10:38:59
2016-04-11T10:38:59
45,384,810
0
0
null
null
null
null
UTF-8
Python
false
false
304
py
#coding=utf-8 __author__ = 'JinyouHU' from Tkinter import * root = Tk() b1 = Button(root, text='30×1', width=30, height=2) b1.pack() b2 = Button(root, text='30×2') b2['width'] = 30 b2['height'] = 3 b2.pack() b3 = Button(root, text='30×3') b3.configure(width=30, height=3) b3.pack() root.mainloop()
[ "auu.aug@gmail.com" ]
auu.aug@gmail.com
4f83c7c667f9390704dc94f81efa7f2c72f39e64
1d96db84225301d972f07cad95c2a13f4fbafa84
/PyROOT/GravityStudies/simple_two_body_gravity.py
127826731c166fee2374beef04ad4c9c01ab5e6a
[]
no_license
mattbellis/matts-work-environment
9eb9b25040dd8fb4a444819b01a80c2d5342b150
41988f3c310f497223445f16e2537e8d1a3f71bc
refs/heads/master
2023-08-23T09:02:37.193619
2023-08-09T05:36:32
2023-08-09T05:36:32
32,194,439
0
0
null
null
null
null
UTF-8
Python
false
false
7,629
py
#!/usr/bin/env python from numpy import array import ROOT from ROOT import * from color_palette import * import sys from optparse import OptionParser import re import random as rnd ################################################################################ ################################################################################ ################################################################################ ################################################################################ def main(argv): parser = OptionParser() parser.add_option("-m", "--max", dest="max", default=1e9, help="Max games to read in.") parser.add_option("--tag", dest="tag", default=None, help="Tag for output files.") parser.add_option("--batch", dest="batch", default=False, action="store_true", help="Run in batch mode.") (options, args) = parser.parse_args() # Style options gStyle.SetOptStat(0) set_palette("palette",50) ############################################################################ # Declare the canvases ############################################################################ num_can = 1 can = [] for i in range(0,num_can): name = "can%d" % (i) if i<2: can.append(TCanvas(name,"",10+10*i,10+10*i,1350,700)) else: can.append(TCanvas(name,"",10+10*i,10+10*i,700,700)) can[i].SetFillColor(0) can[i].Divide(1,1) ############################################################################ # Declare some histograms ############################################################################ lo = 0.0 hi = 1.0 color = 2 nbins = 100 h = [] for i in range(0,5): name = "h%d" % (i) h.append(TH1F(name,"",nbins, lo, hi)) h[i].SetFillStyle(1000) h[i].SetFillColor(color) h[i].SetTitle("") h[i].SetNdivisions(8) h[i].GetYaxis().SetTitle("# occurances") h[i].GetYaxis().SetTitleSize(0.09) h[i].GetYaxis().SetTitleFont(42) h[i].GetYaxis().SetTitleOffset(0.7) h[i].GetYaxis().CenterTitle() h[i].GetXaxis().SetTitle("Arbitrary measurements") h[i].GetXaxis().SetLabelSize(0.12) h[i].GetXaxis().SetTitleSize(0.10) h[i].GetXaxis().SetTitleFont(42) h[i].GetXaxis().SetTitleOffset(1.0) h[i].GetXaxis().CenterTitle() h[i].SetMinimum(0) h2D = [] for i in range(0,5): name = "h2D%d" % (i) h2D.append(TH2F(name,"",nbins, lo, hi, nbins, lo, hi)) h2D[i].SetFillStyle(1000) h2D[i].SetFillColor(color) h2D[i].SetTitle("") h2D[i].SetNdivisions(8) h2D[i].GetYaxis().SetTitleSize(0.09) h2D[i].GetYaxis().SetTitleFont(42) h2D[i].GetYaxis().SetTitleOffset(0.7) h2D[i].GetYaxis().CenterTitle() h2D[i].GetYaxis().SetTitle("Visitng team") h2D[i].GetXaxis().SetTitle("Home team") #h2D[i].GetXaxis().SetLabelSize(0.09) h2D[i].GetXaxis().SetTitleSize(0.09) h2D[i].GetXaxis().SetTitleFont(42) h2D[i].GetXaxis().SetTitleOffset(0.7) h2D[i].GetXaxis().CenterTitle() h2D[i].SetMinimum(0) ############################################################################ # Set some physics quantitites ############################################################################ grav_constant = 100.0 mass = 5.0 # Save time, radius and mag of momentum recorded_values = [array('d'),array('d'),array('d')] ############################################################################ # Build the particles using velocity and position ############################################################################ num_particles = 2.0 particles = [] for i in range(0,num_particles): # Place the particles at 10.0 and -10.0 on z-axis with 0 momentum. z = 100.0 if i==1: z = -100.0 pos = TVector3(0.0,0.0,z) vel = TVector3(0.0,0.0,0.0) prev_pos = TVector3(pos) particles.append((pos,vel,prev_pos)) ############################################################################ # Calculate the motion of two bodies ############################################################################ t = 0 dt = 0.10 num_time_steps = 0 # Declare these once for use later force = TVector3() direction = TVector3() minimum_distance_allowable = 1.0 smallest_distance = 1000000.0 while smallest_distance>minimum_distance_allowable: print t # Copy the current position to the previous position for p in (particles): p[2].SetXYZ(p[0].X(),p[0].Y(),p[0].Z()) for p in particles: # Clear out the force vector force.SetXYZ(0.0,0.0,0.0) # Calculate the forces and then move them # Loop over all the other particles to calculate the sum of the # forces on our one particle for q in particles: if p is not q: #print "print pz and qz: %f %f" % (p[2].Z(),q[2].Z()) direction.SetXYZ(p[2].X(),p[2].Y(),p[2].Z()) direction -= q[2] distance = direction.Mag() print "distance: %f" % (distance) if distance<smallest_distance: smallest_distance=distance # Take into account the normalization that will have to be done. force_mag = grav_constant * mass * mass/(distance*distance*distance) # direction will now actually be the full force vector direction *= (-force_mag) force += direction # Update the momentum # Make force the momentum and then add it force *= dt force.Print() p[1].SetXYZ(p[1].X()+force.X(), p[1].Y()+force.Y(), p[1].Z()+force.Z()) # Update the new position p[0].SetXYZ(p[0].X()+p[1].X()*dt, p[0].Y()+p[1].Y()*dt, p[0].Z()+p[1].Z()*dt) # Save the radius and the magnitude of momentum recorded_values[0].append(t) print "recorded values: %f %f" % (p[0].Mag(),p[1].Mag()) recorded_values[1].append(p[0].Mag()) recorded_values[2].append(p[1].Mag()) dt = smallest_distance/1000.0 t += dt num_time_steps += 1 if num_time_steps>500: break print "num_time_steps: %d" % (num_time_steps) npts = len(recorded_values[0]) gr = TGraph(npts,recorded_values[1],recorded_values[2]) can[0].cd(1) gr.Draw("ap*") gPad.Update() ''' if options.tag != None: name = "Plots/sportsplots%s_%d.eps" % (options.tag,i) can[0].SaveAs(name) ''' ################################################################################ ## Wait for input to keep the GUI (which lives on a ROOT event dispatcher) alive if not options.batch: rep = '' while not rep in [ 'q', 'Q' ]: rep = raw_input( 'enter "q" to quit: ' ) if 1 < len(rep): rep = rep[0] ################################################################################ ################################################################################ if __name__ == '__main__': main(sys.argv)
[ "matthew.bellis@gmail.com" ]
matthew.bellis@gmail.com
e2faec65704111af5e54413795ed61640756088f
8f24e443e42315a81028b648e753c50967c51c78
/rllib/utils/debug/deterministic.py
f41fdabf323bfc57abe2db545babe1a292825d7c
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
permissive
simon-mo/ray
d07efdada8d05c6e10417f96e8dfc35f9ad33397
1e42e6cd15e2fb96c217cba8484e59ed0ef4b0c8
refs/heads/master
2023-03-06T00:09:35.758834
2022-12-23T18:46:48
2022-12-23T18:46:48
122,156,396
4
2
Apache-2.0
2023-03-04T08:56:56
2018-02-20T04:47:06
Python
UTF-8
Python
false
false
1,805
py
import numpy as np import os import random from typing import Optional from ray.rllib.utils.annotations import DeveloperAPI from ray.rllib.utils.framework import try_import_tf, try_import_torch @DeveloperAPI def update_global_seed_if_necessary( framework: Optional[str] = None, seed: Optional[int] = None ) -> None: """Seed global modules such as random, numpy, torch, or tf. This is useful for debugging and testing. Args: framework: The framework specifier (may be None). seed: An optional int seed. If None, will not do anything. """ if seed is None: return # Python random module. random.seed(seed) # Numpy. np.random.seed(seed) # Torch. if framework == "torch": torch, _ = try_import_torch() torch.manual_seed(seed) # See https://github.com/pytorch/pytorch/issues/47672. cuda_version = torch.version.cuda if cuda_version is not None and float(torch.version.cuda) >= 10.2: os.environ["CUBLAS_WORKSPACE_CONFIG"] = "4096:8" else: try: from packaging.version import Version except ImportError: from distutils.version import LooseVersion as Version if Version(torch.__version__) >= Version("1.8.0"): # Not all Operations support this. torch.use_deterministic_algorithms(True) else: torch.set_deterministic(True) # This is only for Convolution no problem. torch.backends.cudnn.deterministic = True elif framework == "tf2": tf1, tf, tfv = try_import_tf() # Tf2.x. if tfv == 2: tf.random.set_seed(seed) # Tf1.x. else: tf1.set_random_seed(seed)
[ "noreply@github.com" ]
simon-mo.noreply@github.com
2356b0c0ef247eac6f4c60a788c1a6f5bdcf1bd6
8bab45756c78e4da7854b899be23c075ff1a170c
/0x03-caching/3-lru_cache.py
d9d80241177193ae3221e6047c536c3521c3ba2c
[]
no_license
Jesus-Acevedo-Cano/holbertonschool-web_back_end
a8b06484b0705935229eb691be0de15b304339d9
0c068b19bb11d6194f97c0157cadffd7da44458f
refs/heads/main
2023-02-17T23:46:24.844689
2021-01-09T03:44:57
2021-01-09T03:44:57
305,505,809
0
0
null
null
null
null
UTF-8
Python
false
false
913
py
#!/usr/bin/python3 """ LRU caching """ from base_caching import BaseCaching class LRUCache(BaseCaching): """ LRU cache class """ def __init__(self): """ constructor """ self.cache = [] super().__init__() def put(self, key, item): """ Add an item in the cache """ if key and item: if key in self.cache_data: self.cache.remove(key) self.cache_data[key] = item self.cache.append(key) if len(self.cache_data) > BaseCaching.MAX_ITEMS: discard = self.cache.pop(0) del self.cache_data[discard] print("DISCARD: {}".format(discard)) def get(self, key): """ Get an item by key """ if key is None or key not in self.cache_data: return None self.cache.remove(key) self.cache.append(key) return self.cache_data[key]
[ "jeacevedocano@gmail.com" ]
jeacevedocano@gmail.com
79eb01e2b3ea229ffdcd8620512e8b6ea1605ca4
f86202fe01c203d6974e35daf6afbf0506607078
/src/restrepo/restrepo/db/scan_images.py
79dc823572a861edabf9260163f30c23a6afdfc7
[]
no_license
sejarah-nusantara/repository
f83701697bd14b920b6dc825509124bcad4c5891
350d15823b3931f01f2db657b20cd93ac7d10a70
refs/heads/master
2021-01-25T13:06:10.833973
2018-03-02T04:22:14
2018-03-02T04:22:14
123,528,705
0
0
null
null
null
null
UTF-8
Python
false
false
587
py
from sqlalchemy import Table, Column, Integer, String, Boolean, ForeignKey from restrepo.db import metadata from restrepo.db.mixins import DictAble scan_image = Table('scan_image', metadata, Column('id', Integer, primary_key=True), Column('scan_number', Integer, ForeignKey('scan.number'), index=True), Column('filename', String(255), index=True), Column('is_default', Boolean), ) class ScanImage(DictAble): "An image linked to a scan. Can be the default one." def __init__(self, **kwdata): for k, v in kwdata.items(): setattr(self, k, v)
[ "github@gerbrandy.com" ]
github@gerbrandy.com
dfc0feb317cf6bd4b82e6d55a8e2183e13948bd5
d957b7167e7e24ac8432a936434bf7b561201fd8
/backend/users/migrations/0002_auto_20200611_0743.py
2207997a2eb78db89cfd152ff95d46a6c050546f
[]
no_license
crowdbotics-apps/digital-rehab-18007
ee0f874fab956f47a7db4ceb5578da6ab8872294
19c9b4575112bae81db0dc5b8a6446266ed308cd
refs/heads/master
2022-10-09T14:43:48.195386
2020-06-11T07:57:43
2020-06-11T07:57:43
271,390,793
0
0
null
null
null
null
UTF-8
Python
false
false
394
py
# Generated by Django 2.2.13 on 2020-06-11 07:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("users", "0001_initial"), ] operations = [ migrations.AlterField( model_name="user", name="name", field=models.CharField(blank=True, max_length=255, null=True), ), ]
[ "team@crowdbotics.com" ]
team@crowdbotics.com
e91824981b8e94f7b2eb6375ede494f624e1cc26
e0db13bc8113fb7b383d0a8d09e09686668e2fb4
/Data-Structures-and-Algorithms/Undirected-Graph-using-Adjacency-Matrix.py
9b90ba566c0e5827a845026d3e22283f4d2d1964
[]
no_license
nirmalnishant645/Python-Programming
dd66acd665af8933fa14b19d01300deb1eccbb7d
70e97e6f35f125acfde3b38e1baa794a357b8a77
refs/heads/master
2022-06-03T12:41:56.483000
2022-05-12T10:54:59
2022-05-12T10:54:59
151,211,590
3
5
null
2020-02-12T05:48:59
2018-10-02T06:44:54
HTML
UTF-8
Python
false
false
1,367
py
''' The Implementation will be same as Directed Graph, but this time the connection will be done both ways. If v1 => v2 then v2 => v1 Or v1 <=> v2 ''' # Simple Graph Implementation class Graph: def __init__(self, number_of_nodes): # Initialise Graph Data Structure self.number_of_nodes = number_of_nodes + 1 # Number of nodes will have to be increased by one self.graph = [[0 for x in range(number_of_nodes + 1)] for y in range(number_of_nodes + 1)] def withInBounds(self, v1, v2): # Function to check if the value is within matrix bounds return v1 >= 0 and v1 <= self.number_of_nodes and v2 >= 0 and v2 <= self.number_of_nodes def insertEdge(self, v1, v2): # Function to inser edge in the Graph if self.withInBounds(v1, v2): # Check if values are within bounds self.graph[v1][v2] = 1 # Change the value of the node from 0 to 1 self.graph[v2][v1] = 1 # Adding the two way relation between the vertices to make in undirected def printGraph(self): # Functipon to Print Graph for i in range(self.number_of_nodes): for j in range(len(self.graph[i])): if self.graph[i][j]: print(i, '=>', j) g = Graph(5) g.insertEdge(1, 2) g.insertEdge(2, 3) g.insertEdge(4, 5) g.printGraph() ''' Output: 1 => 2 2 => 1 2 => 3 3 => 2 4 => 5 5 => 4 '''
[ "nirmalnishant645@gmail.com" ]
nirmalnishant645@gmail.com
fdde462ec23e0151a6b473387539fb36d35269e1
1a9852fe468f18e1ac3042c09286ccda000a4135
/Specialist Certificate in Data Analytics Essentials/DataCamp/02-python-data-science-toolbox-part-2/e28_processing_data_in_chunks1.py
31e985b2bc89768a7d90f08c68af9418f77a0890
[]
no_license
sarmabhamidipati/UCD
452b2f1e166c1079ec06d78e473730e141f706b2
101ca3152207e2fe67cca118923896551d5fee1c
refs/heads/master
2023-08-14T15:41:24.312859
2021-09-22T17:33:01
2021-09-22T17:33:01
386,592,878
0
0
null
null
null
null
UTF-8
Python
false
false
1,497
py
""" Processing data in chunks (1) The csv file 'world_dev_ind.csv' is in your current directory for your use. To begin, you need to open a connection to this file using what is known as a context manager. For example, the command with open('datacamp.csv') as datacamp binds the csv file 'datacamp.csv' as datacamp in the context manager. Here, the with statement is the context manager, and its purpose is to ensure that resources are efficiently allocated when opening a connection to a file. Instructions 100 XP Use open() to bind the csv file 'world_dev_ind.csv' as file in the context manager. Complete the for loop so that it iterates 1000 times to perform the loop body and process only the first 1000 rows of data of the file. """ # Open a connection to the file with open('world_dev_ind.csv') as file: # Skip the column names file.readline() # Initialize an empty dictionary: counts_dict counts_dict = {} # Process only the first 1000 rows for j in range(1000): # Split the current line into a list: line line = file.readline().split(',') # Get the value for the first column: first_col first_col = line[0] # If the column value is in the dict, increment its value if first_col in counts_dict.keys(): counts_dict[first_col] += 1 # Else, add to the dict and set value to 1 else: counts_dict[first_col] = 1 # Print the resulting dictionary print(counts_dict)
[ "b_vvs@yahoo.com" ]
b_vvs@yahoo.com
5cdc2d4a8d76a829d96c2ed7591c5c88e3c42552
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
/python/youtube-dl/2016/8/cmt.py
f24568dcc25740f7814c134f9e58e659e7f11855
[]
no_license
rosoareslv/SED99
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
a062c118f12b93172e31e8ca115ce3f871b64461
refs/heads/main
2023-02-22T21:59:02.703005
2021-01-28T19:40:51
2021-01-28T19:40:51
306,497,459
1
1
null
2020-11-24T20:56:18
2020-10-23T01:18:07
null
UTF-8
Python
false
false
1,765
py
from __future__ import unicode_literals from .mtv import MTVIE from ..utils import ExtractorError class CMTIE(MTVIE): IE_NAME = 'cmt.com' _VALID_URL = r'https?://www\.cmt\.com/(?:videos|shows)/(?:[^/]+/)*(?P<videoid>\d+)' _FEED_URL = 'http://www.cmt.com/sitewide/apps/player/embed/rss/' _TESTS = [{ 'url': 'http://www.cmt.com/videos/garth-brooks/989124/the-call-featuring-trisha-yearwood.jhtml#artist=30061', 'md5': 'e6b7ef3c4c45bbfae88061799bbba6c2', 'info_dict': { 'id': '989124', 'ext': 'mp4', 'title': 'Garth Brooks - "The Call (featuring Trisha Yearwood)"', 'description': 'Blame It All On My Roots', }, 'skip': 'Video not available', }, { 'url': 'http://www.cmt.com/videos/misc/1504699/still-the-king-ep-109-in-3-minutes.jhtml#id=1739908', 'md5': 'e61a801ca4a183a466c08bd98dccbb1c', 'info_dict': { 'id': '1504699', 'ext': 'mp4', 'title': 'Still The King Ep. 109 in 3 Minutes', 'description': 'Relive or catch up with Still The King by watching this recap of season 1, episode 9. New episodes Sundays 9/8c.', 'timestamp': 1469421000.0, 'upload_date': '20160725', }, }, { 'url': 'http://www.cmt.com/shows/party-down-south/party-down-south-ep-407-gone-girl/1738172/playlist/#id=1738172', 'only_matching': True, }] @classmethod def _transform_rtmp_url(cls, rtmp_video_url): if 'error_not_available.swf' in rtmp_video_url: raise ExtractorError( '%s said: video is not available' % cls.IE_NAME, expected=True) return super(CMTIE, cls)._transform_rtmp_url(rtmp_video_url)
[ "rodrigosoaresilva@gmail.com" ]
rodrigosoaresilva@gmail.com
312aa26a98938f328a2eba660cd18cb8d9305fac
57094f0d09fd3e74eeb511e94400c3ec97051ad3
/Quax_dev_archive/quax_research/research/findif.py
837a3116e26a36c17b410aed4ddeca71656b4abe
[]
no_license
adabbott/Research_Notes
cccba246e81065dc4a663703fe225fc1ebbf806b
644394edff99dc6542e8ae6bd0ce8bcf158cff69
refs/heads/master
2023-05-12T20:26:58.938617
2021-06-02T17:15:35
2021-06-02T17:15:35
119,863,228
1
0
null
null
null
null
UTF-8
Python
false
false
687
py
# pip install fdm import numpy as np import jax.numpy as jnp import fdm import jax # Function: #f(x,y,z) = exp(1 * x + 2 * y + 3 * z) def func(vec): coef = jnp.array([1.,2.,3.]) return jnp.exp(jnp.sum(coef * vec)) findif_gradient = fdm.gradient(func) jax_gradient = jax.jacfwd(func, 0) inp1 = np.array([0.1,0.2,0.3]) inp2 = jnp.array([0.1,0.2,0.3]) print(findif_gradient(inp1)) print(jax_gradient(inp2)) findif_hessian = fdm.jacobian(jax_gradient) jax_hessian = jax.jacfwd(jax_gradient) print(findif_hessian(inp1)) print(jax_hessian(inp2)) findif_cubic = fdm.jacobian(jax_hessian) jax_cubic = jax.jacfwd(jax_hessian) print(findif_cubic(inp1)) print(jax_cubic(inp2))
[ "adabbott@uga.edu" ]
adabbott@uga.edu
ba661605c33bc97a360545d8ba5b4e9de8ab3769
4ca44b7bdb470fcbbd60c2868706dbd42b1984c9
/20.02.23/백준 2589.py
e74d174f72d9f3fb56f4e43329178cf1902b773a
[]
no_license
titiman1013/Algorithm
3b3d14b3e2f0cbc4859029eb73ad959ec8778629
8a67e36931c42422779a4c90859b665ee468255b
refs/heads/master
2023-06-29T17:04:40.015311
2021-07-06T01:37:29
2021-07-06T01:37:29
242,510,483
2
0
null
null
null
null
UTF-8
Python
false
false
3,144
py
# BFS # N, M = list(map(int, input().split())) # arr = [list(map(str, list(input()))) for i in range(N)] # dx = [-1, 1, 0, 0] # dy = [0, 0, -1, 1] # for i in range(N): # for j in range(M): # clone = [] # for i in range(N): # clone.append([]) # clone[i] = arr[i][:] # if clone[i][j] == 'L': # que = [] # x = i # y = j # cnt = 0 # result = 0 # clone[x][y] = 'W' # que.append((x, y)) # while que: # x, y = que.pop(0) # for k in range(4): # nx = x + dx[k] # ny = y + dy[k] # if 0 <= nx < N and 0 <= ny < M: # if clone[nx][ny] == 'L': # que.append((nx, ny)) # clone[nx][ny] = 'W' # cnt += 1 # if cnt > result: # result = cnt # print(result) # N, M = list(map(int, input().split())) # arr = [list(map(str, list(input()))) for i in range(N)] # dx = [-1, 1, 0, 0] # dy = [0, 0, -1, 1] # final = 0 # for i in range(N): # for j in range(M): # if arr[i][j] == 'L': # que = [] # visit = [[0] * M for i in range(N)] # x = i # y = j # result = 0 # visit[x][y] = 1 # que.append((x, y)) # while que: # x, y = que.pop(0) # for k in range(4): # nx = x + dx[k] # ny = y + dy[k] # if 0 <= nx < N and 0 <= ny < M: # if arr[nx][ny] == 'L' and visit[nx][ny] == 0: # que.append((nx, ny)) # visit[nx][ny] = visit[x][y] + 1 # if visit[nx][ny] > result: # result = visit[nx][ny] # if result > final: # final = result # print(final-1) # collection 사용 import collections N, M = list(map(int, input().split())) arr = [list(map(str, list(input()))) for i in range(N)] dx = [-1, 1, 0, 0] dy = [0, 0, -1, 1] final = 0 for i in range(N): for j in range(M): if arr[i][j] == 'L': que = collections.deque() visit = [[0] * M for i in range(N)] x = i y = j result = 0 visit[x][y] = 1 que.append((x, y)) while que: x, y = que.popleft() for k in range(4): nx = x + dx[k] ny = y + dy[k] if 0 <= nx < N and 0 <= ny < M: if arr[nx][ny] == 'L' and visit[nx][ny] == 0: que.append((nx, ny)) visit[nx][ny] = visit[x][y] + 1 if visit[nx][ny] > result: result = visit[nx][ny] if result > final: final = result print(final-1)
[ "hyunsukr1013@gmail.com" ]
hyunsukr1013@gmail.com
d93d0dd79f44036af57b9124fc0a49af6d8f58dd
8553e0b06161d288100750cda973924ee4030e17
/clustack/blueprint.py
4dfa4e64602ade14f0636b61a7ba98577f3a14d4
[]
no_license
mrmh2/clustack
0b635fec2c459f7a6db724aead84a36fb6bd7254
4b1e820e82ef8cbae400b69f156574050e72698a
refs/heads/master
2021-01-19T03:23:20.122454
2015-04-13T12:47:07
2015-04-13T12:47:07
28,097,203
0
0
null
null
null
null
UTF-8
Python
false
false
3,276
py
import os import yaml import settings def load_blueprint_yaml(filename): """Load a blueprint from the given YAML file.""" with open(filename) as f: yaml_rep = yaml.load(f) name = yaml_rep['name'] bp = BluePrint(name) bp.version = yaml_rep['version'] if 'dependencies' in yaml_rep: bp.direct_dependencies = yaml_rep['dependencies'] return bp def load_blueprint(filename): """Load a blueprint from the given filename. Try to determine the type of blueprint from the file extension and dispatch to the relevant loader.""" path, ext = os.path.splitext(filename) try: loader = LOADERS[ext] except KeyError: raise Exception("Don't know how to load blueprint: {}".format(filename)) return loader(filename) def ext_matches(name, ext_list): """Return True if file extension is in the supplied list.""" base, ext = os.path.splitext(name) return ext in ext_list def get_basename_and_full_path(name, path): """Given name and path, return name with no extension and full path.""" basename = os.path.splitext(name)[0] full_path = os.path.join(path, name) return basename, full_path def get_available_blueprints(): """Generate list of all available blueprints, in the form of a dictionary of name : path pairs.""" available = {} bp_exts = settings.blueprint_exts bp_path = settings.blueprint_path for path in bp_path: matching_files = [f for f in os.listdir(path) if ext_matches(f, bp_exts)] md = dict(get_basename_and_full_path(fn, path) for fn in matching_files) available.update(md) return available def load_blueprint_by_name(name): """Load a blueprint from a (string) name. Use settings to determine search path, then choose a loader.""" name = name.lower() available_blueprints = get_available_blueprints() if name in available_blueprints: return load_blueprint(available_blueprints[name]) raise Exception("Can't load blueprint {} by name".format(name)) class BluePrint(object): """Class representing instructions for how to build a package. Expected to be constructed from a file, and will be used to create a Builder to build the package.""" def __init__(self, name): self.name = name self.direct_dependencies = [] self._full_dependencies = None @property def full_dependencies(self): """All dependencies, both direct and indirect. To avoid calculating every time, cache the result of the initial tree walk.""" if not self._full_dependencies: self._full_dependencies = self.find_full_dependencies() return self._full_dependencies def find_full_dependencies(self): """Find all indirect dependencies, by finding dependencies of dependencies.""" full_dependencies = [] modules = self.direct_dependencies while modules: module = modules.pop() full_dependencies.append(module) bp_dep = load_blueprint_by_name(module) modules += bp_dep.direct_dependencies return full_dependencies LOADERS = { '.yaml' : load_blueprint_yaml }
[ "mhartley@cantab.net" ]
mhartley@cantab.net
6fdfbeb35e62d8c18a865ee9eff34cc303f77ce4
e35ffef188a8b72000ae9402b9143b9f35cf95ca
/web3/utils/filters.py
ccdec69050ed01b26cf2d405c2b6f66fe6989572
[ "MIT" ]
permissive
riccitensor/web3.py
7dd9215b6d6755340cfc85c37d06cb076b3518de
73bfb0f7bab1f035cb9c4ce9a8660cb664e61c58
refs/heads/master
2020-12-11T09:16:53.374513
2016-08-07T01:11:25
2016-08-07T01:11:25
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,915
py
import re import random import gevent from .types import ( is_string, is_array, ) from .abi import ( construct_event_topic_set, construct_event_data_set, ) def construct_event_filter_params(event_abi, contract_address=None, argument_filters=None, topics=None, fromBlock=None, toBlock=None, address=None): filter_params = {} if topics is None: topic_set = construct_event_topic_set(event_abi, argument_filters) else: topic_set = [topics] + construct_event_topic_set(event_abi, argument_filters) if len(topic_set) == 1 and is_array(topic_set[0]): filter_params['topics'] = topic_set[0] else: filter_params['topics'] = topic_set if address and contract_address: if is_array(address): filter_params['address'] = address + [contract_address] elif is_string(address): filter_params['address'] = [address, contract_address] else: raise ValueError( "Unsupported type for `address` parameter: {0}".format(type(address)) ) elif address: filter_params['address'] = address elif contract_address: filter_params['address'] = contract_address if fromBlock is not None: filter_params['fromBlock'] = fromBlock if toBlock is not None: filter_params['toBlock'] = toBlock data_filters_set = construct_event_data_set(event_abi, argument_filters) return data_filters_set, filter_params class BaseFilter(gevent.Greenlet): callbacks = None running = None stopped = False def __init__(self, web3, filter_id): self.web3 = web3 self.filter_id = filter_id self.callbacks = [] gevent.Greenlet.__init__(self) def __str__(self): return "Filter for {0}".format(self.filter_id) def _run(self): if self.stopped: raise ValueError("Cannot restart a Filter") self.running = True self.rejected_logs = [] previous_logs = self.web3.eth.getFilterLogs(self.filter_id) if previous_logs: for entry in previous_logs: for callback_fn in self.callbacks: if self.is_valid_entry(entry): callback_fn(entry) else: self.rejected_logs.append(entry) while self.running: changes = self.web3.eth.getFilterChanges(self.filter_id) if changes: for entry in changes: for callback_fn in self.callbacks: if self.is_valid_entry(entry): callback_fn(entry) else: self.rejected_logs.append(entry) gevent.sleep(random.random()) def is_valid_entry(self, entry): """ Hook for subclasses to implement additional filtering layers. """ return True def watch(self, *callbacks): if self.stopped: raise ValueError("Cannot watch on a filter that has been stopped") self.callbacks.extend(callbacks) if not self.running: self.start() def stop_watching(self, timeout=0): self.running = False self.stopped = True self.web3.eth.uninstallFilter(self.filter_id) self.join(timeout) stopWatching = stop_watching class BlockFilter(BaseFilter): pass class TransactionFilter(BaseFilter): pass ZERO_32BYTES = '[a-f0-9]{64}' def construct_data_filter_regex(data_filter_set): return re.compile(( '^' + '|'.join(( '0x' + ''.join( (ZERO_32BYTES if v is None else v[2:] for v in data_filter) ) for data_filter in data_filter_set )) + '$' )) class LogFilter(BaseFilter): data_filter_set = None data_filter_set_regex = None def get(self, only_changes=True): if self.running: raise ValueError( "Cannot call `get` on a filter object which is actively watching" ) if only_changes: return self.web3.eth.getFilterChanges(self.filter_id) else: return self.web3.eth.getFilterChanges(self.filter_id) def set_data_filters(self, data_filter_set): self.data_filter_set = data_filter_set if any(data_filter_set): self.data_filter_set_regex = construct_data_filter_regex( data_filter_set, ) def is_valid_entry(self, entry): if not self.data_filter_set_regex: return True return bool(self.data_filter_set_regex.match(entry['data']))
[ "pipermerriam@gmail.com" ]
pipermerriam@gmail.com
f054090518610eef7e91a188cf6eddfc36451fae
92782460989bc10540c85804215832b465a6474a
/spell/__main__.py
45b2f2907893f3d1ded09b0872d5dd381c92b1d3
[ "GPL-1.0-or-later", "GPL-3.0-only", "MIT" ]
permissive
malaikannan/open-tamil
805ccd2b9bd88df23127425c7bcebaf97f337352
99f0c4484cd07a98cf77146c754592e5c26f6965
refs/heads/master
2022-07-19T12:35:36.956062
2020-05-21T07:41:06
2020-05-21T07:41:06
266,903,297
2
0
MIT
2020-05-25T23:54:56
2020-05-25T23:54:56
null
UTF-8
Python
false
false
158
py
#!/usr/bin/python #(C) 2016 Muthiah Annamalai #This file is part of open-tamil package from .spell import main if __name__ == u"__main__": main()
[ "ezhillang@gmail.com" ]
ezhillang@gmail.com
78ec746175809e03465ab3c1d327ae68cb431ec3
ed17ca55fedd70cc336271e40634b09791437db5
/products/migrations/0002_auto_20201204_0247.py
2b725f84fddbe8f837b129604041dbd116466796
[]
no_license
wecode-bootcamp-korea/14-2nd-MyLittleTrip-backend
a5c8beb0a30ed7ef92fba04499036d4ccfbe2add
d9720f51a30028a866fd62d6c66a1a7e4525ce5f
refs/heads/master
2023-01-24T13:40:18.601842
2020-12-09T19:03:35
2020-12-11T03:49:04
317,109,595
0
3
null
2020-12-11T03:49:05
2020-11-30T04:21:54
Python
UTF-8
Python
false
false
381
py
# Generated by Django 3.1.4 on 2020-12-04 02:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0001_initial'), ] operations = [ migrations.AlterField( model_name='region', name='region_code', field=models.CharField(max_length=30), ), ]
[ "53214510+lordmyshepherd@users.noreply.github.com" ]
53214510+lordmyshepherd@users.noreply.github.com
fee4e1d37330f42b34263f994d91a021098befbe
81537f77ddfa3820e7a224173b8249af2d665987
/microcosm_flask/paging.py
dd014de3020195af3815195585789346b2ef9e63
[ "Apache-2.0" ]
permissive
pokey/microcosm-flask
efa0ae6c39f0ecf85c79f3d2ef607af8bad80635
77dd32f4c670c1a6f2ac70dd37d2a3f05d118707
refs/heads/develop
2021-01-13T14:58:48.889868
2017-01-10T22:55:17
2017-01-10T22:55:17
79,353,026
0
0
null
2017-01-18T15:23:13
2017-01-18T15:23:13
null
UTF-8
Python
false
false
3,576
py
""" Pagination support. """ from marshmallow import fields, Schema from microcosm_flask.linking import Link, Links from microcosm_flask.operations import Operation class PageSchema(Schema): offset = fields.Integer(missing=0, default=0) limit = fields.Integer(missing=20, limit=20) def make_paginated_list_schema(ns, item_schema): """ Generate a paginated list schema. :param ns: a `Namespace` for the list's item type :param item_schema: a `Schema` for the list's item type """ class PaginatedListSchema(Schema): __alias__ = "{}_list".format(ns.subject_name) offset = fields.Integer(required=True) limit = fields.Integer(required=True) count = fields.Integer(required=True) items = fields.List(fields.Nested(item_schema), required=True) _links = fields.Raw() return PaginatedListSchema class Page(object): def __init__(self, offset, limit, **rest): self.offset = offset self.limit = limit self.rest = rest @classmethod def from_query_string(cls, qs): """ Create a page from a query string dictionary. This dictionary should probably come from `PageSchema.from_request()`. """ dct = qs.copy() offset = dct.pop("offset", None) limit = dct.pop("limit", None) return cls( offset=offset, limit=limit, **dct ) def next(self): return Page( offset=self.offset + self.limit, limit=self.limit, **self.rest ) def prev(self): return Page( offset=self.offset - self.limit, limit=self.limit, **self.rest ) def to_dict(self): return dict(self.to_tuples()) def to_tuples(self): """ Convert to tuples for deterministic order when passed to urlencode. """ return [ ("offset", self.offset), ("limit", self.limit), ] + [ (key, str(self.rest[key])) for key in sorted(self.rest.keys()) ] class PaginatedList(object): def __init__(self, ns, page, items, count, schema=None, operation=Operation.Search, **extra): self.ns = ns self.page = page self.items = items self.count = count self.schema = schema self.operation = operation self.extra = extra def to_dict(self): return dict( count=self.count, items=[ self.schema.dump(item).data if self.schema else item for item in self.items ], _links=self._links, **self.page.to_dict() ) @property def offset(self): return self.page.offset @property def limit(self): return self.page.limit @property def _links(self): return self.links.to_dict() @property def links(self): links = Links() links["self"] = Link.for_(self.operation, self.ns, qs=self.page.to_tuples(), **self.extra) if self.page.offset + self.page.limit < self.count: links["next"] = Link.for_(self.operation, self.ns, qs=self.page.next().to_tuples(), **self.extra) if self.page.offset > 0: links["prev"] = Link.for_(self.operation, self.ns, qs=self.page.prev().to_tuples(), **self.extra) return links
[ "jesse.myers@globality.com" ]
jesse.myers@globality.com
bdc4b50832daa23779baf1ddce94fb0fda27d228
8c3755e907a8f7fbae4e5e3334aa9332f8f705bb
/python_example_scripts/stack_lifo.py
d367791a5ad2ff1345144dca57c6111f3d7a842d
[]
no_license
xaneon/PythonProgrammingBasics
20c9db82f621a41735856a0b008bf2c328d8e4b5
accf4d16034d33e616b5ebe46f69c1130b09f85e
refs/heads/master
2020-06-13T13:47:02.995326
2019-07-01T13:45:29
2019-07-01T13:45:29
194,235,103
0
0
null
null
null
null
UTF-8
Python
false
false
800
py
import random import os import time def print_gegenstande(gegenstande): os.system("clear") for i, gegenstand in enumerate(gegenstande): print(str(len(gegenstande) - i) + ". " + gegenstand) def eliminate_fifo(gegenstande): if len(gegenstande) == 0: print("Kein Gegenstand mehr uebrig.") else: out = gegenstande.pop(0) print_gegenstande(gegenstande) print("%s herausgenommen." %out) time.sleep(2) eliminate_fifo(gegenstande) print("Simulation einer Schlange, FIFO") anzahl_zufallszahlen = 8 groesste_zahl = 10 zufallszahlen = random.sample(range(1, groesste_zahl), anzahl_zufallszahlen) gegenstande = ['Gegenstand' + str(int(x)) for x in zufallszahlen] print_gegenstande(gegenstande) time.sleep(5) eliminate_fifo(gegenstande)
[ "bonne.habekost@gmail.com" ]
bonne.habekost@gmail.com
b6fa1efaa794a7a60877ebf4753cc19a49117b67
a859aadea24af173a175c2d01910314487ec6fbf
/common/coco_caption/pycocoevalcap/eval.py
1947f13ea55f7a0df5153ed2c5e8c352ae50a0fe
[ "BSD-3-Clause", "BSD-2-Clause-Views" ]
permissive
jiahuei/tf-sparse-captioning
cc52cbef5590b47727ea89f265011c9ab58aebad
9d7b8ecdd44fb1541500ca4f920d6c94fd15bad1
refs/heads/main
2023-04-07T05:27:28.395758
2021-04-19T11:27:28
2021-04-19T11:27:28
359,341,665
0
0
null
null
null
null
UTF-8
Python
false
false
2,928
py
__author__ = 'tylin' from common.coco_caption.pycocoevalcap.tokenizer.ptbtokenizer import PTBTokenizer from common.coco_caption.pycocoevalcap.bleu.bleu import Bleu from common.coco_caption.pycocoevalcap.meteor.meteor import Meteor from common.coco_caption.pycocoevalcap.rouge.rouge import Rouge from common.coco_caption.pycocoevalcap.cider.cider import Cider from common.coco_caption.pycocoevalcap.spice.spice import Spice class COCOEvalCap: def __init__(self, coco, cocoRes): self.evalImgs = [] self.eval = {} self.imgToEval = {} self.coco = coco self.cocoRes = cocoRes self.params = {'image_id': coco.getImgIds()} def evaluate(self): imgIds = self.params['image_id'] # imgIds = self.coco.getImgIds() gts = {} res = {} for imgId in imgIds: gts[imgId] = self.coco.imgToAnns[imgId] res[imgId] = self.cocoRes.imgToAnns[imgId] # ================================================= # Set up scorers # ================================================= print('tokenization...') tokenizer = PTBTokenizer() gts = tokenizer.tokenize(gts) res = tokenizer.tokenize(res) # ================================================= # Set up scorers # ================================================= print('setting up scorers...') scorers = [ (Bleu(4), ["Bleu_1", "Bleu_2", "Bleu_3", "Bleu_4"]), (Meteor(), "METEOR"), (Rouge(), "ROUGE_L"), (Cider(), "CIDEr"), (Spice(), "SPICE") ] # ================================================= # Compute scores # ================================================= for scorer, method in scorers: print('computing %s score...' % (scorer.method())) score, scores = scorer.compute_score(gts, res) if type(method) == list: for sc, scs, m in zip(score, scores, method): self.setEval(sc, m) self.setImgToEvalImgs(scs, gts.keys(), m) print("%s: %0.3f" % (m, sc)) else: self.setEval(score, method) self.setImgToEvalImgs(scores, gts.keys(), method) print("%s: %0.3f" % (method, score)) self.setEvalImgs() def setEval(self, score, method): self.eval[method] = score def setImgToEvalImgs(self, scores, imgIds, method): for imgId, score in zip(imgIds, scores): if not imgId in self.imgToEval: self.imgToEval[imgId] = {} self.imgToEval[imgId]["image_id"] = imgId self.imgToEval[imgId][method] = score def setEvalImgs(self): self.evalImgs = [eval for imgId, eval in self.imgToEval.items()]
[ "tanjiahuei@gmail.com" ]
tanjiahuei@gmail.com
3f9176bfbc4b64d2b60c858a1ea0840683339b80
c84a3895e6fdcaff5a9f97abe9c3efbecbad535f
/strategy/indicator/stochastic/stochastic.py
70af686788a789545bdd38b4abffeef8074a6528
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
cal97g/siis
5a171eb34dd3f7ae6e19d8065ff1e2f8b6251319
adc06e48e5df6ffd7bed6ee6b79d0aa3cfe80e0d
refs/heads/master
2020-07-23T18:11:57.267225
2019-09-05T01:00:37
2019-09-05T01:00:37
207,663,001
0
1
null
2019-09-10T21:05:25
2019-09-10T21:05:25
null
UTF-8
Python
false
false
4,547
py
# @date 2018-09-02 # @author Frederic SCHERMA # @author Xavier BONNIN # @license Copyright (c) 2018 Dream Overflow # Stochastique indicator from strategy.indicator.indicator import Indicator from strategy.indicator.utils import down_sample, MMexp_n, MM_n import numpy as np from talib import STOCH as ta_STOCH, STOCHF as to_STOCHF class StochasticIndicator(Indicator): """ Stochastique indicator. https://www.fidelity.com/learning-center/trading-investing/technical-analysis/technical-indicator-guide/slow-stochastic """ __slots__ = '_len_K', '_len_D', '_prev_k', '_last_k', '_prev_d', '_last_d', '_ks', '_ds' @classmethod def indicator_type(cls): return Indicator.TYPE_MOMENTUM @classmethod def indicator_class(cls): return Indicator.CLS_OSCILLATOR def __init__(self, timeframe, len_K=9, len_D=3): super().__init__("stochastic", timeframe) self._len_K = len_K # periods number for the K self._len_D = len_D # periods number for the D self._prev_k = 0.0 self._last_k = 0.0 self._prev_d = 0.0 self._last_d = 0.0 self._ks = np.array([]) self._ds = np.array([]) @property def length(self): return self._length @length.setter def length(self, length): self._length = length @property def prev_k(self): return self._prev_k @property def last_k(self): return self._last_k @property def prev_d(self): return self._prev_d @property def last_d(self): return self._last_d @property def len_K(self): return self._len_K @len_K.setter def len_K(self, len_K): self._len_K = len_K @property def len_D(self): return self._len_D @len_D.setter def len_D(self, len_D): self._len_D = len_D @property def ks(self): return self._ks @property def ds(self): return self._ds def cross(self): if (self._prev_k > self._prev_d and self._last_k < self._last_d): return -1 elif (self._prev_k < self._prev_d and self._last_k > self._prev_d): return 1 return 0 @staticmethod def Stochastic(N, data, N_D=3): K = np.zeros(len(data)) for (j,d) in enumerate(data): i=min(j,N) highest = max(data[j-i:j+1]) lowest = min(data[j-i:j+1]) if highest == lowest: highest += 0.000000001 K[j]=(d-lowest)/(highest-lowest) # +epsilon to avoid 0 D = MM_n(N_D, K) return (K, D) @staticmethod def Stochastic_sf(N, data, N_D=3, step=1, filtering=False): """ Calcul des stochastiques. N est le nombre de periodes a observer pour repérer le min et le max du cours. N_D est le nombre d'echantillons de K a utiliser pour le calcul de D step permet de ne selectionner qu'un echantillon sur step dans data. filtering permet de filtrer ou non les donnees avant d'appliquer la selection. Retourne les stochastiques K, D interpolees lineairement ; meme taille que data. """ sub_data = down_sample(data, step) if filtering else data [::step] K = np.zeros(len(sub_data)) t_subdata = range(0,len(data),step) for (j,d) in enumerate(sub_data): i=min(j,N) highest = max(sub_data[j-i:j+1]) lowest = min(sub_data[j-i:j+1]) if highest == lowest: highest += 0.000000001 K[j]=(d-lowest)/(highest-lowest) # +epsilon to avoid 0 D = MM_n(N_D, K) return np.interp(range(len(data)), t_subdata, K), np.interp(range(len(data)), t_subdata, D) def compute(self, timestamp, high, low, close): self._prev_k = self._last_k self._prev_d = self._last_d # k, d = StochasticIndicator.Stochastic_sf(self._len_K, close, self._len_D) # , self._step, self._filtering) # k, d = ta_STOCH(high, low, close, fastk_period=self._len_K, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) self._ks, self._ds = to_STOCHF(high, low, close, fastk_period=self._len_K, fastd_period=self._len_D, fastd_matype=0) self._last_k = self._ks[-1] self._last_d = self._ds[-1] self._last_timestamp = timestamp return self._ks, self._ds def trace(self): return tuple(self._last_k, self._last_d)
[ "frederic.scherma@gmail.com" ]
frederic.scherma@gmail.com
90f3fd457bb6be4986e3cb9a139ce1bb796a0b93
260133e46c0c88fd20f2ed18309c5f46508b7fb9
/opengever/core/upgrades/20180427113547_remove_repository_favorites_registry/upgrade.py
d35786bcd9e9437d14564de8a7f13537174a91fb
[]
no_license
robertmuehsig/opengever.core
4180fbea1436fade9b33232a293b0d43ebfc6c51
63b3747793d5b824c56eb3659987bb361d25d8d8
refs/heads/master
2020-09-08T14:55:00.340222
2019-11-08T10:16:02
2019-11-08T10:16:02
221,163,734
0
0
null
2019-11-12T08:08:59
2019-11-12T08:08:54
null
UTF-8
Python
false
false
209
py
from ftw.upgrade import UpgradeStep class RemoveRepositoryFavoritesRegistry(UpgradeStep): """Remove repository favorites registry. """ def __call__(self): self.install_upgrade_profile()
[ "e.schmutz@4teamwork.ch" ]
e.schmutz@4teamwork.ch
e0aaddac3ec13c25540d435aa328944f249a9596
60105dfa9cd52412e86a1970b0873a47c058ca07
/day1/files_ex1.py
7d2050c21a6d506445c58dc66deef58798fb2eec
[ "Apache-2.0" ]
permissive
ktbyers/pynet-ons-feb19
d6802ec01902169dffebe2b11fcd3a1ed9c42d3d
5f02125f115fda2c26af87656b4f83d98cd2822c
refs/heads/master
2020-04-19T20:43:31.754871
2019-02-25T20:47:40
2019-02-25T20:47:40
168,422,755
0
6
Apache-2.0
2019-02-07T20:03:09
2019-01-30T22:05:35
Python
UTF-8
Python
false
false
320
py
#!/usr/bin/env python # READ #### f = open("my_file.txt") my_content = f.read() print(my_content) # WRITE #### print("\nWriting file.") f = open("new_file.txt", "w") f.write("whatever2\n") f.close() # APPEND #### print("\nAppending file.") with open("new_file.txt", "a") as f: f.write("something else\n") print()
[ "ktbyers@twb-tech.com" ]
ktbyers@twb-tech.com
d036805b85edb2e1846da24c7dc43c38d5a4e726
c8c95520fb1a17d627a0256df2c6702f4f53403a
/3.3_the_for_loop.py
371bcc17241b1a8ab78f7f1d729ca822967cbf14
[]
no_license
wsargeant/httlacs
608f1b4b34c95f18f934f10883beb56a2895c269
3337b369c541e18d5ed9ecbca35494c3ebcfa591
refs/heads/master
2023-02-21T21:10:03.228762
2021-01-25T08:44:46
2021-01-25T08:44:46
284,936,152
0
0
null
2020-08-28T10:35:17
2020-08-04T09:32:38
null
UTF-8
Python
false
false
202
py
def main(): pass if __name__ == '__main__': main() for f in ["Joe", "Steve", "Pete", "Ian", "Mike", "Dom"]: invite = "Hi " + f + ". Please come to my party on Saturday." print(invite)
[ "69194027+wsargeant@users.noreply.github.com" ]
69194027+wsargeant@users.noreply.github.com
ee7b8e64c5c5aabbd39dc3e97b98f0c125bbe83b
ba7e577bc4d083d5bfb1b0622d6149d57537bc62
/leetcode/217_contains_duplicate.py
4a01bac85e2491ed77d936570df8ff60f59b2605
[]
no_license
lvraikkonen/GoodCode
5b59f51252384de38fd21f13d4afda1f4f8be94d
a0f270c1adce25be11df92877813037f2e73e28b
refs/heads/master
2022-05-04T19:55:40.751420
2022-04-12T09:41:15
2022-04-12T09:41:15
71,972,790
0
0
null
2020-10-13T18:57:51
2016-10-26T06:24:11
Java
UTF-8
Python
false
false
572
py
from collections import Counter def containsDuplicate_counter(nums): """ :type nums: List[int] :rtype: bool """ n = Counter(nums) for k, v in n.items(): if v > 1: return True return False def containsDuplicate_set(nums): """ :type nums: List[int] :rtype: bool """ distinct_nums = set() for num in nums: if num in distinct_nums: return True distinct_nums.add(num) return False if __name__ == "__main__": result = containsDuplicate_set([1,2,3,3]) print result
[ "claus.lv@hotmail.com" ]
claus.lv@hotmail.com
7e9b9a0aad90d98e4fb2409f0db85fadcc0b665d
bc441bb06b8948288f110af63feda4e798f30225
/architecture_view_sdk/model/metadata_center/stream_metric_states_pb2.py
8a7a27d80fc16e11d705b7d43834edd01cdc33a1
[ "Apache-2.0" ]
permissive
easyopsapis/easyops-api-python
23204f8846a332c30f5f3ff627bf220940137b6b
adf6e3bad33fa6266b5fa0a449dd4ac42f8447d0
refs/heads/master
2020-06-26T23:38:27.308803
2020-06-16T07:25:41
2020-06-16T07:25:41
199,773,131
5
0
null
null
null
null
UTF-8
Python
false
true
3,685
py
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: stream_metric_states.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from architecture_view_sdk.model.metadata_center import stream_metric_schema_pb2 as architecture__view__sdk_dot_model_dot_metadata__center_dot_stream__metric__schema__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='stream_metric_states.proto', package='metadata_center', syntax='proto3', serialized_options=_b('ZIgo.easyops.local/contracts/protorepo-models/easyops/model/metadata_center'), serialized_pb=_b('\n\x1astream_metric_states.proto\x12\x0fmetadata_center\x1a\x46\x61rchitecture_view_sdk/model/metadata_center/stream_metric_schema.proto\"h\n\x12StreamMetricStates\x12\x0b\n\x03org\x18\x01 \x01(\x05\x12\x0f\n\x07\x63ommand\x18\x02 \x01(\t\x12\x34\n\x07payload\x18\x03 \x03(\x0b\x32#.metadata_center.StreamMetricSchemaBKZIgo.easyops.local/contracts/protorepo-models/easyops/model/metadata_centerb\x06proto3') , dependencies=[architecture__view__sdk_dot_model_dot_metadata__center_dot_stream__metric__schema__pb2.DESCRIPTOR,]) _STREAMMETRICSTATES = _descriptor.Descriptor( name='StreamMetricStates', full_name='metadata_center.StreamMetricStates', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='org', full_name='metadata_center.StreamMetricStates.org', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='command', full_name='metadata_center.StreamMetricStates.command', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='payload', full_name='metadata_center.StreamMetricStates.payload', index=2, number=3, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=119, serialized_end=223, ) _STREAMMETRICSTATES.fields_by_name['payload'].message_type = architecture__view__sdk_dot_model_dot_metadata__center_dot_stream__metric__schema__pb2._STREAMMETRICSCHEMA DESCRIPTOR.message_types_by_name['StreamMetricStates'] = _STREAMMETRICSTATES _sym_db.RegisterFileDescriptor(DESCRIPTOR) StreamMetricStates = _reflection.GeneratedProtocolMessageType('StreamMetricStates', (_message.Message,), { 'DESCRIPTOR' : _STREAMMETRICSTATES, '__module__' : 'stream_metric_states_pb2' # @@protoc_insertion_point(class_scope:metadata_center.StreamMetricStates) }) _sym_db.RegisterMessage(StreamMetricStates) DESCRIPTOR._options = None # @@protoc_insertion_point(module_scope)
[ "service@easyops.cn" ]
service@easyops.cn
2fcaf139e76286b816d99605e71bc07a933e540c
dc940d7614c4cf55a3c61a1ad4ee48e4ea4e319d
/src/slurmify/slurmify.py
cc78977d8e499ee972aa5bd9eb2e6fe671d6160d
[ "MIT" ]
permissive
salotz/slurmify
b4c88e434c2814c71fcef9cd13ecd716163a75d8
4a6da629706621b9b2633d34e574b121a75a8f87
refs/heads/master
2020-04-28T23:22:10.227665
2019-10-08T01:37:33
2019-10-08T01:37:33
175,651,924
0
1
MIT
2020-12-01T07:43:57
2019-03-14T15:42:30
Python
UTF-8
Python
false
false
5,320
py
import os import os.path as osp import tempfile import subprocess from jinja2 import Environment, FileSystemLoader from slurmify import TEMPLATES_PATH # names of the templates SLURM_JOB_TEMPLATE = "slurm_job.sh.j2" SLURM_RUN_TEMPLATE = "slurm_run.sh.j2" SLURM_SETUP_TEMPLATE = "slurm_setup.sh.j2" SLURM_TEARDOWN_TEMPLATE = "slurm_teardown.sh.j2" SLURM_COMMANDS_TEMPLATE = "slurm_commands.sh.j2" SLURM_SCRIPT_TEMPLATE = "slurm_script.sh.j2" # list of all the templates SLURM_TEMPLATE_NAMES = (SLURM_JOB_TEMPLATE, SLURM_RUN_TEMPLATE, SLURM_SCRIPT_TEMPLATE, SLURM_COMMANDS_TEMPLATE) # the names of the targets and whether or not they are optional (True) # or not (False). This is from the perspective of the template and not # the interfaces of the programs which may support defaults and other # options etc. SLURM_JOB_TARGETS = ( ('job_name', False), ('stderr_log_dir', False), ('stdout_log_dir', False), ('login_shell', True), ('mail_user', True), ('mail_type', True), ) SLURM_RUN_TARGETS = ( ('walltime', False), ('nodes', False), ('ntasks', False), ('cpus_per_task', False), ('mem_per_cpu', True), ('node_mem', True), ('nodelist', True), ('constraint', True), ('gres', True), ('chdir', True), ) SLURM_SCRIPT_TARGETS = ( ('slurm_job', False), ('slurm_run', False), ('setup', True), ('payload', False), ('teardown', True), ) SLURM_COMMANDS_TARGETS = ( ('commands', False), ('epilog', True) ) SLURM_SCRIPT_EMBED_TARGETS = ( ('script', False), ('epilog', True) ) SLURM_SETUP_TARGETS = ( ('task_name', False), ('task_dir_path', False), ('env_vars', True), ('gnu_module', True), ('cuda_module', True), # slurm job stuff ('walltime', True), ('memory', True), ('num_nodes', True), ('num_processors', True), ('num_gpus', True), ) # Defaults MAIL_TYPE_DEFAULT = "BEGIN,END,FAIL" def get_env(): return Environment(loader=FileSystemLoader(TEMPLATES_PATH)) def check_kwargs(targets, input_kwargs): missing = [] for key, optional in targets: if key not in input_kwargs: if not optional: missing.append(key) return missing class SlurmJob(): def __init__(self, job_name, logs_dir='logs', setup=None, teardown=None, login_shell=True, email=None, mail_type='BEGIN,END,FAIL'): if logs_dir: stderr_log_dir = logs_dir stdout_log_dir = logs_dir self.job_kwargs = { 'job_name' : job_name, 'stderr_log_dir' : stderr_log_dir, 'stdout_log_dir' : stdout_log_dir, 'login_shell' : login_shell, 'mail_user' : email, 'mail_type' : mail_type } self.env = get_env() job_template = self.env.get_template(SLURM_JOB_TEMPLATE) # check to make sure all arguments work if len(check_kwargs(SLURM_JOB_TARGETS, self.job_kwargs)) < 1: self._job_header = job_template.render(self.job_kwargs) else: raise ValueError # get default setup and teardown scripts self._setup = "" self._teardown = "" @property def job_header(self): return self._job_header @property def setup(self): return self._setup @property def teardown(self): return self._teardown def run(self, run_kwargs, commands, epilog=None): run_template = self.env.get_template(SLURM_RUN_TEMPLATE) commands_template = self.env.get_template(SLURM_COMMANDS_TEMPLATE) script_template = self.env.get_template(SLURM_SCRIPT_TEMPLATE) if len(check_kwargs(SLURM_RUN_TARGETS, run_kwargs)) < 1: run_header = run_template.render(run_kwargs) else: raise ValueError payload = commands_template.render(commands=commands, epilog=epilog) script_kwargs = { 'slurm_job' : self.job_header, 'slurm_run' : run_header, 'setup' : self.setup, 'payload' : payload, 'teardown' : self.teardown } if len(check_kwargs(SLURM_SCRIPT_TARGETS, script_kwargs)) < 1: script_str = script_template.render(script_kwargs) else: raise ValueError # make a temporary file for the script and use sbatch to # submit it with tempfile.NamedTemporaryFile() as tmpfile: # write the script to the tempfile tmpfile.write(str.encode(script_str)) # set the file pointer back to the beginning of the file # so we don't have to reopen it tmpfile.seek(0) # the path to the temp file tmpfile_path = tmpfile.name # then actually submit the script and get the return # values complete_process = subprocess.run(['sbatch', tmpfile_path]) # if there was error get it: if complete_process.stderr is not None: pass # get the jobid from stdout #complete_process.stdout return 0, complete_process
[ "samuel.lotz@salotz.info" ]
samuel.lotz@salotz.info
7a8fa12f5d1cb13446a07ad2b0d36370c27adf16
1d04c90b3331261d741cc4f8757aeb0088193627
/setup.py
fab6d30a6a0fe2cbc72fdd710ca21377f27e0b75
[ "ZPL-2.1" ]
permissive
jean/Products.ZopeVersionControl
11f5251fea47e12b6db10c2ff2067f23a93ebad4
c5a7efacf39bd27a7acda525096f7f05e0672179
refs/heads/master
2021-01-22T16:37:29.630614
2013-03-13T14:29:07
2013-03-13T14:29:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
849
py
from setuptools import setup, find_packages __version__ = '1.1.4dev' setup( name='Products.ZopeVersionControl', version=__version__, description="Zope Version Control", long_description=(open('README.rst').read() + "\n" + open('CHANGES.rst').read()), classifiers=[ 'Framework :: Zope2', ], license='ZPL', author='Zope Foundation and Contributors', author_email='zope-dev@zope.org', url='http://pypi.python.org/pypi/Products.ZopeVersionControl', packages=find_packages('src'), package_dir={'': 'src'}, namespace_packages=['Products'], include_package_data=True, zip_safe=False, install_requires=[ 'setuptools', 'zope.interface', 'Acquisition', 'DateTime', 'transaction', 'ZODB3', 'Zope2', ], )
[ "hanno@hannosch.eu" ]
hanno@hannosch.eu
ce530f3a0911852d37807d078ec6dcec182f3b0f
a2dce63dc04f484d1457073610343378656a1ffd
/p24.py
c193733b0ed3535db6ba4015fe24cd7bf5da243e
[]
no_license
analaura09/pythongame
5ece67047095160cdbc56ae3bb14920c787d8d02
54c83cf731a384fdb04bc4c3ed0bcf109b03d5ed
refs/heads/main
2023-03-29T00:35:35.713616
2021-03-21T17:53:28
2021-03-21T17:53:28
348,432,418
0
0
null
null
null
null
UTF-8
Python
false
false
382
py
import run() nome = str(input(' Digite o nome da cidade: ')).strip() print(nome[:5].upper == 'SANTO') opçao = int(input('deseja repetir esse exercicio?[1] \ndeseja voltar para o mundo1? [2] \ndeseja sair do jogo?[3]')) if opçao == 1: import p24 p24.run() if opçao ==2: import mundo1 mundo1.run() if opçao == 3: print('Obrigada por jogar! Volte sempre :)')
[ "pereira.laura@escolar.ifrn.edu.br" ]
pereira.laura@escolar.ifrn.edu.br
bd43d4b1bc8f330307b9720cb6b8e6383124f6dc
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/62/usersdata/191/32531/submittedfiles/ex1.py
e50dfa28cc19c4488d103df646274da8bad5050f
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
338
py
# -*- coding: utf-8 -*- from __future__ import division a = float(input('Digite a: ')) b = float(input('Digite b: ')) c = float(input('Digite c: ')) delta=(b**2)-(4*a*c) if delta>=0: x1=(-b+delta**(1/2))/(2*a) x2=(-b-delta**(1/2))/(2*a) print('x1 é igual a %.2f'%x1) print('x2 é igual a %.2f'%x2) else: print('SRR')
[ "rafael.mota@ufca.edu.br" ]
rafael.mota@ufca.edu.br
61e37196f31ae35d096a8c8fd30ddb31149a289a
3256af0d6c19732bb84b256a9f792aaf7f3d901a
/f5/bigip/tm/asm/policies/test/functional/test_extractions.py
64620349bef5b578dcd0fbe54e55e1a2ec400974
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
F5Networks/f5-common-python
73e33ea489d989399d205077163f24ce584d83b9
3050df0079c2426af99b9a1b8f93d0b512468ff4
refs/heads/development
2023-08-29T10:11:23.713392
2022-09-21T02:45:03
2022-09-21T02:45:03
45,062,555
286
180
Apache-2.0
2023-05-12T23:13:03
2015-10-27T18:48:06
Python
UTF-8
Python
false
false
4,460
py
# Copyright 2017 F5 Networks Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import pytest import tempfile from distutils.version import LooseVersion from f5.bigip.tm.asm.policies.extractions import Extraction from f5.sdk_exception import MissingRequiredCreationParameter from requests.exceptions import HTTPError @pytest.fixture(scope='function') def set_extraction(policy): file = tempfile.NamedTemporaryFile() name = os.path.basename(file.name) r1 = policy.extractions_s.extraction.create( extractFromAllItems=True, name=name ) yield r1 r1.delete() @pytest.mark.skipif( LooseVersion(pytest.config.getoption('--release')) < LooseVersion('11.6.0'), reason='This collection is fully implemented on 11.6.0 or greater.' ) class TestExtractions(object): def test_create_req_arg(self, policy): file = tempfile.NamedTemporaryFile() name = os.path.basename(file.name) r1 = policy.extractions_s.extraction.create( extractFromAllItems=True, name=name ) assert r1.kind == 'tm:asm:policies:extractions:extractionstate' r1.delete() def test_create_mandatory_arg_missing(self, policy2): file = tempfile.NamedTemporaryFile() name = os.path.basename(file.name) with pytest.raises(MissingRequiredCreationParameter) as err: policy2.extractions_s.extraction.create( extractFromAllItems=False, name=name ) assert 'This resource requires at least one of the' in str(err.value) def test_create_mandatory_arg_present(self, policy2): file = tempfile.NamedTemporaryFile() name = os.path.basename(file.name) r1 = policy2.extractions_s.extraction.create( extractFromAllItems=False, name=name, extractFromRegularExpression='["test"]') assert r1.kind == 'tm:asm:policies:extractions:extractionstate' assert r1.extractFromRegularExpression == '["test"]' assert r1.extractFromAllItems is False r1.delete() def test_refresh(self, set_extraction, policy): r1 = set_extraction r2 = policy.extractions_s.extraction.load(id=r1.id) assert r1.kind == r2.kind assert r1.extractFromAllItems == r2.extractFromAllItems assert r1.searchInXml == r2.searchInXml r2.modify(searchInXml=True) assert r1.searchInXml is False assert r2.searchInXml is True r1.refresh() assert r1.searchInXml is True def test_delete(self, policy): file = tempfile.NamedTemporaryFile() name = os.path.basename(file.name) r1 = policy.extractions_s.extraction.create( extractFromAllItems=True, name=name ) idhash = r1.id r1.delete() with pytest.raises(HTTPError) as err: policy.extractions_s.extraction.load(id=idhash) assert err.value.response.status_code == 404 def test_load_no_object(self, policy): with pytest.raises(HTTPError) as err: policy.extractions_s.extraction.load(id='Lx3553-321') assert err.value.response.status_code == 404 def test_load(self, set_extraction, policy): r1 = set_extraction assert r1.kind == 'tm:asm:policies:extractions:extractionstate' assert r1.searchInXml is False r1.modify(searchInXml=True) assert r1.searchInXml is True r2 = policy.extractions_s.extraction.load(id=r1.id) assert r1.kind == r2.kind assert r1.searchInXml == r2.searchInXml def test_extractions_subcollection(self, policy, set_extraction): r1 = set_extraction assert r1.kind == 'tm:asm:policies:extractions:extractionstate' cc = policy.extractions_s.get_collection() assert isinstance(cc, list) assert len(cc) assert isinstance(cc[0], Extraction)
[ "caphrim007@gmail.com" ]
caphrim007@gmail.com
ba4ce143ab4efe10927d17ed3c09492ccae1cd5b
b3aa3d77836fa8f05b54d68e7bd6bff19dced90d
/Codeforces/636 Div 3/D.py
84ea81677d1e3e2eaf8eef86a8f7d3c3ae042df2
[]
no_license
anoubhav/Codeforces-Atcoder-Codechef-solutions
660c5b78723791bc33b1d51977bf11ebe6dfe4c1
aeebcae332af64aba49f52261d11aa6996f33b1c
refs/heads/master
2022-12-08T14:02:49.574928
2020-08-29T14:18:30
2020-08-29T14:18:30
255,004,401
0
0
null
null
null
null
UTF-8
Python
false
false
4,380
py
# # Unsolved in contest ## Accepted solution: O(n+k) solution # https://www.youtube.com/watch?v=QouZfBC9CVw&list=RDCMUC4lyxGubhu5u1s1LYCwXtZw&index=2 def prefix_algo(): t = int(input()) from collections import defaultdict import math for _ in range(t): n, k = list(map(int, input().split())) seq = list(map(int, input().split())) prefix_arr = [0]*(2*k+10) zero_count = defaultdict(int) for i in range(n//2): zero_count[seq[i] + seq[n-i-1]] += 1 a, b = sorted((seq[i], seq[n-i-1])) L = a + 1 R = b + k prefix_arr[L] += 1 prefix_arr[R+1] -= 1 prefsum = 0 for i in range(2*k + 10): prefsum += prefix_arr[i] prefix_arr[i] = prefsum ans = n for i in range(2, 2*k + 1): zero = zero_count[i] ones = prefix_arr[i] - zero twos = n//2 - ones - zero total = ones + twos*2 ans = min(ans, total) print(ans) prefix_algo() ## Naive solution: O(n*k) - TLE def Naive(): t = int(input()) import math for _ in range(t): n, k = list(map(int, input().split())) seq = list(map(int, input().split())) ans = 10**6 for tot in range(2, 2*k + 1): counter = 0 for i in range(n//2): a, b = seq[i], seq[n - i - 1] if a+b>tot: minchange = max(a-1, b-1) if a+b - minchange > tot: counter += 2 else: counter += 1 elif a + b < tot: maxchange = max(k - a, k - b) if a+b+maxchange < tot: counter +=2 else: counter += 1 if counter < ans: ans = counter print(ans) ### Main mistake was that I diregarded the individual numbers (a, b) and only took the sum. The number5 ## Failed approach 1 # ans = 10**6 # pair_sum = list() # for i in range(n//2): # pair_sum.append(seq[i] + seq[n - i - 1]) # for master in pair_sum: # counter = 0 # for pair in pair_sum: # if pair!=master: # if abs(pair - master) >= k: # counter += 2 # else: # counter += 1 # if counter<ans: # ans = counter # master = k # counter = 0 # for pair in pair_sum: # if pair!=master: # if abs(pair - master) >= k: # counter += 2 # else: # counter += 1 # if counter<ans: # ans = counter # print(ans) ## Failed approach 2 # pair_sum = dict() # mode_count = 0 # for i in range(n//2): # temp = seq[i] + seq[n - i - 1] # if temp in pair_sum: pair_sum[temp] += 1 # else: pair_sum[temp] = 1 # if pair_sum[temp]>mode_count: # mode_count = pair_sum[temp] # ans = 10**6 # for key, v in pair_sum.items(): # if v == mode_count: # mode_sum = key # counter = 0 # for i in range(n//2): # temp = seq[i] + seq[n - i - 1] # if temp!=mode_sum: # if abs(temp - mode_sum) >= k: # counter += 2 # else: # counter += 1 # # print(mode_sum, temp, counter) # if counter<ans: # ans = counter # if k//2 not in pair_sum: # mode_sum = k//2 # counter = 0 # for i in range(n//2): # temp = seq[i] + seq[n - i - 1] # if temp!=mode_sum: # if abs(temp - mode_sum) >= k: # counter += 2 # else: # counter += 1 # # print(mode_sum, temp, counter) # if counter<ans: # ans = counter # ans = min(n//2, ans) # print(ans)
[ "anoubhav.agarwaal@gmail.com" ]
anoubhav.agarwaal@gmail.com
a4e1b7f960a339d2696bd14deaf451002d5bf475
12cb9edd19612c132028c45707b4ec944ae4ae88
/3-deploy_web_static.py
8438f8acc72a80543e4eb6219a324f9f94c48f43
[]
no_license
imperfectskillz/AirBnB_clone_v2
6345389a99f66c23d310ac3030986ef8973c00bb
8910d78da6a6bb6f14fa569af913739f4b5cf5f5
refs/heads/master
2020-03-08T01:08:53.124647
2018-04-19T01:14:16
2018-04-19T01:14:16
127,822,734
0
0
null
2018-04-02T23:11:34
2018-04-02T23:11:34
null
UTF-8
Python
false
false
1,537
py
#!/usr/bin/python3 #fabric script generates a tgz archive from fabric.api import * from datetime import datetime import os env.hosts = ["52.91.246.129", "107.23.155.217"] env.user = "ubuntu" def do_pack(): """ creates tgz """ filetime = datetime.now().strftime('%Y%m%d%H%M%s') filename = 'versions/web_static_{}.tgz'.format(filetime) try: local("mkdir -p versions") local('tar -cvzf {} web_static'.format(filename)) return filename except: return None def do_deploy(archive_path): """ distributes archive to web servers """ file = archive_path.split("/")[1] if os.path.isfile(archive_path): try: put(archive_path, "/tmp/{}".format(file)) file1 = file.split(".")[0] run("mkdir -p /data/web_static/releases/{}/".format(file1)) run("tar -xzf /tmp/{} -C /data/web_static/releases/{}".format( file, file1)) run("rm /tmp/{}".format(file)) run("mv /data/web_static/releases/{}/web_static/* /data/web_static/releases/{}/".format(file1, file1)) run("rm -rf /data/web_static/releases/{}/web_static".format(file1)) run("rm -rf /data/web_static/current") run("ln -s /data/web_static/releases/{}/ /data/web_static/current".format(file1)) return True except: return False def deploy(): """ set-up """ temp = do_pack() if not temp: return False return do_deploy(temp)
[ "j.choi.89@gmail.com" ]
j.choi.89@gmail.com
c29aa7ebe11d45637e582453e40d5f668b9e0189
5b3d8b5c612c802fd846de63f86b57652d33f672
/Python/six_kyu/digital_root.py
5655cf937c38c8dc012f4fb38a715f99a3c7198f
[ "Apache-2.0" ]
permissive
Brokenshire/codewars-projects
1e591b57ed910a567f6c0423beb194fa7f8f693e
db9cd09618b8a7085b0d53ad76f73f9e249b9396
refs/heads/master
2021-07-22T18:50:25.847592
2021-01-25T23:27:17
2021-01-25T23:27:17
228,114,677
1
0
null
null
null
null
UTF-8
Python
false
false
1,183
py
# Python solution for 'Sum of Digits / Digital Root' codewars question. # Level: 6 kyu # Tags: Algorithms, Mathematics, Numbers, and Arithmetic. # Author: Jack Brokenshire # Date: 13/02/2020 import unittest def digital_root(n): """ A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers. :param n: A input integer value. :return: Adds each digit together in the given number until it reaches a single-digit number. """ while n > 10: n = sum([int(x) for x in str(n) if n > 10]) digital_root(n) return n class TestDigitalRoot(unittest.TestCase): """Class to test 'digital_root' function""" def test_digital_root(self): self.assertEqual(digital_root(16), 7) self.assertEqual(digital_root(456), 6) self.assertEqual(digital_root(942), 6) self.assertEqual(digital_root(132189), 6) self.assertEqual(digital_root(493193), 2) if __name__ == '__main__': unittest.main()
[ "29889878+Brokenshire@users.noreply.github.com" ]
29889878+Brokenshire@users.noreply.github.com
fb5e0cbc84d8801e24e350f9c849aaae07d4483e
4de03eecadc4c69caf792f4773571c2f6dbe9d68
/tests/api/test_beshared.py
6362f1d3b23953ff61e2bcedd67f638da265f5a2
[ "Apache-2.0" ]
permissive
Tr-1234/seahub
c1663dfd12f7584f24c160bcf2a83afdbe63a9e2
ed255e0566de054b5570218cb39cc320e99ffa44
refs/heads/master
2022-12-23T16:20:13.138757
2020-10-01T04:13:42
2020-10-01T04:13:42
300,138,290
0
0
Apache-2.0
2020-10-01T04:11:41
2020-10-01T04:11:40
null
UTF-8
Python
false
false
2,540
py
import json import seaserv from seaserv import seafile_api from seahub.test_utils import BaseTestCase class BeSharedReposTest(BaseTestCase): def setUp(self): self.login_as(self.admin) def tearDown(self): self.remove_repo() def _prepare_repo_and_group(self): # create repo for user sub_repo_id = seafile_api.create_virtual_repo(self.repo.id, self.folder, self.repo.name, '', self.user.username) self.sub_repo_id = sub_repo_id # create group for admin admin_group_id = seaserv.ccnet_threaded_rpc.create_group('admin-group', self.admin.email) self.admin_group_id = admin_group_id def test_can_list_personal_shared_repo(self): self._prepare_repo_and_group() # A user shares a folder to admin with permission 'rw'. seafile_api.share_repo(self.sub_repo_id, self.user.username, self.admin.username, 'rw') resp = self.client.get('/api2/beshared-repos/') self.assertEqual(200, resp.status_code) json_resp = json.loads(resp.content) assert json_resp[0]['repo_id'] == self.sub_repo_id assert json_resp[0]['share_type'] == 'personal' def test_can_list_group_repo(self): self._prepare_repo_and_group() # A user shares a folder to admin group with permission 'rw'. seafile_api.set_group_repo(self.sub_repo_id, self.admin_group_id, self.user.username, 'rw') resp = self.client.get('/api2/beshared-repos/') self.assertEqual(200, resp.status_code) json_resp = json.loads(resp.content) assert json_resp[0]['repo_id'] == self.sub_repo_id assert json_resp[0]['share_type'] == 'group' def test_can_list_public_repo(self): self._prepare_repo_and_group() # A user shares a folder to public with permission 'rw'. seafile_api.add_inner_pub_repo(self.sub_repo_id, 'rw') resp = self.client.get('/api2/beshared-repos/') self.assertEqual(200, resp.status_code) json_resp = json.loads(resp.content) assert json_resp[0]['repo_id'] == self.sub_repo_id assert json_resp[0]['share_type'] == 'public'
[ "colinsippl@gmx.de" ]
colinsippl@gmx.de
0fcb38ed4b11b89f3af06a4adbf4410b3eab6123
528f910908885c3ded4ecc6380b9603c8dcacbd6
/tbapi/top/api/rest/SimbaRptCusteffectGetRequest.py
58297bc4539f31f788a51628d13782982910cac7
[]
no_license
Monica-ckd/data007
15fe9c4c898a51a58100138b6b064211199d2ed1
0e54ae57eb719b86ec14ce9f77b027882a3398a8
refs/heads/master
2023-03-16T05:26:14.257318
2016-05-25T06:57:05
2016-05-25T06:57:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
468
py
''' Created by auto_sdk on 2013-04-01 16:44:41 ''' from top.api.base import RestApi class SimbaRptCusteffectGetRequest(RestApi): def __init__(self,domain='gw.api.taobao.com',port=80): RestApi.__init__(self,domain, port) self.end_time = None self.nick = None self.page_no = None self.page_size = None self.source = None self.start_time = None self.subway_token = None def getapiname(self): return 'taobao.simba.rpt.custeffect.get'
[ "root@u16392468.onlinehome-server.com" ]
root@u16392468.onlinehome-server.com
10d497ee159d5fa12d220be2c774fd33f365bf17
fcd80f58e8006cb6bb04ac9dca4b3d58dc8d1d70
/files/example197_file_seek.py
9beb719cee7f34becceb6ea5685d4a6b719d77dd
[]
no_license
penguuu/python-examples
56e252be3dbf61cb0345cf8f95a01577f755f332
32f46ba435fd2797454af6228b368524ac1ebd79
refs/heads/master
2021-01-04T22:18:03.474098
2020-02-15T20:32:18
2020-02-15T20:32:18
240,781,755
0
0
null
null
null
null
UTF-8
Python
false
false
223
py
#!/usr/bin/python fo = open("example197_file_seek.py","r") print "Name of the file: ", fo.name line = fo.readline() print "Read Line: %s" % line fo.seek(0,0) line = fo.readline() print "Read Line: %s" % line fo.close()
[ "pengu@shadow.babcom" ]
pengu@shadow.babcom
64b2dd0ee2448d18b763f3d2663e33790714d44c
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
/MbbX7qJJeEnQu9bKr_16.py
770c027324993f571e65cc9d43a73570afc5f508
[]
no_license
daniel-reich/ubiquitous-fiesta
26e80f0082f8589e51d359ce7953117a3da7d38c
9af2700dbe59284f5697e612491499841a6c126f
refs/heads/master
2023-04-05T06:40:37.328213
2021-04-06T20:17:44
2021-04-06T20:17:44
355,318,759
0
0
null
null
null
null
UTF-8
Python
false
false
217
py
def max_occur(text): freqs = {c: text.count(c) for c in text if text.count(c) > 1} ​ if not freqs: return 'No Repetition' ​ return sorted(c for c in freqs if freqs[c] == max(freqs.values()))
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
6d23004951c597c739a77280febec8db68afdaf6
d8a5525d2e2070f0434e971b6b03df6d6457d47d
/torch_glow/tests/nodes/zero_test.py
3a5472f453da540a4dc3a705bbf9d2e2a12c8655
[ "Apache-2.0" ]
permissive
pytorch/glow
0006dbac932da386ff1143cff166b89323aec337
f35c3d180290c79d5d3578ccc800bb35ce88e420
refs/heads/master
2023-08-30T17:44:59.170945
2023-08-29T05:29:36
2023-08-29T05:29:36
105,281,531
3,201
780
Apache-2.0
2023-09-14T08:29:16
2017-09-29T14:28:18
C++
UTF-8
Python
false
false
1,146
py
# Copyright (c) Glow Contributors. See CONTRIBUTORS file. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, division, print_function, unicode_literals import torch from tests import utils class TestZero(utils.TorchGlowTestCase): def test_zero_basic(self): """Basic test of the PyTorch zero Node on Glow.""" class TestModule(torch.nn.Module): def forward(self, a): b = torch.zeros(a.size(), dtype=torch.float) return a + b x = torch.randn(2, 3, 4) utils.compare_tracing_methods(TestModule(), x, fusible_ops={"aten::zeros"})
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
b5995ba400cdef8251e2ed83be1b7a3160a382e1
627cca9406c31ce30c493ff7502f79eb4c57eee3
/xcha/pools/pool_config.py
2302aa6557d98b0686a6c0e7e602138bfb72a332
[ "Apache-2.0" ]
permissive
blockchiansea/xcha-blockchain
40c6d36813f671e94316a522904238f495f39f6b
7de0ba89056236e30069aef12fe25843f6093bcf
refs/heads/master
2023-07-26T02:36:57.654196
2021-09-06T06:04:21
2021-09-06T06:04:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,801
py
import logging from dataclasses import dataclass from pathlib import Path from typing import List from blspy import G1Element from xcha.types.blockchain_format.sized_bytes import bytes32 from xcha.util.byte_types import hexstr_to_bytes from xcha.util.config import load_config, save_config from xcha.util.streamable import Streamable, streamable """ Config example This is what goes into the user's config file, to communicate between the wallet and the farmer processes. pool_list: launcher_id: ae4ef3b9bfe68949691281a015a9c16630fc8f66d48c19ca548fb80768791afa authentication_public_key: 970e181ae45435ae696508a78012dc80548c334cf29676ea6ade7049eb9d2b9579cc30cb44c3fd68d35a250cfbc69e29 owner_public_key: 84c3fcf9d5581c1ddc702cb0f3b4a06043303b334dd993ab42b2c320ebfa98e5ce558448615b3f69638ba92cf7f43da5 payout_instructions: c2b08e41d766da4116e388357ed957d04ad754623a915f3fd65188a8746cf3e8 pool_url: localhost p2_singleton_puzzle_hash: 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824 target_puzzle_hash: 344587cf06a39db471d2cc027504e8688a0a67cce961253500c956c73603fd58 """ # noqa log = logging.getLogger(__name__) @dataclass(frozen=True) @streamable class PoolWalletConfig(Streamable): launcher_id: bytes32 pool_url: str payout_instructions: str target_puzzle_hash: bytes32 p2_singleton_puzzle_hash: bytes32 owner_public_key: G1Element authentication_public_key: G1Element def load_pool_config(root_path: Path) -> List[PoolWalletConfig]: config = load_config(root_path, "config.yaml") ret_list: List[PoolWalletConfig] = [] if "pool_list" in config["pool"]: for pool_config_dict in config["pool"]["pool_list"]: try: pool_config = PoolWalletConfig( hexstr_to_bytes(pool_config_dict["launcher_id"]), pool_config_dict["pool_url"], pool_config_dict["payout_instructions"], hexstr_to_bytes(pool_config_dict["target_puzzle_hash"]), hexstr_to_bytes(pool_config_dict["p2_singleton_puzzle_hash"]), G1Element.from_bytes(hexstr_to_bytes(pool_config_dict["owner_public_key"])), G1Element.from_bytes(hexstr_to_bytes(pool_config_dict["authentication_public_key"])), ) ret_list.append(pool_config) except Exception as e: log.error(f"Exception loading config: {pool_config_dict} {e}") return ret_list async def update_pool_config(root_path: Path, pool_config_list: List[PoolWalletConfig]): full_config = load_config(root_path, "config.yaml") full_config["pool"]["pool_list"] = [c.to_json_dict() for c in pool_config_list] save_config(root_path, "config.yaml", full_config)
[ "xchanet@gmail.com" ]
xchanet@gmail.com
2a04a0b4d524fd056e57e98a0700803743f8a35a
afd2087e80478010d9df66e78280f75e1ff17d45
/torch/nn/intrinsic/modules/fused.py
dc962f956427ec6f6e6b1d0580a1d5c73bd9cd29
[ "BSD-3-Clause", "BSD-2-Clause", "LicenseRef-scancode-secret-labs-2011", "LicenseRef-scancode-generic-cla", "BSL-1.0", "Apache-2.0" ]
permissive
pytorch/pytorch
7521ac50c47d18b916ae47a6592c4646c2cb69b5
a6f7dd4707ac116c0f5fb5f44f42429f38d23ab4
refs/heads/main
2023-08-03T05:05:02.822937
2023-08-03T00:40:33
2023-08-03T04:14:52
65,600,975
77,092
24,610
NOASSERTION
2023-09-14T21:58:39
2016-08-13T05:26:41
Python
UTF-8
Python
false
false
901
py
from torch.ao.nn.intrinsic import BNReLU2d from torch.ao.nn.intrinsic import BNReLU3d from torch.ao.nn.intrinsic import ConvBn1d from torch.ao.nn.intrinsic import ConvBn2d from torch.ao.nn.intrinsic import ConvBn3d from torch.ao.nn.intrinsic import ConvBnReLU1d from torch.ao.nn.intrinsic import ConvBnReLU2d from torch.ao.nn.intrinsic import ConvBnReLU3d from torch.ao.nn.intrinsic import ConvReLU1d from torch.ao.nn.intrinsic import ConvReLU2d from torch.ao.nn.intrinsic import ConvReLU3d from torch.ao.nn.intrinsic import LinearBn1d from torch.ao.nn.intrinsic import LinearReLU from torch.ao.nn.intrinsic.modules.fused import _FusedModule # noqa: F401 __all__ = [ 'BNReLU2d', 'BNReLU3d', 'ConvBn1d', 'ConvBn2d', 'ConvBn3d', 'ConvBnReLU1d', 'ConvBnReLU2d', 'ConvBnReLU3d', 'ConvReLU1d', 'ConvReLU2d', 'ConvReLU3d', 'LinearBn1d', 'LinearReLU', ]
[ "pytorchmergebot@users.noreply.github.com" ]
pytorchmergebot@users.noreply.github.com
6a1fa05b533ac5a143059c018c1463515a70c318
e6630377da829600b846ad7ecd67daa335878b5a
/main/views.py
6211c54b7998d088bd564686df00b806c983aa97
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
jorgecarleitao/public-contracts
839a09cf54af5fc292aa640d1aaf235f1fb755fa
3107ddc007f3574ce19aaa2223399484bc6b1382
refs/heads/master
2021-06-15T23:07:13.291743
2017-05-09T11:44:56
2017-05-09T11:44:56
14,209,257
26
8
null
2017-07-21T10:45:15
2013-11-07T16:36:47
Python
UTF-8
Python
false
false
353
py
from django.shortcuts import render def robots(request): return render(request, 'robots.txt', content_type='text/plain') def home(request): return render(request, 'main_page.html', {'REQUIRE_D3JS': True}) def about(request): return render(request, 'about.html') def contribute(request): return render(request, 'contribute.html')
[ "jorgecarleitao@gmail.com" ]
jorgecarleitao@gmail.com
79431e97956904979ec976554f8289946bb61697
ee760ad085d305f12e4a60e6ea548e94e71606b6
/sds/envs/cartpole/cartpole.py
9f40106c313c24d4b0369a481d801c71182f2463
[ "MIT" ]
permissive
zlatanajanovic/sds
819ab40f044b72e0a88504601f23d233302c0b4b
3c195fb9cbd88a9284287d62c0eacb6afc4598a7
refs/heads/master
2023-07-19T00:55:20.549984
2021-08-23T14:51:09
2021-08-23T14:51:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,644
py
import gym from gym import spaces from gym.utils import seeding import numpy as np def normalize(x): # wraps angle between [-pi, pi] return ((x + np.pi) % (2. * np.pi)) - np.pi class Cartpole(gym.Env): def __init__(self): self.state_dim = 4 self.act_dim = 1 self.obs_dim = 4 self.dt = 0.01 self.sigma = 1e-8 # g = [x, th, dx, dth] self.g = np.array([0., 0., 0., 0.]) self.gw = - np.array([1e0, 2e0, 1e-1, 1e-1]) # x = [x, th, dx, dth] self.xmax = np.array([5., np.inf, np.inf, np.inf]) self.state_space = spaces.Box(low=-self.xmax, high=self.xmax, dtype=np.float64) # y = [x, th, dx, dth] self.ymax = np.array([5., np.inf, np.inf, np.inf]) self.observation_space = spaces.Box(low=-self.ymax, high=self.ymax, dtype=np.float64) self.uw = - 1e-3 * np.ones((self.act_dim, )) self.umax = 5.0 * np.ones((self.act_dim, )) self.action_space = spaces.Box(low=-self.umax, high=self.umax, shape=(1,), dtype=np.float64) self.uniform = True self.state = None self.np_random = None self.seed() @property def xlim(self): return self.xmax @property def ulim(self): return self.umax def dynamics(self, x, u): uc = np.clip(u, -self.ulim, self.ulim) # Equations: http://coneural.org/florian/papers/05_cart_pole.pdf # x = [x, th, dx, dth] g = 9.81 Mc = 0.37 Mp = 0.127 Mt = Mc + Mp l = 0.3365 fr = 0.005 def f(x, u): q, th, dq, dth = x sth = np.sin(th) cth = np.cos(th) # This friction model is not exactly right # It neglects the influence of the pole num = g * sth + cth * (- (u - fr * dq) - Mp * l * dth**2 * sth) / Mt denom = l * ((4. / 3.) - Mp * cth**2 / Mt) ddth = num / denom ddx = (u + Mp * l * (dth**2 * sth - ddth * cth)) / Mt return np.hstack((dq, dth, ddx, ddth)) c1 = f(x, uc) c2 = f(x + 0.5 * self.dt * c1, uc) c3 = f(x + 0.5 * self.dt * c2, uc) c4 = f(x + self.dt * c3, uc) xn = x + self.dt / 6. * (c1 + 2. * c2 + 2. * c3 + c4) xn = np.clip(xn, -self.xlim, self.xlim) return xn def observe(self, x): return np.array([x[0], normalize(x[1]), x[2], x[3]]) def noise(self, x=None, u=None): _u = np.clip(u, -self.ulim, self.ulim) _x = np.clip(x, -self.xlim, self.xlim) return self.sigma * np.eye(self.obs_dim) def rewrad(self, x, u): _x = np.array([x[0], normalize(x[1]), x[2], x[3]]) return (_x - self.g).T @ np.diag(self.gw) @ (_x - self.g)\ + u.T @ np.diag(self.uw) @ u def seed(self, seed=None): self.np_random, seed = seeding.np_random(seed) return [seed] def step(self, u): self.state = self.dynamics(self.state, u) rwrd = self.rewrad(self.state, u) sigma = self.noise(self.state, u) obs = self.np_random.multivariate_normal(self.observe(self.state), sigma) return obs, rwrd, False, {} def reset(self): if self.uniform: low = np.array([-0.1, -np.pi, -5.0, -10.0]) high = np.array([0.1, np.pi, 5.0, 10.0]) else: low, high = np.array([0., np.pi - np.pi / 18., 0., -1.0]),\ np.array([0., np.pi + np.pi / 18., 0., 1.0]) self.state = self.np_random.uniform(low=low, high=high) return self.observe(self.state) # for plotting def fake_step(self, x, u): xn = self.dynamics(x, u) return self.observe(xn) class CartpoleWithCartesianObservation(Cartpole): def __init__(self): super(CartpoleWithCartesianObservation, self).__init__() self.obs_dim = 5 # y = [x, cos, sin, xd, thd] self.ymax = np.array([5., 1., 1., np.inf, np.inf]) self.observation_space = spaces.Box(low=-self.ymax, high=self.ymax, dtype=np.float64) def observe(self, x): return np.array([x[0], np.cos(x[1]), np.sin(x[1]), x[2], x[3]])
[ "abdulsamad@ias.informatik.tu-darmstadt.de" ]
abdulsamad@ias.informatik.tu-darmstadt.de
9f360e44d1c0c0dcee68e96a596c20e516949e0a
487ce91881032c1de16e35ed8bc187d6034205f7
/codes/CodeJamCrawler/16_0_3/pr0v3rbs/c.py
5d1ec463d56cedc7496b8cb3f35b1bb73dc76551
[]
no_license
DaHuO/Supergraph
9cd26d8c5a081803015d93cf5f2674009e92ef7e
c88059dc66297af577ad2b8afa4e0ac0ad622915
refs/heads/master
2021-06-14T16:07:52.405091
2016-08-21T13:39:13
2016-08-21T13:39:13
49,829,508
2
0
null
2021-03-19T21:55:46
2016-01-17T18:23:00
Python
UTF-8
Python
false
false
1,290
py
import math powerArr = [[],[],[],[],[],[],[],[],[],[],[]] baseArr = [0,0,0,0,0,0,0,0,0,0,0] jamArr = [0,0,0,0,0,0,0,0,0,0,0] input() N, J = raw_input().split() N = int(N) J = int(J) def JamCheck(): result = True idx = 0 t = baseArr[2] for i in range(3, 11): baseArr[i] = 0 while t != 0: if t % 2 == 1: for i in range(3, 11): baseArr[i] += powerArr[i][idx] idx += 1 t /= 2 for i in range(2, 11): primeCheck = True j = 2 length = int(math.sqrt(baseArr[i])) + 1 while j <= 10000: if baseArr[i] % j == 0: #jamArr[i] = j jamArr[i] = baseArr[i] / j primeCheck = False break j+=1 if primeCheck: result = False break return result def PrintJam(): print bin(baseArr[2])[2:], jamArr[2], jamArr[3], jamArr[4], jamArr[5], jamArr[6], jamArr[7], jamArr[8], jamArr[9], jamArr[10] for i in range(2, 11): for j in range(N): powerArr[i].append(i**j) baseArr[2] = 2**(N-1) + 1 print "Case #1:" while J != 0: if JamCheck() : PrintJam() J -= 1 baseArr[2] += 2
[ "[dhuo@tcd.ie]" ]
[dhuo@tcd.ie]
70db18cb9ff35971591998a62ddab059246ace2b
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/nouns/_anarchist.py
f6c4dbb7d584b89e893652ff5df9b887a17eaf22
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
391
py
#calss header class _ANARCHIST(): def __init__(self,): self.name = "ANARCHIST" self.definitions = [u'a person who believes in anarchism: ', u'someone who wishes to destroy the existing government and laws: '] self.parents = [] self.childen = [] self.properties = [] self.jsondata = {} self.specie = 'nouns' def run(self, obj1 = [], obj2 = []): return self.jsondata
[ "xingwang1991@gmail.com" ]
xingwang1991@gmail.com
b01999efc5b5875897213f5aaab988ee20c873f5
d94b6845aeeb412aac6850b70e22628bc84d1d6d
/autoregressive_diffusion/experiments/audio/configs/sc09_wavenet.py
957e0ecbd26bb689722cf752a90ff946ab2ea6d4
[ "CC-BY-4.0", "Apache-2.0" ]
permissive
ishine/google-research
541aea114a68ced68736340e037fc0f8257d1ea2
c1ae273841592fce4c993bf35cdd0a6424e73da4
refs/heads/master
2023-06-08T23:02:25.502203
2023-05-31T01:00:56
2023-05-31T01:06:45
242,478,569
0
0
Apache-2.0
2020-06-23T01:55:11
2020-02-23T07:59:42
Jupyter Notebook
UTF-8
Python
false
false
2,032
py
# coding=utf-8 # Copyright 2023 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. """Config for the SC09 dataset. """ import ml_collections D = lambda **kwargs: ml_collections.ConfigDict(kwargs) def get_config(): """Get the default hyperparameter configuration.""" config = ml_collections.ConfigDict() # Dataset configuration. config.dataset = D( name='speech_commands09', train_split='train', eval_split='validation', test_split='test', max_length=16000 # Some audio files are shorter than 16000. ) config.batch_size = 256 config.eval_batch_size = 512 config.mask_shape = (16000, 1) # Training. config.num_train_steps = 1_000_000 config.beta2 = 0.999 config.clip_grad = 1000. config.weight_decay = 0. config.ema_momentum = 0.995 config.learning_rate = D( base_learning_rate=1e-4, factors='constant', warmup_steps=15000, ) config.restore_checkpoints = True config.checkpoint_every_steps = 5_000 config.eval_every_steps = 2_500 config.log_every_steps = 1_000 config.sample_every_steps = None config.seed = 42 # Evaluation. config.sample_batch_size = 16 config.num_eval_passes = 32 # Model. config.model = 'arm' config.output_distribution = 'discretized_logistic' config.num_mixtures = 30 # Architecture. config.arch = D( name='diff_wave', config=D( num_blocks=36, features=256, dilation_cycle=12, ) ) return config
[ "copybara-worker@google.com" ]
copybara-worker@google.com
9aaa492c6143160703e493cdf16a62b43a86dd6e
b32ca71ab8127f7c3c1a73a6a8f01adefa1be026
/mathsquiz6.py
34a38051e90b696fc060dc3e5abac524d9bd01e5
[]
no_license
Botany-Downs-Secondary-College/mathsquiz-Howard13312
a50312776d686ab51eb6421c8af16889a3440c3c
0c78c55ff99d058264791412d312eda4d37f9bef
refs/heads/main
2023-03-28T14:37:25.155100
2021-03-26T12:12:50
2021-03-26T12:12:50
337,539,510
0
0
null
null
null
null
UTF-8
Python
false
false
5,343
py
#mathsquizv6.py #Howard Li #import the tool kit interface (tkinter) modules from tkinter import* from tkinter import ttk from random import* #parent class class Mathquiz: def __init__ (self,parent): '''Widgets for welcome frame''' self.Welcome = Frame(parent) self.Welcome.grid(row=0, column=0) self.Titlelabel1 = Label(self.Welcome, text = "Welcome to Maths quiz", bg = "black", fg = "white", width = 30, padx = 30, pady = 10, font = ("Time", '14', "bold italic")) self.Titlelabel1.grid(columnspan = 2) self.Nextbutton = ttk.Button(self.Welcome, text = 'Next', command = self.show_Questions) self.Nextbutton.grid(row = 8, column = 1) #Name and Age label self.NameLabel = Label(self.Welcome, text = 'Name', anchor = W, fg = "black", width= 10, padx = 30, pady = 10, font = ("Time", '12', "bold italic")) self.NameLabel.grid(row = 2, column = 0) self.NameLabel = Label(self.Welcome, text = 'Age', anchor = W, fg = "black", width= 10, padx = 30, pady = 10, font = ("Time", "12", "bold italic")) self.NameLabel.grid(row = 3, column = 0) #name and age entry self.NameEntry = ttk.Entry(self.Welcome, width = 20) self.NameEntry.grid(row = 2, column = 1, columnspan = 2) self.AgeEntry = ttk.Entry(self.Welcome, width = 20) self.AgeEntry.grid(row = 3, column = 1) #Warning, Difficulty level label and radio buttons self.WarningLabel = Label(self.Welcome, text = '', anchor = W, fg = "red", width= 20, padx = 30, pady = 10) self.WarningLabel.grid(row = 4, columnspan = 2) self.DifficultyLabel = Label(self.Welcome, text = 'Choose diffculity', anchor = W, fg = "black", width= 14, padx = 30, pady = 20, font = ("Time", "12", "bold italic")) self.DifficultyLabel.grid(row = 5, column = 0) self.difficulty = ["Easy", "Medium", "Hard"] self.diff_lvl = StringVar() self.diff_lvl.set(0) self.diff_btns = [] for i in range(len(self.difficulty)): rb = Radiobutton(self.Welcome, variable = self.diff_lvl, value = i, text = self.difficulty[i], anchor = W, padx = 50, width = "5", height = "2") self.diff_btns.append(rb) rb.grid(row = i+6, column = 0, sticky = W) '''Widgets for Questions frame''' self.Questions = Frame(parent) #self.Questions.grid(row = 0, column = 1) self.QuestionLabel = Label(self.Questions, text = "Quiz Questions", bg = "black", fg = "white", width = 20, padx = 30, pady = 10, font = ("Time", '14', "bold italic")) self.QuestionLabel.grid(columnspan = 2) self.HomeButton = ttk.Button(self.Questions, text = 'Home', command = self.show_Welcome) self.HomeButton.grid(row = 8, column = 0) self.Problems = Label(self.Questions, text = "") self.Problems.grid(row = 1, column = 0) self.next_button = ttk.Button(self.Questions, text = "Next question", command = self.next_question) self.next_button.grid(row=8, column=1) def show_Welcome(self): self.Questions.grid_remove() self.Welcome.grid() def show_Questions(self): #Error checking for empty or non-text user entries for Name try: if self.NameEntry.get() == "": self.WarningLabel.configure(text = "Please enter name") self.NameEntry.focus() elif self.NameEntry.get().isalpha() == False: self.WarningLabel.configure(text = "Please enter text") self.NameEntry.delete(0, END) self.NameEntry.focus() #Error for checking for empty and age limit cases elif self.AgeEntry.get() == "": self.WarningLabel.configure(text = "Please enter age") self.AgeEntry.focus() elif int(self.AgeEntry.get()) > 12: self.WarningLabel.configure(text = "You are too old!") self.AgeEntry.delete(0, END) self.AgeEntry.focus() elif int(self.AgeEntry.get()) < 0: self.WarningLabel.configure(text = "You can't be smaller than 0?") self.AgeEntry.delete(0, END) self.AgeEntry.focus() elif int(self.AgeEntry.get()) < 7: self.WarningLabel.configure(text = "You are too young!") self.AgeEntry.delete(0, END) self.AgeEntry.focus() else: self.Welcome.grid_remove() self.Questions.grid() except ValueError: self.WarningLabel.configure(text = "Please enter a number") self.AgeEntry.delete(0, END) self.AgeEntry.focus() def next_question(self): x = randrange(10) y = randrange(10) self.answer = x + y question_text = str(x) + " + " + str(y) + " = " self.Problems.configure(text = question_text) #main rootine if __name__ == "__main__": root = Tk() frames = Mathquiz(root) root.title("Quiz") root.mainloop()
[ "noreply@github.com" ]
Botany-Downs-Secondary-College.noreply@github.com
0a9e74b629c603dd1c1563a8e5ef7e8718e00864
0fe394b10b39864915fcc4073a5fa050aa02502e
/MatplotPractice/AfricaCSV.py
107dee89fc18bac4c8c570c0efbedde89f3b5c09
[]
no_license
JohnAssebe/Python
9997d47bba4a056fdcd74c6e5207fc52b002cbfd
b88a7c2472f245dc6a0e8900bbea490cb0e0beda
refs/heads/master
2022-05-14T10:08:37.311345
2022-05-09T19:48:53
2022-05-09T19:48:53
212,562,910
0
1
null
null
null
null
UTF-8
Python
false
false
790
py
# -*- coding: utf-8 -*- """ Created on Thu Oct 17 11:30:26 2019 @author: Yohannes Assebe """ import csv from matplotlib import pyplot as plt plt.title("Africa Annual Inflation per years") #print(plt.style.available) #plt.style.use("seaborn-notebook") with open("african_crises.csv") as af: files=csv.DictReader(af) x=[] y=[] for row in files: x.append(int(row['year'])) y.append(float(row['inflation_annual_cpi'])) plt.scatter(x,y) plt.scatter(x[1],y[1]) plt.xlabel("Year") plt.ylabel("Annual Inflation") plt.grid(True) #plt.legend() #plt.ylim(0,100) plt.tight_layout() #print(plt.style.available) plt.savefig("AffricaAnnualInflations.png") plt.show() import pandas as pd
[ "noreply@github.com" ]
JohnAssebe.noreply@github.com
b409f72e18569cb332729b7e95a20bd361d3e851
3b84ca7d132e6ca5004029d39bfa7c8fead07fe1
/seexpr/3.0.1/package.py
4a03d862bddca4dccd83610ebaf068b03b7781ef
[]
no_license
est77/rez-packages
05a5a05224e02c0a28bc37a81cbd07ca7447d604
449ade7acf92196efda2e8ec883c52ba4e33262d
refs/heads/master
2020-05-27T10:35:02.323417
2020-02-23T19:03:05
2020-02-23T19:03:05
82,542,112
22
7
null
null
null
null
UTF-8
Python
false
false
180
py
# -*- coding: utf-8 -*- name = "seexpr" version = "3.0.1" description = "SeExpr" variants = [ ['gcc-6.3.1'] ] def commands(): env.LD_LIBRARY_PATH.append("{root}/lib")
[ "ramenhdr@gmail.com" ]
ramenhdr@gmail.com
e8128ec06bdbba0ad8f05aea2b9b0c4a03325995
5c096fea6033e9c07f38e773e32c901bb7146d09
/04/jiangk/reboot-website/app/modules/manufacturers.py
85c4605e190298b07eecad20527588335cd92b34
[]
no_license
keepauto/devops2
8b043ed258030b75c9b2c7129ae1468af5b42850
b93c840bcca4bd8589546a171a6458bcc6d73047
refs/heads/master
2021-01-21T10:37:48.378259
2016-07-29T05:42:46
2016-07-29T05:42:46
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,957
py
#!/usr/bin/python # coding:utf-8 from app.models import Manufacturers from flask import current_app from app.models import db from app.utils import check_field_exists from app.utils import check_output_field from app.utils import check_order_by from app.utils import check_limit from app.utils import process_result from app.utils import check_update_params def create(**kwargs): # 1 获取参数 # print kwargs # 2 检查参数 check_field_exists(Manufacturers, kwargs) # 3 插入到数据库 manufacturers = Manufacturers(**kwargs) db.session.add(manufacturers) try: db.session.commit() except Exception, e: # logging current_app.logger.warning( "commit error: {}".format(e.message) ) raise Exception("commit error") # 4 返回插入的状态 return manufacturers.id def get(**kwargs): # output: [manufacturers_name, user_interface, user_phone] # where: { # id: 1 # } # limit: 10 # order_by: id # 1 整理条件 output = kwargs.get("output", []) limit = kwargs.get("limit", 10) order_by = kwargs.get("order_by", "id desc") where = kwargs.get("where", {}) # 2 验证 # 验证output check_output_field(Manufacturers, output) # 验证 order_by,字符串分割,字段是否在表中 第二个字段必须为asc desc order_by_list = check_order_by(Manufacturers, order_by) # 验证 limit 必须为数字 check_limit(limit) # 验证 where 条件,先不验证 pass # print callable(getattr(getattr(Manufacturers, "id"), "desc")) # 函数对象 # getattr(getattr(Manufacturers, tmp_order_by[0]), tmp_order_by[1]) # 调用函数 # getattr(getattr(Manufacturers, tmp_order_by[0]), tmp_order_by[1])() data = db.session.query(Manufacturers).filter_by(**where)\ .order_by(getattr(getattr(Manufacturers, order_by_list[0]), order_by_list[1])())\ .limit(limit).all() db.session.close() # process result return process_result(data, output) def update(**kwargs): data = kwargs.get("data", {}) where = kwargs.get("where", {}) # # 1 验证data # # 2 验证where # # 3 更新必须提供id,只按照id更新 # # id 要为数字且大于0的整数 check_update_params(Manufacturers, data, where) # update # ret = db.session.query(Manufacturers).filter_by(**where).update(**data) # 调用模块执行出现错误:update() got an unexpected keyword argument 'rel_cabinet_num' ret = db.session.query(Manufacturers).filter_by(**where).update(data) try: db.session.commit() except Exception, e: # logging current_app.logger.warning("commit error: {}".format(e.message)) raise Exception("commit error") # print ret return ret
[ "seerjk@gmail.com" ]
seerjk@gmail.com
11c6ff5edd9c5239ca96577fc4e0da53c251d1a9
70a960186af21ae6f7a8fcd4d13fde54892f1821
/odds_and_ends/EVAunit00/dumps/serverscript/Windows Image Capture
2bdb0607338cfe16a61903f35dd46c65c877f937
[]
no_license
apua/altair_mat
d6f31bacae62d4490d561c2f9ec07a745693e15e
37dd580fd011aaae9ca52f99bb13757bab2df325
refs/heads/master
2021-04-29T05:49:01.561238
2015-08-21T09:40:50
2015-08-21T09:40:50
78,004,547
0
0
null
null
null
null
UTF-8
Python
false
false
4,161
#!/usr/bin/python # -*- mode: Python; tab-width: 4; indent-tabs-mode: nil; -*- # ex: set tabstop=4 : # Please do not change the two lines above. See PEP 8, PEP 263. # import sys import os from optparse import OptionError from osprov.optparse_ext import OptionParser from osprov.scripts import bootmode from osprov.osbp import logger from osprov.util import process from osprov.decorators import HandleShowErrorMessage from osprov import diskmgr from osprov.diskmgr import const, disk, diskmanager, partition from osprov.server import ThisLocalServer from tempfile import mkstemp LOG = logger.getIt("windows_image_capture") IMAGEX_CONFIG_FILE = """ [ExclusionList] "\\Boot" "\\Program Files\\Opsware" "\\Program Files\\Common Files\\Opsware" """ class WindowsImageCaptureOptionParser(OptionParser): """ Option parser for this step """ def defineOptions(self): self.add_option("--bootMode", type="string", help="boot mode of the server, can be UEFI or Legacy (boot mode is autodetected if this parameter is not passed).") self.add_option("--systemDiskNumber", type="int", default=0, help="system disk number where Windows is installed (default disk number is '0').") self.add_option("--systemPartitionLabel", type="string", default="System", help="label of partition where Windows is installed (default partition label is 'System').") self.add_option("--wimFilePath", type="string", help="path where to save WIM file (Currently using CA 'WimFileName' to provide WIM file name).") self.add_option("--wimScript", type="string", help="path to ImageX config file.") def validateArgs(self, opt, args): if opt.bootMode and not opt.bootMode.lower() in [x.lower() for x in bootmode.SUPPORTED_BOOT_MODES]: raise OptionError("Invalid boot mode: " + opt.bootMode, "bootMode") if not opt.wimFilePath: raise OptionError("Missing parameter: --wimFilePath", "wimFilePath") def captureESP(freeLetter, wimFilePath, log=LOG): process.runIt("imagex.exe /check /verify /capture %s: \"%s_ESP\" \"ESP\"" % (freeLetter, wimFilePath), checkExitCode=(0,), log=log) def capturePartition(windowsDriveLetter, wimFilePath, configFilePath=None, log=LOG): if not configFilePath: fd, configFilePath = mkstemp() with os.fdopen(fd, 'w') as f: f.write(IMAGEX_CONFIG_FILE) process.runIt("imagex.exe /config %s /check /verify /capture %s: \"%s\" \"System\"" % (configFilePath, windowsDriveLetter, wimFilePath), checkExitCode=(0,), log=log) @HandleShowErrorMessage("Windows Image Capture", LOG) def main(): # get and parse arguments options, remainingArgs = WindowsImageCaptureOptionParser().parse_args() wimFilePath = options.wimFilePath.strip() systemDiskNumber = options.systemDiskNumber # get bootmode (legacy bios or uefi) if options.bootMode: bootMode = options.bootMode else: bootMode = bootmode.getCurrentBootMode(ThisLocalServer(), log=LOG) windowsDriveLetter = disk.WindowsDisk(systemDiskNumber).getPartitionWithLabel( options.systemPartitionLabel).letter partitionTable = diskmgr.getPartitionTable(bootMode) if const.PARTITION_TABLE_MBR == partitionTable: print "Capturing Windows Image based on Legacy Windows Partitioning Schema" capturePartition(windowsDriveLetter, wimFilePath, configFilePath=options.wimScript) elif const.PARTITION_TABLE_GPT == partitionTable: print "Capturing Windows Image based on Uefi Windows Partitioning Schema" freeLetter = diskmanager.WindowsDiskManager().findFirstAvailableDriveLetter() partition.WindowsPartition(systemDiskNumber, 1).setPartitionLetter(freeLetter) captureESP(freeLetter, wimFilePath) capturePartition(windowsDriveLetter, wimFilePath, configFilePath=options.wimScript) if __name__ == "__main__": sys.exit(main())
[ "apua.juan@hp.com" ]
apua.juan@hp.com
b3f108e068454d46e36179dc7ee8c4f4e19a3dcd
9c517135ceebe11b88a673f707c865470eac91a8
/layers/classifier.py
6d27ff88218a39e7247f85c3e1d23be4a34a947d
[]
no_license
chenun123/reid_baseline
fd6d516a8badcda81484a98c567c92a34bf0b457
315ef25801208fc0d3f7d91fda009089b0901313
refs/heads/master
2020-12-17T15:32:30.223860
2020-01-17T10:55:57
2020-01-17T10:55:57
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,489
py
# encoding: utf-8 """ @author: liaoxingyu @contact: sherlockliao01@gmail.com """ from torch import nn from modeling.losses import * from modeling.backbones import * from .batch_norm import bn_no_bias from modeling.utils import * class ClassBlock(nn.Module): """ Define the bottleneck and classifier layer |--bn--|--relu--|--linear--|--classifier--| """ def __init__(self, in_features, num_classes, relu=True, num_bottleneck=512, fc_layer='softmax'): super().__init__() block1 = [] block1 += [nn.Linear(in_features, num_bottleneck, bias=False)] block1 += [nn.BatchNorm1d(in_features)] if relu: block1 += [nn.LeakyReLU(0.1)] self.block1 = nn.Sequential(*block1) self.bnneck = bn_no_bias(num_bottleneck) if fc_layer == 'softmax': self.classifier = nn.Linear(num_bottleneck, num_classes, bias=False) elif fc_layer == 'circle_loss': self.classifier = CircleLoss(num_bottleneck, num_classes, s=256, m=0.25) def init_parameters(self): self.block1.apply(weights_init_kaiming) self.bnneck.apply(weights_init_kaiming) self.classifier.apply(weights_init_classifier) def forward(self, x, label=None): x = self.block1(x) x = self.bnneck(x) if self.training: # cls_out = self.classifier(x, label) cls_out = self.classifier(x) return cls_out else: return x
[ "sherlockliao01@gmail.com" ]
sherlockliao01@gmail.com