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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1098a789c29b45f0d9d74b610f2bd525c611d6ba
|
e70b678712a355a0b51632728c7781b0bdcf29f4
|
/Algorithms/Python/House-Robber-III.py
|
a74ac277aba3199f40ac9f6b7b313a6b34906408
|
[] |
no_license
|
keyi/Leetcode_Solutions
|
b3e3c6835ed335d7d4ad53a1b37e59ac15fcf3af
|
69e4e969b435ff2796bd7c4b5dad9284a853ab54
|
refs/heads/master
| 2020-05-21T23:36:20.450053
| 2018-11-11T03:45:28
| 2018-11-11T03:45:28
| 33,714,612
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 577
|
py
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(node):
if not node:
return 0, 0
robL, no_robL = dfs(node.left)
robR, no_robR = dfs(node.right)
return node.val + no_robL + no_robR, max(robL, no_robL) + max(robR, no_robR)
return max(dfs(root))
|
[
"yike921012@gmail.com"
] |
yike921012@gmail.com
|
372a51ab5a1ba04386d600954a4b8dfd5297b211
|
e61e725d9a962837e2b56f84e3934b0fb52dd0b1
|
/eoxserver/backends/middleware.py
|
fcd2756c0adad6b32c04637ceb2a4f2e2ccd6006
|
[
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
ESA-VirES/eoxserver
|
719731172c2e5778186a4b144a201f602c07ce7e
|
d7b65adf9317538b267d5cbb1281acb72bc0de2c
|
refs/heads/master
| 2021-01-21T20:06:22.164030
| 2014-10-14T12:21:13
| 2014-10-14T12:21:13
| 25,151,203
| 1
| 0
| null | 2014-12-04T09:46:54
| 2014-10-13T09:00:54
|
Python
|
UTF-8
|
Python
| false
| false
| 2,089
|
py
|
#-------------------------------------------------------------------------------
# $Id$
#
# Project: EOxServer <http://eoxserver.org>
# Authors: Fabian Schindler <fabian.schindler@eox.at>
#
#-------------------------------------------------------------------------------
# Copyright (C) 2013 EOX IT Services GmbH
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies of this Software or works derived from this Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#-------------------------------------------------------------------------------
import logging
from eoxserver.backends.cache import setup_cache_session, shutdown_cache_session
logger = logging.getLogger(__name__)
class BackendsCacheMiddleware(object):
""" A request middleware f
"""
def process_request(self, request):
setup_cache_session()
def process_response(self, request, response):
shutdown_cache_session()
return response
def process_template_response(self, request, response):
shutdown_cache_session()
return response
def process_exception(self, request, exception):
shutdown_cache_session()
return None
|
[
"fabian.schindler@gmx.at"
] |
fabian.schindler@gmx.at
|
451fca20992f85b6ab2bdff565ff25314a62df06
|
5a72f4ad3dee9c93e907e5db6ae073a0f6173557
|
/web/actions/log_handler.py
|
8eb2c9e92525a051d778d3ec66e77de9aa6b3fba
|
[
"Apache-2.0"
] |
permissive
|
avikowy/machinaris
|
170117fa8857942d90b33b15a727674924da1d66
|
23eead3c30e5d4a75b13c142638c61bcd0af4bfe
|
refs/heads/main
| 2023-06-17T15:54:08.795622
| 2021-07-16T04:19:37
| 2021-07-16T04:19:37
| 386,497,979
| 0
| 0
|
Apache-2.0
| 2021-07-16T03:35:17
| 2021-07-16T03:35:17
| null |
UTF-8
|
Python
| false
| false
| 822
|
py
|
#
# Actions around access to logs on distributed workers.
#
import datetime
import os
import psutil
import re
import signal
import shutil
import socket
import time
import traceback
import yaml
from flask import Flask, jsonify, abort, request, flash
from web import app, db, utils
def get_log_lines(worker, log_type, log_id, blockchain):
try:
payload = {"type": log_type }
if log_id != 'undefined':
payload['log_id'] = log_id
if blockchain != 'undefined':
payload['blockchain'] = blockchain
response = utils.send_get(worker, "/logs/{0}".format(log_type), payload, debug=False)
return response.content.decode('utf-8')
except:
app.logger.info(traceback.format_exc())
return 'Failed to load log file from {0}'.format(worker.hostname)
|
[
"guydavis.ca@gmail.com"
] |
guydavis.ca@gmail.com
|
1e748bcd33d6fe1bf140ccdb45cb963a56a7eaaa
|
55c552b03a07dcfa2d621b198aa8664d6ba76b9a
|
/Algorithm/BOJ/13300_방 배정_b2/13300.py
|
1f760d8e2112fd870232bb7889e148e0582076d3
|
[] |
no_license
|
LastCow9000/Algorithms
|
5874f1523202c10864bdd8bb26960953e80bb5c0
|
738d7e1b37f95c6a1b88c99eaf2bc663b5f1cf71
|
refs/heads/master
| 2023-08-31T12:18:45.533380
| 2021-11-07T13:24:32
| 2021-11-07T13:24:32
| 338,107,899
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 723
|
py
|
# boj 13300 방 배정 b2
# https://www.acmicpc.net/problem/13300
import math
N, K = map(int, input().split())
count_studentMen = [0] * 7 # 6학년까지 ex. 1학년은 1번인덱스를 사용
count_studentWomen = [0] * 7
res = 0
for i in range(N):
S, Y = map(int, input().split()) # S성별 Y학년
if S == 0: # 여자라면
count_studentWomen[Y] += 1 # 해당하는 학년의 여자수 증가
else:
count_studentMen[Y] += 1
for i in range(1, 7): # 1~6학년까지 돌면서
# 학년당 인원수 / 한방에 들어갈 수 있는 인원수 올림처리 ex. 2.3 일겨우 3개
res += math.ceil(count_studentMen[i] / K)
res += math.ceil(count_studentWomen[i] / K)
print(res)
|
[
"sys19912002@hanmail.net"
] |
sys19912002@hanmail.net
|
36e25d40975cb3f2bbb9ca251092b2dcf81d78b0
|
de24f83a5e3768a2638ebcf13cbe717e75740168
|
/moodledata/vpl_data/303/usersdata/298/68638/submittedfiles/testes.py
|
7bb6c9f0c7507804399fccf4e2c1e9aca7ac8f50
|
[] |
no_license
|
rafaelperazzo/programacao-web
|
95643423a35c44613b0f64bed05bd34780fe2436
|
170dd5440afb9ee68a973f3de13a99aa4c735d79
|
refs/heads/master
| 2021-01-12T14:06:25.773146
| 2017-12-22T16:05:45
| 2017-12-22T16:05:45
| 69,566,344
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,370
|
py
|
print('Sejam a, b e c os coeficientes de uma equação do segundo grau')
a = float(input('Digite a: '))
b = float(input('Digite b: '))
c = float(input('Digite c: '))
delta = (b**2 - 4*a*c)
if (delta>=0):
raizdelta = float((delta)**(1/2))
else:
raizdelta = float((-(delta)**(1/2))*float(j))
x1 = float(-b/2 + raizdelta/2)
x2 = float(-b/2 - raizdelta/2)
print('A variável x assume os valores x1=%f e x2+%f' % (x1, x2))
n1 = float(input('Digite um valor N1: '))
n2 = float(input('Digite um valor N2: '))
n3 = float(input('Digite um valor N3: '))
total = n1 + n2 + n3
print('TOTAL = %f' % total)
print('\n')
raio = float(input('Insira o raio do círculo, em centímetros: '))
pi = 3.141592
area = float(pi*((raio)**2))
print('A área do círculo é, aproximadamente, A=%.3f cm^2' % area)
print('\n')
altura = float(input('Qual a sua altura, em metros?: '))
peso = float((72.7*altura) - 58)
print('Seu peso ideal é %.2f kg' % peso)
print('\n')
metro = float(input('Insira a medida f, em metros: '))
cent = float((metro)*100)
print('A medida f é f=%.2f cm' % cent)
print('\n')
nota1 = float(input('Qual sua primeira nota?: '))
nota2 = float(input('Qual sua segunda nota?: '))
nota3 = float(input('Qual sua terceira nota?: '))
nota4 = float(input('Qual sua quarta nota?: '))
media = float((nota1 + nota2 + nota3 + nota4)/4)
print('Sua média é %.1f' % media)
|
[
"rafael.mota@ufca.edu.br"
] |
rafael.mota@ufca.edu.br
|
6e3dfb3631b760423c667b2beb46878bf90acc3d
|
79d9637df98bc89387963fc0173f375a690f8922
|
/coffee-time-challenges/01-two-bases/main.py
|
edbf0a927a8c53a494d1f2bc839ea9be5f6798ff
|
[] |
no_license
|
schickling/challenges
|
979248b916a24d232dd8adce89355b9eaf767b34
|
1af54711f0530a46395ccb18eb51fc25bf385f22
|
refs/heads/master
| 2020-04-06T04:00:37.007054
| 2014-11-06T22:50:33
| 2014-11-06T22:50:33
| 21,869,648
| 2
| 3
| null | 2014-08-06T21:44:20
| 2014-07-15T17:46:46
|
Python
|
UTF-8
|
Python
| false
| false
| 369
|
py
|
#!/usr/bin/env python3
from itertools import combinations_with_replacement
def check(x, y, z):
return x*100+y*10+z == x+y*9+z*9**2
def main():
retults = []
for x, y, z in combinations_with_replacement(list(range(10)), 3):
if check(x, y, z):
retults.append((x, y, z))
return retults
if __name__ == '__main__':
print(main())
|
[
"info@martin-thoma.de"
] |
info@martin-thoma.de
|
8c475f1e44e2c48ce766a5e3e2fdc0acbf79ef4b
|
50b9e93fb40e368c73d8d22680171f22e0200c65
|
/tuesday-api/first-meet-jwt.py
|
a45f78edc5bc526f05c65977e80d5700d79089cc
|
[] |
no_license
|
bopopescu/python-cgi-monitor
|
cd87a2a07a41547a19222dd7bef7190eec221ed1
|
c79e81e129a5f1da3bffae6d69ec8ba2c0e2a8a6
|
refs/heads/master
| 2022-11-19T23:44:39.484833
| 2019-01-22T11:36:55
| 2019-01-22T11:36:55
| 281,807,428
| 0
| 0
| null | 2020-07-22T23:55:00
| 2020-07-22T23:54:59
| null |
UTF-8
|
Python
| false
| false
| 2,432
|
py
|
from datetime import datetime, timedelta
import jwt
JWT_SECRET = 'secret'
JWT_ALGORITHM = 'HS256'
JWT_ISS = 'http://192.168.254.31'
JWT_AUD = 'http://192.168.254.31'
JWT_EXP_DELTA_SECONDS = 60
def encode_jwt(user):
JWT_IAT=JWT_NBF = datetime.utcnow()
playload = {
'user_iid': user,
'iss': JWT_ISS,
'aud': JWT_AUD,
'iat': JWT_IAT,
'nbf': JWT_NBF,
'exp': datetime.utcnow() + timedelta(seconds=JWT_EXP_DELTA_SECONDS)
}
jwt_token = jwt.encode(playload, JWT_SECRET, JWT_ALGORITHM)
return jwt_token
def decode_jwt(str, user):
zoo = jwt.decode(str, 'plain', JWT_ALGORITHM, audience=user)
print zoo
print type(zoo)
print dir(zoo)
code = encode_jwt('admin')
print code
# decode_jwt('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJodHRwOi8vMTkyLjE2OC4yNTQuMzEiLCJ1c2VyX2lpZCI6ImFkbWluIiwiaXNzIjoiaHR0cDovLzE5Mi4xNjguMjU0LjMxIiwiZXhwIjoxNTQwNTQ2MjM4LCJpYXQiOjE1NDA0NTk4MzgsIm5iZiI6MTU0MDQ1OTgzOH0.vZsPWmHUd_zcdHHQau5rzRyXdL-sw2NDymVXrSKpkUE')
# decode_jwt('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoid2FydXQua2QiLCJleHAiOjE1NDA0NTYwMjB9.zoWIgEN8z0X9IyxDUTi2iIPtpNfSzPREMtkEVEKV4kw')
# decode_jwt('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJodHRwOi8vMTkyLjE2OC4yNTQuMzEiLCJ1c2VyX2lpZCI6ImFkbWluIiwiaXNzIjoiaHR0cDovLzE5Mi4xNjguMjU0LjMxIiwiZXhwIjoxNTQwNDYwNTQzLCJpYXQiOjE1NDA0NjA0ODMsIm5iZiI6MTU0MDQ2MDQ4M30.3_orBKIxZYfRq-BwlRQF__8SrFxbrAbK_OFMMgoMA0k', 'http://192.168.254.31')
# decode_jwt(code, JWT_AUD)
# decode_jwt('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9')
def python_sha256():
import hashlib
print hashlib.sha256("playload = {'user_id': 'warut.kd','exp': datetime.utcnow() + timedelta(seconds=JWT_EXP_DELTA_SECONDS)}").hexdigest()
# python_sha256()
# async def login(request):
# post_data = await request.post()
#
# try:
# user = User.objects.get(email=post_data['email'])
# user.match_password(post_data['password'])
# except (User.DoesNotExist, User.PasswordDoesNotMatch):
# return json_response({'message': 'Wrong credentials'}, status=400)
#
# payload = {
# 'user_id': user.id,
# 'exp': datetime.utcnow() + timedelta(seconds=JWT_EXP_DELTA_SECONDS)
# }
# jwt_token = jwt.encode(payload, JWT_SECRET, JWT_ALGORITHM)
# return json_response({'token': jwt_token.decode('utf-8')})
#
# app = web.Application()
# app.router.add_route('POST', '/login', login)
|
[
"31108772+pdeesawat4887@users.noreply.github.com"
] |
31108772+pdeesawat4887@users.noreply.github.com
|
1a604200841cdb5e426f73eaa13a5b46d175c696
|
e85e846960750dd498431ac8412d9967646ff98d
|
/cms/urls/admin.py
|
a20ef9f30b42d704db803611f070617109c8e0d0
|
[] |
no_license
|
onosaburo/clublink_django
|
19368b4a59b3aed3632883ceffe3326bfc7a61a6
|
d2f6024b6224ea7f47595481b3382b8d0670584f
|
refs/heads/master
| 2022-03-30T05:30:12.288354
| 2020-01-27T18:09:11
| 2020-01-27T18:09:11
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 404
|
py
|
from django.conf.urls import include, url
urlpatterns = [
url(r'^club-sites/', include('clublink.cms.modules.club_sites.urls')),
url(r'^corp-site/', include('clublink.cms.modules.corp_site.urls')),
url(r'^assets/', include('clublink.cms.modules.assets.urls')),
url(r'^users/', include('clublink.cms.modules.users.urls')),
url(r'', include('clublink.cms.modules.dashboard.urls')),
]
|
[
"bestwork888@outlook.com"
] |
bestwork888@outlook.com
|
d52c94cca0b3de9681b5b345b45606a67bb54bd9
|
329664fce59d25d6e88c125c1105bc6b4989a3b8
|
/_exercice_version_prof.py
|
6fa3252521c4ec7bf995ba41442cfd66c1597a72
|
[] |
no_license
|
INF1007-2021A/2021a-c01-ch6-supp-3-exercices-LucasBouchard1
|
a8e7d13d8c582ebc44fe10f4be5e98ab65609bcb
|
f46ea10010a823cad46bbc93dba8d7691568d330
|
refs/heads/master
| 2023-08-13T20:49:54.742681
| 2021-09-30T18:05:38
| 2021-09-30T18:05:38
| 410,077,221
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,700
|
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def check_brackets(text, brackets):
# TODO: Associer les ouvrantes et fermantes (à l'aide d'un dict)
opening_brackets = dict(zip(brackets[0::2], brackets[1::2])) # Ouvrants à fermants
closing_brackets = dict(zip(brackets[1::2], brackets[0::2])) # Fermants à ouvrants
# TODO: Vérifier les ouvertures/fermetures
bracket_stack = []
# Pour chaque char de la string
for chr in text:
# Si ouvrant:
if chr in opening_brackets:
# On empile
bracket_stack.append(chr)
# Si fermant
elif chr in closing_brackets:
# Si la pile est vide ou on n'a pas l'ouvrant associé au top de la pile
if len(bracket_stack) == 0 or bracket_stack[-1] != closing_brackets[chr]:
# Pas bon
return False
# On dépile
bracket_stack.pop()
# On vérifie que la pile est vide à la fin (au cas où il y aurait des ouvrants de trop)
return len(bracket_stack) == 0
def remove_comments(full_text, comment_start, comment_end):
# Cette ligne sert à rien, on ne modifie pas la variable originale de toute façon
text = full_text
while True:
# Trouver le prochain début de commentaire
start = text.find(comment_start)
# Trouver la prochaine fin de commentaire
end = text.find(comment_end)
# Si aucun des deux trouvés
if start == -1 and end == -1:
return text
# Si fermeture précède ouverture ou j'en ai un mais pas l'autre
if end < start or (start == -1) != (end == -1):
# Pas bon
return None
# Enlever le commentaire de la string
text = text[:start] + text[end + len(comment_end):]
def get_tag_prefix(text, opening_tags, closing_tags):
for t in zip(opening_tags, closing_tags):
if text.startswith(t[0]):
return (t[0], None)
elif text.startswith(t[1]):
return (None, t[1])
return (None, None)
def check_tags(full_text, tag_names, comment_tags):
text = remove_comments(full_text, *comment_tags)
if text is None:
return False
# On construit nos balises à la HTML ("head" donne "<head>" et "</head>")
otags = {f"<{name}>": f"</{name}>" for name in tag_names}
ctags = dict((v, k) for k, v in otags.items())
# Même algo qu'au numéro 1, mais adapté aux balises de plusieurs caractères
tag_stack = []
while len(text) != 0:
tag = get_tag_prefix(text, otags.keys(), ctags.keys())
# Si ouvrant:
if tag[0] is not None:
# On empile et on avance
tag_stack.append(tag[0])
text = text[len(tag[0]):]
# Si fermant:
elif tag[1] is not None:
# Si pile vide OU match pas le haut de la pile:
if len(tag_stack) == 0 or tag_stack[-1] != ctags[tag[1]]:
# Pas bon
return False
# On dépile et on avance
tag_stack.pop()
text = text[len(tag[1]):]
# Sinon:
else:
# On avance jusqu'à la prochaine balise.
text = text[1:]
# On vérifie que la pile est vide à la fin (au cas où il y aurait des balises ouvrantes de trop)
return len(tag_stack) == 0
if __name__ == "__main__":
brackets = ("(", ")", "{", "}", "[", "]")
yeet = "(yeet){yeet}"
yeeet = "({yeet})"
yeeeet = "({yeet)}"
yeeeeet = "(yeet"
print(check_brackets(yeet, brackets))
print(check_brackets(yeeet, brackets))
print(check_brackets(yeeeet, brackets))
print(check_brackets(yeeeeet, brackets))
print()
spam = "Hello, world!"
eggs = "Hello, /* OOGAH BOOGAH world!"
parrot = "Hello, OOGAH BOOGAH*/ world!"
print(remove_comments(spam, "/*", "*/"))
print(remove_comments(eggs, "/*", "*/"))
print(remove_comments(parrot, "/*", "*/"))
print()
otags = ("<head>", "<body>", "<h1>")
ctags = ("</head>", "</body>", "</h1>")
print(get_tag_prefix("<body><h1>Hello!</h1></body>", otags, ctags))
print(get_tag_prefix("<h1>Hello!</h1></body>", otags, ctags))
print(get_tag_prefix("Hello!</h1></body>", otags, ctags))
print(get_tag_prefix("</h1></body>", otags, ctags))
print(get_tag_prefix("</body>", otags, ctags))
print()
spam = (
"<html>"
" <head>"
" <title>"
" <!-- Ici j'ai écrit qqch -->"
" Example"
" </title>"
" </head>"
" <body>"
" <h1>Hello, world</h1>"
" <!-- Les tags vides sont ignorés -->"
" <br>"
" <h1/>"
" </body>"
"</html>"
)
eggs = (
"<html>"
" <head>"
" <title>"
" <!-- Ici j'ai écrit qqch -->"
" Example"
" <!-- Il manque un end tag"
" </title>-->"
" </head>"
"</html>"
)
parrot = (
"<html>"
" <head>"
" <title>"
" Commentaire mal formé -->"
" Example"
" </title>"
" </head>"
"</html>"
)
tags = ("html", "head", "title", "body", "h1")
comment_tags = ("<!--", "-->")
print(check_tags(spam, tags, comment_tags))
print(check_tags(eggs, tags, comment_tags))
print(check_tags(parrot, tags, comment_tags))
print()
|
[
"66690702+github-classroom[bot]@users.noreply.github.com"
] |
66690702+github-classroom[bot]@users.noreply.github.com
|
ad894d4f56aba4cac738231d9e972e40bc62b0a9
|
3d7e1a506d65c23c84b7430fa46623cb98de8c64
|
/moreifelse.py
|
d00d9e4937067bacab561253371fcb13cdce1fc3
|
[] |
no_license
|
crakama/UdacityIntrotoComputerScience
|
cb6ac8a9084f078eaf245a52adc43541c35dc3f4
|
416b82b85ff70c48eabae6bb9d7b43354a158d9a
|
refs/heads/master
| 2021-01-09T20:39:15.974791
| 2016-07-18T20:59:09
| 2016-07-18T20:59:09
| 60,571,882
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 396
|
py
|
# Define a procedure, is_friend, that takes
# a string as its input, and returns a
# Boolean indicating if the input string
# is the name of a friend. Assume
# I am friends with everyone whose name
# starts with either 'D' or 'N', but no one
# else. You do not need to check for
# lower case 'd' or 'n
def is_friend(string):
if string[0] == 'D' or string[0] == 'N':
return True
return False
|
[
"crakama89@gmail.com"
] |
crakama89@gmail.com
|
ece46492b31fb46f106f1115a52f482853cf4f21
|
b167407960a3b69b16752590def1a62b297a4b0c
|
/tools/project-creator/Python2.6.6/Lib/bsddb/test/test_get_none.py
|
9c08a61b1e86fd2f0f11cfd0919ea35f308fe7de
|
[
"MIT"
] |
permissive
|
xcode1986/nineck.ca
|
543d1be2066e88a7db3745b483f61daedf5f378a
|
637dfec24407d220bb745beacebea4a375bfd78f
|
refs/heads/master
| 2020-04-15T14:48:08.551821
| 2019-01-15T07:36:06
| 2019-01-15T07:36:06
| 164,768,581
| 1
| 1
|
MIT
| 2019-01-15T08:30:27
| 2019-01-09T02:09:21
|
C++
|
UTF-8
|
Python
| false
| false
| 2,330
|
py
|
"""
TestCases for checking set_get_returns_none.
"""
import os, string
import unittest
from test_all import db, verbose, get_new_database_path
#----------------------------------------------------------------------
class GetReturnsNoneTestCase(unittest.TestCase):
def setUp(self):
self.filename = get_new_database_path()
def tearDown(self):
try:
os.remove(self.filename)
except os.error:
pass
def test01_get_returns_none(self):
d = db.DB()
d.open(self.filename, db.DB_BTREE, db.DB_CREATE)
d.set_get_returns_none(1)
for x in string.letters:
d.put(x, x * 40)
data = d.get('bad key')
self.assertEqual(data, None)
data = d.get(string.letters[0])
self.assertEqual(data, string.letters[0]*40)
count = 0
c = d.cursor()
rec = c.first()
while rec:
count = count + 1
rec = c.next()
self.assertEqual(rec, None)
self.assertEqual(count, len(string.letters))
c.close()
d.close()
def test02_get_raises_exception(self):
d = db.DB()
d.open(self.filename, db.DB_BTREE, db.DB_CREATE)
d.set_get_returns_none(0)
for x in string.letters:
d.put(x, x * 40)
self.assertRaises(db.DBNotFoundError, d.get, 'bad key')
self.assertRaises(KeyError, d.get, 'bad key')
data = d.get(string.letters[0])
self.assertEqual(data, string.letters[0]*40)
count = 0
exceptionHappened = 0
c = d.cursor()
rec = c.first()
while rec:
count = count + 1
try:
rec = c.next()
except db.DBNotFoundError: # end of the records
exceptionHappened = 1
break
self.assertNotEqual(rec, None)
self.assert_(exceptionHappened)
self.assertEqual(count, len(string.letters))
c.close()
d.close()
#----------------------------------------------------------------------
def test_suite():
return unittest.makeSuite(GetReturnsNoneTestCase)
if __name__ == '__main__':
unittest.main(defaultTest='test_suite')
|
[
"278688386@qq.com"
] |
278688386@qq.com
|
59d056538621fac227eb382e34ac693ad942fe9a
|
5189a2e2e1fbf04edb2e212652b268361bc54de6
|
/dephell/commands/jail_show.py
|
0dea75396705ef81137ac8537f6baff5868bde42
|
[
"MIT"
] |
permissive
|
Brishen/dephell
|
50f74a4d9c94fc81c3ae5bc3b8472b4d89e23fd7
|
1a09de4b9204466b4c9b833fd880542fb6b73d52
|
refs/heads/master
| 2021-03-30T09:19:05.518468
| 2020-03-17T17:54:22
| 2020-03-17T17:54:22
| 248,037,267
| 0
| 0
|
MIT
| 2020-03-17T17:53:53
| 2020-03-17T17:53:52
| null |
UTF-8
|
Python
| false
| false
| 2,249
|
py
|
# built-in
from argparse import ArgumentParser
from pathlib import Path
# external
from dephell_venvs import VEnvs
from packaging.utils import canonicalize_name
# app
from ..actions import format_size, get_path_size, make_json
from ..config import builders
from ..converters import InstalledConverter
from .base import BaseCommand
class JailShowCommand(BaseCommand):
"""Show info about the package isolated environment.
"""
@staticmethod
def build_parser(parser) -> ArgumentParser:
builders.build_config(parser)
builders.build_venv(parser)
builders.build_output(parser)
builders.build_other(parser)
parser.add_argument('name', help='jail name')
return parser
def __call__(self) -> bool:
venvs = VEnvs(path=self.config['venv'])
name = canonicalize_name(self.args.name)
venv = venvs.get_by_name(name)
if not venv.exists():
self.logger.error('jail does not exist', extra=dict(package=name))
return False
# get list of exposed entrypoints
entrypoints_names = []
for entrypoint in venv.bin_path.iterdir():
global_entrypoint = Path(self.config['bin']) / entrypoint.name
if not global_entrypoint.exists():
continue
if not global_entrypoint.resolve().samefile(entrypoint):
continue
entrypoints_names.append(entrypoint.name)
root = InstalledConverter().load(paths=[venv.lib_path], names={name})
version = None
for subdep in root.dependencies:
if subdep.name != name:
continue
version = str(subdep.constraint).replace('=', '')
data = dict(
name=name,
path=str(venv.path),
entrypoints=entrypoints_names,
version=version,
size=dict(
lib=format_size(get_path_size(venv.lib_path)),
total=format_size(get_path_size(venv.path)),
),
)
print(make_json(
data=data,
key=self.config.get('filter'),
colors=not self.config['nocolors'],
table=self.config['table'],
))
return True
|
[
"master_fess@mail.ru"
] |
master_fess@mail.ru
|
b62c2124b3745f705af3028c3d40ff02d6de01eb
|
a6f8aae8f552a06b82fe018246e8dcd65c27e632
|
/pr064/pr064.py
|
118db0003bd02932d1a6e1bd3e0df29b4e8e386a
|
[] |
no_license
|
P4SSER8Y/ProjectEuler
|
2339ee7676f15866ceb38cad35e21ead0dad57e9
|
15d1b681e22133fc562a08b4e8e41e582ca8e625
|
refs/heads/master
| 2021-06-01T09:22:11.165235
| 2016-05-06T14:02:40
| 2016-05-06T14:02:40
| 46,722,844
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 916
|
py
|
from math import sqrt, floor
from itertools import count
def get(n):
def gcd(a, b):
if b == 0:
return a
return gcd(b, a%b)
if n == (int(sqrt(n)))**2:
return 0
an = lambda k, c, d: int(floor(((k*sqrt(n)-c)/d)))
pn = lambda k, c, d: [d*k,
-d*(c+d*an(k,c,d)),
k*k*n-(c+d*an(k,c,d))**2]
a = [0]
p = [[1, 0, 1]]
a.append(an(*p[-1]))
t = pn(*p[-1])
g = gcd(gcd(t[0], t[1]), t[2])
p.append([t[0]//g, t[1]//g, t[2]//g])
for _ in count(2):
a.append(an(*p[-1]))
t = pn(*p[-1])
g = gcd(gcd(t[0], t[1]), t[2])
p.append([t[0]//g, t[1]//g, t[2]//g])
if p[-1] == p[1]:
return _ - 1
def run():
ret = 0
for n in range(1, 10001):
if get(n) % 2 == 1:
ret += 1
return ret
if __name__ == "__main__":
print(run())
|
[
"beobachter70@163.com"
] |
beobachter70@163.com
|
ecac4bdb1c8034948e2a47fc06bb722bf9c7a990
|
c1960138a37d9b87bbc6ebd225ec54e09ede4a33
|
/adafruit-circuitpython-bundle-py-20210402/lib/adafruit_mcp230xx/digital_inout.py
|
877d588cc07250f952b5661bf7a59f8ccf8b843d
|
[] |
no_license
|
apalileo/ACCD_PHCR_SP21
|
76d0e27c4203a2e90270cb2d84a75169f5db5240
|
37923f70f4c5536b18f0353470bedab200c67bad
|
refs/heads/main
| 2023-04-07T00:01:35.922061
| 2021-04-15T18:02:22
| 2021-04-15T18:02:22
| 332,101,844
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,166
|
py
|
# SPDX-FileCopyrightText: 2017 Tony DiCola for Adafruit Industries
# SPDX-FileCopyrightText: 2019 Carter Nelson
#
# SPDX-License-Identifier: MIT
"""
`digital_inout`
====================================================
Digital input/output of the MCP230xx.
* Author(s): Tony DiCola
"""
import digitalio
__version__ = "2.4.5"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_MCP230xx.git"
# Internal helpers to simplify setting and getting a bit inside an integer.
def _get_bit(val, bit):
return val & (1 << bit) > 0
def _enable_bit(val, bit):
return val | (1 << bit)
def _clear_bit(val, bit):
return val & ~(1 << bit)
class DigitalInOut:
"""Digital input/output of the MCP230xx. The interface is exactly the
same as the digitalio.DigitalInOut class, however:
* MCP230xx family does not support pull-down resistors;
* MCP23016 does not support pull-up resistors.
Exceptions will be thrown when attempting to set unsupported pull
configurations.
"""
def __init__(self, pin_number, mcp230xx):
"""Specify the pin number of the MCP230xx (0...7 for MCP23008, or 0...15
for MCP23017) and MCP23008 instance.
"""
self._pin = pin_number
self._mcp = mcp230xx
# kwargs in switch functions below are _necessary_ for compatibility
# with DigitalInout class (which allows specifying pull, etc. which
# is unused by this class). Do not remove them, instead turn off pylint
# in this case.
# pylint: disable=unused-argument
def switch_to_output(self, value=False, **kwargs):
"""Switch the pin state to a digital output with the provided starting
value (True/False for high or low, default is False/low).
"""
self.direction = digitalio.Direction.OUTPUT
self.value = value
def switch_to_input(self, pull=None, invert_polarity=False, **kwargs):
"""Switch the pin state to a digital input with the provided starting
pull-up resistor state (optional, no pull-up by default) and input polarity. Note that
pull-down resistors are NOT supported!
"""
self.direction = digitalio.Direction.INPUT
self.pull = pull
self.invert_polarity = invert_polarity
# pylint: enable=unused-argument
@property
def value(self):
"""The value of the pin, either True for high or False for
low. Note you must configure as an output or input appropriately
before reading and writing this value.
"""
return _get_bit(self._mcp.gpio, self._pin)
@value.setter
def value(self, val):
if val:
self._mcp.gpio = _enable_bit(self._mcp.gpio, self._pin)
else:
self._mcp.gpio = _clear_bit(self._mcp.gpio, self._pin)
@property
def direction(self):
"""The direction of the pin, either True for an input or
False for an output.
"""
if _get_bit(self._mcp.iodir, self._pin):
return digitalio.Direction.INPUT
return digitalio.Direction.OUTPUT
@direction.setter
def direction(self, val):
if val == digitalio.Direction.INPUT:
self._mcp.iodir = _enable_bit(self._mcp.iodir, self._pin)
elif val == digitalio.Direction.OUTPUT:
self._mcp.iodir = _clear_bit(self._mcp.iodir, self._pin)
else:
raise ValueError("Expected INPUT or OUTPUT direction!")
@property
def pull(self):
"""Enable or disable internal pull-up resistors for this pin. A
value of digitalio.Pull.UP will enable a pull-up resistor, and None will
disable it. Pull-down resistors are NOT supported!
"""
try:
if _get_bit(self._mcp.gppu, self._pin):
return digitalio.Pull.UP
except AttributeError as error:
# MCP23016 doesn't have a `gppu` register.
raise ValueError("Pull-up/pull-down resistors not supported.") from error
return None
@pull.setter
def pull(self, val):
try:
if val is None:
self._mcp.gppu = _clear_bit(self._mcp.gppu, self._pin)
elif val == digitalio.Pull.UP:
self._mcp.gppu = _enable_bit(self._mcp.gppu, self._pin)
elif val == digitalio.Pull.DOWN:
raise ValueError("Pull-down resistors are not supported!")
else:
raise ValueError("Expected UP, DOWN, or None for pull state!")
except AttributeError as error:
# MCP23016 doesn't have a `gppu` register.
raise ValueError("Pull-up/pull-down resistors not supported.") from error
@property
def invert_polarity(self):
"""The polarity of the pin, either True for an Inverted or
False for an normal.
"""
if _get_bit(self._mcp.ipol, self._pin):
return True
return False
@invert_polarity.setter
def invert_polarity(self, val):
if val:
self._mcp.ipol = _enable_bit(self._mcp.ipol, self._pin)
else:
self._mcp.ipol = _clear_bit(self._mcp.ipol, self._pin)
|
[
"55570902+apalileo@users.noreply.github.com"
] |
55570902+apalileo@users.noreply.github.com
|
751478a95c3542713d69302bb04e829266b80014
|
67b62f49ff89982ef62ce5d5c68bc7655ededcee
|
/chap6/basic_evaluator.py
|
7fd1b1bcb0e15607838e88ad314e8711d2e2c8e8
|
[] |
no_license
|
planset/stone-py
|
0614737e59a14745019754c453f9b49e44f125cf
|
467617e201a3f4028f2fb23b2bc6ce3aaa371125
|
refs/heads/master
| 2016-09-06T18:36:49.564450
| 2012-12-31T12:57:06
| 2012-12-31T12:57:06
| 6,389,161
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,955
|
py
|
# -*- coding: utf-8 -*-
from stone.util import reviser, super
from stone.myast import ast, literal, expression, statement
from stone import exception
#class BasicEvaluator(object):
# def __init__(self):
# pass
TRUE = 1
FALSE = 0
@reviser
class ASTreeEx(ast.ASTree):
def eval(self, env):
raise NotImplementedError()
@reviser
class ASTListEx(ast.ASTList):
def __init__(self, list_of_astree):
super(ASTListEx, self).__init__(list_of_astree)
def eval(self, env):
raise exception.StoneException("cannot eval: " + self.to_string(), self)
@reviser
class ASTLeafEx(ast.ASTLeaf):
def __init__(self, token):
super(ASTLeafEx, self).__init__(token)
def eval(self, env):
raise exception.StoneException("cannot eval: " + self.to_string(), self)
@reviser
class NumberEx(literal.NumberLiteral):
def __init__(self, token):
super(NumberEx, self).__init__(token)
def eval(self, env):
return self.value()
@reviser
class StringEx(literal.StringLiteral):
def __init__(self, token):
super(StringEx, self).__init__(token)
def eval(self, env):
return self.value()
@reviser
class NameEx(literal.Name):
def __init__(self, token):
super(NameEx, self).__init__(token)
def eval(self, env):
value = env.get(self.name())
if value is None:
raise exception.StoneException('undefined name: ' + self.name(), self)
else:
return value
@reviser
class NegativeEx(expression.NegativeExpr):
def __init__(self, list_of_astree):
super(NegativeEx, self).__init__(list_of_astree)
def eval(self, env):
v = self.operand().eval(env)
if isinstance(v, int):
return -v
else:
raise exception.StoneException('bad type for -', self)
@reviser
class BinaryEx(expression.BinaryExpr):
def __init__(self, list_of_astree):
super(BinaryEx, self).__init__(list_of_astree)
def eval(self, env):
op = self.operator()
if op == '=':
right = self.right().eval(env)
return self.compute_assign(env, right)
else:
left = self.left().eval(env)
right = self.right().eval(env)
return self.compute_op(left, op, right)
def compute_assign(self, env, rvalue):
l = self.left()
if isinstance(l, literal.Name):
env.put(l.name(), rvalue)
return rvalue
else:
raise expression.StoneException('bad assignment', self)
def compute_op(self, left, op, right):
if isinstance(left, int) and isinstance(right, int):
return self.compute_number(left, op, right)
else:
if op == '+':
return str(left) + str(right)
elif op == '==':
if left is None:
return TRUE if right else FALSE
else:
return TRUE if left == right else FALSE
else:
raise exception.StoneException('bad type', self)
def compute_number(self, left, op, right):
a = int(left)
b = int(right)
if op == '+':
return a + b
elif op == '-':
return a - b
elif op == '*':
return a * b
elif op == '/':
return a / b
elif op == '%':
return a % b
elif op == '==':
return TRUE if a == b else FALSE
elif op == '>':
return TRUE if a > b else FALSE
elif op == '<':
return TRUE if a < b else FALSE
else:
return exception.StoneException('bad operator', self)
@reviser
class BlockEx(statement.BlockStmnt):
def __init__(self, list_of_astree):
super(BlockEx, self).__init__(list_of_astree)
def eval(self, env):
result = 0
for token in self.children():
if not isinstance(token, statement.NullStmnt):
result = token.eval(env)
return result
@reviser
class IfEx(statement.IfStmnt):
def __init__(self, list_of_astree):
super(IfEx, self).__init__(list_of_astree)
def eval(self, env):
c = self.condition().eval(env)
if isinstance(c, int) and int(c) != FALSE:
return self.then_block().eval(env)
else:
b = self.else_block()
if b is None:
return 0
else:
return b.eval(env)
@reviser
class WhileEx(statement.WhileStmnt):
def __init__(self, list_of_astree):
super(WhileEx, self).__init__(list_of_astree)
def eval(self, env):
result = 0
while True:
c = self.condition().eval(env)
if isinstance(c, int) and int(c) == FALSE:
return result
else:
result = self.body().eval(env)
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
|
[
"planset@gmail.com"
] |
planset@gmail.com
|
8de737368f805d8d9c748a04dc6b26df83141c3e
|
f55623e3aea5b8ae3d2c37bcfa8a853150a0b376
|
/a10_horizon/_enabled_hooks/_91000_a10admin_panel.py
|
bbfda541cbf0467babfe76f4b091824b63db24dd
|
[
"Apache-2.0"
] |
permissive
|
isaaczurn/a10-horizon
|
0fab288d321516de72ea276d54b415a1c2e4d7d6
|
a96f9e95dfcda619f08a19a9057b061bdba12487
|
refs/heads/development
| 2020-12-26T04:49:33.131115
| 2016-08-11T16:47:09
| 2016-08-11T16:47:09
| 64,965,205
| 1
| 0
| null | 2016-08-04T20:31:28
| 2016-08-04T20:31:28
| null |
UTF-8
|
Python
| false
| false
| 846
|
py
|
# Copyright (C) 2016, A10 Networks Inc. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
PANEL_GROUP = 'a10admin'
PANEL_GROUP_NAME = 'A10 Networks'
PANEL_DASHBOARD = "admin"
PANEL_GROUP_DASHBOARD = PANEL_DASHBOARD
ADD_INSTALLED_APPS = ['a10_horizon.dashboard.admin']
AUTO_DISCOVER_STATIC_FILES = True
|
[
"mdurrant@a10networks.com"
] |
mdurrant@a10networks.com
|
7151eacc02e7268941d808551b82a302f388b83a
|
a24d889cc6fd5cd3fc180bcf5cf7dcd688eb691a
|
/yggdrasil/metaschema/properties/__init__.py
|
e26481182221d47dd0902bcc594398be467a91c2
|
[
"BSD-3-Clause"
] |
permissive
|
ghanashyamchalla/yggdrasil
|
f5346bad5d1f4ed8a53e7b570c19eefb58a8a921
|
7b59439276eacb66f1f6ea4177d3a85cc061eed5
|
refs/heads/master
| 2022-04-20T06:08:49.110242
| 2020-04-15T02:44:51
| 2020-04-15T02:44:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,579
|
py
|
import os
import glob
import importlib
from collections import OrderedDict
_metaschema_properties = OrderedDict()
def register_metaschema_property(prop_class):
r"""Register a schema property.
Args:
prop_class (class): Class to be registered.
Raises:
ValueError: If a property class has already been registered under the
same name.
ValueError: If the base validator already has a validator function for
the property and the new property class has a schema defined.
ValueError: If the base validator already has a validator function for
the property and the validate method on the new property class is
not disabled.
ValueError: If the property class does not have an entry in the existing
metaschema.
"""
from yggdrasil.metaschema import _metaschema, _base_validator
global _metaschema_properties
prop_name = prop_class.name
if prop_name in _metaschema_properties:
raise ValueError("Property '%s' already registered." % prop_name)
if prop_name in _base_validator.VALIDATORS:
if (prop_class.schema is not None):
raise ValueError("Replacement property '%s' modifies the default schema."
% prop_name)
if (((prop_class._validate not in [None, False])
or ('validate' in prop_class.__dict__))):
raise ValueError("Replacement property '%s' modifies the default validator."
% prop_name)
prop_class._validate = False
# prop_class.types = [] # To ensure base class not modified by all
# prop_class.python_types = []
# Check metaschema if it exists
if _metaschema is not None:
if prop_name not in _metaschema['properties']:
raise ValueError("Property '%s' not in pre-loaded metaschema." % prop_name)
_metaschema_properties[prop_name] = prop_class
return prop_class
class MetaschemaPropertyMeta(type):
r"""Meta class for registering properties."""
def __new__(meta, name, bases, class_dict):
cls = type.__new__(meta, name, bases, class_dict)
if not (name.endswith('Base') or (cls.name in ['base'])
or cls._dont_register):
cls = register_metaschema_property(cls)
return cls
def get_registered_properties():
r"""Return a dictionary of registered properties.
Returns:
dict: Registered property/class pairs.
"""
return _metaschema_properties
def get_metaschema_property(property_name, skip_generic=False):
r"""Get the property class associated with a metaschema property.
Args:
property_name (str): Name of property to get class for.
skip_generic (bool, optional): If True and the property dosn't have a
class, None is returned. Defaults to False.
Returns:
MetaschemaProperty: Associated property class.
"""
from yggdrasil.metaschema.properties import MetaschemaProperty
if property_name in _metaschema_properties:
return _metaschema_properties[property_name]
else:
if skip_generic:
return None
else:
return MetaschemaProperty.MetaschemaProperty
def import_all_properties():
r"""Import all types to ensure they are registered."""
for x in glob.glob(os.path.join(os.path.dirname(__file__), '*.py')):
mod = os.path.basename(x)[:-3]
if not mod.startswith('__'):
importlib.import_module('yggdrasil.metaschema.properties.%s' % mod)
|
[
"langmm.astro@gmail.com"
] |
langmm.astro@gmail.com
|
11783965c99a7fec6aa8653159a599e25ce3ebfa
|
491d2fd36f2ca26975b3eb302a3d5600415bf7c4
|
/central/multi_node_utils.py
|
8fbeb6444b67d9aab6cdff45669e13032d27f208
|
[] |
no_license
|
kmanchella-habana/Model-References
|
9fa42654d57a867d82f417e9fff668946f9105f6
|
460d3b23ce75f30561e8f725ebcb21298897d163
|
refs/heads/master
| 2023-08-28T17:42:48.866251
| 2021-09-18T21:38:04
| 2021-09-18T21:38:04
| 411,371,667
| 0
| 0
| null | 2021-09-28T17:08:13
| 2021-09-28T17:08:13
| null |
UTF-8
|
Python
| false
| false
| 6,092
|
py
|
###############################################################################
# Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company
###############################################################################
"""Utilities for multi-card and scaleout training"""
import os
import socket
import subprocess
import sys
from functools import lru_cache
from central.habana_model_runner_utils import (get_canonical_path,
get_multi_node_config_nodes,
is_valid_multi_node_config)
def run_cmd_as_subprocess(cmd=str, use_devnull=False):
print(cmd)
sys.stdout.flush()
sys.stderr.flush()
if use_devnull:
with subprocess.Popen(cmd, shell=True, executable='/bin/bash', stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) as proc:
proc.wait()
else:
with subprocess.Popen(cmd, shell=True, executable='/bin/bash') as proc:
proc.wait()
# -------------------------------------------------------------------------------
# For scaleout, depends on MULTI_HLS_IPS environment variable being set to contain
# ",' separated list of host IPs.
# If MULTI_HLS_IPS is not set, the command "cmd" will be run on the local host.
# Make sure that the command "cmd" being run on the remote host does not depend on
# any other environment variables being available on the remote host besides the ones
# in the "env_vars_for_mpi" list that this function will export to the remote IPs.
# -------------------------------------------------------------------------------
def run_per_ip(cmd, env_vars_for_mpi=None, use_devnull=False, kubernetes_run=False):
if kubernetes_run:
print("************************* Kubernetes mode *************************")
run_cmd_as_subprocess(cmd, use_devnull)
return
if os.environ.get('OMPI_COMM_WORLD_SIZE') is not None:
raise RuntimeError(
"Function run_per_ip is not meant to be run from within an OpenMPI context. It is intended to invoke mpirun by itelf.")
if not is_valid_multi_node_config():
print("************************* Single-HLS mode *************************")
run_cmd_as_subprocess(cmd, use_devnull)
else:
if os.environ.get('DOCKER_SSHD_PORT'):
portnum = os.environ.get('DOCKER_SSHD_PORT')
else:
portnum = 3022
scmd = f"mpirun --allow-run-as-root --mca plm_rsh_args -p{portnum} --tag-output --merge-stderr-to-stdout --prefix {os.environ.get('MPI_ROOT')} -H {os.environ.get('MULTI_HLS_IPS')} "
if env_vars_for_mpi is not None:
for env_var in env_vars_for_mpi:
scmd += f"-x {env_var} "
scmd += cmd
print(f"{socket.gethostname()}: In MULTI NODE run_per_ip(): scmd = {scmd}")
run_cmd_as_subprocess(scmd, use_devnull)
# Generate the MPI hostfile
def generate_mpi_hostfile(file_path, devices_per_hls=8):
mpi_hostfile_path = ''
if is_valid_multi_node_config():
multi_hls_nodes = get_multi_node_config_nodes()
print("Generating MPI hostfile...")
file_name = "hostfile"
os.makedirs(get_canonical_path(file_path), mode=0o777, exist_ok=True)
mpi_hostfile_path = get_canonical_path(file_path).joinpath(file_name)
if os.path.exists(mpi_hostfile_path):
cmd = f"rm -f {str(mpi_hostfile_path)}"
run_cmd_as_subprocess(cmd)
print(f"Path: {mpi_hostfile_path}")
out_fid = open(mpi_hostfile_path, 'a')
config_str = ''
for node in multi_hls_nodes:
config_str += f"{node} slots={devices_per_hls}\n"
print(f"MPI hostfile: \n{config_str}")
out_fid.write(config_str)
out_fid.close()
return mpi_hostfile_path
def print_file_contents(file_name):
with open(file_name, 'r') as fl:
for line in fl:
print(line, end='')
def _is_relevant_env_var(env_var: str):
""" Given an environment variable name, determines whether is it "relevant" for the child processes spawned by OpenMPI.
OpenMPI passes the local environment only to the local child processes.
"""
RELEVANT_ENV_VAR_INFIXES = [
"PATH", "LD_", # System-specific: PATH, PYTHONPATH, LD_LIBRARY_PATH, LD_PRELOAD
"TF_", # TensorFlow-specific, e.g.: TF_BF16_CONVERSION
"TPC_", # TPC-specific, e.g.: RUN_TPC_FUSER
"GC_", # GC-specific, e.g.: GC_KERNEL_PATH
"HABANA", "HBN", # Other Habana-specific, e.g.: HABANA_INITIAL_WORKSPACE_SIZE_MB
"HOROVOD", # Horovod-specific, e.g.: HOROVOD_LOG_LEVEL
"SYN", # Synapse-specific
"HCL", # HCL-specific, e.g.: HCL_CONFIG_PATH
"HCCL", "NCCL", # HCCL-specific: HCCL_SOCKET_IFNAME, HABANA_NCCL_COMM_API
"LOG_LEVEL", # Logger-specific, e.g.: LOG_LEVEL_HCL, LOG_LEVEL_SYN_API
]
OTHER_RELEVANT_ENV_VARS = [
"VIRTUAL_ENV",
"ENABLE_CONSOLE",
"MULTI_HLS_IPS"
]
ENV_VARS_DEPRECATIONS = {
"TF_ENABLE_BF16_CONVERSION": "Superceeded by TF_BF16_CONVERSION.",
"HABANA_USE_PREALLOC_BUFFER_FOR_ALLREDUCE": "'same address' optimization for collective operations is no longer supported.",
"HABANA_USE_STREAMS_FOR_HCL": "HCL streams are always used. Setting to 0 enforces blocking synchronization after collective operations (debug feature).",
}
if env_var in ENV_VARS_DEPRECATIONS:
print(
f"warninig: Environment variable '{env_var}' is deprecated: {ENV_VARS_DEPRECATIONS[env_var]}")
if env_var in OTHER_RELEVANT_ENV_VARS:
return True
for infix in RELEVANT_ENV_VAR_INFIXES:
if infix in env_var:
return True
return False
@lru_cache()
def get_relevant_env_vars():
""" Retrieves the list of those environment variables, which should be passed to the child processes spawned by OpenMPI.
"""
return [env_var for env_var in os.environ if _is_relevant_env_var(env_var)]
|
[
"mpandit@habana.ai"
] |
mpandit@habana.ai
|
f871cb804836e1732c5ccb6ac5804e5a11670af4
|
64a1a418c6e0794dcf7be5605f1e254f2beaa65d
|
/tutorial/ch1/qt5_2.py
|
fc15b92cc431579a59972a827e95fbdeb97dd546
|
[] |
no_license
|
notmikeb/python_desk
|
792c93f68b69dcd8c24384883421166771d40c15
|
1685d6e9e0c8b4d8201625ce58fa2420bc1b930e
|
refs/heads/master
| 2021-01-20T09:36:46.832716
| 2016-02-03T13:51:20
| 2016-02-03T13:51:20
| 40,387,601
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 496
|
py
|
"""
ZetCode pyQT5 tutorial
"""
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300,300, 300, 220)
self.setWindowTitle('Icon')
self.setWindowIcon(QIcon('web.jpg'))
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
print ("done app")
print ("show done")
ex = Example()
app.exec_()
|
[
"notmikeb@gmail.com"
] |
notmikeb@gmail.com
|
42827266ae0abe6cf4bb9c8f2a439f58df2b3e9a
|
8781d392b65ccf7ebad7332de07eddea3349f55c
|
/examples/vtk-structured-2d-curved.py
|
e322305c0b6b03fe6e91706abff7bb1edf09c799
|
[
"MIT"
] |
permissive
|
mattwala/pyvisfile
|
95006fb7771cb7b51264543344fcbb1da0504432
|
41c908e1530d73a2af83fa9436751cb46c0f922a
|
refs/heads/master
| 2022-11-11T11:19:15.474390
| 2020-06-23T05:14:31
| 2020-06-23T05:14:31
| 276,822,466
| 0
| 0
|
MIT
| 2020-07-03T06:14:45
| 2020-07-03T06:14:44
| null |
UTF-8
|
Python
| false
| false
| 482
|
py
|
from __future__ import absolute_import
from pyvisfile.vtk import write_structured_grid
import numpy as np
angle_mesh = np.mgrid[1:2:10j, 0:2*np.pi:20j]
r = angle_mesh[0, np.newaxis]
phi = angle_mesh[1, np.newaxis]
mesh = np.vstack((
r*np.cos(phi),
r*np.sin(phi),
))
from pytools.obj_array import make_obj_array
vec = make_obj_array([
np.cos(phi),
np.sin(phi),
])
write_structured_grid("yo-2d.vts", mesh,
point_data=[("phi", phi), ("vec", vec)])
|
[
"inform@tiker.net"
] |
inform@tiker.net
|
12d2b319e45161b64b8c5e2a24a13222bf797dc1
|
43e900f11e2b230cdc0b2e48007d40294fefd87a
|
/Facebook/1763.longest-nice-substring.py
|
6c10cfdaef09b7133bf7adcc369d6f99c980d0c9
|
[] |
no_license
|
DarkAlexWang/leetcode
|
02f2ed993688c34d3ce8f95d81b3e36a53ca002f
|
89142297559af20cf990a8e40975811b4be36955
|
refs/heads/master
| 2023-01-07T13:01:19.598427
| 2022-12-28T19:00:19
| 2022-12-28T19:00:19
| 232,729,581
| 3
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 539
|
py
|
#
# @lc app=leetcode id=1763 lang=python3
#
# [1763] Longest Nice Substring
#
# @lc code=start
class Solution:
def longestNiceSubstring(self, s: str) -> str:
if len(s) < 2:
return ""
chars = set(list(s))
for i in range(len(s)):
if not (s[i].lower() in chars and s[i].upper() in chars):
s1 = self.longestNiceSubstring(s[:i])
s2 = self.longestNiceSubstring(s[i + 1:])
return s2 if len(s2) > len(s1) else s1
return s
# @lc code=end
|
[
"wangzhihuan0815@gmail.com"
] |
wangzhihuan0815@gmail.com
|
d045c1f2d9bbf9c9ae7d90b60a3d2acae0704637
|
acd41dc7e684eb2e58b6bef2b3e86950b8064945
|
/res/packages/scripts/scripts/client/gui/miniclient/tech_tree/pointcuts.py
|
fb5d3bd3f860d356b28b23a159f21b25c9372f1e
|
[] |
no_license
|
webiumsk/WoT-0.9.18.0
|
e07acd08b33bfe7c73c910f5cb2a054a58a9beea
|
89979c1ad547f1a1bbb2189f5ee3b10685e9a216
|
refs/heads/master
| 2021-01-20T09:37:10.323406
| 2017-05-04T13:51:43
| 2017-05-04T13:51:43
| 90,268,530
| 0
| 0
| null | null | null | null |
WINDOWS-1250
|
Python
| false
| false
| 1,103
|
py
|
# 2017.05.04 15:21:52 Střední Evropa (letní čas)
# Embedded file name: scripts/client/gui/miniclient/tech_tree/pointcuts.py
import aspects
from helpers import aop
class OnTechTreePopulate(aop.Pointcut):
def __init__(self):
aop.Pointcut.__init__(self, 'gui.Scaleform.daapi.view.lobby.techtree.TechTree', 'TechTree', '_populate', aspects=(aspects.OnTechTreePopulate,))
class OnBuyVehicle(aop.Pointcut):
def __init__(self, config):
aop.Pointcut.__init__(self, 'gui.Scaleform.daapi.view.lobby.vehicle_obtain_windows', 'VehicleBuyWindow', 'submit', aspects=(aspects.OnBuyVehicle(config),))
class OnRestoreVehicle(aop.Pointcut):
def __init__(self, config):
aop.Pointcut.__init__(self, 'gui.Scaleform.daapi.view.lobby.vehicle_obtain_windows', 'VehicleRestoreWindow', 'submit', aspects=(aspects.OnRestoreVehicle(config),))
# okay decompyling C:\Users\PC\wotmods\files\originals\res\packages\scripts\scripts\client\gui\miniclient\tech_tree\pointcuts.pyc
# decompiled 1 files: 1 okay, 0 failed, 0 verify failed
# 2017.05.04 15:21:52 Střední Evropa (letní čas)
|
[
"info@webium.sk"
] |
info@webium.sk
|
5573c985cf87f71b6dc605b266b0413315c3457f
|
15e818aada2b18047fa895690bc1c2afda6d7273
|
/analysis/control/optimize.py
|
84bb77fa593651b7c63536c6d78e82f883a5d0b6
|
[
"Apache-2.0"
] |
permissive
|
ghomsy/makani
|
4ee34c4248fb0ac355f65aaed35718b1f5eabecf
|
818ae8b7119b200a28af6b3669a3045f30e0dc64
|
refs/heads/master
| 2023-01-11T18:46:21.939471
| 2020-11-10T00:23:31
| 2020-11-10T00:23:31
| 301,863,147
| 0
| 0
|
Apache-2.0
| 2020-11-10T00:23:32
| 2020-10-06T21:51:21
| null |
UTF-8
|
Python
| false
| false
| 3,865
|
py
|
# Copyright 2020 Makani Technologies LLC
#
# 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.
"""Wrappers around third-party optimization libraries."""
import cvxopt
import cvxopt.solvers
from makani.analysis.control import type_util
import numpy as np
from numpy import linalg
# pylint doesn't like capital letters in variable names, in contrast
# to numerical optimization conventions.
# pylint: disable=invalid-name
class ArgumentException(Exception):
pass
class BadSolutionException(Exception):
pass
class NoSolutionException(Exception):
pass
def SolveQp(P, q, G, h, A, b, ineq_tolerance=1e-6, eq_tolerance=1e-6):
"""Solve a quadratic program (QP).
Solves a QP of the form:
min. 0.5 * x^T * P x + q^T * x
subj. to (G * x)[i] <= h[i] for i in len(x)
A * x = b
Arguments:
P: Quadratic term of the cost (n-by-n positive semidefinite np.matrix).
q: Linear term of the cost (n-by-1 np.matrix).
G: Linear term of inequality constraints (k-by-n np.matrix).
h: constant term of the inequality constraints (k-by-1 np.matrix).
A: Linear term of the equations (l-by-n np.matrix).
b: Constant term of the equations (l-by-1 np.matrix).
ineq_tolerance: Required tolerance for inequality constraints.
eq_tolerance: Required tolerance for equality constraints.
Raises:
ArgumentException: If the arguments are not of the right type or shape.
NoSolutionException: If the solver reports any errors.
BadSolutionException: If the solver returns a solution that does not respect
constraints conditions.
Returns:
A n-by-1 np.matrix containing the (not necessarily unique) optimal solution.
"""
if (not isinstance(q, np.matrix) or not isinstance(h, np.matrix)
or not isinstance(b, np.matrix)):
raise ArgumentException()
num_var = q.shape[0]
num_ineq = h.shape[0]
num_eq = b.shape[0]
if (not type_util.CheckIsMatrix(P, shape=(num_var, num_var))
or not np.all(P.A1 == P.T.A1)
or not type_util.CheckIsMatrix(q, shape=(num_var, 1))
or not type_util.CheckIsMatrix(G, shape=(num_ineq, num_var))
or not type_util.CheckIsMatrix(h, shape=(num_ineq, 1))
or not type_util.CheckIsMatrix(A, shape=(num_eq, num_var))
or not type_util.CheckIsMatrix(b, shape=(num_eq, 1))):
raise ArgumentException(num_var, num_ineq, num_eq)
eig, _ = linalg.eigh(P)
if not np.all(eig >= -1e-6):
raise ArgumentException('P is not positive definite')
old_options = cvxopt.solvers.options
cvxopt.solvers.options['show_progress'] = False
try:
result = cvxopt.solvers.qp(cvxopt.matrix(P),
cvxopt.matrix(q),
cvxopt.matrix(G),
cvxopt.matrix(h),
cvxopt.matrix(A),
cvxopt.matrix(b))
except Exception as e:
raise NoSolutionException(e)
if result['status'] != 'optimal':
raise NoSolutionException(result)
x = np.matrix(result['x'])
# Check primal feasibility.
if np.any(G * x - h >= ineq_tolerance):
raise BadSolutionException('Inequalities mismatch.')
if np.any(np.abs(b - A * x) >= eq_tolerance):
raise BadSolutionException('Equalities mismatch.')
# TODO: Test optimality.
cvxopt.solvers.options = old_options
return np.matrix(result['x'])
|
[
"luislarco@google.com"
] |
luislarco@google.com
|
87d64712d998d3b868640d48f892d7e959c074cc
|
87dae6d55c66df1d40d6881272009319a1600cb3
|
/PROGRAMACION I SEGUNDO CUATRIMESTE TP1 EJ 1.py
|
fdb33f593f6082dcfbe9ff1eb7b7f96ae7012bcd
|
[] |
no_license
|
abaldeg/EjerciciosPython
|
92a30a82c05ec75aa7f313c8a6fa0dd052a8db11
|
c8a3238587ebf6b10dbff32516c81bf00bb01630
|
refs/heads/master
| 2021-07-09T07:46:11.584855
| 2020-11-09T11:51:50
| 2020-11-09T11:51:50
| 210,438,930
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 679
|
py
|
"""
Desarrollar una función que reciba tres números positivos y devuelva el mayor de
los tres, sólo si éste es único (mayor estricto). En caso de no existir el mayor estricto
devolver -1. No utilizar operadores lógicos (and, or, not). Desarrollar también
un programa para ingresar los tres valores, invocar a la función y mostrar el
máximo hallado, o un mensaje informativo si éste no existe.
"""
def obtenerMayor(n1,n2,n3):
if n1>n2:
if n1>n3:
mayor=n1
elif n2>n1:
if n2>n3:
mayor=n2
elif n3>n1:
if n3>n2:
mayor=n3
else:
mayor=-1
return(mayor)
print(obtenerMayor(1,1,1))
|
[
"abaldeg@gmail.com"
] |
abaldeg@gmail.com
|
9de584dc3b0a4e354a76f9b19a508aacad68619d
|
d79ec3cb3e59778d2b4a17846434ef2d027d5f98
|
/polls/migrations/0001_initial.py
|
d025fcfa894499c76821c28ea2673060914a4cd2
|
[] |
no_license
|
Marlysson/PollsApp
|
df08a9eae257f947f93ffa4130aec26186a087a8
|
57b1477ecc3732444123dbfa996a7287dc5d7052
|
refs/heads/master
| 2020-12-02T10:13:55.554610
| 2017-11-11T14:50:21
| 2017-11-11T14:50:21
| 96,703,281
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 700
|
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-06 19:29
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Question',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('question_text', models.CharField(max_length=50)),
('closed', models.BooleanField(default=False)),
('pub_date', models.DateField()),
],
),
]
|
[
"marlysson5@gmail.com"
] |
marlysson5@gmail.com
|
8e10a71488576fd11c908c3ed8dcc5e6ab0dfff5
|
8c9d5bc245b343d9a36882d6d1c850ce6a86442d
|
/dbdaora/geospatial/_tests/datastore/conftest.py
|
3fa3329a173ddadfe0ab7827399e84af9c563b7e
|
[
"MIT"
] |
permissive
|
dutradda/dbdaora
|
1089fa9c80a93c38357818680327b24d48ac8b64
|
5c87a3818e9d736bbf5e1438edc5929a2f5acd3f
|
refs/heads/master
| 2021-07-04T10:06:59.596720
| 2020-12-05T12:24:45
| 2020-12-05T12:24:45
| 205,046,848
| 23
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 446
|
py
|
import pytest
from dbdaora import DatastoreGeoSpatialRepository, KindKeyDatastoreDataSource
@pytest.fixture
def fallback_data_source():
return KindKeyDatastoreDataSource()
@pytest.fixture
def fake_repository_cls(fake_entity_cls):
class FakeGeoSpatialRepository(DatastoreGeoSpatialRepository):
name = 'fake'
key_attrs = ('fake2_id', 'fake_id')
entity_cls = fake_entity_cls
return FakeGeoSpatialRepository
|
[
"diogo.albuquerque@luizalabs.com"
] |
diogo.albuquerque@luizalabs.com
|
f5c61dfd6024796264c0b50d239d70e492c8e49e
|
e83e8a3b7ef31b36b2c590b37bf2d1df1487fe5a
|
/tests/test_docs/test_query.py
|
a7d055d10b61f98b14ac194e3ebf9d696b3d26ff
|
[
"MIT"
] |
permissive
|
duilio/django-ninja
|
19d66eae1b3b01f9910f3ea0f569ed6d3a561707
|
8dac3c981bcf431322d32acd34c8179564a3698d
|
refs/heads/master
| 2023-01-21T07:17:02.544071
| 2020-11-25T10:48:30
| 2020-11-25T10:48:30
| 316,243,580
| 0
| 0
|
MIT
| 2020-11-26T13:56:19
| 2020-11-26T13:45:12
| null |
UTF-8
|
Python
| false
| false
| 3,259
|
py
|
from unittest.mock import patch
from ninja import NinjaAPI
from client import NinjaClient
def test_examples():
api = NinjaAPI()
with patch("builtins.api", api, create=True):
import docs.src.tutorial.query.code01
import docs.src.tutorial.query.code02
import docs.src.tutorial.query.code03
import docs.src.tutorial.query.code010
client = NinjaClient(api)
# Defaults
assert client.get("/weapons").json() == [
"Ninjato",
"Shuriken",
"Katana",
"Kama",
"Kunai",
"Naginata",
"Yari",
]
assert client.get("/weapons?offset=0&limit=3").json() == [
"Ninjato",
"Shuriken",
"Katana",
]
assert client.get("/weapons?offset=2&limit=2").json() == [
"Katana",
"Kama",
]
# Required/Optional
assert client.get("/weapons/search?offset=1&q=k").json() == [
"Katana",
"Kama",
"Kunai",
]
# Coversion
# fmt: off
assert client.get("/example?b=1").json() == [None, True, None, None]
assert client.get("/example?b=True").json() == [None, True, None, None]
assert client.get("/example?b=true").json() == [None, True, None, None]
assert client.get("/example?b=on").json() == [None, True, None, None]
assert client.get("/example?b=yes").json() == [None, True, None, None]
assert client.get("/example?b=0").json() == [None, False, None, None]
assert client.get("/example?b=no").json() == [None, False, None, None]
assert client.get("/example?b=false").json() == [None, False, None, None]
assert client.get("/example?d=1577836800").json() == [None, None, "2020-01-01", None]
assert client.get("/example?d=2020-01-01").json() == [None, None, "2020-01-01", None]
# fmt: on
# Schema
assert client.get("/filter").json() == {
"filters": {"limit": 100, "offset": None, "query": None}
}
assert client.get("/filter?limit=10").json() == {
"filters": {"limit": 10, "offset": None, "query": None}
}
assert client.get("/filter?offset=10").json() == {
"filters": {"limit": 100, "offset": 10, "query": None}
}
assert client.get("/filter?query=10").json() == {
"filters": {"limit": 100, "offset": None, "query": "10"}
}
schema = api.get_openapi_schema("")
params = schema["paths"]["/filter"]["get"]["parameters"]
assert params == [
{
"in": "query",
"name": "limit",
"required": False,
"schema": {"title": "Limit", "default": 100, "type": "integer"},
},
{
"in": "query",
"name": "offset",
"required": False,
"schema": {"title": "Offset", "type": "integer"},
},
{
"in": "query",
"name": "query",
"required": False,
"schema": {"title": "Query", "type": "string"},
},
]
|
[
"ppr.vitaly@gmail.com"
] |
ppr.vitaly@gmail.com
|
edcc63746e71ca4f277f371dacf3b89403bc4ebd
|
3ee1bb0d0acfa5c412b37365a4564f0df1c093fb
|
/lotte/31_eff_cnn.py
|
8635f32148d2aa946e79fef91e3e007516f0af09
|
[] |
no_license
|
moileehyeji/Study
|
3a20bf0d74e1faec7a2a5981c1c7e7861c08c073
|
188843c6415a4c546fdf6648400d072359d1a22b
|
refs/heads/main
| 2023-04-18T02:30:15.810749
| 2021-05-04T08:43:53
| 2021-05-04T08:43:53
| 324,901,835
| 3
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,598
|
py
|
import numpy as np
import pandas as pd
import tensorflow as tf
from keras.preprocessing.image import ImageDataGenerator
from numpy import expand_dims
from keras import Sequential
from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
from keras.optimizers import Adam,SGD
from sklearn.model_selection import train_test_split
from tensorflow.keras.applications import EfficientNetB4,EfficientNetB2,EfficientNetB1
from tensorflow.keras.applications.efficientnet import preprocess_input
from tqdm import tqdm
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Model
from tensorflow.keras.layers import GlobalAveragePooling2D, Flatten, BatchNormalization, Dense, Activation, Conv2D, Dropout
from tensorflow.keras import regularizers
#data load
x = np.load("C:/data/lotte/npy/128_project_x.npy",allow_pickle=True)
y = np.load("C:/data/lotte/npy/128_project_y.npy",allow_pickle=True)
x_pred = np.load('C:/data/lotte/npy/128_test.npy',allow_pickle=True)
x = preprocess_input(x)
x_pred = preprocess_input(x_pred)
idg = ImageDataGenerator(
width_shift_range=(-1,1),
height_shift_range=(-1,1),
rotation_range=45,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest')
idg2 = ImageDataGenerator()
x_train, x_valid, y_train, y_valid = train_test_split(x,y, train_size = 0.9, shuffle = True, random_state=66)
train_generator = idg.flow(x_train,y_train,batch_size=32, seed = 42)
valid_generator = idg2.flow(x_valid,y_valid)
efficientnet = EfficientNetB2(include_top=False,weights='imagenet',input_shape=x_train.shape[1:])
a = efficientnet.output
a = Conv2D(filters = 32,kernel_size=(12,12), strides=(1,1),padding='same',kernel_regularizer=regularizers.l2(1e-5)) (a)
a = BatchNormalization() (a)
a = Activation('swish') (a)
a = GlobalAveragePooling2D() (a)
a = Dense(512, activation= 'swish') (a)
a = Dropout(0.5) (a)
a = Dense(1000, activation= 'softmax') (a)
model = Model(inputs = efficientnet.input, outputs = a)
# efficientnet.summary()
mc = ModelCheckpoint('C:/data/lotte/h5/[0.01902]31_eff_cnn.h5',save_best_only=True, verbose=1)
early_stopping = EarlyStopping(patience= 10)
lr = ReduceLROnPlateau(patience= 5, factor=0.4)
model.compile(loss='categorical_crossentropy',
optimizer=tf.keras.optimizers.SGD(learning_rate=0.02, momentum=0.9),
metrics=['acc'])
# learning_history = model.fit_generator (train_generator,epochs=100, steps_per_epoch= len(x_train) / 32,
# validation_data=valid_generator, callbacks=[early_stopping,lr,mc])
# predict
model.load_weights('C:/data/lotte/h5/[0.01902]31_eff_cnn.h5')
result = model.predict(x_pred,verbose=True)
sub = pd.read_csv('C:/data/lotte/csv/sample.csv')
sub['prediction'] = np.argmax(result,axis = 1)
sub.to_csv('C:/data/lotte/csv/31_1.csv',index=False)
""" tta_steps = 30
predictions = []
for i in tqdm(range(tta_steps)):
# generator 초기화
test_generator.reset()
preds = model.predict_generator(generator = test_generator, verbose = 1)
predictions.append(preds)
sub = pd.read_csv('C:/data/lotte/sample.csv')
sub['prediction'] = np.argmax(result,axis = 1)
sub.to_csv('C:/data/lotte/csv/31_tta_i.csv',index=False)
pred = np.mean(predictions, axis=0)
sub = pd.read_csv('C:/data/lotte/sample.csv')
sub['prediction'] = np.argmax(result,axis = 1)
sub.to_csv('C:/data/lotte/31_tta.csv',index=False) """
# 최종 31 : 77.919
# [0.01902]31_eff_cnn 31_1: 73.894
# [0.00776]31_eff_cnn 31_2: 77.403
|
[
"noreply@github.com"
] |
moileehyeji.noreply@github.com
|
3150e892a3d4da245621a1bb195d4cbfa8821d0b
|
ba09a6cc089e408e2a865810b0e365d004712ce8
|
/Calculator/calculator.py
|
b858bb30a91766785f55b12d25b67dfc1136b2cd
|
[] |
no_license
|
ephreal/Silliness
|
5459977e1bca44cde4639f8bf83bd8a976b2ee63
|
bce290f86f818ad926613e84a07e5d354a112c4b
|
refs/heads/master
| 2021-06-05T02:41:42.467732
| 2020-02-20T16:31:35
| 2020-02-20T16:31:35
| 133,086,053
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,289
|
py
|
import tkinter as tk
from decimal import Decimal
from tkinter import ttk
class Calculator(ttk.Frame):
def __init__(self, master=tk.Tk()):
super().__init__(master)
self.master = master
self.master.title("tKalculator")
self.operator = None
self.prev_num = 0
self.completed_calculation = False
self.grid()
self.create_widgets()
self.bind_keys()
self.arrange_widgets()
self.mainloop()
def create_widgets(self):
"""
Create all calculator buttons
and widgets
"""
self.number_buttons = []
# Number display
self.top_display_space = ttk.Label(self, text=" ")
self.display = tk.Text(self, height=1, width=30, pady=4)
self.display.insert(1.0, "0")
self.display["state"] = "disabled"
self.bottom_display_space = ttk.Label(self, text=" ")
# Number buttons
# For some reason, the for loop makes everything send
# a "9" to the update function
for num in range(0, 10):
num = str(num)
self.number_buttons.append(
# note to self: The num=num is necessary here
ttk.Button(self, text=num, command=lambda num=num: self.update(num))
)
self.decimal_button = ttk.Button(self, text=".",
command=lambda: self.update("."))
# Special Buttons
self.clearall_button = ttk.Button(self, text="A/C", command=self.all_clear)
self.clear_button = ttk.Button(self, text="C", command=self.clear)
# Math operators
self.add_button = ttk.Button(self, text="+", command=lambda: self.math("+"))
self.sub_button = ttk.Button(self, text="-", command=lambda: self.math("-"))
self.mult_button = ttk.Button(self, text="X", command=lambda: self.math("x"))
self.div_button = ttk.Button(self, text="/", command=lambda: self.math("/"))
self.eql_button = ttk.Button(self, text="=", command=lambda: self.math("="))
def arrange_widgets(self):
"""
Arrange all calculator widgets.
"""
# Display
self.top_display_space.grid(row=0, column=1)
self.display.grid(row=1, column=0, columnspan=5)
self.bottom_display_space.grid(row=2, column=2)
# Number buttons
row = 3
column = 1
for i in range(1, 10):
self.number_buttons[i].grid(row=row, column=column)
column += 1
if column > 3:
column = 1
row += 1
self.number_buttons[0].grid(row=6, column=2)
self.decimal_button.grid(row=6, column=1)
# Special Buttons
self.clearall_button.grid(row=7, column=1)
self.clear_button.grid(row=6, column=3)
# Math operator buttons
self.add_button.grid(row=7, column=2)
self.sub_button.grid(row=7, column=3)
self.mult_button.grid(row=8, column=2)
self.div_button.grid(row=8, column=3)
self.eql_button.grid(row=8, column=1)
def bind_keys(self):
"""
Binds events to keyboard button presses.
"""
# Keys to bind
keys = "1234567890.caCA+-*x/="
special_keys = [
"<KP_1>", "<KP_2>", "<KP_3>",
"<KP_4>", "<KP_5>", "<KP_6>",
"<KP_7>", "<KP_8>", "<KP_9>",
"<KP_0>", "<KP_Decimal>", "<KP_Add>",
"<KP_Subtract>", "<KP_Multiply>",
"<KP_Divide>", "<KP_Enter>",
"<Return>", "<Escape>",
"<BackSpace>"
]
# A couple for loops to bind all the keys
for key in keys:
self.master.bind(key, self.keypress_handler)
for key in special_keys:
self.master.bind(key, self.keypress_handler)
def backspace(self, event):
"""
Remove one character from the display.
"""
self.display["state"] = "normal"
current = self.display.get(1.0, tk.END)
self.display.delete(1.0, tk.END)
current = current[:-2]
# Make sure that the display is never empty
if current == "":
current = "0"
self.display.insert(1.0, current)
self.display["state"] = "disabled"
def keypress_handler(self, event):
"""
Handles any bound keyboard presses.
"""
char_keycode = '01234567890.'
char_operator = "+-x*/"
if (event.char in char_keycode):
self.update(event.char)
elif event.char in char_operator:
self.math(event.char)
elif event.char == "\r" or event.char == "=":
self.math("=")
elif event.char == "\x1b":
self.master.destroy()
elif event.char == "c" or event.char == "C":
self.clear()
elif event.char == "a" or event.char == "A":
self.all_clear()
def update(self, character):
"""
Handles all updating of the number display.
"""
# Allow editing of the display
self.display["state"] = "normal"
# Get the current number
num = self.display.get(1.0, tk.END)
# clear the display
self.display.delete(1.0, tk.END)
# Remove "\n"
num = num.strip()
# Clear num provided we're not putting a
# decimal after a zero
if num == "0" and not character == ".":
num = ""
num = f"{num}{character}"
self.display.insert(1.0, f"{num}")
self.display["state"] = "disabled"
def all_clear(self):
"""
Resets everything for starting a
new calculation.
"""
self.clear()
self.prev_num = 0
self.operator = None
def clear(self):
"""
Clears the display by removing
any current text and setting the
display to 0
"""
self.display["state"] = "normal"
self.display.delete(1.0, tk.END)
self.display.insert(1.0, "0")
self.display["state"] = "disabled"
def math(self, operator):
"""
Handle any actual math.
"""
if not self.operator:
# If an operator doesn't exist, the
# calculator is waiting for a new
# input.
self.operator = operator
self.prev_num = self.display.get(1.0, tk.END)
self.clear()
else:
# The calculator is ready to do some math.
self.prev_num = Decimal(self.prev_num)
curr_num = self.display.get(1.0, tk.END)
curr_num = Decimal(curr_num)
if self.operator == "+":
self.prev_num += curr_num
elif self.operator == "-":
self.prev_num -= curr_num
elif self.operator == "x" or self.operator == "*":
self.prev_num *= curr_num
elif self.operator == "/":
self.prev_num /= curr_num
self.operator = operator
if self.operator == "=":
# It's now time to show the current result
# of all calculations.
self.display["state"] = "normal"
self.display.delete(1.0, tk.END)
self.display.insert(1.0, str(self.prev_num))
self.display["state"] = "disabled"
self.completed_calculation = True
else:
# We're ready for another number to
# perform calculations on
self.clear()
if __name__ == "__main__":
calc = Calculator()
|
[
"tjannx@hotmail.com"
] |
tjannx@hotmail.com
|
3a239988545f0c87767b909a0dfbec058597d3dd
|
f9033131dc4d66ede2c5c22fcaa4a0be5b682152
|
/Sorting/Tasks/eolymp(5089).py
|
21668b326d3a8cfd9412a0d740ab1941e4accc97
|
[] |
no_license
|
Invalid-coder/Data-Structures-and-algorithms
|
9bd755ce3d4eb11e605480db53302096c9874364
|
42c6eb8656e85b76f1c0043dcddc9c526ae12ba1
|
refs/heads/main
| 2023-04-29T08:40:34.661184
| 2021-05-19T10:57:37
| 2021-05-19T10:57:37
| 301,458,981
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 860
|
py
|
#https://www.e-olymp.com/uk/submissions/7293961
def greater(a, b):
i = 0
j = 0
while i < len(a) and j < len(b):
if ord(a[i]) > ord(b[j]):
return a
elif ord(a[i]) < ord(b[j]):
return b
else:
i += 1
j += 1
if i == len(a) and j < len(b):
return b
elif j == len(b) and i < len(a):
return a
else:
return a
def selectionSort(array):
n = len(array)
for i in range(n - 1, 0, -1):
maxpos = 0
for j in range(1, i + 1):
if greater(array[maxpos], array[j]) == array[j]:
maxpos = j
array[i], array[maxpos] = array[maxpos], array[i]
if __name__ == '__main__':
n = int(input())
array = [input() for _ in range(n)]
selectionSort(array)
for el in array:
print(el)
|
[
"gusevvovik@gmail.com"
] |
gusevvovik@gmail.com
|
1d2ff22060d90ac5eebb0f152bd66b24eb89a21d
|
4d66a2b4f40e7169b00871e7f75202fd38201d98
|
/linkie/tests/run_tests.py
|
5bdd879b985b69fb0642864bdeba2dbaff39bfcc
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
uccser/linkie
|
e90d97d9d22c9a1d1eb95d87eb59f3079e4da2ce
|
f062762c42c812f18374a064ba2ac80d9146b7d5
|
refs/heads/master
| 2023-03-23T10:56:12.508180
| 2020-06-08T00:07:33
| 2020-06-08T00:07:33
| 124,695,953
| 2
| 0
|
MIT
| 2021-03-25T21:38:39
| 2018-03-10T20:28:47
|
Python
|
UTF-8
|
Python
| false
| false
| 3,251
|
py
|
import os
import unittest
from subprocess import run
from linkie import Linkie
class LinkieTestSuite(unittest.TestCase):
def __init__(self, *args, **kwargs):
unittest.TestCase.__init__(self, *args, **kwargs)
self.default_working_directory = os.getcwd()
def setUp(self):
os.chdir(self.default_working_directory)
def test_basic(self):
os.chdir('./linkie/tests/assets/basic/')
linkie = Linkie()
self.assertEqual(linkie.run(), 0)
def test_broken(self):
os.chdir('./linkie/tests/assets/broken/')
linkie = Linkie()
self.assertEqual(linkie.run(), 1)
def test_multiple(self):
os.chdir('./linkie/tests/assets/multiple/')
linkie = Linkie()
self.assertEqual(linkie.run(), 0)
def test_excluded_directories(self):
os.chdir('./linkie/tests/assets/excluded_directories/')
linkie = Linkie()
self.assertEqual(linkie.run(), 0)
def test_excluded_directories_custom(self):
os.chdir('./linkie/tests/assets/excluded_directories_custom/')
linkie = Linkie(config_file_path='linkie.yaml')
self.assertEqual(linkie.run(), 0)
def test_file_types(self):
os.chdir('./linkie/tests/assets/file_types/')
linkie = Linkie()
self.assertEqual(linkie.run(), 0)
def test_file_types_custom(self):
os.chdir('./linkie/tests/assets/file_types_custom/')
linkie = Linkie(config_file_path='linkie.yaml')
self.assertEqual(linkie.run(), 1)
def test_skip_urls(self):
os.chdir('./linkie/tests/assets/skip_urls/')
linkie = Linkie()
self.assertEqual(linkie.run(), 0)
self.assertEqual(len(linkie.urls), 2)
def test_skip_urls_custom(self):
os.chdir('./linkie/tests/assets/skip_urls_custom/')
linkie = Linkie(config_file_path='linkie.yaml')
self.assertEqual(linkie.run(), 0)
self.assertEqual(len(linkie.urls), 1)
def test_command_line_basic(self):
linkie = run('linkie', cwd='./linkie/tests/assets/basic/')
self.assertEqual(linkie.returncode, 0)
def test_command_line_broken(self):
linkie = run('linkie', cwd='./linkie/tests/assets/broken/')
self.assertEqual(linkie.returncode, 1)
def test_command_line_multiple(self):
linkie = run('linkie', cwd='./linkie/tests/assets/multiple/')
self.assertEqual(linkie.returncode, 0)
def test_command_line_excluded_directories(self):
linkie = run('linkie', cwd='./linkie/tests/assets/excluded_directories/')
self.assertEqual(linkie.returncode, 0)
def test_command_line_excluded_directories_custom(self):
linkie = run(['linkie', 'linkie.yaml'], cwd='./linkie/tests/assets/excluded_directories_custom/')
self.assertEqual(linkie.returncode, 0)
def test_command_line_file_types(self):
linkie = run('linkie', cwd='./linkie/tests/assets/file_types/')
self.assertEqual(linkie.returncode, 0)
def test_command_line_file_types_custom(self):
linkie = run(['linkie', 'linkie.yaml'], cwd='./linkie/tests/assets/file_types_custom/')
self.assertEqual(linkie.returncode, 1)
if __name__ == '__main__':
unittest.main()
|
[
"jackmorgannz@gmail.com"
] |
jackmorgannz@gmail.com
|
91ed8fe756697243b39c0671ce9ffe931e906c4a
|
7ec38beb6f041319916390ee92876678412b30f7
|
/src/leecode/explore/queue_stack/01.Design Circular Queue.py
|
3b4c90c483baf7a706bf6efc41b4e3e9939b2ee3
|
[] |
no_license
|
hopensic/LearnPython
|
3570e212a1931d4dad65b64ecdd24414daf51c73
|
f735b5d865789843f06a623a4006f8883d6d1ae0
|
refs/heads/master
| 2022-02-18T23:11:30.663902
| 2022-02-12T17:51:56
| 2022-02-12T17:51:56
| 218,924,551
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,471
|
py
|
class MyCircularQueue:
def __init__(self, k: int):
self.queuesize = k
self.lst = [None] * k
self.head = -1
self.tail = -1
"""
Initialize your data structure here. Set the size of the queue to be k.
"""
def enQueue(self, value: int) -> bool:
"""
Insert an element into the circular queue. Return true if the operation is successful.
"""
if self.isFull():
return False
if self.head < 0:
self.head = (self.head + 1) % self.queuesize
self.tail = (self.tail + 1) % self.queuesize
self.lst[self.tail] = value
return True
def deQueue(self) -> bool:
"""
Delete an element from the circular queue. Return true if the operation is successful.
"""
if self.isEmpty():
return False
self.lst[self.head] = None
if self.head == self.tail:
self.head = -1
self.tail = -1
else:
self.head = (self.head + 1) % self.queuesize
return True
def Front(self) -> int:
"""
Get the front item from the queue.
"""
if self.head > -1:
return self.lst[self.head]
else:
return -1
def Rear(self) -> int:
"""
Get the last item from the queue.
"""
if self.tail > -1:
return self.lst[self.tail]
else:
return -1
def isEmpty(self) -> bool:
"""
Checks whether the circular queue is empty or not.
"""
return True if self.head < 0 and self.tail < 0 else False
def isFull(self) -> bool:
"""
Checks whether the circular queue is full or not.
"""
if self.head > -1 and self.tail > -1:
if (self.tail + 1) % self.queuesize == self.head:
return True
else:
return False
else:
return False
# Your MyCircularQueue object will be instantiated and called as such:
obj = MyCircularQueue(2)
param_1 = obj.enQueue(4)
param_1 = obj.Rear()
param_1 = obj.enQueue(9)
param_2 = obj.deQueue()
param_2 = obj.Front()
param_2 = obj.deQueue()
param_2 = obj.deQueue()
param_1 = obj.Rear()
param_2 = obj.deQueue()
param_1 = obj.enQueue(5)
param_4 = obj.Rear()
param_2 = obj.deQueue()
param_2 = obj.Front()
param_2 = obj.deQueue()
param_2 = obj.deQueue()
param_2 = obj.deQueue()
|
[
"hopensic@gmail.com"
] |
hopensic@gmail.com
|
18b8e0edad42cc713cfad35c0c03af6cd4ec0305
|
e2cd117b1060d445d0c6825b4761dc8d9d261a59
|
/2020/algorithm/앨리스코딩/6. 0 이동시키기.py
|
6476493c4bdbd3ab90e1098ac3ac28208bbf5509
|
[] |
no_license
|
winterash2/TIL
|
856fc55f076a6aadff60e6949a3ce44534e24eda
|
9b8e93e4eacce2644a9a564e3b118bb00c3f4132
|
refs/heads/master
| 2023-06-12T23:58:00.192688
| 2021-07-04T14:20:30
| 2021-07-04T14:20:30
| 288,957,710
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,189
|
py
|
# 0 이동시키기
# 여러개의 0과 양의 정수들이 섞여 있는 배열이 주어졌다고 합시다. 이 배열에서 0들은 전부 뒤로 빼내고, 나머지 숫자들의 순서는 그대로 유지한 배열을 반환하는 함수를 만들어 봅시다.
# 예를 들어서, [0, 8, 0, 37, 4, 5, 0, 50, 0, 34, 0, 0] 가 입력으로 주어졌을 경우 [8, 37, 4, 5, 50, 34, 0, 0, 0, 0, 0, 0] 을 반환하면 됩니다.
# 이 문제는 공간 복잡도를 고려하면서 풀어 보도록 합시다. 공간 복잡도 O(1)으로 이 문제를 풀 수 있을까요?
# def moveZerosToEnd(nums): #공간복잡도 높음
# result = []
# num_zero = 0
# for num in nums:
# if num == 0:
# num_zero += 1
# else:
# result.append(num)
# for i in range(num_zero):
# result.append(0)
# return result
def moveZerosToEnd(nums):
i = j = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[j] = nums[i]
if i != j:
nums[i] = 0
j += 1
print(nums)
return nums
def main():
print(moveZerosToEnd([1, 8, 0, 37, 4, 5, 0, 50, 0, 34, 0, 0]))
main()
|
[
"winterash2@naver.com"
] |
winterash2@naver.com
|
61ecce1e44b4d35a64266562120e27f0ca389441
|
7b5c1352e1a4fb8352161cc135bfd1225a633828
|
/2017-cvr-tencent-final/src/data_process/shuffle.py
|
7e0c621d4a5903ba07e6d2e8d4dffff21d9be4f3
|
[] |
no_license
|
zgcgreat/2017-cvr-tencent
|
b7f54ae8df55fbb30f2430f695a148844982aa3a
|
fe79d0756bbf862d45e63e35b7c28da8396bcbda
|
refs/heads/master
| 2021-04-03T08:32:33.651705
| 2018-07-17T08:36:53
| 2018-07-17T08:36:53
| 124,724,199
| 6
| 3
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 559
|
py
|
# _*_ coding: utf-8 _*_
'''
打乱数据集顺序
'''
import random
import time
start = time.time()
print('shuffling dataset...')
input = open('../../data/traincp.csv', 'r')
output = open('../../data/train_data/train.csv', 'w')
lines = input.readlines()
outlines = []
output.write(lines.pop(0)) # pop()方法, 传递的是待删除元素的index
while lines:
line = lines.pop(random.randrange(len(lines)))
output.write(line)
input.close()
output.close()
print('dataset shuffled !')
print('Time spent: {0:.2f}s'.format(time.time() - start))
|
[
"1107630485@qq.com"
] |
1107630485@qq.com
|
4d33eb0ee9a1b6f8917d7d2ffbe3b0a8693c4976
|
07bd6d166bfe69f62559d51476ac724c380f932b
|
/devel/lib/python2.7/dist-packages/webots_demo/srv/_motor_set_control_pid.py
|
cc26f674b3a03915318d6b15b213af63468ca3be
|
[] |
no_license
|
Dangko/webots_differential_car
|
0efa45e1d729a14839e6e318da64c7f8398edd17
|
188fe93c2fb8d2e681b617df78b93dcdf52e09a9
|
refs/heads/master
| 2023-06-02T16:40:58.472884
| 2021-06-14T09:19:58
| 2021-06-14T09:19:58
| 376,771,194
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 8,158
|
py
|
# This Python file uses the following encoding: utf-8
"""autogenerated by genpy from webots_demo/motor_set_control_pidRequest.msg. Do not edit."""
import codecs
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class motor_set_control_pidRequest(genpy.Message):
_md5sum = "1ebf8f7154a3c8eec118cec294f2c32c"
_type = "webots_demo/motor_set_control_pidRequest"
_has_header = False # flag to mark the presence of a Header object
_full_text = """float64 controlp
float64 controli
float64 controld
"""
__slots__ = ['controlp','controli','controld']
_slot_types = ['float64','float64','float64']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
controlp,controli,controld
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(motor_set_control_pidRequest, self).__init__(*args, **kwds)
# message fields cannot be None, assign default values for those that are
if self.controlp is None:
self.controlp = 0.
if self.controli is None:
self.controli = 0.
if self.controld is None:
self.controld = 0.
else:
self.controlp = 0.
self.controli = 0.
self.controld = 0.
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
_x = self
buff.write(_get_struct_3d().pack(_x.controlp, _x.controli, _x.controld))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
_x = self
start = end
end += 24
(_x.controlp, _x.controli, _x.controld,) = _get_struct_3d().unpack(str[start:end])
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
_x = self
buff.write(_get_struct_3d().pack(_x.controlp, _x.controli, _x.controld))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
_x = self
start = end
end += 24
(_x.controlp, _x.controli, _x.controld,) = _get_struct_3d().unpack(str[start:end])
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
_struct_I = genpy.struct_I
def _get_struct_I():
global _struct_I
return _struct_I
_struct_3d = None
def _get_struct_3d():
global _struct_3d
if _struct_3d is None:
_struct_3d = struct.Struct("<3d")
return _struct_3d
# This Python file uses the following encoding: utf-8
"""autogenerated by genpy from webots_demo/motor_set_control_pidResponse.msg. Do not edit."""
import codecs
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class motor_set_control_pidResponse(genpy.Message):
_md5sum = "0b13460cb14006d3852674b4c614f25f"
_type = "webots_demo/motor_set_control_pidResponse"
_has_header = False # flag to mark the presence of a Header object
_full_text = """int8 success
"""
__slots__ = ['success']
_slot_types = ['int8']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
success
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(motor_set_control_pidResponse, self).__init__(*args, **kwds)
# message fields cannot be None, assign default values for those that are
if self.success is None:
self.success = 0
else:
self.success = 0
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
_x = self.success
buff.write(_get_struct_b().pack(_x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 1
(self.success,) = _get_struct_b().unpack(str[start:end])
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
_x = self.success
buff.write(_get_struct_b().pack(_x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
codecs.lookup_error("rosmsg").msg_type = self._type
try:
end = 0
start = end
end += 1
(self.success,) = _get_struct_b().unpack(str[start:end])
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
_struct_I = genpy.struct_I
def _get_struct_I():
global _struct_I
return _struct_I
_struct_b = None
def _get_struct_b():
global _struct_b
if _struct_b is None:
_struct_b = struct.Struct("<b")
return _struct_b
class motor_set_control_pid(object):
_type = 'webots_demo/motor_set_control_pid'
_md5sum = '712b4e401e3c9cbb098cd0435a9a13d3'
_request_class = motor_set_control_pidRequest
_response_class = motor_set_control_pidResponse
|
[
"1477055603@qq.com"
] |
1477055603@qq.com
|
3bd486d899d983a5806e09c4acf7cbbd5d851437
|
c3760e71f4024a9610bdde03de84a0c406601e63
|
/baiTapVN2.py
|
a4123564c7dfa336d2714212fc79c931f3b2bea1
|
[] |
no_license
|
thuongtran1210/Buoi3
|
3abe6040b15f48cf04bb39da10b5588254d7514f
|
f62fbf75ff0a0de89acfd122a0a70be44162468a
|
refs/heads/master
| 2022-12-28T22:26:21.288946
| 2020-10-04T16:43:23
| 2020-10-04T16:43:23
| 301,168,792
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 331
|
py
|
# ----Bài 02: Viết hàm
# def reverse_string(str)
# trả lại chuỗi đảo ngược của chuỗi str
# --------------------------------------------------------------
def reverse_string(str):
return str[::-1]
str=input("Nhập số nghịch đảo: ")
print(f"Sau khi nghịch đảo: {reverse_string(str)}")
|
[
"you@example.com"
] |
you@example.com
|
f5db65735ebada9140b63f4d29e2e61a85008ae1
|
ce55c319f5a78b69fefc63595d433864a2e531b5
|
/前后端分离-vue-DRF/houfen_DRF-projects/14day/zhuce_denglu/util/throttle.py
|
e3aab6ab4c5ccccbd9b04f6a13ac2cc5b000a29b
|
[] |
no_license
|
Suijng/1809_data
|
a072c875e8746190e3b715e53f1afe3323f4666b
|
45f8a57089f5c30ccc1a3cddb03b76dc95355417
|
refs/heads/master
| 2022-12-21T12:38:30.458291
| 2019-09-27T01:14:41
| 2019-09-27T01:14:41
| 211,207,071
| 0
| 0
| null | 2022-11-22T03:16:18
| 2019-09-27T00:55:21
|
HTML
|
UTF-8
|
Python
| false
| false
| 2,077
|
py
|
from rest_framework.throttling import SimpleRateThrottle
import time
class MyScopedRateThrottle(SimpleRateThrottle):
scope = 'unlogin'
def get_cache_key(self, request, view):
"""
Should return a unique cache-key which can be used for throttling.
Must be overridden.
May return `None` if the request should not be throttled.
"""
# IP地址用户获取访问记录
return self.get_ident(request)
# raise NotImplementedError('.get_cache_key() must be overridden')
# # 节流
# VISIT_RECORD = {}
#
#
# class VisitThrottle(object):
#
# def __init__(self):
# # 获取用户历史访问记录
# self.history = []
#
# # allow_request是否允许方法
# # True 允许访问
# # False 不允许访问
# def allow_request(self, request, view):
# # 1.获取用户IP
# user_ip = request._request.META.get("REMOTE_ADDR")
# key = user_ip
# print('1.user_ip------------', key)
#
# # 2.添加到访问记录里 创建当前时间
# createtime = time.time()
# if key not in VISIT_RECORD:
# # 当前的IP地址没有访问过服务器 没有记录 添加到字典
# VISIT_RECORD[key] = [createtime]
# return True
#
# # 获取当前用户所有的访问历史记录 返回列表
# visit_history = VISIT_RECORD[key]
# print('3.history==============', visit_history)
# self.history = visit_history
#
# # 用记录里的最有一个时间 对比 < 当前时间 -60秒
# while visit_history and visit_history[-1] < createtime - 60:
# # 删除用户记录
# visit_history.pop()
#
# # 判断小于5秒 添加到 历史列表最前面
# if len(visit_history) < 5:
# visit_history.insert(0, createtime)
# return True
#
# return False # 表示访问频率过高
#
# def wait(self):
# first_time = self.history[-1]
# return 60 - (time.time() - first_time)
|
[
"1627765913@qq.com"
] |
1627765913@qq.com
|
e2ee0e7695e88092fc028728b0f13572aeebd631
|
5b771c11e8967038025376c6ec31962ca90748dd
|
/insurance/insurance_reminder/urls.py
|
f00b885bb1c629961284a04ee7869785729b4efd
|
[] |
no_license
|
AsemAntar/Django_Projects
|
7135eca3b4bcb656fc88e0838483c97d7f1746e1
|
4141c2c7e91845eec307f6dd6c69199302eabb16
|
refs/heads/master
| 2022-12-10T06:32:35.787504
| 2020-05-26T14:43:01
| 2020-05-26T14:43:01
| 216,863,494
| 0
| 0
| null | 2022-12-05T13:31:53
| 2019-10-22T16:47:28
|
Python
|
UTF-8
|
Python
| false
| false
| 222
|
py
|
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('guest_registeration.urls')),
path('users/', include('users.urls')),
]
|
[
"asemantar@gmail.com"
] |
asemantar@gmail.com
|
dfece195db40ed9971ed5c97d130ee352f56a42f
|
7cca7ed981242788687db90d8f3a108bbcf4c6f9
|
/pretrain_CNN_fix_parameter_DQN/pretrain_env.py
|
595cbcee11364c4d917fb8941b8da2fce8d8ac1a
|
[] |
no_license
|
Ryanshuai/robot_round_catch
|
7204e1cf9927672257d542afc7a00bd710f5e243
|
1175fb3df0ae7ec395b85dfbfbcbb60a79878024
|
refs/heads/master
| 2021-09-09T23:08:59.680793
| 2018-03-20T06:32:51
| 2018-03-20T06:32:51
| 94,294,080
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,212
|
py
|
"""
This part of code is the environment.
Using Tensorflow to build the neural network.
"""
import numpy as np
import tensorflow as tf
import pygame
from random import uniform
FPS = 90
SCREEN_WHIDTH = 672
SCREEN_HEIGHT = 672
# init the game
pygame.init()
FPSCLOCK = pygame.time.Clock()
screen = pygame.display.set_mode([SCREEN_WHIDTH, SCREEN_HEIGHT])
pygame.display.set_caption('hunting')
# load resources
background = (255, 255, 255) # white
hunter_color = [(0, 0, 255), (255, 0, 0), (0, 255, 0), (255, 255, 0)] # B #R #G #Y
escaper_color = (0, 0, 0) # bck
class ENV:
def __init__(self):
self.hunter_radius = 8
self.escaper_radius = 8
self.max_pos = np.array([SCREEN_WHIDTH, SCREEN_HEIGHT])
self.catch_angle_max = np.pi * 3 / 4 # 135°
self.catch_dis = 50.
self.collide_min = self.hunter_radius + self.escaper_radius + 2.
# the center pos, x : [0, SCREEN_WHIDTH], y: [0, SCREEN_HEIGHT]
self.delta_t = 0.1 # 100ms
self.hunter_acc = 20
self.escaper_acc = 10
self.hunter_spd_max = 100 # 5 pixels once
self.escaper_spd_max = 70
self.hunter_spd = np.zeros([4, 2], dtype=np.float32)
self.escaper_spd = np.zeros([2], dtype=np.float32)
self._init_pos()
def _init_pos(self):
# the boundary
x_min = SCREEN_WHIDTH / 3
x_max = 2 * SCREEN_WHIDTH / 3
y_min = SCREEN_HEIGHT / 3
y_max = 2 * SCREEN_HEIGHT / 3
self.escaper_pos = np.array([uniform(x_min + self.collide_min, x_max - self.collide_min),
uniform(y_min + self.collide_min, y_max - self.collide_min)], dtype=np.float32)
self.hunter_pos = np.zeros([4, 2], dtype=np.float32)
self.hunter_pos[0] = [uniform(0, x_min - self.collide_min), uniform(0, y_min - self.collide_min)]
self.hunter_pos[1] = [uniform(x_max + self.collide_min, SCREEN_WHIDTH), uniform(0, y_min - self.collide_min)]
self.hunter_pos[2] = [uniform(0, x_min - self.collide_min), uniform(y_max + self.collide_min, SCREEN_HEIGHT)]
self.hunter_pos[3] = [uniform(x_max + self.collide_min, SCREEN_WHIDTH),
uniform(y_max + self.collide_min, SCREEN_HEIGHT)]
def frame_step(self, input_actions):
# update the pos and speed
self.move(input_actions)
# update the display
screen.fill(background)
for i in range(len(self.hunter_pos)):
pygame.draw.rect(screen, hunter_color[i],
((self.hunter_pos[i][0] - self.hunter_radius,
self.hunter_pos[i][1] - self.hunter_radius),
(self.hunter_radius*2, self.hunter_radius*2)))
pygame.draw.rect(screen, escaper_color,
((self.escaper_pos[0] - self.escaper_radius, self.escaper_pos[1] - self.escaper_radius),
(self.escaper_radius*2, self.escaper_radius*2)))
image_data = pygame.surfarray.array3d(pygame.display.get_surface())
pygame.display.update()
FPSCLOCK.tick(FPS)
robot_state = [self.escaper_pos[0], self.hunter_pos[0][0], self.hunter_pos[1][0], self.hunter_pos[2][0],self.hunter_pos[3][0],
self.escaper_pos[1], self.hunter_pos[0][1], self.hunter_pos[1][1], self.hunter_pos[2][1],self.hunter_pos[3][1],
self.escaper_spd[0], self.hunter_spd[0][0], self.hunter_spd[1][0], self.hunter_spd[2][0],self.hunter_spd[3][0],
self.escaper_spd[1], self.hunter_spd[0][1], self.hunter_spd[1][1], self.hunter_spd[2][1],self.hunter_spd[3][1],]
return image_data, robot_state
def move(self, input_actions):
robot_n = len(input_actions)
for i in range(robot_n - 1):#hunters
if input_actions[i] == 1: # up, update y_speed
self.hunter_spd[i][1] -= self.hunter_acc * self.delta_t
elif input_actions[i] == 2: # down
self.hunter_spd[i][1] += self.hunter_acc * self.delta_t
elif input_actions[i] == 3: # left, update x_speed
self.hunter_spd[i][0] -= self.hunter_acc * self.delta_t
elif input_actions[i] == 4: # right
self.hunter_spd[i][0] += self.hunter_acc * self.delta_t
else:
pass
if self.hunter_spd[i][0] < -self.hunter_spd_max:
self.hunter_spd[i][0] = -self.hunter_spd_max
elif self.hunter_spd[i][0] > self.hunter_spd_max:
self.hunter_spd[i][0] = self.hunter_spd_max
if self.hunter_spd[i][1] < -self.hunter_spd_max:
self.hunter_spd[i][1] = -self.hunter_spd_max
elif self.hunter_spd[i][1] > self.hunter_spd_max:
self.hunter_spd[i][1] = self.hunter_spd_max
else:
pass
self.hunter_pos[i] += self.hunter_spd[i] * self.delta_t
if self.hunter_pos[i][0] < 0:
self.hunter_pos[i][0] = 0
self.hunter_spd[i][0] = 0
elif self.hunter_pos[i][0] > SCREEN_WHIDTH:
self.hunter_pos[i][0] = SCREEN_WHIDTH
self.hunter_spd[i][0] = 0
else:
pass
if self.hunter_pos[i][1] < 0:
self.hunter_pos[i][1] = 0
self.hunter_spd[i][1] = 0
elif self.hunter_pos[i][1] > SCREEN_HEIGHT:
self.hunter_pos[i][1] = SCREEN_HEIGHT
self.hunter_spd[i][1] = 0
#escaper
if input_actions[robot_n - 1] == 1: # up, update y_speed
self.escaper_spd[1] -= self.escaper_acc * self.delta_t
elif input_actions[robot_n - 1] == 2: # down
self.escaper_spd[1] += self.escaper_acc * self.delta_t
elif input_actions[robot_n - 1] == 3: # left, update x_speed
self.escaper_spd[0] -= self.escaper_acc * self.delta_t
elif input_actions[robot_n - 1] == 4: # right
self.escaper_spd[0] += self.escaper_acc * self.delta_t
else:
pass
if self.escaper_spd[0] < -self.escaper_spd_max:
self.escaper_spd[0] = -self.escaper_spd_max
elif self.escaper_spd[0] > self.escaper_spd_max:
self.escaper_spd[0] = self.escaper_spd_max
else:
pass
if self.escaper_spd[1] < -self.escaper_spd_max:
self.escaper_spd[1] = -self.escaper_spd_max
elif self.escaper_spd[1] > self.escaper_spd_max:
self.escaper_spd[1] = self.escaper_spd_max
else:
pass
self.escaper_pos += self.escaper_spd * self.delta_t
if self.escaper_pos[0] < 0:
self.escaper_pos[0] = 0
self.escaper_spd[0] = 0
elif self.escaper_pos[0] > SCREEN_WHIDTH:
self.escaper_pos[0] = SCREEN_WHIDTH
self.escaper_spd[0] = 0
if self.escaper_pos[1] < 0:
self.escaper_pos[1] = 0
self.escaper_spd[1] = 0
elif self.escaper_pos[1] > SCREEN_HEIGHT:
self.escaper_pos[1] = SCREEN_HEIGHT
self.escaper_spd[1] = 0
|
[
"1018718155@qq.com"
] |
1018718155@qq.com
|
f96b6f6fb6ba491017ce77ff995c18a718e4bf44
|
d2e8ad203a37b534a113d4f0d4dd51d9aeae382a
|
/django-koldar-utils/django_koldar_utils/django_toolbox/conf/DictSettingMergerAppConf.py
|
82a1709767e65cb47e03e5e6f5f95f2f0dbda8dc
|
[
"MIT"
] |
permissive
|
Koldar/django-koldar-common-apps
|
40e24a7aae78973fa28ca411e2a32cb4b2f4dbbf
|
06e6bb103d22f1f6522e97c05ff8931413c69f19
|
refs/heads/main
| 2023-08-17T11:44:34.631914
| 2021-10-08T12:40:40
| 2021-10-08T12:40:40
| 372,714,560
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,166
|
py
|
from appconf import AppConf
class DictSettingMergerAppConf(AppConf):
"""
A derived class of AppConf that automatically merge the configurations from settings.py and the default ones.
In the settings you should have:
.. ::code-block:: python
APPCONF_PREFIX = {
"SETTINGS_1": 3
}
In the conf.py of the django_toolbox app, you need to code:
.. ::code-block:: python
class DjangoAppGraphQLAppConf(DictSettingMergerAppConfMixIn):
class Meta:
prefix = "APPCONF_PREFIX"
def configure(self):
return self.merge_configurations()
SETTINGS_1: int = 0
After that settings will be set to 3, rather than 0.
Note that this class merges only if in the settings.py there is a dictionary with the same name of the prefix!
"""
def merge_configurations(self):
# we have imported settings here in order to allow sphinx to buidl the documentation (otherwise it needs settings.py)
from django.conf import settings
prefix = getattr(self, "Meta").prefix
if not hasattr(settings, prefix):
return self.configured_data
# the data the user has written in the settings.py
data_in_settings = getattr(settings, prefix)
# the data in the AppConf instance specyfing default values
default_data = dict(self.configured_data)
result = dict()
# specify settings which do not have default values in the conf.py
# (thus are requried) with the values specified in the settings.py
for class_attribute_name, class_attribute_value in data_in_settings.items():
result[class_attribute_name] = data_in_settings[class_attribute_name]
# overwrite settings which have default values
# with the values specified in the settings.py
for class_attribute_name, class_attribute_value in default_data.items():
if class_attribute_name not in result:
result[class_attribute_name] = default_data[class_attribute_name]
return result
|
[
"massimobono1@gmail.com"
] |
massimobono1@gmail.com
|
85d08bd8390cacd47b28abaea8585359bc9b16a8
|
d0d3d2b68c7ae9c6b374bf9cc574bb9571076d5e
|
/models/model_selection.py
|
a895a9ddcf5a3cc5fddf1da42389f67e5b9bfd99
|
[] |
no_license
|
gustafholst/hitmusicnet
|
f5fda86fef9c3c4684b97d432d4f2403e05b6458
|
eb3c43845e5cedde0c19f907cbaf9d7d71530beb
|
refs/heads/master
| 2023-03-20T11:03:56.730327
| 2020-01-27T16:01:22
| 2020-01-27T16:01:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,272
|
py
|
def select_model(model_val=1):
model_args = {}
if model_val == 1:
model_args = {'model_name': 'model_1_A', 'model_dir': 'saved_models',
'model_subDir': 'feature_compressed',
'input_dim': 97, 'output_dim': 1, 'optimizer': 'adadelta',
'metrics': ["mean_absolute_error"], 'loss': "mse", 'earlyStop': True,
'weights': 'weights.h5', 'plot_loss': True,
'neurons': {'alpha': 1, 'beta': (1/2), 'gamma': (1/3)},
'n_layers': 4, 'weights_init': 'glorot_uniform', 'dropout': .25,
'epochs': 100, 'batch_size': 256, 'early_mon': 'val_mean_absolute_error',
'mode': 'min', 'checkout_mon': 'val_loss'}
elif model_val == 2:
model_args = {'model_name': 'model_1_B', 'model_dir': 'saved_models',
'model_subDir': 'feature_compressed',
'input_dim': 97, 'output_dim': 1, 'optimizer': 'adam',
'metrics': ["mean_absolute_error"], 'loss': "mse", 'earlyStop': True,
'weights': 'weights.h5', 'plot_loss': False,
'neurons': {'alpha': 1, 'beta': (1/2), 'gamma': (1/3)},
'n_layers': 4, 'weights_init': 'glorot_uniform', 'dropout': .25,
'epochs': 100, 'batch_size': 256, 'early_mon': 'val_mean_absolute_error',
'mode': 'min', 'checkout_mon': 'val_loss'}
elif model_val == 3:
model_args = {'model_name': 'model_1_C', 'model_dir': 'saved_models',
'model_subDir': 'feature_compressed',
'input_dim': 97, 'output_dim': 1, 'optimizer': 'adadelta',
'metrics': ["mean_absolute_error"], 'loss': "mse", 'earlyStop': True,
'weights': 'weights.h5', 'plot_loss': False,
'neurons': {'alpha': 1, 'beta': (1/2), 'gamma': (1/3)},
'n_layers': 4, 'weights_init': 'he_normal', 'dropout': .25,
'epochs': 100, 'batch_size': 256, 'early_mon': 'val_mean_absolute_error',
'mode': 'min', 'checkout_mon': 'val_loss'}
elif model_val == 4:
model_args = {'model_name': 'model_1_D', 'model_dir': 'saved_models',
'model_subDir': 'feature_compressed',
'input_dim': 97, 'output_dim': 1, 'optimizer': 'adam',
'metrics': ["mean_absolute_error"], 'loss': "mse", 'earlyStop': True,
'weights': 'weights.h5', 'plot_loss': False,
'neurons': {'alpha': 1, 'beta': (1/2), 'gamma': (1/3)},
'n_layers': 4, 'weights_init': 'he_normal', 'dropout': .25,
'epochs': 100, 'batch_size': 256, 'early_mon': 'val_mean_absolute_error',
'mode': 'min', 'checkout_mon': 'val_loss'}
# ------------------------------------------------------------------------------------------------------------------
elif model_val == 5:
model_args = {'model_name': 'model_1_A', 'model_dir': 'saved_models',
'model_subDir': 'class_feature_compressed',
'input_dim': 97, 'output_dim': 3, 'optimizer': 'adadelta',
'metrics': ["accuracy"], 'loss': "categorical_crossentropy", 'earlyStop': True,
'weights': 'weights.h5', 'plot_loss': True,
'neurons': {'alpha': 1, 'beta': (1/2), 'gamma': (1/3)},
'n_layers': 4, 'weights_init': 'glorot_uniform', 'dropout': .25,
'epochs': 100, 'batch_size': 256, 'early_mon': 'val_acc',
'mode': 'max', 'checkout_mon': 'val_acc'}
elif model_val == 6:
model_args = {'model_name': 'model_2_B', 'model_dir': 'saved_models',
'model_subDir': 'class_feature_compressed',
'input_dim': 97, 'output_dim': 3, 'optimizer': 'adam',
'metrics': ["accuracy"], 'loss': "categorical_crossentropy", 'earlyStop': True,
'weights': 'weights.h5', 'plot_loss': False,
'neurons': {'alpha': 1, 'beta': (1/2), 'gamma': (1/3)},
'n_layers': 4, 'weights_init': 'glorot_uniform', 'dropout': .25,
'epochs': 100, 'batch_size': 256, 'early_mon': 'val_acc',
'mode': 'max', 'checkout_mon': 'val_acc'}
elif model_val == 7:
model_args = {'model_name': 'model_3_C', 'model_dir': 'saved_models',
'model_subDir': 'class_feature_compressed',
'input_dim': 97, 'output_dim': 3, 'optimizer': 'adadelta',
'metrics': ["accuracy"], 'loss': "categorical_crossentropy", 'earlyStop': True,
'weights': 'weights.h5', 'plot_loss': False,
'neurons': {'alpha': 1, 'beta': (1 / 2), 'gamma': (1 / 3)},
'n_layers': 4, 'weights_init': 'he_normal', 'dropout': .25,
'epochs': 100, 'batch_size': 256, 'early_mon': 'val_acc',
'mode': 'max', 'checkout_mon': 'val_acc'}
return model_args
|
[
"="
] |
=
|
0fba8a6c3f9302d8cd7becf379dc74a91b648a1d
|
c00724308e01332418f539d9a1bedca09696a253
|
/setup.py
|
5dd977999e08b6a1a2de1dfef1be84c049522d99
|
[
"MIT"
] |
permissive
|
felipecolen/pycep-correios
|
f8b53efc939e48ef71caedcf1136d941d18d4d89
|
7c6c734c4bd3205bdca2f9b1bf4463045a96c8ef
|
refs/heads/master
| 2021-01-22T08:28:18.083461
| 2016-07-31T20:10:47
| 2016-07-31T20:10:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,091
|
py
|
# -*- coding: utf-8 -*-
# #############################################################################
# The MIT License (MIT)
#
# Copyright (c) 2016 Michell Stuttgart
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# #############################################################################
from setuptools import setup, find_packages
setup(
name='pycep-correios',
version='1.0.0',
keywords='correios setuptools development cep',
packages=find_packages(),
url='https://github.com/mstuttgart/pycep-correios',
license='MIT',
author='Michell Stuttgart',
author_email='michellstut@gmail.com',
description='Método para busca de dados de CEP no webservice dos '
'Correios',
install_requires=[
'requests',
],
test_suite='test',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.4',
],
)
|
[
"michellstut@gmail.com"
] |
michellstut@gmail.com
|
edb2a540151d4958fb9579f831a30f731284d00c
|
bde9a6e8a2aee89572dac4872b8263e42c13a142
|
/gestalt/estimator_wrappers/wrap_r_ranger.py
|
1a9202cf794666f79f719d6e7aa1ad2e5c8ce4f8
|
[
"MIT"
] |
permissive
|
chrinide/gestalt
|
b1ee66971007139b6e39b5c3dbd43a562bf5caee
|
f8f24d1fa879851ba989b244f71b348e995e221c
|
refs/heads/master
| 2021-01-20T08:07:18.877738
| 2017-05-01T06:08:26
| 2017-05-01T06:08:26
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,696
|
py
|
# import sklearn BaseEstimator etc to use
import pandas as pd
from rpy2 import robjects as ro
from rpy2.robjects import pandas2ri
from rpy2.robjects.packages import importr
from sklearn.base import BaseEstimator
from sklearn.base import ClassifierMixin
# Activate R objects.
pandas2ri.activate()
R = ro.r
# import the R packages required.
base = importr('base')
ranger = importr('ranger')
"""
An example of how to make an R plugin to use with Gestalt, this way we can run our favourite R packages using the
same stacking framework.
"""
class RangerClassifier(BaseEstimator, ClassifierMixin):
"""
From Ranger DESCRIPTION FILE:
A fast implementation of Random Forests, particularly suited for high dimensional data.
Ensembles of classification, regression, survival and probability prediction trees are supported.
We pull in all the options that ranger allows, but as this is a classifier we hard-code
probability=True, to give probability values.
"""
def __init__(self, formula='RANGER_TARGET_DUMMY~.', num_trees=500, num_threads=1, verbose=True, seed=42):
self.formula = formula
self.num_trees = num_trees
self.probability = True
self.num_threads = num_threads
self.verbose = verbose
self.seed = seed
self.num_classes = None
self.clf = None
def fit(self, X, y):
# First convert the X and y into a dataframe object to use in R
# We have to convert the y back to a dataframe to join for using with R
# We give the a meaningless name to allow the formula to work correctly.
y = pd.DataFrame(y, index=X.index, columns = ['RANGER_TARGET_DUMMY'])
self.num_classes = y.ix[:, 0].nunique()
r_dataframe = pd.concat([X, y], axis=1)
r_dataframe['RANGER_TARGET_DUMMY'] = r_dataframe['RANGER_TARGET_DUMMY'].astype('str')
self.clf = ranger.ranger(formula=self.formula,
data=r_dataframe,
num_trees=self.num_trees,
probability=self.probability,
num_threads=self.num_threads,
verbose=self.verbose,
seed=self.seed)
return
def predict_proba(self, X):
# Ranger doesnt have a specific separate predict and predict probabilities class, it is set in the params
# REM: R is not Python :)
pr = R.predict(self.clf, dat=X)
pandas_preds = ro.pandas2ri.ri2py_dataframe(pr.rx('predictions')[0])
if self.num_classes == 2:
pandas_preds = pandas_preds.ix[:, 1]
return pandas_preds.values
|
[
"you@example.com"
] |
you@example.com
|
4257890a7490b2def67115c1e7771a15801e77b2
|
ae652aec76faffce67e85922d73a7977df95b3b6
|
/util.py
|
e7527c2069a3f57700ad3025738fe7bf868ece28
|
[] |
no_license
|
wwq0327/note
|
e75964e0539a9efce0889b7774f78da0bcdff7fb
|
f893e851cb85b974bfbf5917a7fa5845b2f20eac
|
refs/heads/master
| 2020-05-18T07:57:33.446712
| 2011-11-13T13:40:07
| 2011-11-13T13:40:07
| 2,765,724
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 599
|
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
util
~~~~~~~~~~~~~~~~~~~~
:date: 2011-10-17
"""
def lines(file):
'''在文本的最后一行加入一个空行'''
for line in file: yield line
yield '\n'
def blocks(file):
'''收集遇到的所有行,直接遇到一个空行,然后返回已经收集到的行。
那些返回的行就是一个代码块
'''
block = []
for line in lines(file):
if line.strip():
block.append(line)
elif block:
yield ''.join(block).strip()
block = []
|
[
"wwq0327@gmail.com"
] |
wwq0327@gmail.com
|
425a35d7f2a14880501a7ed5d0ae0c3945f95335
|
1ca1799ce0abe12e37cf2893af2dd6fcf784317c
|
/env/bin/easy_install-3.6
|
134cb8672b89aa373c27aab0a51561c722a4558d
|
[] |
no_license
|
anubishere/projekt_eita15
|
93c542e8c10ada5bc469c8e5cdca48506405f872
|
d1bc9b3e11917d6aaf942a95bb2bbdd370e91c45
|
refs/heads/master
| 2021-02-16T05:36:26.032675
| 2020-03-04T18:10:56
| 2020-03-04T18:10:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 286
|
6
|
#!/home/victor/skola/kurser/digitala_system/projekt_eita15/env/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from setuptools.command.easy_install import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())
|
[
"victorkrook96@gmail.com"
] |
victorkrook96@gmail.com
|
4d8a89ad46d29396654cfe3031188c065de896cd
|
781b9a4a1098f3ac339f97eb1a622924bcc5914d
|
/Exercices/S1_04_AlgorithmesDichotomiques/TP05c.py
|
f1d7d9d939d0575e3055f1da3e04e0ed8b98dfbb
|
[] |
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
| 4,235
|
py
|
##### TP 5
##### Recherche dans une liste triée.
## I.1
## Q1
# g=0, d=8
# m=4, L[m]=11 et 5 < 11, on pose g=0, d=3
# m=2, L[m]=5. On a trouvé x0
# g=0, d=8
# m=4, L[m]=8 et 8<11, on pose g=5, d=8
# m=6, L[m]=13 et 11<13, on pose g=5, d=5
# m=5, L[m]=10 et 10<11, on pose g=6, d=5. On s'arrête.
## Q2
def dichotomie(x0,L):
Test=False
n=len(L)
g,d=0,n-1
while g<=d and not Test:
m=(g+d)//2
if L[m]==x0:
Test=True
elif L[m]>x0:
d=m-1
else:
g=m+1
return(Test)
## Q3
# Si x0 n_est pas présent, on exécute la boucle tant que g<=d. On sort avec g=d+1.
# A l_entrée du 1er tout de boucle, on a d-g+1=n. A chaque tour, la valeur d-g+1 diminue environ de moitié. Donc après k tours de boucles, la longueur de l_intervalle est de l_ordre de n/2**k.
# De plus, à chaque tour de boucle, il y a 2 comparaisons.
# Au dernier tour numéro k, on a g=d soit lorsque n/2**k = 1 d_ou k=log_2(n).
# On obtient donc un nombre de comparaisons équivalent à 2*ln(n)/ln(2): complexité logarithmique.
# Dans le cas séquentiel, on obtient une complexité linéaire, donc beaucoup moins intéressant.
## I.2
# L'idée est de s'arrêter lorsque d-g=1 avec L[g]\>0>L[d]
def recherche_dicho(L):
n=len(L)
g,d=0,n-1
while d-g>1:
m=(g+d)//2
if L[m]>=0:
g=m
else:
d=m
return(g,L[g])
## I.3
## 1
# Pour une valeur à epsilon près, on s_arrete lorsque 0<d-g<2*epsilon et on renvoie (g+d)/2
## 2
def recherche_zero(f,a,b,epsilon):
g,d=a,b
while d-g>2*epsilon:
m=(g+d)/2
if f(m)*f(g)<=0:
d=m
else:
g=m
return((g+d)/2)
## 3
def f(x):
return(x**2-2)
# print(recherche_zero(f,0,2,0.001)
## 4
# Avec epsilon = 1/2**p, il faut compter combien il y a de tours de boucles. En sortie du kieme tour de boucle, d-g vaut (b-a)/2**k. Il y a donc k tours de boucles avec (b-a)/2**k<=1/2**(p-1) soit k>=p-1+log_2(b-a) soit une complexité logarithmique encore.
##### II. Exponentiation rapide.
import numpy as np
import matplotlib.pyplot as plt
import time as t
import random as r
## 1.(a)
def exponaif(x,n):
p=1
for i in range(n):
p=p*x
return(p)
# Le nombre d'opérations effectuées est exactement n (1 produit à chaque tour)
## 1.(b)
def exporapide(x,n):
y=x
k=n
p=1
while k>0:
if k % 2==1:
p=p*y
y=y*y
k=k//2
return(p)
# A chaque tour de boucle, il y a au plus 1 comparaison et 2 ou 3 opérations. En sortie du ième tour, k vaut environ n/2**k. On sort de la fonction lorsque n/2**k vaut 1 soit k=ln(n)/ln(2).
# Le nombre d_opérations est donc compris entre 2*ln(n)/ln(2) et 3*ln(n)/ln(2): complexité logarithmique en O(ln(n)).
## 2
## 2;(a)
import time as t
def Pnaif(x,n):
S=0
for i in range(n):
S=S+i*exponaif(x,i)
return(S)
# n+n(n+1)/2 ~ n**2/2 opérations. Quadratique
## 2. (b)
def Prapide(x,n):
S=0
for i in range(n):
S=S+i*exporapide(x,i)
return(S)
# O(log(i)) pour chaque i*x**i. Il reste la somme des n termes.
# D'où n+somme des log(i)=O(n.ln(n)).
## 2. (c)
def Phorner(x,L):
"""L est la liste des coefficients"""
n=len(L)-1
S=0
for i in range(n+1):
S=S*x+L[n-i]
return(S)
# 2n opérations. Linéaire mais plus intéressante que ci-dessus.
## 3
# Liste des temps d'exécution pour le calcul de x**n pour n=0..50 :
N=[i for i in range(101)]
# Tracé des temps pour les calculs de P(x) avec n=0..100 avec P(x)=somme des iX**i, i=0..n
def Temps_calcul_P(x):
# Le polynôme est donné par une liste des coefficients.
Tn,Tr,Th=[],[],[]
for n in N:
L=[k for k in range(n+1)]
tps=t.perf_counter()
Pnaif(x,n)
Tn.append(t.perf_counter()-tps)
tps=t.perf_counter()
Sr=0
Prapide(x,n)
Tr.append(t.perf_counter()-tps)
tps=t.perf_counter()
Phorner(x,L)
Th.append(t.perf_counter()-tps)
plt.plot(N,Th,label='méthode horner')
plt.plot(N,Tr,label='méthode rapide')
plt.plot(N,Tn,label='méthode naïve')
plt.legend()
plt.show()
#####
|
[
"xpessoles.ptsi@free.fr"
] |
xpessoles.ptsi@free.fr
|
f73d54fdd4af870903d5e22391dbe348021ff86f
|
ffc1ab091d54635c96cd4ed6098c4bf388222f02
|
/nipype/nipype-master/nipype/interfaces/afni/tests/test_auto_Qwarp.py
|
2848fe97f8622750e68d5cf9d3e43276808c0a92
|
[
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
bharathlakshman/brainintensive
|
fc7833078bb6ad9574e015004f2b3905c85b699e
|
eec8a91cbec29ba27d620984394d3ee21d0db58f
|
refs/heads/master
| 2021-01-01T19:04:25.724906
| 2017-07-28T01:48:28
| 2017-07-28T01:48:28
| 98,499,935
| 1
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,792
|
py
|
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..preprocess import Qwarp
def test_Qwarp_inputs():
input_map = dict(Qfinal=dict(argstr='-Qfinal',
),
Qonly=dict(argstr='-Qonly',
),
allsave=dict(argstr='-allsave',
xor=['nopadWARP', 'duplo', 'plusminus'],
),
args=dict(argstr='%s',
),
ballopt=dict(argstr='-ballopt',
xor=['workhard', 'boxopt'],
),
base_file=dict(argstr='-base %s',
copyfile=False,
mandatory=True,
),
baxopt=dict(argstr='-boxopt',
xor=['workhard', 'ballopt'],
),
blur=dict(argstr='-blur %s',
),
duplo=dict(argstr='-duplo',
xor=['gridlist', 'maxlev', 'inilev', 'iniwarp', 'plusminus', 'allsave'],
),
emask=dict(argstr='-emask %s',
copyfile=False,
),
environ=dict(nohash=True,
usedefault=True,
),
expad=dict(argstr='-expad %d',
xor=['nopadWARP'],
),
gridlist=dict(argstr='-gridlist %s',
copyfile=False,
xor=['duplo', 'plusminus'],
),
hel=dict(argstr='-hel',
xor=['nmi', 'mi', 'lpc', 'lpa', 'pear'],
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
in_file=dict(argstr='-source %s',
copyfile=False,
mandatory=True,
),
inilev=dict(argstr='-inlev %d',
xor=['duplo'],
),
iniwarp=dict(argstr='-iniwarp %s',
xor=['duplo'],
),
iwarp=dict(argstr='-iwarp',
xor=['plusminus'],
),
lpa=dict(argstr='-lpa',
xor=['nmi', 'mi', 'lpc', 'hel', 'pear'],
),
lpc=dict(argstr='-lpc',
position=-2,
xor=['nmi', 'mi', 'hel', 'lpa', 'pear'],
),
maxlev=dict(argstr='-maxlev %d',
position=-1,
xor=['duplo'],
),
mi=dict(argstr='-mi',
xor=['mi', 'hel', 'lpc', 'lpa', 'pear'],
),
minpatch=dict(argstr='-minpatch %d',
),
nmi=dict(argstr='-nmi',
xor=['nmi', 'hel', 'lpc', 'lpa', 'pear'],
),
noXdis=dict(argstr='-noXdis',
),
noYdis=dict(argstr='-noYdis',
),
noZdis=dict(argstr='-noZdis',
),
noneg=dict(argstr='-noneg',
),
nopad=dict(argstr='-nopad',
),
nopadWARP=dict(argstr='-nopadWARP',
xor=['allsave', 'expad'],
),
nopenalty=dict(argstr='-nopenalty',
),
nowarp=dict(argstr='-nowarp',
),
noweight=dict(argstr='-noweight',
),
out_file=dict(argstr='-prefix %s',
genfile=True,
name_source=['in_file'],
name_template='%s_QW',
),
out_weight_file=dict(argstr='-wtprefix %s',
),
outputtype=dict(),
overwrite=dict(argstr='-overwrite',
),
pblur=dict(argstr='-pblur %s',
),
pear=dict(argstr='-pear',
),
penfac=dict(argstr='-penfac %f',
),
plusminus=dict(argstr='-plusminus',
xor=['duplo', 'allsave', 'iwarp'],
),
quiet=dict(argstr='-quiet',
xor=['verb'],
),
resample=dict(argstr='-resample',
),
terminal_output=dict(nohash=True,
),
verb=dict(argstr='-verb',
xor=['quiet'],
),
wball=dict(argstr='-wball %s',
),
weight=dict(argstr='-weight %s',
),
wmask=dict(argstr='-wpass %s %f',
),
workhard=dict(argstr='-workhard',
xor=['boxopt', 'ballopt'],
),
)
inputs = Qwarp.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(inputs.traits()[key], metakey) == value
def test_Qwarp_outputs():
output_map = dict(base_warp=dict(),
source_warp=dict(),
warped_base=dict(),
warped_source=dict(),
weights=dict(),
)
outputs = Qwarp.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(outputs.traits()[key], metakey) == value
|
[
"ibharathlakshman@gmail.com"
] |
ibharathlakshman@gmail.com
|
6ef29292a7e42861fa5c76bb43f7c074044b2706
|
2850d9adba96bc4e73185de5d6adebf363a5c534
|
/tce/tcloud/clb/InquiryLBPrice.py
|
8d39cc90ea056cc0f7f42b894868a5e5193ddabb
|
[
"Apache-2.0"
] |
permissive
|
FatAnker/tencentcloud-sdk-python
|
d8f757b12ad336e78a06b68a789ecc3c86d1d331
|
d6f75a41dc7053cb51f9091f4d41b8cb7a837559
|
refs/heads/master
| 2020-04-30T22:34:16.740484
| 2019-04-28T11:14:11
| 2019-04-28T11:14:11
| 177,122,691
| 0
| 1
| null | 2019-03-22T10:46:01
| 2019-03-22T10:46:01
| null |
UTF-8
|
Python
| false
| false
| 1,376
|
py
|
# -*- coding: utf8 -*-
from QcloudApi.qcloudapi import QcloudApi
from tce.tcloud.utils.config import global_config
# 设置需要加载的模块
module = 'lb'
# 对应接口的接口名,请参考wiki文档上对应接口的接口名
action = 'InquiryLBPrice'
region = global_config.get('regions')
params = global_config.get(region)
secretId = params['secretId']
secretKey = params['secretKey']
domain =params['domain']
# 云API的公共参数
config = {
'Region': region,
'secretId': secretId,
'secretKey': secretKey,
'method': 'GET',
'SignatureMethod': 'HmacSHA1'
}
# 接口参数,根据实际情况填写,支持json
# 例如数组可以 "ArrayExample": ["1","2","3"]
# 例如字典可以 "DictExample": {"key1": "value1", "key2": "values2"}
action_params = {
'loadBalancerType':2
}
try:
service = QcloudApi(module, config)
# 请求前可以通过下面几个方法重新设置请求的secretId/secretKey/Region/method/SignatureMethod参数
# 重新设置请求的Region
# service.setRegion('shanghai')
# 打印生成的请求URL,不发起请求
print(service.generateUrl(action, action_params))
# 调用接口,发起请求,并打印返回结果
print(service.call(action, action_params))
except Exception as e:
import traceback
print('traceback.format_exc():\n%s' % traceback.format_exc())
|
[
"1113452717@qq.com"
] |
1113452717@qq.com
|
becdb112bb47e331e0ba9f6b5eb175b7e8f43035
|
3c6b36eb1f4f9760c52903f6d0ec4a501f948c90
|
/osp/test/citations/utils/test_get_text.py
|
663abb8fd5fc80e075106a2ff9727effea40b0c3
|
[
"Apache-2.0"
] |
permissive
|
davidmcclure/open-syllabus-project
|
38444249af845013e3f281a7a713dca83159c56e
|
078cfd4c5a257fbfb0901d43bfbc6350824eed4e
|
refs/heads/master
| 2021-06-30T21:47:07.636558
| 2021-06-27T15:15:35
| 2021-06-27T15:15:35
| 50,152,020
| 220
| 14
|
Apache-2.0
| 2021-06-27T15:11:15
| 2016-01-22T02:29:57
|
Python
|
UTF-8
|
Python
| false
| false
| 501
|
py
|
import pytest
from osp.citations.utils import get_text
from bs4 import BeautifulSoup
@pytest.mark.parametrize('tag,text', [
('<tag>Article Title</tag>', 'Article Title'),
# Strip whitespace.
('<tag> Article Title </tag>', 'Article Title'),
# Empty text -> None.
('<tag></tag>', None),
('<tag> </tag>', None),
# Missing tag -> None.
('', None),
])
def test_get_text(tag, text):
tree = BeautifulSoup(tag, 'lxml')
assert get_text(tree, 'tag') == text
|
[
"davidwilliammcclure@gmail.com"
] |
davidwilliammcclure@gmail.com
|
32273e37f6ed947cad8183262e2fbe2b5511c0bf
|
e42c337b179ea9e85c41c992d1440dbdd10e4bdb
|
/solution/leetcode/120.py
|
18bddd5d74b8a75dc62e353f0e5eb862930701c7
|
[] |
no_license
|
harshraj22/problem_solving
|
7733a43e2dcbf507257e61732430d5c0fc1b4cb9
|
2c7d1ed486ae59126244168a446d74ae4fdadbc6
|
refs/heads/master
| 2023-05-26T12:58:40.098378
| 2023-05-12T17:53:11
| 2023-05-12T17:53:11
| 193,202,408
| 20
| 5
| null | 2022-08-03T16:40:45
| 2019-06-22T06:58:09
|
C++
|
UTF-8
|
Python
| false
| false
| 501
|
py
|
# https://leetcode.com/problems/triangle/
class Solution:
from math import inf
def minimumTotal(self, triangle: List[List[int]]) -> int:
# create a copy
dp = [[inf for _ in row] for row in triangle]
dp[0][0] = triangle[0][0]
for i, row in enumerate(dp[:-1]):
for j, cell in enumerate(row):
try:
dp[i+1][j] = max(dp[i+1][j], dp[i][j] + triangle[i+1][j])
dp[i+1][j+1] = max(dp[i+1][j+1], dp[i][j] + triangle[i+1][j+1])
except IndexError:
pass
return min(dp[-1])
|
[
"harshraj22aug@gmail.com"
] |
harshraj22aug@gmail.com
|
495ce2f9cfe10accb714b8a7ae55e59dcd8e762c
|
eec105101d7a82d0551503100a3bd9a1a2af3b3c
|
/Assignments/a5_public/code/char_decoder.py
|
180d88968e8b831c9cb4d68b2702a7a64917d69a
|
[] |
no_license
|
ethanenguyen/Stanford-CS224n-NLP
|
807c36cf67f8aade5b1ca7bfd5878ac354e96bbb
|
181c659dbb0e0a1a1c3865a336fd74c8ebc5633e
|
refs/heads/master
| 2022-03-28T04:16:01.236240
| 2020-01-14T13:52:21
| 2020-01-14T13:52:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,318
|
py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CS224N 2018-19: Homework 5
"""
import torch
import torch.nn as nn
class CharDecoder(nn.Module):
def __init__(self, hidden_size, char_embedding_size=50, target_vocab=None):
""" Init Character Decoder.
@param hidden_size (int): Hidden size of the decoder LSTM
@param char_embedding_size (int): dimensionality of character embeddings
@param target_vocab (VocabEntry): vocabulary for the target language. See vocab.py for documentation.
"""
### YOUR CODE HERE for part 2a
### TODO - Initialize as an nn.Module.
### - Initialize the following variables:
### self.charDecoder: LSTM. Please use nn.LSTM() to construct this.
### self.char_output_projection: Linear layer, called W_{dec} and b_{dec} in the PDF
### self.decoderCharEmb: Embedding matrix of character embeddings
### self.target_vocab: vocabulary for the target language
###
### Hint: - Use target_vocab.char2id to access the character vocabulary for the target language.
### - Set the padding_idx argument of the embedding matrix.
### - Create a new Embedding layer. Do not reuse embeddings created in Part 1 of this assignment.
super(CharDecoder, self).__init__() # Initialize as an nn.Module
self.charDecoder = nn.LSTM(char_embedding_size, hidden_size)
self.char_output_projection = nn.Linear(hidden_size, len(target_vocab.char2id), bias=True)
self.decoderCharEmb = nn.Embedding(len(target_vocab.char2id), char_embedding_size, padding_idx=target_vocab.char2id['<pad>'])
self.target_vocab = target_vocab
self.loss = nn.CrossEntropyLoss(
reduction='sum', # computed as the *sum* of cross-entropy losses of all the words in the batch
ignore_index=self.target_vocab.char2id['<pad>'] # # not take into account pad character when compute loss
)
### END YOUR CODE
# When our word-level decoder produces an <unk> token, we run our character-level decoder (a character-level conditional language model)
def forward(self, x, dec_hidden=None):
""" Forward pass of character decoder.
@param x: tensor of integers, shape (length, batch)
@param dec_hidden: internal state of the LSTM before reading the input characters. A tuple of two tensors of shape (1, batch, hidden_size)
@returns scores: called s_t in the PDF, shape (length, batch, self.vocab_size)
@returns dec_hidden: internal state of the LSTM after reading the input characters. A tuple of two tensors of shape (1, batch, hidden_size)
"""
### YOUR CODE HERE for part 2b
### TODO - Implement the forward pass of the character decoder.
x_emb = self.decoderCharEmb(x)
hidden, dec_hidden = self.charDecoder(x_emb, dec_hidden)
scores = self.char_output_projection(hidden) # i.e. s_t, logits
### END YOUR CODE
return scores, dec_hidden
# When we train the NMT system, we train the character decoder on every word in the target sentence
# (not just the words reparesented by <unk>)
def train_forward(self, char_sequence, dec_hidden=None):
""" Forward computation during training.
@param char_sequence: tensor of integers, shape (length, batch). Note that "length" here and in forward() need not be the same.
@param dec_hidden: initial internal state of the LSTM, obtained from the output of the word-level decoder. A tuple of two tensors of shape (1, batch, hidden_size)
@returns The cross-entropy loss, computed as the *sum* of cross-entropy losses of all the words in the batch.
"""
### YOUR CODE HERE for part 2c
### TODO - Implement training forward pass.
###
### Hint: - Make sure padding characters do not contribute to the cross-entropy loss.
### - char_sequence corresponds to the sequence x_1 ... x_{n+1} from the handout (e.g., <START>,m,u,s,i,c,<END>).
x = char_sequence[:-1] # exclude the <END> token
scores, dec_hidden = self.forward(x, dec_hidden)
targets = char_sequence[1:] # exclude the <START> token
targets = targets.reshape(-1) # squeeze into 1D (embed_size * batch_size)
scores = scores.reshape(-1, scores.shape[-1]) # (embed_size * batch_size, V_char)
ce_loss = self.loss(scores, targets)
### END YOUR CODE
return ce_loss
def decode_greedy(self, initialStates, device, max_length=21):
""" Greedy decoding
@param initialStates: initial internal state of the LSTM, a tuple of two tensors of size (1, batch, hidden_size)
@param device: torch.device (indicates whether the model is on CPU or GPU)
@param max_length: maximum length of words to decode
@returns decodedWords: a list (of length batch) of strings, each of which has length <= max_length.
The decoded strings should NOT contain the start-of-word and end-of-word characters.
"""
### YOUR CODE HERE for part 2d
### TODO - Implement greedy decoding.
### Hints:
### - Use target_vocab.char2id and target_vocab.id2char to convert between integers and characters
### - Use torch.tensor(..., device=device) to turn a list of character indices into a tensor.
### - We use curly brackets as start-of-word and end-of-word characters. That is, use the character '{' for <START> and '}' for <END>.
### Their indices are self.target_vocab.start_of_word and self.target_vocab.end_of_word, respectively.
# initial constant
batch_size = initialStates[0].shape[1]
start_index = self.target_vocab.start_of_word
end_index = self.target_vocab.end_of_word
# initial state
dec_hidden = initialStates
# char for each entry in a batch (1, batch_size) <- unsqueeze for the LSTM dim
current_chars = torch.tensor([start_index] * batch_size, device=device).unsqueeze(0)
decodeTuple = [['', False] for _ in range(batch_size)] # output words for each entry (output string, if this entry has already reached the end)
for t in range(max_length):
scores, dec_hidden = self.forward(current_chars, dec_hidden)
prob = torch.softmax(scores, dim=2)
current_chars = torch.argmax(scores, dim=2) # greedy pick a word with highest score
char_indices = current_chars.detach().squeeze(0) # returns a new Tensor, detached from the current graph
for i, char_index in enumerate(char_indices):
if not decodeTuple[i][1]: # this entry in a batch has not reached the end
if char_index == end_index:
# reach the end
decodeTuple[i][1] = True
else:
# concate the predict word at the bottom
decodeTuple[i][0] += self.target_vocab.id2char[char_index.item()]
decodedWords = [item[0] for item in decodeTuple]
### END YOUR CODE
return decodedWords
|
[
"daviddwlee84@gmail.com"
] |
daviddwlee84@gmail.com
|
bb5554675b64f4e7bfbfe07ba6ff2472ec4f1c0e
|
ac0c96ad280ac43de9c06ba21a1cbe2b1679b2f9
|
/minidump/streams/HandleOperationListStream.py
|
3e3e7422e7caf3d7beec41f6aea2c8b0d753690a
|
[
"MIT"
] |
permissive
|
mkorman90/minidump
|
5cfc9e7119f68e91e77e0039b7c364d46b769e39
|
749e6da56d0ea414450c287caa4ecfb292197b59
|
refs/heads/master
| 2020-05-09T23:39:29.089331
| 2018-06-17T14:51:30
| 2018-06-17T14:51:30
| 181,508,823
| 3
| 0
|
MIT
| 2019-04-15T14:53:20
| 2019-04-15T14:53:20
| null |
UTF-8
|
Python
| false
| false
| 668
|
py
|
#!/usr/bin/env python3
#
# Author:
# Tamas Jos (@skelsec)
#
class MINIDUMP_HANDLE_OPERATION_LIST:
def __init__(self):
self.SizeOfHeader = None
self.SizeOfEntry = None
self.NumberOfEntries = None
self.Reserved = None
def parse(dir, buff):
mhds = MINIDUMP_HANDLE_OPERATION_LIST()
mhds.SizeOfHeader = int.from_bytes(buff.read(4), byteorder = 'little', signed = False)
mhds.SizeOfEntry = int.from_bytes(buff.read(4), byteorder = 'little', signed = False)
mhds.NumberOfEntries = int.from_bytes(buff.read(4), byteorder = 'little', signed = False)
mhds.Reserved = int.from_bytes(buff.read(4), byteorder = 'little', signed = False)
return mhds
|
[
"info@skelsec.com"
] |
info@skelsec.com
|
c3418c0bc14439f3a396442041af6a15d8b775f9
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p03096/s362138423.py
|
0610f35f78b278535f070e6f3b9519ef3b0d4fe8
|
[] |
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
| 754
|
py
|
MOD = 10**9+7
N = int(input())
C = []
C.append(int(input()))
for i in range(N-1):
c = int(input())
if c == C[-1]:
continue
C.append(c)
#print(C)
N = len(C)
lis = [[0] for i in range(max(C)+1)]
for i in range(N):
lis[C[i]].append(i+1)
for i in range(len(lis)):
lis[i].append(MOD)
def binary_search(lis,i):
ok = 0
ng = len(lis)-1
while ng-ok > 1:
mid = (ok + ng)// 2
if lis[mid] < i:
ok = mid
else:
ng = mid
return lis[ok]
#print(binary_search([0,1,2,3,4],3))
#print(lis)
dp = [0] * (N+1)
dp[0] = 1
for i in range(1,N+1):
dp[i] += dp[i-1]
p = binary_search(lis[C[i-1]],i)
if p != 0:
dp[i] += dp[p]
dp[i] %= MOD
#print(p)
print(dp[-1])
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
88cc90c811bf40584e981843c0665460c3140aad
|
3ae288daabf10b5f3dd5f09bb7bb974a6caacdaf
|
/processimage/cropimage/urls.py
|
24083c8f8536913662bc82f1876b785f6dd67890
|
[
"MIT"
] |
permissive
|
singh1114/image-processor
|
62ab01f9b87b6deda5debb010feeb4c74135c39b
|
a2b6e8fcb64b1449859a06775b2d7b3a0205e952
|
refs/heads/master
| 2022-12-13T21:44:56.316988
| 2019-02-04T06:13:05
| 2019-02-04T06:13:05
| 167,675,243
| 0
| 0
|
MIT
| 2022-12-08T01:35:03
| 2019-01-26T10:12:44
|
Python
|
UTF-8
|
Python
| false
| false
| 483
|
py
|
from django.urls import path
from cropimage.views import (
ImageUploadView,
ShowMainImagesView,
ShowCroppedImagesView
)
app_name = 'cropimage'
urlpatterns = [
path('upload_image/', ImageUploadView.as_admin_view(), name='upload'),
path('show_main_images/',
ShowMainImagesView.as_admin_view(), name='show_main_image'),
path('show_cropped_images/<uuid:main_image_uuid>',
ShowCroppedImagesView.as_admin_view(), name='show_cropped_images'),
]
|
[
"ranvir.singh1114@gmail.com"
] |
ranvir.singh1114@gmail.com
|
13eb9d5df7bd1b66c602bda0c55492a22a3cfd1b
|
0f946e4bbad3a44339e75893fbd185ae1fb25f67
|
/lesson13/utils.py
|
1444b0df757759af65c486ab2bbd1f438df459bd
|
[] |
no_license
|
kirigaikabuto/distancelesson2
|
e53dda7d8a07ea5c4ec2e7a39a47619b533a5df8
|
24cf61d34334fa2d6a736a81d4bc75170db2a2ad
|
refs/heads/master
| 2022-07-03T07:16:47.588461
| 2020-05-13T13:50:54
| 2020-05-13T13:50:54
| 254,647,334
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 355
|
py
|
def create_student(line):
parts=line.split(",")
name = parts[0]
age = int(parts[1])
marks_str = parts[2]
marks_str_arr = marks_str.split(" ")
marks_int_arr = [int(i) for i in marks_str_arr]
d={}
d['name']=name
d['age']=age
d['marks']=marks_int_arr
return d
def print_arr(arr):
for i in arr:
print(i)
|
[
"ytleugazy@dar.kz"
] |
ytleugazy@dar.kz
|
5474853aa0063918f02b655556ab3268ea02e12a
|
edb699b1a63c3412e5a8788e32b26690c707ce2e
|
/rdconf.py
|
1c57f37d1fefcab9072488d13dec9db4abe06cb2
|
[
"MIT"
] |
permissive
|
dkoes/rdkit-scripts
|
518fe55058524ddd3a4f5ad4f0dd3d125a73f01a
|
71cf2ccc4b26eb1541cc63690f40aa24b195fe8d
|
refs/heads/master
| 2022-07-14T19:04:18.760183
| 2022-07-01T12:39:32
| 2022-07-01T12:39:32
| 72,130,300
| 48
| 32
|
MIT
| 2019-04-15T18:46:27
| 2016-10-27T17:09:14
|
Python
|
UTF-8
|
Python
| false
| false
| 6,117
|
py
|
#!/usr/bin/python3
import sys,string,argparse
from rdkit.Chem import AllChem as Chem
from optparse import OptionParser
import os, gzip
'''Given a smiles file, generate 3D conformers in output sdf.
Energy minimizes and filters conformers to meet energy window and rms constraints.
Some time ago I compared this to alternative conformer generators and
it was quite competitive (especially after RDKit's UFF implementation
added OOP terms).
'''
#convert smiles to sdf
def getRMS(mol, c1,c2):
rms = Chem.GetBestRMS(mol,mol,c1,c2)
return rms
parser = OptionParser(usage="Usage: %prog [options] <input>.smi <output>.sdf")
parser.add_option("--maxconfs", dest="maxconfs",action="store",
help="maximum number of conformers to generate per a molecule (default 20)", default="20", type="int", metavar="CNT")
parser.add_option("--sample_multiplier", dest="sample",action="store",
help="sample N*maxconfs conformers and choose the maxconformers with lowest energy (default 1)", default="1", type="float", metavar="N")
parser.add_option("--seed", dest="seed",action="store",
help="random seed (default 9162006)", default="9162006", type="int", metavar="s")
parser.add_option("--rms_threshold", dest="rms",action="store",
help="filter based on rms (default 0.7)", default="0.7", type="float", metavar="R")
parser.add_option("--energy_window", dest="energy",action="store",
help="filter based on energy difference with lowest energy conformer", default="10", type="float", metavar="E")
parser.add_option("-v","--verbose", dest="verbose",action="store_true",default=False,
help="verbose output")
parser.add_option("--mmff", dest="mmff",action="store_true",default=False,
help="use MMFF forcefield instead of UFF")
parser.add_option("--nomin", dest="nomin",action="store_true",default=False,
help="don't perform energy minimization (bad idea)")
parser.add_option("--etkdg", dest="etkdg",action="store_true",default=False,
help="use new ETKDG knowledge-based method instead of distance geometry")
(options, args) = parser.parse_args()
if(len(args) < 2):
parser.error("Need input and output")
sys.exit(-1)
input = args[0]
output = args[1]
smifile = open(input)
if options.verbose:
print("Generating a maximum of",options.maxconfs,"per a mol")
if options.etkdg and not Chem.ETKDG:
print("ETKDB does not appear to be implemented. Please upgrade RDKit.")
sys.exit(1)
split = os.path.splitext(output)
if split[1] == '.gz':
outf=gzip.open(output,'wt+')
output = split[0] #strip .gz
else:
outf = open(output,'w+')
if os.path.splitext(output)[1] == '.pdb':
sdwriter = Chem.PDBWriter(outf)
else:
sdwriter = Chem.SDWriter(outf)
if sdwriter is None:
print("Could not open ".output)
sys.exit(-1)
for line in smifile:
toks = line.split()
smi = toks[0]
name = ' '.join(toks[1:])
pieces = smi.split('.')
if len(pieces) > 1:
smi = max(pieces, key=len) #take largest component by length
print("Taking largest component: %s\t%s" % (smi,name))
mol = Chem.MolFromSmiles(smi)
if mol is not None:
if options.verbose:
print(smi)
try:
Chem.SanitizeMol(mol)
mol = Chem.AddHs(mol)
mol.SetProp("_Name",name);
if options.etkdg:
cids = Chem.EmbedMultipleConfs(mol, int(options.sample*options.maxconfs), Chem.ETKDG())
else:
cids = Chem.EmbedMultipleConfs(mol, int(options.sample*options.maxconfs),randomSeed=options.seed)
if options.verbose:
print(len(cids),"conformers found")
cenergy = []
for conf in cids:
#not passing confID only minimizes the first conformer
if options.nomin:
cenergy.append(conf)
elif options.mmff:
converged = Chem.MMFFOptimizeMolecule(mol,confId=conf)
mp = Chem.MMFFGetMoleculeProperties(mol)
cenergy.append(Chem.MMFFGetMoleculeForceField(mol,mp,confId=conf).CalcEnergy())
else:
converged = not Chem.UFFOptimizeMolecule(mol,confId=conf)
cenergy.append(Chem.UFFGetMoleculeForceField(mol,confId=conf).CalcEnergy())
if options.verbose:
print("Convergence of conformer",conf,converged,cenergy[-1])
mol = Chem.RemoveHs(mol)
sortedcids = sorted(cids,key = lambda cid: cenergy[cid])
if len(sortedcids) > 0:
mine = cenergy[sortedcids[0]]
else:
mine = 0
if(options.rms == 0):
cnt = 0;
for conf in sortedcids:
if(cnt >= options.maxconfs):
break
if(options.energy < 0) or cenergy[conf]-mine <= options.energy:
sdwriter.write(mol,conf)
cnt+=1
else:
written = {}
for conf in sortedcids:
if len(written) >= options.maxconfs:
break
#check rmsd
passed = True
for seenconf in written.keys():
rms = getRMS(mol,seenconf,conf)
if(rms < options.rms) or (options.energy > 0 and cenergy[conf]-mine > options.energy):
passed = False
break
if(passed):
written[conf] = True
sdwriter.write(mol,conf)
except (KeyboardInterrupt, SystemExit):
raise
except Exception as e:
print("Exception",e)
else:
print("ERROR:",smi)
sdwriter.close()
outf.close()
|
[
"dkoes@pitt.edu"
] |
dkoes@pitt.edu
|
db508cd4bcd3fa891bbd1f0067a4bb8269d2f093
|
3378bf2ebcd3cd794b26b74f033932cb0c6a6590
|
/tuframework/network_architecture/cotr/DeTrans/ops/functions/ms_deform_attn_func.py
|
ce8862f5fc39e40bd00747c8d9c65fcffb6118b3
|
[
"Apache-2.0"
] |
permissive
|
Magnety/tuFramework
|
d3d81f0663edbffbdd9b45138cbca82ffb78f03e
|
b31cb34d476ef306b52da955021f93c91c14ddf4
|
refs/heads/master
| 2023-05-01T04:36:04.873112
| 2021-05-18T01:07:54
| 2021-05-18T01:07:54
| 361,652,585
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,271
|
py
|
import torch
import torch.nn.functional as F
from torch.autograd import Function
from torch.autograd.function import once_differentiable
def ms_deform_attn_core_pytorch_3D(value, value_spatial_shapes, sampling_locations, attention_weights):
N_, S_, M_, D_ = value.shape
_, Lq_, M_, L_, P_, _ = sampling_locations.shape
value_list = value.split([T_ * H_ * W_ for T_, H_, W_ in value_spatial_shapes], dim=1)
sampling_grids = 2 * sampling_locations - 1
# sampling_grids = 3 * sampling_locations - 1
sampling_value_list = []
for lid_, (T_, H_, W_) in enumerate(value_spatial_shapes):
value_l_ = value_list[lid_].flatten(2).transpose(1, 2).reshape(N_*M_, D_, T_, H_, W_)
sampling_grid_l_ = sampling_grids[:, :, :, lid_].transpose(1, 2).flatten(0, 1)[:,None,:,:,:]
sampling_value_l_ = F.grid_sample(value_l_, sampling_grid_l_.to(dtype=value_l_.dtype), mode='bilinear', padding_mode='zeros', align_corners=False)[:,:,0]
sampling_value_list.append(sampling_value_l_)
attention_weights = attention_weights.transpose(1, 2).reshape(N_*M_, 1, Lq_, L_*P_)
output = (torch.stack(sampling_value_list, dim=-2).flatten(-2) * attention_weights).sum(-1).view(N_, M_*D_, Lq_)
return output.transpose(1, 2).contiguous()
|
[
"liuyiyao0916@163.com"
] |
liuyiyao0916@163.com
|
ef258bb106bc53bf5ed4c1a06b980d66154f5206
|
09e57dd1374713f06b70d7b37a580130d9bbab0d
|
/data/cirq_new/cirq_program/startCirq_Class783.py
|
22d75780c4d05107a506bcec34d8229140243599
|
[
"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
| 2,189
|
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=4
# total number=20
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
#thatsNoCode
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.H.on(input_qubit[1])) # number=2
c.append(cirq.H.on(input_qubit[1])) # number=7
c.append(cirq.H.on(input_qubit[2])) # number=3
c.append(cirq.H.on(input_qubit[3])) # number=4
c.append(cirq.H.on(input_qubit[0])) # number=17
c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=18
c.append(cirq.H.on(input_qubit[0])) # number=19
c.append(cirq.H.on(input_qubit[0])) # number=14
c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=15
c.append(cirq.H.on(input_qubit[0])) # number=16
c.append(cirq.Z.on(input_qubit[1])) # number=13
c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=8
c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=9
c.append(cirq.SWAP.on(input_qubit[3],input_qubit[0])) # number=10
c.append(cirq.SWAP.on(input_qubit[3],input_qubit[0])) # number=11
c.append(cirq.Z.on(input_qubit[2])) # number=12
# circuit end
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 =2820
info = cirq.final_state_vector(circuit)
qubits = round(log2(len(info)))
frequencies = {
np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)
for i in range(2 ** qubits)
}
writefile = open("../data/startCirq_Class783.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
|
df0e78b60bfc72c412b3fa914ea00ef5c830d3b3
|
234df74b8d2ff67e1ec1e44df6128e9506ad8ab1
|
/sgim/apps/catalogo/views.py
|
f2afa8b7e3b90431b4c76df2159ca9f2a62b26f6
|
[] |
no_license
|
edxavier/tesis2015
|
c1289bc648c054edde082e200beda1cfb6e9e27f
|
d04b20b67f9f1ef2e6d97a18b7bfa6466223384f
|
refs/heads/master
| 2021-01-23T03:33:27.149595
| 2016-02-17T21:51:37
| 2016-02-17T21:51:37
| 33,018,981
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,473
|
py
|
from django.shortcuts import render
from django.views.generic import View
from django.http import JsonResponse
from rest_framework import viewsets
from .serializers import (TipoDispSerializer, EdificioSerializer, OficinaSerializer,
EstadoOpeSerializer, SistemaSerializer,
TipoComponenteSerializer, PersonalSerializer,
CargoSerializer, EstadoManttoSerializer,
TipoIncidenteSerializer)
from .models import (TipoDispositivo, Edificio, Oficina,
EstadoOperacional, Sistema, TipoComponente,
Personal, Cargo, TipoIncidente, EstadoMantenimiento)
# Create your views here.
class TipoDispoViewSet(viewsets.ModelViewSet):
queryset = TipoDispositivo.objects.filter(activo=True)
serializer_class = TipoDispSerializer
class EdificioViewSet(viewsets.ModelViewSet):
queryset = Edificio.objects.filter(activo=True)
serializer_class = EdificioSerializer
class OficinaViewSet(viewsets.ModelViewSet):
queryset = Oficina.objects.filter(activo=True)
serializer_class = OficinaSerializer
filter_fields = ('edificio',)
class EstadoOpeViewSet(viewsets.ModelViewSet):
queryset = EstadoOperacional.objects.filter(activo=True)
serializer_class = EstadoOpeSerializer
class SistemaViewSet(viewsets.ModelViewSet):
queryset = Sistema.objects.filter(activo=True)
serializer_class = SistemaSerializer
class TipoComponenteViewSet(viewsets.ModelViewSet):
queryset = TipoComponente.objects.filter(activo=True)
serializer_class = TipoComponenteSerializer
class PersonalViewSet(viewsets.ModelViewSet):
queryset = Personal.objects.filter(activo=True)
serializer_class = PersonalSerializer
filter_fields = ('cargo',)
class CargoViewSet(viewsets.ModelViewSet):
queryset = Cargo.objects.filter(activo=True)
serializer_class = CargoSerializer
class TipoIncidenteViewSet(viewsets.ModelViewSet):
queryset = TipoIncidente.objects.filter(activo=True)
serializer_class = TipoIncidenteSerializer
class EstadoManttoViewSet(viewsets.ModelViewSet):
queryset = EstadoMantenimiento.objects.filter(activo=True)
serializer_class = EstadoManttoSerializer
class Listar(View):
def get(self, request, *args, **kwargs):
data = TipoDispSerializer(TipoDispositivo.objects.all(), many=True)
return JsonResponse({'items':data.data, 'status': "success"})
|
[
"edxavier05@gmail.com"
] |
edxavier05@gmail.com
|
8d59c63bb569d0b06ceed76e1ba3e92ddfc89ae5
|
612325535126eaddebc230d8c27af095c8e5cc2f
|
/src/build/android/pylib/utils/device_dependencies_test.py
|
40a9c3791fd32e20a2ab0f1ae30c53831e561944
|
[
"BSD-3-Clause"
] |
permissive
|
TrellixVulnTeam/proto-quic_1V94
|
1a3a03ac7a08a494b3d4e9857b24bb8f2c2cd673
|
feee14d96ee95313f236e0f0e3ff7719246c84f7
|
refs/heads/master
| 2023-04-01T14:36:53.888576
| 2019-10-17T02:23:04
| 2019-10-17T02:23:04
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,048
|
py
|
#! /usr/bin/env python
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import unittest
from pylib import constants
from pylib.utils import device_dependencies
class DevicePathComponentsForTest(unittest.TestCase):
def testCheckedInFile(self):
test_path = os.path.join(constants.DIR_SOURCE_ROOT, 'foo', 'bar', 'baz.txt')
output_directory = os.path.join(
constants.DIR_SOURCE_ROOT, 'out-foo', 'Release')
self.assertEquals(
[None, 'foo', 'bar', 'baz.txt'],
device_dependencies.DevicePathComponentsFor(
test_path, output_directory))
def testOutputDirectoryFile(self):
test_path = os.path.join(constants.DIR_SOURCE_ROOT, 'out-foo', 'Release',
'icudtl.dat')
output_directory = os.path.join(
constants.DIR_SOURCE_ROOT, 'out-foo', 'Release')
self.assertEquals(
[None, 'icudtl.dat'],
device_dependencies.DevicePathComponentsFor(
test_path, output_directory))
def testOutputDirectorySubdirFile(self):
test_path = os.path.join(constants.DIR_SOURCE_ROOT, 'out-foo', 'Release',
'test_dir', 'icudtl.dat')
output_directory = os.path.join(
constants.DIR_SOURCE_ROOT, 'out-foo', 'Release')
self.assertEquals(
[None, 'test_dir', 'icudtl.dat'],
device_dependencies.DevicePathComponentsFor(
test_path, output_directory))
def testOutputDirectoryPakFile(self):
test_path = os.path.join(constants.DIR_SOURCE_ROOT, 'out-foo', 'Release',
'foo.pak')
output_directory = os.path.join(
constants.DIR_SOURCE_ROOT, 'out-foo', 'Release')
self.assertEquals(
[None, 'paks', 'foo.pak'],
device_dependencies.DevicePathComponentsFor(
test_path, output_directory))
if __name__ == '__main__':
unittest.main()
|
[
"2100639007@qq.com"
] |
2100639007@qq.com
|
5a083a5caacded4d0503d61b1eed6d0a6b641e29
|
0cf6728548830b42c60e37ea1c38b54d0e019ddd
|
/Learning_Quant/python金融大数据挖掘与分析全流程详解/chapter12.py
|
05cc6faabfc1d70c38f3d38fc05b14eb7a328704
|
[] |
no_license
|
MuSaCN/PythonLearning
|
8efe166f66f2bd020d00b479421878d91f580298
|
507f1d82a9228d0209c416626566cf390e1cf758
|
refs/heads/master
| 2022-11-11T09:13:08.863712
| 2022-11-08T04:20:09
| 2022-11-08T04:20:09
| 299,617,217
| 2
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,889
|
py
|
# Author:Zhang Yuan
from MyPackage import *
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import seaborn as sns
import statsmodels.api as sm
from scipy import stats
#------------------------------------------------------------
__mypath__ = MyPath.MyClass_Path("\\python金融大数据挖掘与分析全流程详解") # 路径类
myfile = MyFile.MyClass_File() # 文件操作类
mytime = MyTime.MyClass_Time() # 时间类
myplt = MyPlot.MyClass_Plot() # 直接绘图类(单个图窗)
mypltpro = MyPlot.MyClass_PlotPro() # Plot高级图系列
myfig = MyPlot.MyClass_Figure(AddFigure=False) # 对象式绘图类(可多个图窗)
myfigpro = MyPlot.MyClass_FigurePro(AddFigure=False) # Figure高级图系列
mynp = MyArray.MyClass_NumPy() # 多维数组类(整合Numpy)
mypd = MyArray.MyClass_Pandas() # 矩阵数组类(整合Pandas)
mypdpro = MyArray.MyClass_PandasPro() # 高级矩阵数组类
myDA = MyDataAnalysis.MyClass_DataAnalysis() # 数据分析类
# myMql = MyMql.MyClass_MqlBackups() # Mql备份类
# myMT5 = MyMql.MyClass_ConnectMT5(connect=False) # Python链接MetaTrader5客户端类
# myDefault = MyDefault.MyClass_Default_Matplotlib() # matplotlib默认设置
# myBaidu = MyWebCrawler.MyClass_BaiduPan() # Baidu网盘交互类
# myImage = MyImage.MyClass_ImageProcess() # 图片处理类
myBT = MyBackTest.MyClass_BackTestEvent() # 事件驱动型回测类
myBTV = MyBackTest.MyClass_BackTestVector() # 向量型回测类
myML = MyMachineLearning.MyClass_MachineLearning() # 机器学习综合类
mySQL = MyDataBase.MyClass_MySQL(connect=False) # MySQL类
myWebQD = MyWebCrawler.MyClass_QuotesDownload(tushare=False) # 金融行情下载类
myWebR = MyWebCrawler.MyClass_Requests() # Requests爬虫类
myWebS = MyWebCrawler.MyClass_Selenium(openChrome=False) # Selenium模拟浏览器类
myWebAPP = MyWebCrawler.MyClass_APPIntegration() # 爬虫整合应用类
myEmail = MyWebCrawler.MyClass_Email() # 邮箱交互类
myReportA = MyQuant.MyClass_ReportAnalysis() # 研报分析类
#------------------------------------------------------------
# 12.1.1-1 requests库下载文件
url = 'http://images.china-pub.com/ebook8055001-8060000/8057968/shupi.jpg'
myWebR.download(url,"pic.jpg")
# 12.1.1-2 通过pandas获取表格
url = 'http://vip.stock.finance.sina.com.cn/q/go.php/vInvestConsult/kind/dzjy/index.phtml' # 新浪财经数据中心提供股票大宗交易的在线表格
myWebAPP.read_html(url,to_excel="测试.xlsx")
# 12.1.2 和讯研报网表格获取
table = myWebAPP.hexun_yanbao_stock(ybsj_index=5,to_page=1,to_excel=None)
# ---分析和讯研报数据_券商评级调升股: page_or_read = 5爬取网站 / "*.xlsx"读取;lengths代表时长,[10,20]则表示10、20天前;path为仅路径
myReportA.hexun_broker_buy_analysis(page_or_excel=2,lengths=[10,20,30],path="")
|
[
"39754824+MuSaCN@users.noreply.github.com"
] |
39754824+MuSaCN@users.noreply.github.com
|
fb63f6ee8a057a30027089c59c6d5ccb87cc6dc9
|
facb8b9155a569b09ba66aefc22564a5bf9cd319
|
/wp2/kikoAnalysis/slpDailyMeanFiles/43-tideGauge.py
|
4657f7de0acc7b31a05efa28139e82d5dd1442be
|
[] |
no_license
|
moinabyssinia/modeling-global-storm-surges
|
13e69faa8f45a1244a964c5de4e2a5a6c95b2128
|
6e385b2a5f0867df8ceabd155e17ba876779c1bd
|
refs/heads/master
| 2023-06-09T00:40:39.319465
| 2021-06-25T21:00:44
| 2021-06-25T21:00:44
| 229,080,191
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,411
|
py
|
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 29 09:40:12 2020
@author: Michael Tadesse
"""
import os
import pandas as pd
dir_in = "/lustre/fs0/home/mtadesse/eraFiveConcat"
dir_out = "/lustre/fs0/home/mtadesse/dailyPred"
os.chdir(dir_in)
tgList = os.listdir()
x = 43
y = 44
#looping through individual tide gauges
for ii in range(x, y):
os.chdir(tgList[ii])
#load file
slp = pd.read_csv('slp.csv')
slp.drop(['Unnamed: 0', 'Unnamed: 0.1'], axis = 1, inplace = True)
#sort by date
slp = slp.sort_values(by = 'date')
#reset indices
slp.reset_index(inplace = True)
slp.drop(['index'], axis = 1, inplace = True)
#get daily time steps
getDays = lambda x: x.split()[0]
slp['days'] = pd.DataFrame(list(map(getDays, slp['date'])))
#get unique days
days = slp['days'].unique()
first = True
for d in days:
currentDay = slp[slp['days'] == d]
print(currentDay)
if first:
currentMean = pd.DataFrame(currentDay.mean(axis = 0)).T
currentMean['date'] = d
first = False
dailyMean = currentMean
else:
currentMean = pd.DataFrame(currentDay.mean(axis = 0)).T
currentMean['date'] = d
dailyMean = pd.concat([dailyMean, currentMean], axis = 0)
dailyMean.to_csv('slpDaily.csv')
|
[
"michaelg.tadesse@gmail.com"
] |
michaelg.tadesse@gmail.com
|
73f7923b5825d9bf1260499fa1cc901620659557
|
f82757475ea13965581c2147ff57123b361c5d62
|
/gi-stubs/repository/Gio/UnixInputStreamClass.py
|
83dcff9394d0a3fa7e5dbf2594bcb42187c4ab48
|
[] |
no_license
|
ttys3/pygobject-stubs
|
9b15d1b473db06f47e5ffba5ad0a31d6d1becb57
|
d0e6e93399212aada4386d2ce80344eb9a31db48
|
refs/heads/master
| 2022-09-23T12:58:44.526554
| 2020-06-06T04:15:00
| 2020-06-06T04:15:00
| 269,693,287
| 8
| 2
| null | 2020-06-05T15:57:54
| 2020-06-05T15:57:54
| null |
UTF-8
|
Python
| false
| false
| 5,125
|
py
|
# encoding: utf-8
# module gi.repository.Gio
# from /usr/lib64/girepository-1.0/Gio-2.0.typelib
# by generator 1.147
# no doc
# imports
import gi as __gi
import gi.overrides as __gi_overrides
import gi.overrides.Gio as __gi_overrides_Gio
import gi.overrides.GObject as __gi_overrides_GObject
import gi.repository.GObject as __gi_repository_GObject
import gobject as __gobject
class UnixInputStreamClass(__gi.Struct):
"""
:Constructors:
::
UnixInputStreamClass()
"""
def __delattr__(self, *args, **kwargs): # real signature unknown
""" Implement delattr(self, name). """
pass
def __dir__(self, *args, **kwargs): # real signature unknown
""" Default dir() implementation. """
pass
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __format__(self, *args, **kwargs): # real signature unknown
""" Default object formatter. """
pass
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __hash__(self, *args, **kwargs): # real signature unknown
""" Return hash(self). """
pass
def __init_subclass__(self, *args, **kwargs): # real signature unknown
"""
This method is called when a class is subclassed.
The default implementation does nothing. It may be
overridden to extend subclasses.
"""
pass
def __init__(self): # real signature unknown; restored from __doc__
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
def __reduce_ex__(self, *args, **kwargs): # real signature unknown
""" Helper for pickle. """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
""" Helper for pickle. """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
def __setattr__(self, *args, **kwargs): # real signature unknown
""" Implement setattr(self, name, value). """
pass
def __sizeof__(self, *args, **kwargs): # real signature unknown
""" Size of object in memory, in bytes. """
pass
def __str__(self, *args, **kwargs): # real signature unknown
""" Return str(self). """
pass
def __subclasshook__(self, *args, **kwargs): # real signature unknown
"""
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__().
It should return True, False or NotImplemented. If it returns
NotImplemented, the normal algorithm is used. Otherwise, it
overrides the normal algorithm (and the outcome is cached).
"""
pass
def __weakref__(self, *args, **kwargs): # real signature unknown
pass
parent_class = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
_g_reserved1 = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
_g_reserved2 = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
_g_reserved3 = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
_g_reserved4 = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
_g_reserved5 = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
__class__ = None # (!) real value is "<class 'gi.types.StructMeta'>"
__dict__ = None # (!) real value is "mappingproxy({'__info__': StructInfo(UnixInputStreamClass), '__module__': 'gi.repository.Gio', '__gtype__': <GType void (4)>, '__dict__': <attribute '__dict__' of 'UnixInputStreamClass' objects>, '__weakref__': <attribute '__weakref__' of 'UnixInputStreamClass' objects>, '__doc__': None, 'parent_class': <property object at 0x7f4b87767d60>, '_g_reserved1': <property object at 0x7f4b87767e50>, '_g_reserved2': <property object at 0x7f4b87767f40>, '_g_reserved3': <property object at 0x7f4b8776b090>, '_g_reserved4': <property object at 0x7f4b8776b180>, '_g_reserved5': <property object at 0x7f4b8776b270>})"
__gtype__ = None # (!) real value is '<GType void (4)>'
__info__ = StructInfo(UnixInputStreamClass)
|
[
"ttys3@outlook.com"
] |
ttys3@outlook.com
|
f27837e23b09a26eefdf2310dfb8b68e4031e84d
|
0822d36728e9ed1d4e91d8ee8b5ea39010ac9371
|
/robo/pages/mato_grosso_do_sul/jd1noticias.py
|
738245155ef16987361a670e3484ee9f0add3ad5
|
[] |
no_license
|
diegothuran/blog
|
11161e6f425d08bf7689190eac0ca5bd7cb65dd7
|
233135a1db24541de98a7aeffd840cf51e5e462e
|
refs/heads/master
| 2022-12-08T14:03:02.876353
| 2019-06-05T17:57:55
| 2019-06-05T17:57:55
| 176,329,704
| 0
| 0
| null | 2022-12-08T04:53:02
| 2019-03-18T16:46:43
|
Python
|
UTF-8
|
Python
| false
| false
| 924
|
py
|
# coding: utf-8
import sys
sys.path.insert(0, '../../../blog')
from bs4 import BeautifulSoup
import requests
from robo.pages.util.constantes import PAGE_LIMIT
GLOBAL_RANK = 1125849
RANK_BRAZIL = 31946
NAME = 'jd1noticias.com'
def get_urls():
try:
urls = []
for i in range(1, PAGE_LIMIT):
link = 'http://www.jd1noticias.com/canal/ultimas-noticias/p/' + str(i)
req = requests.get(link)
noticias = BeautifulSoup(req.text, "html.parser").find_all('ul', class_='listNoticias listCanal')
for lista in noticias:
for noticia in lista:
try:
href = noticia.find_all('a', href=True)[0]['href']
urls.append(href)
except:
pass
return urls
except:
raise Exception('Exception in jd1noticias')
|
[
"diego.thuran@gmail.com"
] |
diego.thuran@gmail.com
|
299c3360d98aebb3d35976830345e1b5570228f7
|
5ae3bc1920fafc33693cdfa3928a48158aa6f725
|
/315/315-Segment.py
|
d49170abb3a3388d343616b67714c0002c5e9626
|
[] |
no_license
|
sjzyjc/leetcode
|
2d0764aec6681d567bffd8ff9a8cc482c44336c2
|
5e09a5d36ac55d782628a888ad57d48e234b61ac
|
refs/heads/master
| 2021-04-03T08:26:38.232218
| 2019-08-15T21:54:59
| 2019-08-15T21:54:59
| 124,685,278
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,317
|
py
|
class SegmentTreeNode:
def __init__(self, start, end, val):
self.start = start
self.end = end
self.val = val
self.left = self.right = None
class SegmentTree:
def __init__(self, n):
self.root = self.build(0, len(n) - 1, n)
def build(self, start, end, n):
if start > end:
return None
cur = SegmentTreeNode(start, end, n[start])
if start == end:
return cur
mid = (start + end) // 2
cur.left = self.build(start, mid, n)
cur.right = self.build(mid + 1, end, n)
if cur.left:
cur.val = cur.left.val
if cur.right:
cur.val += cur.right.val
return cur
def query(self, root, start, end):
if not root:
return 0
if root.start == start and root.end == end:
return root.val
mid = (root.start + root.end) // 2
if end <= mid:
return self.query(root.left, start, end)
elif start > mid:
return self.query(root.right, start, end)
else:
return self.query(root.left, start, mid) + self.query(root.right, mid+1, end)
def update(self, root, index):
if not root:
return
if root.start == root.end == index:
root.val += 1
return
mid = (root.start + root.end) // 2
if index <= mid:
self.update(root.left, index)
else:
self.update(root.right, index)
root.val = root.left.val + root.right.val
class Solution(object):
def countSmaller(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if not nums:
return []
min_num = min(nums)
size = max(nums) - min_num + 1
count = [0 for _ in range(size)]
st = SegmentTree(count)
ans = []
for index in range(len(nums) - 1, -1, -1):
count_index = nums[index] - min_num
st.update(st.root, count_index)
ans.append(st.query(st.root, 0, count_index - 1))
return ans[::-1]
|
[
"jcyang@MacBook-Air.local"
] |
jcyang@MacBook-Air.local
|
c9135d8bc839acb9df559e73377e0df9a5dc5901
|
edb10a06f56d9bd19b0b60581728900a03d9732a
|
/Python/leetcode/Anagrams.py
|
ca5c1a364909e0a69634540c9097753018bccfff
|
[
"MIT"
] |
permissive
|
darrencheng0817/AlgorithmLearning
|
3ba19e6044bc14b0244d477903959730e9f9aaa8
|
aec1ddd0c51b619c1bae1e05f940d9ed587aa82f
|
refs/heads/master
| 2021-01-21T04:26:14.814810
| 2019-11-22T06:02:01
| 2019-11-22T06:02:01
| 47,100,767
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 409
|
py
|
'''
Created on 1.12.2016
@author: Darren
''''''
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
Note:
For the return value, each inner list s elements must follow the lexicographic order.
All inputs will be in lower-case.
"
'''
|
[
"darrencheng0817@gmail.com"
] |
darrencheng0817@gmail.com
|
df69ecd68dbc05aa63ae2dc25a88a9c5272233bc
|
cec916f882afbd09fe68f6b88879e68eaea976f6
|
/bigmler/resourcesapi/fusions.py
|
1c8a17d3f87803d2ed503abbe367ac47e23f8336
|
[
"Apache-2.0"
] |
permissive
|
jaor/bigmler
|
d86db6d7950768d7ba3e21b5f29bc265467f4cad
|
bbf221e41ef04e8d37a511a35a63216b64689449
|
refs/heads/master
| 2023-04-26T12:07:49.428263
| 2023-04-12T15:22:20
| 2023-04-12T15:22:20
| 15,663,632
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,785
|
py
|
# -*- coding: utf-8 -*-
#
# Copyright 2020-2023 BigML
#
# 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.
"""Resources management functions
"""
import sys
import bigml.api
from bigmler.utils import (dated, get_url, log_message, check_resource,
is_shared,
check_resource_error, log_created_resources)
from bigmler.reports import report
from bigmler.resourcesapi.common import set_basic_args, \
update_json_args, wait_for_available_tasks
from bigmler.resourcesapi.common import FIELDS_QS, \
ALL_FIELDS_QS
def set_fusion_args(args, name=None, fields=None):
"""Return fusion arguments dict
"""
if name is None:
name = args.name
fusion_args = set_basic_args(args, name)
if 'fusion' in args.json_args:
update_json_args(fusion_args,
args.json_args.get('fusion'),
fields)
return fusion_args
def create_fusion(models, fusion, fusion_args,
args, api=None, path=None,
session_file=None, log=None):
"""Create remote fusion
"""
if api is None:
api = bigml.api.BigML()
fusions = []
fusion_ids = []
if fusion is not None:
fusions = [fusion]
fusion_ids = [fusion]
# if resuming and all fusions were created
if models:
# Only one fusion per command, at present
message = dated("Creating fusion.\n")
log_message(message, log_file=session_file,
console=args.verbosity)
query_string = FIELDS_QS
inprogress = []
wait_for_available_tasks(inprogress,
args.max_parallel_fusions,
api, "fusion")
fusion = api.create_fusion(models,
fusion_args,
retries=None)
fusion_id = check_resource_error( \
fusion,
"Failed to create fusion: ")
log_message("%s\n" % fusion_id, log_file=log)
fusion_ids.append(fusion_id)
inprogress.append(fusion_id)
fusions.append(fusion)
log_created_resources("fusions", path, fusion_id,
mode='a')
if args.verbosity:
if bigml.api.get_status(fusion)['code'] != bigml.api.FINISHED:
try:
fusion = check_resource( \
fusion, api.get_fusion,
query_string=query_string,
raise_on_error=True)
except Exception as exception:
sys.exit("Failed to get a finished fusion: %s" %
str(exception))
fusions[0] = fusion
message = dated("Fusion created: %s\n" %
get_url(fusion))
log_message(message, log_file=session_file,
console=args.verbosity)
if args.reports:
report(args.reports, path, fusion)
return fusion
def get_fusion(fusion,
args, api=None, session_file=None):
"""Retrieves remote fusion in its actual status
"""
if api is None:
api = bigml.api.BigML()
message = dated("Retrieving Fusion. %s\n" %
get_url(fusion))
log_message(message, log_file=session_file, console=args.verbosity)
# only one fusion at present
try:
# we need the whole fields structure when exporting fields
fusion = check_resource(fusion,
api.get_fusion,
query_string=ALL_FIELDS_QS,
raise_on_error=True)
except Exception as exception:
sys.exit("Failed to get a finished fusion: %s" % \
str(exception))
return fusion
def set_publish_fusion_args(args):
"""Set args to publish fusion
"""
public_fusion = {}
if args.public_fusion:
public_fusion = {"private": False}
if args.model_price:
public_fusion.update(price=args.model_price)
if args.cpp:
public_fusion.update(credits_per_prediction=args.cpp)
return public_fusion
def update_fusion(fusion, fusion_args, args,
api=None, path=None, session_file=None):
"""Updates fusion properties
"""
if api is None:
api = bigml.api.BigML()
message = dated("Updating Fusion. %s\n" %
get_url(fusion))
log_message(message, log_file=session_file,
console=args.verbosity)
fusion = api.update_fusion(fusion, fusion_args)
check_resource_error(fusion,
"Failed to update Fusion: %s"
% fusion['resource'])
fusion = check_resource(fusion,
api.get_fusion,
query_string=FIELDS_QS,
raise_on_error=True)
if is_shared(fusion):
message = dated("Shared Fusion link. %s\n" %
get_url(fusion, shared=True))
log_message(message, log_file=session_file, console=args.verbosity)
if args.reports:
report(args.reports, path, fusion)
return fusion
|
[
"merce@bigml.com"
] |
merce@bigml.com
|
8b298efd886c26c6cc53a15b22eb5b96064022d5
|
7d7da2d78526436aedbe44f2a1b26f31409993f5
|
/ABOUT/views.py
|
5c8a785178e768c6719b4701506222f43a77f655
|
[] |
no_license
|
Arif553715/NGO
|
c4042b59a96de0b1f8c74f73ca166aa03ed6223c
|
7a901931dd70702e6e81d8e0880bca962da09443
|
refs/heads/master
| 2020-05-06T20:32:42.036796
| 2019-04-18T09:36:17
| 2019-04-18T09:36:17
| 180,239,663
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 752
|
py
|
from django.shortcuts import render,HttpResponse,get_object_or_404
from .models import Author1,Artical,Catagory,Our_Team
# Create your views here.
# start blogapp
def about(request):
context={'post':Artical.objects.all(),
'teams':Our_Team.objects.all()}
return render(request,'about.html',context)
def getauthor(request,name):
return render(request,'profile.html')
def getsingle(request,id):
post=get_object_or_404(Artical,pk=id)
first=Artical.objects.first()
last=Artical.objects.last()
context={
'post':post,
'first':first,
'last':last
}
return render(request,'single.html',context)
def gettopic(request,name):
return render(request,'catagory.html')
# end blogapp
|
[
"root@localhost.localdomain"
] |
root@localhost.localdomain
|
b9603c227e39f7d5e195f02d9a03afe31a826525
|
f9f2d8064943906e8ee0d305d405ca1e5dd0a6b7
|
/Hysteresis_Measurement/tooltip.py
|
d252b1f9c6760bf06e328eb70ab58b3b73bb2afb
|
[] |
no_license
|
Jeffrey-Ede/Atomic-Force-Microscopy
|
a46930657b256f4dc772c1b2130a55486dbb6e2b
|
7df834b17ad9974016b02a72711f8847f6b15d4d
|
refs/heads/master
| 2021-01-18T12:06:38.779728
| 2017-10-06T07:24:12
| 2017-10-06T07:24:12
| 100,364,689
| 4
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,336
|
py
|
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 15 22:48:56 2017
@author: Jeffrey Ede
"""
import tkinter as Tk
class ToolTip(object):
def __init__(self, widget):
self.widget = widget
self.tipwindow = None
self.id = None
self.x = self.y = 0
def showtip(self, text):
"Display text in tooltip window"
self.text = text
if self.tipwindow or not self.text:
return
x, y, cx, cy = self.widget.bbox("insert")
x = x + self.widget.winfo_rootx() + 27
y = y + cy + self.widget.winfo_rooty() +27
self.tipwindow = tw = Tk.Toplevel(self.widget)
tw.wm_overrideredirect(1)
tw.wm_geometry("+%d+%d" % (x, y))
label = Tk.Label(tw, text=self.text, justify=Tk.LEFT,
background="#ffffe0", relief=Tk.SOLID, borderwidth=1,
font=("tahoma", "8", "normal"))
label.pack(ipadx=1)
def hidetip(self):
tw = self.tipwindow
self.tipwindow = None
if tw:
tw.destroy()
def createToolTip(widget, text):
toolTip = ToolTip(widget)
def enter(event):
toolTip.showtip(text)
def leave(event):
toolTip.hidetip()
widget.bind('<Enter>', enter)
widget.bind('<Leave>', leave)
|
[
"noreply@github.com"
] |
Jeffrey-Ede.noreply@github.com
|
a4e87d3fbf5daf9bafa306e7e3ed00ae74f7e018
|
13cccbc1bbaec02f53d2f4e654d480512f6c2bb5
|
/binary-search/leetcode-tutorial/Search_in_Rotated_Sorted_Array.py
|
5d641e52117e3dc735343227c664d4231e10097f
|
[] |
no_license
|
sjdeak/interview-practice
|
580cc61ec0d20d548bbc1e9ebebb4a64cd7ac2dc
|
1746aaf5ab06603942f9c85c360e319c110d4df8
|
refs/heads/master
| 2020-07-20T21:06:23.864208
| 2019-09-08T10:54:16
| 2019-09-08T10:54:16
| 206,709,284
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,079
|
py
|
# https://leetcode.com/explore/learn/card/binary-search/125/template-i/952/
import os, sys, shutil, glob, re
import time, calendar
from datetime import datetime, timezone
import hashlib, zipfile, zlib
from math import *
from operator import itemgetter
from functools import wraps, cmp_to_key
from itertools import count, combinations, permutations
from collections import namedtuple, defaultdict, Counter
from queue import Queue
def refreshGlobals():
pass
refreshGlobals()
def binarySearch(left, right, nums, target):
if len(nums) == 0:
return -1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
def findPivot(nums):
left, right = 0, len(nums) - 1
leftMin, rightMax = nums[0], nums[-1]
if leftMin < rightMax:
return 0
while left < right:
mid = left + (right - left) // 2
if nums[mid] >= leftMin:
left = mid + 1
else:
right = mid
return left
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return -1
left, right = None, None
leftMin, rightMax = nums[0], nums[-1]
if leftMin <= rightMax: # 不分左右端
left, right = 0, len(nums) - 1
else:
pivot = findPivot(nums)
if target >= nums[0]: # >= 左端最小值 则target在左端
left, right = 0, pivot - 1
else: # 否则在右端
left, right = pivot, len(nums) - 1
return binarySearch(left, right, nums, target)
if __name__ == '__main__' and ('SJDEAK' in os.environ):
from utils.tree import TreeNode, array2TreeNode
def test(*args):
print('输入数据: ', *args)
print('结果: ', Solution().search(*args), end='\n-----\n')
test([4, 5, 6, 7, 0, 1, 2], 0)
test([4, 5, 6, 7, 0, 1, 2], 3)
test([0, 1, 2, 4, 5, 6, 7], 3)
test([1, 2, 4, 5, 6, 7, 0], 7)
test([], 7)
test([1], 1)
else:
print = lambda *args, **kwargs: None
|
[
"sjdeak@yahoo.com"
] |
sjdeak@yahoo.com
|
349b2be9f926e5186d63da726ea61cc465eb15c3
|
a685fa36823caa4b910969e80adbcae4f2829bd6
|
/python_Fundamentals/Find_Characters.py
|
70a7927579c0dbc033b28e77130ce161b8d75be1
|
[] |
no_license
|
hmp36/Python
|
35e4fbc003b216ca6c7c45c558dd4f24edba5b9a
|
dcddf40a0428542d78f2e32d4755b54ebdaadffd
|
refs/heads/master
| 2021-09-15T01:35:41.013949
| 2018-05-23T13:05:59
| 2018-05-23T13:05:59
| 112,358,856
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 302
|
py
|
#find_characters
def find_character(word_list, char):
new_list = []
for i in range(0, len(word_list)):
if word_list[i].find(char) != -1:
new_list.append(word_list[i])
print new_list
test_list = ['hello','world','my','name','is','Hagan']
find_character(test_list,'o')
|
[
"haganpratt@gmail.com"
] |
haganpratt@gmail.com
|
61723176d8f107f09aa921c5b13fd058568de260
|
85e27209a7df58f76ab0f9f2ed13b1c6ac31ffc9
|
/src_python/habitat_sim/utils/gfx_replay_utils.py
|
f4a40ecbd3f41db0fa440ce577fe25b83c0612c5
|
[
"CC-BY-4.0",
"CC-BY-3.0",
"MIT"
] |
permissive
|
facebookresearch/habitat-sim
|
72a78877c412fef1d42a553f896654c71c54d245
|
6f46bccc1733f4cec30b89d994ac55df2b46eb4a
|
refs/heads/main
| 2023-09-03T00:17:30.809849
| 2023-08-29T16:06:16
| 2023-08-29T16:06:16
| 169,164,539
| 1,924
| 432
|
MIT
| 2023-09-14T17:12:21
| 2019-02-04T23:14:28
|
C++
|
UTF-8
|
Python
| false
| false
| 1,009
|
py
|
# Copyright (c) Meta Platforms, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import magnum as mn
import habitat_sim
def add_node_user_transform(sim, node, name):
translation = node.absolute_translation
rot = mn.Quaternion(mn.Quaterniond(node.rotation))
while True:
node = node.parent
if not node:
break
try:
rot = node.rotation * rot
except AttributeError:
# scene root has no rotation attribute
break
sim.gfx_replay_manager.add_user_transform_to_keyframe(name, translation, rot)
def make_backend_configuration_for_playback(
need_separate_semantic_scene_graph=False,
):
backend_cfg = habitat_sim.SimulatorConfiguration()
backend_cfg.scene_id = "NONE" # see Asset.h EMPTY_SCENE
backend_cfg.force_separate_semantic_scene_graph = need_separate_semantic_scene_graph
return backend_cfg
|
[
"noreply@github.com"
] |
facebookresearch.noreply@github.com
|
6001ba346612f6f193597608f08320170e40f44b
|
05f668036da3c4295b7f5282b7a7c9bd387bdd0b
|
/spiders/start.py
|
1df95b4204485539feeb2f92e43feb231c054bc9
|
[
"MIT"
] |
permissive
|
ProgramRipper/biliob-spider
|
8ae476f7ab096734ac9c24c3318f98ee41af8c7f
|
2fe3d5fd91bb301dd0d0eb21d03153d6882f6bcf
|
refs/heads/master
| 2022-04-11T09:51:42.037081
| 2020-03-23T16:31:12
| 2020-03-23T16:31:12
| 312,482,354
| 0
| 0
|
MIT
| 2023-05-17T00:33:30
| 2020-11-13T05:32:19
| null |
UTF-8
|
Python
| false
| false
| 1,500
|
py
|
from time import sleep
import datetime
import schedule
import psutil
import os
def find_procs_by_name(name):
"Return a list of processes matching 'name'."
ls = []
for process in psutil.process_iter():
try:
for each in process.cmdline():
if name in each:
ls.append(process.pid)
break
pass
except Exception as e:
pass
return ls
def delete_by_name(name):
pids = find_procs_by_name(name)
for pid in pids:
os.kill(pid, 9)
spiders = ['add_public_video.py',
'author_follow.py',
'author.py',
'video.py',
'new_author.py',
'new_video.py',
'tag.py']
weekly_spider = [
'utils/keyword.py'
]
daily_spiders = ['utils/keyword_author.py']
def check():
for each_spider_group in [spiders, weekly_spider]:
for each_spider in each_spider_group:
pid = find_procs_by_name(each_spider)
if len(pid) == 0:
run_spider(each_spider)
pass
def run_spider(spider):
print('[{}] 重启 {}'.format(datetime.datetime.now(), spider))
delete_by_name(spider)
cmd = 'nohup python {} 1>{}.log 2>&1 &'.format(spider, spider)
os.system(cmd)
pass
schedule.every(10).seconds.do(check)
schedule.every().day.at('09:00').do(run_spider, 'rank_add.py')
schedule.every().day.at('03:00').do(run_spider, 'utils/keyword_author.py')
schedule.every().wednesday.at('03:20').do(run_spider, 'utils/keyword.py')
while True:
schedule.run_pending()
sleep(10)
|
[
"jannchie@gmail.com"
] |
jannchie@gmail.com
|
ef2e356bf57c377f09b460ddb28b36cf239114ae
|
e23a4f57ce5474d468258e5e63b9e23fb6011188
|
/125_algorithms/_exercises/templates/_algorithms_challenges/hackerrank/HackerrankPractice-master/Algorithms/01. Warmup/008. Mini-Max Sum.py
|
426a1546f2599b3b1e1a4fc95470f8d1c9f0422f
|
[] |
no_license
|
syurskyi/Python_Topics
|
52851ecce000cb751a3b986408efe32f0b4c0835
|
be331826b490b73f0a176e6abed86ef68ff2dd2b
|
refs/heads/master
| 2023-06-08T19:29:16.214395
| 2023-05-29T17:09:11
| 2023-05-29T17:09:11
| 220,583,118
| 3
| 2
| null | 2023-02-16T03:08:10
| 2019-11-09T02:58:47
|
Python
|
UTF-8
|
Python
| false
| false
| 162
|
py
|
# Problem: https://www.hackerrank.com/challenges/mini-max-sum/problem
# Score: 10
arr l.. m..(i.., i.. ).s..()))
print(s..(arr) - m..(arr), s..(arr) - m..(arr
|
[
"sergejyurskyj@yahoo.com"
] |
sergejyurskyj@yahoo.com
|
18927a4d6c41ee8f5750ed1b5eee62ec6a794d33
|
bdccb54daf0d0b0a19fabfe9ea9b90fcfc1bdfbf
|
/Interview Preparation Kits/Interview Preparation Kit/Miscellaneous/Flipping Bits/flipping_bits.py
|
cd52f26938ced69241748542cf1618a1bdcac0d9
|
[
"MIT"
] |
permissive
|
xuedong/hacker-rank
|
aba1ad8587bc88efda1e90d7ecfef8dbd74ccd68
|
1ee76899d555850a257a7d3000d8c2be78339dc9
|
refs/heads/master
| 2022-08-08T07:43:26.633759
| 2022-07-16T11:02:27
| 2022-07-16T11:02:27
| 120,025,883
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 410
|
py
|
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the flippingBits function below.
def flippingBits(n):
return ~n & 0xffffffff
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
q = int(input())
for q_itr in range(q):
n = int(input())
result = flippingBits(n)
fptr.write(str(result) + '\n')
fptr.close()
|
[
"shang.xuedong@yahoo.fr"
] |
shang.xuedong@yahoo.fr
|
796fb3923593aff09a76764b03a1b6e7e18b9a25
|
1990344218def595b8fe8a60d2367f8733289586
|
/Tape.py
|
ee1c22b1754b1f413c8732078cf15e7b640bfbea
|
[] |
no_license
|
fortable1999/dynamicprogramming
|
7afd49a5bc8b2f92eb927581e718c57fdb040f51
|
976efa646cb16e40eb13772046e7d04ff109dc10
|
refs/heads/master
| 2020-04-09T15:31:08.153342
| 2018-12-06T02:17:51
| 2018-12-06T02:17:51
| 160,428,467
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 379
|
py
|
import math
def solution(A):
# write your code in Python 3.6
left, right = A[0], sum(A[1:])
diff = abs(left - right)
for elem in A[1:-1]:
left += elem
right -= elem
if abs(left - right) < diff:
diff = abs(left - right)
return diff
print(solution([-1, 1, 1000, -1]))
print(solution([1, -1, -11]))
print(solution([1, 2]))
|
[
"fortable1999@gmail.com"
] |
fortable1999@gmail.com
|
8b63a29441cb9e8d2602e6259654e50e3ae5e4be
|
8da91c26d423bacbeee1163ac7e969904c7e4338
|
/pyvisdk/mo/guest_operations_manager.py
|
42811965f87e374b8b96d6972b7bd55e7f8b7f68
|
[] |
no_license
|
pexip/os-python-infi-pyvisdk
|
5d8f3a3858cdd61fb76485574e74ae525cdc7e25
|
1aadea0afbc306d09f6ecb9af0e683dbbf961d20
|
refs/heads/master
| 2023-08-28T02:40:28.789786
| 2020-07-16T04:00:53
| 2020-07-16T04:00:53
| 10,032,240
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,275
|
py
|
from pyvisdk.base.managed_object_types import ManagedObjectTypes
from pyvisdk.base.base_entity import BaseEntity
import logging
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
class GuestOperationsManager(BaseEntity):
'''GuestOperationsManager is the managed object that provides APIs to manipulate
the guest operating system files and process. Each class of APIs is separated
into its own manager.'''
def __init__(self, core, name=None, ref=None, type=ManagedObjectTypes.GuestOperationsManager):
super(GuestOperationsManager, self).__init__(core, name=name, ref=ref, type=type)
@property
def authManager(self):
'''A singleton managed object that provides methods for guest authentication
operations.'''
return self.update('authManager')
@property
def fileManager(self):
'''A singleton managed object that provides methods for guest file operations.'''
return self.update('fileManager')
@property
def processManager(self):
'''A singleton managed object that provides methods for guest process operations.'''
return self.update('processManager')
|
[
"jmb@pexip.com"
] |
jmb@pexip.com
|
e33b7e0b004944fe986a82dc58d7668f0d622a18
|
15f321878face2af9317363c5f6de1e5ddd9b749
|
/solutions_python/Problem_136/1488.py
|
04ea069f2a72cc94a1d2641d3b845e5b20b5ece6
|
[] |
no_license
|
dr-dos-ok/Code_Jam_Webscraper
|
c06fd59870842664cd79c41eb460a09553e1c80a
|
26a35bf114a3aa30fc4c677ef069d95f41665cc0
|
refs/heads/master
| 2020-04-06T08:17:40.938460
| 2018-10-14T10:12:47
| 2018-10-14T10:12:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 598
|
py
|
# https://code.google.com/codejam/contest/2974486/dashboard#s=p1
import sys
def readline():
return sys.stdin.readline().rstrip()
f0 = 2
t = int(readline())
for case in range(t):
line = readline()
[c, f, x] = [float(s) for s in line.split()]
time = x/f0
time2 = c/f0 + x/(f+f0)
more = time2 < time
factories = 0
n = 0
while more:
factories = factories + c/(f*n+f0)
time2 = factories + x/(f*(n+1)+f0)
more = time2 < time
time = min(time2, time)
n = n+1
result = time
print 'Case #{}: {}'.format(case+1, result)
|
[
"miliar1732@gmail.com"
] |
miliar1732@gmail.com
|
6f8f55d475bcc0e553f442897fd874177c3d347c
|
2491df3f643539e6055bb0b2a4b659474c57491f
|
/interval.py
|
1c48b76451542d32868f5e00496c2a8e10df5e23
|
[] |
no_license
|
ghilbing/Ejemplos
|
85efc91346028b8a3d26d7680d9286b26234c771
|
339a45ef48c9a61002a01f7c823cc42d34fab409
|
refs/heads/master
| 2021-05-13T13:58:33.010157
| 2018-02-26T20:44:44
| 2018-02-26T20:44:44
| 116,724,506
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,199
|
py
|
def interval(intervals, new_interval):
s = new_interval.start
e = new_interval.end
parts = merge = []
left = []
right = []
for i in intervals:
parts[(i.end < s) - (i.start > e)].append(i)
if merge:
s = min(s, merge[0].start)
e = max(e, merge[-1].end)
return left + [Interval(s, e)] + right
# Definition for an interval.
class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
intervals = [ (6037774, 6198243), (6726550, 7004541), (8842554, 10866536), (11027721, 11341296), (11972532, 14746848), (16374805, 16706396), (17557262, 20518214), (22139780, 22379559), (27212352, 28404611), (28921768, 29621583), (29823256, 32060921), (33950165, 36418956), (37225039, 37785557), (40087908, 41184444), (41922814, 45297414), (48142402, 48244133), (48622983, 50443163), (50898369, 55612831), (57030757, 58120901), (59772759, 59943999), (61141939, 64859907), (65277782, 65296274), (67497842, 68386607), (70414085, 73339545), (73896106, 75605861), (79672668, 84539434), (84821550, 86558001), (91116470, 92198054), (96147808, 98979097) ]
new_interval = (36210193, 61984219)
print interval(intervals, new_interval)
|
[
"ghilbing@gmail.com"
] |
ghilbing@gmail.com
|
2f7e7080307ec0ae3515529e27fa46310cc9f7cb
|
a0a0932b6ab6ec47c2757d8929216790f5bc6535
|
/order/apps.py
|
63251174a40de7091e5dd63e488b3497605ea2bb
|
[] |
no_license
|
lianglunzhong/latte-erp
|
b4e6e3b13c4bce17911ff166fecc36172e0bea5b
|
b58936c8d9917f3efdcb3585c54bfd3aba4723c2
|
refs/heads/master
| 2022-11-27T03:08:23.780124
| 2017-04-28T02:51:43
| 2017-04-28T02:51:43
| 89,660,834
| 0
| 0
| null | 2022-11-22T01:04:12
| 2017-04-28T02:48:50
|
Python
|
UTF-8
|
Python
| false
| false
| 179
|
py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
class OrderConfig(AppConfig):
name = 'order'
verbose_name = u"订单"
|
[
"liang.lunzhong@wxzeshang.com"
] |
liang.lunzhong@wxzeshang.com
|
aa7e54c13f82ec435d13c5be8999b09e623f6ee0
|
e07b8420df6ebe15b0de68ca6889fcaa68d8fad3
|
/Keras/study/cross_entrophy.py
|
18e196f4acd85efa5fad1fc77cdf07724becf698
|
[] |
no_license
|
AllenLiuX/Machine-Learning-Projects
|
2fcbb3dc3d8efee08de9d96020e551a9c0758fa6
|
ea20ea04cb956a9fb8f7099ddb7ec36ab5730cc2
|
refs/heads/master
| 2023-01-24T05:46:33.123993
| 2020-11-21T08:24:05
| 2020-11-21T08:24:05
| 299,807,064
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,397
|
py
|
import numpy as np
import matplotlib.pyplot as plt
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.optimizers import SGD
# (x_train, y_train), (x_test, y_test) = mnist.load_data()
f = np.load('mnist.npz')
x_train, y_train = f['x_train'], f['y_train']
x_test, y_test = f['x_test'], f['y_test']
f.close()
# (x_train, y_train), (x_test, y_test) = np.load('mnist.npz')
# (60000, 28, 28)
print('x_shape:', x_train.shape) #60000
print('y_shape:', y_train.shape) #60000
# 60000, 28, 28 -> 60000, 784
x_train = x_train.reshape(x_train.shape[0], -1)/255.0 #/255 -> 均一化, -1表示自动计算行数
x_test = x_test.reshape(x_test.shape[0], -1)/255.0
#换one hot格式
y_train = np_utils.to_categorical(y_train, num_classes=10)
y_test = np_utils.to_categorical(y_test, num_classes=10)
# 创建模型
model = Sequential()
model.add(Dense(units=10, input_dim=784, bias_initializer='one', activation='softmax'))
sgd = SGD(lr=0.2)
# 定义优化器,loss,训练过程中计算准确率
model.compile(optimizer=sgd,
loss='categorical_crossentropy',
metrics=['accuracy'])
# 训练模型
model.fit(x_train, y_train, batch_size=32, epochs=10)
# 评估模型
loss, accuracy = model.evaluate(x_test, y_test)
print('\ntest loss', loss)
print('accuracy', accuracy)
|
[
"13120200491@163.com"
] |
13120200491@163.com
|
9ddb472d2ff2e53ba564d04caed1083c15bdb513
|
2033d6d7b9547c6722bfc9f52379683ebfca7186
|
/pbf_kao_gui/Commands/new_pygame_screen.py
|
e4d417e14846ac385b85c64668550296c079c27d
|
[] |
no_license
|
cloew/KaoGUIPBF
|
5119e4f149343804d6e031b14d920a9e2229eb2b
|
819a908bccfd579c9d0666f216395d08e230353f
|
refs/heads/master
| 2021-01-01T20:16:57.033719
| 2015-02-17T16:39:51
| 2015-02-17T16:39:51
| 16,234,905
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,039
|
py
|
from pbf.helpers.filename_helper import GetPythonClassnameFromFilename
from pbf.templates.template_loader import TemplateLoader
from pbf_kao_gui.templates import TemplatesRoot
class NewPygameScreen:
""" Command to Create a new Pygame Screen """
TEMPLATE_LOADER = TemplateLoader("pygame_screen.py", TemplatesRoot)
def addArguments(self, parser):
""" Add arguments to the parser """
parser.add_argument('destination', action='store', help='Destination for the new pygame screen')
def run(self, arguments):
""" Run the command """
screenFileName = arguments.destination
screenName = GetPythonClassnameFromFilename(screenFileName)
print "Creating Pygame Screen:", screenName, "at:", screenFileName
self.createScreen(screenFileName, screenName)
def createScreen(self, screenFileName, screenName):
""" Create the widget file """
self.TEMPLATE_LOADER.copy(screenFileName, keywords={"%ScreenName%":screenName})
|
[
"cloew123@gmail.com"
] |
cloew123@gmail.com
|
ebb2fa048817413a11e3f6b1fa17173e0b9a4846
|
95594364c548081b4f139b0fec2d2474d23129da
|
/Pretreatment/Audio/Step3_Assembly.py
|
a86b07697b9a6e3da8c5f926464515397e374d1f
|
[] |
no_license
|
Grace-JingXiao/AVEC_2017_DDS_CNN_Research
|
0e932e2e5f38039dd2884595e6d75bc67da8e20a
|
71d04f3d765efb18f6dbe99eab3ef12e5e5f8489
|
refs/heads/master
| 2020-09-05T22:09:02.904761
| 2019-09-11T06:07:53
| 2019-09-11T06:07:53
| 220,227,983
| 1
| 0
| null | 2019-11-07T12:06:41
| 2019-11-07T12:06:40
| null |
UTF-8
|
Python
| false
| false
| 906
|
py
|
import numpy
import os
if __name__ == '__main__':
loadpath = 'D:/PythonProjects_Data/AVEC2017-OtherFeatures/Step1_features3D/'
savepath = 'D:/PythonProjects_Data/AVEC2017-OtherFeatures/Step3_features3D_Assembly/'
os.makedirs(savepath)
ususalShape = 0
for foldname in os.listdir(loadpath):
totalData = []
for filename in os.listdir(os.path.join(loadpath, foldname)):
if filename.find('Participant') == -1: continue
data = numpy.genfromtxt(fname=os.path.join(loadpath, foldname, filename), dtype=float, delimiter=',')
if ususalShape == 0:
ususalShape = numpy.shape(data)[1]
else:
data = numpy.reshape(data, [-1, ususalShape])
totalData.extend(data)
print(foldname, numpy.shape(totalData))
numpy.save(savepath + foldname + '.npy', totalData, allow_pickle=True)
|
[
"35563563+BaoZhongtian@users.noreply.github.com"
] |
35563563+BaoZhongtian@users.noreply.github.com
|
8b332439a2fe2e912f9c5478e97e3bb5fc6ab0dd
|
08fe752455b2e8bea36f69bd7eb0d70641691514
|
/12월 3주차/[BAEKJOON] 12904_A와 B.py
|
abd5edb88c54b6248ff79f668d83207e4fb1c09a
|
[] |
no_license
|
2020-ASW/gayoung_yoon
|
69a7a20c073710aaec76261cac59aa6541250588
|
0ad21c5484ed087d704d72b03fc1f14c3fa9e25f
|
refs/heads/main
| 2023-02-14T19:28:38.966502
| 2021-01-10T07:56:10
| 2021-01-10T07:56:10
| 320,287,097
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 442
|
py
|
# S = "B"
# T = "ABBA"
# S = "AB"
# T = "ABB"
'''
조건1 문자열의 뒤에 A를 추가한다.
조건2 문자열을 뒤집고 뒤에 B를 추가한다.
S -> T를 확인하기 위해 T -> S로 변경가능한지 check!
'''
S = list(input())
T = list(input())
while True:
if len(S) == len(T):
break
if T[-1] == 'A':
T.pop()
else:
T.pop()
T = T[::-1]
if S == T:
print(1)
else:
print(0)
|
[
"gyyoon4u@naver.com"
] |
gyyoon4u@naver.com
|
212953611e16a73c32f310c5769c10ea1a31a979
|
adb748ac7d24f6184ad81881d6caf5ea4689c38f
|
/spatialdata/units/NondimElasticQuasistatic.py
|
3e050ad231632b437bb4a2686b50c9bb5b8b973c
|
[
"MIT"
] |
permissive
|
Zilhe/spatialdata
|
7a291703703cc2ff254cceec3683dc066925b5f4
|
fee0e77dcb820d466857a0e914af265255709285
|
refs/heads/main
| 2023-04-30T08:16:55.977142
| 2021-05-19T01:41:42
| 2021-05-19T01:41:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,928
|
py
|
# ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copyright (c) 2010-2017 University of California, Davis
#
# See COPYING for license information.
#
# ----------------------------------------------------------------------
#
# @file spatialdata/units/NondimElasticQuasistatic.py
#
# @brief Python manager for nondimensionalizing quasi-static
# elasticity problems.
#
# Factory: nondimensional
from .Nondimensional import Nondimensional
class NondimElasticQuasistatic(Nondimensional):
"""
Python manager for nondimensionalizing quasi-static elasticity problems.
Factory: nondimensional
INVENTORY
Properties
- *shear_modulus* Shear modules for pressure scale of problem.
- *length_scale* Discretization size for length scale of problem.
- *relaxation_time* Viscoelastic relaxation time for time scale of problem.
Facilities
- None
"""
import pythia.pyre.inventory
from pythia.pyre.units.length import meter
lengthScale = pythia.pyre.inventory.dimensional("length_scale", default=1.0e+3 * meter,
validator=pythia.pyre.inventory.greater(0.0 * meter))
lengthScale.meta['tip'] = "Value to nondimensionalize length scale."
from pythia.pyre.units.pressure import pascal
shearModulus = pythia.pyre.inventory.dimensional("shear_modulus", default=3.0e+10 * pascal,
validator=pythia.pyre.inventory.greater(0.0 * pascal))
shearModulus.meta['tip'] = "Shear modulus to nondimensionalize pressure."
from pythia.pyre.units.time import year
relaxationTime = pythia.pyre.inventory.dimensional("relaxation_time", default=100.0 * year,
validator=pythia.pyre.inventory.greater(0.0 * year))
relaxationTime.meta['tip'] = "Relaxation time to nondimensionalize time."
# PUBLIC METHODS /////////////////////////////////////////////////////
def __init__(self, name="nondimelasticquasistatic"):
"""
Constructor.
"""
Nondimensional.__init__(self, name)
# PRIVATE METHODS ////////////////////////////////////////////////////
def _configure(self):
"""
Setup members using inventory.
"""
Nondimensional._configure(self)
self.setLengthScale(self.inventory.lengthScale)
self.setPressureScale(self.inventory.shearModulus)
self.setTimeScale(self.inventory.relaxationTime)
self.computeDensityScale()
# FACTORIES ////////////////////////////////////////////////////////////
def nondimensional():
"""
Factory associated with NondimElasticQuasistatic.
"""
return NondimElasticQuasistatic()
# End of file
|
[
"baagaard@usgs.gov"
] |
baagaard@usgs.gov
|
ee7531e0c603f1da58441201aa9edfb6ddd4b581
|
368be25e37bafa8cc795f7c9f34e4585e017091f
|
/.history/app_fav_books/views_20201115164620.py
|
ec1fa1c5ffa54349752a175c646dd05ab409740e
|
[] |
no_license
|
steven-halla/fav_books_proj
|
ebcfbfda0e7f3cdc49d592c86c633b1d331da513
|
512005deb84ac906c9f24d4ab0939bd0db096716
|
refs/heads/master
| 2023-03-30T09:37:38.016063
| 2021-04-02T20:27:22
| 2021-04-02T20:27:22
| 354,125,658
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,513
|
py
|
from django.shortcuts import render, redirect
from .models import *
from django.contrib import messages
# contains user signup + login form
def view_index(request):
# bonus, if user is already logged in, lets not show them login/registration page,
# and instead redirect them to /books, which is already where we redirect users
# after they login/register.
if 'user_id' in request.session:
return redirect("/books")
return render(request, "index.html")
# user signup form will post to a url (/register) which maps to this function
def register_new_user(request):
# returns a dictionary of errors.
# e.g. errors['first_name'] = 'letters only'
errors = User.objects.user_registration_validator(request.POST)
# iterate over each error (key/value) pair in the errors dictionary
# and take the error key and value and makes a full error message,
# and then adds the error message via messages.error()
if len(errors) > 0:
for key, value in errors.items():
error_msg = key + ' - ' + value
messages.error(request, error_msg)
return redirect("/")
else:
first_name_from_post = request.POST['first_name']
last_name_from_post = request.POST['last_name']
email_from_post = request.POST['email']
password_from_post = request.POST['password']
new_user = User.objects.create(
first_name=first_name_from_post,
last_name=last_name_from_post,
email=email_from_post,
password=password_from_post
)
print(new_user.id)
request.session['user_id'] = new_user.id
return redirect('/books')
def login(request):
# user did provide email/password, now lets check database
email_from_post = request.POST['email']
password_from_post = request.POST['password']
# this will return all users that have the email_from_post
# in future we should require email to be unique
users = User.objects.filter(email=email_from_post)
if len(users) == 0:
messages.error(request, "email/password does not exist")
return redirect("/")
user = users[0]
print(user)
# check that the user submitted password is the same as what we have stored in the database
if (user.password != password_from_post):
messages.error(request, "email/password does not exist")
return redirect("/")
# we store the logged in user's id in the session variable,
# so that we can quickly get the current logged in user's id any time we need it in back end functions.
# e.g. view_books when we look up the user by: User.objects.get(id=request.session['user_id'])
# session variables are shared accors all of my requests
# LEARN
request.session['user_id'] = user.id
return redirect("/books")
def logout(request):
request.session.clear()
return redirect("/")
# this will render view_books.html page.
# this page will show a list of all the books and the current logged in user.
def view_books(request):
if 'user_id' not in request.session:
return redirect("/")
user = User.objects.get(id=request.session['user_id'])
all_books_from_db = Books.objects.all()
context = {
"user": user,
"all_books": all_books_from_db
}
return render(request, "view_books.html", context)
# this will render view_book.html page.
# this page will show a single book and the current logged in user.
def view_book(request, book_id):
if 'user_id' not in request.session:
return redirect("/")
user = User.objects.get(id=request.session['user_id'])
book_from_db = Books.objects.get(id=book_id)
context = {
"user": user,
"book": book_from_db
}
print(book_from_db.id)
return render(request, "view_book.html", context)
# adds new book to database that you like
def add_book(request):
if 'user_id' not in request.session:
return redirect("/")
errors = Books.objects.add_book_validator(request.POST)
print(errors)
if len(errors) > 0:
for key, value in errors.items():
error_msg = key + ' - ' + value
messages.error(request, error_msg)
return redirect("/books")
# current logged in user
current_user = User.objects.get(id=request.session['user_id'])
title_from_post = request.POST['title']
description_from_post = request.POST['desc']
book = Books.objects.create(
title=title_from_post,
desc=description_from_post,
uploaded_by_id=current_user.id,
)
print(book)
book.users_who_favorite.add(current_user)
return redirect("/books")
# favorite a book that you did not upload
def favorite_book(request, book_id):
if 'user_id' not in request.session:
return redirect("/")
book_from_db = Books.objects.get(id=book_id)
user_from_db = User.objects.get(id=request.session['user_id'])
# TODO if user has already added book as favorite, just return, don't re-add
book_from_db.users_who_favorite.add(user_from_db)
book_from_db.save()
return redirect("/books/" + str(book_id))
def edit_book(request):
errors = Books.objects.add_book_validator(request.POST)
if len(errors) > 0:
for key, value in errors.items():
messages.error(request, value)
return redirect("/books/" + str(book_id) + "/edit")
book_to_update = Books.objects.get(id=book)
|
[
"69405488+steven-halla@users.noreply.github.com"
] |
69405488+steven-halla@users.noreply.github.com
|
57651bd056392553b7461799fcdab49cd38ccc3f
|
c21960247829b620d0e36a3408ef8099d248c742
|
/cirq/protocols/equal_up_to_global_phase.py
|
a6db82844732657e2d5140fb5820451d2b01ddff
|
[
"Apache-2.0"
] |
permissive
|
iamvamsikrishnad/Cirq
|
ce1439853c9172690e3340fec70b47fd5614e2d1
|
4bec5447242c0d06f773a075383eea9dae0eebd3
|
refs/heads/master
| 2020-06-06T06:15:10.526041
| 2019-06-19T02:32:58
| 2019-06-19T02:32:58
| 192,661,193
| 1
| 0
|
Apache-2.0
| 2019-06-19T04:57:38
| 2019-06-19T04:57:38
| null |
UTF-8
|
Python
| false
| false
| 4,248
|
py
|
# Copyright 2019 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from collections import Iterable
import numbers
from typing import Any, Union
import numpy as np
from typing_extensions import Protocol
import cirq
class SupportsEqualUpToGlobalPhase(Protocol):
"""Object which can be compared for equality mod global phase."""
def _equal_up_to_global_phase_(self, other: Any, *,
atol: Union[int, float]) -> bool:
"""Approximate comparator.
Types implementing this protocol define their own logic for comparison
with other types.
Args:
other: Target object for comparison of equality up to global phase.
atol: The minimum absolute tolerance. See `np.isclose()`
documentation for details.
Returns:
True if objects are equal up to a global phase, False otherwise.
Returns NotImplemented when checking equality up to a global phase
is not implemented for given types.
"""
def equal_up_to_global_phase(val: Any,
other: Any,
*,
atol: Union[int, float] = 1e-8) -> bool:
"""Determine whether two objects are equal up to global phase.
If `val` implements a `_equal_up_to_global_phase_` method then it is
invoked and takes precedence over all other checks:
- For complex primitive type the magnitudes of the values are compared.
- For `val` and `other` both iterable of the same length, consecutive
elements are compared recursively. Types of `val` and `other` does not
necessarily needs to match each other. They just need to be iterable and
have the same structure.
- For all other types, fall back to `_approx_eq_`
Args:
val: Source object for approximate comparison.
other: Target object for approximate comparison.
atol: The minimum absolute tolerance. This places an upper bound on
the differences in *magnitudes* of two compared complex numbers.
Returns:
True if objects are approximately equal up to phase, False otherwise.
"""
# Attempt _equal_up_to_global_phase_ for val.
eq_up_to_phase_getter = getattr(val, '_equal_up_to_global_phase_', None)
if eq_up_to_phase_getter is not None:
result = eq_up_to_phase_getter(other, atol)
if result is not NotImplemented:
return result
# Fall back to _equal_up_to_global_phase_ for other.
other_eq_up_to_phase_getter = getattr(other, '_equal_up_to_global_phase_',
None)
if other_eq_up_to_phase_getter is not None:
result = other_eq_up_to_phase_getter(val, atol)
if result is not NotImplemented:
return result
# Fall back to special check for numeric arrays.
# Defer to numpy automatic type casting to determine numeric type.
if isinstance(val, Iterable) and isinstance(other, Iterable):
a = np.asarray(val)
b = np.asarray(other)
if a.dtype.kind in 'uifc' and b.dtype.kind in 'uifc':
return cirq.linalg.allclose_up_to_global_phase(a, b, atol=atol)
# Fall back to approx_eq for compare the magnitude of two numbers.
if isinstance(val, numbers.Number) and isinstance(other, numbers.Number):
result = cirq.approx_eq(abs(val), abs(other), atol=atol) # type: ignore
if result is not NotImplemented:
return result
# Fall back to cirq approx_eq for remaining types.
return cirq.approx_eq(val, other, atol=atol)
|
[
"craiggidney+github+cirqbot@google.com"
] |
craiggidney+github+cirqbot@google.com
|
b5fd20af137de58b757e8b55bfffde6aa2cc80f8
|
ee8c4c954b7c1711899b6d2527bdb12b5c79c9be
|
/assessment2/amazon/run/core/controllers/unwieldy.py
|
30434fbf85008b2c83c8b9159fa9d0a2baf010fe
|
[] |
no_license
|
sqlconsult/byte
|
02ac9899aebea4475614969b594bfe2992ffe29a
|
548f6cb5038e927b54adca29caf02c981fdcecfc
|
refs/heads/master
| 2021-01-25T14:45:42.120220
| 2018-08-11T23:45:31
| 2018-08-11T23:45:31
| 117,135,069
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 370
|
py
|
#!/usr/bin/env python3
from flask import Blueprint, Flask, render_template, request, url_for
controller = Blueprint('unwieldy', __name__, url_prefix='/unwieldy')
# @controller.route('/<string:title>', methods=['GET'])
# def lookup(title):
# if title == 'Republic': # TODO 2
# return render_template('republic.html') # TODO 2
# else:
# pass
|
[
"sqlconsult@hotmail.com"
] |
sqlconsult@hotmail.com
|
513441ca0605b94e533042b091aea4e190179b11
|
23a0130020e00bf09dbf9e158460ed3534adddba
|
/Main.py
|
155f306f28acf1e00c4b54d05604fb7743806502
|
[] |
no_license
|
Smikhalcv/diplom_adpy-10
|
f6923e1e6ad3c99faa0eba294050448affca5737
|
072a69b95e821c2804966fc21f6214f274573206
|
refs/heads/master
| 2022-10-14T16:59:43.901261
| 2020-06-11T22:02:16
| 2020-06-11T22:02:16
| 260,189,471
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,161
|
py
|
from User.get_token import Token
from User.user_id import id_user
from search_peoples import Search
from mongo_db import Mongo_DB
from executor import get_result
if __name__ in '__main__':
database = Mongo_DB('VKinder')
database.create_db()
token = Token()
access_token = token.read_token()
user_id = str(id_user(access_token))
if user_id in database.show_coll():
print('По данному пользователю уже проводился поиск, начать новый? (да/нет)')
print('(при выборе нет, продолжит чтение из старого поиска)')
flag = input('- ')
if flag.lower().startswith('д'):
user = Search(access_token, user_id)
user.change_parametr()
value_compability = user.compability()
get_result(access_token, user_id)
else:
get_result(access_token, user_id)
if user_id not in database.show_coll():
user = Search(access_token, user_id)
user.change_parametr()
value_compability = user.compability()
get_result(access_token, user_id)
|
[
"Smikhalcv@yandex.ru"
] |
Smikhalcv@yandex.ru
|
c6e7a41f411c28428cdffda9d8489491dfb15727
|
cce6364dd85b62782671cd8048873eede2045137
|
/primary/3_isPalindrome.py
|
499cab542bacb21c2fb831b1a52c66aa1c3dc427
|
[] |
no_license
|
gmt710/leetcode_python
|
ed647958440f66583b8717dae7bca49c516984da
|
441623afee3713506b702c5fd462c7ba84b48442
|
refs/heads/master
| 2020-03-28T05:11:02.851792
| 2019-04-17T09:14:51
| 2019-04-17T09:14:51
| 147,761,046
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 479
|
py
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
q = []
while(head):
q.append(head.val)
head = head.next
if q == q[::-1]:
return True
else:
return False
|
[
"noreply@github.com"
] |
gmt710.noreply@github.com
|
2592d28fb5f3680d1324df3073feaa1e5934d16e
|
960b3a17a4011264a001304e64bfb76d669b8ac5
|
/mstrio/utils/formjson.py
|
1a7443b172fcf930301b16b20e88b803adfcb11c
|
[
"Apache-2.0"
] |
permissive
|
MicroStrategy/mstrio-py
|
012d55df782a56dab3a32e0217b9cbfd0b59b8dd
|
c6cea33b15bcd876ded4de25138b3f5e5165cd6d
|
refs/heads/master
| 2023-08-08T17:12:07.714614
| 2023-08-03T12:30:11
| 2023-08-03T12:30:11
| 138,627,591
| 84
| 60
|
Apache-2.0
| 2023-07-31T06:43:33
| 2018-06-25T17:23:55
|
Python
|
UTF-8
|
Python
| false
| false
| 2,139
|
py
|
def _map_data_type(datatype):
if datatype == 'object':
return "STRING"
elif datatype in ['int64', 'int32']:
return "INTEGER"
elif datatype in ['float64', 'float32']:
return "DOUBLE"
elif datatype == 'bool':
return "BOOL"
elif datatype == 'datetime64[ns]':
return 'DATETIME'
def formjson(df, table_name, as_metrics=None, as_attributes=None):
def _form_column_headers(_col_names, _col_types):
return [{'name': n, 'dataType': t} for n, t in zip(_col_names, _col_types)]
def _form_attribute_list(_attributes):
return [
{
'name': n,
'attributeForms': [
{
'category': 'ID',
'expressions': [{'formula': table_name + "." + n}],
}
],
}
for n in _attributes
]
def _form_metric_list(_metrics):
return [
{
'name': n,
'dataType': 'number',
'expressions': [{'formula': table_name + "." + n}],
}
for n in _metrics
]
col_names = list(df.columns)
col_types = list(map(_map_data_type, list(df.dtypes.values)))
# Adjust attributes/metrics mapping if new mappings were provided in
# as_metrics and as_attributes
attributes = []
metrics = []
for _name, _type in zip(col_names, col_types):
if _type in ['DOUBLE', 'INTEGER']: # metric
if as_attributes is not None and _name in as_attributes:
attributes.append(_name)
else:
metrics.append(_name)
else: # attribute
if as_metrics is not None and _name in as_metrics:
metrics.append(_name)
else:
attributes.append(_name)
column_headers = _form_column_headers(_col_names=col_names, _col_types=col_types)
attribute_list = _form_attribute_list(_attributes=attributes)
metric_list = _form_metric_list(_metrics=metrics)
return column_headers, attribute_list, metric_list
|
[
"noreply@github.com"
] |
MicroStrategy.noreply@github.com
|
8079e7c0070fb7f2259f0841bdbfdf4061c16d82
|
08bfc8a1f8e44adc624d1f1c6250a3d9635f99de
|
/SDKs/swig/Examples/test-suite/python/overload_numeric_runme.py
|
5c80fb9fa3daff4ae841ab619589410a4f917df7
|
[] |
no_license
|
Personwithhat/CE_SDKs
|
cd998a2181fcbc9e3de8c58c7cc7b2156ca21d02
|
7afbd2f7767c9c5e95912a1af42b37c24d57f0d4
|
refs/heads/master
| 2020-04-09T22:14:56.917176
| 2019-07-04T00:19:11
| 2019-07-04T00:19:11
| 160,623,495
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 129
|
py
|
version https://git-lfs.github.com/spec/v1
oid sha256:d59bc759f2c6bc1cca8b0a8bc70aca5b1e64ce1a52153ed569bfe234315d4512
size 1317
|
[
"personwithhats2@Gmail.com"
] |
personwithhats2@Gmail.com
|
931602884d1cb512161cc9ce477f276bbb8c1cfa
|
981f1a81ba19baa36bcb109d55ee8e7520fe5aca
|
/Orm_test.py
|
4ae2a3d305124b2e735345ed8a1505038ff06f51
|
[] |
no_license
|
Pythondeveloper6/Library-System-Python-PyQt5
|
6f1a43bdeae0d4689ed5da1f6710e7211dae52fd
|
28971eb5232d2f42de12fb396abacda12b4d3c65
|
refs/heads/master
| 2020-09-15T09:41:34.853547
| 2020-07-01T18:30:15
| 2020-07-01T18:30:15
| 223,413,327
| 24
| 14
| null | 2019-12-22T12:21:16
| 2019-11-22T13:48:48
|
Python
|
UTF-8
|
Python
| false
| false
| 621
|
py
|
from peewee import *
# db = SqliteDatabase('people.db')
# Connect to a MySQL database on network.
db = MySQLDatabase('myapp', user='root', password='toor',
host='localhost', port=3306)
class Person(Model):
name = CharField()
birthday = DateField()
class Meta:
database = db # This model uses the "people.db" database.
class Pet(Model):
owner = ForeignKeyField(Person, backref='pets')
name = CharField()
animal_type = CharField()
class Meta:
database = db # this model uses the "people.db" database
db.connect()
db.create_tables([Pet , Person])
|
[
"pythondeveloper6@gmail.com"
] |
pythondeveloper6@gmail.com
|
1136c6923f5b46ab2360eb4494b1157796fcccb7
|
d83118503614bb83ad8edb72dda7f449a1226f8b
|
/src/dprj/platinumegg/app/cabaret/views/mgr/model_edit/gacha_header.py
|
2db815f7f6f2334c265f0fe81fb7afe0a57ec6a9
|
[] |
no_license
|
hitandaway100/caba
|
686fe4390e182e158cd9714c90024a082deb8c69
|
492bf477ac00c380f2b2758c86b46aa7e58bbad9
|
refs/heads/master
| 2021-08-23T05:59:28.910129
| 2017-12-03T19:03:15
| 2017-12-03T19:03:15
| 112,512,044
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,372
|
py
|
# -*- coding: utf-8 -*-
from platinumegg.app.cabaret.views.mgr.model_edit import AdminModelEditHandler,\
AppModelForm, ModelEditValidError, AppModelChoiceField
from defines import Defines
from platinumegg.app.cabaret.models.Gacha import GachaHeaderMaster, GachaMaster
class Handler(AdminModelEditHandler):
"""マスターデータの操作.
"""
class Form(AppModelForm):
class Meta:
model = GachaHeaderMaster
exclude = (
Defines.MASTER_EDITTIME_COLUMN,
)
id = AppModelChoiceField(GachaMaster, required=False, label=u'ガチャID')
def setting_property(self):
self.MODEL_LABEL = u'引抜のヘッダー画像設定'
self.html_param['Defines'] = Defines
def __valid_master(self, master):
if not master.is_public:
return
if not isinstance(master.header, list):
raise ModelEditValidError(u'headerのJSONが壊れています.master=%d' % master.id)
# elif len(master.header) == 0:
# raise ModelEditValidError(u'空のheaderが設定されています.master=%d' % master.id)
def valid_insert(self, master):
self.__valid_master(master)
def valid_update(self, master):
self.__valid_master(master)
def main(request):
return Handler.run(request)
|
[
"shangye@mail.com"
] |
shangye@mail.com
|
841c6046c5b6b37c26338a127242921eb0a5ea05
|
2bbc7ba3ecdb54feffa446ed50297432f249e3dc
|
/tests/test_addons/test_addon_mtext.py
|
3aec15c652a5c501ee0432a626c758f40b8ebcd8
|
[
"MIT"
] |
permissive
|
stephenthoma/ezdxf
|
16f7b06e43bad55ccf96387e22b68fd624a5d8fb
|
5cb1fb0298707d69d1b039858523b97990d85fba
|
refs/heads/master
| 2020-04-04T11:59:42.480375
| 2018-04-02T05:01:49
| 2018-04-02T05:01:49
| 155,910,581
| 0
| 0
|
NOASSERTION
| 2018-11-02T19:07:21
| 2018-11-02T19:07:21
| null |
UTF-8
|
Python
| false
| false
| 4,379
|
py
|
# Created: 09.03.2010, 2018 adapted for ezdxf
# Copyright (C) 2010-2018, Manfred Moitzi
# License: MIT License
from __future__ import unicode_literals
__author__ = "mozman <me@mozman.at>"
import pytest
import ezdxf
from ezdxf.addons import MText
@pytest.fixture(scope='module')
def dxf():
return ezdxf.new('R12')
def test_horiz_top(dxf):
layout = dxf.blocks.new('test_horiz_top')
text = "lineA\nlineB"
mtext = MText(text, (0., 0., 0.), 1.0)
mtext.render(layout)
assert len(layout) == 2
lines = list(layout)
assert lines[0].dxftype() == 'TEXT'
assert lines[1].dxftype() == 'TEXT'
assert lines[0].dxf.text == 'lineA'
assert lines[1].dxf.text == 'lineB'
assert lines[0].dxf.align_point == (0, 0, 0)
assert lines[1].dxf.align_point == (0, -1, 0)
assert lines[0].dxf.valign == MText.TOP
assert lines[0].dxf.halign == MText.LEFT
def test_horiz_bottom(dxf):
layout = dxf.blocks.new('test_horiz_bottom')
text = "lineA\nlineB"
mtext = MText(text, (0., 0., 0.), 1.0, align='BOTTOM_LEFT')
mtext.render(layout)
assert len(layout) == 2
lines = list(layout)
assert lines[0].dxftype() == 'TEXT'
assert lines[1].dxftype() == 'TEXT'
assert lines[0].dxf.text == 'lineA'
assert lines[1].dxf.text == 'lineB'
assert lines[0].dxf.align_point == (0, 1, 0)
assert lines[1].dxf.align_point == (0, 0, 0)
assert lines[0].dxf.valign == MText.BOTTOM
assert lines[0].dxf.halign == MText.LEFT
def test_horiz_middle(dxf):
layout = dxf.blocks.new('test_horiz_middle')
text = "lineA\nlineB"
mtext = MText(text, (0., 0., 0.), 1.0, align='MIDDLE_LEFT')
mtext.render(layout)
assert len(layout) == 2
lines = list(layout)
assert lines[0].dxftype() == 'TEXT'
assert lines[1].dxftype() == 'TEXT'
assert lines[0].dxf.text == 'lineA'
assert lines[1].dxf.text == 'lineB'
assert lines[0].dxf.align_point == (0, .5, 0)
assert lines[1].dxf.align_point == (0, -.5, 0)
assert lines[0].dxf.valign == MText.MIDDLE
assert lines[0].dxf.halign == MText.LEFT
def test_45deg_top(dxf):
layout = dxf.blocks.new('test_45deg_top')
text = "lineA\nlineB\nlineC"
mtext = MText(text, (0., 0., 0.), 1.0, align='TOP_LEFT', rotation=45)
mtext.render(layout)
assert len(layout) == 3
lines = list(layout)
assert lines[0].dxftype() == 'TEXT'
assert lines[1].dxftype() == 'TEXT'
assert lines[2].dxftype() == 'TEXT'
assert lines[0].dxf.text == 'lineA'
assert lines[1].dxf.text == 'lineB'
assert lines[2].dxf.text == 'lineC'
assert lines[0].dxf.align_point == (0, 0, 0)
assert lines[1].dxf.align_point == (0.707107, -0.707107, 0)
assert lines[2].dxf.align_point == (1.414214, -1.414214, 0)
assert lines[0].dxf.rotation == 45
assert lines[0].dxf.valign == MText.TOP
assert lines[0].dxf.halign == MText.LEFT
def test_45deg_bottom(dxf):
layout = dxf.blocks.new('test_45deg_top')
text = "lineA\nlineB\nlineC"
mtext = MText(text, (0., 0., 0.), 1.0, align='BOTTOM_LEFT', rotation=45)
mtext.render(layout)
assert len(layout) == 3
lines = list(layout)
assert lines[0].dxftype() == 'TEXT'
assert lines[1].dxftype() == 'TEXT'
assert lines[2].dxftype() == 'TEXT'
assert lines[0].dxf.text == 'lineA'
assert lines[1].dxf.text == 'lineB'
assert lines[2].dxf.text == 'lineC'
assert lines[0].dxf.align_point == (-1.414214, 1.414214, 0)
assert lines[1].dxf.align_point == (-0.707107, 0.707107, 0)
assert lines[2].dxf.align_point == (0, 0, 0)
assert lines[0].dxf.rotation == 45
assert lines[0].dxf.valign == MText.BOTTOM
assert lines[0].dxf.halign == MText.LEFT
def test_one_liner(dxf):
layout = dxf.blocks.new('test_one_liner')
text = "OneLine"
mtext = MText(text, (0., 0., 0.))
mtext.render(layout)
assert len(layout) == 1
lines = list(layout)
assert lines[0].dxftype() == 'TEXT'
assert lines[0].dxf.align_point == (0, 0, 0)
assert lines[0].dxf.valign == MText.TOP
assert lines[0].dxf.halign == MText.LEFT
def test_get_attribute_by_subscript():
mtext = MText("Test\nTest", (0, 0))
layer = mtext['layer']
assert layer == mtext.layer
def test_set_attribute_by_subscript():
mtext = MText("Test\nTest", (0, 0))
mtext['layer'] = "modified"
assert mtext.layer == "modified"
|
[
"mozman@gmx.at"
] |
mozman@gmx.at
|
48c65b2c68ce49ed81e4e99de686a1e06dc4d029
|
f0d713996eb095bcdc701f3fab0a8110b8541cbb
|
/Fe6wvtjcNFwuANuLu_17.py
|
2edae5acef2d0784cbb3e57f8f1de8dc2e9a243d
|
[] |
no_license
|
daniel-reich/turbo-robot
|
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
|
a7a25c63097674c0a81675eed7e6b763785f1c41
|
refs/heads/main
| 2023-03-26T01:55:14.210264
| 2021-03-23T16:08:01
| 2021-03-23T16:08:01
| 350,773,815
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,088
|
py
|
"""
A game of table tennis almost always sounds like _Ping!_ followed by _Pong!_
Therefore, you know that Player 2 has won if you hear _Pong!_ as the last
sound (since Player 1 didn't return the ball back).
Given a list of _Ping!_ , create a function that inserts _Pong!_ in between
each element. Also:
* If `win` equals `True`, end the list with _Pong!_.
* If `win` equals `False`, end with _Ping!_ instead.
### Examples
ping_pong(["Ping!"], True) ➞ ["Ping!", "Pong!"]
ping_pong(["Ping!", "Ping!"], False) ➞ ["Ping!", "Pong!", "Ping!"]
ping_pong(["Ping!", "Ping!", "Ping!"], True) ➞ ["Ping!", "Pong!", "Ping!", "Pong!", "Ping!", "Pong!"]
### Notes
* You will always return the ball (i.e. the Pongs are yours).
* Player 1 serves the ball and makes _Ping!_.
* Return a list of strings.
"""
def ping_pong(lst, win):
l=[]
if win:
for i in range(len(lst)):
l.append("Ping!")
l.append("Pong!")
return l
else:
for i in range(len(lst)):
l.append("Ping!")
l.append("Pong!")
l.pop(-1)
return l
|
[
"daniel.reich@danielreichs-MacBook-Pro.local"
] |
daniel.reich@danielreichs-MacBook-Pro.local
|
16d79f6a693248f707912d0602e5b5898033423f
|
60a525218779f250d725ca4f9677bd626eb687b9
|
/repos/system_upgrade/common/actors/checkfips/tests/unit_test_checkfips.py
|
7774352e00b1e0a332de81aef86c509fa0641ce8
|
[
"Apache-2.0"
] |
permissive
|
examon/leapp-repository
|
920c9246540a2c603c7c9dfcbf9ae3673487f221
|
4cedc35b45aeb9131a651c8362f5ff4d89e3b5ee
|
refs/heads/master
| 2023-02-24T09:33:10.280795
| 2023-02-01T10:05:25
| 2023-02-06T11:03:38
| 169,085,644
| 0
| 0
|
Apache-2.0
| 2020-02-24T09:56:34
| 2019-02-04T13:52:38
|
Python
|
UTF-8
|
Python
| false
| false
| 1,403
|
py
|
import pytest
from leapp.models import KernelCmdline, KernelCmdlineArg, Report
from leapp.snactor.fixture import current_actor_context
ballast1 = [KernelCmdlineArg(key=k, value=v) for k, v in [
('BOOT_IMAGE', '/vmlinuz-3.10.0-1127.el7.x86_64'),
('root', '/dev/mapper/rhel_ibm--p8--kvm--03--guest--02-root'),
('ro', ''),
('console', 'tty0'),
('console', 'ttyS0,115200'),
('rd_NO_PLYMOUTH', '')]]
ballast2 = [KernelCmdlineArg(key=k, value=v) for k, v in [
('crashkernel', 'auto'),
('rd.lvm.lv', 'rhel_ibm-p8-kvm-03-guest-02/root'),
('rd.lvm.lv', 'rhel_ibm-p8-kvm-03-guest-02/swap'),
('rhgb', ''),
('quiet', ''),
('LANG', 'en_US.UTF-8')]]
@pytest.mark.parametrize('parameters,expected_report', [
([], False),
([KernelCmdlineArg(key='fips', value='')], False),
([KernelCmdlineArg(key='fips', value='0')], False),
([KernelCmdlineArg(key='fips', value='1')], True),
([KernelCmdlineArg(key='fips', value='11')], False),
([KernelCmdlineArg(key='fips', value='yes')], False)
])
def test_check_fips(current_actor_context, parameters, expected_report):
cmdline = KernelCmdline(parameters=ballast1+parameters+ballast2)
current_actor_context.feed(cmdline)
current_actor_context.run()
if expected_report:
assert current_actor_context.consume(Report)
else:
assert not current_actor_context.consume(Report)
|
[
"xstodu05@gmail.com"
] |
xstodu05@gmail.com
|
d4dfd3cbda727e702637ff99d4c9cb5e3d6eca6d
|
53fab060fa262e5d5026e0807d93c75fb81e67b9
|
/backup/user_014/ch167_2020_06_22_20_37_54_917135.py
|
a99f1260d35132010fb4d2db003a6410b59fc2c4
|
[] |
no_license
|
gabriellaec/desoft-analise-exercicios
|
b77c6999424c5ce7e44086a12589a0ad43d6adca
|
01940ab0897aa6005764fc220b900e4d6161d36b
|
refs/heads/main
| 2023-01-31T17:19:42.050628
| 2020-12-16T05:21:31
| 2020-12-16T05:21:31
| 306,735,108
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 276
|
py
|
def bairro_mais_custoso(gastos):
saida_1 = {}
saida_2 = {}
for x,y in gastos.items():
saida_1[x] = y[6:12]
for a,b in saida.items():
saida_2[a] = sum(b)
for i,j in saida_2.items():
if j == max(saida_2.values()):
return i
|
[
"you@example.com"
] |
you@example.com
|
9309569dbb1a25d10ac57786f2e48786252a6ec1
|
05ace8ef6257681ae5b677ad1fcfceb316c5fd24
|
/moshmosh/repl_apis.py
|
99b0530c2b6116c52020d0369353a87b90d1a9da
|
[
"MIT"
] |
permissive
|
thautwarm/moshmosh
|
cb0e5c2cc7c00886ec5f400629185f32cbe4e8c7
|
12435ac6288e88b42ea13d59825b90b37e297f38
|
refs/heads/master
| 2022-01-09T01:50:34.333840
| 2020-05-29T01:19:40
| 2020-05-29T01:19:40
| 196,604,714
| 120
| 7
|
MIT
| 2022-01-01T03:36:27
| 2019-07-12T15:39:55
|
Python
|
UTF-8
|
Python
| false
| false
| 4,289
|
py
|
from moshmosh.extension import *
from moshmosh.extension import _extension_pragma_re_u
def update_pragmas(extension_builder: t.Dict[object, Extension], lines):
"""
Traverse the source codes and extract out the scope of
every extension. Incrementally.
"""
# bind to local for faster visiting in the loop
extension_pragma_re = _extension_pragma_re_u
registered = Registered.extensions
# for new cells of IPython, refresh the scoping info
# of the extensions
for ext in extension_builder.values():
intervals = ext.activation.intervals
if intervals:
last = intervals.pop()
intervals.clear()
if type(last) is int:
intervals.append(0)
for i, line in enumerate(lines):
pragma = extension_pragma_re.match(line)
if pragma:
pragma = pragma.groupdict()
action = pragma['action']
extension = pragma['ext']
params = pragma['params'] or ''
params = (param.strip() for param in params.split(','))
params = tuple(i for i in params if i)
try:
ext_cls = registered[extension]
except KeyError:
# TODO: add source code position info
raise ExtensionNotFoundError(extension)
key = (ext_cls, params)
ext = extension_builder.get(key, None)
if ext is None:
try:
ext = extension_builder[key] = ext_cls(*params)
except Exception as e:
raise
lineno = i + 1
if action == "+":
ext.activation.enable(lineno)
else:
ext.activation.disable(lineno)
return list(extension_builder.values())
def perform_extension_incr(
extension_builder: t.Dict[object, Extension],
source_code,
filename
):
str_type = type(source_code)
node = ast.parse(source_code, filename)
if str_type is bytes:
source_code = source_code.decode('utf8')
extensions = update_pragmas(extension_builder, StringIO(source_code))
extensions = sum(map(list, solve_deps(extensions)), [])
string_io = StringIO()
for each in extensions:
each.pre_rewrite_src(string_io)
for each in extensions:
node = each.rewrite_ast(node)
ast.fix_missing_locations(node)
literal = ast_to_literal(node)
string_io.write("import ast as _ast\n")
string_io.write("from moshmosh.rewrite_helper import literal_to_ast as _literal_to_ast\n")
string_io.write('\n')
string_io.write('__literal__ = ')
string_io.write(repr(literal))
string_io.write('\n')
string_io.write("__ast__ = _literal_to_ast(__literal__)\n")
string_io.write('__code__ = compile')
string_io.write('(__ast__, ')
string_io.write('__import__("os").path.abspath("") if __name__ == "__main__" else __file__,')
string_io.write('"exec")\n')
string_io.write('exec(__code__, globals())\n')
for each in extensions:
each.post_rewrite_src(string_io)
code = string_io.getvalue()
if str_type is bytes:
code = bytes(code, encoding='utf8')
return code
class IPythonSupport:
def __init__(self, builder: t.Dict[object, Extension]):
self.builder = builder
self.tmp_exts = None
def input_transform(self, lines):
self.tmp_exts = update_pragmas(self.builder, lines)
return lines
def ast_transform(self, node):
extensions = self.tmp_exts
extensions = sum(map(list, solve_deps(extensions)), [])
prev_io = StringIO()
for each in extensions:
each.pre_rewrite_src(prev_io)
prev_io.write("import ast as _ast\n")
prev_io.write("from moshmosh.rewrite_helper import literal_to_ast as _literal_to_ast\n")
prev_stmts = ast.parse(prev_io.getvalue()).body
for each in extensions:
node = each.rewrite_ast(node)
ast.fix_missing_locations(node)
post_io = StringIO()
for each in extensions:
each.post_rewrite_src(post_io)
post_stmts = ast.parse(post_io.getvalue()).body
node.body = prev_stmts + node.body + post_stmts
return node
|
[
"twshere@outlook.com"
] |
twshere@outlook.com
|
b150aea66bc591e189b33cf0d8f0aa9d5350afed
|
8ae16d0b53f3b70adab41b307d30148a3b7b6133
|
/csv_read.py
|
56bc1dfd50fa8a983b42d8ad2391437544c4817f
|
[] |
no_license
|
maiorem/python_dataAnalysis
|
415af6fe401b76e623ba6c336e027d053d8dccc5
|
a2eb45bfcfb9ed3ae2533c021de1e8537bf2f563
|
refs/heads/main
| 2023-03-31T09:28:28.664694
| 2021-04-04T06:40:02
| 2021-04-04T06:40:02
| 354,154,214
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 777
|
py
|
line_counter=0
data_header=[]
employee=[]
customer_USA_only_list=[]
customer=None
with open('customers.csv') as customer_data :
while 1:
data=customer_data.readline()
if not data : break
if line_counter==0 :
data_header=data.split(",")
else :
customer=data.split(",")
if customer[10].upper()=="USA":
customer_USA_only_list.append(customer)
line_counter+=1
print("Header : ", data_header)
for i in range(0, 10) :
print("Data", customer_USA_only_list[i])
print(len(customer_USA_only_list))
with open("customer_USA_only.csv", "w") as customer_USA_only_csv :
for customer in customer_USA_only_list :
customer_USA_only_csv.write(",".join(customer).strip('\n')+"\n")
|
[
"maiorem00@gmail.com"
] |
maiorem00@gmail.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.