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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5472dd53d9f8c1cf0e8181de52297ae189580ff9 | f83f053278a036e18466d85585bc03a28c0f140a | /xsdata/codegen/handlers/attribute_restrictions.py | cf27e1d0045aaf0e265180f2ea1987505d025f1c | [
"MIT"
] | permissive | finswimmer/xsdata | dd951124e378bf9f4d8bd6939e4ebe542c677ee2 | eed822b83f362f48561a7d116e181a5422ff52dd | refs/heads/master | 2023-05-05T21:16:20.693559 | 2021-05-31T16:11:44 | 2021-05-31T16:33:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,481 | py | from xsdata.codegen.mixins import HandlerInterface
from xsdata.codegen.models import Attr
from xsdata.codegen.models import Class
class AttributeRestrictionsHandler(HandlerInterface):
"""Sanitize attributes restrictions."""
__slots__ = ()
def process(self, target: Class):
for index, attr in enumerate(target.attrs):
self.reset_occurrences(attr)
self.reset_sequential(target, index)
@classmethod
def reset_occurrences(cls, attr: Attr):
"""Sanitize attribute required flag by comparing the min/max
occurrences restrictions."""
restrictions = attr.restrictions
min_occurs = restrictions.min_occurs or 0
max_occurs = restrictions.max_occurs or 0
if attr.is_attribute:
restrictions.min_occurs = None
restrictions.max_occurs = None
elif attr.is_tokens:
restrictions.required = None
if max_occurs <= 1:
restrictions.min_occurs = None
restrictions.max_occurs = None
elif attr.xml_type is None or min_occurs == max_occurs == 1:
restrictions.required = True
restrictions.min_occurs = None
restrictions.max_occurs = None
elif min_occurs == 0 and max_occurs < 2:
restrictions.required = None
restrictions.min_occurs = None
restrictions.max_occurs = None
attr.default = None
attr.fixed = False
else: # max_occurs > 1
restrictions.min_occurs = min_occurs
restrictions.required = None
attr.fixed = False
if attr.default or attr.fixed or attr.restrictions.nillable:
restrictions.required = None
@classmethod
def reset_sequential(cls, target: Class, index: int):
"""Reset the attribute at the given index if it has no siblings with
the sequential restriction."""
attr = target.attrs[index]
before = target.attrs[index - 1] if index - 1 >= 0 else None
after = target.attrs[index + 1] if index + 1 < len(target.attrs) else None
if not attr.is_list:
attr.restrictions.sequential = False
if (
not attr.restrictions.sequential
or (before and before.restrictions.sequential)
or (after and after.restrictions.sequential and after.is_list)
):
return
attr.restrictions.sequential = False
| [
"tsoulloftas@gmail.com"
] | tsoulloftas@gmail.com |
54bb59e1aa9b8b756b91237113e05b4270ca5bfe | f57529f95a0fd10676f46063fdcd273fb5a81427 | /boj/01001-02000/1914.py | 75afdaa28e8b881d375944ecb481c5e5941ab8cb | [] | no_license | hoyasmh/PS | a9b83b0044e483586590c9b7c6bf8a77236b67e7 | 6bbaa0ce77b2726f6af782af049d73720820f761 | refs/heads/master | 2023-04-23T10:43:27.349785 | 2021-05-17T13:43:53 | 2021-05-17T13:43:53 | 311,239,034 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 419 | py | def h(n,a,b,c):
if n>0:
h(n-1,a,c,b)
print(a,c)
h(n-1,b,a,c)
s=int(input())
print(2**s-1)
h(s,1,2,3)
# def hanoi(n, a, b, c):
# if n > 0:
# hanoi(n - 1, a, c, b)
# print("%d번 원반을 %c에서 %c로 옮김"%(n, a, b))
# hanoi(n - 1, c, b, a)
#
# if __name__ == "__main__":
# print("원반의 갯수 : ")
# n = int(input())
# hanoi(n,'a','b','c')
| [
"hoyasmh@gmail.com"
] | hoyasmh@gmail.com |
08337b0bd47f2c40824bf33ed5cfb498412f19f5 | 1c21fa248091e31c362b95afafc5021211e85e63 | /invensis_pmc/inhouseapp/utils/decorators.py | ef84ceff1a3d3226cd385ba8f8ac51b6bf89d02d | [] | no_license | anudeepnaidu95/dev5 | 3d3252a51fccbb794e78a91681708e1b3c1ce0d4 | 7351244b79be242aa2cad36dbe1adca22a744edc | refs/heads/master | 2021-01-20T12:28:07.286078 | 2017-05-05T11:08:37 | 2017-05-05T11:08:37 | 90,365,863 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,662 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import timeit
import jsonpickle
from django.utils import six
from django.core.exceptions import PermissionDenied
from django.contrib.auth.decorators import user_passes_test
from django.core.urlresolvers import reverse
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import redirect
from django.utils.translation import ugettext_lazy as _
from django.contrib import messages
def log(fn):
"""
Logger decorator.
Logs function Executing and Executed info and total Executed Time.
"""
def wrapper(*args, **kwargs):
# Get information about executing function
function_name = "'(%(type)s) %(module)s.%(name)s'" % \
{'module': fn.__module__, 'type': fn.__class__.__name__, 'name': fn.__name__}
# Log about start of the function
settings.LOGIC_LOGGER.info('Start %s', function_name)
# Function start time
start = timeit.default_timer()
# Executing function itself
fn_result = fn(*args, **kwargs)
# Function end time
stop = timeit.default_timer()
# Calculate function executing time
time = stop - start
# Log about end of the function
settings.LOGIC_LOGGER.info('End %s in %.5f SECs', function_name, time)
return fn_result
return wrapper
def json(fn):
"""
Gets view method response and returns it in JSON format.
"""
def wrapper(request, *args, **kwargs):
try:
# Executing function itself
fn_result = fn(request, *args, **kwargs)
# Prepare JSON dictionary for successful result
json_result = {'is_successful': True, 'result': fn_result}
except Exception as e:
# If AJAX_DEBUG is enabled raise exception
if settings.JSON_DEBUG:
raise
# Else prepare JSON result object with error message
error_message = e.message.upper()
json_result = {'is_successful': False, 'message': error_message}
# Wrap result with JSON HTTPResponse and return
return HttpResponse(jsonpickle.encode(json_result, unpicklable=False), content_type='application/json')
return wrapper
def anonymous_required(function):
"""
Check either user registered or not. If it is already registered user will redirect to 'INDEX'.
"""
def wrap(request, *args, **kwargs):
user = request.user
if user.is_authenticated():
messages.add_message(request, messages.ERROR, _('You are already registered and logged in.'))
return redirect(reverse('home'))
else:
return function(request, *args, **kwargs)
return wrap
def group_required(group, login_url=None, raise_exception=False):
"""
Decorator for views that checks whether a user has a group permission,
redirecting to the log-in page if necessary.
If the raise_exception parameter is given the PermissionDenied exception
is raised.
"""
def check_perms(user):
if isinstance(group, six.string_types):
groups = (group, )
else:
groups = group
# First check if the user has the permission (even anon users)
if user.groups.filter(name__in=groups).exists():
return True
# In case the 403 handler should be called raise the exception
if raise_exception:
raise PermissionDenied
# As the last resort, show the login form
return False
return user_passes_test(check_perms, login_url=login_url) | [
"anudeepnaidu95@gmail.com"
] | anudeepnaidu95@gmail.com |
94d08669d7d91b6bae39af0f8cd3f736aa4d581e | 4794379ca67670b65097830df76dd5440c69ddf6 | /oop_advance/slots.py | 2dcea1fb857c1f05d25824b1cb714780f170d880 | [] | no_license | kk412027247/learn-python | f7e12c1b476e47a2a18c609a81dbfe8bd1e31a41 | 25bb231e62a17303ec543e41a18d9302dac9d607 | refs/heads/master | 2020-05-26T14:31:05.096302 | 2019-10-13T07:06:29 | 2019-10-13T07:06:29 | 188,265,271 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 594 | py | from types import MethodType
class Student(object):
pass
s = Student()
s.name = 'Michael'
print(s.name)
def set_age(self, age):
self.age = age
s.set_age = MethodType(set_age, s)
s.set_age(25)
print(s.age)
def set_score(self, score):
self.score = score
Student.set_score = set_score
s.set_score(100)
print(s.score)
s2 = Student()
s2.set_score(99)
print(s2.score)
class Student(object):
__slots__ = ('age', 'name')
s = Student()
s.name = 'Michael'
s.age = 25
# s.score = 99
class GraduateStudent(Student):
pass
g = GraduateStudent()
g.score = 9999
| [
"kk412027247@gmail.com"
] | kk412027247@gmail.com |
9ccf72911d2d92e9eb8901fb65d14b172b2d10df | be55991401aef504c42625c5201c8a9f14ca7c3b | /leetcode/graph/hard/dungeon_game_174/my_answer.py | 4d7e22d5b43386c062551f7d021dd7ac567375ab | [
"Apache-2.0"
] | permissive | BillionsRichard/pycharmWorkspace | adc1f8bb15b58ded489fc8dec0df397601823d2c | 709e2681fc6d85ff52fb25717215a365f51073aa | refs/heads/master | 2021-09-14T21:12:59.839963 | 2021-08-08T09:05:37 | 2021-08-08T09:05:37 | 143,610,481 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,605 | py | # encoding: utf-8
"""
@version: v1.0
@author: Richard
@license: Apache Licence
@contact: billions.richard@qq.com
@site:
@software: PyCharm
@time: 2019/10/20 16:28
"""
class Solution:
def calculateMinimumHP(self, dungeon: list) -> int:
m, n = len(dungeon), len(dungeon[0])
# dp[x][y] 表示勇士到达 (x,y) 坐标时最低需要的健康值
dp = [[0 for _ in range(n)] for _ in range(m)]
for x in range(m):
for y in range(n):
if dungeon[x][y] >= 0:
dp[x][y] = 1 # 至少需要1个健康值进入房间
else:
# 比如进入该房间会损失 3 点健康值,
# 那么进入该房间至少需要 4 点健康值
dp[x][y] = 1 - dungeon[x][y] #
# 从地图右下角 (倒数第 1 列 倒数第一行) 逐个扫描计算
for y in range(n - 1, -1, -1): # 按列
for x in range(m - 1, -1, -1): # 按行
if y == n - 1 and x == m - 1: # 跳过 最右下角
continue
"""
最后一列(dungenon[m-1][n-1]除外)每一格的健康值只受到其下方健
康值和进入房间初始健康值的约束
dp[x][y] + dungeon[x][y] = dp[x+1][y] =>
dp[x][y] = dp[x+1][y] - dungeon[x][y]
"""
if y == n - 1:
dp[x][y] = max(dp[x][y], dp[x + 1][y] - dungeon[x][y])
continue
"""
第1列至倒数第二列每一格的健康值只受到其右方健康值和进入房间初始
健康值的约束
dp[x][y] + dungeon[x][y] = dp[x][y+1] =>
dp[x][y] = dp[x][y+1] - dungeon[x][y]
"""
right_min = dp[x][y + 1] - dungeon[x][y]
if x == m - 1:
dp[x][y] = max(dp[x][y], right_min)
continue
"""
第1列至倒数第二列,第一行到倒数第二行中,每一格的健康值同时受到
其右方健康值、下方健康值 和进入房间初始健康值的约束
dp[x][y] + dungeon[x][y] = dp[x+1][y] =>
dp[x][y] = dp[x+1][y] - dungeon[x][y]
"""
down_min = dp[x + 1][y] - dungeon[x][y]
neighbor_min = min(right_min, down_min) # 此处有1条路可走即可
dp[x][y] = max(dp[x][y], neighbor_min)
return dp[0][0]
| [
"295292802@qq.com"
] | 295292802@qq.com |
fab1af44d31dd57e504c8b276a0b0b78dae067e2 | c8c95520fb1a17d627a0256df2c6702f4f53403a | /10.6.3_exercises.py | 70ad860142aa2c9a7972a1446f9c1829e3d0fcd1 | [] | no_license | wsargeant/httlacs | 608f1b4b34c95f18f934f10883beb56a2895c269 | 3337b369c541e18d5ed9ecbca35494c3ebcfa591 | refs/heads/master | 2023-02-21T21:10:03.228762 | 2021-01-25T08:44:46 | 2021-01-25T08:44:46 | 284,936,152 | 0 | 0 | null | 2020-08-28T10:35:17 | 2020-08-04T09:32:38 | null | UTF-8 | Python | false | false | 2,406 | py | import turtle
turtle.setup(400,600)
wn = turtle.Screen()
wn.title("Tess becomes a traffic light")
wn.bgcolor("lightgreen")
tess = turtle.Turtle()
green_light = turtle.Turtle()
amber_light = turtle.Turtle()
red_light = turtle.Turtle()
def draw_housing():
""" Draw a housing to hold the traffic lights"""
tess.pensize(3)
tess.color("black", "darkgrey")
tess.begin_fill()
tess.forward(80)
tess.left(90)
tess.forward(200)
tess.circle(40, 180)
tess.forward(200)
tess.left(90)
tess.end_fill()
tess.hideturtle()
draw_housing()
# position green_light onto the place where the green light should be
green_light.hideturtle()
green_light.penup()
green_light.forward(40)
green_light.left(90)
green_light.forward(50)
# turn green_light into a big green circle
green_light.shape("circle")
green_light.shapesize(3)
green_light.fillcolor("green")
green_light.showturtle()
# position amber_light onto the place where the amber light should be
amber_light.hideturtle()
amber_light.penup()
amber_light.forward(40)
amber_light.left(90)
amber_light.forward(120)
# turn amber_light into a big orange circle
amber_light.shape("circle")
amber_light.shapesize(3)
amber_light.fillcolor("orange")
# position red_light onto the place where the red light should be
red_light.hideturtle()
red_light.penup()
red_light.forward(40)
red_light.left(90)
red_light.forward(190)
# turn red_light into a big red circle
red_light.shape("circle")
red_light.shapesize(3)
red_light.fillcolor("red")
# a traffic light is a state machine with 3 states,
# green, amber, red. We number each state 0, 1, 2
# when the machine changes state, we change which turtle to show
state_num = 0
def advance_state_machine():
""" Traffic light sequence on timer"""
global state_num
if state_num == 0: #transition from state 0 to state 1
green_light.hideturtle()
amber_light.showturtle()
state_num = 1
wn.ontimer(advance_state_machine, 1000)
elif state_num == 1: # transition from state 1 to state 2
amber_light.hideturtle()
red_light.showturtle()
state_num = 2
wn.ontimer(advance_state_machine, 1000)
else:
red_light.hideturtle()
green_light.showturtle()
state_num = 0
# bind the event handler to the space key
wn.onkey(advance_state_machine, "space")
wn.listen() # listen for events
wn.mainloop() | [
"69194027+wsargeant@users.noreply.github.com"
] | 69194027+wsargeant@users.noreply.github.com |
f7e37c2a90c62480274603a2d723babb7e5c0bf0 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02743/s644313592.py | 035aeecce49eb8a0432c5a0407dd58feff435620 | [] | 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 | 367 | py | from typing import List
def main():
nums = [int(n) for n in input().split(' ')]
if si(nums):
print('Yes')
else:
print('No')
def si(nums: List[int]) -> bool:
result = False
a, b, c = nums
if 4 * a * b < (c - a - b) ** 2 and (c - a - b) > 0:
result = True
return result
if __name__ == '__main__':
main()
| [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
35f014f32beeaa20fc17beb68ae7b31007579727 | 958cbae5e11bd8116c9478b1c32b7c226fa68d38 | /myvenv/bin/pilprint.py | 73975b7983f252c90abe9835754750c65f3e0faf | [] | no_license | sarkmen/onedayschool | 0f49d26fae4a359d3e16b08efef0d951bf061b9e | 2bce3adf98bd1152a9aa5b30aaeb5b5885192b88 | refs/heads/master | 2021-01-21T04:50:26.946895 | 2016-07-19T05:42:39 | 2016-07-19T05:42:39 | 55,145,604 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,574 | py | #!/Users/Roadwalker/dev/onedayschool/myvenv/bin/python3
#
# The Python Imaging Library.
# $Id$
#
# print image files to postscript printer
#
# History:
# 0.1 1996-04-20 fl Created
# 0.2 1996-10-04 fl Use draft mode when converting.
# 0.3 2003-05-06 fl Fixed a typo or two.
#
from __future__ import print_function
import getopt
import os
import sys
import subprocess
VERSION = "pilprint 0.3/2003-05-05"
from PIL import Image
from PIL import PSDraw
letter = (1.0*72, 1.0*72, 7.5*72, 10.0*72)
def description(filepath, image):
title = os.path.splitext(os.path.split(filepath)[1])[0]
format = " (%dx%d "
if image.format:
format = " (" + image.format + " %dx%d "
return title + format % image.size + image.mode + ")"
if len(sys.argv) == 1:
print("PIL Print 0.2a1/96-10-04 -- print image files")
print("Usage: pilprint files...")
print("Options:")
print(" -c colour printer (default is monochrome)")
print(" -p print via lpr (default is stdout)")
print(" -P <printer> same as -p but use given printer")
sys.exit(1)
try:
opt, argv = getopt.getopt(sys.argv[1:], "cdpP:")
except getopt.error as v:
print(v)
sys.exit(1)
printerArgs = [] # print to stdout
monochrome = 1 # reduce file size for most common case
for o, a in opt:
if o == "-d":
# debug: show available drivers
Image.init()
print(Image.ID)
sys.exit(1)
elif o == "-c":
# colour printer
monochrome = 0
elif o == "-p":
# default printer channel
printerArgs = ["lpr"]
elif o == "-P":
# printer channel
printerArgs = ["lpr", "-P%s" % a]
for filepath in argv:
try:
im = Image.open(filepath)
title = description(filepath, im)
if monochrome and im.mode not in ["1", "L"]:
im.draft("L", im.size)
im = im.convert("L")
if printerArgs:
p = subprocess.Popen(printerArgs, stdin=subprocess.PIPE)
fp = p.stdin
else:
fp = sys.stdout
ps = PSDraw.PSDraw(fp)
ps.begin_document()
ps.setfont("Helvetica-Narrow-Bold", 18)
ps.text((letter[0], letter[3]+24), title)
ps.setfont("Helvetica-Narrow-Bold", 8)
ps.text((letter[0], letter[1]-30), VERSION)
ps.image(letter, im)
ps.end_document()
if printerArgs:
fp.close()
except:
print("cannot print image", end=' ')
print("(%s:%s)" % (sys.exc_info()[0], sys.exc_info()[1]))
| [
"beomjun.gim3@gmail.com"
] | beomjun.gim3@gmail.com |
0c0eeb57c9fdcdcb8ca39adf4dd38098bc1c6d90 | 518bf342bc4138982af3e2724e75f1d9ca3ba56c | /solutions/1913. Maximum Product Difference Between Two Pairs/1913.py | 95b10944b5dc495737e66afb6181f548621313b9 | [
"MIT"
] | permissive | walkccc/LeetCode | dae85af7cc689882a84ee5011f0a13a19ad97f18 | a27be41c174565d365cbfe785f0633f634a01b2a | refs/heads/main | 2023-08-28T01:32:43.384999 | 2023-08-20T19:00:45 | 2023-08-20T19:00:45 | 172,231,974 | 692 | 302 | MIT | 2023-08-13T14:48:42 | 2019-02-23T15:46:23 | C++ | UTF-8 | Python | false | false | 420 | py | class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
max1 = -math.inf
max2 = -math.inf
min1 = math.inf
min2 = math.inf
for num in nums:
if num > max1:
max2 = max1
max1 = num
elif num > max2:
max2 = num
if num < min1:
min2 = min1
min1 = num
elif num < min2:
min2 = num
return max1 * max2 - min1 * min2
| [
"me@pengyuc.com"
] | me@pengyuc.com |
a14d6b0e0748fc1cda2fb198decd0056b8b3d273 | 327c11245c022825975b5e3c5e99be01c3102cd3 | /chatterbot/stemming.py | b353587e8dc19156199faf119162233bcc327271 | [
"BSD-3-Clause"
] | permissive | KevinMaldjian/ChatterBot | 68c9f7ee5592e9fc06deea99c16b00cf6fc21fc4 | 91975d04efe7b6a63aaa379ed682a8dae64c47cf | refs/heads/master | 2020-04-10T11:47:41.920838 | 2018-12-08T15:59:28 | 2018-12-08T16:05:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,726 | py | import string
from nltk import pos_tag
from nltk.corpus import wordnet, stopwords
class SimpleStemmer(object):
"""
A very simple stemming algorithm that removes stopwords and punctuation.
It then removes the beginning and ending characters of each word.
This should work for any language.
"""
def __init__(self, language='english'):
self.punctuation_table = str.maketrans(dict.fromkeys(string.punctuation))
self.language = language
self.stopwords = None
def initialize_nltk_stopwords(self):
"""
Download required NLTK stopwords corpus if it has not already been downloaded.
"""
from chatterbot.utils import nltk_download_corpus
nltk_download_corpus('stopwords')
def get_stopwords(self):
"""
Get the list of stopwords from the NLTK corpus.
"""
if not self.stopwords:
self.stopwords = stopwords.words(self.language)
return self.stopwords
def get_stemmed_words(self, text, size=4):
stemmed_words = []
# Make the text lowercase
text = text.lower()
# Remove punctuation
text_with_punctuation_removed = text.translate(self.punctuation_table)
if text_with_punctuation_removed:
text = text_with_punctuation_removed
words = text.split(' ')
# Do not stem singe-word strings that are less than the size limit for characters
if len(words) == 1 and len(words[0]) < size:
return words
# Generate the stemmed text
for word in words:
# Remove stopwords
if word not in self.get_stopwords():
# Chop off the ends of the word
start = len(word) // size
stop = start * -1
word = word[start:stop]
if word:
stemmed_words.append(word)
# Return the word list if it could not be stemmed
if not stemmed_words and words:
return words
return stemmed_words
def get_bigram_pair_string(self, text):
"""
Return bigram pairs of stemmed text for a given string.
For example:
"Hello Dr. Salazar. How are you today?"
"[ell alaza] [alaza oda]"
"ellalaza alazaoda"
"""
words = self.get_stemmed_words(text)
bigrams = []
word_count = len(words)
if word_count <= 1:
bigrams = words
for index in range(0, word_count - 1):
bigram = words[index] + words[index + 1]
bigrams.append(bigram)
return ' '.join(bigrams)
def treebank_to_wordnet(pos):
"""
* https://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html
* http://www.nltk.org/_modules/nltk/corpus/reader/wordnet.html
"""
data_map = {
'N': wordnet.NOUN,
'J': wordnet.ADJ,
'V': wordnet.VERB,
'R': wordnet.ADV
}
return data_map.get(pos[0])
class PosHypernymStemmer(object):
"""
For each non-stopword in a string, return a string where each word is a
hypernym preceded by the part of speech of the word before it.
"""
def __init__(self, language='english'):
self.punctuation_table = str.maketrans(dict.fromkeys(string.punctuation))
self.language = language
self.stopwords = None
def initialize_nltk_stopwords(self):
"""
Download required NLTK stopwords corpus if it has not already been downloaded.
"""
from chatterbot.utils import nltk_download_corpus
nltk_download_corpus('stopwords')
def initialize_nltk_wordnet(self):
"""
Download required NLTK corpora if they have not already been downloaded.
"""
from chatterbot.utils import nltk_download_corpus
nltk_download_corpus('corpora/wordnet')
def get_stopwords(self):
"""
Get the list of stopwords from the NLTK corpus.
"""
if not self.stopwords:
self.stopwords = stopwords.words(self.language)
return self.stopwords
def get_hypernyms(self, pos_tags):
"""
Return the hypernyms for each word in a list of POS tagged words.
"""
results = []
for word, pos in pos_tags:
synsets = wordnet.synsets(word, treebank_to_wordnet(pos))
if synsets:
synset = synsets[0]
hypernyms = synset.hypernyms()
if hypernyms:
results.append(hypernyms[0].name().split('.')[0])
else:
results.append(word)
else:
results.append(word)
return results
def get_bigram_pair_string(self, text):
"""
For example:
What a beautiful swamp
becomes:
DT:beautiful JJ:wetland
"""
words = text.split()
# Separate punctuation from last word in string
word_with_punctuation_removed = words[-1].strip(string.punctuation)
if word_with_punctuation_removed:
words[-1] = word_with_punctuation_removed
pos_tags = pos_tag(words)
hypernyms = self.get_hypernyms(pos_tags)
bigrams = []
word_count = len(words)
if word_count <= 1:
bigrams = words
if bigrams:
bigrams[0] = bigrams[0].lower()
for index in range(1, word_count):
if words[index].lower() not in self.get_stopwords():
bigram = pos_tags[index - 1][1] + ':' + hypernyms[index].lower()
bigrams.append(bigram)
return ' '.join(bigrams)
| [
"gunthercx@gmail.com"
] | gunthercx@gmail.com |
cba3f9fae1a60a8fcceec19e2d36d35d7fac6b27 | 70263abbb3c7efabf4039f5861e4d417926c13af | /nova/nova/cmd/conductor.py | 94377f7045a3003d21fdfdad38e524c6b1d0a07b | [
"Apache-2.0"
] | permissive | bopopescu/keystone_hierarchical_projects | 9b272be1e3069a8ad1875103a1b7231257c90d9c | bf5cbb2e1c58dae17e77c2ec32ed171ec3104725 | refs/heads/master | 2022-11-21T04:33:35.089778 | 2014-02-24T19:23:47 | 2014-02-24T19:23:47 | 282,174,859 | 0 | 0 | null | 2020-07-24T09:12:32 | 2020-07-24T09:12:31 | null | UTF-8 | Python | false | false | 1,399 | py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 IBM Corp.
#
# 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.
"""Starter script for Nova Conductor."""
import sys
from oslo.config import cfg
from nova import config
from nova import objects
from nova.openstack.common import log as logging
from nova import service
from nova import utils
CONF = cfg.CONF
CONF.import_opt('topic', 'nova.conductor.api', group='conductor')
def main():
objects.register_all()
config.parse_args(sys.argv)
logging.setup("nova")
utils.monkey_patch()
server = service.Service.create(binary='nova-conductor',
topic=CONF.conductor.topic,
manager=CONF.conductor.manager)
workers = CONF.conductor.workers or utils.cpu_count()
service.serve(server, workers=workers)
service.wait()
| [
"tellesnobrega@gmail.com"
] | tellesnobrega@gmail.com |
3ca4b1890044c389fe0a23bd35ee50baa6b78a33 | 2b167e29ba07e9f577c20c54cb943861d0ccfa69 | /numerical_analysis_backup/small-scale-multiobj/pod150_milp/hybrid/runsimu7_hybrid.py | 6c259e8aadbfc3137fa5ac817b5354e031843b24 | [] | no_license | LiYan1988/kthOld_OFC | 17aeeed21e195d1a9a3262ec2e67d6b1d3f9ff0f | b1237577ea68ad735a65981bf29584ebd889132b | refs/heads/master | 2021-01-11T17:27:25.574431 | 2017-01-23T05:32:35 | 2017-01-23T05:32:35 | 79,773,237 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,394 | py | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 4 15:15:10 2016
@author: li
optimize hybrid
"""
#import sys
#sys.path.insert(0, '/home/li/Dropbox/KTH/numerical_analysis/ILPs')
import csv
from gurobipy import *
import numpy as np
from arch4_decomposition import Arch4_decompose
from arch1 import ModelSDM_arch1
from arch2_decomposition import Arch2_decompose
from arch5_decomposition import Arch5_decompose
np.random.seed(2010)
num_cores=3
num_slots=80
n_sim = 1 # number of simulations
n_start = 7 # index of start
n_end = n_start+n_sim # index of end
time_limit_routing = 1000 # 1000
time_limit_sa = 18000
result = np.zeros((n_sim, 15))
total_cnk = []
for i in range(n_start, n_end):
filename = 'traffic_matrix__matrix_'+str(i)+'.csv'
# print filename
tm = []
with open(filename) as f:
reader = csv.reader(f)
for idx, row in enumerate(reader):
if idx>11:
row.pop()
row = [int(u) for u in row]
tm.append(row)
tm = np.array(tm)*25
total_cnk.append(tm.flatten().astype(bool).sum())
result[i-n_start, 14] = tm.flatten().astype(bool).sum()
print "\n"
print total_cnk
print "\n"
#%% arch4
print "Architecture 4"
m = Arch4_decompose(tm, num_slots=num_slots, num_cores=num_cores,alpha=1,beta=0.01)
m.create_model_routing(mipfocus=1,timelimit=time_limit_routing,mipgap=0.01)
m.create_model_sa(mipfocus=1,timelimit=time_limit_sa)
result[i-n_start, 0] = m.connections_lb
result[i-n_start, 1] = m.connections_ub
result[i-n_start, 2] = m.throughput_lb
result[i-n_start, 3] = m.throughput_ub
#%% arch1
print "Architecutre 1"
m = ModelSDM_arch1(tm, num_slots=num_slots, num_cores=num_cores,alpha=1,beta=0.01)
m.create_model(mipfocus=1, timelimit=time_limit_routing,mipgap=0.01)
result[i-n_start, 4] = m.connections
result[i-n_start, 5] = m.throughput
#%% arch2
print "Architecture 2"
m = Arch2_decompose(tm, num_slots=num_slots, num_cores=num_cores,alpha=1,beta=0.01)
m.create_model_routing(mipfocus=1,timelimit=time_limit_routing,mipgap=0.01)
m.create_model_sa(mipfocus=1,timelimit=time_limit_sa)
result[i-n_start, 6] = m.connections_lb
result[i-n_start, 7] = m.connections_ub
result[i-n_start, 8] = m.throughput_lb
result[i-n_start, 9] = m.throughput_ub
#%% arch5
print "Architecture 5"
m = Arch5_decompose(tm, num_slots=num_slots, num_cores=num_cores,alpha=1,beta=0.01)
m.create_model_routing(mipfocus=1, timelimit=time_limit_routing, mipgap=0.01)
m.create_model_sa(mipfocus=1, timelimit=time_limit_sa)
result[i-n_start, 10] = m.connections_lb
result[i-n_start, 11] = m.connections_ub
result[i-n_start, 12] = m.throughput_lb
result[i-n_start, 13] = m.throughput_ub
file_name = "result_hybrid_{}to{}.csv".format(n_start, n_end)
with open(file_name, 'w') as f:
writer = csv.writer(f, delimiter=',')
writer.writerow(['arch4_connections_lb', 'arch4_connections_ub',
'arch4_throughput_lb', 'arch4_throughput_ub',
'arch1_connections', 'arch1_throughput',
'arch2_connections_lb', 'arch2_connections_ub',
'arch2_throughput_lb', 'arch2_throughput_ub',
'arch5_connections_lb', 'arch5_connections_ub',
'arch5_throughput_lb', 'arch5_throughput_ub',
'total_cnk'])
writer.writerows(result) | [
"li.yan.ly414@gmail.com"
] | li.yan.ly414@gmail.com |
0f8b912ba66a1173d67a43cd005f23f5bc24a832 | 7fcdb9f3d8dfd39bf196fdb473fba5566cd97500 | /integration/tmux/create_pane_spec.py | e171e83b4763dbcc3d38ab2830bea6ece428ed02 | [
"MIT"
] | permissive | tek/myo-py | 4ccf7892a8317d54a02ed8f3d65ea54f07d984b4 | 3772a00a021cbf4efb55786e26881767d854afe8 | refs/heads/master | 2021-10-19T20:45:24.774281 | 2019-02-23T15:16:58 | 2019-02-23T15:16:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,335 | py | from kallikrein import Expectation, k
from kallikrein.matchers.typed import have_type
from amino import do, Do
from chiasma.util.id import StrIdent
from amino.test.spec import SpecBase
from ribosome.nvim.io.compute import NvimIO
from ribosome.nvim.api.command import nvim_command
from ribosome.test.klk.matchers.prog import component_state
from ribosome.test.integration.embed import plugin_test
from ribosome.test.config import TestConfig
from ribosome.nvim.io.api import N
from myo import myo_config
from myo.ui.data.view import Pane
@do(NvimIO[Expectation])
def create_pane_spec() -> Do:
yield nvim_command('MyoCreatePane', '{ "layout": "make", "ident": "pane"}')
state = yield component_state('ui')
space = yield N.m(state.spaces.head, 'no space')
win = yield N.m(space.windows.head, 'no window')
layout = yield N.m(win.layout.sub.find(lambda a: a.data.ident == StrIdent('make')), 'no layout `make`')
pane = yield N.m(layout.sub.find(lambda a: a.data.ident == StrIdent('pane')), 'no pane `pane`')
return k(pane.data).must(have_type(Pane))
test_config = TestConfig.cons(myo_config)
class CreatePaneSpec(SpecBase):
'''
create a pane $create_pane
'''
def create_pane(self) -> Expectation:
return plugin_test(test_config, create_pane_spec)
__all__ = ('CreatePaneSpec',)
| [
"torstenschmits@gmail.com"
] | torstenschmits@gmail.com |
b6f245ee3c5b5ad2ae95c0b7ff11b2cf6c9b9995 | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/otherforms/_docketed.py | 47549313b856590ea1a3308650f7333c6d6d0449 | [
"MIT"
] | permissive | cash2one/xai | de7adad1758f50dd6786bf0111e71a903f039b64 | e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6 | refs/heads/master | 2021-01-19T12:33:54.964379 | 2017-01-28T02:00:50 | 2017-01-28T02:00:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 224 | py |
#calss header
class _DOCKETED():
def __init__(self,):
self.name = "DOCKETED"
self.definitions = docket
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.basic = ['docket']
| [
"xingwang1991@gmail.com"
] | xingwang1991@gmail.com |
44ac6e76c3e0b9341d50614fe10d9fd3728459fb | 754fb49b8c3e41a9790fadb92f27571f175150fb | /text_matching/20125222/ESIM/test.py | 923f3f093fa5cb140b83a64a1ebcd815bc979fcd | [] | no_license | HuihuiChyan/BJTUNLP_Practice2020 | 8df2c956a9629c8841d7b7d70d2ea86345be0b0e | 4ba1f8f146f5d090d401c38f5536907afca4830b | refs/heads/master | 2023-02-16T17:47:55.570612 | 2021-01-13T09:40:20 | 2021-01-13T09:40:20 | 295,123,517 | 21 | 3 | null | null | null | null | UTF-8 | Python | false | false | 471 | py | import argparse
import torch
import utils
import model
import train
import test
#设置设备
def test(args,device,net,train_iter):
net.load_state_dict(torch.load(args.save_path))
print(net)
net.eval()
for feature,_ in train_iter:
f=open("result.txt")
feature = feature.transpose(1, 0)
feature = feature.to(device)
score = net(feature[0], feature[1])
f.write(torch.argmax(score.cpu().data, dim=1))
f.close() | [
"noreply@github.com"
] | HuihuiChyan.noreply@github.com |
891ab579b163f740e989fdea514ebf2c0ec2931d | 3b944f1714c458c5d6d0e84d4b1498f2b59c4ef7 | /67. Add Binary.py | 0feccbd47c3a2de8dcae01d332f475c8c2a2cfb2 | [] | no_license | shiannn/LeetCodePython | e4d66f108200d8329616b3e45b70c3f8fc4cd9ed | 6e4472d41904e60ff9d70b5f3979c5dcae98c838 | refs/heads/master | 2021-06-26T03:24:03.079077 | 2021-02-24T16:54:18 | 2021-02-24T16:54:18 | 213,206,772 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,021 | py | class Solution:
def addBinary(self, a: str, b: str) -> str:
carry = 0
bit = 0
ret = ""
all_len = max(len(a), len(b))
for i in range(1, all_len+1):
if len(a) - i >= 0:
aa = a[len(a) - i]
else:
aa = 0
if len(b) - i >= 0:
bb = b[len(b) - i]
else:
bb = 0
bit = int(aa) + int(bb) + carry
if bit == 0:
ret = "0"+ret
carry = 0
elif bit == 1:
ret = "1"+ret
carry = 0
elif bit == 2:
ret = "0"+ret
carry = 1
elif bit == 3:
ret = "1"+ret
carry = 1
if carry > 0:
ret = str(carry) + ret
return ret
if __name__ == '__main__':
#a = '11'
#b = '1'
a = "1010"
b = "1011"
sol = Solution()
ret = sol.addBinary(a, b)
print(ret) | [
"b05502087@ntu.edu.tw"
] | b05502087@ntu.edu.tw |
fe6302586a28e6dbbb50242710d80872542efaae | 15863dafe261decf655286de2fcc6e67cadef3d8 | /website/apps/loans/migrations/0003_loanprofilev1_assets_verification_method.py | 56d08ce867e953afb77df96d9ab32e6fa5decfae | [] | no_license | protoprojects/worksample | 5aa833570a39d5c61e0c658a968f28140694c567 | f1a8cd8268d032ea8321e1588e226da09925b7aa | refs/heads/master | 2021-06-26T17:34:10.847038 | 2017-09-14T00:14:03 | 2017-09-14T00:14:03 | 103,463,317 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 600 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-05-31 07:33
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('loans', '0002_employmentv1_is_current_employment'),
]
operations = [
migrations.AddField(
model_name='loanprofilev1',
name='assets_verification_method',
field=models.CharField(blank=True, choices=[('self_reported', 'Self Reported'), ('yodlee', 'Yodlee Aggregated assets')], max_length=127, null=True),
),
]
| [
"dev@divethree.com"
] | dev@divethree.com |
6e273e8d146220a1751305959dc5d98e59fc206d | 3052e12cd492f3ffc3eedadc1bec6e6bb220e16b | /0x06-python-classes/102-square.py | 67848441ec4aa157cc06583f7c91a89207b42a60 | [] | no_license | JoseAVallejo12/holbertonschool-higher_level_programming | 2e9f79d495b664299a57c723e4be2ad8507abb4f | f2d9d456c854b52c932ec617ea3c40564b78bcdb | refs/heads/master | 2022-12-17T22:36:41.416213 | 2020-09-25T20:08:41 | 2020-09-25T20:08:41 | 259,383,382 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,371 | py | #!/usr/bin/python3
# 102-square.py
# jose vallejo <1545@holbertonschool.com
""" Define a new class """
class Square(object):
""" create Square class """
def __init__(self, size=0):
""" inicialice size var """
self.__size = size
@property
def size(self):
""" getter method for private size """
return self.__size
@size.setter
def size(self, value):
""" setter method for private size """
if type(value) is not int or float:
raise TypeError("size must be a number")
elif value < 0:
raise ValueError("size must be >= 0")
def area(self):
""" Method for Calculate area """
return self.__size * self.__size
def __eq__(self, other):
""" __eq__ represent a == b """
return self.__size == other
def __ne__(self, other):
""" __ne__ represent a != b or a <> b """
return self.__size != other
def __gt__(self, other):
""" __gt__ represent a > b """
return self.__size > other
def __ge__(self, other):
""" __eq__ represent a==b """
return self.__size >= other
def __lt__(self, other):
""" __lt__ represent a < b """
return self.__size < other
def __le__(self, other):
""" __le__ represent a <= b """
return self.__size <= other
| [
"josealfredovallejo25@gmail.com"
] | josealfredovallejo25@gmail.com |
8941614c0c690934b59b84074e2f8ef37b10da44 | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_319/ch15_2020_09_30_19_19_59_252844.py | c9f8753e8fea96067b6cc7e293c8ac16eee99427 | [] | 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 | 163 | py | Qual_o_seu_nome = input('Qual o seu nome?')
if Qual_o_seu_nome == Chris:
return 'Todo mundo odeia o Chris'
else:
return 'Olá, NOME'
print(Qual_o_seu_nome) | [
"you@example.com"
] | you@example.com |
e86f5382c89102f0d86b4c313724b8f605b98150 | 63050299cfe58aebf6dd26a5178051a839de8c39 | /game/game_data.py | 92697b75c725f4e4cf5f6c34508d70c35701a5bd | [] | no_license | stmobo/Split-Minded | df12a6a60eb086294f2a7e6f14ad137cd628228c | 0307ff4c9777f08d582147decd4dc762c40b2688 | refs/heads/master | 2020-03-12T04:25:04.820340 | 2018-04-25T01:47:17 | 2018-04-25T01:47:17 | 130,444,429 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 468 | py | import renpy.exports as renpy
# the game runs at 1280x720 by default
# use roughly half of the total screen size for the control game view
tile_size = 50 # px square
field_sz_tiles = [30, 30]
field_size = [field_sz_tiles[0]*tile_size, field_sz_tiles[1]*tile_size]
screen_total_size = [1280, 720]
gameplay_screen_size = [640, 640]
screen_center = None
combat_in_progress = False
ai_active = False
# dev purposes only:
force_combat_winner = None
skip_combat = False
| [
"stmobo@gmail.com"
] | stmobo@gmail.com |
d94a5cdac376d139ebc4289f0fd4dfaee5f315e9 | 15f321878face2af9317363c5f6de1e5ddd9b749 | /solutions_python/Problem_117/664.py | 3f8b42535772cdcba828eea3e04f7364e212ad5d | [] | 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 | 1,624 | py |
__author__ = 'sergeyy'
import time
import numpy as np
def getUsedH(a):
res = set()
for l in a:
res = res | set(l)
return res
def delLine(a, l):
del a[l]
return a
def delColl(a, c):
for l in a:
del l[c]
return a
def isCuutbl(line):
if line[0] >= max(line):
return True
return False
def removeH(a,h):
if min([min(x) for x in a]) < h:
return False
while True:
lToRem = []
cToRem = []
for i in range(len(a)):
if (a[i][0] == h):
if isCuutbl(a[i]):
lToRem.append(i);
for i in range(len(a[0])):
if (a[0][i] == h):
if isCuutbl([x[i] for x in a]):
cToRem.append(i);
if not lToRem and not cToRem:
return a
for i in sorted(lToRem, reverse=True):
delLine(a, i)
for i in sorted(cToRem, reverse=True):
delColl(a, i)
if not a:
return a
def solve(a):
for h in getUsedH(a):
a = removeH(a,h)
if a == False:
return 'NO'
if a:
return 'NO'
return 'YES'
with open('input.txt', 'r') as fin:
with open('output.txt', 'w') as fout:
cnt = int(fin.readline())
for case in range(1, cnt+1):
n, m = [int(x) for x in fin.readline().split()]
a = [[]*m]*n
for i in range(n):
a[i] = [int(x) for x in fin.readline().split()]
oline = ''
oline = 'Case #' + str(case) +': ' + solve(a) +'\n'
fout.write(oline)
print (time.clock())
| [
"miliar1732@gmail.com"
] | miliar1732@gmail.com |
48a6fbcf96afb2fa41e94c660956111df1d9812a | 7f2fc00415c152538520df84387549def73c4320 | /p0_data_prepare/path2test_list.py | 2fb54f06df155865096f47ccd75db55e4e20728c | [
"MIT"
] | permissive | mxer/face_project | da326be7c70c07ae510c2b5b8063902b27ae3a5b | 8d70858817da4d15c7b513ae492034784f57f35f | refs/heads/main | 2023-08-06T09:24:49.842098 | 2021-09-18T08:32:18 | 2021-09-18T08:32:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 759 | py | import os
import argparse
def main(args):
# to list.txt
root_ = args.folder_dir
files = []
for root, dirs, file in os.walk(root_):
for f in file:
files.append(os.path.join(root, f))
folder_ = os.path.split(args.txt_dir)[0]
if not os.path.exists(folder_):
os.makedirs(folder_)
f_ = open(args.txt_dir, 'w')
for file in files:
line = file + '\n'
f_.write(line)
f_.close()
if __name__ == '__main__':
parse = argparse.ArgumentParser()
parse.add_argument('--folder_dir', type=str,
default=r'E:\dataset-zoo\face-real\1-N\key')
parse.add_argument('--txt_dir', type=str, default=r'E:\list-zoo\real.txt')
args = parse.parse_args()
main(args) | [
"chen19940524@live.com"
] | chen19940524@live.com |
1e7178314f6883226677aa0092bc7b7f7415728c | b75237a8c9436cc31458ca20e93b4f3b46703b63 | /src/oaipmh/tests/createdata.py | 541e06ace459ffeb7572f91bfc20b62f10fa0566 | [
"BSD-3-Clause"
] | permissive | ulikoehler/pyoai | 09ebc795f707e829de1587f8cdec011201d46f75 | 461ccf81526a5ca98623dd39e210cded4fb6263d | refs/heads/master | 2022-05-10T19:36:54.980792 | 2022-03-09T16:10:36 | 2022-03-09T16:10:36 | 30,493,052 | 1 | 2 | NOASSERTION | 2022-03-09T16:10:37 | 2015-02-08T14:14:53 | Python | UTF-8 | Python | false | false | 2,109 | py | from fakeclient import FakeCreaterClient
# tied to the server at EUR..
client = FakeCreaterClient(
'http://dspace.ubib.eur.nl/oai/',
'/home/faassen/py/oai/tests/fake2')
print "GetRecord"
header, metadata, about = client.getRecord(
metadataPrefix='oai_dc', identifier='hdl:1765/315')
print "identifier:", header.identifier()
print "datestamp:", header.datestamp()
print "setSpec:", header.setSpec()
print "isDeleted:", header.isDeleted()
print
print "Identify"
identify = client.identify()
print "repositoryName:", identify.repositoryName()
print "baseURL:", identify.baseURL()
print "protocolVerson:", identify.protocolVersion()
print "adminEmails:", identify.adminEmails()
print "earliestDatestamp:", identify.earliestDatestamp()
print "deletedRecords:", identify.deletedRecord()
print "granularity:", identify.granularity()
print "compression:", identify.compression()
print
print "ListIdentifiers"
headers = client.listIdentifiers(from_=datetime(2003, 04, 10),
metadataPrefix='oai_dc')
for header in headers:
print "identifier:", header.identifier()
print "datestamp:", header.datestamp()
print "setSpec:", header.setSpec()
print "isDeleted:", header.isDeleted()
print
print "ListMetadataFormats"
for prefix, schema, ns in client.listMetadataFormats():
print "metadataPrefix:", prefix
print "schema:", schema
print "metadataNamespace:", ns
print
print "ListRecords"
for header, metadata, about in client.listRecords(
from_=datetime(2003, 04, 10), metadataPrefix='oai_dc'):
print "header"
print "identifier:", header.identifier()
print "datestamp:", header.datestamp()
print "setSpec:", header.setSpec()
print "isDeleted:", header.isDeleted()
#print "metadata"
#for fieldname in fieldnames:
# print "%s:" % fieldname, metadata.getField(fieldname)
print "about"
print about
print
print "ListSets"
for setSpec, setName, setDescription in client.listSets():
print "setSpec:", setSpec
print "setName:", setName
print "setDescription:", setDescription
print
client.save()
| [
"none@none"
] | none@none |
33453a0ed6537cf87445691a5ccc4ad2c51ff81f | bb51bebd6ff9fccc5a639d621190d46bb66e4456 | /bill_calc.py | 5e030d865a88fbcc2b69b66232ef3045b6e47f85 | [] | no_license | annalisestevenson/bill_lab | c7cb1b42844147378d336bfcbae1f481eb14b65c | c4f6badc3d7c1a73d446f0e43bee74d3f57e2f3f | refs/heads/master | 2016-09-13T23:38:25.760794 | 2016-05-06T02:50:00 | 2016-05-06T02:50:00 | 58,176,103 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,143 | py | tip_percentage= 18
bill_amount= 10
def calculate_bill():
return (tip_percentage*.01* bill_amount)+bill_amount
def calc_alone_bill():
return bill_amount
def tip_ave():
return (.18*bill_amount) + bill_amount
def main():
global bill_amount
bill_amount= float(raw_input("How much was your bill, not including tip?"))
dine_alone=raw_input("Did you dine alone, Y/N?")
if (dine_alone.upper()=="N"):
dine= int(raw_input("How many people were at dinner?"))
tip_percentage= raw_input("Is 18 percent tip okay, Y/N?")
if (tip_percentage.upper()=="N"):
tip= float(raw_input("How much do you want to leave for tip?"))
print "Your total is", ((tip*.01*bill_amount)+bill_amount)/dine
else:
print "Your total is", tip_ave()/dine
else:
global tip_percentage
tip_percentage= float(raw_input("How much do you want to leave for tip?"))
alone_bill= calculate_bill()
print "Your total is", alone_bill
# tip_percentage= raw_input("Is 18 percent tip okay, Y/N?")
# if (tip_percentage.upper()=="N"):
# tip= int(raw_input("How much do you want to leave for tip?"))
# else:
# return tip_ave
if __name__ == "__main__":
main() | [
"info@hackbrightacademy.com"
] | info@hackbrightacademy.com |
d8d595e7f69bb51aaf3a7bcc753fd581253604dd | 1ff265ac6bdf43f5a859f357312dd3ff788804a6 | /cards.py | ebaa6094cc4fbb22b25c24cc4dcee8020ccc2a4a | [] | no_license | sgriffith3/july_pyb | f1f493450ab4933a4443518863f772ad54865c26 | 5e06012ad436071416b95613ed46e972c46b0ff7 | refs/heads/master | 2022-11-19T04:58:41.632000 | 2020-07-17T19:46:44 | 2020-07-17T19:46:44 | 279,335,603 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 542 | py | import random
class DeckofCards:
def __init__(self):
cards = []
nums = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A']
for n in nums:
for suit in ['spades', 'diamonds', 'clubs', 'hearts']:
card = f"{n} of {suit}"
cards.append(card)
self.cards = cards
def pick_one(self):
one = random.choice(self.cards)
self.cards.remove(one)
return one
deck = DeckofCards()
print(len(deck.cards))
print(deck.pick_one())
print(len(deck.cards))
| [
"sgriffith@alta3.com"
] | sgriffith@alta3.com |
dfe90b2f77adbed5cee3c8bf22fc1cadf07db007 | a281d09ed91914b134028c3a9f11f0beb69a9089 | /contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/metrics/data_profiler_metrics/data_profiler_profile_percent_diff.py | 74cfa564650c69823f7fd47fecd0d9e533bd6e47 | [
"Apache-2.0"
] | permissive | CarstenFrommhold/great_expectations | 4e67bbf43d21bc414f56d576704259a4eca283a5 | 23d61c5ed26689d6ff9cec647cc35712ad744559 | refs/heads/develop | 2023-01-08T10:01:12.074165 | 2022-11-29T18:50:18 | 2022-11-29T18:50:18 | 311,708,429 | 0 | 0 | Apache-2.0 | 2020-11-10T15:52:05 | 2020-11-10T15:52:04 | null | UTF-8 | Python | false | false | 4,150 | py | import copy
from typing import Optional
from great_expectations.core.expectation_configuration import ExpectationConfiguration
from great_expectations.execution_engine import ExecutionEngine, PandasExecutionEngine
from great_expectations.expectations.metrics.metric_provider import metric_value
from great_expectations.validator.metric_configuration import MetricConfiguration
from .data_profiler_profile_metric_provider import DataProfilerProfileMetricProvider
class DataProfilerProfilePercentDiff(DataProfilerProfileMetricProvider):
metric_name = "data_profiler.profile_percent_diff"
value_keys = ("profile_path",)
@metric_value(PandasExecutionEngine)
def _pandas(
cls,
execution_engine,
metric_domain_kwargs,
metric_value_kwargs,
metrics,
runtime_configuration,
):
numerical_diff_stats = [
"min",
"max",
"sum",
"mean",
"median",
"median_absolute_deviation",
"variance",
"stddev",
"unique_count",
"unique_ratio",
"gini_impurity",
"unalikeability",
"sample_size",
"null_count",
]
profile_report = metrics["data_profiler.profile_report"]
diff_report = metrics["data_profiler.profile_diff"]
pr_columns = profile_report["data_stats"]
dr_columns = diff_report["data_stats"]
percent_delta_data_stats = []
for pr_col, dr_col in zip(pr_columns, dr_columns):
pr_stats = pr_col["statistics"]
dr_stats = dr_col["statistics"]
percent_delta_col = copy.deepcopy(dr_col)
percent_delta_stats = {}
for (dr_stat, dr_val) in dr_stats.items():
if dr_stat not in numerical_diff_stats:
percent_delta_stats[dr_stat] = dr_val
continue
if dr_val == "unchanged":
dr_val = 0
if dr_stat not in pr_stats:
percent_delta_stats[dr_stat] = "ERR_no_original_value"
continue
pr_val = pr_stats[dr_stat]
percent_change = 0
if pr_val == 0:
percent_change = "ERR_divide_by_zero" # Div by 0 error
else:
percent_change = dr_val / pr_val
percent_delta_stats[dr_stat] = percent_change
percent_delta_col["statistics"] = percent_delta_stats
percent_delta_data_stats.append(percent_delta_col)
percent_diff_report = copy.deepcopy(diff_report)
percent_diff_report["data_stats"] = percent_delta_data_stats
return percent_diff_report
@classmethod
def _get_evaluation_dependencies(
cls,
metric: MetricConfiguration,
configuration: Optional[ExpectationConfiguration] = None,
execution_engine: Optional[ExecutionEngine] = None,
runtime_configuration: Optional[dict] = None,
):
"""
Returns a dictionary of given metric names and their corresponding configuration, specifying
the metric types and their respective domains"""
dependencies: dict = super()._get_evaluation_dependencies(
metric=metric,
configuration=configuration,
execution_engine=execution_engine,
runtime_configuration=runtime_configuration,
)
if metric.metric_name == "data_profiler.profile_percent_diff":
dependencies["data_profiler.profile_report"] = MetricConfiguration(
metric_name="data_profiler.profile_report",
metric_domain_kwargs=metric.metric_domain_kwargs,
metric_value_kwargs=metric.metric_value_kwargs,
)
dependencies["data_profiler.profile_diff"] = MetricConfiguration(
metric_name="data_profiler.profile_diff",
metric_domain_kwargs=metric.metric_domain_kwargs,
metric_value_kwargs=metric.metric_value_kwargs,
)
return dependencies
| [
"noreply@github.com"
] | CarstenFrommhold.noreply@github.com |
4acd9eeaf1e4d74b16644837730b5b590e581b08 | f7dd190a665a4966db33dcc1cc461dd060ca5946 | /venv/Lib/site-packages/rx/linq/observable/fromiterable.py | d7cb23a2d561fb56e33b039fe26c8d9f34747115 | [] | no_license | Darwin939/macmeharder_back | 2cc35e2e8b39a82c8ce201e63d9f6a9954a04463 | 8fc078333a746ac7f65497e155c58415252b2d33 | refs/heads/main | 2023-02-28T12:01:23.237320 | 2021-02-02T17:37:33 | 2021-02-02T17:37:33 | 328,173,062 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,532 | py | from rx import config
from rx.core import Observable, AnonymousObservable
from rx.concurrency import current_thread_scheduler
from rx.disposables import MultipleAssignmentDisposable
from rx.internal import extensionclassmethod
@extensionclassmethod(Observable, alias=["from_", "from_list"])
def from_iterable(cls, iterable, scheduler=None):
"""Converts an array to an observable sequence, using an optional
scheduler to enumerate the array.
1 - res = rx.Observable.from_iterable([1,2,3])
2 - res = rx.Observable.from_iterable([1,2,3], rx.Scheduler.timeout)
Keyword arguments:
:param Observable cls: Observable class
:param Scheduler scheduler: [Optional] Scheduler to run the
enumeration of the input sequence on.
:returns: The observable sequence whose elements are pulled from the
given enumerable sequence.
:rtype: Observable
"""
scheduler = scheduler or current_thread_scheduler
lock = config["concurrency"].RLock()
def subscribe(observer):
sd = MultipleAssignmentDisposable()
iterator = iter(iterable)
def action(scheduler, state=None):
try:
with lock:
item = next(iterator)
except StopIteration:
observer.on_completed()
else:
observer.on_next(item)
sd.disposable = scheduler.schedule(action)
sd.disposable = scheduler.schedule(action)
return sd
return AnonymousObservable(subscribe)
| [
"51247000+Darwin939@users.noreply.github.com"
] | 51247000+Darwin939@users.noreply.github.com |
c263915915e3ecdd4dfe80ac85a6252e793db04b | 2d23c271ec1a226bb345c23d7b2671ec021e9502 | /N-Queens II.py | 0e810b3a5a8215fc322e50aa8bbaad18095b027a | [] | no_license | chenlanlan/leetcode | 2e6aec0846ed951466bcd2c2e4596c998faca8e4 | d02478853c32c29477f53852286c429c20f1424e | refs/heads/master | 2016-09-08T05:07:46.904441 | 2015-07-12T05:41:15 | 2015-07-12T05:41:15 | 32,845,795 | 5 | 1 | null | null | null | null | UTF-8 | Python | false | false | 859 | py | #!/usr/bin/python
class Solution:
# @param {integer} n
# @return {integer}
def __init__(self):
self.ans = 0
def queens(self, board, n, curLevel):
if curLevel == n:
self.ans += 1
return
for i in range (n):
valid = True
for j in range(curLevel):
if board[j] == i:
valid = False
break
if abs(board[j] - i) == curLevel - j:
valid = False
break
if valid:
board[curLevel] = i
self.queens(board, n, curLevel + 1)
return
def totalNQueens(self, n):
board = [-1 for i in range (n)]
self.queens(board, n, 0)
return self.ans
test = Solution()
print(test.totalNQueens(4))
| [
"silan0318@163.com"
] | silan0318@163.com |
d9fe9d52411101f054693c8637b85329e64ad2f7 | 6051b9afd2969b65a055255d8fcde0555c62fc44 | /shop/admin.py | 0b0c0d68b8d7a21f803996bbbc85e35658b943f1 | [] | no_license | nazmul199512/django-ecommerce-app | 33a66f8efa9d63fc1fbf09d7e34d8ea74ffab63c | 6e48bdb86e7f04d7741eb0d302ee909ce99d6b88 | refs/heads/master | 2022-05-09T06:26:02.349432 | 2020-04-25T18:54:48 | 2020-04-25T18:54:48 | 258,850,131 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 130 | py | from django.contrib import admin
from .models import Product, Contact
admin.site.register(Product),
admin.site.register(Contact)
| [
"nazmul199512@gmail.com"
] | nazmul199512@gmail.com |
e27814dfaf0caaa92047a775a4c6e4f33ed268a1 | 41de4210af23a8a8a3ca7dd090bb51faecf4a0c8 | /lib/python3.5/site-packages/statsmodels/nonparametric/tests/test_kernels.py | b113306af1f38c208b9b5187b53a94b2ceb23ab2 | [
"Python-2.0"
] | permissive | randybrown-github/ziplineMacOS | 42a0c2bfca2a54baa03d2803dc41317647811285 | eb5872c0903d653e19f259f0800fb7aecee0ee5c | refs/heads/master | 2022-11-07T15:51:39.808092 | 2020-06-18T20:06:42 | 2020-06-18T20:06:42 | 272,631,387 | 0 | 1 | null | 2022-11-02T03:21:45 | 2020-06-16T06:48:53 | Python | UTF-8 | Python | false | false | 4,996 | py | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 14 17:23:25 2013
Author: Josef Perktold
"""
from __future__ import print_function
import os
import numpy as np
from statsmodels.sandbox.nonparametric import kernels
from numpy.testing import assert_allclose, assert_array_less
DEBUG = 0
curdir = os.path.dirname(os.path.abspath(__file__))
fname = 'results/results_kernel_regression.csv'
results = np.recfromcsv(os.path.join(curdir, fname))
y = results['accident']
x = results['service']
positive = x >= 0
x = np.log(x[positive])
y = y[positive]
xg = np.linspace(x.min(), x.max(), 40) # grid points default in Stata
#kern_name = 'gau'
#kern = kernels.Gaussian()
#kern_name = 'epan2'
#kern = kernels.Epanechnikov()
#kern_name = 'rec'
#kern = kernels.Uniform() # ours looks awful
#kern_name = 'tri'
#kern = kernels.Triangular()
#kern_name = 'cos'
#kern = kernels.Cosine() #doesn't match up, nan in Stata results ?
#kern_name = 'bi'
#kern = kernels.Biweight()
class CheckKernelMixin(object):
se_rtol = 0.7
upp_rtol = 0.1
low_rtol = 0.2
low_atol = 0.3
def test_smoothconf(self):
kern_name = self.kern_name
kern = self.kern
#fittedg = np.array([kernels.Epanechnikov().smoothconf(x, y, xi) for xi in xg])
fittedg = np.array([kern.smoothconf(x, y, xi) for xi in xg])
# attach for inspection from outside of test run
self.fittedg = fittedg
res_fitted = results['s_' + kern_name]
res_se = results['se_' + kern_name]
crit = 1.9599639845400545 # norm.isf(0.05 / 2)
# implied standard deviation from conf_int
se = (fittedg[:, 2] - fittedg[:, 1]) / crit
fitted = fittedg[:, 1]
# check both rtol & atol
assert_allclose(fitted, res_fitted, rtol=5e-7, atol=1e-20)
assert_allclose(fitted, res_fitted, rtol=0, atol=1e-6)
# TODO: check we are using a different algorithm for se
# The following are very rough checks
self.se = se
self.res_se = res_se
se_valid = np.isfinite(res_se)
# if np.any(~se_valid):
# print('nan in stata result', self.__class__.__name__)
assert_allclose(se[se_valid], res_se[se_valid], rtol=self.se_rtol, atol=0.2)
# check that most values are closer
mask = np.abs(se - res_se) > (0.2 + 0.2 * res_se)
if not hasattr(self, 'se_n_diff'):
se_n_diff = 40 * 0.125
else:
se_n_diff = self.se_n_diff
assert_array_less(mask.sum(), se_n_diff + 1) # at most 5 large diffs
if DEBUG:
# raises: RuntimeWarning: invalid value encountered in divide
print(fitted / res_fitted - 1)
print(se / res_se - 1)
# Stata only displays ci, doesn't save it
res_upp = res_fitted + crit * res_se
res_low = res_fitted - crit * res_se
self.res_fittedg = np.column_stack((res_low, res_fitted, res_upp))
if DEBUG:
print(fittedg[:, 2] / res_upp - 1)
print(fittedg[:, 2] - res_upp)
print(fittedg[:, 0] - res_low)
print(np.max(np.abs(fittedg[:, 2] / res_upp - 1)))
assert_allclose(fittedg[se_valid, 2], res_upp[se_valid],
rtol=self.upp_rtol, atol=0.2)
assert_allclose(fittedg[se_valid, 0], res_low[se_valid],
rtol=self.low_rtol, atol=self.low_atol)
#assert_allclose(fitted, res_fitted, rtol=0, atol=1e-6)
def t_est_smoothconf_data(self):
kern = self.kern
crit = 1.9599639845400545 # norm.isf(0.05 / 2)
# no reference results saved to csv yet
fitted_x = np.array([kern.smoothconf(x, y, xi) for xi in x])
if DEBUG:
print(fitted_x[:, 2] - fitted_x[:, 1]) / crit
class TestEpan(CheckKernelMixin):
kern_name = 'epan2'
kern = kernels.Epanechnikov()
class TestGau(CheckKernelMixin):
kern_name = 'gau'
kern = kernels.Gaussian()
class TestUniform(CheckKernelMixin):
kern_name = 'rec'
kern = kernels.Uniform()
se_rtol = 0.8
se_n_diff = 8
upp_rtol = 0.4
low_rtol = 0.2
low_atol = 0.8
class TestTriangular(CheckKernelMixin):
kern_name = 'tri'
kern = kernels.Triangular()
se_n_diff = 10
upp_rtol = 0.15
low_rtol = 0.3
class T_estCosine(CheckKernelMixin):
# Stata results for Cosine look strange, has nans
kern_name = 'cos'
kern = kernels.Cosine2()
class TestBiweight(CheckKernelMixin):
kern_name = 'bi'
kern = kernels.Biweight()
se_n_diff = 9
low_rtol = 0.3
if __name__ == '__main__':
tt = TestEpan()
tt = TestGau()
tt = TestBiweight()
tt.test_smoothconf()
diff_rel = tt.fittedg / tt.res_fittedg - 1
diff_abs = tt.fittedg - tt.res_fittedg
mask = np.abs(tt.fittedg - tt.res_fittedg) > (0.3 + 0.1 * tt.res_fittedg)
| [
"randybrown18@me.com"
] | randybrown18@me.com |
21668d9f7981e397a1a67b0e5002313b2d9129a6 | c5ff781994b48e4699e6a4719951c22badf76716 | /conda_package_handling/utils.py | 209b3d5d941beafdf7796735fcb2187e5c6f6681 | [
"BSD-3-Clause"
] | permissive | soapy1/conda-package-handling | 1145b6762b47bc4d1dd85dd9319954b8f7b044a0 | bf21ee30a73b45d493ba0679bb51fbced4faf824 | refs/heads/master | 2020-05-19T04:12:19.773121 | 2019-02-13T16:23:53 | 2019-02-13T16:23:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,409 | py | import contextlib
import hashlib
import os
import re
import shutil
import warnings as _warnings
from six import string_types
try:
from tempfile import TemporaryDirectory
except ImportError:
from tempfile import mkdtemp
class TemporaryDirectory(object):
"""Create and return a temporary directory. This has the same
behavior as mkdtemp but can be used as a context manager. For
example:
with TemporaryDirectory() as tmpdir:
...
Upon exiting the context, the directory and everything contained
in it are removed.
"""
# Handle mkdtemp raising an exception
name = None
_closed = False
def __init__(self, suffix="", prefix='tmp', dir=None):
self.name = mkdtemp(suffix, prefix, dir)
def __repr__(self):
return "<{} {!r}>".format(self.__class__.__name__, self.name)
def __enter__(self):
return self.name
def cleanup(self, _warn=False, _warnings=_warnings):
if self.name and not self._closed:
try:
shutil.rmtree(self.name)
except (TypeError, AttributeError) as ex:
if "None" not in '%s' % (ex,):
raise
shutil.rmtree(self.name)
self._closed = True
if _warn and _warnings.warn:
_warnings.warn("Implicitly cleaning up {!r}".format(self),
_warnings.ResourceWarning)
def __exit__(self, exc, value, tb):
self.cleanup()
def __del__(self):
# Issue a ResourceWarning if implicit cleanup needed
self.cleanup(_warn=True)
@contextlib.contextmanager
def tmp_chdir(dest):
curdir = os.getcwd()
try:
os.chdir(dest)
yield
finally:
os.chdir(curdir)
def ensure_list(arg):
if (isinstance(arg, string_types) or not hasattr(arg, '__iter__')):
if arg is not None:
arg = [arg]
else:
arg = []
return arg
def filter_files(files_list, prefix, filter_patterns=(r'(.*[\\\\/])?\.git[\\\\/].*',
r'(.*[\\\\/])?\.git$',
r'(.*)?\.DS_Store.*',
r'.*\.la$',
r'conda-meta.*')):
"""Remove things like the .git directory from the list of files to be copied"""
for pattern in filter_patterns:
r = re.compile(pattern)
files_list = set(files_list) - set(filter(r.match, files_list))
return [f for f in files_list if not os.path.isdir(os.path.join(prefix, f))]
def filter_info_files(files_list, prefix):
return filter_files(files_list, prefix, filter_patterns=(
'info[\\\\/]index.json',
'info[\\\\/]files',
'info[\\\\/]paths.json',
'info[\\\\/]about.json',
'info[\\\\/]has_prefix',
'info[\\\\/]hash_input_files', # legacy, not used anymore
'info[\\\\/]hash_input.json',
'info[\\\\/]run_exports.yaml', # legacy
'info[\\\\/]run_exports.json', # current
'info[\\\\/]git',
'info[\\\\/]recipe[\\\\/].*',
'info[\\\\/]recipe_log.json',
'info[\\\\/]recipe.tar',
'info[\\\\/]test[\\\\/].*',
'info[\\\\/]LICENSE.txt',
'info[\\\\/]requires',
'info[\\\\/]meta',
'info[\\\\/]platform',
'info[\\\\/]no_link',
'info[\\\\/]link.json',
'info[\\\\/]icon.png',
))
def _checksum(fd, algorithm, buffersize=65536):
hash_impl = getattr(hashlib, algorithm)
if not hash_impl:
raise ValueError("Unrecognized hash algorithm: {}".format(algorithm))
else:
hash_impl = hash_impl()
for block in iter(lambda: fd.read(buffersize), b''):
hash_impl.update(block)
return hash_impl.hexdigest()
def sha256_checksum(fd):
return _checksum(fd, 'sha256')
def md5_checksum(fd):
return _checksum(fd, 'md5')
| [
"msarahan@gmail.com"
] | msarahan@gmail.com |
eaed488643b5678c463000200f53b36f46b825ce | 1576481f1e922a56962fce7cdf12745ec94d29d0 | /pywemo/ouimeaux_device/insight.py | 66ea79f45fde64eb9ce078ca0e1c7643a9cc77a2 | [
"BSD-3-Clause",
"MIT"
] | permissive | tomwilkie/pywemo | c5478fe6c8b74909716e956ddd0495eae459cecc | 6e48ef0e7a5430b7f028a82f82b682b889d21829 | refs/heads/master | 2021-01-17T17:31:12.205633 | 2015-04-18T00:54:09 | 2015-04-18T00:54:09 | 28,048,919 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,733 | py | from datetime import datetime
from .switch import Switch
class Insight(Switch):
def __repr__(self):
return '<WeMo Insight "{name}">'.format(name=self.name)
@property
def insight_params(self):
params = self.insight.GetInsightParams().get('InsightParams')
(
state, # 0 if off, 1 if on, 8 if on but load is off
lastchange,
onfor, # seconds
ontoday, # seconds
ontotal, # seconds
timeperiod, # The period over which averages are calculated
_x, # This one is always 19 for me; what is it?
currentmw,
todaymw,
totalmw,
powerthreshold
) = params.split('|')
return {'state': state,
'lastchange': datetime.fromtimestamp(int(lastchange)),
'onfor': int(onfor),
'ontoday': int(ontoday),
'ontotal': int(ontotal),
'todaymw': int(float(todaymw)),
'totalmw': int(float(totalmw)),
'currentpower': int(float(currentmw))}
@property
def today_kwh(self):
return self.insight_params['todaymw'] * 1.6666667e-8
@property
def current_power(self):
"""
Returns the current power usage in mW.
"""
return self.insight_params['currentpower']
@property
def today_on_time(self):
return self.insight_params['ontoday']
@property
def on_for(self):
return self.insight_params['onfor']
@property
def last_change(self):
return self.insight_params['lastchange']
@property
def today_standby_time(self):
return self.insight_params['ontoday']
| [
"Paulus@PaulusSchoutsen.nl"
] | Paulus@PaulusSchoutsen.nl |
acb012a38a19f295e6d2b0a0acab5cde51f0a9f4 | 163bbb4e0920dedd5941e3edfb2d8706ba75627d | /Code/CodeRecords/2338/60763/273941.py | dfb9cb96f0d7d1e3c021894db75f11a1b60bd05f | [] | no_license | AdamZhouSE/pythonHomework | a25c120b03a158d60aaa9fdc5fb203b1bb377a19 | ffc5606817a666aa6241cfab27364326f5c066ff | refs/heads/master | 2022-11-24T08:05:22.122011 | 2020-07-28T16:21:24 | 2020-07-28T16:21:24 | 259,576,640 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 434 | py | T = int(input())
for i in range(T):
nx = list(map(int, ('' + input()).split(' ')))
n,x = nx[0],nx[1]
a = list(map(int, ('' + input()).split(' ')))
isContain = False
for j in range(n):
for k in range(n):
if j ==k:
continue
if a[j] + a[k] == x:
isContain = True
break
if isContain:
print("Yes")
else:
print("No") | [
"1069583789@qq.com"
] | 1069583789@qq.com |
7a98a4faf482eda836808da7fca33248732e244b | b6cac88da54791fe3b1588882ad13745d7a72a31 | /visualize/migrations/0003_bookmark_description.py | aca98a7a7cd07ebcf5658f82adfb7fccaf05b921 | [] | no_license | MidAtlanticPortal/mp-visualize | d662352a344c27c1493bcde34664a89c08453e8d | 300281f461aced50fd8a57e2dfbd5b8c75d4e911 | refs/heads/main | 2022-11-10T18:28:13.699794 | 2021-05-13T16:24:23 | 2021-05-13T16:24:23 | 44,761,880 | 1 | 1 | null | 2022-10-15T00:27:09 | 2015-10-22T17:32:28 | JavaScript | UTF-8 | Python | false | false | 455 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('visualize', '0002_content'),
]
operations = [
migrations.AddField(
model_name='bookmark',
name='description',
field=models.TextField(default=None, null=True, blank=True),
preserve_default=True,
),
]
| [
"ryan.d.hodges@gmail.com"
] | ryan.d.hodges@gmail.com |
44050fcf2efb032490eda335ee86a27171c500a6 | 152f54367e5a9f633217f5d1c9f327158d90bc85 | /sms.py | fac199f987b086c76ffb26f677a537be08f50c36 | [] | no_license | makalaaneesh/python-scripts | cf506bc62cb01f56367a510a81132ec5568bca98 | 40750a0a24db8c022b0fe1b16992d57817b764c2 | refs/heads/master | 2021-01-18T21:35:30.682773 | 2016-04-29T19:17:05 | 2016-04-29T19:17:05 | 29,910,777 | 0 | 2 | null | 2015-11-12T16:00:48 | 2015-01-27T11:17:06 | Python | UTF-8 | Python | false | false | 397 | py | headers = {
"X-Mashape-Key": "KEY"
}
import requests
message = "Double check. i could spam you you know"
semi_colon = '%3B'
phone = 'xx;xx'
username = 'phonenumber'
password = 'password' #1450
response = requests.get("https://freesms8.p.mashape.com/index.php?msg="+message+"&phone="+phone+"&pwd="+password+"&uid="+username, headers=headers)
print response.status_code
print response.content
| [
"makalaaneesh@yahoo.com"
] | makalaaneesh@yahoo.com |
0ae02dca88b48b82467eec4cc534e533f872f722 | 93713f46f16f1e29b725f263da164fed24ebf8a8 | /Library/lib/python3.7/site-packages/terminado/uimodule.py | 584259c87499503331c62bd650f9b84fe6358e97 | [
"BSD-3-Clause"
] | permissive | holzschu/Carnets | b83d15136d25db640cea023abb5c280b26a9620e | 1ad7ec05fb1e3676ac879585296c513c3ee50ef9 | refs/heads/master | 2023-02-20T12:05:14.980685 | 2023-02-13T15:59:23 | 2023-02-13T15:59:23 | 167,671,526 | 541 | 36 | BSD-3-Clause | 2022-11-29T03:08:22 | 2019-01-26T09:26:46 | Python | UTF-8 | Python | false | false | 1,012 | py | """A Tornado UI module for a terminal backed by terminado.
See the Tornado docs for information on UI modules:
http://www.tornadoweb.org/en/stable/guide/templates.html#ui-modules
"""
# Copyright (c) Jupyter Development Team
# Copyright (c) 2014, Ramalingam Saravanan <sarava@sarava.net>
# Distributed under the terms of the Simplified BSD License.
import os.path
import tornado.web
class Terminal(tornado.web.UIModule):
def render(self, ws_url, cols=80, rows=25):
return ('<div class="terminado-container" '
'data-ws-url="{ws_url}" '
'data-rows="{rows}" data-cols="{cols}"/>').format(
ws_url=ws_url, rows=rows, cols=cols)
def javascript_files(self):
# TODO: Can we calculate these dynamically?
return ['/xstatic/termjs/term.js', '/static/terminado.js']
def embedded_javascript(self):
file = os.path.join(os.path.dirname(__file__), 'uimod_embed.js')
with open(file) as f:
return f.read()
| [
"nicolas.holzschuch@inria.fr"
] | nicolas.holzschuch@inria.fr |
8d3cdc75dc12985fae9f51ea8f9279df7717d4ba | 1bfad01139237049eded6c42981ee9b4c09bb6de | /RestPy/ixnetwork_restpy/testplatform/sessions/ixnetwork/topology/learnedlspindex.py | 3c6d7aba9e95f03e6a73232b9e12d28bd68c0c92 | [
"MIT"
] | permissive | kakkotetsu/IxNetwork | 3a395c2b4de1488994a0cfe51bca36d21e4368a5 | f9fb614b51bb8988af035967991ad36702933274 | refs/heads/master | 2020-04-22T09:46:37.408010 | 2019-02-07T18:12:20 | 2019-02-07T18:12:20 | 170,284,084 | 0 | 0 | MIT | 2019-02-12T08:51:02 | 2019-02-12T08:51:01 | null | UTF-8 | Python | false | false | 2,468 | py |
# Copyright 1997 - 2018 by IXIA Keysight
#
# 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 ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class LearnedLspIndex(Base):
"""The LearnedLspIndex class encapsulates a required learnedLspIndex node in the ixnetwork hierarchy.
An instance of the class can be obtained by accessing the LearnedLspIndex property from a parent instance.
The internal properties list will contain one and only one set of properties which is populated when the property is accessed.
"""
_SDM_NAME = 'learnedLspIndex'
def __init__(self, parent):
super(LearnedLspIndex, self).__init__(parent)
@property
def Count(self):
"""total number of values
Returns:
number
"""
return self._get_attribute('count')
def FetchAndUpdateConfigFromCloud(self, Mode):
"""Executes the fetchAndUpdateConfigFromCloud operation on the server.
Args:
Arg1 (str(None|/api/v1/sessions/1/ixnetwork/globals?deepchild=*|/api/v1/sessions/1/ixnetwork/topology?deepchild=*)): The method internally sets Arg1 to the current href for this instance
Mode (str):
Raises:
NotFoundError: The requested resource does not exist on the server
ServerError: The server has encountered an uncategorized error condition
"""
Arg1 = self.href
return self._execute('FetchAndUpdateConfigFromCloud', payload=locals(), response_object=None)
| [
"hubert.gee@keysight.com"
] | hubert.gee@keysight.com |
6f403e6bceb52c0706ae8c96e1056976c974d6cc | bb33e6be8316f35decbb2b81badf2b6dcf7df515 | /source/res/scripts/client/gui/scaleform/daapi/view/lobby/MinimapLobby.py | 32508605dd055d92317f7e646f0d28a40723876c | [] | no_license | StranikS-Scan/WorldOfTanks-Decompiled | 999c9567de38c32c760ab72c21c00ea7bc20990c | d2fe9c195825ececc728e87a02983908b7ea9199 | refs/heads/1.18 | 2023-08-25T17:39:27.718097 | 2022-09-22T06:49:44 | 2022-09-22T06:49:44 | 148,696,315 | 103 | 39 | null | 2022-09-14T17:50:03 | 2018-09-13T20:49:11 | Python | UTF-8 | Python | false | false | 3,856 | py | # Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: scripts/client/gui/Scaleform/daapi/view/lobby/MinimapLobby.py
import ArenaType
from gui.Scaleform.daapi.view.meta.MinimapPresentationMeta import MinimapPresentationMeta
from gui.Scaleform.locale.RES_ICONS import RES_ICONS
from helpers import dependency
from skeletons.account_helpers.settings_core import ISettingsCore
class MinimapLobby(MinimapPresentationMeta):
settingsCore = dependency.descriptor(ISettingsCore)
def __init__(self):
super(MinimapLobby, self).__init__()
self.__playerTeam = 1
self.__arenaTypeID = None
self.__cfg = dict()
self.__minimapSize = 300
return
def _populate(self):
super(MinimapLobby, self)._populate()
self.settingsCore.onSettingsChanged += self.onSettingsChanging
def _dispose(self):
self.settingsCore.onSettingsChanged -= self.onSettingsChanging
super(MinimapLobby, self)._dispose()
def onSettingsChanging(self, diff):
if 'isColorBlind' in diff:
self.as_updatePointsS()
def setMap(self, arenaID):
self.setArena(arenaID)
def setMinimapData(self, arenaID, playerTeam, size):
self.__minimapSize = size
self.__playerTeam = playerTeam
self.setArena(arenaID)
def setPlayerTeam(self, playerTeam):
self.__playerTeam = playerTeam
def swapTeams(self, team):
doBuild = False
if not team:
team = 1
if team is not self.__playerTeam:
self.__playerTeam = team
doBuild = True
if doBuild and self.__arenaTypeID is not None:
self.build()
return
def setArena(self, arenaTypeID):
self.__arenaTypeID = int(arenaTypeID)
arenaType = ArenaType.g_cache[self.__arenaTypeID]
cfg = {'texture': RES_ICONS.getMapPath(arenaType.geometryName),
'size': arenaType.boundingBox,
'teamBasePositions': arenaType.teamBasePositions,
'teamSpawnPoints': arenaType.teamSpawnPoints,
'controlPoints': arenaType.controlPoints}
self.setConfig(cfg)
def setEmpty(self):
self.as_clearS()
path = RES_ICONS.getMapPath('question')
self.as_changeMapS(path)
def setConfig(self, cfg):
self.__cfg = cfg
self.build()
def build(self):
self.as_clearS()
self.as_changeMapS(self.__cfg['texture'])
bottomLeft, upperRight = self.__cfg['size']
mapWidthMult, mapHeightMult = (upperRight - bottomLeft) / self.__minimapSize
offset = (upperRight + bottomLeft) * 0.5
def _normalizePoint(posX, posY):
return ((posX - offset.x) / mapWidthMult, (posY - offset.y) / mapHeightMult)
for team, teamSpawnPoints in enumerate(self.__cfg['teamSpawnPoints'], 1):
for spawn, spawnPoint in enumerate(teamSpawnPoints, 1):
posX, posY = _normalizePoint(spawnPoint[0], spawnPoint[1])
self.as_addPointS(posX, posY, 'spawn', 'blue' if team == self.__playerTeam else 'red', spawn + 1 if len(teamSpawnPoints) > 1 else 1)
for team, teamBasePoints in enumerate(self.__cfg['teamBasePositions'], 1):
for baseNumber, basePoint in enumerate(teamBasePoints.values(), 2):
posX, posY = _normalizePoint(basePoint[0], basePoint[1])
self.as_addPointS(posX, posY, 'base', 'blue' if team == self.__playerTeam else 'red', baseNumber if len(teamBasePoints) > 1 else 1)
if self.__cfg['controlPoints']:
for index, controlPoint in enumerate(self.__cfg['controlPoints'], 2):
posX, posY = _normalizePoint(controlPoint[0], controlPoint[1])
self.as_addPointS(posX, posY, 'control', 'empty', index if len(self.__cfg['controlPoints']) > 1 else 1)
| [
"StranikS_Scan@mail.ru"
] | StranikS_Scan@mail.ru |
90c9232164970d90d692cc1657a3835b8b64f6ad | 255e19ddc1bcde0d3d4fe70e01cec9bb724979c9 | /dockerized-gists/93666/snippet.py | c0127e80358508837ecd626a3fa2379bf4e75d2d | [
"MIT"
] | permissive | gistable/gistable | 26c1e909928ec463026811f69b61619b62f14721 | 665d39a2bd82543d5196555f0801ef8fd4a3ee48 | refs/heads/master | 2023-02-17T21:33:55.558398 | 2023-02-11T18:20:10 | 2023-02-11T18:20:10 | 119,861,038 | 76 | 19 | null | 2020-07-26T03:14:55 | 2018-02-01T16:19:24 | Python | UTF-8 | Python | false | false | 702 | py | def format_filename(s):
"""Take a string and return a valid filename constructed from the string.
Uses a whitelist approach: any characters not present in valid_chars are
removed. Also spaces are replaced with underscores.
Note: this method may produce invalid filenames such as ``, `.` or `..`
When I use this method I prepend a date string like '2009_01_15_19_46_32_'
and append a file extension like '.txt', so I avoid the potential of using
an invalid filename.
"""
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
filename = ''.join(c for c in s if c in valid_chars)
filename = filename.replace(' ','_') # I don't like spaces in filenames.
return filename | [
"gistshub@gmail.com"
] | gistshub@gmail.com |
5e4805054d945c675d646fdf4e1f6df585066afe | 30fcd4c53519cd17497106cbe963f4f28d5c4edd | /shopping_list.py | d52b1975c3a343ac0640ff59620aa3bf1aba9b94 | [] | no_license | aymeet/shopping_list | 1e0300a85cf7443662c1829f5a73ae01b739a99b | c6d2252d1211621e8e056d51d6cbb05abe0a1a40 | refs/heads/master | 2021-01-20T04:09:46.330549 | 2017-04-28T00:56:49 | 2017-04-28T00:56:49 | 89,649,186 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,612 | py | """
Shopping List (Hackbright Prep dictionary code challenge)
Create a dictionary of shopping lists, and be able to
* add / remove lists
* add / remove items from lists
"""
def add_new_shopping_list(lists_by_name, new_list_name):
"""Add new shopping list to dict: key is list name, value is empty list
Will not allow duplicate shopping list names to be added. This method
is case-sensitive.
Arguments:
lists_by_name: dict of shopping lists
new_list_name: string name of the new list to add
Returns:
None
"""
if lists_by_name.get(new_list_name) is None:
lists_by_name[new_list_name] = []
print lists_by_name
def remove_shopping_list(lists_by_name, list_name_to_remove):
"""Remove shopping list from shopping lists dict.
If the shopping list name does not exist in the dictionary, print a message
and do nothing. This method is case-sensitive.
Arguments:
lists_by_name: dict of shopping lists
list_name_to_remove: string name of the list to remove
Returns:
None
"""
if lists_by_name.get(list_name_to_remove) is None:
print list_name_to_remove + " does not exist"
else:
del lists_by_name[list_name_to_remove]
def add_to_shopping_list(lists_by_name, list_name, items):
"""Add given items to shopping list.
Arguments:
lists_by_name: dict of shopping lists
list_name: string name of a shopping list
items: list of items to add to the list
Returns:
None
"""
# your code here!
pass
def remove_from_shopping_list(lists_by_name, list_name, items):
"""Remove given items from shopping list.
If an item doesn't exist in the list, print an error, and continue to
attempt to remove the other items.
Arguments:
lists_by_name: dict of shopping lists
list_name: string name of a shopping list
items: list of items to remove from the list
Returns:
None
"""
# your code here!
pass
def display_shopping_list(lists_by_name, list_name):
"""Print the contents of a shopping list.
If the list is missing, return a string message saying so. This function is
case sensitive.
Arguments:
lists_by_name: dict of shopping lists
list_name: string name of a shopping list
Returns:
None
"""
for item in lists_by_name:
print item
def show_all_lists(lists_by_name):
"""Given a dictionary of shopping lists, print out each list.
Arguments:
lists_by_name: dict of shopping lists
Returns:
None
"""
for item in lists_by_name:
print item
def parse_string_of_items(items_string):
"""Split input string on commas and return the list of items.
Trim leading and trailing whitespace.
Arguments:
items_string: a string with 0 or more commas separating items
Returns:
list of strings
"""
# list to return, starts out empty
items = []
# split the items_string on commas into a temporary list
temp_items = items_string.split(',')
# iterate through the temporary list and strip white space from each item
# before appending it to the list to be returned
for item in temp_items:
items.append(item.strip())
return items
def edit_shopping_list(lists_by_name, list_name, add_or_remove):
"""Get items from user and add / remove them from the shopping list
Arguments:
lists_by_name: dict of shopping lists
list_name: string name of a shopping list
add_or_remove: string that is either 'add' or 'remove', indicating whether
the collected items should be added to or removed from the list
Returns:
None
"""
# if so, get items to add to the list
input_str = raw_input('Please enter items separated by commas: ')
# list-ify the input string
items = parse_string_of_items(input_str)
# add or remove, according to the argument
if add_or_remove == 'add':
add_to_shopping_list(shopping_lists_by_name, list_name, items)
else:
remove_from_shopping_list(shopping_lists_by_name, list_name, items)
def get_menu_choice():
"""Print a menu and asks the user to make a choice.
Arguments:
None
Returns:
int: the user's menu choice
"""
print '\n 0 - Main Menu'
print ' 1 - Show all lists.'
print ' 2 - Show a specific list.'
print ' 3 - Add a new shopping list.'
print ' 4 - Add item(s) to a shopping list.'
print ' 5 - Remove items(s) from a shopping list.'
print ' 6 - Remove a list by name.'
print ' 7 - Exit the program.\n'
choice = int(raw_input('Choose from the menu options: '))
return choice
def execute_repl(shopping_lists_by_name):
"""Execute the repl loop for the control structure of the program.
(REPL stands for Read - Eval - Print Loop. For more info:
https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop)
Arguments:
shopping_lists_by_name: dict of shopping lists
Returns:
None
"""
while True:
# get the next choice from the user
choice = get_menu_choice()
if choice == 0:
# main menu
continue # continue goes to the next loop iteration
elif choice == 1:
# show all lists
# call function to display all lists
show_all_lists(shopping_lists_by_name)
elif choice == 3:
# Add a new shopping list
# get name of list and add it
list_name = raw_input('Enter the name for your list: ')
add_new_shopping_list(shopping_lists_by_name, list_name)
# get items for list and add them
input_str = raw_input('Please enter items separated by commas: ')
items = parse_string_of_items(input_str)
shopping_lists_by_name[list_name] = items
elif choice == 7:
# quit
break
else:
# all of the remaning choices require an existing list. First, run
# code to get the list name from the user and verify it exists in
# the dict
# determine which list
list_name = raw_input('Which list would you like to see? ')
# test to see if the list is in the shopping list dict
if list_name not in shopping_lists_by_name:
# no list by this name :-(
print 'There is no {} list.'.format(list_name)
continue
# if the code reaches this point, it means the list exists in the
# dictionary, so proceed according to which choice was chosen
if choice == 2:
# show a specific list
display_shopping_list(shopping_lists_by_name, list_name)
elif choice == 4:
# Add item(s) to a shopping list
# add items to the shopping list
edit_shopping_list(shopping_lists_by_name, list_name, 'add')
elif choice == 5:
# Remove an item from a shopping list
# add items to the shopping list
edit_shopping_list(shopping_lists_by_name, list_name, 'remove')
elif choice == 6:
# remove list
remove_shopping_list(shopping_lists_by_name, list_name)
# Main code here
shopping_lists_by_name = {} # key is list name, value is [shopping list]
execute_repl(shopping_lists_by_name)
| [
"no-reply@hackbrightacademy.com"
] | no-reply@hackbrightacademy.com |
913e29f0f26471e63160c9235f604a5c3154198b | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_141/ch18_2020_09_09_19_35_24_611574.py | 7b2fd62536d60fa3e0c59e54e26d481a70df8eba | [] | 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 | 184 | py | def verifica_idade(anos):
if anos >= 18:
print("Liberado BRASIL")
elif anos >= 21:
print("Liberado EUA e BRASIL")
else:
print("Não está liberado") | [
"you@example.com"
] | you@example.com |
5f0c1da84c218d3c1464c3f4c1c30f0baff4e48a | 06119696c70c8e5458102f380d1842b3e3717b13 | /wassh/bin/lint | 6f621bc57a7ea6309db65fdbbd07aa1fc8691e09 | [
"BSD-2-Clause"
] | permissive | lproux/chOSapp | f166ad701857ce0f5b1bcafe97e778ff310ebdcc | 9c7e724c23bfca141a68c9a7d3639075ea908d52 | refs/heads/main | 2023-05-05T09:08:59.607603 | 2021-05-14T07:45:40 | 2021-05-14T17:31:07 | 367,856,793 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,840 | #!/usr/bin/env python3
# Copyright 2020 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Lint our source files."""
import os
from pathlib import Path
import sys
import wassh
import libdot
JS_DIR = wassh.DIR / 'js'
WJB_DIR = wassh.DIR.parent / 'wasi-js-bindings'
def _get_default_paths(basedir):
"""Get list of paths to lint by default."""
most_files = sorted(x for x in libdot.lint.get_known_sources(basedir)
if x.suffix not in {'.js'})
# All files in js/*.js.
# Use relpath for nicer default output.
js_files = sorted(JS_DIR.glob('**/*.js'))
return [os.path.relpath(x) for x in most_files + js_files]
def main(argv):
"""The main func!"""
# We need to use an absolute path with the module root to workaround
# https://github.com/google/closure-compiler/issues/3580
for i, arg in enumerate(argv):
path = Path(arg)
if arg and arg[0] != '-' and path.exists():
argv[i] = os.path.relpath(path.resolve(), wassh.DIR)
os.chdir(wassh.DIR)
wasi_externs = WJB_DIR / 'externs'
closure_args = list(libdot.lint.DEFAULT_CLOSURE_ARGS) + [
'--js_module_root', JS_DIR,
# TODO(vapier): We want to turn this on at some point.
'--jscomp_off=strictMissingProperties',
# Let closure compiler itself do the expansion.
wassh.DIR.parent / 'wasi-js-bindings' / 'js' / '**.js',
] + [f'--externs={os.path.relpath(x)}'
for x in sorted(wasi_externs.glob('*.js'))]
return libdot.lint.main(argv, basedir=wassh.DIR,
get_default_paths=_get_default_paths,
closure_args=closure_args)
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
| [
"vapier@chromium.org"
] | vapier@chromium.org | |
4cba5aaf29add8565a672b7eacd28035fad23519 | 543286f4fdefe79bd149ff6e103a2ea5049f2cf4 | /Exercicios&cursos/eXcript/Aula 10 - Gerenciador de leiaute pack.py | 729776a1ddf43603ea188c61d45cdb88de9d361c | [] | no_license | antonioleitebr1968/Estudos-e-Projetos-Python | fdb0d332cc4f12634b75984bf019ecb314193cc6 | 9c9b20f1c6eabb086b60e3ba1b58132552a84ea6 | refs/heads/master | 2022-04-01T20:03:12.906373 | 2020-02-13T16:20:51 | 2020-02-13T16:20:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 431 | py | from tkinter import *
janela = Tk()
lb1 = Label(janela, text='label1', bg='green')
lb2 = Label(janela, text='label2', bg='red')
lb3 = Label(janela, text='label3', bg='yellow')
lb4 = Label(janela, text='label4', bg='blue')
lb2.pack()
lb1.pack()
lb3.pack()
lb4.pack(side=BOTTOM)
janela.geometry('400x300+200+200')
janela.mainloop()
#Nota: Propriedade SIDE
#TOP == TOPO
#LEFT == ESQUERDA
#RIGHT == DIREITA
#BOTTOM == INFERIOR | [
"progmatheusmorais@gmail.com"
] | progmatheusmorais@gmail.com |
42f3e50b0b2eb2a7ded8a894750027dba4d4896a | e71b6d14fbdbc57c7234ca45a47329d7d02fc6f7 | /flask_api/venv/lib/python3.7/site-packages/vsts/npm/v4_1/models/upstream_source_info.py | 21e55cba9de401017666da42d7fc8f6db31cd757 | [] | no_license | u-blavins/secret_sasquatch_society | c36993c738ab29a6a4879bfbeb78a5803f4f2a57 | 0214eadcdfa9b40254e331a6617c50b422212f4c | refs/heads/master | 2020-08-14T00:39:52.948272 | 2020-01-22T13:54:58 | 2020-01-22T13:54:58 | 215,058,646 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,359 | py | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest.serialization import Model
class UpstreamSourceInfo(Model):
"""UpstreamSourceInfo.
:param id:
:type id: str
:param location:
:type location: str
:param name:
:type name: str
:param source_type:
:type source_type: object
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'source_type': {'key': 'sourceType', 'type': 'object'}
}
def __init__(self, id=None, location=None, name=None, source_type=None):
super(UpstreamSourceInfo, self).__init__()
self.id = id
self.location = location
self.name = name
self.source_type = source_type
| [
"usama.blavins1@gmail.com"
] | usama.blavins1@gmail.com |
ef588dbdd970cdf3978c52e3416432ac5a91bdc6 | c6e22a6901bc40ba92a0470c6323929368727bbb | /src/virtual_tour/serializers.py | 636293e43ed900ce3f0403d8d5f1ce5f2aa622aa | [] | no_license | iamgaddiel/learners_coner | bdc47c7caac9898ca3a8836f1ad972afa9f88cf8 | fb3ea68de8c02d1f1db6177b7c267a743a0b5a32 | refs/heads/main | 2023-08-04T06:12:08.728355 | 2021-09-13T04:24:42 | 2021-09-13T04:24:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 202 | py | from rest_framework import serializers
from .models import VirtualTour
class VirtualTourSerializer(serializers.ModelSerializer):
class Meta:
model = VirtualTour
fields = '__all__'
| [
"gaddiel@localhost.localdomain"
] | gaddiel@localhost.localdomain |
ce2e26a49d8a3dcfc7b90e49e4999c830e6b0d4f | 0f835a836f1885f8802db10813603862f8aabf7c | /src/todo/urls.py | 778e7ed416a3458d65f6e5c66a824e6dabaf776c | [] | no_license | yordan-marinov/su_dj_basics | 80eecd75630599f4458c36af16366d547d215d00 | 24cbe5b291c495cbb77a650766fd5689ba191451 | refs/heads/main | 2023-06-06T07:25:50.297776 | 2021-06-22T08:21:20 | 2021-06-22T08:21:20 | 370,289,231 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 332 | py | from django.urls import path
from .views import todo_create, todo_delete, todo_edit, todo_list
urlpatterns = [
path("", todo_list, name="todo_list"),
path("create/", todo_create, name="todo_create"),
path("edit/<int:pk>/", todo_edit, name="todo_edit"),
path("delete/<int:pk>/", todo_delete, name="todo_delete"),
]
| [
"jordanmarinov8@gmail.com"
] | jordanmarinov8@gmail.com |
3500ef3acf09023a8b49b10527ae01d5437a8ccc | 5a1f77b71892745656ec9a47e58a078a49eb787f | /1_Kithgard_Dungeon/052-Kithgard_Gates/kithgard_gates.py | 57be0f04eaee30b7cb49cb7d20dd33a2803f9efa | [
"MIT"
] | permissive | ripssr/Code-Combat | 78776e7e67c033d131e699dfeffb72ca09fd798e | fbda1ac0ae4a2e2cbfce21492a2caec8098f1bef | refs/heads/master | 2020-06-11T20:17:59.817187 | 2019-07-21T09:46:04 | 2019-07-21T09:46:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 174 | py | # You need the Elemental codex 1+ to cast "Haste"
# You need the Emperor's gloves to cast "Chain Lightning"
hero.cast("haste", hero);
hero.moveDown(0.7)
hero.moveRight(2.5)
| [
"katik.hello@gmail.com"
] | katik.hello@gmail.com |
7851674a43efd44e592eebdb0548527abaec7298 | 51f887286aa3bd2c3dbe4c616ad306ce08976441 | /pybind/slxos/v17r_1_01a/interface/ethernet/link_oam_interface/remote_failure/link_fault/__init__.py | e4db3e5baa84ab0f2cd42f54cb3ae5914099cac4 | [
"Apache-2.0"
] | permissive | b2220333/pybind | a8c06460fd66a97a78c243bf144488eb88d7732a | 44c467e71b2b425be63867aba6e6fa28b2cfe7fb | refs/heads/master | 2020-03-18T09:09:29.574226 | 2018-04-03T20:09:50 | 2018-04-03T20:09:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,033 | py |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from decimal import Decimal
from bitarray import bitarray
import __builtin__
class link_fault(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module brocade-interface - based on the path /interface/ethernet/link-oam-interface/remote-failure/link-fault. Each member element of
the container is represented as a class variable - with a specific
YANG type.
"""
__slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__link_fault_action',)
_yang_name = 'link-fault'
_rest_name = 'link-fault'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
path_helper_ = kwargs.pop("path_helper", None)
if path_helper_ is False:
self._path_helper = False
elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper):
self._path_helper = path_helper_
elif hasattr(self, "_parent"):
path_helper_ = getattr(self._parent, "_path_helper", False)
self._path_helper = path_helper_
else:
self._path_helper = False
extmethods = kwargs.pop("extmethods", None)
if extmethods is False:
self._extmethods = False
elif extmethods is not None and isinstance(extmethods, dict):
self._extmethods = extmethods
elif hasattr(self, "_parent"):
extmethods = getattr(self._parent, "_extmethods", None)
self._extmethods = extmethods
else:
self._extmethods = False
self.__link_fault_action = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'block-interface': {'value': 1}},), is_leaf=True, yang_name="link-fault-action", rest_name="action", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-full-command': None, u'info': u'Configures an action for the event', u'cli-full-no': None, u'alt-name': u'action'}}, namespace='urn:brocade.com:mgmt:brocade-dot3ah', defining_module='brocade-dot3ah', yang_type='action-type', is_config=True)
load = kwargs.pop("load", None)
if args:
if len(args) > 1:
raise TypeError("cannot create a YANG container with >1 argument")
all_attr = True
for e in self._pyangbind_elements:
if not hasattr(args[0], e):
all_attr = False
break
if not all_attr:
raise ValueError("Supplied object did not have the correct attributes")
for e in self._pyangbind_elements:
nobj = getattr(args[0], e)
if nobj._changed() is False:
continue
setmethod = getattr(self, "_set_%s" % e)
if load is None:
setmethod(getattr(args[0], e))
else:
setmethod(getattr(args[0], e), load=load)
def _path(self):
if hasattr(self, "_parent"):
return self._parent._path()+[self._yang_name]
else:
return [u'interface', u'ethernet', u'link-oam-interface', u'remote-failure', u'link-fault']
def _rest_path(self):
if hasattr(self, "_parent"):
if self._rest_name:
return self._parent._rest_path()+[self._rest_name]
else:
return self._parent._rest_path()
else:
return [u'interface', u'Ethernet', u'link-oam', u'remote-failure', u'link-fault']
def _get_link_fault_action(self):
"""
Getter method for link_fault_action, mapped from YANG variable /interface/ethernet/link_oam_interface/remote_failure/link_fault/link_fault_action (action-type)
"""
return self.__link_fault_action
def _set_link_fault_action(self, v, load=False):
"""
Setter method for link_fault_action, mapped from YANG variable /interface/ethernet/link_oam_interface/remote_failure/link_fault/link_fault_action (action-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_link_fault_action is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_link_fault_action() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'block-interface': {'value': 1}},), is_leaf=True, yang_name="link-fault-action", rest_name="action", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-full-command': None, u'info': u'Configures an action for the event', u'cli-full-no': None, u'alt-name': u'action'}}, namespace='urn:brocade.com:mgmt:brocade-dot3ah', defining_module='brocade-dot3ah', yang_type='action-type', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """link_fault_action must be of a type compatible with action-type""",
'defined-type': "brocade-dot3ah:action-type",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'block-interface': {'value': 1}},), is_leaf=True, yang_name="link-fault-action", rest_name="action", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-full-command': None, u'info': u'Configures an action for the event', u'cli-full-no': None, u'alt-name': u'action'}}, namespace='urn:brocade.com:mgmt:brocade-dot3ah', defining_module='brocade-dot3ah', yang_type='action-type', is_config=True)""",
})
self.__link_fault_action = t
if hasattr(self, '_set'):
self._set()
def _unset_link_fault_action(self):
self.__link_fault_action = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'block-interface': {'value': 1}},), is_leaf=True, yang_name="link-fault-action", rest_name="action", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-full-command': None, u'info': u'Configures an action for the event', u'cli-full-no': None, u'alt-name': u'action'}}, namespace='urn:brocade.com:mgmt:brocade-dot3ah', defining_module='brocade-dot3ah', yang_type='action-type', is_config=True)
link_fault_action = __builtin__.property(_get_link_fault_action, _set_link_fault_action)
_pyangbind_elements = {'link_fault_action': link_fault_action, }
| [
"badaniya@brocade.com"
] | badaniya@brocade.com |
2f515b8a5dbe71e724bfe160a4d7abc563bd68f7 | 3d96cee3f0c986c7195e7677d85e91dc837d8dd4 | /venv/bin/pip3 | 4b76198db216e8fbf6aa3d14a970e17ee8167061 | [] | no_license | dannycrief/full-stack-web-dev-couse | 7faffe1c9e6c39baf03d6ee54f716e4f8b4c8733 | 0b22bc84742d8e78bd6a2e03adfbc44137f3d607 | refs/heads/master | 2023-01-12T09:25:16.378035 | 2021-03-21T16:51:18 | 2021-03-21T16:51:18 | 220,825,261 | 0 | 1 | null | 2023-01-05T12:57:14 | 2019-11-10T17:34:02 | Python | UTF-8 | Python | false | false | 272 | #!/home/skozurak/Projects/full-stack-web-dev-couse/venv/bin/python3.8
# -*- coding: utf-8 -*-
import re
import sys
from pip._internal.cli.main import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())
| [
"step.kozbvb@gmail.com"
] | step.kozbvb@gmail.com | |
60ae92e25652dac7f0639f7d268ef2bde0015f14 | 723a0ff7e88b5c64bc712be8faa7721c40a9be92 | /torch_chemistry/datasets/utils.py | 57cdea4c70245f8240305a7413b23ce0bdc5e732 | [
"MIT"
] | permissive | wengelearning/pytorch_chemistry | b9b3e328dadf7efa9c6304c15dea0cabbfedac50 | 14ca01ab2a30728016ce6c6793f119438a09ade5 | refs/heads/master | 2022-04-05T11:54:32.773305 | 2020-03-01T07:38:22 | 2020-03-01T07:38:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,461 | py | import os
import shutil
from pathlib import Path
from zipfile import ZipFile
from typing import List
import requests
import torch
import torch.nn.functional as F
from ..utils import to_Path
def check_download_file_size(url: str) -> int:
res = requests.head(url)
size = res.headers['content-length']
return int(size)
def check_local_file_size(filename: str) -> int:
p = to_Path(filename)
info = os.stat(p)
return info.st_size
def download(url: str = '', filename: str = '', savedir: str ='.') -> int:
savefile = to_Path(savedir) / filename
if not savefile.exists():
with requests.get(url, stream=True) as r:
with open(savefile, 'wb') as f:
shutil.copyfileobj(r.raw, f)
return savefile
def extract_zipfile(zfilename: str, extractdir: str ='.') -> List[str]:
with ZipFile(zfilename) as zipfile:
zipfile.extractall(extractdir)
namelist = zipfile.namelist()
return namelist
def to_sparse(x: torch.tensor, max_size: int = None):
""" ref: https://discuss.pytorch.org/t/how-to-convert-a-dense-matrix-to-a-sparse-one/7809 """
""" converts dense tensor x to sparse format """
x_typename = torch.typename(x).split('.')[-1]
sparse_tensortype = getattr(torch.sparse, x_typename)
indices = torch.nonzero(x)
if len(indices.shape) == 0: # if all elements are zeros
return sparse_tensortype(*x.shape)
indices = indices.t()
values = x[tuple(indices[i] for i in range(indices.shape[0]))]
if max_size is None:
return sparse_tensortype(indices, values, x.size())
else:
return sparse_tensortype(indices, values, (max_size, max_size))
def get_mol_edge_index(mol, edge_types: dict):
row, col, bond_idx = [], [], []
for bond in mol.GetBonds():
start, end = bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()
row += [start, end]
col += [end, start]
bond_idx += 2 * [edge_types[bond.GetBondType()]]
edge_index = torch.tensor([row, col], dtype=torch.long)
edge_attr = F.one_hot(torch.tensor(bond_idx).long(),
num_classes=len(edge_types)).to(torch.long)
return edge_index, edge_attr
def to_one_hot(x: torch.tensor, n_classes: int):
length = len(x)
if length < n_classes:
_x = torch.arange(length)
out = torch.zeros(length, n_classes)
out[_x, x] = 1
return out
return torch.eye(length, n_classes)[x, :]
| [
"kbu94982@gmail.com"
] | kbu94982@gmail.com |
4e01761c4fbcb7957337a1f92fd2e922997fc09d | 3ca49c828f75d5d4880dbd4b940f93285e505f26 | /resources/icon_src/plot_ot_bx.py | b61d63391cb87a6827508d0a13d7bd36d4fa0726 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | permissive | liangwang0734/Viscid | fc15c71725f3c55eafe7d91822347f00de1ea6d4 | 41e19fee8576c5e3fa9c758c48731bc25e1db1b9 | refs/heads/master | 2021-08-30T11:32:21.157520 | 2017-06-08T22:58:29 | 2017-06-08T22:58:29 | 48,387,722 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 384 | py | import matplotlib.pyplot as plt
import seaborn as sns
import viscid
from viscid.plot import vpyplot as vlt
f = viscid.load_file('./otico_001.3d.xdmf')
mymap = sns.diverging_palette(28, 240, s=95, l=50, as_cmap=True)
figure = plt.figure(figsize=(14, 10))
g = f.get_grid(time=12)
vlt.plot(g['bx']['z=0'], cmap=mymap, style='contourf', levels=256)
vlt.savefig('OT_bx.png')
plt.show()
| [
"kristofor.maynard@gmail.com"
] | kristofor.maynard@gmail.com |
8a6957b4940d94bee65df73706811ee6ed17110d | 4ae6482f032a0bf185598e1ee607021cae881f7c | /word2vec.py | ced07e8595fa11971641f8138c9a67fd5e2f6265 | [] | no_license | stiero/sick-spence | 074ce903faf0e730b33c3f95f96db27206c5831e | ce47740ab4f63c2fe4ae9871bb7c8f1b4ffaa34a | refs/heads/master | 2021-10-11T16:35:21.356768 | 2019-01-28T17:00:39 | 2019-01-28T17:00:39 | 125,160,717 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,282 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 9 16:31:26 2018
@author: henson
"""
import re
import os
os.chdir("/home/henson/Desktop/conditions")
from gensim.models.word2vec import Word2Vec
from nltk.corpus import stopwords
from nltk import RegexpTokenizer
from nltk.stem.lancaster import LancasterStemmer
stop = set(stopwords.words('english'))
tkr = RegexpTokenizer('[a-zA-Z0-9@]+')
stemmer = LancasterStemmer()
def file_read(file):
fp = open(file, "r")
lines = [tkr.tokenize(line.lower()) for line in fp.readlines()]
#lines = [line for sublist in lines for line in sublist]
#lines = [stemmer.stem(line) for sublist in lines for line in sublist]
#lines = [line for sublist in lines for line in sublist]
#lines = list(set(lines))
regex = re.compile('([^\s\w]|_)+')
cleaned_lines = []
for line in lines:
line_temp = regex.sub('', str(line))
line_temp = tkr.tokenize(line_temp)
#line_temp = line_temp.lower()
cleaned_lines.append(line_temp)
cleaned_lines = list(filter(None, cleaned_lines))
return cleaned_lines
#return lines
file_list = ["fever.txt", "asthma.txt", "chronic_pain.txt", "cold.txt", "cramps.txt",
"depression.txt", "diarrhea.txt", "dizziness.txt", "fatigue.txt",
"headache.txt", "hypertension.txt", "nausea.txt", "rash.txt",
"swelling.txt", "sleepiness.txt"]
full_text = []
for file in file_list:
text = file_read(file)
#print(text)
full_text.append(text)
full_text = [item for sublist in full_text for item in sublist]
vector_size = 500
window_size=5
word2vec = Word2Vec(sentences=full_text,
size=vector_size,
window=window_size,
negative=20,
iter=100,
seed=1000,
)
#Words most similar to fever
word2vec.most_similar("fever")
#Some similarities between conditions
print(word2vec.wv.similarity("fever", "asthma"))
print(word2vec.wv.similarity("fever", "pain"))
print(word2vec.wv.similarity("cold", "fever"))
print(word2vec.wv.similarity("cold", "headache"))
print(word2vec.wv.similarity("fever", "nausea"))
| [
"you@example.com"
] | you@example.com |
79faefd38606f26118f15d3b6254830942092324 | c4c5f22b796269062f618038fdf0158ae7769487 | /python/quick_der/main.pyi | 4cb732180c3b0c851ccdf5c3605021b7b4cc11b2 | [
"BSD-2-Clause"
] | permissive | tonytheodore/quick-der | c5ce28e16c4f1e92b57825d3b083258790172c19 | 1becc1d3286a05b78eee3aa436e607c67ffd34a9 | refs/heads/master | 2021-05-07T13:46:17.488790 | 2017-11-03T15:45:26 | 2017-11-03T15:45:26 | 109,690,235 | 0 | 0 | null | 2017-11-06T12:05:57 | 2017-11-06T12:05:57 | null | UTF-8 | Python | false | false | 5,651 | pyi | # Stubs for quick_der.main (Python 3.6)
#
# NOTE: This dynamically typed stub was automatically generated by stubgen.
from asn1ate.sema import *
from typing import Any, Optional
class dprint:
enable: bool = ...
def __init__(self, s, *args) -> None: ...
def tosym(name): ...
api_prefix: str
dertag2atomsubclass: Any
class QuickDERgeneric:
outfile: Any = ...
comma1: Any = ...
comma0: Any = ...
def __init__(self, outfn, outext) -> None: ...
def write(self, txt): ...
def writeln(self, txt: str = ...): ...
def newcomma(self, comma, firstcomma: str = ...): ...
def comma(self): ...
def getcomma(self): ...
def setcomma(self, comma1, comma0): ...
def close(self): ...
class QuickDER2c(QuickDERgeneric):
to_be_defined: Any = ...
to_be_overlaid: Any = ...
cursor_offset: Any = ...
nested_typerefs: Any = ...
nested_typecuts: Any = ...
semamod: Any = ...
refmods: Any = ...
overlay_funmap: Any = ...
pack_funmap: Any = ...
psub_funmap: Any = ...
issued_typedefs: Any = ...
def __init__(self, semamod, outfn, refmods) -> None: ...
def generate_head(self): ...
def generate_tail(self): ...
def generate_overlay(self): ...
def generate_pack(self): ...
def generate_psub(self): ...
def generate_psub_sub(self, node, subquads, tp, fld): ...
def generate_overlay_node(self, node, tp, fld): ...
def generate_pack_node(self, node, **kwargs): ...
def generate_psub_node(self, node, tp, fld, prim): ...
def overlayValueAssignment(self, node, tp, fld): ...
def packValueAssignment(self, node): ...
def psubValueAssignment(self, node, tp, fld, prim): ...
def overlayTypeAssignment(self, node, tp, fld): ...
def packTypeAssignment(self, node, implicit: bool = ...): ...
def psubTypeAssignment(self, node, tp, fld, prim): ...
def overlayDefinedType(self, node, tp, fld): ...
def packDefinedType(self, node, implicit: bool = ..., outer_tag: Optional[Any] = ...): ...
unit: Any = ...
def psubDefinedType(self, node, tp, fld, prim): ...
def overlaySimpleType(self, node, tp, fld): ...
def packSimpleType(self, node, implicit: bool = ..., outer_tag: Optional[Any] = ...): ...
def psubSimpleType(self, node, tp, fld, prim): ...
def overlayTaggedType(self, node, tp, fld): ...
def packTaggedType(self, node, implicit: bool = ..., outer_tag: Optional[Any] = ...): ...
def packTaggedType_TODO(self, node, implicit: bool = ...): ...
def psubTaggedType(self, node, tp, fld, prim): ...
def overlayConstructedType(self, node, tp, fld, naked: bool = ...): ...
def psubConstructedType(self, node, tp, fld, prim): ...
def packSequenceType(self, node, implicit: bool = ..., outer_tag: str = ...): ...
def packSetType(self, node, implicit: bool = ..., outer_tag: str = ...): ...
def packChoiceType(self, node, implicit: bool = ..., outer_tag: Optional[Any] = ...): ...
def overlayRepeatingStructureType(self, node, tp, fld): ...
def psubRepeatingStructureType(self, node, tp, fld, prim): ...
def packSequenceOfType(self, node, implicit: bool = ..., outer_tag: str = ...): ...
def packSetOfType(self, node, implicit: bool = ..., outer_tag: str = ...): ...
class QuickDER2py(QuickDERgeneric):
cursor_offset: Any = ...
nested_typerefs: Any = ...
nested_typecuts: Any = ...
semamod: Any = ...
refmods: Any = ...
funmap_pytype: Any = ...
def __init__(self, semamod, outfn, refmods) -> None: ...
def comment(self, text): ...
def generate_head(self): ...
def generate_tail(self): ...
def generate_values(self): ...
def pygenValueAssignment(self, node): ...
def pyvalInteger(self, valnode): ...
def pyvalOID(self, valnode): ...
def generate_classes(self): ...
def pygenTypeAssignment(self, node): ...
def generate_pytype(self, node, **subarg): ...
unit: Any = ...
def pytypeDefinedType(self, node, **subarg): ...
def pytypeSimple(self, node, implicit_tag: Optional[Any] = ...): ...
def pytypeTagged(self, node, implicit_tag: Optional[Any] = ...): ...
def pytypeNamedType(self, node, **subarg): ...
def pyhelpConstructedType(self, node): ...
def pytypeChoice(self, node, implicit_tag: Optional[Any] = ...): ...
def pytypeSequence(self, node, implicit_tag: str = ...): ...
def pytypeSet(self, node, implicit_tag: str = ...): ...
def pyhelpRepeatedType(self, node, dertag, recptag): ...
def pytypeSequenceOf(self, node, implicit_tag: str = ...): ...
def pytypeSetOf(self, node, implicit_tag: str = ...): ...
class QuickDER2testdata(QuickDERgeneric):
semamod: Any = ...
refmods: Any = ...
type2tdgen: Any = ...
funmap_tdgen: Any = ...
def __init__(self, semamod, outfn, refmods) -> None: ...
def fetch_one(self, typename, casenr): ...
def fetch_multi(self, typename, testcases): ...
def all_typenames(self): ...
def generate_testdata(self): ...
def process_TypeAssignment(self, node): ...
def generate_tdgen(self, node, **subarg): ...
def tdgenDefinedType(self, node, **subarg): ...
def der_prefixhead(self, tag, body): ...
simple_cases: Any = ...
def tdgenSimple(self, node): ...
def tdgenNamedType(self, node, **subarg): ...
nodeclass2basaltag: Any = ...
def tdgenTagged(self, node, implicit_tag: Optional[Any] = ...): ...
def tdgenChoice(self, node, implicit_tag: Optional[Any] = ...): ...
def tdgenConstructed(self, node, implicit_tag: Optional[Any] = ...): ...
def tdgenRepeated(self, node, **subarg): ...
def main(script_name, script_args): ...
| [
"gijs@pythonic.nl"
] | gijs@pythonic.nl |
cd85fd7a701f085a896dcd9fec6d6c2a12562e45 | d488f052805a87b5c4b124ca93494bc9b78620f7 | /google-cloud-sdk/.install/.backup/lib/googlecloudsdk/calliope/display_info.py | 494c7184d5c3c77b64993d9477d0779c6f41a541 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | PacktPublishing/DevOps-Fundamentals | 5ce1fc938db66b420691aa8106ecfb3f9ceb1ace | 60597e831e08325c7e51e8557591917f7c417275 | refs/heads/master | 2023-02-02T04:48:15.346907 | 2023-01-30T08:33:35 | 2023-01-30T08:33:35 | 131,293,311 | 13 | 19 | null | null | null | null | UTF-8 | Python | false | false | 4,805 | py | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Resource display info for the Calliope display module."""
from __future__ import absolute_import
from __future__ import unicode_literals
from googlecloudsdk.core.cache import cache_update_ops
class DisplayInfo(object):
"""Display info accumulator for priming Displayer.
"legacy" logic will be dropped when the incremental Command class refactor
is complete.
NOTICE: If you add an attribute:
(1) document it
(2) handle it in AddLowerDisplayInfo()
Attributes:
_cache_updater: A resource_cache.Updater class that will be instantiated
and called to update the cache to reflect the resources returned by the
calling command.
_filter: The default filter string. args.filter takes precedence.
_format: The default format string. args.format takes precedence.
_transforms: The filter/format transforms symbol dict.
_aliases: The resource name alias dict.
"""
def __init__(self):
self._cache_updater = None
self._filter = None
self._format = None
self._transforms = {}
self._aliases = {}
# pylint: disable=redefined-builtin, name matches args.format and --format
def AddLowerDisplayInfo(self, display_info):
"""Add lower precedence display_info to the object.
This method is called by calliope to propagate CLI low precedence parent
info to its high precedence children.
Args:
display_info: The low precedence DisplayInfo object to add.
"""
if not self._cache_updater:
self._cache_updater = display_info.cache_updater
if not self._filter:
self._filter = display_info.filter
if not self._format:
self._format = display_info.format
if display_info.transforms:
transforms = dict(display_info.transforms)
transforms.update(self.transforms)
self._transforms = transforms
if display_info.aliases:
aliases = dict(display_info.aliases)
aliases.update(self._aliases)
self._aliases = aliases
def AddFormat(self, format):
"""Adds a format to the display info, newer info takes precedence.
Args:
format: The default format string. args.format takes precedence.
"""
if format:
self._format = format
def AddFilter(self, filter):
"""Adds a filter to the display info, newer info takes precedence.
Args:
filter: The default filter string. args.filter takes precedence.
"""
if filter:
self._filter = filter
def AddTransforms(self, transforms):
"""Adds transforms to the display info, newer values takes precedence.
Args:
transforms: A filter/format transforms symbol dict.
"""
if transforms:
self._transforms.update(transforms)
def AddUriFunc(self, uri_func):
"""Adds a uri transform to the display info using uri_func.
Args:
uri_func: func(resource), A function that returns the uri for a
resource object.
"""
def _TransformUri(resource, undefined=None):
try:
return uri_func(resource) or undefined
except (AttributeError, TypeError):
return undefined
self.AddTransforms({'uri': _TransformUri})
def AddAliases(self, aliases):
"""Adds aliases to the display info, newer values takes precedence.
Args:
aliases: The resource name alias dict.
"""
if aliases:
self._aliases.update(aliases)
def AddCacheUpdater(self, cache_updater):
"""Adds a cache_updater to the display info, newer values takes precedence.
The cache updater is called to update the resource cache for CreateCommand,
DeleteCommand and ListCommand commands.
Args:
cache_updater: A resource_cache.Updater class that will be instantiated
and called to update the cache to reflect the resources returned by the
calling command. None disables cache update.
"""
self._cache_updater = cache_updater or cache_update_ops.NoCacheUpdater
@property
def cache_updater(self):
return self._cache_updater
@property
def format(self):
return self._format
@property
def filter(self):
return self._filter
@property
def aliases(self):
return self._aliases
@property
def transforms(self):
return self._transforms
| [
"saneetk@packtpub.com"
] | saneetk@packtpub.com |
7c747fb48d6766c4376bc60b101efbfed54ce545 | 1c43338af57ff781d704ff68a0ea79f908bf94d5 | /python/skyhook/op/all_decorate.py | a952bbbdb0796d3e38ddad7183665c1b2abf7ff6 | [
"MIT"
] | permissive | skyhookml/skyhookml | dcde20626bab09843092e82b3160a80dfaa21061 | 5d2d8d3b80db409d44b4a9e4d0d3c495a116fee1 | refs/heads/master | 2023-06-13T03:51:08.343428 | 2021-07-09T18:00:35 | 2021-07-09T18:00:35 | 320,390,825 | 9 | 3 | MIT | 2021-04-28T17:46:26 | 2020-12-10T21:10:07 | Go | UTF-8 | Python | false | false | 1,166 | py | from skyhook.op.op import Operator
import skyhook.common as lib
import skyhook.io
import requests
class AllDecorateOperator(Operator):
def __init__(self, meta_packet):
super(AllDecorateOperator, self).__init__(meta_packet)
# Function must be set after initialization.
self.f = None
def apply(self, task):
# Use LoadData to fetch datas one by one.
# We combine it with metadata to create the input arguments.
items = [item_list[0] for item_list in task['Items']['inputs']]
args = []
for i, item in enumerate(items):
data, metadata = self.read_item(self.inputs[i], item)
args.append({
'Data': data,
'Metadata': metadata,
})
# Run the user-defined function.
outputs = self.f(*args)
if not isinstance(outputs, tuple):
outputs = (outputs,)
# Write each output item.
for i, data in enumerate(outputs):
if isinstance(data, dict) and 'Data' in data:
data, metadata = data['Data'], data['Metadata']
else:
metadata = {}
self.write_item(self.outputs[i], task['Key'], data, metadata)
def all_decorate(f):
def wrap(meta_packet):
op = AllDecorateOperator(meta_packet)
op.f = f
return op
return wrap
| [
"fbastani@perennate.com"
] | fbastani@perennate.com |
058ef9a85453f91db61408ad2be56cfd3f100d38 | 3534f9bf3b7e3f397bc5e80736fc50561dec95d1 | /activitystreams_test.py | ef2c511de267d5818a0e7e425a3f69a170ed3eb0 | [
"LicenseRef-scancode-public-domain"
] | permissive | rhiaro/activitystreams-unofficial | c6ece0e341b8b7e7addeb276e323a92cadde707c | cfaf4f82c44ceab857d0a4f52e0247ff78c73b72 | refs/heads/master | 2021-01-16T20:05:58.942272 | 2015-03-14T05:48:08 | 2015-03-14T05:48:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,739 | py | """Unit tests for activitystreams.py.
"""
__author__ = ['Ryan Barrett <activitystreams@ryanb.org>']
import copy
import json
import activitystreams
import facebook_test
import instagram_test
from oauth_dropins.webutil import testutil
import source
import twitter_test
class FakeSource(source.Source):
def __init__(self, **kwargs):
pass
class HandlerTest(testutil.HandlerTest):
activities = [{'foo': 'bar'}]
def setUp(self):
super(HandlerTest, self).setUp()
self.reset()
def reset(self):
self.mox.UnsetStubs()
self.mox.ResetAll()
activitystreams.SOURCE = FakeSource
self.mox.StubOutWithMock(FakeSource, 'get_activities_response')
def get_response(self, url, *args, **kwargs):
start_index = kwargs.setdefault('start_index', 0)
kwargs.setdefault('count', activitystreams.ITEMS_PER_PAGE)
FakeSource.get_activities_response(*args, **kwargs).AndReturn({
'startIndex': start_index,
'itemsPerPage': 1,
'totalResults': 9,
'items': self.activities,
'filtered': False,
'sorted': False,
'updatedSince': False,
})
self.mox.ReplayAll()
return activitystreams.application.get_response(url)
def check_request(self, url, *args, **kwargs):
resp = self.get_response(url, *args, **kwargs)
self.assertEquals(200, resp.status_int)
self.assert_equals({
'startIndex': int(kwargs.get('start_index', 0)),
'itemsPerPage': 1,
'totalResults': 9,
'items': [{'foo': 'bar'}],
'filtered': False,
'sorted': False,
'updatedSince': False,
},
json.loads(resp.body))
def test_all_defaults(self):
self.check_request('/')
def test_me(self):
self.check_request('/@me', None)
def test_user_id(self):
self.check_request('/123/', '123')
def test_all(self):
self.check_request('/123/@all/', '123', None)
def test_friends(self):
self.check_request('/123/@friends/', '123', None)
def test_self(self):
self.check_request('/123/@self/', '123', '@self')
def test_group_id(self):
self.check_request('/123/456', '123', '456')
def test_app(self):
self.check_request('/123/456/@app/', '123', '456', None)
def test_app_id(self):
self.check_request('/123/456/789/', '123', '456', '789')
def test_activity_id(self):
self.check_request('/123/456/789/000/', '123', '456', '789', '000')
def test_defaults_and_activity_id(self):
self.check_request('/@me/@all/@app/000/', None, None, None, '000')
def test_json_format(self):
self.check_request('/@me/?format=json', None)
def test_xml_format(self):
resp = self.get_response('?format=xml')
self.assertEquals(200, resp.status_int)
self.assert_multiline_equals("""\
<?xml version="1.0" encoding="UTF-8"?>
<response>
<items>
<foo>bar</foo>
</items>
<itemsPerPage>1</itemsPerPage>
<updatedSince>False</updatedSince>
<startIndex>0</startIndex>
<sorted>False</sorted>
<filtered>False</filtered>
<totalResults>9</totalResults>
</response>
""", resp.body)
def test_atom_format(self):
for test_module in facebook_test, instagram_test, twitter_test:
self.reset()
self.mox.StubOutWithMock(FakeSource, 'get_actor')
FakeSource.get_actor(None).AndReturn(test_module.ACTOR)
self.activities = [copy.deepcopy(test_module.ACTIVITY)]
# include access_token param to check that it gets stripped
resp = self.get_response('?format=atom&access_token=foo&a=b')
self.assertEquals(200, resp.status_int)
self.assert_multiline_equals(
test_module.ATOM % {'request_url': 'http://localhost',
'host_url': 'http://localhost/'},
resp.body)
def test_unknown_format(self):
resp = activitystreams.application.get_response('?format=bad')
self.assertEquals(400, resp.status_int)
def test_bad_start_index(self):
resp = activitystreams.application.get_response('?startIndex=foo')
self.assertEquals(400, resp.status_int)
def test_bad_count(self):
resp = activitystreams.application.get_response('?count=-1')
self.assertEquals(400, resp.status_int)
def test_start_index(self):
expected_count = activitystreams.ITEMS_PER_PAGE - 2
self.check_request('?startIndex=2', start_index=2, count=expected_count)
def test_count(self):
self.check_request('?count=3', count=3)
def test_start_index_and_count(self):
self.check_request('?startIndex=4&count=5', start_index=4, count=5)
def test_count_greater_than_items_per_page(self):
self.check_request('?count=999', count=activitystreams.ITEMS_PER_PAGE)
# TODO: move to facebook and/or twitter since they do implementation
# def test_start_index_count_zero(self):
# self.check_request('?startIndex=0&count=0', self.ACTIVITIES)
# def test_start_index(self):
# self.check_request('?startIndex=1&count=0', self.ACTIVITIES[1:])
# self.check_request('?startIndex=2&count=0', self.ACTIVITIES[2:])
# def test_count_past_end(self):
# self.check_request('?startIndex=0&count=10', self.ACTIVITIES)
# self.check_request('?startIndex=1&count=10', self.ACTIVITIES[1:])
# def test_start_index_past_end(self):
# self.check_request('?startIndex=10&count=0', [])
# self.check_request('?startIndex=10&count=10', [])
# def test_start_index_subtracts_from_count(self):
# try:
# orig_items_per_page = activitystreams.ITEMS_PER_PAGE
# activitystreams.ITEMS_PER_PAGE = 2
# self.check_request('?startIndex=1&count=0', self.ACTIVITIES[1:2])
# finally:
# activitystreams.ITEMS_PER_PAGE = orig_items_per_page
# def test_start_index_and_count(self):
# self.check_request('?startIndex=1&count=1', [self.ACTIVITIES[1]])
| [
"git@ryanb.org"
] | git@ryanb.org |
658d0a11036050ce40cb2311da2ac7539607f050 | 0502750293383c6dae2aaf4013717d9c83f52c62 | /exercism/python/archive/prime-factors/prime_factors.py | 4dca4fefddd4177d80ad4fc02d69cc52c0c0c9cb | [] | no_license | sebito91/challenges | fcfb680e7fc1abfa9fea9cd5f108c42795da4679 | b4f2d3b7f8b7c78f02b67d67d4bcb7fad2b7e284 | refs/heads/master | 2023-07-08T15:43:42.850679 | 2023-06-26T19:38:51 | 2023-06-26T19:38:51 | 117,160,720 | 5 | 0 | null | null | null | null | UTF-8 | Python | false | false | 585 | py | """ Module to return the set of prime factors for a number """
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import math
def prime_factors(number):
""" return the list of prime factors of the given number """
if number == 1:
return []
thelist = []
while number % 2 == 0:
number /= 2
thelist.append(2)
for each in xrange(3, int(math.sqrt(number))+1, 2):
while number % each == 0:
number /= each
thelist.append(each)
if number > 2:
thelist.append(number)
return thelist
| [
"sebito91@gmail.com"
] | sebito91@gmail.com |
8eb96542eb2443f15fcdbd700049efb6b975ab53 | aaa204ad7f134b526593c785eaa739bff9fc4d2a | /airflow/api_connexion/schemas/dag_warning_schema.py | 211f251e7d26e6255de19ef603116ddec9d3bef6 | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | permissive | cfei18/incubator-airflow | 913b40efa3d9f1fdfc5e299ce2693492c9a92dd4 | ffb2078eb5546420864229cdc6ee361f89cab7bd | refs/heads/master | 2022-09-28T14:44:04.250367 | 2022-09-19T16:50:23 | 2022-09-19T16:50:23 | 88,665,367 | 0 | 1 | Apache-2.0 | 2021-02-05T16:29:42 | 2017-04-18T20:00:03 | Python | UTF-8 | Python | false | false | 1,735 | py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from __future__ import annotations
from typing import NamedTuple
from marshmallow import Schema, fields
from marshmallow_sqlalchemy import SQLAlchemySchema, auto_field
from airflow.models.dagwarning import DagWarning
class DagWarningSchema(SQLAlchemySchema):
"""Import error schema"""
class Meta:
"""Meta"""
model = DagWarning
dag_id = auto_field(data_key="dag_id", dump_only=True)
warning_type = auto_field()
message = auto_field()
timestamp = auto_field(format="iso")
class DagWarningCollection(NamedTuple):
"""List of dag warnings with metadata"""
dag_warnings: list[DagWarning]
total_entries: int
class DagWarningCollectionSchema(Schema):
"""Import error collection schema"""
dag_warnings = fields.List(fields.Nested(DagWarningSchema))
total_entries = fields.Int()
dag_warning_schema = DagWarningSchema()
dag_warning_collection_schema = DagWarningCollectionSchema()
| [
"noreply@github.com"
] | cfei18.noreply@github.com |
2c0ff3e8c8731cd7fa9acc4cbadcc1f28978387e | 45dca4f728d6d7ce2f8ba4d711aaa9983871740a | /tensorpack/dataflow/imgaug/meta.py | 1093bf047a28b33b5a1b851bc7caf01e145c3870 | [
"Apache-2.0"
] | permissive | mtoto/tensorpack | 5de9f0d87f34f70527cdea1ddeb4006f8a503ca7 | 552f8b2690f369cb30dc29e07535dda7aa68f5b1 | refs/heads/master | 2020-03-15T08:03:26.843432 | 2018-05-02T22:04:49 | 2018-05-02T22:04:49 | 132,042,806 | 0 | 0 | Apache-2.0 | 2018-05-03T19:52:39 | 2018-05-03T19:52:38 | null | UTF-8 | Python | false | false | 4,607 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: meta.py
from .base import ImageAugmentor
__all__ = ['RandomChooseAug', 'MapImage', 'Identity', 'RandomApplyAug',
'RandomOrderAug']
class Identity(ImageAugmentor):
""" A no-op augmentor """
def _augment(self, img, _):
return img
class RandomApplyAug(ImageAugmentor):
""" Randomly apply the augmentor with a probability.
Otherwise do nothing
"""
def __init__(self, aug, prob):
"""
Args:
aug (ImageAugmentor): an augmentor
prob (float): the probability
"""
self._init(locals())
super(RandomApplyAug, self).__init__()
def _get_augment_params(self, img):
p = self.rng.rand()
if p < self.prob:
prm = self.aug._get_augment_params(img)
return (True, prm)
else:
return (False, None)
def _augment_return_params(self, img):
p = self.rng.rand()
if p < self.prob:
img, prms = self.aug._augment_return_params(img)
return img, (True, prms)
else:
return img, (False, None)
def reset_state(self):
super(RandomApplyAug, self).reset_state()
self.aug.reset_state()
def _augment(self, img, prm):
if not prm[0]:
return img
else:
return self.aug._augment(img, prm[1])
def _augment_coords(self, coords, prm):
if not prm[0]:
return coords
else:
return self.aug._augment_coords(coords, prm[1])
class RandomChooseAug(ImageAugmentor):
""" Randomly choose one from a list of augmentors """
def __init__(self, aug_lists):
"""
Args:
aug_lists (list): list of augmentors, or list of (augmentor, probability) tuples
"""
if isinstance(aug_lists[0], (tuple, list)):
prob = [k[1] for k in aug_lists]
aug_lists = [k[0] for k in aug_lists]
self._init(locals())
else:
prob = [1.0 / len(aug_lists)] * len(aug_lists)
self._init(locals())
super(RandomChooseAug, self).__init__()
def reset_state(self):
super(RandomChooseAug, self).reset_state()
for a in self.aug_lists:
a.reset_state()
def _get_augment_params(self, img):
aug_idx = self.rng.choice(len(self.aug_lists), p=self.prob)
aug_prm = self.aug_lists[aug_idx]._get_augment_params(img)
return aug_idx, aug_prm
def _augment(self, img, prm):
idx, prm = prm
return self.aug_lists[idx]._augment(img, prm)
def _augment_coords(self, coords, prm):
idx, prm = prm
return self.aug_lists[idx]._augment_coords(coords, prm)
class RandomOrderAug(ImageAugmentor):
"""
Apply the augmentors with randomized order.
"""
def __init__(self, aug_lists):
"""
Args:
aug_lists (list): list of augmentors.
The augmentors are assumed to not change the shape of images.
"""
self._init(locals())
super(RandomOrderAug, self).__init__()
def reset_state(self):
super(RandomOrderAug, self).reset_state()
for a in self.aug_lists:
a.reset_state()
def _get_augment_params(self, img):
# Note: If augmentors change the shape of image, get_augment_param might not work
# All augmentors should only rely on the shape of image
idxs = self.rng.permutation(len(self.aug_lists))
prms = [self.aug_lists[k]._get_augment_params(img)
for k in range(len(self.aug_lists))]
return idxs, prms
def _augment(self, img, prm):
idxs, prms = prm
for k in idxs:
img = self.aug_lists[k]._augment(img, prms[k])
return img
def _augment_coords(self, coords, prm):
idxs, prms = prm
for k in idxs:
img = self.aug_lists[k]._augment_coords(coords, prms[k])
return img
class MapImage(ImageAugmentor):
"""
Map the image array by a function.
"""
def __init__(self, func, coord_func=None):
"""
Args:
func: a function which takes an image array and return an augmented one
"""
super(MapImage, self).__init__()
self.func = func
self.coord_func = coord_func
def _augment(self, img, _):
return self.func(img)
def _augment_coords(self, coords, _):
if self.coord_func is None:
raise NotImplementedError
return self.coord_func(coords)
| [
"ppwwyyxxc@gmail.com"
] | ppwwyyxxc@gmail.com |
9e6e98bcaf65a333c3415b95e9d1b93b57bb6ab8 | 60e4baae4d6b323b3d3b656df3a7b0ea3ca40ef2 | /project/apps/community/migrations/0006_comment_created_date.py | 72662e4eb6a332438ac5fac1c3c7c801c8f017f5 | [] | no_license | Burzhun/Big-django-project | a03a61a15ee75f49324ad7ea51372b6b013d1650 | 1a71f974b7b5399a45862711b5f858c0d4af50d2 | refs/heads/master | 2020-04-11T00:16:06.211039 | 2018-12-11T19:13:38 | 2018-12-11T19:13:38 | 161,381,283 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 572 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-04-04 19:34
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('community', '0005_comment_expert_answer'),
]
operations = [
migrations.AddField(
model_name='comment',
name='created_date',
field=models.DateTimeField(db_index=True, default=django.utils.timezone.now, verbose_name='Дата создания'),
),
]
| [
"burjunov@yandex.ru"
] | burjunov@yandex.ru |
ba5c486c32a7be995fe3c55dd4486130ed1a3c95 | 163bbb4e0920dedd5941e3edfb2d8706ba75627d | /Code/CodeRecords/2842/60580/316589.py | 47764e1e08d51f730408ee0f95aa554ff5fc9f29 | [] | no_license | AdamZhouSE/pythonHomework | a25c120b03a158d60aaa9fdc5fb203b1bb377a19 | ffc5606817a666aa6241cfab27364326f5c066ff | refs/heads/master | 2022-11-24T08:05:22.122011 | 2020-07-28T16:21:24 | 2020-07-28T16:21:24 | 259,576,640 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 320 | py | n = int(input())
array = [0] * n
for i in range(n):
temp = int(input())
if temp == -1:
array[i] = -1
else:
array[i] = temp - 1
count = []
for i in range(n):
j = i
temp = 0
while array[j] != -1:
temp = temp + 1
j = array[j]
count.append(temp)
print(max(count))
| [
"1069583789@qq.com"
] | 1069583789@qq.com |
238ccfd4362df93c4e34f8f29a13d1dee0422ea8 | 8c2de4da068ba3ed3ce1adf0a113877385b7783c | /hyperion/diarization/__init__.py | 494ef35caac655fc51985be54a762d30647364a0 | [
"Apache-2.0"
] | permissive | hyperion-ml/hyperion | a024c718c4552ba3a03aae2c2ca1b8674eaebc76 | c4c9eee0acab1ba572843373245da12d00dfffaa | refs/heads/master | 2023-08-28T22:28:37.624139 | 2022-03-25T16:28:08 | 2022-03-25T16:28:08 | 175,275,679 | 55 | 20 | Apache-2.0 | 2023-09-13T15:35:46 | 2019-03-12T18:40:19 | Python | UTF-8 | Python | false | false | 173 | py | """
Copyright 2018 Johns Hopkins University (Author: Jesus Villalba)
Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""
from .diar_ahc_plda import DiarAHCPLDA
| [
"jesus.antonio.villalba@gmail.com"
] | jesus.antonio.villalba@gmail.com |
3f7929b0a938ce5579e05271c8c032a63b81cf4a | 0b636a0a7bfcb534a3f00cf6c38b54ad8d050639 | /AtCoder/ABC144D.py | ce77a9178f2c9434acc53d00097e590d80101e9a | [] | no_license | RRFHOUDEN/competitive-programming | 23be02f55ab67f7d03ccec32f291e136770fc113 | 582ed5c5d5e9797fc952ee1d569ef72f8bf8ef48 | refs/heads/master | 2022-10-19T21:53:26.952049 | 2020-06-13T11:44:07 | 2020-06-13T11:44:07 | 258,940,723 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 323 | py | import fractions
a, b, x = map(int, input().split())
PI = 3.1415926535897932384626
if x >= a * a * b / 2:
ans = fractions.atan(2 * (a * a * b - x) / (a * a * a))
ans = fractions.degrees(ans)
else:
ans = fractions.atan(2 * x / (a * b * b))
ans = fractions.degrees(ans)
ans = 90 - ans
print(ans) | [
"keisuke.toyodano@gmail.com"
] | keisuke.toyodano@gmail.com |
da631c41d70c1d7f33b03220272f3b4868cae56e | f445450ac693b466ca20b42f1ac82071d32dd991 | /generated_tempdir_2019_09_15_163300/generated_part009169.py | 278cb18a9c17ec793e71dc502195fe855036b2a7 | [] | no_license | Upabjojr/rubi_generated | 76e43cbafe70b4e1516fb761cabd9e5257691374 | cd35e9e51722b04fb159ada3d5811d62a423e429 | refs/heads/master | 2020-07-25T17:26:19.227918 | 2019-09-15T15:41:48 | 2019-09-15T15:41:48 | 208,357,412 | 4 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,516 | py | from sympy.abc import *
from matchpy.matching.many_to_one import CommutativeMatcher
from matchpy import *
from matchpy.utils import VariableWithCount
from collections import deque
from multiset import Multiset
from sympy.integrals.rubi.constraints import *
from sympy.integrals.rubi.utility_function import *
from sympy.integrals.rubi.rules.miscellaneous_integration import *
from sympy import *
class CommutativeMatcher110400(CommutativeMatcher):
_instance = None
patterns = {
0: (0, Multiset({}), [
(VariableWithCount('i3.1.2.1.0', 1, 1, None), Mul),
(VariableWithCount('i3.1.2.1.0_1', 1, 1, S(1)), Mul)
]),
1: (1, Multiset({0: 1}), [
(VariableWithCount('i3.1.2.1.0', 1, 1, S(1)), Mul)
])
}
subjects = {}
subjects_by_id = {}
bipartite = BipartiteGraph()
associative = Mul
max_optional_count = 1
anonymous_patterns = set()
def __init__(self):
self.add_subject(None)
@staticmethod
def get():
if CommutativeMatcher110400._instance is None:
CommutativeMatcher110400._instance = CommutativeMatcher110400()
return CommutativeMatcher110400._instance
@staticmethod
def get_match_iter(subject):
subjects = deque([subject]) if subject is not None else deque()
subst0 = Substitution()
# State 110399
if len(subjects) >= 1 and isinstance(subjects[0], Pow):
tmp1 = subjects.popleft()
subjects2 = deque(tmp1._args)
# State 110742
if len(subjects2) >= 1:
tmp3 = subjects2.popleft()
subst1 = Substitution(subst0)
try:
subst1.try_add_variable('i3.1.2.1.1', tmp3)
except ValueError:
pass
else:
pass
# State 110743
if len(subjects2) >= 1 and subjects2[0] == Integer(2):
tmp5 = subjects2.popleft()
# State 110744
if len(subjects2) == 0:
pass
# State 110745
if len(subjects) == 0:
pass
# 0: x**2
yield 0, subst1
subjects2.appendleft(tmp5)
subjects2.appendleft(tmp3)
subjects.appendleft(tmp1)
return
yield
from collections import deque | [
"franz.bonazzi@gmail.com"
] | franz.bonazzi@gmail.com |
62ec0f10af3cd0254445d9c25cfa5e46cd0b104b | 6b03517ab54bc5dfd7464bd680e4d6a0df054dbc | /src/bot/settings.py | 446d8f863c3cd1dffd0a5cd9f4cde9d4da4bc8d2 | [] | no_license | mike0sv/telegram-bot-django-template-project | 88eba6ef485dc603161cf6110f32149509eacc2b | 43fd7cfa1d54887274a6ee0e6f56c4d9cdd1cb10 | refs/heads/master | 2021-06-24T10:05:58.092449 | 2019-09-26T15:52:55 | 2019-09-26T15:52:55 | 168,697,668 | 0 | 1 | null | 2021-06-10T21:10:30 | 2019-02-01T12:57:41 | Python | UTF-8 | Python | false | false | 4,436 | py | """
Django settings for bot project.
Generated by 'django-admin startproject' using Django 2.1.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'syd-@wanon*sja0%d6ztc%l@dfkjv8mkgx*#&mtve@(_0nj2q8'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'backend'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'bot.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'bot.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
DOCKER_ENV = os.environ.get('DOCKER', 'false') == 'true'
if DOCKER_ENV:
DATABASES['default'] = {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'tgbot',
'PASSWORD': 'postgres',
'USER': 'postgres',
'HOST': 'postgres'
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
}
},
'loggers': {
'django.request': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
},
'bot': {
'handlers': ['console'],
'level': 'INFO',
}
},
}
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
def env(name, default=None, type=None):
value = os.environ.get(name, default)
return type(value) if type is not None else value
DEFAULT_BOT_TOKEN = env('BOT_TOKEN', None)
TG_USE_PROXY = env('TG_USE_PROXY', 'True', type=lambda x: x == 'True')
TG_PROXY_ADDRESS = env('TG_PROXY_ADDRESS')
TG_PROXY_USERNAME = env('TG_PROXY_USERNAME')
TG_PROXY_PASSWORD = env('TG_PROXY_PASSWORD')
TG_WEBHOOK_CERT_KEY = os.environ.get('BOT_CERT_KEY', 'cert/private.key')
TG_WEBHOOK_CERT_PEM = os.environ.get('BOT_CERT_PEM', 'cert/cert.pem')
TG_WEBHOOK = os.environ.get('BOT_WEBHOOK') == 'true'
TG_WEBHOOK_PORT = int(os.environ.get('BOT_WEBHOOK_PORT', 5555))
| [
"mike0sv@gmail.com"
] | mike0sv@gmail.com |
7e1835c0f76b6c713b30174e560aeb5c4b77e5bd | bc9f66258575dd5c8f36f5ad3d9dfdcb3670897d | /lib/surface/compute/networks/delete.py | 39d2c060fc886ce025072ddf7996fe34279c33f2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | google-cloud-sdk-unofficial/google-cloud-sdk | 05fbb473d629195f25887fc5bfaa712f2cbc0a24 | 392abf004b16203030e6efd2f0af24db7c8d669e | refs/heads/master | 2023-08-31T05:40:41.317697 | 2023-08-23T18:23:16 | 2023-08-23T18:23:16 | 335,182,594 | 9 | 2 | NOASSERTION | 2022-10-29T20:49:13 | 2021-02-02T05:47:30 | Python | UTF-8 | Python | false | false | 2,389 | py | # -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. 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.
"""Command for deleting networks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import flags as compute_flags
from googlecloudsdk.command_lib.compute.networks import flags
class Delete(base.DeleteCommand):
r"""Delete Compute Engine networks.
*{command}* deletes one or more Compute Engine
networks. Networks can only be deleted when no other resources
(e.g., virtual machine instances) refer to them.
## EXAMPLES
To delete a network with the name 'network-name', run:
$ {command} network-name
To delete two networks with the names 'network-name1' and 'network-name2',
run:
$ {command} network-name1 network-name2
"""
NETWORK_ARG = None
@staticmethod
def Args(parser):
Delete.NETWORK_ARG = flags.NetworkArgument(plural=True)
Delete.NETWORK_ARG.AddArgument(parser, operation_type='delete')
parser.display_info.AddCacheUpdater(flags.NetworksCompleter)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
network_refs = Delete.NETWORK_ARG.ResolveAsResource(
args,
holder.resources,
scope_lister=compute_flags.GetDefaultScopeLister(client))
utils.PromptForDeletion(network_refs)
requests = []
for network_ref in network_refs:
requests.append((client.apitools_client.networks, 'Delete',
client.messages.ComputeNetworksDeleteRequest(
**network_ref.AsDict())))
return client.MakeRequests(requests)
| [
"cloudsdk.mirror@gmail.com"
] | cloudsdk.mirror@gmail.com |
84f22aec0e44660430ea57649264e25e7d9cd0ac | 67325192c1e528a39d457f11e61b480d68826708 | /mods/mcpython/Item/stone_brick.py | d89a7eefa7b49fc05f922501e114e4cddf3480be | [
"MIT"
] | permissive | vashistaarav1611/mcpython-a-minecraft-clone-in-python | 5851b377b54fd2b28c106112c7b18f397b71ab50 | c16cd66f319efdeec4130e1a43f5a857caf1ea13 | refs/heads/master | 2023-02-01T22:48:51.787106 | 2020-12-21T15:02:25 | 2020-12-21T15:02:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 225 | py | from .Item import *
class StoneBrick(Item):
def getName(self):
return "minecraft:stone_brick"
def getTexturFile(self):
return "./assets/textures/items/stonebrick.png"
handler.register(StoneBrick)
| [
"baulukas1301@googlemail.com"
] | baulukas1301@googlemail.com |
2a47b827129883aed64529d397c3c7dfc99df3af | 163bbb4e0920dedd5941e3edfb2d8706ba75627d | /Code/CodeRecords/2876/61020/297101.py | 9989eb94aabc4644e48460e350427804c5b184bd | [] | no_license | AdamZhouSE/pythonHomework | a25c120b03a158d60aaa9fdc5fb203b1bb377a19 | ffc5606817a666aa6241cfab27364326f5c066ff | refs/heads/master | 2022-11-24T08:05:22.122011 | 2020-07-28T16:21:24 | 2020-07-28T16:21:24 | 259,576,640 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,201 | py | import itertools
import copy
def indexes_of(a_list_, ele):
result = []
for j in range(len(a_list_)):
if a_list_[j] == ele:
result.append(j)
return result
def is_done(a_list):
if len(a_list) <= 2:
return True
if len(a_list) == 3:
if a_list != ['1', '0', '1']:
return True
return False
if len(a_list) > 3:
return is_done(a_list[0:3]) and is_done(a_list[1:])
def min_switch(a_list):
indexes_of_1 = indexes_of(a_list, '1')
if is_done(a_list):
return 0
for i in range(1, len(indexes_of_1)):
coms = list(itertools.combinations(indexes_of_1, 2))
for indexes in coms:
seq_to_be_change = copy.copy(a_list)
for index in indexes:
seq_to_be_change[index] = 0
if is_done(seq_to_be_change):
return i
trash = input()
nums = input().split()
print(min_switch(nums))
# test1
# import copy
#
# a = ['0', '1', '2']
# b = copy.copy(a)
#
# print(a == b)
# print(a is b)
#
# b[1] = '4'
# print(a)
# print(b)
# test2
# import copy
#
# a = ['0', '1', '2']
# b = copy.deepcopy(a)
# print(a == b)
# print(a is b)
| [
"1069583789@qq.com"
] | 1069583789@qq.com |
10e2468f2d86c9659123463bdfb409ef99344a45 | 163bbb4e0920dedd5941e3edfb2d8706ba75627d | /Code/CodeRecords/2812/60651/233659.py | e0225c2f2d256ddec8d6adca5ebbca99843180af | [] | no_license | AdamZhouSE/pythonHomework | a25c120b03a158d60aaa9fdc5fb203b1bb377a19 | ffc5606817a666aa6241cfab27364326f5c066ff | refs/heads/master | 2022-11-24T08:05:22.122011 | 2020-07-28T16:21:24 | 2020-07-28T16:21:24 | 259,576,640 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 281 | py | inlist=input().split()
position=int(inlist[0])
n=int(inlist[1])
molist=[]
for i in range(n):
innum=int(input())
mo=innum%position
if mo not in molist:
molist.append(mo)
else:
print(i+1)
break
if(len(molist)==n):
print(-1)
| [
"1069583789@qq.com"
] | 1069583789@qq.com |
ad71c973ebccb1a08a32fdb6c07b5344bd636377 | 5ada50387ed5998d292011031b5f3739ac20414b | /find_bridges/python/find_bridges_1.py | 90648ab138b60265117445e2e51bc4b590e7fc32 | [] | no_license | bigWaitForItOh/Graph-Algorithms | 84484230588d3d81584d4d3feb6c231ea77e84b0 | 011163856d60be89c602044c705c835af47b3b95 | refs/heads/master | 2021-01-17T10:21:43.900771 | 2016-05-22T19:01:38 | 2016-05-22T19:01:38 | 44,433,628 | 7 | 2 | null | 2016-05-22T19:01:38 | 2015-10-17T10:54:27 | Python | UTF-8 | Python | false | false | 1,454 | py | ##################################################################################################################################
#Program to find Bridges in a simple, unweighted, undirected graph.
#Time Complexity: O (E*(V + E))
#E = number of edges, V = number of Nodes
#For each edge in the graph, it removes the edge and explores the new graph using Breadth First Search to check if the graph is still connected.
#It then inserts the removed edge back into the graph
##################################################################################################################################
def is_connected (graph):
queue, visited = [list (graph.keys ()) [0]], set ();
current = None;
while (queue):
current = queue.pop ();
visited.add (current);
for neighbour in graph [current]:
if (not (neighbour in visited or neighbour in queue)):
queue.append (neighbour);
return (len (graph) == len (visited));
def find_bridges (graph):
bridges = set ();
for node in graph:
for neighbour in graph [node]:
graph [node].remove (neighbour);
graph [neighbour].remove (node);
if (not is_connected (graph)):
bridges.add ( (node, neighbour) );
graph [node].add (neighbour);
graph [neighbour].add (node);
return (bridges);
graph = {
'A' : set (['B','C']),
'B' : set (['A','C']),
'C' : set (['A','B','D','F']),
'D' : set (['C','E']),
'E' : set (['D']),
'F' : set (['C'])
};
print (find_bridges (graph));
| [
"duaraghav8@gmail.com"
] | duaraghav8@gmail.com |
6053f2bbd3c07939d3ae090def23183a8179fae1 | f37c8a91ba8f18db083cf4dcb7d74cee6b84e444 | /pynion/filesystem/_filetypes/basefile.py | 51482cc137768351b0c4b566255392fd7a571a68 | [
"MIT"
] | permissive | jaumebonet/pynion | 6818d764cd1dbb9cbb53d665837adab828e8eac7 | 4052aee023df7206c2e56a28c361d4a5a445a6d4 | refs/heads/master | 2021-01-10T08:56:24.968686 | 2016-02-16T18:43:31 | 2016-02-16T18:43:31 | 50,191,510 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 6,770 | py | import os
import json
import pathlib
from ... import Manager
from ...metaclass import Multiton
from ...errors.fe import FileOpenError as FOE
from ...errors.fe import FileWrongRequestedActionError as FWR
m = Manager()
class BaseFile(object):
"""
The **BaseFile** :py:class:`pynion.Multiton` is a file management object
created directly through the py:class:`pynion.File` factory.
It specifically manages regular files.
Allows the with statement in read files.
"""
__metaclass__ = Multiton
_IDENTIFIER = 'file_name'
def __init__(self, file_name, action):
self.fname = pathlib.Path(file_name)
self.action = action
self._fd = None
self._pattern = None
##############
# ATTRIBUTES #
##############
@property
def full(self):
"""
:return: Full path of the file
:rtype: str
"""
try:
return str(self.fname.resolve())
except:
return os.path.abspath(str(self.fname))
@property
def dir(self):
"""
:return: Full path containing directory
:rtype: str
"""
return str(self.fname.resolve().parent)
@property
def last_dir(self):
"""
:return: Name of the containing directory
:rtype: str
"""
return str(self.fname.resolve().parent.name)
@property
def name(self):
"""
:return: Name of the file
:rtype: str
"""
return str(self.fname.name)
@property
def prefix(self):
"""
:return: Name of the file without extension
:rtype: str
"""
return str(self.fname.stem)
@property
def first_prefix(self):
"""
:return: Name of the first section of the file
:rtype: str
"""
return self.name.split('.')[0]
@property
def extension(self):
"""
:return: Name of the file's extension
:rtype: str
"""
return str(self.fname.suffix)
@property
def extensions(self):
"""
:return: List of all the sections of the file name except the first one.
:rtype: list
"""
return self.fname.suffixes
@property
def descriptor(self):
"""
:return: Descriptor of the stored file
:rtype: str
"""
return self._fd
@property
def size(self):
"""
:return: File size
:rtype: str
"""
return self.fname.stat().st_size
@property
def pattern(self):
"""
:return: Dictionary with the pattern assigned sections of the file name.
:rtype: dict
"""
if self._pattern is None:
return None
pattern = {}
for p in self._pattern:
pattern[p] = self.__dict__[p]
return pattern
############
# BOOLEANS #
############
@property
def is_open(self):
"""
:return: Check if the file descriptor is open
:rtype: bool
"""
return self._fd is not None
@property
def is_to_write(self):
"""
:return: Check if the file is set to write
:rtype: bool
"""
return self.action in set(['w', 'a'])
@property
def is_to_read(self):
"""
:return: Check if the file is set to read
:rtype: bool
"""
return self.action in set(['r'])
###########
# METHODS #
###########
def relative_to(self, path = pathlib.Path.cwd()):
"""
:param str path: Path to which the relative path is required.
:return: Actual path relative to the query path
:rtype: str
"""
return self.fname.relative_to(path)
####################
# METHODS: ON FILE #
####################
def open(self):
"""
Open the file in the previously defined action type.
:rtype: self
"""
if self.is_open:
return self
self._fd = open(self.full, self.action)
return self
def read(self):
"""
:raise: :py:class:`pynion.errors.fe.FileWrongRequestedActionError` if
opened in write mode.
:rtype: File Descriptor
"""
self._check_action('r')
return self._fd
def readline(self):
"""
:raise: :py:class:`pynion.errors.fe.FileWrongRequestedActionError` if
opened in write mode.
:return: One line of the file.
:rtype: str
"""
self._check_action('r')
return self._fd.readline()
def readJSON(self, encoding = 'utf-8'):
"""
Retrieve all data in file as a JSON dictionary.
:param str encoding: Encoding read format (default: utf-8)
:raise: :py:class:`pynion.errors.fe.FileWrongRequestedActionError` if
opened in write mode.
:rtype: dict
"""
d = []
self.open()
for l in self.read():
d.append(l.strip())
return json.loads(''.join(d), encoding=encoding)
def write(self, line, encoding = None):
"""
Write to the file
:param str line: Content to write
:param str encoding: Encoding format (use utf-8, for example, if needs
to print greek characters)
:raise: :py:class:`pynion.errors.fe.FileWrongRequestedActionError` if
opened in read mode.
"""
self._check_action('w')
if encoding is None:
self._fd.write(line)
else:
self._fd.write(line.encode(encoding))
def flush(self):
"""
:raise: :py:class:`pynion.errors.fe.FileWrongRequestedActionError` if
opened in read mode.
"""
self._check_action('w')
self._fd.flush()
def close(self):
"""
Close the file.
"""
self._fd.close()
self._fd = None
###################
# PRIVATE METHODS #
###################
def _check_action(self, call_method):
if not self.is_open:
raise FOE(self.full, self.action)
if call_method == 'r' and self.is_to_write:
raise FWR(self.full, self.action)
elif call_method == 'w' and self.is_to_read:
raise FWR(self.full, self.action)
def __enter__(self):
self.open()
return self.read()
def __exit__(self, type, value, traceback):
self.close()
#################
# MAGIC METHODS #
#################
def __str__(self):
return self.full
def __repr__(self):
return '<{0}: {1.full}>'.format(self.__class__.__name__, self)
| [
"jaume.bonet@gmail.com"
] | jaume.bonet@gmail.com |
a13eef2c9f8d1c682afb5937f3c0ee35111df469 | 543286f4fdefe79bd149ff6e103a2ea5049f2cf4 | /Exercicios&cursos/Curso_em_video(exercicios)/ex069.py | 854d134399c74f92c2fa1147ab4f12df2330b19b | [] | no_license | antonioleitebr1968/Estudos-e-Projetos-Python | fdb0d332cc4f12634b75984bf019ecb314193cc6 | 9c9b20f1c6eabb086b60e3ba1b58132552a84ea6 | refs/heads/master | 2022-04-01T20:03:12.906373 | 2020-02-13T16:20:51 | 2020-02-13T16:20:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 864 | py | faixa = '-=' * 30
faixa2 = '-' * 60
titulo = 'ANALISE DE DADOS'
mulhermenor20 = homens = maior18 = 0
print(f'{faixa}')
print(f'{titulo:^60}')
print(f'{faixa}')
while True:
idade = int(input('Idade: '))
if idade > 18:
maior18 += 1
sexo = 'X'
while sexo not in 'FM':
sexo = str(input('Sexo: [F/M] ')).strip().upper()[0]
if sexo == 'M':
homens += 1
if sexo == 'F' and idade < 20:
mulhermenor20 += 1
resposta = 'X'
while resposta not in 'SN':
resposta = str(input('Quer continuar? [S/N] ')).strip().upper()[0]
if resposta == 'N':
break
print(f'{faixa2}')
print(faixa)
print('FIM DO PROGRAMA')
print(faixa)
print(f'No total foram {maior18} pessoas maiores de 18 anos,', end=' ')
print(f' {homens} homens registrados e {mulhermenor20} mulheres menores de 20 anos.')
| [
"progmatheusmorais@gmail.com"
] | progmatheusmorais@gmail.com |
0971ac262da6ca6e551f02234105af8c202c022b | fa0ae8d2e5ecf78df4547f0a106550724f59879a | /Numpy/day01/DS/code/day01/shape.py | 725f0c91dba7df05a2d0f848223a328dee0cdc5e | [] | no_license | Polaris-d/note | 71f8297bc88ceb44025e37eb63c25c5069b7d746 | 6f1a9d71e02fb35d50957f2cf6098f8aca656da9 | refs/heads/master | 2020-03-22T17:51:49.118575 | 2018-09-06T03:36:00 | 2018-09-06T03:36:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 836 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
a = np.arange(1, 3)
print(a, a.shape, sep='\n')
b = np.array([[1, 2, 3],
[4, 5, 6]])
print(b, b.shape, sep='\n')
c = np.array([[np.arange(1, 5),
np.arange(5, 9),
np.arange(9, 13)],
[np.arange(13, 17),
np.arange(17, 21),
np.arange(21, 25)]])
print(c, c.shape, type(c), sep='\n')
print(a.dtype)
d = np.array(['A', 'B', 'C', 'DEF'])
print(d.dtype)
print(d)
e = d.reshape(2, 2)
print(d)
print(e)
f = a.astype(str)
print(a.dtype)
print(f.dtype)
print(f)
for i in range(c.shape[0]):
for j in range(c.shape[1]):
for k in range(c.shape[2]):
print(c[i][j][k], c[i, j, k])
print(c[0])
print(c[0, 0])
print(c[0, 0, 0])
| [
"610079251@qq.com"
] | 610079251@qq.com |
3aba794c0288ded329f17467797fdeea487a623c | 0a7c9373185d387b025acc4fe3b4efe1e58c183e | /src/experiment1_use_opencv/py/keras_training.py | 1731faedb6b2d62ab47dfda3e5b54b76e690e2cc | [
"MIT"
] | permissive | yingshaoxo/tensorflowjs-posenet-research | a1acc4f1d6876932ad8b6742b2428457bebb9d46 | 91627c52822adb6adfd76a8c4cca34384ec6f077 | refs/heads/master | 2020-03-27T21:19:26.980730 | 2018-09-03T01:31:20 | 2018-09-03T01:31:20 | 147,135,102 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,240 | py | import os
from auto_everything.base import IO
io = IO()
import json
from pprint import pprint
import numpy as np
files = os.listdir("../data")
files = [file for file in files if '.json' in file]
global x, y
for index, file in enumerate(files):
# get x
xx = json.loads(io.read("../data/{name}".format(name=file)))
xx = np.array(xx)
print(xx.shape)
# get y
#yy = np.zeros(xx.shape[0])
yy = np.full(xx.shape[0], index)
if index == 0:
x = xx
y = yy
else:
x = np.append(x, xx, axis=0)
y = np.append(y, yy, axis=0)
# randomnize data
index = np.arange(x.shape[0])
np.random.shuffle(index)
# 3D to 2D
x = x[index]
x = x.reshape(len(x), -1)
y = y[index]
print(x.shape)
print(y.shape[0])
print(x)
print(y)
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(Dense(34, input_dim=34, activation='relu'))
model.add(Dense(21, activation='relu'))
model.add(Dense(1))
model.compile(loss='logcosh', optimizer='adam', metrics=['accuracy'])
model.fit(x, y, batch_size=10, epochs=500)
test_x = x[5:50]
test_y = y[5:50]
predicted = model.predict(test_x)
print(test_y)
print(predicted)
model.save("../pose_detect_model.h5")
| [
"yingshaoxo@gmail.com"
] | yingshaoxo@gmail.com |
54ffa7b9ce50ace8890d47976a16236c01bc54da | d554b1aa8b70fddf81da8988b4aaa43788fede88 | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4491/codes/1573_2897.py | 53be2056601ce33622953ff40274a3c112279c47 | [] | no_license | JosephLevinthal/Research-projects | a3bc3ca3b09faad16f5cce5949a2279cf14742ba | 60d5fd6eb864a5181f4321e7a992812f3c2139f9 | refs/heads/master | 2022-07-31T06:43:02.686109 | 2020-05-23T00:24:26 | 2020-05-23T00:24:26 | 266,199,309 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 188 | py | # Use este codigo como ponto de partida
# Leitura de valores de entrada e conversao para inteiro
num = int(input("Digite o numero: "))
# Impressao do dobro do numero
f = num * 2
print(f) | [
"jvlo@icomp.ufam.edu.br"
] | jvlo@icomp.ufam.edu.br |
8e4240bce53538f22730417db80c199e0a496034 | 08428ba80f90f73bbce19e5bd0f423a1b4d025d7 | /src/registration_manager/panel.py | 5a00ffb7ad287770870a2bd2e23168d8114c7213 | [] | no_license | marcoverl/openstack-security-integrations | 0d3afe093b361c548b65be9e405e10318d51c7cd | 58c560885b007cf25444e552de17c0d6a5a0e716 | refs/heads/master | 2021-01-16T21:18:56.071490 | 2014-06-17T07:56:48 | 2014-06-17T07:56:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 279 | py |
from django.utils.translation import ugettext_lazy as _
import horizon
from openstack_dashboard.dashboards.admin import dashboard
class RegisterManager(horizon.Panel):
name = _("Registrations")
slug = 'registration_manager'
dashboard.Admin.register(RegisterManager)
| [
"paolo.andreetto@pd.infn.it"
] | paolo.andreetto@pd.infn.it |
87484cd5541d4353e73c169808da3e10751ad6b6 | 139715a923c8c82b172803d5bdc1b1bca46fbdf3 | /leetcode/edit_distance.py | 93d846c3c6b853be90ff7d4600bfe1c8b780533a | [] | no_license | haoccheng/pegasus | ab32dcc4265ed901e73790d8952aa3d72bdf72e7 | 76cbac7ffbea738c917e96655e206f8ecb705167 | refs/heads/master | 2021-01-10T11:33:23.038288 | 2016-03-18T04:17:28 | 2016-03-18T04:17:28 | 46,103,391 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 730 | py | # edit distance.
import sys
def edit_distance(word1, word2):
if len(word1) == 0 or len(word2) == 0:
return max(len(word1), len(word2))
scores = []
for i in range(len(word1)+1):
row = [0] * (len(word2)+1)
scores.append(row)
for i in range(len(word1)+1):
scores[i][0] = i
for j in range(len(word2)+1):
scores[0][j] = j
for i in range(1, len(word1)+1):
for j in range(1, len(word2)+1):
s0 = sys.maxint
if word1[i-1] == word2[j-1]:
s0 = scores[i-1][j-1]
else:
s0 = scores[i-1][j-1] + 1
s1 = scores[i-1][j] + 1
s2 = scores[i][j-1] + 1
scores[i][j] = min(min(s0, s1), s2)
return scores[-1][len(scores[-1])-1]
print edit_distance('abc', 'abe')
| [
"haoc.cheng@gmail.com"
] | haoc.cheng@gmail.com |
82396827ebf5c7d3fd9a5a7608b6a4bfabebaa49 | b76d2b037c2af38edfeb718deae22697444ee121 | /proto-chain/clientX.py | 088c20d16f02d7dd5c02678f617c8019405a3791 | [] | no_license | hyo07/proto-chain | e8aa1a5d549310da79e9b28c55683a9361c48fe5 | 4fd3e91d6f9d4912634759a908f5a2bf0c1f4d47 | refs/heads/master | 2020-06-06T07:36:27.302334 | 2019-07-01T07:07:46 | 2019-07-01T07:07:46 | 192,679,743 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,661 | py | import signal
from time import sleep
import json
import sys
from core.client_core import ClientCore
from p2p.message_manager import MSG_NEW_TRANSACTION
args = sys.argv
my_p2p_client = None
def signal_handler(signal, frame):
shutdown_client()
def shutdown_client():
global my_p2p_client
my_p2p_client.shutdown()
def make_transaction():
"""
好きなトランザクションを書き込む
"""
transaction_list = []
print("トランザクションを登録できます\n"
"中断する場合は、'Ctlr + C'を入力してください\n")
while True:
transaction = input_set()
transaction_list.append(transaction)
select_num = check_continue_input()
if select_num is 1:
pass
elif select_num is 2:
print("5秒後、トランザクションを送信します\n"
"中断する場合は、'Ctlr + C'を入力してください")
sleep(5)
break
return transaction_list
def input_set():
"""
値受け取り部分
"""
print("-------------------------\n"
"トランザクション登録")
sender = input("sender: ")
recipient = input("recipient: ")
value = int(input("value: "))
return {'sender': sender, 'recipient': recipient, 'value': value}
def check_continue_input():
"""
登録を続行か、送信かの選択
"""
print("続く操作を選択してください")
while True:
select_num = input("""
1: トランザクションの登録を続ける
2: 登録したトランザクションを送信する
>>>>> """)
if (select_num == "1") or (select_num == "2"):
break
else:
print("正しい値を入力してください(1 or 2)")
return int(select_num)
def main():
transaction_list = make_transaction()
print("------------------------------------------------------------\n")
signal.signal(signal.SIGINT, signal_handler)
global my_p2p_client
# my_p2p_client = ClientCore(50087, connect_ip, core_port=50082)
try:
if args[2]:
my_p2p_client = ClientCore(50085, args[1], int(args[2]))
elif args[1]:
my_p2p_client = ClientCore(50085, args[1])
except IndexError:
my_p2p_client = ClientCore(50085)
my_p2p_client.start()
sleep(10)
for transaction in transaction_list:
my_p2p_client.send_message_to_my_core_node(MSG_NEW_TRANSACTION, json.dumps(transaction))
sleep(2)
sleep(10)
shutdown_client()
if __name__ == '__main__':
main()
| [
"yutaka727kato@gmail.com"
] | yutaka727kato@gmail.com |
6cd1198a4f82961a4c7a78dfcd5be9ed8c45de47 | 2f98aa7e5bfc2fc5ef25e4d5cfa1d7802e3a7fae | /python/python_5366.py | f754dea2bb211c5338c9f0d91f52f31b943a1deb | [] | no_license | AK-1121/code_extraction | cc812b6832b112e3ffcc2bb7eb4237fd85c88c01 | 5297a4a3aab3bb37efa24a89636935da04a1f8b6 | refs/heads/master | 2020-05-23T08:04:11.789141 | 2015-10-22T19:19:40 | 2015-10-22T19:19:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 175 | py | # multiple d-bus session bus objects in python
bus1 = dbus.bus.BusConnection("tcp:host=192.168.0.1,port=1234")
bus2 = dbus.bus.BusConnection("tcp:host=192.168.0.2,port=1234")
| [
"ubuntu@ip-172-31-7-228.us-west-2.compute.internal"
] | ubuntu@ip-172-31-7-228.us-west-2.compute.internal |
ccad96c6a0e3a3644cb0519285c2ccddd9e3ad2b | 7701773efa258510951bc7d45325b4cca26b3a7d | /kivy_explore/hellow.py | cceaf36129a48ed0edcff3422d8396b5f66fa9b8 | [] | no_license | Archanciel/explore | c170b2c8b5eed0c1220d5e7c2ac326228f6b2485 | 0576369ded0e54ce7ff9596ec4df076e69067e0c | refs/heads/master | 2022-06-17T19:15:03.647074 | 2022-06-01T20:07:04 | 2022-06-01T20:07:04 | 105,314,051 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 309 | py | import kivy
kivy.require('1.0.7')
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
class MyHelloWGUI(BoxLayout):
def sayHello(self):
print('Hello !')
def sayBye(self):
print('Bye !')
class HelloWApp(App):
pass
if __name__ == '__main__':
HelloWApp().run() | [
"jp.schnyder@gmail.com"
] | jp.schnyder@gmail.com |
55ce960f1c7ccea191a699610a7f6539b4617d3e | 2a54e8d6ed124c64abb9e075cc5524bb859ba0fa | /.history/3-OO-Python/13-dunder-methods_20200417032242.py | d9f6c382c9a09c6d06baeaffae52e92e3eecca08 | [] | no_license | CaptainStorm21/Python-Foundation | 01b5fbaf7a913506518cf22e0339dd948e65cea1 | a385adeda74f43dd7fb2d99d326b0be23db25024 | refs/heads/master | 2021-05-23T01:29:18.885239 | 2020-04-23T19:18:06 | 2020-04-23T19:18:06 | 253,171,611 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 218 | py | class Toy():
def __init__ (self, color, age):
self.color = color
self.age = age
def __str__(self):
action_figure = Toy ('red', 10)
print(action_figure.__str__())
# print(str(action_figure))
| [
"tikana4@yahoo.com"
] | tikana4@yahoo.com |
c37f9cb8b1c274e45069ac3ff3d0dcde11eef52c | f337bc5f179b25969ba73e7680ffb0a0616e3b97 | /python/BOJ/2XXX/2121.py | c87cd111128ccd88a8374937493e42bf22929655 | [] | no_license | raiders032/PS | 31771c5496a70f4730402698f743bbdc501e49a3 | 08e1384655975b868e80521167ec876b96fa01c8 | refs/heads/master | 2023-06-08T10:21:00.230154 | 2023-06-04T01:38:08 | 2023-06-04T01:38:08 | 349,925,005 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 571 | py | """
https://www.acmicpc.net/problem/2121
2121.넷이 놀기
실버3
풀이1.1792ms
"""
import sys
input = sys.stdin.readline
N = int(input())
A, B = map(int, input().split())
points = set()
sheep_count = 0
for _ in range(N):
x, y = map(int, input().split())
points.add((x, y))
dx = [A, A, 0]
dy = [0, B, B]
for x, y in points:
is_valid = True
for i in range(3):
nx = x + dx[i]
ny = y + dy[i]
if (nx, ny) not in points:
is_valid = False
break
if is_valid:
sheep_count += 1
print(sheep_count) | [
"nameks@naver.com"
] | nameks@naver.com |
90f8bc3f0964f54d0e651907e690a7bf85c005a1 | 916480ae24345193efa95df013f637e0a115653b | /web/transiq/sme/migrations/0026_smesummary.py | cdaad0519ec3f2a3ad05aedf28f7880fe64b8bc6 | [
"Apache-2.0"
] | permissive | manibhushan05/tms | 50e289c670e1615a067c61a051c498cdc54958df | 763fafb271ce07d13ac8ce575f2fee653cf39343 | refs/heads/master | 2022-12-11T07:59:30.297259 | 2021-09-08T03:24:59 | 2021-09-08T03:24:59 | 210,017,184 | 0 | 0 | Apache-2.0 | 2022-12-08T02:35:01 | 2019-09-21T16:23:57 | Python | UTF-8 | Python | false | false | 1,208 | py | # Generated by Django 2.0.5 on 2018-11-18 19:28
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('sme', '0025_sme_material'),
]
operations = [
migrations.CreateModel(
name='SmeSummary',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('billed_accounting_summary', django.contrib.postgres.fields.jsonb.JSONField()),
('placed_order_accounting_summary', django.contrib.postgres.fields.jsonb.JSONField()),
('accounting_summary', django.contrib.postgres.fields.jsonb.JSONField()),
('created_on', models.DateTimeField(auto_now_add=True)),
('updated_on', models.DateTimeField(auto_now=True)),
('deleted', models.BooleanField(default=False)),
('deleted_on', models.DateTimeField(blank=True, null=True)),
('sme', models.OneToOneField(on_delete=django.db.models.deletion.DO_NOTHING, to='sme.Sme')),
],
),
]
| [
"mani@myhost.local"
] | mani@myhost.local |
0cca402c23bbae04f908bfa3169dc41f789604ba | bcb877f449d74a1b30ab1e4b1b04c5091ad48c20 | /2020/day23.py | 65bc5c70c4f3c9dabb591c2ce7a23d15ef8cb56f | [
"MIT"
] | permissive | dimkarakostas/advent-of-code | c8366b9914e942cc4b4ec451713fae296314296a | 9c10ab540dc00b6356e25ac28351a3cefbe98300 | refs/heads/master | 2022-12-10T08:46:35.130563 | 2022-12-08T11:14:48 | 2022-12-08T11:14:48 | 160,544,569 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,712 | py | from collections import deque
problem_input = '463528179'
inp = deque([int(i) for i in problem_input])
curr = inp[0]
for move in range(100):
picked = []
for _ in range(3):
picked.append(inp[(inp.index(curr) + 1) % len(inp)])
inp.remove(picked[-1])
dest = curr - 1
while dest not in inp:
dest -= 1
if dest <= 0:
dest = max(inp)
if inp[-1] == dest:
for i in range(3):
inp.append(picked[i])
else:
dest_idx = inp.index(dest)
for i in range(2, -1, -1):
inp.insert(dest_idx+1, picked[i])
curr = inp[(inp.index(curr) + 1) % len(inp)]
outp = []
idx = inp.index(1) + 1
for i in range(len(inp) - 1):
outp.append(str(inp[(idx + i) % len(inp)]))
print('Part 1:', ''.join(outp))
class Node:
def __init__(self, val):
self.val = val
self.next = None
inp = list([int(i) for i in problem_input])
nodes = [Node(i) for i in range(1000001)]
for idx, item in enumerate(inp[:-1]):
nodes[item].next = nodes[inp[idx + 1]]
nodes[inp[-1]].next = nodes[max(inp) + 1]
for item in range(max(inp)+1, len(nodes)-1):
nodes[item].next = nodes[item+1]
nodes[len(nodes)-1].next = nodes[inp[0]]
curr = nodes[inp[0]]
for _ in range(10000000):
picked = [curr.next, curr.next.next, curr.next.next.next]
picked_vals = {i.val for i in picked}
curr.next = picked[-1].next
dest = curr.val - 1
while dest in picked_vals or dest == 0:
dest -= 1
if dest <= 0:
dest = len(nodes) - 1
picked[-1].next = nodes[dest].next
nodes[dest].next = picked[0]
curr = curr.next
print('Part 2:', nodes[1].next.val * nodes[1].next.next.val)
| [
"dimit.karakostas@gmail.com"
] | dimit.karakostas@gmail.com |
a90f9ca2409ed2a986641dc81ca62b4b7043b79d | 55c250525bd7198ac905b1f2f86d16a44f73e03a | /Python/Projects/sphinx/util/nodes.py | 40e49021c00292298f6c0fed6211e82b2d78ffca | [
"LicenseRef-scancode-other-permissive",
"BSD-3-Clause"
] | permissive | NateWeiler/Resources | 213d18ba86f7cc9d845741b8571b9e2c2c6be916 | bd4a8a82a3e83a381c97d19e5df42cbababfc66c | refs/heads/master | 2023-09-03T17:50:31.937137 | 2023-08-28T23:50:57 | 2023-08-28T23:50:57 | 267,368,545 | 2 | 1 | null | 2022-09-08T15:20:18 | 2020-05-27T16:18:17 | null | UTF-8 | Python | false | false | 130 | py | version https://git-lfs.github.com/spec/v1
oid sha256:5cbc9876159b9a3355e26db5ad2e756f478d71524439897687e9546b84674d14
size 22333
| [
"nateweiler84@gmail.com"
] | nateweiler84@gmail.com |
d9078b9975bba2f2a10fc34ce38bdc837fae2c0b | 0b134572e3ac3903ebb44df6d4138cbab9d3327c | /app/tests/cases_tests/test_widget.py | 59f149277f7d70ad19567ee2ac62dcb65f700d75 | [
"Apache-2.0"
] | permissive | comic/grand-challenge.org | 660de3bafaf8f4560317f1dfd9ae9585ec272896 | dac25f93b395974b32ba2a8a5f9e19b84b49e09d | refs/heads/main | 2023-09-01T15:57:14.790244 | 2023-08-31T14:23:04 | 2023-08-31T14:23:04 | 4,557,968 | 135 | 53 | Apache-2.0 | 2023-09-14T13:41:03 | 2012-06-05T09:26:39 | Python | UTF-8 | Python | false | false | 5,179 | py | import pytest
from django.core.exceptions import ValidationError
from guardian.shortcuts import assign_perm
from grandchallenge.cases.widgets import FlexibleImageField, WidgetChoices
from grandchallenge.components.models import ComponentInterface
from grandchallenge.core.guardian import get_objects_for_user
from grandchallenge.uploads.models import UserUpload
from tests.components_tests.factories import ComponentInterfaceFactory
from tests.factories import ImageFactory, UserFactory
from tests.uploads_tests.factories import UserUploadFactory
from tests.utils import get_view_for_user
@pytest.mark.django_db
def test_flexible_image_field_validation():
user = UserFactory()
upload1 = UserUploadFactory(creator=user)
upload2 = UserUploadFactory()
im1, im2 = ImageFactory.create_batch(2)
assign_perm("cases.view_image", user, im1)
ci = ComponentInterfaceFactory(kind=ComponentInterface.Kind.IMAGE)
field = FlexibleImageField(
image_queryset=get_objects_for_user(user, "cases.view_image"),
upload_queryset=UserUpload.objects.filter(creator=user).all(),
)
parsed_value_for_empty_data = field.widget.value_from_datadict(
data={}, name=ci.slug, files={}
)
decompressed_value_for_missing_value = field.widget.decompress(value=None)
assert not parsed_value_for_empty_data
assert decompressed_value_for_missing_value == [None, None]
parsed_value_for_image_with_permission = field.widget.value_from_datadict(
data={ci.slug: im1.pk}, name=ci.slug, files={}
)
decompressed_value_for_image_with_permission = field.widget.decompress(
im1.pk
)
assert (
parsed_value_for_image_with_permission
== decompressed_value_for_image_with_permission
== [
im1.pk,
None,
]
)
assert field.clean(parsed_value_for_image_with_permission) == im1
parsed_value_for_image_without_permission = (
field.widget.value_from_datadict(
data={ci.slug: im2.pk}, name=ci.slug, files={}
)
)
decompressed_value_for_image_without_permission = field.widget.decompress(
im2.pk
)
assert (
parsed_value_for_image_without_permission
== decompressed_value_for_image_without_permission
== [im2.pk, None]
)
with pytest.raises(ValidationError):
field.clean(parsed_value_for_image_without_permission)
parsed_value_for_upload_from_user = field.widget.value_from_datadict(
data={ci.slug: str(upload1.pk)}, name=ci.slug, files={}
)
decompressed_value_for_upload_from_user = field.widget.decompress(
str(upload1.pk)
)
assert (
parsed_value_for_upload_from_user
== decompressed_value_for_upload_from_user
== [None, [str(upload1.pk)]]
)
assert field.clean(parsed_value_for_upload_from_user).get() == upload1
parsed_value_from_upload_from_other_user = (
field.widget.value_from_datadict(
data={ci.slug: str(upload2.pk)}, name=ci.slug, files={}
)
)
decompressed_value_for_upload_from_other_user = field.widget.decompress(
str(upload2.pk)
)
assert (
parsed_value_from_upload_from_other_user
== decompressed_value_for_upload_from_other_user
== [None, [str(upload2.pk)]]
)
with pytest.raises(ValidationError):
field.clean(parsed_value_from_upload_from_other_user)
parsed_value_for_missing_value = field.widget.value_from_datadict(
data={ci.slug: "IMAGE_UPLOAD"}, name=ci.slug, files={}
)
decompressed_value_for_missing_value = field.widget.decompress(
"IMAGE_UPLOAD"
)
assert (
parsed_value_for_missing_value
== decompressed_value_for_missing_value
== [None, None]
)
with pytest.raises(ValidationError):
field.clean(parsed_value_for_missing_value)
@pytest.mark.django_db
def test_flexible_image_widget(client):
user = UserFactory()
ci = ComponentInterfaceFactory(kind=ComponentInterface.Kind.IMAGE)
response = get_view_for_user(
viewname="cases:select-image-widget",
client=client,
user=user,
data={
f"WidgetChoice-{ci.slug}": WidgetChoices.IMAGE_SEARCH.name,
"interface_slug": ci.slug,
},
)
assert '<input class="form-control" type="search"' in str(response.content)
response2 = get_view_for_user(
viewname="cases:select-image-widget",
client=client,
user=user,
data={
f"WidgetChoice-{ci.slug}": WidgetChoices.IMAGE_UPLOAD.name,
"interface_slug": ci.slug,
},
)
assert 'class="user-upload"' in str(response2.content)
response3 = get_view_for_user(
viewname="cases:select-image-widget",
client=client,
user=user,
data={
f"WidgetChoice-{ci.slug}": WidgetChoices.UNDEFINED.name,
"interface_slug": ci.slug,
},
)
assert response3.content == b""
| [
"noreply@github.com"
] | comic.noreply@github.com |
7ffa8e50447a97f8cbf4119dc67d8bb4a3c4aa2a | 82507189fa8aa54eec7151f9a246859052b5b30e | /dj_ajax_todo/urls.py | 8a79d2f91f6bdb27bab536426e9837e965d2f1e0 | [] | no_license | nouhben/django-ajax-todo | 96a02f21f53efcc1f8a9d32fcee3c500bcb89e74 | 00cc03db7ed12cee14b91618714b5c78429da77c | refs/heads/master | 2023-08-17T07:45:34.146971 | 2021-03-19T15:07:27 | 2021-03-19T15:07:27 | 266,007,953 | 0 | 0 | null | 2021-09-22T19:04:21 | 2020-05-22T03:20:14 | Python | UTF-8 | Python | false | false | 201 | py | from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('',include('todo.urls')),
path('todos/',include('todo.urls')),
path('admin/', admin.site.urls),
]
| [
"benkadi.nouh@icloud.com"
] | benkadi.nouh@icloud.com |
6360a786f13684708b89f005c7278215a84639df | 64ccbe2ce2176ecda231f20f1341af8368b30fd4 | /dnd/views.py | 827aab3f1ac43ce0f91eb5e89012df97ddfae18b | [] | no_license | dabslee/D-D5e-Tools | 4a6a4d4d228eba68d9750b1145ec3195dbd03db5 | 1f6f3d3b6ceac17d077ad2a29e24553e07447095 | refs/heads/master | 2023-08-15T17:27:12.336245 | 2021-10-09T02:26:48 | 2021-10-09T02:26:48 | 414,007,862 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 183 | py | from django.shortcuts import render
# Create your views here.
def home(request):
context = {
"current_page": "home"
}
return render(request, "home.html", context) | [
"brandon.sangmin.lee@gmail.com"
] | brandon.sangmin.lee@gmail.com |
10eeb1a0a39540332aac618a4f134f9b13a15a4b | bfb591a1d5166d3b56f2e8fb7f2aa52cdbfd4831 | /questions/q219_partition_equal_sum_subset/recursive.py | 6a32060facebff16a805ab0abcb96cf3f09ed2e2 | [
"MIT"
] | permissive | aadhityasw/Competitive-Programs | 8a5543995ae6ae2adae7ebaa9cb41b222d8372f1 | 3d233b665a3b2a9d0b1245f7de688b725d258b1c | refs/heads/master | 2022-01-16T19:36:48.332134 | 2022-01-03T18:14:45 | 2022-01-03T18:14:45 | 192,506,814 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,307 | py | class Solution:
def recursiveSearch(self, summ, n) :
if summ == self.required or summ == 0 :
return 1
if n < 0 :
return 0
if self.visited[summ][n] :
return 0
self.visited[summ][n] = True
return (
self.recursiveSearch(summ, n-1) or
self.recursiveSearch((summ - self.arr[n]), n-1) if summ > self.arr[n] else False
)
def equalPartition(self, N, arr):
self.arr = arr
# Find the sum of the array
summ = sum(arr)
# If the sum is odd, then return false
if summ % 2 != 0 :
return 0
# This is the number we need to obtain during the computation
self.required = summ // 2
# Form the DP table
self.visited = [[False for _ in range(N)] for _ in range(summ+1)]
# Perform a Recursive search
return self.recursiveSearch(summ, N-1)
if __name__ == '__main__':
t = int(input())
for _ in range(t):
N = int(input())
arr = input().split()
for it in range(N):
arr[it] = int(arr[it])
ob = Solution()
if (ob.equalPartition(N, arr) == 1):
print("YES")
else:
print("NO")
| [
"aadhityas@gmail.com"
] | aadhityas@gmail.com |
c1c08ab9d53ffc2101a9a0097c30215b7a1559c5 | ef479ad92071445cf2478930094472f415e0410b | /08_mask_rcnn_inceptionv2/01_float32/03_weight_quantization.py | 25d757da7bc1a057144b1bfef373f076543e8bc2 | [
"MIT"
] | permissive | Chomolungma/PINTO_model_zoo | 6f379aaadf5ff6d42f859a6a80673c816de2c664 | df020dbdcfc4a79932da6885f0cb257ffc32e37b | refs/heads/master | 2021-04-23T04:58:02.213884 | 2020-03-20T10:59:12 | 2020-03-20T10:59:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 632 | py | import tensorflow as tf
### Tensorflow v2.1.0 - master - commit 8fdb834931fe62abaeab39fe6bf0bcc9499b25bf
# Weight Quantization - Input/Output=float32
converter = tf.lite.TFLiteConverter.from_saved_model('./saved_model')
converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS]
tflite_quant_model = converter.convert()
with open('./mask_rcnn_inception_v2_coco_800_weight_quant.tflite', 'wb') as w:
w.write(tflite_quant_model)
print("Weight Quantization complete! - mask_rcnn_inception_v2_coco_800_weight_quant.tflite")
| [
"rmsdh122@yahoo.co.jp"
] | rmsdh122@yahoo.co.jp |
f73a19e9239492bf90244981ed07ce1af89650e9 | 60693b05f465e6755cf0e6f3d0cf6c78c716559a | /StateM/StateSplit.py | 2ba95883eb54e944a29e40208a5f76bbc0eac9be | [] | no_license | WXW322/ProrocolReverseTool | 6fe842f3787fbcb2dfb3dbc8d1ece66fed5593e9 | a619b51243f0844ac7ef6561bfd68a1f0856f794 | refs/heads/master | 2020-08-21T19:00:19.799383 | 2019-10-21T06:51:47 | 2019-10-21T06:51:47 | 216,224,178 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 872 | py | from common.readdata import *
class StateSplit:
def __init__(self):
pass
def generateStates(self, messages):
result = []
for message in messages:
result.append((get_ip(message.source), message.data))
return result
def splitByDire(self, messages):
ipMessages = self.generateStates(messages)
splitResults = []
i = 0
sourceIp = ipMessages[0][0]
while(i < len(ipMessages)):
tempResult = []
while(i < len(ipMessages) and ipMessages[i][0] == sourceIp):
tempResult.append(ipMessages[i][1])
i = i + 1
while (i < len(ipMessages) and ipMessages[i][0] != sourceIp):
tempResult.append(ipMessages[i][1])
i = i + 1
splitResults.append(tempResult)
return splitResults
| [
"15895903730@163.com"
] | 15895903730@163.com |
11bc419b59eefd5c2b9fdaf4f7e22060ff2267a5 | dacf092e82b5cc841554178e5117c38fd0b28827 | /day24_program4/interface/admin_interface.py | 5372c7850010cca75f8f2bcefb6a71d576ef284a | [] | no_license | RainMoun/python_programming_camp | f9bbee707e7468a7b5d6633c2364f5dd75abc8a4 | f8e06cdd2e6174bd6986d1097cb580a6a3b7201f | refs/heads/master | 2020-04-15T11:27:09.680587 | 2019-04-06T02:21:14 | 2019-04-06T02:21:14 | 164,630,838 | 4 | 1 | null | null | null | null | UTF-8 | Python | false | false | 962 | py | import os
import socket
import time
from interface import common_interface
from conf import setting
def upload_file_interface(admin_name, file_path): # 将本地文件上传至服务器
if not os.path.isfile(file_path):
return False, '文件不存在'
file_path_lst = file_path.split('/')
file_name = file_path_lst[-1]
file_size = os.path.getsize(file_path)
file_md5 = common_interface.get_file_md5(file_path)
# file = models.File(file_name, file_size, file_md5)
sk = socket.socket()
sk.connect(setting.SERVER_ADDRESS)
file_info = 'post|%s|%s|%s|%s' % (admin_name, file_name, file_size, file_md5)
sk.sendall(file_info.encode('utf-8'))
time.sleep(1)
f = open(file_path, 'rb')
has_sent = 0
while has_sent != file_size:
data = f.read(1024)
sk.sendall(data)
has_sent += len(data)
f.close()
sk.close()
print('upload success')
return True, '文件传输成功'
| [
"775653143@qq.com"
] | 775653143@qq.com |
32d8dc9ef7307c6d3118b4af34978bf943b77ba4 | 951e433b25a25afeea4d9b45994a57e0a6044144 | /NowCoder/拼多多_回合制游戏.py | b9c5f768b6df142db72c09e965dc9fcc88c5528e | [] | no_license | EricaEmmm/CodePython | 7c401073e0a9b7cd15f9f4a553f0aa3db1a951a3 | d52aa2a0bf71b5e7934ee7bff70d593a41b7e644 | refs/heads/master | 2020-05-31T14:00:34.266117 | 2019-09-22T09:48:23 | 2019-09-22T09:48:23 | 190,318,878 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,350 | py | # 回合制游戏
# 你在玩一个回合制角色扮演的游戏。现在你在准备一个策略,以便在最短的回合内击败敌方角色。在战斗开始时,敌人拥有HP格血量。
# 当血量小于等于0时,敌人死去。一个缺乏经验的玩家可能简单地尝试每个回合都攻击。但是你知道辅助技能的重要性。
# 在你的每个回合开始时你可以选择以下两个动作之一:聚力或者攻击。
# 聚力会提高你下个回合攻击的伤害。
# 攻击会对敌人造成一定量的伤害。如果你上个回合使用了聚力,那这次攻击会对敌人造成buffedAttack点伤害。否则,会造成normalAttack点伤害。
# 给出血量HP和不同攻击的伤害,buffedAttack和normalAttack,返回你能杀死敌人的最小回合数。
#
# 输入描述:
# 第一行是一个数字HP
# 第二行是一个数字normalAttack
# 第三行是一个数字buffedAttack
# 1 <= HP,buffedAttack,normalAttack <= 10^9
# 输出描述:
# 输出一个数字表示最小回合数
#
# 输入例子1:
# 13
# 3
# 5
# 输出例子1:
# 5
# buff=0,表示上个回合攻击了,这个回合只能normalAttack
# buff=1,表示上个回合聚力了,这个回合只能normalAttack
def helper(HP, normalAttack, buffedAttack, buff):
if HP <= 0:
return
if buff:
return min(helper(HP-normalAttack), normalAttack, buffedAttack, 1)
if __name__ == '__main__':
HP = int(input())
normalAttack = int(input())
buffedAttack = int(input())
if normalAttack >= HP:
print(1)
res = 0
if normalAttack * 2 >= buffedAttack: # 当蓄力的伤害不高于普通伤害的二倍的时候,全用普通伤害
# while HP > 0:
# res += 1
# HP -= normalAttack
# print(res)
res = HP // normalAttack
if HP-res*normalAttack > 0:
print(res+1)
else:
print(res)
else:
# while HP > normalAttack:
# res += 2
# HP -= buffedAttack
# if HP <= 0:
# print(res)
# else:
# print(res+1)
res = HP // buffedAttack
if HP-res*buffedAttack > normalAttack:
print(2*(res+1))
elif HP-res*buffedAttack > 0:
print(2*res+1)
else:
print(2*res)
| [
"1016920795@qq.com"
] | 1016920795@qq.com |
74f00f42f7ad17c83df242a9a67d18dd57e80f6d | 146143036ef6a0bf2346eef9881db3ac85059008 | /kdl_wagtail/people/migrations/0002_rename_field_summary_on_person_to_introduction.py | 04f158bb7929b972babedece17961f9fae723c7f | [
"MIT"
] | permissive | kingsdigitallab/django-kdl-wagtail | bc5a26420fcef3a25c6a42b0c5bb5f8643d32951 | 457623a35057f88ee575397ac2c68797f35085e1 | refs/heads/master | 2023-01-06T02:43:48.073289 | 2021-10-08T19:25:56 | 2021-10-08T19:25:56 | 168,135,935 | 3 | 0 | MIT | 2022-12-26T20:39:03 | 2019-01-29T10:27:05 | Python | UTF-8 | Python | false | false | 370 | py | # Generated by Django 2.1.5 on 2019-01-31 10:04
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('kdl_wagtail_people', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='person',
old_name='summary',
new_name='introduction',
),
]
| [
"jmvieira@gmail.com"
] | jmvieira@gmail.com |
e8db7174a5e58d829efa2ed8646b01398663afb2 | 1b8d162160f5ab6d6a6b8940b8ab83b482abb409 | /tests/aggregation/test_max.py | d32d10c32315d5359c79abb9b11b2e441941fdc9 | [
"Apache-2.0"
] | permissive | jlinn/pylastica | f81e438a109dfe06adc7e9b70fdf794c5d01a53f | 0fbf68ed3e17d665e3cdf1913444ebf1f72693dd | refs/heads/master | 2020-05-19T14:07:38.794717 | 2014-07-23T23:43:00 | 2014-07-23T23:43:00 | 10,442,284 | 5 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,063 | py | from pylastica.aggregation.max import Max
from pylastica.document import Document
from pylastica.query.query import Query
from pylastica.script import Script
from tests.base import Base
__author__ = 'Joe Linn'
import unittest
class MaxTest(unittest.TestCase, Base):
def setUp(self):
super(MaxTest, self).setUp()
self._index = self._create_index("test_aggregation_max")
docs = [
Document("1", {"price": 5}),
Document("2", {"price": 8}),
Document("3", {"price": 1}),
Document("4", {"price": 3})
]
self._index.get_doc_type("test").add_documents(docs)
self._index.refresh()
def tearDown(self):
super(MaxTest, self).tearDown()
self._index.delete()
def test_to_dict(self):
expected = {
"max": {
"field": "price",
"script": "_value * conversion_rate",
"params": {
"conversion_rate": 1.2
}
},
"aggs": {
"subagg": {"max": {"field": "foo"}}
}
}
agg = Max("min_price_in_euros")
agg.set_field("price")
agg.set_script(Script("_value * conversion_rate", {"conversion_rate": 1.2}))
agg.add_aggregation(Max("subagg").set_field("foo"))
self.assertEqual(expected, agg.to_dict())
def test_max_aggregation(self):
agg = Max("min_price")
agg.set_field("price")
query = Query()
query.add_aggregation(agg)
results = self._index.get_doc_type("test").search(query).aggregations["min_price"]
self.assertAlmostEqual(8, results["value"])
# test using a script
agg.set_script(Script("_value * conversion_rate", {"conversion_rate": 1.2}))
query = Query()
query.add_aggregation(agg)
results = self._index.get_doc_type("test").search(query).aggregations["min_price"]
self.assertEqual(8 * 1.2, results["value"])
if __name__ == '__main__':
unittest.main()
| [
"joe@venturocket.com"
] | joe@venturocket.com |
938d2387acdadda18fcff71135fa9bb41e9d267b | 232411e5462f43b38abd3f0e8078e9acb5a9fde7 | /build/rotors_description/catkin_generated/pkg.develspace.context.pc.py | d9fa71b7cb86e4b8eb08039501fa05b1632357d6 | [] | no_license | Fengaleng/feng_ws | 34d8ee5c208f240c24539984bc9d692ddf1808f9 | a9fa2e871a43146a3a85a0c0a9481793539654eb | refs/heads/main | 2023-03-29T17:25:42.110485 | 2021-03-30T14:50:24 | 2021-03-30T14:50:24 | 353,034,507 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 406 | py | # generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else []
PROJECT_CATKIN_DEPENDS = "".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else []
PROJECT_NAME = "rotors_description"
PROJECT_SPACE_DIR = "/home/fechec/feng_ws/devel/.private/rotors_description"
PROJECT_VERSION = "2.2.3"
| [
"chenfy1998@gmail.com"
] | chenfy1998@gmail.com |
b35f61492670ffc4e2044973d754b52e2c12fc65 | 4e30c855c253cc1d972d29e83edb9d5ef662d30a | /invoice/models.py | 10e28aa5941aea567f4bca34e53e910b3c7e20b5 | [
"MIT"
] | permissive | rajeshr188/django-onex | 8b531fc2f519d004d1da64f87b10ffacbd0f2719 | 0a190ca9bcf96cf44f7773686205f2c1f83f3769 | refs/heads/master | 2023-08-21T22:36:43.898564 | 2023-08-15T12:08:24 | 2023-08-15T12:08:24 | 163,012,755 | 2 | 0 | NOASSERTION | 2023-07-22T09:47:28 | 2018-12-24T17:46:35 | Python | UTF-8 | Python | false | false | 541 | py | from django.db import models
from django.utils import timezone
# Create your models here.
class voucher(models.Model):
pass
class PaymentTerm(models.Model):
name = models.CharField(max_length=30)
description = models.TextField()
due_days = models.PositiveSmallIntegerField()
discount_days = models.PositiveSmallIntegerField()
discount = models.DecimalField(max_digits=10, decimal_places=2)
class Meta:
ordering = ("due_days",)
def __str__(self):
return f"{self.name} ({self.due_days})"
| [
"rajeshrathodh@gmail.com"
] | rajeshrathodh@gmail.com |
f80f0be06fc4b0b545009feebda90b8c1dfed845 | ea48ef0588c104e49a7ebec5bd8dc359fdeb6674 | /mini_web_frame/deme/django_orm模型.py | 4f0825357545e2d50dbb4344b17e936e298facf0 | [] | no_license | Jizishuo/django--text | c0d58d739ef643c7f3793fbead19302778670368 | 152a5c99e7a16a75fda2f1f85edcfdce9274c9c2 | refs/heads/master | 2020-04-01T10:39:18.131551 | 2018-11-18T13:31:59 | 2018-11-18T13:31:59 | 153,125,799 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,053 | py | '''
class ModelMetaclass(type):
def __new__(cls, name, bases, attrs): #name=user,bases=(),attrs={'uid':(..)...}
mappings = dict()
#判断是否需要保存
#例如type('AAA', (), {'num ':1, 'num2':2}) 创建类
for k, v in attrs.items():
if isinstance(v, tuple):
#print("mappings %s--->%s" % (k, v))
mappings[k] = v
#删除这些存在字典中的属性
for k in mappings.keys():
attrs.pop(k)
#将之前的uid/name..以及对应的对象引用,类名
attrs['__mappings__'] = mappings #雷属性与列名字的映射关系
attrs['__table__'] = name
#tuple(attrs)
return type.__new__(cls, name, bases, attrs)
class User(metaclass=ModelMetaclass):
uid = ('uid', 'int unsigned')
name = ('username', 'varchar(30)')
email = ('email', 'varchar(30)')
password = ('password', 'varchar(30)')
#经过modelmetaclas后变
#__mappings__ = {
#'uid' : ('uid', 'int unsigned'),
#'name' : ('username', 'varchar(30)'),
#'email' : ('email', 'varchar(30)'),
#'password' : ('password', 'varchar(30)'),
#}
#__table__ = 'User'
def __init__(self, **kwargs):
for name, value in kwargs.items():
setattr(self, name, value)
#uid=123 name=uid,value=123的name=value...
def save(self):
fields = []
args = []
for k, v in self.__mappings__.items():
fields.append(v[0])
args.append(getattr(self, k, None))
#这个不完美
#sql = 'insert into %s (%s) values (%s)' % (self.__table__, ','.join(fields), ','.join([str(i) for i in args]))
# insert into User (uid,username,email,password) values (123,root,xxx@xxx,xxxx)
args_temp = list()
for temp in args: #['123', "'root'", "'xxx@xxx'", "'xxxx'"]
#判断插入的如果是数字
if isinstance(temp, int):
args_temp.append(str(temp))
elif isinstance(temp, str):
args_temp.append("""'%s'""" % temp)
print(args_temp)
sql = 'insert into %s (%s) values (%s)' % (self.__table__, ','.join(fields), ','.join(args_temp))
print(sql)
#insert into User (uid,username,email,password) values (123,'root','xxx@xxx','xxxx')
u = User(uid=123, name='root', email='xxx@xxx', password='xxxx')
u.save()
'''
class ModelMetaclass(type):
def __new__(cls, name, bases, attrs): #name=user,bases=(),attrs={'uid':(..)...}
mappings = dict()
#判断是否需要保存
#例如type('AAA', (), {'num ':1, 'num2':2}) 创建类
for k, v in attrs.items():
if isinstance(v, tuple):
#print("mappings %s--->%s" % (k, v))
mappings[k] = v
#删除这些存在字典中的属性
for k in mappings.keys():
attrs.pop(k)
#将之前的uid/name..以及对应的对象引用,类名
attrs['__mappings__'] = mappings #雷属性与列名字的映射关系
attrs['__table__'] = name
#tuple(attrs)
return type.__new__(cls, name, bases, attrs)
class Model(metaclass=ModelMetaclass):
#经过modelmetaclas后变
#__mappings__ = {
#'uid' : ('uid', 'int unsigned'),
#'name' : ('username', 'varchar(30)'),
#'email' : ('email', 'varchar(30)'),
#'password' : ('password', 'varchar(30)'),
#}
#__table__ = 'User'
def __init__(self, **kwargs):
for name, value in kwargs.items():
setattr(self, name, value)
#uid=123 name=uid,value=123的name=value...
def save(self):
fields = []
args = []
for k, v in self.__mappings__.items():
fields.append(v[0])
args.append(getattr(self, k, None))
#这个不完美
#sql = 'insert into %s (%s) values (%s)' % (self.__table__, ','.join(fields), ','.join([str(i) for i in args]))
# insert into User (uid,username,email,password) values (123,root,xxx@xxx,xxxx)
args_temp = list()
for temp in args: #['123', "'root'", "'xxx@xxx'", "'xxxx'"]
#判断插入的如果是数字
if isinstance(temp, int):
args_temp.append(str(temp))
elif isinstance(temp, str):
args_temp.append("""'%s'""" % temp)
print(args_temp)
sql = 'insert into %s (%s) values (%s)' % (self.__table__, ','.join(fields), ','.join(args_temp))
print(sql)
#insert into User (uid,username,email,password) values (123,'root','xxx@xxx','xxxx')
class User(Model):
uid = ('uid', 'int unsigned')
name = ('username', 'varchar(30)')
email = ('email', 'varchar(30)')
password = ('password', 'varchar(30)')
u = User(uid=123, name='root', email='xxx@xxx', password='xxxx')
u.save() | [
"948369894@qq.com"
] | 948369894@qq.com |
7744e21b09e713d7eb3c26adcc7d76080eb9c847 | 620323fc090cebaf7aca456ff3f7fbbe1e210394 | /qt__pyqt__pyside__pyqode/example_QStackedWidget/use_listwidget.py | df42105e6af3e29d463d9aa479d1ebed22cc55a4 | [
"CC-BY-4.0"
] | permissive | gil9red/SimplePyScripts | bd2733372728bf9b9f00570e90316fa12116516b | 773c2c9724edd8827a1dbd91694d780e03fcb05a | refs/heads/master | 2023-08-31T04:26:09.120173 | 2023-08-30T17:22:59 | 2023-08-30T17:22:59 | 22,650,442 | 157 | 46 | null | 2023-09-08T17:51:33 | 2014-08-05T16:19:52 | Python | UTF-8 | Python | false | false | 1,025 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
from PyQt5.QtWidgets import (
QApplication,
QHBoxLayout,
QWidget,
QLabel,
QStackedWidget,
QListWidget,
)
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.stacked_widget = QStackedWidget()
self.stacked_widget.addWidget(QLabel("1234"))
self.stacked_widget.addWidget(QLabel("ABCD"))
self.stacked_widget.addWidget(QLabel("FOO_BAR"))
self.control_list = QListWidget()
self.control_list.addItems(["1234", "ABCD", "FOO_BAR"])
self.control_list.setFixedWidth(80)
self.control_list.clicked.connect(
lambda index: self.stacked_widget.setCurrentIndex(index.row())
)
main_layout = QHBoxLayout(self)
main_layout.addWidget(self.control_list)
main_layout.addWidget(self.stacked_widget)
if __name__ == "__main__":
app = QApplication([])
mw = MainWindow()
mw.show()
app.exec()
| [
"ilya.petrash@inbox.ru"
] | ilya.petrash@inbox.ru |
f9aba00ebbe58ef41e41b7374c770514fad67a28 | 6dedbcff0af848aa979574426ad9fa3936be5c4a | /cengal/parallel_execution/coroutines/coro_standard_services/shutdown_on_keyboard_interrupt/versions/v_0/__init__.py | 5e2395584c9ba7589876333ee84c164b51c2af0c | [
"Apache-2.0"
] | permissive | FI-Mihej/Cengal | 558d13541865e22006431bd1a1410ad57261484a | d36c05f4c90dfdac7296e87cf682df2f4d367e4b | refs/heads/master | 2023-06-08T00:39:39.414352 | 2023-06-05T21:35:50 | 2023-06-05T21:35:50 | 68,829,562 | 10 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,252 | py | #!/usr/bin/env python
# coding=utf-8
# Copyright © 2012-2023 ButenkoMS. All rights reserved. Contacts: <gtalk@butenkoms.space>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from .shutdown_on_keyboard_interrupt import *
"""
Module Docstring
Docstrings: http://www.python.org/dev/peps/pep-0257/
"""
__author__ = "ButenkoMS <gtalk@butenkoms.space>"
__copyright__ = "Copyright © 2012-2023 ButenkoMS. All rights reserved. Contacts: <gtalk@butenkoms.space>"
__credits__ = ["ButenkoMS <gtalk@butenkoms.space>", ]
__license__ = "Apache License, Version 2.0"
__version__ = "3.2.6"
__maintainer__ = "ButenkoMS <gtalk@butenkoms.space>"
__email__ = "gtalk@butenkoms.space"
# __status__ = "Prototype"
__status__ = "Development"
# __status__ = "Production"
| [
"gtalk@butenkoms.space"
] | gtalk@butenkoms.space |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.