blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
69
license_type
stringclasses
2 values
repo_name
stringlengths
5
118
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
63
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
2.91k
686M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
220 values
src_encoding
stringclasses
30 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
2
10.3M
extension
stringclasses
257 values
content
stringlengths
2
10.3M
authors
listlengths
1
1
author_id
stringlengths
0
212
7b074b16357bc2c87f85ae3c3bc8abc531229670
d4f7d1b2eea81e42db32638d0fdaf35908786a95
/common/imagesDownload.py
dc891f16374b86196c09695299ee6d01dbb168a6
[]
no_license
gyuha/mshow_downloader
e47e1d1a26203b5dbba4b36e0ad2f01d87368235
f44f6f706bdc3742bb892f9c96557a327fe040c3
refs/heads/master
2022-08-24T03:53:51.697041
2022-08-13T15:30:28
2022-08-13T15:30:28
161,354,810
7
0
null
2022-08-13T15:30:10
2018-12-11T15:31:19
Python
UTF-8
Python
false
false
2,960
py
import os import pathlib import re import shutil import sys import time import urllib.request import zipfile from datetime import date from multiprocessing import Pool, cpu_count from os.path import basename import requests import tqdm import wget from bs4 import BeautifulSoup from mshow.config import Config from mshow.imageCompress import imagesCompress from mshow.imageConverter import convertImages CUSTOM_USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36' def pathName(path): path = re.sub(r"NEW\t+", "", path) path = path.replace('\n', '') path = re.sub(r"\t.*$", "", path) path = path.replace(':', '').replace('?', '').replace( '/', '').replace('!', '').replace('\\', '') path = path.replace("「", " ").replace("」", '').replace(".", "") path = path.replace("<", "").replace(">", "") path = path.replace("\"", "") path = path.strip() return path def imagesDownload(title, savePath, images, chapter, seed): title = pathName(title) pathlib.Path(savePath).mkdir(parents=True, exist_ok=True) target = [] # c = Config() for i, img in enumerate(images): # img = re.sub(r"mangashow\d.me", c.getName(), img[0]) target.append([img, savePath, i+1]) pool = Pool(processes=cpu_count()) try: # for tar in target: # __downloadFromUrl(tar) for _ in tqdm.tqdm(pool.imap_unordered(__downloadFromUrl, target), total=len(target), ncols=68, desc=" Download", leave=False): pass finally: pool.close() pool.join() print(" "*80, end="\r") # if int(seed) > 0: # convertImages(savePath, chapter, seed) # imagesCompress(savePath) __zipFolder(savePath + "-" + pathName(title) + ".cbz", savePath) shutil.rmtree(savePath, ignore_errors=True) def __zipFolder(filename, path): zipf = zipfile.ZipFile(filename, 'w', zipfile.ZIP_DEFLATED) for f in os.listdir(path): zipf.write(os.path.join(path, f), basename(f)) zipf.close() def __downloadFromUrl(p, trycount=0): url = p[0] outputPath = p[1] num = p[2] name = "%03d" % (num,) + ".jpg" outputPath = os.path.join(outputPath, name) try: req = urllib.request.Request( url, headers={'User-Agent': CUSTOM_USER_AGENT}) with open(outputPath, "wb") as f: with urllib.request.urlopen(req, timeout=30) as r: f.write(r.read()) # urllib.request.urlretrieve(url, "D:/abc/image/local-filename.jpg") # requests.urllib3.disable_warnings() # s = requests.Session() # s.headers.update({'Connection': 'keep-alive', # 'User-Agent': CUSTOM_USER_AGENT}) # r = s.get(url, stream=True, verify=False) # with open(outputPath, 'wb') as f: # for chunk in r.content(chunk_size=4096): # f.write(chunk) # f.close() except: if trycount < 3: print(" Retry: ", url) __downloadFromUrl(p, trycount + 1) return
[ "nicegyuha@gmail.com" ]
nicegyuha@gmail.com
c2f5b5868e69f80eef26381c90750d43279f8390
8d02f4a2f340ce9f1ca581a54a093f8133ab4ffa
/Livraria/endgamelivraria/endgamelivraria/endgamelivraria/settings.py
e425a0a2d22b12f2a715310d198c870bd6948955
[]
no_license
Manoel-Junior/Sistema-de-Gestao-de-Livrarias-Online
bd4be6c8fcd9934586953ae818b6bbe3a035a49f
eb41668697671dbf8ac6112e5de6afec58e9083e
refs/heads/master
2020-06-06T15:00:51.877670
2019-06-19T17:18:17
2019-06-19T17:18:17
192,771,580
0
0
null
2019-12-03T23:33:20
2019-06-19T16:51:32
Python
UTF-8
Python
false
false
3,580
py
""" Django settings for endgamelivraria project. Generated by 'django-admin startproject' using Django 2.2.1. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/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.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'en^efdane%su+t)h-254i*f!#gus%w-m%&^3rw#5t0%c)0c4vk' # 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', 'enter', 'bootstrapform', 'crispy_forms', ] CRISPY_TEMPLATE_PACK = 'bootstrap4' 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 = 'endgamelivraria.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'endgamelivraria.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'Livraria', 'USER': 'postgres', 'PASSWORD': 'hcss1995.', 'HOST': 'localhost', 'PORT': '5432', } } # Password validation # https://docs.djangoproject.com/en/2.2/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.2/topics/i18n/ LANGUAGE_CODE = 'pt-br' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static"), '/endgamelivraria/enter/static/',
[ "noreply@github.com" ]
Manoel-Junior.noreply@github.com
6f57d3d39373561775457a376036713d40b1e070
97c17d1b34df7b1de217cb52fd5cbb2e6671c743
/generator/project.py
020fa2d653012061cda784998f77357db9e56d9e
[ "Apache-2.0" ]
permissive
mihushynmaksym/Mantis_tests
63fc5a0bffb30298a53b2348bda66e6c549152b8
e5b125d3eb54e26543298724c0577e45ea863aca
refs/heads/main
2022-12-30T17:45:14.374085
2020-10-19T03:31:42
2020-10-19T03:31:42
303,779,079
0
0
null
null
null
null
UTF-8
Python
false
false
948
py
from model.project import Project import random import string import os.path import jsonpickle import getopt import sys try: opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of groups", "file"]) except getopt.GetoptError as err: getopt.usage() sys.exit(2) n = 5 f = "data/project.json" for o, a in opts: if o == "-n": n = int(a) elif o == "-f": f = a def random_string_for_group(prefix, maxlen): symbols = string.ascii_letters + string.digits return prefix + "".join([random.choice(symbols) for i in range(random.randrange(maxlen))]) test_data = [Project( name=random_string_for_group("w", 10), description=random_string_for_group("q", 10)) for i in range(n)] file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", f) with open(file, "w") as out: jsonpickle.set_encoder_options("json", indent=2) out.write(jsonpickle.encode(test_data))
[ "mihushynmaksym@gmail.com" ]
mihushynmaksym@gmail.com
616d706d6ce1b30b0bc74811e9df65ffbb9d2ae1
a432e6060e065b777e9bb14249f2148ed9af24d0
/Patents/src/com/example/servlets/compare.py
50324545a43638ddf9d439da312dbe58067bf292
[]
no_license
anishetty11/Face-Rekognition
0d46533934d0c380c17df15d6d78bde78bd1b1be
a916ebc3defbb45500aefd4b6d43e1c676961254
refs/heads/master
2021-04-27T19:51:10.009709
2020-11-13T05:19:14
2020-11-13T05:19:14
122,366,327
0
0
null
null
null
null
UTF-8
Python
false
false
1,443
py
from dbconnect import db from capture_image import get_image from gul_bad_code import upload import boto3 import sys import os g=open("program_executed.txt",'w') try: client=boto3.client('rekognition','us-west-2') #image_binary=get_image.capture_image() imageFile="temp.jpg" image = open(imageFile,'rb') image_binary=(image.read()) SourceImage_list=db.get_patient_details() for i in SourceImage_list: print ("---->Checking the image with: ",i) try: response = client.compare_faces( SourceImage={ 'S3Object': { 'Bucket': 'patients-recogn', 'Name': i, #'Version': 'string' } }, TargetImage={ #'Bytes': b'bytes', 'Bytes': image_binary #'S3Object': { # 'Bucket': 'patients-recogn-refer', # 'Name': 'input3.jpg', #'Version': 'string' }, SimilarityThreshold=70 ) if len(response['UnmatchedFaces'])==0: print ("\n\n~~~~~~~~~~~~Face has a match:" + i+"~~~~~~~~~~~~~~\n") f=open("~~face_matched.txt",'w') row=db.get_details(i) for j in row: f.write(str(j)+'\n') f.close() sys.exit() except Exception as e: print ("Error in loading image from s3 (",i," :",e) continue except Exception as e: print ("\n:(\nFace not detected: ",e) print( " No match found, add new user? y/n") if os.path.isfile("~~tmp.txt"): os.remove("~~tmp.txt") if(input()=='y'): upload.uploadImage()
[ "anishshetty@live.com" ]
anishshetty@live.com
7b67372b80781dbc722821dd0e9e4fccabe7148f
2ad9a73cb3e2da46fb15ae56a6dee11407fe8845
/ports/kodi/addons/plugin.video.transistortv/scrapers/premiumizev2_scraper.py
69c8e67f70be1ddef948a478838c26a63220c567
[]
no_license
hpduong/retropie_configs
cde596b35897a3faeedefabd742fc15820d58255
ed4e39146e5bebc0212dcef91108541a128d9325
refs/heads/master
2021-07-12T15:46:17.589357
2018-11-11T19:10:54
2018-11-11T19:10:54
157,111,040
1
2
null
2020-07-24T03:43:29
2018-11-11T18:59:52
Python
UTF-8
Python
false
false
9,637
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 re import kodi import log_utils # @UnusedImport from transistortv_lib import scraper_utils from transistortv_lib.utils2 import i18n from transistortv_lib.constants import FORCE_NO_MATCH from transistortv_lib.constants import VIDEO_TYPES from transistortv_lib.constants import QUALITIES from transistortv_lib.constants import DELIM import scraper logger = log_utils.Logger.get_logger() VIDEO_EXT = ['MKV', 'AVI', 'MP4'] MIN_MEG = 100 LIST_URL = '/api/transfer/list' FOLDER_URL = '/api/folder/list' BROWSE_URL = '/api/torrent/browse' class Scraper(scraper.Scraper): base_url = '' base_name = 'Premiumize.me' def __init__(self, timeout=scraper.DEFAULT_TIMEOUT): self.timeout = timeout if kodi.get_setting('%s-use_https' % (self.__class__.base_name)) == 'true': scheme = 'https' prefix = 'www' else: scheme = 'http' prefix = 'http' base_url = kodi.get_setting('%s-base_url' % (self.__class__.base_name)) self.base_url = scheme + '://' + prefix + '.' + base_url self.username = kodi.get_setting('%s-username' % (self.__class__.base_name)) self.password = kodi.get_setting('%s-password' % (self.__class__.base_name)) @classmethod def provides(cls): return frozenset([VIDEO_TYPES.MOVIE, VIDEO_TYPES.EPISODE, VIDEO_TYPES.SEASON]) @classmethod def get_name(cls): return 'Premiumize.V2' def get_sources(self, video): hosters = [] source_url = self.get_url(video) if not source_url or source_url == FORCE_NO_MATCH: return hosters for stream in self.__get_videos(source_url, video): if video.video_type == VIDEO_TYPES.EPISODE and not scraper_utils.release_check(video, stream['name']): continue host = scraper_utils.get_direct_hostname(self, stream['url']) hoster = {'multi-part': False, 'class': self, 'views': None, 'url': stream['url'], 'rating': None, 'host': host, 'quality': stream['quality'], 'direct': True} if 'size' in stream: hoster['size'] = scraper_utils.format_size(stream['size']) if 'name' in stream: hoster['extra'] = stream['name'] hosters.append(hoster) return hosters def __get_videos(self, source_url, video): videos = [] query = scraper_utils.parse_query(source_url) if 'hash' in query: url = scraper_utils.urljoin(self.base_url, BROWSE_URL) js_data = self._http_get(url, params={'hash': query['hash']}, cache_limit=1) if 'content' in js_data: videos = self.__get_videos2(js_data['content'], video) return videos def __get_videos2(self, content, video): videos = [] for key in content: item = content[key] if item['type'].lower() == 'dir': videos += self.__get_videos2(item['children'], video) else: if item['ext'].upper() in VIDEO_EXT and ('size' not in item or int(item['size']) > (MIN_MEG * 1024 * 1024)): temp_video = {'name': item['name'], 'url': item['url'], 'size': item['size']} temp_video['quality'] = self.__get_quality(item, video) videos.append(temp_video) if 'transcoded' in item and item['transcoded']: transcode = item['transcoded'] name = '(Transcode) %s' % (item['name']) temp_video = {'name': name, 'url': transcode['url']} temp_video['quality'] = self.__get_quality(transcode, video) if 'size' in transcode: temp_video['size'] = transcode['size'] videos.append(temp_video) return videos def __get_quality(self, item, video): if item.get('width'): return scraper_utils.width_get_quality(item['width']) elif item.get('height'): return scraper_utils.height_get_quality(item['height']) elif 'name' in item: if video.video_type == VIDEO_TYPES.MOVIE: meta = scraper_utils.parse_movie_link(item['name']) else: meta = scraper_utils.parse_episode_link(item['name']) return scraper_utils.height_get_quality(meta['height']) else: return QUALITIES.HIGH def get_url(self, video): url = super(self.__class__, self).get_url(video) # check each torrent to see if it's an episode if there is no season url if url is None and video.video_type == VIDEO_TYPES.EPISODE: if not scraper_utils.force_title(video): for item in self.__get_torrents(): if scraper_utils.release_check(video, item['name']): return 'hash=%s' % (item['hash']) return url def _get_episode_url(self, season_url, video): query = scraper_utils.parse_query(season_url) if 'hash' in query: for stream in self.__get_videos(season_url, video): if scraper_utils.release_check(video, stream['name']): return season_url def __get_torrents(self, folder_id=None): torrents = [] url = scraper_utils.urljoin(self.base_url, FOLDER_URL) if folder_id is not None: url += '?id=%s' % (folder_id) js_data = self._http_get(url, cache_limit=.001) if 'content' in js_data: for item in js_data['content']: if item['type'] == 'folder': torrents += self.__get_torrents(item['id']) elif item['type'] == 'torrent': torrents.append(item) return torrents def search(self, video_type, title, year, season=''): results = [] norm_title = scraper_utils.normalize_title(title) for item in self.__get_torrents(): if title or year or season: is_season = re.search('(.*?{delim}season{delim}+(\d+)){delim}?(.*)'.format(delim=DELIM), item['name'], re.I) if (not is_season and video_type == VIDEO_TYPES.SEASON) or (is_season and video_type == VIDEO_TYPES.MOVIE): continue if re.search('{delim}S\d+E\d+{delim}'.format(delim=DELIM), item['name'], re.I): continue # skip episodes if video_type == VIDEO_TYPES.SEASON: match_title, match_season, extra = is_season.groups() if season and int(match_season) != int(season): continue match_year = '' match_title = re.sub(DELIM, ' ', match_title) else: match = re.search('(.*?)\(?(\d{4})\)?(.*)', item['name']) if match: match_title, match_year, extra = match.groups() else: match_title, match_year, extra = item['name'], '', '' else: match_title, match_year, extra = item['name'], '', '' match_title = match_title.strip() extra = extra.strip() if norm_title in scraper_utils.normalize_title(match_title) and (not year or not match_year or year == match_year): result_title = match_title if extra: result_title += ' [%s]' % (extra) result = {'title': result_title, 'year': match_year, 'url': 'hash=%s' % (item['hash'])} results.append(result) return results @classmethod def get_settings(cls): name = cls.get_name() settings = [ ' <setting id="%s-enable" type="bool" label="%s %s" default="true" visible="true"/>' % (name, name, i18n('enabled')), ' <setting id="%s-sub_check" type="bool" label=" %s" default="false" visible="eq(-1,true)"/>' % (name, i18n('page_existence')), ] return settings def _http_get(self, url, params=None, data=None, allow_redirect=True, cache_limit=8): if not self.username or not self.password: return {} if data is None: data = {} data.update({'customer_id': self.username, 'pin': self.password}) result = super(self.__class__, self)._http_get(url, params=params, data=data, allow_redirect=allow_redirect, cache_limit=cache_limit) js_result = scraper_utils.parse_json(result, url) if 'status' in js_result and js_result['status'] == 'error': logger.log('Premiumize V2 Scraper Error: %s - (%s)' % (url, js_result.get('message', 'Unknown Error')), log_utils.LOGWARNING) js_result = {} return js_result
[ "henryduong@gmail.com" ]
henryduong@gmail.com
bc0c564fc708099ee3a1ee9245efc66093f51371
52cb25dca22292fce4d3907cc370098d7a57fcc2
/BAEKJOON/스택/1874_스택 수열.py
cd390374565cc30f00a17f883e2ac40791b3a1f1
[]
no_license
shjang1013/Algorithm
c4fc4c52cbbd3b7ecf063c716f600d1dbfc40d1a
33f2caa6339afc6fc53ea872691145effbce0309
refs/heads/master
2022-09-16T12:02:53.146884
2022-08-31T16:29:04
2022-08-31T16:29:04
227,843,135
1
0
null
null
null
null
UTF-8
Python
false
false
564
py
# 1부터 n까지의 수를 스택에 넣었다가 뽑아 늘어놓음으로써, 하나의 수열을 만들 수 있다. # [1,2,3,4,5,6,7,8] => [4,3,6,8,7,5,2,1] import sys N = int(input()) stack = [] op = [] count = 1 temp = True for i in range(N): n = int(sys.stdin.readline()) while count <= n: stack.append(count) op.append("+") count += 1 if stack[-1] == n: stack.pop() op.append("-") else: temp = False break if temp == False: print("NO") else: print('\n'.join(op))
[ "shjang113@gmail.com" ]
shjang113@gmail.com
e5f861cefd30ef3e8e1fd1a13a5198418d127fea
4bd49c12feeef0bc8342188a6e79cf2281b9832b
/django/analyses/management/commands/Test_Fixtures/ucl_batch.py
f96f34e57aba7e7e2614fd512aca61b8f374659a
[]
no_license
jonbutterworth/ConturDjango
238ff36eb9d68544db047630f76b5d4a25309e81
855b9a19a2446175746830129c601c3c442a2225
refs/heads/master
2023-03-13T20:47:30.356427
2019-03-19T16:55:22
2019-03-19T16:55:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
608
py
#!/usr/bin/python import subprocess batch_setup_file = """\ {HerwigSetup}; cd {pwd}/{modelpath}; {ConturSetup}; Herwig run --seed={i}{j} --tag={modelpath} -j 2 -N {numEv} LHC.run; """ def write_batch_file(batch_filename, modelpath, pwd, HerwigSetup, ConturSetup, numEv, i, j): batch_command = batch_setup_file.format(locals()) batch_filename = "{}.sh".format(modelpath) with open(batch_filename, 'w') as batch_submit: batch_submit.write(batch_command) return batch_command def run_batch_file(batch_filename): subprocess.call(["qsub","-q","medium",batch_filename],shell=True )
[ "NathanMAC@Nathans-MBP.home" ]
NathanMAC@Nathans-MBP.home
dd801a3914c9df830e89a54f58c355e0dec176a9
0cf1c2739ed6c3c1174054bef62a217c7cbd46d8
/MarvellousNum.py
d3ec5165818f652ff01d1500fcbd7d091fe6bbd7
[]
no_license
suniljarad/unity
6d2d84283385d2175de21e2b8ca5ae20b5622433
0e3f7a66d3f4832567ff6e37de295e5205fc9d9e
refs/heads/master
2021-07-16T00:26:51.494058
2021-03-13T12:04:57
2021-03-13T12:04:57
41,076,224
0
0
null
null
null
null
UTF-8
Python
false
false
417
py
def ChkPrime(List): prime=[] sum=0 for num in List: c=0 for i in range(1,num): if(num%i==0): c=c+1 if(c==1): prime.append(num) print("prime Number List:",prime) sum=sum+num print("Addition of Prime numbers is:",sum)
[ "noreply@github.com" ]
suniljarad.noreply@github.com
bc7d8ecba2ea3d08d1b0d03ab497311104f63738
ff93e108a358a40d71b426bb9615587dfcab4d03
/Python_Basic/9_Class/class_basics_1.py
626a48139eb7a1d686767ec3a31ac348d0fbd5a3
[]
no_license
soumya9988/Python_Machine_Learning_Basics
074ff0e8e55fd925ca50e0f9b56dba76fc93d187
3711bc8e618123420985d01304e13051d9fb13e0
refs/heads/master
2020-03-31T14:31:49.217429
2019-11-16T21:55:54
2019-11-16T21:55:54
152,298,905
0
0
null
null
null
null
UTF-8
Python
false
false
3,299
py
class Menu: def __init__(self, name, items, start_time, end_time): self.name = name self.items = items self.start_time = start_time self.end_time = end_time def __repr__(self): return '{} menu available from {} to {}'.format(self.name, self.start_time, self.end_time) def calculate_bill(self, purchased_items): sum_of_items = 0 for item in purchased_items: if item in self.items: sum_of_items += self.items[item] return sum_of_items class Franchise: def __init__(self, address, menus): self.address = address self.menus = menus def __repr__(self): return self.address def available_menus(self, time): available = [] for menu in self.menus: if menu.start_time <= time and \ menu.end_time >= time: available.append(menu.name) return available class Business: def __init__(self, name, franchises): self.name = name self.franchises = franchises items = {'pancakes': 7.50, 'waffles': 9.00, 'burger': 11.00, 'home fries': 4.50, 'coffee': 1.50, 'espresso': 3.00, 'tea': 1.00, 'mimosa': 10.50, 'orange juice': 3.50} eb_items = {'salumeria plate': 8.00, 'salad and breadsticks (serves 2, no refills)': 14.00, 'pizza with quattro formaggi': 9.00, 'duck ragu': 17.50, 'mushroom ravioli (vegan)': 13.50, 'coffee': 1.50, 'espresso': 3.00, } d_items = {'crostini with eggplant caponata': 13.00, 'ceaser salad': 16.00, 'pizza with quattro formaggi': 11.00, 'duck ragu': 19.50, 'mushroom ravioli (vegan)': 13.50, 'coffee': 2.00, 'espresso': 3.00, } k_items = {'chicken nuggets': 6.50, 'fusilli with wild mushrooms': 12.00, 'apple juice': 3.00 } brunch = Menu('brunch', items, 11.00, 16.00) early_bird = Menu('early_bird', eb_items, 15.00, 18.00) dinner = Menu('dinner', d_items, 17.00, 23.00) kids = Menu('kids', k_items, 11.00, 21.00) print(brunch) print(early_bird) print(dinner) print(kids) purchased = ['pancakes', 'home fries', 'coffee'] cost = brunch.calculate_bill(purchased) print('Cost of brunch purchased: ', cost) cost_eb = early_bird.calculate_bill(['mushroom ravioli (vegan)', 'salumeria plate']) print('Cost of early bird purchased: ', cost_eb) flagship_store = Franchise("1232 West End Road", [brunch, dinner, kids, early_bird]) new_installment = Franchise("12 East Mulberry Street", [brunch, dinner, kids, early_bird]) print('You can choose from the following menus at 12 pm: ', new_installment.available_menus(12.00)) print('You can choose from the following menus at 5 pm: ', new_installment.available_menus(17.00)) arepas_menu = {'arepa pabellon': 7.00, 'pernil arepa': 8.50, 'guayanes arepa': 8.00, 'jamon arepa': 7.50} arepas_place = Franchise("189 Fitzgerald Avenue", arepas_menu) arepas_business = Business("Take a' Arepa", arepas_place) print(arepas_place)
[ "soumya.9988@gmail.com" ]
soumya.9988@gmail.com
f09496653dce43d8f46fed26f76d3ae2e791acb6
bf5fcb896d802ecc3f08133a5bfbe835912d9975
/songs/views.py
67efb2c1e4f0cebce30a3544e9269b7242e1e800
[]
no_license
DenisVakulenko/DDPS3
d85b699a848775ea5051ada7e844158abdd76b80
ca1b8efd8ef7496a9657018308e53362c8ead40a
refs/heads/master
2016-09-06T03:32:55.739410
2015-03-07T08:06:09
2015-03-07T08:06:09
31,305,945
0
0
null
null
null
null
UTF-8
Python
false
false
2,301
py
from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect, HttpResponse from django.template import RequestContext, loader from django.views.decorators.csrf import csrf_exempt import requests import json import urllib, urllib2 from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.views.decorators.csrf import csrf_exempt from models import Song @csrf_exempt def song(request): if request.method == 'POST': id = request.path.split('/')[2] s = Song.objects.get(id=id) s.name=request.REQUEST['name'] s.author=request.REQUEST['author'] s.save() return HttpResponse(s.json(), content_type="application/json") if request.method == 'GET': id = request.path.split('/')[2] s = Song.objects.get(id=id) return HttpResponse(s.json(), content_type="application/json") if request.method == 'DELETE': id = request.path.split('/')[2] s = Song.objects.get(id=id) s.delete() return HttpResponse("'ok' : 'ok'", content_type="application/json") @csrf_exempt def songs(request): if request.method == 'PUT': s = Song(name=request.REQUEST['name'], author=request.REQUEST['author']) s.save() return HttpResponse(s.json(), content_type="application/json") if request.method == 'GET': records = Song.objects.all() p = Paginator([rec.dict() for rec in records], 5) if 'page' in request.GET: page = request.GET.get('page') else: page = 1 try: records_json = p.page(page).object_list except PageNotAnInteger: page = 1 records_json = p.page(page).object_list except EmptyPage: page = p.num_pages records_json = p.page(page).object_list c = json.dumps(records_json) return HttpResponse('{ "page" : ' + str(page) + ', "pages" : ' + str(p.num_pages) + ', "content" : ' + c + '}', content_type="application/json") # Song(name='Kashmir', author='Led Zeppelin').save() # Song(name='Immigrant Song', author='Led Zeppelin').save() # Song(name='The End', author='Doors').save() # Song(name='God Gave Rock\'N\'Roll To You', author='Kiss').save()
[ "vakulenko.denis@alphaopen.com" ]
vakulenko.denis@alphaopen.com
d48d5b7aba752ceaf1f1afc65a3f1a8cea199a88
4ebbaf7ebd7bb00711750a2a76c2fa80c21771be
/tess_tests.py
e487932775939928b3372adb822e62bde7b6ccf2
[ "MIT" ]
permissive
bslate/tess
16850aac949a6d89cba72e2afd1c9aad896f0d49
c90e6a203312e4b1f7174899245cd9a6e01290e6
refs/heads/master
2021-05-29T06:25:01.028320
2015-05-15T21:29:43
2015-05-15T21:29:43
35,632,987
2
1
null
null
null
null
UTF-8
Python
false
false
2,299
py
#!/usr/bin/env python from tess import * class Square (Shape): def __init__(self): super(Square, self).__init__() a = (10, 10, 0) b = (20, 10, 0) c = (20, 20, 0) d = (10, 20, 0) self.paths.append([a, b, c, d]) # append a list class Concave (Shape): def __init__(self): super(Concave, self).__init__() a = (20, 15, 0) b = (20, 5, 0) c = (10, 25, 0) d = (30, 25, 0) self.paths.append([a, c, b, d]) # note order is not alphabetical class TetrisT (Shape): def __init__(self): super(TetrisT, self).__init__() # the first point is bottom left and goes clockwise from there self.paths.append([ (-225.396225, -36.19598, 0), (-229.254745, -16.5716381, 0), (-209.6308, -12.7113495, 0), (-213.489441, 6.912962, 0), (-193.863342, 10.762394, 0), (-190.0048, -8.861887, 0), (-170.38089, -5.00150061, 0), (-166.522415, -24.62577, 0) ]) class SquareWithTriangleHoles(Shape): def __init__(self): super(SquareWithTriangleHoles, self).__init__() # square is abcd a = (10, 10, 0) b = (10, 50, 0) c = (60, 50, 0) d = (60, 10, 0) self.paths.append([a, b, c, d]) # upward pointing triangle is efg e = (20, 30, 0) f = (25, 40, 0) g = (30, 30, 0) self.paths.append([e, f, g]) # downward pointing triangle is hij h = (40, 30, 0) i = (45, 20, 0) j = (50, 30, 0) self.paths.append([h, i, j]) def main(): zt = ZoteTess() shape = Square() response = zt.triangulate(shape) print_triangles("Square", response) shape = Concave() response = zt.triangulate(shape) print_triangles("Concave", response) shape = TetrisT() response = zt.triangulate(shape) print_triangles("TetrisT", response) shape = SquareWithTriangleHoles() response = zt.triangulate(shape) print_triangles("SquareWithTriangleHoles", response) shape = DiskFile("test_data.dat") response = zt.triangulate(shape) print_triangles("Disk file (test_data.dat)", response) if __name__ == "__main__": main()
[ "gabe@blankslatesystems.com" ]
gabe@blankslatesystems.com
2e14ed70dade5c806292ff6f5c16084a0bf063fe
dfdde7150bdbca59f6447788262a70550094128d
/mpttassesment/urls.py
7b6e39adcd7d97694ba04483087aa8f3e80cb9f7
[]
no_license
Swaav/mptt
43b71b7ff7adde9e483af8119ee38a9b5f81e933
bad403e22f28e8651ff68852984b5fd33169904c
refs/heads/master
2021-09-23T12:22:51.476416
2019-12-19T22:05:15
2019-12-19T22:05:15
229,145,752
0
0
null
2021-09-22T18:23:13
2019-12-19T22:02:50
Python
UTF-8
Python
false
false
2,044
py
"""mpttassesment URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/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, re_path from mptt.admin import DraggableMPTTAdmin from mpttassesment.models import MyFile from mpttassesment.views import show_myfile # admin.site.register(MyFile) class CategoryAdmin(DraggableMPTTAdmin): mptt_indent_field = 'name' list_display = ('tree_actions', 'indented_title', 'related_products_count', 'related_products_cumulative_count') list_display_links = ('indented_title') def get_queryset(self, request): qs = super().get_queryset(request) qs = MyFile.objects.add_related_count( qs, 'category', 'products_cumulative_count', cumulative=True ) qs = MyFile.objects.add_related_count( qs, 'categories', 'products_count', cumulative=False ) return qs def related_products_count(self, instance): return instance.products_count related_products_count.short_description = 'Related files (for this specific folder)' def related_products_cumulative_count(self, instance): return instance.products_cumulative_count related_products_cumulative_count.short_description = 'Related files (in tree)' urlpatterns = [ path('admin/', admin.site.urls), re_path('', show_myfile) ]
[ "swavae00@gmail.com" ]
swavae00@gmail.com
4d4500f358976f5d0376f344548791023fd93706
a2a1dbc39e991035b9707f6ae201c84d882adccb
/google_books/books.py
3feeb54e0a760900e0d9f94788c31c35b4a7a0d4
[]
no_license
Ingrid-Nataly-Cruz-Espinosa/Aplicaciones_web_orientadas_a_servicios
7ebf32dcf61e447f340fb5ba0cefad7640ce57e9
66cb7101ea9d8f4999ce53465a9d33081f6967e9
refs/heads/main
2023-04-05T19:14:17.045103
2021-03-21T02:24:05
2021-03-21T02:24:05
334,285,124
0
0
null
null
null
null
UTF-8
Python
false
false
447
py
import requests import json result = requests.get("https://www.googleapis.com/books/v1/volumes?q=sinsajo") libro = result.json() items = libro["items"] encoded = json.dumps(items) decoded = json.loads(encoded) print(decoded[0]["volumeInfo"]["authors"]) autor=str(decoded[0]["volumeInfo"]["authors"]) print(autor) autor.replace("[","") autor.replace("]","") print(decoded[0]["volumeInfo"]["imageLinks"]["smallThumbnail"]) print (result.text)
[ "1719110501@utectulancingo.edu.mx" ]
1719110501@utectulancingo.edu.mx
d5865a32ff288ba1cabfafe902940e806dea3a43
1f26a00f7063923ae65f51fe97d27288382a4899
/sudokurace/server/application.py
5adefc12b26b855a8b1cee96df16abec9ac03019
[]
no_license
ahoward1024/sudoku-race
e6a05bfc8a5d1bf5a9f382873ea07a19bb99abba
f63d984d9e9862c04b002ea0ac595e58d134a128
refs/heads/master
2021-06-05T02:17:32.711271
2020-12-21T23:32:57
2020-12-21T23:32:57
135,497,749
0
0
null
null
null
null
UTF-8
Python
false
false
1,446
py
from http import HTTPStatus from starlette.applications import Starlette from starlette.responses import JSONResponse, PlainTextResponse from starlette.routing import Route import pkg_resources class Application: name = "default" conn = None def __init__(self, name, conn) -> None: super().__init__() self.name = name if not None else name self.version = pkg_resources.get_distribution("sudokurace").version self.conn = conn def __get_name(self): async def name_closure(_): return JSONResponse({"name": self.name}) return name_closure def __get_version(self): async def closure(_): return PlainTextResponse(self.version) return closure def __get_healthz(self): async def closure(_): try: with self.conn.cursor() as cur: cur.execute("SELECT 1;") return PlainTextResponse("ok") except: return PlainTextResponse( "not ok", status_code=HTTPStatus.SERVICE_UNAVAILABLE ) return closure def collect_routes(self): return [ Route("/name", self.__get_name()), Route("/version", self.__get_version()), Route("/healthz", self.__get_healthz()), ] def server(self): return Starlette(debug=True, routes=self.collect_routes())
[ "AaronBatilo@gmail.com" ]
AaronBatilo@gmail.com
8edf947ca5ec01d921df981f6c58b0fdef80b460
06a2b13e45c9bd7d8f428b590a45634aaac3566e
/movies_admin/members/managers.py
218ad670118d7962d48649ce5b9ff31392566428
[]
no_license
vromanuk/Admin_panel_sprint_2
b930c742f0b1f14c5c7a1b58b93984593f8326ca
777d62c5366525646e46c1017be286a148f27df3
refs/heads/main
2023-06-05T01:13:58.135448
2021-06-24T19:02:37
2021-06-24T19:02:37
376,740,305
0
0
null
null
null
null
UTF-8
Python
false
false
749
py
from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, password=None, **kwargs): if not email: raise ValueError("The email address must be set") user = self.model( email=email, is_staff=False, is_active=True, is_superuser=False, **kwargs, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password, **kwargs): u = self.create_user(email, password, **kwargs) u.is_staff = True u.is_active = True u.is_superuser = True u.save(using=self._db) return u
[ "v.romaniuk@orderry.com" ]
v.romaniuk@orderry.com
9efe909c265f82499d2be6a904c8fd902fed2bcb
19236d9e966cf5bafbe5479d613a175211e1dd37
/cohesity_management_sdk/models/google_cloud_credentials.py
7e3886d7a27110ac94aca21b0b5ecde8f814ff97
[ "MIT" ]
permissive
hemanshu-cohesity/management-sdk-python
236c44fbd9604809027f8ddd0ae6c36e4e727615
07c5adee58810979780679065250d82b4b2cdaab
refs/heads/master
2020-04-29T23:22:08.909550
2019-04-10T02:42:16
2019-04-10T02:42:16
176,474,523
0
0
NOASSERTION
2019-03-19T09:27:14
2019-03-19T09:27:12
null
UTF-8
Python
false
false
3,125
py
# -*- coding: utf-8 -*- # Copyright 2019 Cohesity Inc. class GoogleCloudCredentials(object): """Implementation of the 'Google Cloud Credentials.' model. Specifies the cloud credentials to connect to a Google service account. Attributes: client_email_address (string): Specifies the client email address used to access Google Cloud Storage. client_private_key (string): Specifies the private key used to access Google Cloud Storage that is generated when the service account is created. project_id (string): Specifies the project id of an existing Google Cloud project to store objects. tier_type (TierType2Enum): Specifies the storage class of GCP. GoogleTierType specifies the storage class for Google. 'kGoogleStandard' indicates a tier type of Google properties. 'kGoogleNearline' indicates a tier type of Google properties that is not accessed frequently. 'kGoogleColdline' indicates a tier type of Google properties that is rarely accessed. 'kGoogleRegional' indicates a tier type of Google properties that stores frequently accessed data in the same region. 'kGoogleMultiRegional' indicates a tier type of Google properties that is frequently accessed ("hot" objects) around the world. """ # Create a mapping from Model property names to API property names _names = { "client_email_address":'clientEmailAddress', "client_private_key":'clientPrivateKey', "project_id":'projectId', "tier_type":'tierType' } def __init__(self, client_email_address=None, client_private_key=None, project_id=None, tier_type=None): """Constructor for the GoogleCloudCredentials class""" # Initialize members of the class self.client_email_address = client_email_address self.client_private_key = client_private_key self.project_id = project_id self.tier_type = tier_type @classmethod def from_dictionary(cls, dictionary): """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class. """ if dictionary is None: return None # Extract variables from the dictionary client_email_address = dictionary.get('clientEmailAddress') client_private_key = dictionary.get('clientPrivateKey') project_id = dictionary.get('projectId') tier_type = dictionary.get('tierType') # Return an object of this model return cls(client_email_address, client_private_key, project_id, tier_type)
[ "ashish@cohesity.com" ]
ashish@cohesity.com
7932c0ccbe52f6dff8961451ec9518ed9b1d0ba0
c0d5b7f8e48a26c6ddc63c76c43ab5b397c00028
/piccolo/apps/user/piccolo_app.py
c01ee635f12d335e6a45650fda81dbfe9fab4925
[ "MIT" ]
permissive
aminalaee/piccolo
f6c5e5e1c128568f7ccb9ad1dfb4746acedae262
af8d2d45294dcd84f4f9b6028752aa45b699ec15
refs/heads/master
2023-07-14T09:44:04.160116
2021-07-11T22:56:27
2021-07-11T22:56:27
386,398,401
0
0
MIT
2021-07-15T19:32:50
2021-07-15T19:08:17
null
UTF-8
Python
false
false
729
py
import os from piccolo.conf.apps import AppConfig, Command from .commands.change_password import change_password from .commands.change_permissions import change_permissions from .commands.create import create from .tables import BaseUser CURRENT_DIRECTORY = os.path.dirname(os.path.abspath(__file__)) APP_CONFIG = AppConfig( app_name="user", migrations_folder_path=os.path.join( CURRENT_DIRECTORY, "piccolo_migrations" ), table_classes=[BaseUser], migration_dependencies=[], commands=[ Command(callable=create, aliases=["new"]), Command(callable=change_password, aliases=["password", "pass"]), Command(callable=change_permissions, aliases=["perm", "perms"]), ], )
[ "dan@dantownsend.co.uk" ]
dan@dantownsend.co.uk
db2cdc19635349844c5e850f4b577b0118d4ae0e
29a4c1e436bc90deaaf7711e468154597fc379b7
/modules/trigonometric/doc/fast_sind.py
46fee4678b0eeccbe7f58327e5d8b321d06b825f
[ "BSL-1.0" ]
permissive
brycelelbach/nt2
31bdde2338ebcaa24bb76f542bd0778a620f8e7c
73d7e8dd390fa4c8d251c6451acdae65def70e0b
refs/heads/master
2021-01-17T12:41:35.021457
2011-04-03T17:37:15
2011-04-03T17:37:15
1,263,345
1
0
null
null
null
null
UTF-8
Python
false
false
2,873
py
[ ## this file was manually modified by jt { 'functor' : { 'arity' : '1', 'call_types' : [], 'ret_arity' : '0', 'rturn' : { 'default' : 'typename boost::result_of<nt2::meta::floating(T)>::type', }, 'simd_types' : ['real_convert_'], 'special' : ['trigonometric'], 'type_defs' : [], 'types' : ['real_', 'unsigned_int_', 'signed_int_'], }, 'info' : 'manually modified', 'unit' : { 'global_header' : { 'first_stamp' : 'created by jt the 11/02/2011', 'included' : ['#include <nt2/toolbox/trigonometric/include/constants.hpp>', '#include <nt2/include/functions/sind.hpp>'], 'notes' : [], 'stamp' : 'modified by jt the 11/02/2011', }, 'ranges' : { 'default' : [['T(-45)', 'T(45)']], 'unsigned_int_' : [['0', 'T(45)']], }, 'specific_values' : { 'default' : { 'nt2::Zero<T>()' : {'result' : 'nt2::Zero<r_t>()','ulp_thresh' : '0.5',}, 'nt2::_45<T>()' : {'result' : 'nt2::Sqrt_2o_2<r_t>()','ulp_thresh' : '0.5',}, }, 'real_' : { '-nt2::_180<T>()' : {'result' : 'nt2::Nan<r_t>()','ulp_thresh' : '0.5',}, '-nt2::_45<T>()' : {'result' : '-nt2::Sqrt_2o_2<r_t>()','ulp_thresh' : '0.5',}, '-nt2::_90<T>()' : {'result' : 'nt2::Nan<r_t>()','ulp_thresh' : '0.5',}, 'nt2::Inf<T>()' : {'result' : 'nt2::Nan<r_t>()','ulp_thresh' : '0.5',}, 'nt2::Minf<T>()' : {'result' : 'nt2::Nan<r_t>()','ulp_thresh' : '0.5',}, 'nt2::Nan<T>()' : {'result' : 'nt2::Nan<r_t>()','ulp_thresh' : '0.5',}, 'nt2::Zero<T>()' : {'result' : 'nt2::Zero<r_t>()','ulp_thresh' : '0.5',}, 'nt2::_180<T>()' : {'result' : 'nt2::Nan<r_t>()','ulp_thresh' : '0.5',}, 'nt2::_45<T>()' : {'result' : 'nt2::Sqrt_2o_2<r_t>()','ulp_thresh' : '0.5',}, 'nt2::_90<T>()' : {'result' : 'nt2::Nan<r_t>()','ulp_thresh' : '0.5',}, }, 'signed_int_' : { '-nt2::_45<T>()' : {'result' : '-nt2::Sqrt_2o_2<r_t>()','ulp_thresh' : '0.5',}, 'nt2::Zero<T>()' : {'result' : 'nt2::Zero<r_t>()','ulp_thresh' : '0.5',}, 'nt2::_45<T>()' : {'result' : 'nt2::Sqrt_2o_2<r_t>()','ulp_thresh' : '0.5',}, }, }, 'verif_test' : { 'property_call' : { 'real_' : ['nt2::fast_sind(a0)'], }, 'property_value' : { 'real_' : ['nt2::sind(a0)'], }, 'ulp_thresh' : { 'real_' : ['1.0'], }, }, }, }, ]
[ "jtlapreste@gmail.com" ]
jtlapreste@gmail.com
29f4a0db13b5b070a90de41edc0dda150a27d9a4
14eb90d70f9371f95cb96620a5f67bb1791ca172
/api/migrations/0015_auto_20170903_1006.py
72142eb9a1631de464e2098d25c5913319501409
[]
no_license
christopherswenson/pool-shenanigans
b16cd26e3fc190e946d7c501e596b5b21bb73e21
2f9339d213fcd82e29e23beb9038ad326a9f4904
refs/heads/master
2020-12-30T09:15:07.783685
2017-09-03T17:51:51
2017-09-03T17:51:51
100,398,819
1
0
null
2017-09-03T17:51:52
2017-08-15T16:49:20
CSS
UTF-8
Python
false
false
1,041
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-03 17:06 from __future__ import unicode_literals import api.models from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('api', '0014_table_tablemember'), ] operations = [ migrations.RemoveField( model_name='player', name='guest_code', ), migrations.AddField( model_name='invitation', name='is_guest_code', field=models.BooleanField(default=False), ), migrations.AddField( model_name='player', name='guest_invitation', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='api.Invitation'), ), migrations.AlterField( model_name='invitation', name='code', field=models.CharField(default=api.models.generate_invitation_code, max_length=255), ), ]
[ "christopher@looker.com" ]
christopher@looker.com
b41c3c42ad4d526ed713b181a1ef397ed599bc9c
3582180423aff9a8dad78b98206fcea4469e67b7
/PYTHON/Stack.py
484f885ce5100181013cdf5c582de1ce2453ca87
[ "MIT" ]
permissive
Janitham97/open-source-contribution
92376b77261201f960e392762c663374a6053bb7
3aefc9ced878e698cf3176f4ff917b04089fe8e0
refs/heads/main
2023-09-02T17:01:07.126482
2021-10-16T16:44:40
2021-10-16T16:44:40
412,547,680
0
0
null
2021-10-01T16:49:50
2021-10-01T16:49:49
null
UTF-8
Python
false
false
560
py
from sys import maxsize def createStack(): stack = [] return stack def isEmpty(stack): return len(stack) == 0 def push(stack, item): stack.append(item) print(item + " pushed to stack ") def pop(stack): if (isEmpty(stack)): return str(-maxsize -1) return stack.pop() def peek(stack): if (isEmpty(stack)): return str(-maxsize -1) return stack[len(stack) - 1] stack = createStack() push(stack, str(500)) push(stack, str(120)) push(stack, str(2)) print(pop(stack) + " popped from stack")
[ "janitha.missaka@gmail.com" ]
janitha.missaka@gmail.com
36552e1de95599c7eb795167abd599a4c38fbd7a
2a3741cd59de9f4f44634bb54141d1c4d7b9e591
/node_modules/gulp-sass/node_modules/node-sass/build/config.gypi
0fb0c44744c90e08045b2525be66bae0da22316c
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
paulnagle/NA-IRELAND-IONIC
7bc4075b54133d2d1e44e280e84b3129e635ff4f
1699fc0f5333f4aa1f6ec754973651530d523da7
refs/heads/master
2021-01-21T04:50:55.148102
2016-06-08T14:02:06
2016-06-08T14:02:06
50,344,195
1
0
null
null
null
null
UTF-8
Python
false
false
4,116
gypi
# Do not edit. File was generated by node-gyp's "configure" step { "target_defaults": { "cflags": [], "default_configuration": "Release", "defines": [], "include_dirs": [], "libraries": [] }, "variables": { "asan": 0, "host_arch": "x64", "icu_data_file": "icudt57l.dat", "icu_data_in": "../../deps/icu-small/source/data/in/icudt57l.dat", "icu_endianness": "l", "icu_gyp_path": "tools/icu/icu-generic.gyp", "icu_locales": "en,root", "icu_path": "deps/icu-small", "icu_small": "true", "icu_ver_major": "57", "llvm_version": 0, "node_byteorder": "little", "node_enable_v8_vtunejit": "false", "node_install_npm": "false", "node_no_browser_globals": "false", "node_prefix": "/usr/local/Cellar/node/6.2.0", "node_release_urlbase": "", "node_shared_cares": "false", "node_shared_http_parser": "false", "node_shared_libuv": "false", "node_shared_openssl": "false", "node_shared_zlib": "false", "node_tag": "", "node_use_dtrace": "true", "node_use_etw": "false", "node_use_lttng": "false", "node_use_openssl": "true", "node_use_perfctr": "false", "openssl_fips": "", "openssl_no_asm": 0, "target_arch": "x64", "uv_parent_path": "/deps/uv/", "uv_use_dtrace": "true", "v8_enable_gdbjit": 0, "v8_enable_i18n_support": 1, "v8_no_strict_aliasing": 1, "v8_optimized_debug": 0, "v8_random_seed": 0, "v8_use_snapshot": "true", "want_separate_host_toolset": 0, "xcode_version": "7.3", "nodedir": "/Users/paulnagle/.node-gyp/6.2.0", "copy_dev_lib": "true", "standalone_static_library": 1, "libsass_ext": "", "libsass_cflags": "", "libsass_ldflags": "", "libsass_library": "", "save_dev": "", "legacy_bundling": "", "dry_run": "", "viewer": "man", "only": "", "browser": "", "also": "", "rollback": "true", "usage": "", "globalignorefile": "/usr/local/etc/npmignore", "shell": "/bin/bash", "maxsockets": "50", "init_author_url": "", "shrinkwrap": "true", "parseable": "", "init_license": "ISC", "if_present": "", "sign_git_tag": "", "init_author_email": "", "cache_max": "Infinity", "long": "", "local_address": "", "git_tag_version": "true", "cert": "", "registry": "https://registry.npmjs.org/", "npat": "", "fetch_retries": "2", "versions": "", "message": "%s", "key": "", "globalconfig": "/usr/local/etc/npmrc", "always_auth": "", "global_style": "", "cache_lock_retries": "10", "cafile": "", "heading": "npm", "proprietary_attribs": "true", "fetch_retry_mintimeout": "10000", "json": "", "access": "", "https_proxy": "", "engine_strict": "", "description": "true", "userconfig": "/Users/paulnagle/.npmrc", "init_module": "/Users/paulnagle/.npm-init.js", "user": "501", "node_version": "6.2.0", "save": "", "editor": "vi", "tag": "latest", "progress": "true", "global": "", "optional": "true", "force": "", "bin_links": "true", "searchopts": "", "depth": "Infinity", "searchsort": "name", "rebuild_bundle": "true", "unicode": "true", "fetch_retry_maxtimeout": "60000", "tag_version_prefix": "v", "strict_ssl": "true", "save_prefix": "^", "ca": "", "save_exact": "", "group": "20", "fetch_retry_factor": "10", "dev": "", "version": "", "cache_lock_stale": "60000", "cache_min": "10", "searchexclude": "", "cache": "/Users/paulnagle/.npm", "color": "true", "save_optional": "", "ignore_scripts": "", "user_agent": "npm/3.8.9 node/v6.2.0 darwin x64", "cache_lock_wait": "10000", "production": "", "save_bundle": "", "umask": "0022", "init_version": "1.0.0", "scope": "", "init_author_name": "", "git": "git", "unsafe_perm": "true", "tmp": "/var/folders/rs/1d66p3b503l2r73d43z0qsqh0000gn/T", "onload_script": "", "link": "", "prefix": "/usr/local" } }
[ "paulnagle@gmail.com" ]
paulnagle@gmail.com
3579af76ad1cbb9f2c1c330b7209bb7ce0bc7f71
f760e65fe94b7f5f6f11cb5826ed53e3dde069d7
/forcePlates/MayaIntegration/tests/unit/threads/test_persistence_sync_thread.py
e4cfdd7cf881efc04a58ad64ac104771fa4c1535
[ "MIT" ]
permissive
MontyThibault/centre-of-mass-awareness
fc9ad59dfe15572f1f4668ca3e5d6095dda09aec
58778f148e65749e1dfc443043e9fc054ca3ff4d
refs/heads/master
2020-07-20T18:56:42.503050
2016-11-19T17:21:06
2016-11-19T17:21:06
67,234,077
0
0
null
null
null
null
UTF-8
Python
false
false
747
py
## Centre of Pressure Uncertainty for Virtual Character Control ## McGill Computer Graphics Lab ## ## Released under the MIT license. This code is free to be modified ## and distributed. ## ## Author: Monty Thibault, montythibault@gmail.com ## Last Updated: Sep 02, 2016 ## ------------------------------------------------------------------------ from plugin.threads.persistence_sync_thread import PersistenceSyncThread as PST import os import pytest @pytest.yield_fixture def teardown_pickle_files(): yield os.remove('.test.pickle') def test_persistence_sync_thread_without_starting(teardown_pickle_files): x = PST('.test.pickle') x.objs['abc'] = 123 x.objs.close() y = PST('.test.pickle') assert y.objs['abc'] == 123
[ "montythibault@gmail.com" ]
montythibault@gmail.com
ea1a45ac18e6c14f36edd844e4effdd6a0dfaa7a
9cc4ea509d55d2842bfe269785148c8c23b8a52d
/golf_app/migrations/0008_auto_20200530_2332.py
ef7c5d995aff288132bddc1e980bf1f822c8ad70
[]
no_license
4rc4ngel/golf_society
25baa35e03e3720fc4121ed3f4e86a5ec6807ee4
cf5cd29f63af3b478196c6b863301f67b8e9c8da
refs/heads/master
2023-05-13T14:13:00.933077
2020-05-31T22:44:55
2020-05-31T22:44:55
268,325,473
0
0
null
2021-06-10T22:58:45
2020-05-31T17:05:31
Python
UTF-8
Python
false
false
846
py
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2020-05-30 22:32 from __future__ import unicode_literals import datetime from django.conf import settings from django.db import migrations, models import django.db.models.deletion from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('golf_app', '0007_auto_20200530_2318'), ] operations = [ migrations.AlterField( model_name='post', name='author', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), migrations.AlterField( model_name='post', name='date_created', field=models.DateTimeField(default=datetime.datetime(2020, 5, 30, 22, 32, 13, 845031, tzinfo=utc)), ), ]
[ "martynstanley@me.com" ]
martynstanley@me.com
eae6fd1f2a5e6597b58d1de81269f9f69bbd904f
db2123520c2c979e0560965d009ac4f378b55990
/vic-builder/geocode.py
c77a25c5ea9b635569b54453b6be48bc4526d677
[]
no_license
jimsteel/GovHack-exdstc
55b2b3cf4a78b71e885285c7dad77222ed6e1942
39deaa13c48f9135200cf84f0d6479a32f42ab3f
refs/heads/master
2020-05-19T09:27:25.631514
2014-07-13T07:03:46
2014-07-13T07:03:46
null
0
0
null
null
null
null
UTF-8
Python
false
false
282
py
#!/usr/bin/python # # Gets latitude & longitude for an address # import geopy from geopy.geocoders import GoogleV3 geolocator = GoogleV3() address, (latitude, longitude) = geolocator.geocode("475 BEAVERS ROAD , NORTHCOTE 3070") print address print latitude print longitude
[ "michael@josephmark.com.au" ]
michael@josephmark.com.au
219b4971707dca05aae2f356353fce5dd07b8626
ef7e23f513ec5022cb524ed74690ea89530a0e45
/src/data_prep/read/bam_to_hap/FastaFile.py
b9c3efd7d88141db5388642ca9c6b6d4b7b8ccf5
[]
no_license
rivas-lab/nanopore
5a6d54c5f850b494fb397c9cbdfe1f962590654f
0502cd177b038471c0946cb0255e4e867f8c82f1
refs/heads/master
2021-03-24T09:40:08.268807
2017-08-22T19:03:44
2017-08-22T19:03:44
70,011,685
0
0
null
null
null
null
UTF-8
Python
false
false
729
py
import pysam class FastaFile: """A class to load and manage collection of FASTA files """ def __init__(self, filename, fast_ext='fa'): self.filename = filename self.fast_ext = fast_ext self.seq = {} def load(self, chromosome): self.seq[self.uniq_key(chromosome)] = \ pysam.FastaFile('{}{}.{}'.format(self.filename, chromosome, self.fast_ext)) def uniq_key(self, chromosome): return str(chromosome) def is_loaded(self, chromosome): return self.uniq_key(chromosome) in self.seq def get_seq(self, chromosome): if not self.is_loaded(chromosome): self.load(chromosome) return self.seq[self.uniq_key(chromosome)]
[ "ytanigaw@stanford.edu" ]
ytanigaw@stanford.edu
cd1f5aa15aa51608ab94f358ef5e2b37ada43441
036563dcc730d6a0904da8be02f22a05caf79006
/contrib/bitrpc/bitrpc.py
dab123e2d256dae0968369c65e1cb0e7aff1e6df
[ "MIT" ]
permissive
izzy-developer/core
00155a1dec133b62a3f6c850b1c271bb456267a3
32b83537a255aeef50a64252ea001c99c7e69a01
refs/heads/main
2023-05-13T22:23:12.513181
2021-05-31T02:43:07
2021-05-31T02:43:07
372,362,743
0
1
null
null
null
null
UTF-8
Python
false
false
9,393
py
from jsonrpc import ServiceProxy import sys import string import getpass # ===== BEGIN USER SETTINGS ===== # if you do not set these you will be prompted for a password for every command rpcuser = "" rpcpass = "" # ====== END USER SETTINGS ====== if rpcpass == "": access = ServiceProxy("http://127.0.0.1:31473") else: access = ServiceProxy("http://"+rpcuser+":"+rpcpass+"@127.0.0.1:31473") cmd = sys.argv[1].lower() if cmd == "backupwallet": try: path = raw_input("Enter destination path/filename: ") print access.backupwallet(path) except: print "\n---An error occurred---\n" elif cmd == "encryptwallet": try: pwd = getpass.getpass(prompt="Enter passphrase: ") pwd2 = getpass.getpass(prompt="Repeat passphrase: ") if pwd == pwd2: access.encryptwallet(pwd) print "\n---Wallet encrypted. Server stopping, restart to run with encrypted wallet---\n" else: print "\n---Passphrases do not match---\n" except: print "\n---An error occurred---\n" elif cmd == "getaccount": try: addr = raw_input("Enter a Bitcoin address: ") print access.getaccount(addr) except: print "\n---An error occurred---\n" elif cmd == "getaccountaddress": try: acct = raw_input("Enter an account name: ") print access.getaccountaddress(acct) except: print "\n---An error occurred---\n" elif cmd == "getaddressesbyaccount": try: acct = raw_input("Enter an account name: ") print access.getaddressesbyaccount(acct) except: print "\n---An error occurred---\n" elif cmd == "getbalance": try: acct = raw_input("Enter an account (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getbalance(acct, mc) except: print access.getbalance() except: print "\n---An error occurred---\n" elif cmd == "getblockbycount": try: height = raw_input("Height: ") print access.getblockbycount(height) except: print "\n---An error occurred---\n" elif cmd == "getblockcount": try: print access.getblockcount() except: print "\n---An error occurred---\n" elif cmd == "getblocknumber": try: print access.getblocknumber() except: print "\n---An error occurred---\n" elif cmd == "getconnectioncount": try: print access.getconnectioncount() except: print "\n---An error occurred---\n" elif cmd == "getdifficulty": try: print access.getdifficulty() except: print "\n---An error occurred---\n" elif cmd == "getinfo": try: print access.getinfo() except: print "\n---An error occurred---\n" elif cmd == "getnewaddress": try: acct = raw_input("Enter an account name: ") try: print access.getnewaddress(acct) except: print access.getnewaddress() except: print "\n---An error occurred---\n" elif cmd == "getreceivedbyaccount": try: acct = raw_input("Enter an account (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getreceivedbyaccount(acct, mc) except: print access.getreceivedbyaccount() except: print "\n---An error occurred---\n" elif cmd == "getreceivedbyaddress": try: addr = raw_input("Enter a Bitcoin address (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getreceivedbyaddress(addr, mc) except: print access.getreceivedbyaddress() except: print "\n---An error occurred---\n" elif cmd == "gettransaction": try: txid = raw_input("Enter a transaction ID: ") print access.gettransaction(txid) except: print "\n---An error occurred---\n" elif cmd == "getwork": try: data = raw_input("Data (optional): ") try: print access.gettransaction(data) except: print access.gettransaction() except: print "\n---An error occurred---\n" elif cmd == "help": try: cmd = raw_input("Command (optional): ") try: print access.help(cmd) except: print access.help() except: print "\n---An error occurred---\n" elif cmd == "listaccounts": try: mc = raw_input("Minimum confirmations (optional): ") try: print access.listaccounts(mc) except: print access.listaccounts() except: print "\n---An error occurred---\n" elif cmd == "listreceivedbyaccount": try: mc = raw_input("Minimum confirmations (optional): ") incemp = raw_input("Include empty? (true/false, optional): ") try: print access.listreceivedbyaccount(mc, incemp) except: print access.listreceivedbyaccount() except: print "\n---An error occurred---\n" elif cmd == "listreceivedbyaddress": try: mc = raw_input("Minimum confirmations (optional): ") incemp = raw_input("Include empty? (true/false, optional): ") try: print access.listreceivedbyaddress(mc, incemp) except: print access.listreceivedbyaddress() except: print "\n---An error occurred---\n" elif cmd == "listtransactions": try: acct = raw_input("Account (optional): ") count = raw_input("Number of transactions (optional): ") frm = raw_input("Skip (optional):") try: print access.listtransactions(acct, count, frm) except: print access.listtransactions() except: print "\n---An error occurred---\n" elif cmd == "move": try: frm = raw_input("From: ") to = raw_input("To: ") amt = raw_input("Amount:") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") try: print access.move(frm, to, amt, mc, comment) except: print access.move(frm, to, amt) except: print "\n---An error occurred---\n" elif cmd == "sendfrom": try: frm = raw_input("From: ") to = raw_input("To: ") amt = raw_input("Amount:") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") commentto = raw_input("Comment-to (optional): ") try: print access.sendfrom(frm, to, amt, mc, comment, commentto) except: print access.sendfrom(frm, to, amt) except: print "\n---An error occurred---\n" elif cmd == "sendmany": try: frm = raw_input("From: ") to = raw_input("To (in format address1:amount1,address2:amount2,...): ") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") try: print access.sendmany(frm,to,mc,comment) except: print access.sendmany(frm,to) except: print "\n---An error occurred---\n" elif cmd == "sendtoaddress": try: to = raw_input("To (in format address1:amount1,address2:amount2,...): ") amt = raw_input("Amount:") comment = raw_input("Comment (optional): ") commentto = raw_input("Comment-to (optional): ") try: print access.sendtoaddress(to,amt,comment,commentto) except: print access.sendtoaddress(to,amt) except: print "\n---An error occurred---\n" elif cmd == "setaccount": try: addr = raw_input("Address: ") acct = raw_input("Account:") print access.setaccount(addr,acct) except: print "\n---An error occurred---\n" elif cmd == "setgenerate": try: gen= raw_input("Generate? (true/false): ") cpus = raw_input("Max processors/cores (-1 for unlimited, optional):") try: print access.setgenerate(gen, cpus) except: print access.setgenerate(gen) except: print "\n---An error occurred---\n" elif cmd == "settxfee": try: amt = raw_input("Amount:") print access.settxfee(amt) except: print "\n---An error occurred---\n" elif cmd == "stop": try: print access.stop() except: print "\n---An error occurred---\n" elif cmd == "validateaddress": try: addr = raw_input("Address: ") print access.validateaddress(addr) except: print "\n---An error occurred---\n" elif cmd == "walletpassphrase": try: pwd = getpass.getpass(prompt="Enter wallet passphrase: ") access.walletpassphrase(pwd, 60) print "\n---Wallet unlocked---\n" except: print "\n---An error occurred---\n" elif cmd == "walletpassphrasechange": try: pwd = getpass.getpass(prompt="Enter old wallet passphrase: ") pwd2 = getpass.getpass(prompt="Enter new wallet passphrase: ") access.walletpassphrasechange(pwd, pwd2) print print "\n---Passphrase changed---\n" except: print print "\n---An error occurred---\n" print else: print "Command not found or not supported"
[ "ranzdevelopment@gmail.com" ]
ranzdevelopment@gmail.com
d48e462220ed36219cb1f149b0329c73aa27a5be
8b4f0404966794961fb9c67f68627637df684874
/DAG.py
c90951668f7006de7fd8715f0e4d664229e85de8
[]
no_license
lih426/LCA-Python
7794a39c4d59176eabc700dd200fbe2b13f7ac47
47958b4687aa15bdeb9018656de2b322140e7857
refs/heads/main
2023-08-27T15:05:24.107296
2021-11-05T06:05:41
2021-11-05T06:05:41
417,229,053
1
0
null
2021-11-05T06:05:42
2021-10-14T17:47:13
Python
UTF-8
Python
false
false
3,510
py
import sys class DAG(object): # creates empty set for nodes for the DAG def __init__(self): self.createGraph() # prints DAG def printDAG(self, graph): print(graph) # prints the nodes from a list in DAG def printNodeList(self, list): print(list) # creates empty dictionary def createGraph(self): self.graph = {} # add node to DAG (set) def addNode(self, node, graph=None): if not graph: graph = self.graph if node in graph: return False graph[node] = [] # add edge in the DAG def addEdge(self, parent, child, graph=None): if not graph: graph = self.graph if parent in graph and child in graph: graph[parent].append(child) else: print("nodes do not exist") # Depth First Search def DFS(self, node_list, graph, node): if not graph[node]: return True else: for child in graph[node]: if child not in node_list: node_list.append(child) if not self.DFS(node_list, graph, child): return self.DFS(node_list, graph, child) node_list.remove(child) else: return False return True # wrapper for Depth First Search def Wrapper_DFS(self, graph): res = True for node in graph: if not self.DFS([node], graph, node): res = False break return res # wrapper for LCA using Depth First Search def Wrapper_LCA(self, graph, node1, node2): global nodeList1 global nodeList2 nodeList1 = [] nodeList2 = [] # storing the node routes for each node into a list for node in graph: self.LCA_DFS([node], graph, node, 1, node1) self.LCA_DFS([node], graph, node, 2, node2) leastCount = sys.maxsize for a in nodeList1: for b in nodeList2: count = 0 # +=1 till the node is found for ind, node1 in enumerate(reversed(a)): count = ind for node2 in reversed(b): # LCA is the one with the lowest count if node1 == node2 and count < leastCount: LCANode = node2 leastCount = count return LCANode count += 1 # calculates the DFS for an LCA node def LCA_DFS(self, nodeList, graph, node, index, endNode): # if the node is end node if node == endNode: # using index for the two routes if index == 1: nodeList1.append(nodeList[:]) elif index == 2: nodeList2.append(nodeList[:]) return True # if the node is not present in the graph if not graph[node]: return True # other cases else: for child in graph[node]: if child not in nodeList: nodeList.append(child) if not self.LCA_DFS(nodeList, graph, child, index, endNode): return self.LCA_DFS(nodeList, graph, child, index, endNode) nodeList.remove(child) else: return False return True
[ "lhngln8964@gmail.com" ]
lhngln8964@gmail.com
79b178ed4d676dcbbee9196d4c115bd628e2a38a
f0c35cf7f03c56834d4fac0704b14b381f02c258
/client.py
e0c9b6b6c1fbf8bababb5ff0af6eeb7479bab57e
[]
no_license
Prince-G525/CS425
d667cfc6c61cb3169d62ba8e98040d955a5183fd
117246a24d5fe404db32c04dbf237b1f74646c1f
refs/heads/master
2020-04-05T22:12:11.919151
2018-11-15T16:51:58
2018-11-15T16:51:58
157,248,600
0
0
null
null
null
null
UTF-8
Python
false
false
2,421
py
#!/usr/bin/env python3 """Script for Tkinter GUI chat client.""" from socket import AF_INET, socket, SOCK_STREAM from threading import Thread import tkinter import sys def receive(): """Handles receiving of messages.""" while True: try: msg = client_socket.recv(BUFSIZ).decode("utf8") msg = msg.split('\n') for m in msg: msg_list.insert(tkinter.END, m) except OSError: # Possibly client has left the chat. break def send(event=None): # event is passed by binders. """Handles sending of messages.""" msg = my_msg.get() my_msg.set("") # Clears input field. client_socket.send(bytes(msg, "utf8")) if msg == "exit": client_socket.close() top.quit() def on_closing(event=None): """This function is to be called when the window is closed.""" my_msg.set("exit") send() top = tkinter.Tk() top.title("Chatter") messages_frame = tkinter.Frame(top) my_msg = tkinter.StringVar() # For the messages to be sent. my_msg.set("Type your messages here.") scrollbar = tkinter.Scrollbar(messages_frame) # To navigate through past messages. msg_list = tkinter.Listbox(messages_frame, height=15, width=50, yscrollcommand=scrollbar.set) scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y) msg_list.pack(side=tkinter.LEFT, fill=tkinter.BOTH) msg_list.pack() messages_frame.pack() entry_field = tkinter.Entry(top, textvariable=my_msg) entry_field.bind("<Return>", send) entry_field.pack() send_button = tkinter.Button(top, text="Send", command=send) send_button.pack() top.protocol("WM_DELETE_WINDOW", on_closing) HOST = '' PORT = 0 if len(sys.argv) == 3: HOST = sys.argv[1] PORT = int(sys.argv[2]) else: print('Please input 2 arguments server IP and port#') exit(1) BUFSIZ = 1024 ADDR = (HOST, PORT) client_socket = socket(AF_INET, SOCK_STREAM) client_socket.connect(ADDR) receive_thread = Thread(target=receive) receive_thread.start() tkinter.mainloop() # Starts GUI execution. ''' #!/usr/bin/env python3 #dummy client for testing from socket import AF_INET,socket,SOCK_STREAM HOST = '127.0.0.1' PORT = 10000 ADDR = (HOST,PORT) client = socket(AF_INET,SOCK_STREAM) client.connect(ADDR) while True: msg = client.recv(1024).decode("utf8") print(msg) sendm = input() client.send(bytes(sendm,"utf8")) if sendm=="exit": break client.close() '''
[ "princ@iitk.ac.in" ]
princ@iitk.ac.in
e050482071635eb07a60e3d7c52ecbe616329826
8205f0871fdffdf8d582b7ca0d21b596d72540bd
/budgetq/nlp/topic_modeling.py
6fc771fb2a83f27a09e8152694f610fe4ef6b988
[]
no_license
michaelfong2017/ppa
395f99cb06ab8f4fc76e7bb90557648ac13c4686
247f1cb8eac89634c233a4ddc23b6d406ebbb7d4
refs/heads/master
2023-07-02T18:47:26.304331
2021-03-05T06:47:53
2021-03-05T06:47:53
335,323,744
0
0
null
null
null
null
UTF-8
Python
false
false
6,245
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Dec 29 23:01:35 2020 @author: michael """ # %% import MySQLdb import MySQLdb.cursors import pandas as pd import re import en_core_web_lg # %% from nltk.corpus import * import nltk import jieba import gensim import gensim.corpora as corpora from gensim.utils import simple_preprocess from gensim.models import CoherenceModel from gensim import corpora, models, similarities # %% import os FILE_DIR = os.path.dirname(os.path.abspath(__file__)) # #%% Only called once when " 1" has not been appended in dictionary. # with open(os.path.join(FILE_DIR, "data/vocabulary/cantonese_dict.txt")) as f: # lines = f.read().splitlines() # with open(os.path.join(FILE_DIR, "data/vocabulary/cantonese_dict.txt"), "w") as f: # f.write('\n'.join([line + ' 1' for line in lines])) # #%% Only called once when stopwords.txt still includes duplicates. # with open(os.path.join(FILE_DIR, "data/stopwords.txt")) as f: # lines = f.read().splitlines() # s = set(lines) # with open(os.path.join(FILE_DIR, "data/stopwords.txt"), "w") as f: # f.write('\n'.join([line for line in list(s)])) # %% nltk.download('all-corpora') # %% ''' Download NLTK corpora ''' nltk_corpora = ["unicode_samples", "indian", "stopwords", "brown", "swadesh", "mac_morpho", "abc", "words", "udhr2", "lin_thesaurus", "webtext", "names", "sentiwordnet", "cmudict", "ptb", "inaugural", "conll2002", "ieer", "problem_reports", "floresta", "sinica_treebank", "gutenberg", "kimmo", "nonbreaking_prefixes", "senseval", "verbnet", "chat80", "biocreative_ppi", "framenet_v17", "pil", "alpino", "omw", "cess_cat", "shakespeare", "city_database", "movie_reviews", "wordnet_ic", "conll2000", "dependency_treebank", "wordnet", "cess_esp", "toolbox", "mte_teip5", "treebank", "rte", "nps_chat", "crubadan", "ppattach", "switchboard", "brown_tei", "verbnet3", "ycoe", "timit", "pl196x", "state_union", "framenet_v15", "paradigms", "genesis", "gazetteers", "qc", "udhr", "dolch"] for corpus in nltk_corpora: try: exec("word_list = %s.words()" % corpus) if not corpus == "stopwords": with open(os.path.join(FILE_DIR, "data/vocabulary/nltk_"+corpus+".txt"), "w") as f: f.write('\n'.join([line + " 1" for line in word_list])) except: print("ImportError") # %% ''' Download Spacy corpora ''' nlp = en_core_web_lg.load() with open(os.path.join(FILE_DIR, "data/vocabulary/spacy_en_core_web_lg.txt"), "w") as f: f.write('\n'.join([line + " 1" for line in list(nlp.vocab.strings)])) # %% ''' Load corpora (custom dictionary) ''' for filename in os.listdir(os.path.join(FILE_DIR, "data/vocabulary")): if filename.endswith(".txt"): print(filename) jieba.load_userdict(os.path.join( FILE_DIR, "data/vocabulary/" + filename)) # %% stopwords_list = [line.strip() for line in open(os.path.join( FILE_DIR, "data/stopwords.txt"), 'r', encoding='UTF-8').readlines()] filter_list = [line.strip() for line in open(os.path.join( FILE_DIR, "data/filter.txt"), 'r', encoding='UTF-8').readlines()] # %% def seg_depart(sentence, stopwords_list): if not isinstance(value, str): return '' ''' Filter patterns such as <br/>, <table border=" ''' for f in filter_list: sentence = re.sub(f, '', sentence) ''' Filter character by character Keep space when char is symbol or space so that words will not be squeezed together ''' sentence = list([char.lower() if char.isalpha() or char.isnumeric() or char == ' ' else ' ' for char in sentence]) sentence = "".join(sentence) '''Tokenization''' sentence_depart = jieba.cut(sentence.strip()) outstr = '' for word in sentence_depart: ''' Remove punctuations and stopwords ''' if (word.isalpha() or word.isdigit()) and word not in stopwords_list: outstr += word outstr += ";" return outstr # %% col_list = ["id", "question", "answer"] df_qa = pd.read_csv(os.path.join( FILE_DIR, "data/questions.csv"), sep=";", usecols=col_list) # %% # i = 0 # for index, value in df_qa['question'].iteritems(): # if i >= 10: # break # # print(value) # tokens = seg_depart(value, stopwords_list) # print(tokens) # i = i + 1 # %% print(df_qa['question'][1]) # %% '''Add columns in MySQL first if not done''' ''' alter table budgetq.question add column tokenized_question text; alter table budgetq.question add column tokenized_answer text; ''' # %% conn = MySQLdb.connect(host='localhost', db='budgetq', user='root', passwd='P@ssw0rd', charset='utf8') try: with conn.cursor() as cursor: cursor.execute('SET SQL_SAFE_UPDATES=0') for index, value in df_qa['question'].iteritems(): # if index >= 100: # break if index % 500 == 0: print(f'Now process row with id={index+1}') tokens = seg_depart(value, stopwords_list) cursor.execute( f'UPDATE question Q SET Q.tokenized_question=\"{tokens}\" WHERE Q.id=\"{index+1}\"') cursor.execute('SET SQL_SAFE_UPDATES=1') conn.commit() i = i + 1 finally: conn.close() # %% conn = MySQLdb.connect(host='localhost', db='budgetq', user='root', passwd='P@ssw0rd', charset='utf8') try: with conn.cursor() as cursor: cursor.execute('SET SQL_SAFE_UPDATES=0') for index, value in df_qa['answer'].iteritems(): # if index >= 100: # break if index % 500 == 0: print(f'Now process row with id={index+1}') tokens = seg_depart(value, stopwords_list) cursor.execute( f'UPDATE question Q SET Q.tokenized_answer=\"{tokens}\" WHERE Q.id=\"{index+1}\"') cursor.execute('SET SQL_SAFE_UPDATES=1') conn.commit() i = i + 1 finally: conn.close()
[ "michaelfong2017@gmail.com" ]
michaelfong2017@gmail.com
de63dab531b2b844a146088eee338cd159d0a6a9
c6fee65223253d24781554fae1699b1ddb2614d6
/M5HW3_Santiago.py
82054da042b93afb6086f0bd5e81d100da34a545
[]
no_license
JSantiago2007/cti110
f7422a7851bae0c8aab0da08de34131a120ba848
2c2e8e26a60a74bc16f1706cd7658972208084d5
refs/heads/master
2021-08-29T11:56:34.690526
2017-12-13T22:18:48
2017-12-13T22:18:48
103,087,638
0
0
null
null
null
null
UTF-8
Python
false
false
1,001
py
# CTI 110 # M5HW3: Factorial # Juan Santiago # 10/19/2017 #The notation n! (“n-factorial”) represents the factorial of the #non-negative integer n. The factorial of n is the product of #all nonnegative integers from 1 to n. #For example: #4! = 1 * 2 * 3 * 4 = 24 #The factorial of zero (0!) is defined to be 1. #Assignment #Write a program that asks the user for a nonnegative integer #and then uses a loop to calculate the factorial of that number. #Display the factorial #Here is an example program run. #(The user’s entries, after the “?”, are listed in bold.) #Enter a nonnegative integer? 4 #The factorial of 4 is 24 #>>> userInteger = int( input("Please enter a number: ") ) while userInteger < 1: userInteger = int( input("Please enter a positive number please: ") ) factorial = 1 for currentNumber in range( 1,userInteger + 1): factorial = factorial * currentNumber print() print("The factorial of", userInteger, "is", factorial)
[ "noreply@github.com" ]
JSantiago2007.noreply@github.com
0fe6bdfbe73b0b423ac569d90c58b1e105332d94
90bce847e6b10f5a71c88231059b3ab8d35d9f0a
/1.Presentaciones/11_S/datavi/ej1.py
57046d5e78c84a740215c4d2973bd08a26a0f0e4
[]
no_license
smonsalve/ST0240-20162
66f929e7e541845df658206d25640367eb03f379
74ee1f2c9d2106fb7ec7a736b6f33d70325219b4
refs/heads/master
2020-04-13T04:02:19.854744
2016-10-07T19:27:42
2016-10-07T19:27:42
61,818,937
1
0
null
null
null
null
UTF-8
Python
false
false
150
py
import matplotlib.pyplot as plt a = plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.xlabel('esta seria la etiqueta de X') plt.show() a.savefig()
[ "smonsalve@gmail.com" ]
smonsalve@gmail.com
6cbb6e5b1fe7fbef2464a8e566009eacccc44143
9dd96571cb0fe8a36efc915ec7cc6f834afdd107
/manage.py
86b1ec395c0571de5a7d9dc0ef30d88d7162bbfa
[]
no_license
lionlinekz/ticketfinder
2368fb57e25c52c432a8ca3f292cf9536123d00b
66a429d2add412433ec7ef2742265d3ebeeba5d3
refs/heads/master
2021-01-16T21:26:49.112352
2016-07-21T03:39:33
2016-07-21T03:39:33
63,568,408
0
0
null
null
null
null
UTF-8
Python
false
false
255
py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ticketfinder.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
[ "aset.kaz@gmail.com" ]
aset.kaz@gmail.com
75daebcc86d0bf64b8b7f701df957b9bccc1bb99
8d6a6491ed762cb883f5e24f293a6317d2aa7f27
/test/gdad_python.py
5a00056742609a835ceef309f5fab6341ff10195
[]
no_license
Ihyugo/learning
49428c50c02b8a366bf314af7e69292ee5110fb2
c9aac1c06c7aff0858cce1ad0e29d3ff6c0ddbc6
refs/heads/master
2022-01-26T19:00:25.051961
2019-07-31T07:37:58
2019-07-31T07:37:58
105,742,806
0
0
null
null
null
null
UTF-8
Python
false
false
2,485
py
# text p.28 import pandas as pd df = pd.read_csv('https://archive.ics.uci.edu/ml/' 'machine-learning-databases/iris/iris.data', header=None) df.tail() import matplotlib.pyplot as plt import numpy as np #1-100行目の目的て変数の抽出 y = df.iloc[0:100, 4].values # Iris-setosaを-1、Iris-virginicaを1に変換 y = np.where(y == 'Iris-setosa', -1, 1) #1-100行目の1,3列目の抽出 X = df.iloc[0:100, [0, 2]].values # 品種setosaのプロット(赤の○) from iris_marker import * from test import * #勾配領域を1行2勾配領域を1行2列に分割 fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(8, 4)) #勾配降下法によるADLINEの学習(学習率 eta=0.01) ada1 = AdalineGD(n_iter=10, eta=0.01,).fit(X,y) #エポック数とコストの関係を表す折れ線グラフのプロット(縦軸のコストは常用対数) ax[0].plot(range(1,len(ada1.cost_)+1), np.log10(ada1.cost_), marker='o') #軸のラベルの設定 ax[0].set_xlabel('Epochs') ax[0].set_ylabel('log(Sum-squared-error') #タイトルの設定 ax[0].set_title('Adaline - Learning-error') #勾配降下法によるADLINEの学習(学習率 eta=0.0001) ada2 = AdalineGD(n_iter=10, eta=0.0001).fit(X, y) #エポック数うとコストの関係を表す折れ線グラフのプロット ax[1].plot(range(1,len(ada2.cost_)+1), ada2.cost_, marker='o') #軸のラベルの設定 ax[1].set_xlabel('Epochs') ax[1].set_ylabel('Sum-squared-error') #タイトルの設定 ax[1].set_title('Adaline - Learning rate 0.0001') plt.show() # text p.39 #データのコピー X_std = np.copy(X) #各列の標準化 X_std[:,0] = (X[:,0] - X[:,0].mean()) / X[:,0].std() X_std[:,1] = (X[:,1] - X[:,1].mean()) / X[:,1].std() #勾配降下法によるADLINEの学習(標準化後、学習率 eta=0.01) ada = AdalineGD(n_iter=15, eta=0.01) # モデルの適合 ada.fit(X_std, y) # 境界領域のプロット plot_decision_regions(X_std, y, classifier=ada) # タイトルの設定 plt.title('Adaline - Grandient Descent') # 軸のラベルの設定 plt.xlabel('sepal length [standard]') plt.ylabel('petal length [standard]') # 凡例の設定 plt.legend(loc='upper left') # 図の表示 plt.show() # エポック数とコストの関係を表す折れ線グラフのプロット plt.plot(range(1,len(ada.cost_)+1), ada.cost_, marker='o') # 軸のラベルの設定 plt.xlabel('Epochs') plt.ylabel('Sum-squared-error') # 図の表示 plt.show() # text p.44
[ "yugo1997.10.14@gmail.com" ]
yugo1997.10.14@gmail.com
7b17d48cc8a7d3d9ea0e9c2fc38978a6cdb97760
02726c324ad93be88b61a8e4e789e2475f0e6f4f
/manager/views/admin.py
7f3d71ade0a593ddbd66aadad33ad143401a6429
[]
no_license
stkaeljason/shuxin-manager
6f8f5b8218553a2f9ee7631c79b346ec35ed8313
2ae2ad22bae0708dc0b0c15159949da50be620a3
refs/heads/master
2020-07-02T06:02:23.905187
2016-08-18T09:23:35
2016-08-18T09:23:35
65,983,847
0
0
null
null
null
null
UTF-8
Python
false
false
10,205
py
# -*- coding:utf-8 -*- import os from flask import Blueprint, render_template, request, url_for, \ redirect, session, flash, current_app from flask.ext.login import login_required, login_user, logout_user from sqlalchemy.orm import exc as orm_exc from manager.models import Admin from manager.global_var import login_manager from manager.libs.qiniuwrapper import QiniuWrapper from manager.libs.utils import get_image_upload_name, reduce_image_size from manager import models_handle import json from manager.global_var import redis_db from werkzeug.utils import secure_filename from manager.settings.last_settings import UPLOAD_FOLDER import sys reload(sys) sys.setdefaultencoding('utf8') app = Blueprint('admin', __name__) @login_manager.unauthorized_handler def unauthorized(): return redirect(url_for('.signin')) @login_manager.user_loader def load_user(userid): return Admin.query.filter_by(id=userid).first() @app.route('/signin/', methods=['GET', 'POST']) def signin(): if request.method == 'POST' and request.form: email = request.form.get('email', '') password = request.form.get('password', '') try: user = Admin.query.filter_by(email=email).one() except orm_exc.NoResultFound: flash("用户名不存在") return render_template('access/AdminLogin.html') if not user.check_password(password): flash("密码错误") return render_template('access/AdminLogin.html') login_user(user) # save user email in session for java cms use to display user info session['email'] = user.email return redirect(url_for('.get_user')) else: return render_template('access/AdminLogin.html') @app.route('/signout/') @login_required def signout(): logout_user() session.pop('user_email', None) return redirect(url_for('.signin')) @app.route('/') @login_required def index(): return redirect(url_for('.signin')) @app.route('/user') @login_required def get_user(): return render_template('user/user.html') @app.route('/get_user', methods=['POST']) @login_required def get_user_list(): start = request.values.get('start') limit = request.values.get('limit') start = int(start) limit = int(limit) print start print limit res = models_handle.get_users(start, limit) return json.dumps(res) @app.route('/post', methods=['POST', 'GET']) @login_required def get_postinfo(): start = request.values.get('start') limit = request.values.get('limit') start = int(start) limit = int(limit) res = models_handle.get_post(start, limit) current_app.logger.debug(res) return json.dumps(res) @app.route('/post/send', methods=['GET', 'POST']) @login_required def send_post(): if request.method == 'GET': users = models_handle.get_admin_users() groups = models_handle.get_groups() return render_template('user/send_post.html', users=users, groups=groups) elif request.method == 'POST': # 获取form表单 uid = request.form.get('uid', None) realname = '' if uid and '/' in uid: realname = uid.split('/')[0].strip() uid = uid.split('/')[1].strip() nickname = request.form.get('nickname', None) group_name = request.form.get('group_name', None) if group_name: group_name, group_id, group_class = [s.strip() for s in group_name.split('/')] content = request.form.get('content', None) imgs = [] for filestorage in request.files.getlist("picture[]"): # Workaround: larger uploads cause a dummy file named '<fdopen>'. # See the Flask mailing list for more information. if filestorage.filename and filestorage.filename not in (None, 'fdopen', '<fdopen>'): if (not os.path.exists(UPLOAD_FOLDER)): os.makedirs(UPLOAD_FOLDER) filename = secure_filename(filestorage.filename) filepath = os.path.join(UPLOAD_FOLDER, filename) filestorage.save(filepath) reduce_image_size(filepath) qiniu = QiniuWrapper() key = get_image_upload_name(filepath, prefix='post') success, info = qiniu.upload_file(key, filepath) if success: imgs.append(key) else: current_app.logger.error('upload <%s> failed' % filepath) avatar = request.files['avatar'] if avatar: avatarname = secure_filename(avatar.filename) avatarpath = os.path.join(UPLOAD_FOLDER, avatarname) avatar.save(avatarpath) reduce_image_size(avatarpath) qiniu = QiniuWrapper() key = get_image_upload_name(avatarpath, prefix='user') success, info = qiniu.upload_file(key, avatarpath) if success: avatar = key current_app.logger.debug('upload avatar <%s> success' % key) else: current_app.logger.error('upload avatar <%s> failed' % avatarpath) else: avatar = models_handle.getuserinfo_byname(realname)['avatar'] current_app.logger.debug('using user default avatar: %s' % avatar) res = models_handle.add_post( author_id=uid, nickname=nickname, parent_id=group_id, group_name=group_name, content=content, pictures=imgs, avatar=avatar) current_app.logger.debug(res) return redirect(url_for('.comment')) @app.route('/push', methods=['GET']) @login_required def push(): return render_template('user/push.html') @app.route('/sendpush', methods=['POST']) def sendpush(): groupName = request.form['group_name'].split('/')[0].strip() groupId = request.form['group_name'].split('/')[1].strip() pushContent = request.form['content'] print groupName print groupId print pushContent # return redirect(url_for('.push')) return render_template('user/push.html', info="发送成功") @app.route('/comment') @login_required def comment(): return render_template('user/comment.html') @app.route('/get_post_count', methods=['POST']) @login_required def post_count(): res = models_handle.get_post_count() count = 0 for i in res: count = i.values()[0] return str(count) @app.route('/get_user_count', methods=['POST']) @login_required def user_count(): res = models_handle.get_user_count() count = 0 for i in res: count = i.values()[0] print count return str(count) @app.route('/get_comment', methods=['POST']) @login_required def get_comment(): root_id = request.values.get('id') res = models_handle.get_comment(root_id) current_app.logger.debug(res) return json.dumps(res) @app.route('/post_comment', methods=['POST']) @login_required def post_comment(): return 'ok' @app.route('/getuid_byname', methods=['GET', 'POST']) @login_required def get_uid(): uid = '' if request.method == 'GET': uid = models_handle.getuid_byname(request.args.get('nickname')) else: uid = models_handle.getuid_byname(request.form.get('nickname')) return str(uid) @app.route('/get_groups_by_rule', methods=['GET']) @login_required def get_groups_by_rule(): rule = request.args.get('rule') groups = models_handle.get_groups_by_rule(rule) current_app.logger.debug(groups) return json.dumps(groups) @app.route('/group') @login_required def get_group(): res = models_handle.get_groups_by_rule('') # current_app.logger.debug(res) return render_template('user/group.html', res=res) @app.route('/get_allGroup') @login_required def get_groups(): res = models_handle.get_groups_by_rule(None) return json.dumps(res) @app.route('/topic') @login_required def topic(): return render_template('user/topic.html') @app.route('/topic/new_topic', methods=['GET', 'POST']) @login_required def new_topic(): if request.method == 'GET': users = models_handle.get_admin_users() groups = models_handle.get_groups_by_rule('') return render_template('user/send_topic.html', users=users, groups=groups) if request.method == 'POST': background = request.files['background'] if background: if (not os.path.exists(UPLOAD_FOLDER)): os.mkdir(UPLOAD_FOLDER) backgroundname = secure_filename(background.filename) backgroundpath = os.path.join(UPLOAD_FOLDER, backgroundname) background.save(backgroundpath) reduce_image_size(backgroundpath) qiniu = QiniuWrapper() key = get_image_upload_name(backgroundpath, prefix='user') success, info = qiniu.upload_file(key, backgroundpath) if success: background = key current_app.logger.debug('upload avatar <%s> success' % key) else: current_app.logger.error('upload avatar <%s> failed' % backgroundpath) else: background = 'http://image.ciwei.io/group/background/recentdays.jpg' current_app.logger.debug('using user default avatar: %s' % background) topicName = request.form['topicName'] if request.form['type'] == 'group': # containerId = request.form['group_name'].split('/')[1].strip() # containerName = request.form['group_name'].split('/')[0].strip() containerId = [s.strip().split('/')[1] for s in request.form.getlist('group_name[]')] containerName = [s.strip().split('/')[0] for s in request.form.getlist('group_name[]')] else: containerId = ['ALL'] containerName = ['属信'] res = models_handle.add_topic( topicName=topicName, containerName=containerName, containerId=containerId, background=background ) current_app.logger.debug(res) return redirect(url_for('.new_topic')) else: return 'illegal method'
[ "jason@yunchuideiMac.local" ]
jason@yunchuideiMac.local
9b05e900a827ba62799fd474339ec44e3c0583d7
88deb146e8874c95ca5d504a0a363ee8e960c7e0
/Demo.py
02337348071fdefc5c8892f2c19be9df0cbcc531
[]
no_license
WangXiaojie01/ConfParser
8789ff1a30c2ab81f6ec1e0a9f27204d58547809
e7b21434051c396b130a1250466e4d447061ba81
refs/heads/master
2020-12-14T05:32:44.477056
2020-03-16T05:26:16
2020-03-16T05:26:16
234,657,789
1
0
null
null
null
null
UTF-8
Python
false
false
859
py
#!/usr/bin/env python #-*- coding:utf8 -*- ''' copyright @wangxiaojie 2020.01.17 author: wangxiaojie ''' import os, sys codePath = os.path.abspath(os.path.join(__file__, "..", "Code")) if os.path.exists(codePath): sys.path.append(codePath) from ConfParser import * if __name__ == "__main__": #配置文件的路径 confFile = os.path.abspath(os.path.join(__file__, "../../etc/init.conf")) #初始化ConfParser iniConfParser = ConfParser(confFile) #获取配置,第一个参数为选项,第二个参数为要获取的参数名,第三个参数为获取不到参数后返回的默认值 RecvTimeout = iniConfParser.getValueWithDefault("socket", "RecvTimeout", 10) print(RecvTimeout) #直接调用接口获取参数 RecvTimeout = getValueWithDefault(confFile, "socket", "RecvTimeout1", 15) print(RecvTimeout)
[ "1259488569@qq.com" ]
1259488569@qq.com
a27b261cbaf540c639cf5cccbc701942cfdbbcbe
95cfb298f55db7c4a2195c7cad4da3540a71ecb3
/CaptureHandPackage/FaceModel.py
3944ee2b34f21f5bd779257eca300f3b3c0f6b18
[]
no_license
TheOddMan/NFU-project
2d114d177eaa2cccb06e3d82a36459ef0a987d2d
b378eea5438fb06a474dee690c35289b21d19d30
refs/heads/master
2020-12-14T20:00:31.215752
2020-02-21T13:21:33
2020-02-21T13:21:33
234,853,891
1
0
null
null
null
null
UTF-8
Python
false
false
249
py
from keras.engine import Model from keras.layers import Input from keras_vggface.vggface import VGGFace vgg_features = VGGFace(include_top=False, input_shape=(224, 224, 3), pooling='avg') # pooling: None, avg or max print(vgg_features.summary())
[ "ilcb112045@gmail.com" ]
ilcb112045@gmail.com
fe7966a458e3345c21f86f2e2e0166b0bf0a6ec3
c8ceca7daf6531ea5339712712a650831e3cf6aa
/Program as a .PY/Dialog.py
2cd6aa9138a0fc92b02d55548b337e55391df816
[]
no_license
AnthonyKuntz/Riot-QA-Internship-Challenge
fa2d89bc2c6e93b47145ca02d2b3a845c8803243
e676439f368014511d6db35c00f74b87de2025ce
refs/heads/master
2016-09-01T12:16:05.595738
2015-10-31T05:21:45
2015-10-31T05:21:45
44,932,508
0
0
null
null
null
null
UTF-8
Python
false
false
735
py
import tkSimpleDialog import tkMessageBox from Tkinter import * # Adapted from course notes at cs.cmu.edu/~112 class MyDialog(tkSimpleDialog.Dialog): def body(self, master): self.canvas = master self.canvas.modalResult = None Label(master, text="Ability Power").grid(row=0) Label(master, text="Attack Damage").grid(row=1) Label(master, text="Cooldown Reduction").grid(row=2) self.e1 = Entry(master) self.e2 = Entry(master) self.e3 = Entry(master) self.e1.grid(row=0, column=1) self.e2.grid(row=1, column=1) self.e3.grid(row=2, column=1) return self.e1 # initial focus def apply(self): first = self.e1.get() second = self.e2.get() third = self.e3.get() self.canvas.modalResult = (first, second, third)
[ "akuntz@cmu.edu" ]
akuntz@cmu.edu
f909abbadd18a8fa6c131a7325ab1474993211fd
9ce48b9beb79ae34c3a903580f8016ba952981b0
/tsfuse/transformers/boolean.py
1cc6dafa1f6f09025a0c9b6adb6fe3da8c9f9102
[ "Apache-2.0" ]
permissive
datastreaming/tsfuse
77c77cd1bb9bd018b4b413383b0163e4d1eb6953
98a66c66f525c2e7f94fd487cf6dafe0ff8212ad
refs/heads/master
2022-12-18T05:17:07.546305
2020-09-18T15:16:46
2020-09-18T15:16:46
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,634
py
import numpy as np from ..computation import Transformer from ..computation.nodes import Greater, Less from ..data import Collection __all__ = [ 'Greater', 'Less', 'Equal', 'NotEqual', ] class Equal(Transformer): """ Element-wise equality comparison. Preconditions: - Number of inputs: 1 """ def __init__(self, *parents, **kwargs): super(Equal, self).__init__(*parents, **kwargs) self.preconditions = [ lambda *collections: len(collections) == 2, ] @staticmethod def apply(x, y): x, y = _collections(x, y) values = np.array(x.values == y.values, dtype=bool) return _result(x, y, values) class NotEqual(Transformer): """ Element-wise inequality comparison. Preconditions: - Number of inputs: 1 """ def __init__(self, *parents, **kwargs): super(NotEqual, self).__init__(*parents, **kwargs) self.preconditions = [ lambda *collections: len(collections) == 2, ] @staticmethod def apply(x, y): x, y = _collections(x, y) values = np.array(x.values != y.values, dtype=bool) return _result(x, y, values) def _collections(x, y): if not isinstance(x, Collection): x = Collection(np.array([[[[x]]]])) if not isinstance(y, Collection): y = Collection(np.array([[[[y]]]])) return x, y def _result(x, y, values): if values.shape == x.shape: return Collection(values, index=x.index, dimensions=x.dimensions) else: return Collection(values, index=y.index, dimensions=y.dimensions)
[ "arne.debrabandere@cs.kuleuven.be" ]
arne.debrabandere@cs.kuleuven.be
a937f5d7fc87c0d7d50c3d34d25169594f08b310
3ef70fe63acaa665e2b163f30f1abd0a592231c1
/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_v1parser.py
b17099f3cc388868573fb479110f29e78e8bce65
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
wistbean/learn_python3_spider
14914b63691ac032955ba1adc29ad64976d80e15
40861791ec4ed3bbd14b07875af25cc740f76920
refs/heads/master
2023-08-16T05:42:27.208302
2023-03-30T17:03:58
2023-03-30T17:03:58
179,152,420
14,403
3,556
MIT
2022-05-20T14:08:34
2019-04-02T20:19:54
Python
UTF-8
Python
false
false
4,326
py
# -*- test-case-name: twisted.protocols.haproxy.test.test_v1parser -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ IProxyParser implementation for version one of the PROXY protocol. """ from zope.interface import implementer from twisted.internet import address from ._exceptions import ( convertError, InvalidProxyHeader, InvalidNetworkProtocol, MissingAddressData ) from . import _info from . import _interfaces @implementer(_interfaces.IProxyParser) class V1Parser(object): """ PROXY protocol version one header parser. Version one of the PROXY protocol is a human readable format represented by a single, newline delimited binary string that contains all of the relevant source and destination data. """ PROXYSTR = b'PROXY' UNKNOWN_PROTO = b'UNKNOWN' TCP4_PROTO = b'TCP4' TCP6_PROTO = b'TCP6' ALLOWED_NET_PROTOS = ( TCP4_PROTO, TCP6_PROTO, UNKNOWN_PROTO, ) NEWLINE = b'\r\n' def __init__(self): self.buffer = b'' def feed(self, data): """ Consume a chunk of data and attempt to parse it. @param data: A bytestring. @type data: L{bytes} @return: A two-tuple containing, in order, a L{_interfaces.IProxyInfo} and any bytes fed to the parser that followed the end of the header. Both of these values are None until a complete header is parsed. @raises InvalidProxyHeader: If the bytes fed to the parser create an invalid PROXY header. """ self.buffer += data if len(self.buffer) > 107 and self.NEWLINE not in self.buffer: raise InvalidProxyHeader() lines = (self.buffer).split(self.NEWLINE, 1) if not len(lines) > 1: return (None, None) self.buffer = b'' remaining = lines.pop() header = lines.pop() info = self.parse(header) return (info, remaining) @classmethod def parse(cls, line): """ Parse a bytestring as a full PROXY protocol header line. @param line: A bytestring that represents a valid HAProxy PROXY protocol header line. @type line: bytes @return: A L{_interfaces.IProxyInfo} containing the parsed data. @raises InvalidProxyHeader: If the bytestring does not represent a valid PROXY header. @raises InvalidNetworkProtocol: When no protocol can be parsed or is not one of the allowed values. @raises MissingAddressData: When the protocol is TCP* but the header does not contain a complete set of addresses and ports. """ originalLine = line proxyStr = None networkProtocol = None sourceAddr = None sourcePort = None destAddr = None destPort = None with convertError(ValueError, InvalidProxyHeader): proxyStr, line = line.split(b' ', 1) if proxyStr != cls.PROXYSTR: raise InvalidProxyHeader() with convertError(ValueError, InvalidNetworkProtocol): networkProtocol, line = line.split(b' ', 1) if networkProtocol not in cls.ALLOWED_NET_PROTOS: raise InvalidNetworkProtocol() if networkProtocol == cls.UNKNOWN_PROTO: return _info.ProxyInfo(originalLine, None, None) with convertError(ValueError, MissingAddressData): sourceAddr, line = line.split(b' ', 1) with convertError(ValueError, MissingAddressData): destAddr, line = line.split(b' ', 1) with convertError(ValueError, MissingAddressData): sourcePort, line = line.split(b' ', 1) with convertError(ValueError, MissingAddressData): destPort = line.split(b' ')[0] if networkProtocol == cls.TCP4_PROTO: return _info.ProxyInfo( originalLine, address.IPv4Address('TCP', sourceAddr, int(sourcePort)), address.IPv4Address('TCP', destAddr, int(destPort)), ) return _info.ProxyInfo( originalLine, address.IPv6Address('TCP', sourceAddr, int(sourcePort)), address.IPv6Address('TCP', destAddr, int(destPort)), )
[ "354142480@qq.com" ]
354142480@qq.com
d46c0ec761c1a8d40751447b17fda5f1446f8667
d8526bd1832f70e31af64c80e3d3449b6f36a772
/Workspace/DataSkim/python/jetSkim_cff.py
d4db4053073524821e6f3ee50555f996cfef426b
[]
no_license
tedanielson/oldUserCode
e53d78fc504dae8a685417f6cd582114c21d4011
1f62e961ecc4783db0f810cb9a1b1f553c31200e
refs/heads/master
2016-09-06T02:31:41.627459
2013-02-06T22:15:05
2013-02-06T22:15:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,523
py
import FWCore.ParameterSet.Config as cms #from HLTrigger.HLTfilters.hltHighLevel_cfi import * #exoticaMuHLT = hltHighLevel #Define the HLT path to be used. #exoticaMuHLT.HLTPaths =['HLT_L1MuOpen'] #exoticaMuHLT.TriggerResultsTag = cms.InputTag("TriggerResults","","HLT8E29") #Define the HLT quality cut #exoticaHLTMuonFilter = cms.EDFilter("HLTSummaryFilter", # summary = cms.InputTag("hltTriggerSummaryAOD","","HLT8E29"), # trigger summary # member = cms.InputTag("hltL3MuonCandidates","","HLT8E29"), # filter or collection # cut = cms.string("pt>0"), # cut on trigger object # minN = cms.int32(0) # min. # of passing objects needed # ) Jet2 = cms.EDFilter("EtaPtMinCandViewSelector", src = cms.InputTag("iterativeCone5CaloJets"), ptMin = cms.double(8), etaMin = cms.double(-2), etaMax = cms.double(2) ) Jet1 = cms.EDFilter("EtaPtMinCandViewSelector", src = cms.InputTag("Jet2"), ptMin = cms.double(8), etaMin = cms.double(-1), etaMax = cms.double(1) ) #Define the Reco quality cut #jetFilter = cms.EDFilter("CaloJetSelector", # src = cms.InputTag("iterativeCone5CaloJets"), # cut = cms.string('pt > 100 && abs(eta) < 2.0' ), # filter = cms.bool(True), # minNumber = cms.uint32(2) # sizeSelector = cms.uint32(2) # ) dijetFilter = cms.EDFilter("CandViewCountFilter", src = cms.InputTag("Jet2"), minNumber = cms.uint32(2) ) jetFilter = cms.EDFilter("CandViewCountFilter", src = cms.InputTag("Jet1"), minNumber = cms.uint32(1) ) #===== add electrons ======= jetSuperClusterMerger = cms.EDFilter("EgammaSuperClusterMerger", src = cms.VInputTag(cms.InputTag('correctedHybridSuperClusters'), cms.InputTag('correctedMulti5x5SuperClustersWithPreshower')) ) jetSuperClusterCands = cms.EDProducer("ConcreteEcalCandidateProducer", src = cms.InputTag("jetSuperClusterMerger"), particleType = cms.string('e-') ) goodJetSuperClusters = cms.EDFilter("CandViewRefSelector", src = cms.InputTag("jetSuperClusterCands"), cut = cms.string('et > 3.0') ) jetSuperClusterPt5Filter = cms.EDFilter("CandViewCountFilter", src = cms.InputTag("goodJetSuperClusters"), minNumber = cms.uint32(2) ) twoEmClusters = cms.Sequence( jetSuperClusterMerger+jetSuperClusterCands+goodJetSuperClusters+jetSuperClusterPt5Filter ) #Define group sequence, using HLT/Reco quality cut. #exoticaMuHLTQualitySeq = cms.Sequence() jetRecoQualitySeq = cms.Sequence( # twoEmClusters + Jet2+Jet1+dijetFilter+jetFilter )
[ "" ]
1aa69b710c08a012be06066a9573d470123cf31e
2b7b16fba84b2e02cc56214d844e44f120d72181
/psiCalculate.py
e32aca9e0947ee34b088f47f2cef504c005ad2fb
[]
no_license
xjtu-omics/opium_poppy_isoseq
07eba1ca5b1610d39efe4306e21509cba6fa0bd3
9c8ea0de3f6e07d98fec2933d6a03b56f2dfc60f
refs/heads/master
2023-08-13T12:13:39.548191
2021-09-16T06:48:31
2021-09-16T06:48:31
288,669,937
0
0
null
null
null
null
UTF-8
Python
false
false
2,102
py
import os from collections import defaultdict with open('../data/total_RI_strict.ioe','r') as f,\ open('../data/ri.gff','w') as of: line=f.readline() while True: line=f.readline() if line=='': break line=line.strip() cpline=line line=line.split('\t') chrm=line[0] int_chr=int(chrm.split('r')[1]) if int_chr>=12: chrm=str('unplaced-scaffold_' + str(int_chr-12)) gene=line[1] info=line[2].split(':')[3].split('-') strand=line[2].split(':')[5] st=int(info[0])+1 ed=int(info[1])-1 print(chrm,'dexseq_prepare_annotation.py\texonic_part',st,ed,'.',strand,'.',gene+':'+chrm+':'+str(st)+':'+str(ed),sep='\t',file=of) os.system("sort -u -k9,9 ../data/ri.gff | sort -k1,1 -k4,4n >../data/ri.sorted.gff && rm ../data/ri.gff") tissues=['S1','S2','S3','S4','S5','S6','S7'] for tis in tissues: os.system("bamToBed -i ../../2nd_read/lqs/sdata/%s.bam -cigar | /home/xutun/software/filterSamFile/bin/bedToJunction - | awk 'BEGIN{OFS=\"\\t\"}{print $1,$2,$3,$4,$5,$6}' | sort -k1,1 -k2,2n >../data/%s.intron.bed "%(tis,tis)) os.system("intersectBed -wao -sorted -f 1.0 -a ../data/ri.sorted.gff -b ../data/%s.intron.bed | awk -v OFS=\"\\t\" '{$16<=0?s[$9]+=0:s[$9]+=$14;}END{for (i in s){print i,s[i]}}' | sort -k1 >../data/%s.exonic_parts.exclusion"%(tis,tis)) os.system("bedtools bamtobed -split -i ../../2nd_read/lqs/sdata/%s.bam |sort -k1,1 -k2,2n >../data/%s.bed"%(tis,tis)) os.system("awk -v OFS=\"\\t\" '{print $1,$4,$5,$9;}' ../data/ri.sorted.gff |coverageBed -sorted -split -b ../data/%s.bed -a stdin | awk 'BEGIN{OFS=\"\\t\"}{print $1,$2,$3,$3-$2+1,$5,$4}' | sort -k 6 >../data/%s.exonic_parts.inclusion"%(tis,tis)) os.system("paste ../data/%s.exonic_parts.inclusion ../data/%s.exonic_parts.exclusion | awk -v \"len=150\" 'BEGIN{OFS=\"\\t\";print \"exon_ID\",\"length\",\"inclusion\",\"exclusion\",\"PSI\"}{NIR=$5/($4+len-1);NER=$8/(len-1);print $6,$4,$5,$8,(NIR+NER<=0)?\"NA\":NIR/(NIR+NER);}'>../data/%s.exonic_parts.psi"%(tis,tis,tis))
[ "xu_tun@qq.com" ]
xu_tun@qq.com
ce4235d0efda7c46891df822ff1a0d4393fd7ba7
e048c7dac598676170a06529ff7cd11285ce6a4a
/ndasynapse/__init__.py
bc443b66fed92a2060c4301f221f7c36c2cad47b
[]
no_license
bsmn/ndasynapse
2084d03c95a74dc80e7aa8c3326f65f6d3895272
e03067fdf08f5f66b49e610154311fd5d6f7370f
refs/heads/master
2021-03-27T09:08:45.741592
2020-04-20T17:10:08
2020-04-20T17:10:08
78,232,701
1
4
null
2020-04-16T14:40:54
2017-01-06T19:27:37
Python
UTF-8
Python
false
false
77
py
from . import nda from . import synapse from .__version__ import __version__
[ "kenneth.daily@sagebase.org" ]
kenneth.daily@sagebase.org
8cc937b31dbeb51c1d972914b85d8a535d8f2af0
a6afede30aaa5f0cdffe732333672fa408cffac2
/pmaf/pipe/agents/__init__.py
a1df624a4ed79c0a2a9ed018869483508966cb39
[ "BSD-3-Clause" ]
permissive
mmtechslv/PhyloMAF
f788bda21cec31381b6d900afae6461f4d4fd962
028364e018f5f22a89aef9d4a86df9ba706747b5
refs/heads/master
2023-04-12T11:28:22.471600
2022-04-23T22:05:05
2022-04-23T22:05:05
197,987,819
1
0
BSD-3-Clause
2021-06-28T12:02:47
2019-07-20T22:41:45
Python
UTF-8
Python
false
false
558
py
r""" Pipe Agents (:mod:`pmaf.pipe.agents`) ===================================== .. currentmodule:: pmaf.pipe.agents .. rubric:: Working with data mining pipelines This sub-package :mod:`~pmaf.pipe.agents` contains classes for transitional data management, mediator classes for remote and local databases and data main miner class. Agents (Packages) ----------------- .. autosummary:: :toctree: dockers mediators miners """ from . import dockers from . import mediators from . import miners __all__ = ["dockers", "mediators", "miners"]
[ "mmtechslv@gmail.com" ]
mmtechslv@gmail.com
2ca581f03723a412af5d5b6230e228539380cfd6
0d86c841c5a42dd3d2626a4170208d51b016970b
/prac06/KivyDemos-master/simple_animation_demo.py
3f6f5d08ae18651e3c6678cbb07f4b65d8ab2232
[]
no_license
joellimrl/Practicals
af0622798e3fdf8f4fbac8730f410777271d198c
46b4617d75cb6a9507f1172e58670ac70b3a173c
refs/heads/master
2021-01-02T09:18:58.609397
2017-09-28T07:41:21
2017-09-28T07:41:21
99,191,856
1
0
null
2017-08-17T04:40:50
2017-08-03T04:49:59
Python
UTF-8
Python
false
false
1,099
py
from kivy.app import App from kivy.lang import Builder from kivy.properties import StringProperty from kivy.clock import Clock from kivy.graphics import Ellipse, Rectangle from kivy.core.window import Window from kivy.graphics import Color class SimpleAnimation(App): info_message = StringProperty() def __init__(self, **kwargs): super(SimpleAnimation, self).__init__(**kwargs) Window.size = (500, 300) self.ball = None def build(self): Clock.schedule_interval(self.update, 1) self.root = Builder.load_file("simple_animation_demo.kv") self.ball = Ellipse() self.ball.size = (100, 100) self.ball.pos = 20, 20 self.root.canvas.add(Color(1, 0, 0, 1)) self.root.canvas.add(self.ball) self.root.canvas.add(Color(1, 1, 0, 1)) self.root.canvas.add(Rectangle()) return self.root def update(self, dt): self.info_message = '{:.5f}'.format(dt) x, y = self.ball.pos self.ball.pos = x + 1, y if __name__ == '__main__': app = SimpleAnimation() app.run()
[ "joellimruili@gmail.com" ]
joellimruili@gmail.com
e34dd61a178f3d66f14a823d2a80342f6c313852
0a3291bca919394d7537ab1533fd996d86b17ac2
/edb/server/ha/stolon.py
0d7e527a13a3e5e48c5fccd6afa9b0dda2072510
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
parampavar/edgedb
06c8254620737fce25bc7b0597f286857cb71616
8811ff35a7c1ede673c5aefdbc4167eda1c89107
refs/heads/master
2023-08-09T18:46:26.187456
2023-08-08T15:14:57
2023-08-08T15:14:57
186,318,764
0
0
Apache-2.0
2023-09-14T21:40:48
2019-05-13T00:23:43
Python
UTF-8
Python
false
false
5,386
py
# # This source file is part of the EdgeDB open source project. # # Copyright 2021-present MagicStack Inc. and the EdgeDB authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import annotations from typing import * import asyncio import base64 import functools import json import logging import ssl import urllib.parse from edb.common import asyncwatcher from edb.server import consul from . import base logger = logging.getLogger("edb.server") class StolonBackend(base.HABackend): _master_addr: Optional[Tuple[str, int]] def __init__(self) -> None: super().__init__() self._master_addr = None async def get_cluster_consensus(self) -> Tuple[str, int]: if self._master_addr is None: started_by_us = await self.start_watching() try: assert self._waiter is None self._waiter = asyncio.get_running_loop().create_future() await self._waiter finally: if started_by_us: self.stop_watching() await self.wait_stopped_watching() assert self._master_addr return self._master_addr def get_master_addr(self) -> Optional[Tuple[str, int]]: return self._master_addr def on_update(self, payload: bytes) -> None: try: data = json.loads(base64.b64decode(payload)) except (TypeError, ValueError): logger.exception(f"could not decode Stolon cluster data") return # Successful Consul response, reset retry backoff self._retry_attempt = 0 cluster_status = data.get("cluster", {}).get("status", {}) master_db = cluster_status.get("master") cluster_phase = cluster_status.get("phase") if cluster_phase != "normal": logger.debug("Stolon cluster phase: %r", cluster_phase) if not master_db: return master_status = ( data.get("dbs", {}).get(master_db, {}).get("status", {}) ) master_healthy = master_status.get("healthy") if not master_healthy: logger.warning("Stolon reports unhealthy master Postgres.") return master_host = master_status.get("listenAddress") master_port = master_status.get("port") if not master_host or not master_port: return master_addr = master_host, int(master_port) if master_addr != self._master_addr: if self._master_addr is None: logger.info("Discovered master Postgres at %r", master_addr) self._master_addr = master_addr else: logger.critical( f"Switching over the master Postgres from %r to %r", self._master_addr, master_addr, ) self._master_addr = master_addr if self._failover_cb is not None: self._failover_cb() if self._waiter is not None: if not self._waiter.done(): self._waiter.set_result(None) self._waiter = None class StolonConsulBackend(StolonBackend): def __init__( self, cluster_name: str, *, host: str = "127.0.0.1", port: int = 8500, ssl: Optional[ssl.SSLContext] = None, ) -> None: super().__init__() self._cluster_name = cluster_name self._host = host self._port = port self._ssl = ssl async def _start_watching(self) -> asyncwatcher.AsyncWatcherProtocol: _, pr = await asyncio.get_running_loop().create_connection( functools.partial( consul.ConsulKVProtocol, self, self._host, f"stolon/cluster/{self._cluster_name}/clusterdata", ), self._host, self._port, ssl=self._ssl, ) return pr # type: ignore [return-value] def get_backend( sub_scheme: str, parsed_dsn: urllib.parse.ParseResult ) -> StolonBackend: name = parsed_dsn.path.lstrip("/") if not name: raise ValueError("Stolon requires cluster name in the URI as path.") cls = None storage, _, wire_protocol = sub_scheme.partition("+") if storage == "consul": cls = StolonConsulBackend if not cls: raise ValueError(f"{parsed_dsn.scheme} is not supported") if wire_protocol not in {"", "http", "https"}: raise ValueError(f"Wire protocol {wire_protocol} is not supported") args: Dict[str, Any] = {} if parsed_dsn.hostname: args["host"] = parsed_dsn.hostname if parsed_dsn.port: args["port"] = parsed_dsn.port if wire_protocol == "https": args["ssl"] = ssl.create_default_context() return cls(name, **args)
[ "noreply@github.com" ]
parampavar.noreply@github.com
d94f6aca21c32ee0df258e1981ca6b92cbc4b900
12f5bc18984ad30e1a8d4ada001b307ab1d2898e
/Count3.py
553c0048d6290f58fdee575bd6c7cc68c75887ee
[]
no_license
abarnaramaraj/count3
30433cf07c2a20fbc072addc94becd73bb9beab8
8b1e75a5d3255166094bf6e3a07354de6e83e840
refs/heads/master
2020-04-29T15:52:38.735035
2019-03-18T09:02:02
2019-03-18T09:02:02
176,242,195
0
0
null
null
null
null
UTF-8
Python
false
false
88
py
count=0 number=int(input("number")) while(num!=0) count++ num=num/10 print("number is")
[ "noreply@github.com" ]
abarnaramaraj.noreply@github.com
adbc8ad555b360cc9ec1f1b00bc29886237bb6b2
7f6d742e5be59cfbab2d9742eeb46130e84e6f96
/app1/migrations/0004_newlicence_photo.py
74add6f3a9139bcad7ef8f347081bbe8d414de19
[]
no_license
Alokv5/E_mandi
3cf49704128a9678f03ccc4fedd2deeab830c637
d5f5fcf259661bdd3878a4ade592bca43446adf7
refs/heads/master
2022-12-07T06:39:25.204862
2020-08-30T18:16:39
2020-08-30T18:16:39
291,526,720
0
0
null
null
null
null
UTF-8
Python
false
false
405
py
# Generated by Django 3.1 on 2020-08-16 17:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app1', '0003_auto_20200814_2151'), ] operations = [ migrations.AddField( model_name='newlicence', name='photo', field=models.ImageField(default=False, upload_to='product/'), ), ]
[ "vermaalok007@gmail.com" ]
vermaalok007@gmail.com
60bd09afebd2a97319aa608a6ee44a7fd37b29a0
53bd30eee243a73bf19921739454a177a8bab127
/excapp/migrations/0002_datahistory.py
31da2844c89998a546d9f612985ee6253eeef234
[]
no_license
kirigaikabuto/bck
61697fbe2edd7e4f5b866628a368693a05f6dad9
2b17f8c5d438248d73aaf9dbebd3d5dea827a42d
refs/heads/master
2021-02-04T01:20:06.470527
2021-01-04T15:24:13
2021-01-04T15:24:13
243,593,240
0
0
null
2020-06-06T01:30:15
2020-02-27T18:55:15
Python
UTF-8
Python
false
false
745
py
# Generated by Django 2.2.10 on 2020-11-24 18:51 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('excapp', '0001_initial'), ] operations = [ migrations.CreateModel( name='DataHistory', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('child', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='child', to='excapp.Data')), ('parent', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='parent', to='excapp.Data')), ], ), ]
[ "ytleugazy@dar.kz" ]
ytleugazy@dar.kz
882a480400364fb93696d119447567a1baae6749
7b92157818d1d4f05a74fcc3e373eebeab4897cd
/semana1/quick_find.py
6c7073c0b709532726d1fa2d3901880d4adae7f6
[]
no_license
SabinoGs/algorithms
cc32ec1538c00a04166a77e8458b987227f0a386
326688e9e3e790134809092e4b7f9f5a217e28e9
refs/heads/master
2022-12-05T18:41:41.252629
2020-08-11T20:49:25
2020-08-11T20:49:25
281,818,136
0
0
null
null
null
null
UTF-8
Python
false
false
791
py
class UnionFind(): def __init__(self, n_elementos): self.connected_components_ids = list(range(n_elementos)) self.tamanho_lista = n_elementos def union(self, elemento_a, elemento_b): id_elemento_a = self.connected_components_ids[elemento_a] id_elemento_b = self.connected_components_ids[elemento_b] for i in range(0, self.tamanho_lista): if self.connected_components_ids[i] == id_elemento_a: self.connected_components_ids[i] = id_elemento_b def connected(self, elemento_a, elemento_b): connected = False id_a = self.connected_components_ids[elemento_a] id_b = self.connected_components_ids[elemento_b] if id_a == id_b: connected = True return connected
[ "c1299699@interno.bb.com.br" ]
c1299699@interno.bb.com.br
23399885dc33da95aecac463dd2bfa6138baf944
dc497880445f7fd262c45f1b34c6548cbb299aa7
/sina_weibo/spiders/media.py
e110dfc784c7849cfddef9d2ff13fd6de230adf0
[]
no_license
Maql50/sina_weibo
62edccaef9e19724bc33812bc122506ccf2192ac
f14ad671a0af011c74bcec63fc272b2a4b085bd9
refs/heads/master
2021-05-03T23:38:49.689699
2016-10-24T09:34:25
2016-10-24T09:34:25
71,773,771
0
1
null
null
null
null
UTF-8
Python
false
false
7,754
py
# encoding=utf-8 import re import datetime import socket import logging import pytz import uuid import psycopg2 import urlparse from bs4 import BeautifulSoup as bs from scrapy.selector import Selector from scrapy.http import Request from scrapy.spiders import Spider from scrapy import signals from scrapy.xlib.pydispatch import dispatcher from scrapy.conf import settings from scrapy.exceptions import CloseSpider from sina_weibo.utils import getCookies from sina_weibo.items import InformationItem, FollowsItem from sina_weibo.handlers import PGHandler from sina_weibo.postgres import db from parse_user_detil import get_user_detail, get_uid_by_uname,parse_follows class MediaSpider(Spider): '''爬取媒体汇''' name = "weibo_media" domain = "http://weibo.cn" target = 'weibo' hostname = socket.gethostname() jobtime = datetime.datetime.now() time_record_static = datetime.datetime.now() time_record_dynamic = datetime.datetime.now() cell_id = None job_id = None user_id = None error_found = False ua = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0' cookies = {} handle_httpstatus_list = [302] #媒体汇url,以地区为分类 start_urls = [ 'http://weibo.cn/v2star/?cat=2&sorttype=area' ] time_record_static = datetime.datetime.now() time_record_dynamic = datetime.datetime.now() account = '' password = '' def __init__(self, *args, **kwargs): super(Spider, self).__init__(self.name, *args, **kwargs) dispatcher.connect(self.spider_opened, signals.spider_opened) dispatcher.connect(self.spider_closed, signals.spider_closed) meta_conn_string = ' '.join(["host=", settings['META_DB']['host'], "dbname=", settings['META_DB']['dbname'], \ "user=", settings['META_DB']['user'], "password=", settings['META_DB']['password'], "port=", settings['META_DB']['port']]) self.meta_conn = psycopg2.connect(meta_conn_string) self.meta_conn.autocommit = True self.meta_session = db(self.meta_conn) data_conn_string = ' '.join(["host=", settings['DATA_DB']['host'], "dbname=", settings['DATA_DB']['dbname'], \ "user=", settings['DATA_DB']['user'], "password=", settings['DATA_DB']['password'], "port=", settings['DATA_DB']['port']]) self.data_conn = psycopg2.connect(data_conn_string) self.data_session = db(self.data_conn) resource = self.meta_session.getOne( "select account, password, ua_mobile, download_delay from crawler_resource where host = '%s' and target = '%s'" % ( self.hostname, self.target)) self.account = resource[0] self.password = resource[1] self.cell_name = self.name self.cookies = getCookies(self.account, self.password) self.cell_name = self.name def spider_opened(self, spider): # get stats handler = PGHandler(self.name) handler.setLevel(settings.get('LOG_LEVEL')) logger = logging.getLogger() logger.addHandler(handler) self.dstats = spider.crawler.stats.get_stats() self.collect_stats(status='running') def spider_closed(self, spider): self.data_conn.close() self.collect_stats(status='finished') def parse(self, response): ''' 解析媒体汇url, 以便爬取用户和用户关注的人 ''' #获取每个地区对应的url urls = response.xpath("/html/body/div[5]/a/@href").extract() for url in urls: # 请求每个url对应的页面 self.time_record_dynamic = datetime.datetime.now() if (self.time_record_dynamic - self.time_record_static).seconds > 43200: self.cookies = self.getCookies() self.time_record_static = datetime.datetime.now() self.time_record_dynamic = datetime.datetime.now() yield Request(url = urlparse.urljoin(self.start_urls[0], url), callback=self.parse_each_area) def parse_each_area(self, response): ''' 解析每个地区对应的页面 ''' soup = bs(response.body, 'html.parser') # 获取每个媒体汇的用户id tables = soup.find_all('div', class_='c')[2].find_all('table') for table in tables: uid = table.tr.find_all("td", valign="top")[1].find_all('a')[0]['href'].split('/')[2] # 爬个人信息 yield get_user_detail(uid=uid, cookies=self.cookies) #下页 np = response.css('#pagelist > form:nth-child(1) > div:nth-child(1) > a:nth-child(1)::text') if np and u'下页' == np[0].extract(): url = response.urljoin(response.css('#pagelist > form:nth-child(1) > div:nth-child(1) > a:nth-child(1)::attr(href)')[0].extract()) yield Request(url=url,callback=self.parse_each_area) def collect_stats(self, status): response_count_3xx = None response_count_4xx = None response_count_5xx = None job_stats = {} job_stats['host'] = self.hostname # job_stats['user_id'] = self.user_id # job_stats['cell_id'] = self.cell_id job_stats['cell_name'] = self.name job_stats['item_count'] = self.dstats.get('item_scraped_count', 0) if self.dstats.get('start_time', datetime.datetime.now()): # when job starts in waiting queue job_stats['run_time'] = pytz.utc.localize(self.dstats.get('start_time')) # when job starts running if self.dstats.get('finish_time'): job_stats['end_time'] = pytz.utc.localize(self.dstats.get('finish_time')) if status == 'running': job_stats['status'] = 'running' elif status == 'finished': job_stats['status'] = self.dstats.get('finish_reason', None) if self.error_found or job_stats['item_count'] == 0: job_stats['status'] = 'failed' job_stats['image_count'] = self.dstats.get('image_count') job_stats['image_downloaded'] = self.dstats.get('image_downloaded') job_stats['request_count'] = self.dstats.get('downloader/request_count') job_stats['response_bytes'] = self.dstats.get('downloader/response_bytes') job_stats['response_count'] = self.dstats.get('downloader/response_count') job_stats['response_count_200'] = self.dstats.get('downloader/response_status_count/200') for key, value in self.dstats.iteritems(): if 'downloader/response_status_count/3' in key: job_stats['response_count_3xx'] = int(response_count_3xx or 0) + value elif 'downloader/response_status_count/4' in key: job_stats['response_count_4xx'] = int(response_count_4xx or 0) + value elif 'downloader/response_status_count/5' in key: job_stats['response_count_5xx'] = int(response_count_5xx or 0) + value job_stats['load_time'] = datetime.datetime.now() try: with self.meta_conn: if not self.job_id: self.job_id = uuid.uuid1().hex job_stats['job_id'] = self.job_id job_stats['start_time'] = self.jobtime self.meta_session.Insert(settings['STATS_TABLE'], job_stats) else: wheredict = {} wheredict['job_id'] = self.job_id self.meta_session.Update(settings['STATS_TABLE'], job_stats, wheredict) except psycopg2.Error, e: logging.warn('Failed to refresh job stats: %s' % e)
[ "784567806@qq.com" ]
784567806@qq.com
9f1db4bf64f35377784047cef1b28f075d9ad8c6
31a7bb720dc016911cfcfe59032b79af881bdae8
/users/views.py
abdf996c965064da4ef7529558f01036dd0b1766
[]
no_license
barioder/Learninglog
d24f5282c6c2953b105dce6c1696100da3da3d52
0d33474a37cdb4a0020922ea71ac370967a6ece5
refs/heads/master
2023-01-19T03:20:29.498572
2020-11-25T11:42:36
2020-11-25T11:42:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
538
py
from django.shortcuts import render, redirect from django.contrib.auth import login from django.contrib.auth.forms import UserCreationForm # Create your views here. def register (request): """register new user""" if request.method != 'POST': form = UserCreationForm() else: form = UserCreationForm(data=request.POST) if form.is_valid(): new_user = form.save() login(request, new_user) return redirect ('learnig_logs:index') context = {'form':form} return render (request, 'registration/register.html',context)
[ "barioder27@gmail.com" ]
barioder27@gmail.com
33e6b8fd5dde7b3155a868fa935ea463f9b30003
76201225a7e7f04c803a460a137be27018e5926b
/misc/imgutil.py
d1809bdbd07d2ef4c1cda5233db0cb71fec6df6d
[]
no_license
rahulsharma-rs/DSUtilities
f6b9dc60b7128ccdc3f4024a8bb8cd8fb3d9a5ea
a2e95ae3fd98add388c717982e96e37763f14362
refs/heads/master
2021-08-28T04:26:23.078477
2021-08-12T23:26:40
2021-08-12T23:26:40
215,266,874
0
0
null
null
null
null
UTF-8
Python
false
false
3,225
py
__author__ = 'Rahul' import cv2 import numpy import os """ The module deal with the data in the form of image. The are four methods: 1- imageToArray(<image-path>) : it converts each image into an array of dimension rows*columns. 2- prepImgDataSet(<Dir-path>) : it looks for images in a specific directory and prepares the data set. 3- arrayToImage(<data-array>, <rows>, <columns>): it converts the image array to an image matrix of shape rows x columns. 4- showImage(<image-matrix>): it displays the image corresponding to input matrix. There are three global variable: 1- dataSet : it holds the array of image data 2- rows and columns : it informs about the dimension of the matrix of image. """ rows= None columns= None dataSet= None #method to read the image and convert it into an array def imageToArray(image): #reading the image in gray scale tempImg = cv2.imread(image, cv2.IMREAD_GRAYSCALE) global rows, columns if rows==None and columns==None: rows = tempImg.shape[0] columns = tempImg.shape[1] #detecting number of rows and columns in the image row = tempImg.shape[0] column = tempImg.shape[1] if row==rows and column==columns: # reshaping the image into an array tempImg= cv2.divide(tempImg.astype(float),255.00) imageArray= tempImg.reshape(rows*columns) # temp=numpy.divide(imageArray,255) return imageArray else: print "size mismatch not considering the image" return None def prepImgDataSet(pathOfDir): # listing the images in the directory listing= os.listdir(pathOfDir) # consider only image file extentions fileXten = ('.png', '.jpg', '.jpeg', '.gif','.pgm') dataList=[] for file in listing: #checking the image file extentions if file.endswith(fileXten): tempPath= pathOfDir+"/"+file tempArray= imageToArray(tempPath) if tempArray != None: tempArray =tempArray # normalizing the data between [0 and 1] dataList.append(tempArray) #dataSet = numpy.asarray(dataList) dataSet=dataList return dataSet, rows, columns def arrayToImage(arrayData, rows, columns): #converting the data into a matrix tempMat= arrayData.reshape(rows, columns) return tempMat def showImage(imageMat, scale=1): tempRes=cv2.resize(imageMat,None,fx=scale, fy=scale, interpolation = cv2.INTER_CUBIC) cv2.imshow('result', tempRes) cv2.waitKey(0) cv2.destroyAllWindows() def createImage(path, imageMat, scale=1): tempRes=cv2.resize(imageMat,None,fx=scale, fy=scale, interpolation = cv2.INTER_CUBIC) cv2.imwrite(path,tempRes) def main(path): # call the prepare image data global dataSet, rows, columns dataSet= prepImgDataSet(path) #for each image in the data-set display the image based upon the scale for data in dataSet: imageData= arrayToImage(data, rows, columns) imageData = cv2.multiply(imageData,255) # de-normalizing the data to its original form showImage(imageData,1) print dataSet if __name__=="__main__": path= '/Users/Rahul/PycharmProjects/turtle/testmnist' main(path)
[ "noreply@github.com" ]
rahulsharma-rs.noreply@github.com
24eab8d06975af2c329392f0eabc7cff9649a5a0
330e23aa947048cfab34e888e6e54085810b26ae
/Milestone4/plot.py
4423499a929b8441327a89c35921f8ff07fc0b79
[]
no_license
marenras/AST5220
e7ad2a5fb37740d468f62260f1e30137eb26f33a
783d4ad27c9e1b3c69c35f2c8f39f392360db4dd
refs/heads/master
2022-01-08T21:38:33.670369
2019-06-01T11:48:21
2019-06-01T11:48:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,049
py
import numpy as np import matplotlib.pyplot as plt import sys as sys font = {'family' : 'normal', 'weight' : 'normal', 'size' : 13} plt.rc('font', **font) save = False if len(sys.argv) > 1: if sys.argv[1] in ['save', 'Save']: save = True else: print("Please write 'save' in command line to save the plots.") sys.exit() # Reading in l-values for the tranfer function and the integrand l_values = np.loadtxt('data/l_values.dat', unpack=True) # Reading in power spectra values with the best parameters l, C_l = np.loadtxt('data/CMB_spectrum_best_fit.dat', unpack=True) # Reading in power spectra observed data l_real, CMB_real, ndC, pdC = np.loadtxt('data/COM_PowerSpect_CMB-TT-full_R3.01.txt', unpack=True) # Reading in tranfer function and integrand for 6 values of k theta = [] integrand = [] kcH = [] for k in range(1,7): kcH_, theta_, integrand_ = np.loadtxt('data/theta_integrand_%d.dat' %(k), unpack=True) kcH.append(kcH_) theta.append(theta_) integrand.append(integrand_) fig_CMB = plt.figure() plt.errorbar(l_real, CMB_real, yerr=[ndC,pdC], color='lightblue', label='Observed', zorder=1) plt.plot(l, C_l*5775/max(C_l), label='Best fit') plt.ylabel(r'$l(l+1) C_l / 2 \pi$ [$\mu$K$^2$]') plt.xlabel(r'$l$') plt.legend(loc='best') plt.xlim(l[0], l[-1]) plt.grid() plt.show() fig_theta = plt.figure() for i in range(6): plt.plot(kcH[i], theta[i], label=r'l = %d' %(l_values[i])) plt.ylabel(r'$\Theta_l$') plt.xlabel(r'$ck/H_0$') plt.xlim([-10,500]) plt.legend(loc='best') plt.grid() plt.show() fig_integrand = plt.figure() for i in range(6): plt.plot(kcH[i], integrand[i], label=r'l = %d' %(l_values[i])) plt.ylabel(r'$l(l+1)\Theta_l^2 H_0/ck$') plt.xlabel(r'$ck/H_0$') plt.legend(loc='best') plt.axis([-10,500, -0.0001, 0.0016]) plt.grid() plt.show() if save: fig_CMB.savefig("figures/CMB_best_fit.pdf", bbox_inches='tight') fig_theta.savefig("figures/theta.pdf", bbox_inches='tight') fig_integrand.savefig("figures/integrand.pdf", bbox_inches='tight')
[ "marenr@live.no" ]
marenr@live.no
a112e954dfaf060d989babe6364ee1c3020aa372
99eafe70c42d20e61f219ce7d2659d4a10cde0e2
/src/main.py
0624f746d67fc50f33f8c9635871c49fe963b1b5
[ "Apache-2.0" ]
permissive
Maldini32/DWAVE4TSPLIB
ea57e2c419425a8a75d50a4a634dc5ac03ac61a7
58d5908cf16e08887ad7f30cc941a863aa45b24f
refs/heads/master
2022-06-26T05:36:58.200417
2020-05-08T09:43:26
2020-05-08T09:43:26
262,282,815
1
1
null
null
null
null
UTF-8
Python
false
false
1,803
py
import time import TSP_utilities from dwave_tsp_solver import DWaveTSPSolver def solveTSPinstance(instance): nodes_array = TSP_utilities.readInstance(instance) tsp_matrix = TSP_utilities.get_tsp_matrix(nodes_array) sapi_token = None dwave_url = 'https://cloud.dwavesys.com/sapi' start_time = time.time() bf_start_time = start_time # print("Brute Force solution") # brute_force_solution = TSP_utilities.solve_tsp_brute_force_from_given_node(nodes_array, starting_node) # end_time = time.time() # calculation_time = end_time - start_time # print("Calculation time:", calculation_time) # TSP_utilities.plot_solution('brute_force_' + str(start_time), nodes_array, brute_force_solution) if sapi_token is None or dwave_url is None: print("You cannot run code on DWave without specifying your sapi_token and url") elif len(nodes_array) >= 40: print("This problem size is to big to run on D-Wave.") else: print("DWave solution") start_time = time.time() dwave_solver = DWaveTSPSolver(tsp_matrix, sapi_token=sapi_token, url=dwave_url) dwave_solution, dwave_distribution = dwave_solver.solve_tsp() end_time = time.time() calculation_time = end_time - start_time print("Calculation time:", calculation_time) costs = [(sol, TSP_utilities.calculate_cost(tsp_matrix, sol), dwave_distribution[sol]) for sol in dwave_distribution] solution_cost = TSP_utilities.calculate_cost(tsp_matrix, dwave_solution) print("DWave:", dwave_solution, solution_cost) for cost in costs: print(cost) TSP_utilities.plot_solution('dwave_' + str(bf_start_time), nodes_array, dwave_solution) if __name__ == '__main__': solveTSPinstance("data/burma14.tsp")
[ "noreply@github.com" ]
Maldini32.noreply@github.com
211fd3287065052e7e4aacaec4588629dc97e657
2a2e464904a41efdb43ee5f5c6a7d7b5a088b76a
/dataset/2017_English_final/2017_English_final/GOLD/Subtask_A/train/concat.py
01f1a14e96f82d8bee6c08dc41e6b6b0bded42ea
[ "CC-BY-3.0" ]
permissive
aaka3207/-Justdoit-Twitter-Sentiment-Analysis
2e3172292f6cc61424583908dee7d51ff04eec59
337511a91ce27d6fc28bf92e10f43635f915ce7c
refs/heads/master
2020-04-06T16:26:49.854377
2019-01-04T17:06:54
2019-01-04T17:06:54
157,620,048
0
1
null
null
null
null
UTF-8
Python
false
false
451
py
import glob import pandas as pd path = 'C:/Users/Sir/OneDrive/School/UIC/IDS 472/Final Project/main/dataset/2017_English_final/2017_English_final/GOLD/Subtask_A/train' allFiles = glob.glob(path + "/*.csv") frame = pd.DataFrame() list_ = [] print(allFiles) for file_ in allFiles: df = pd.read_csv(file_,index_col=None, header=0) print(len(df)) list_.append(df) frame = pd.concat(list_, ignore_index=True) frame.to_csv('../train/full.csv')
[ "aakash2@uic.edu" ]
aakash2@uic.edu
3eb335c6ccd891177979caa39fcb1f3045ac3675
205bebf6a2689e1d1125be4a22e6b5b356279175
/inputdata.py
f21a277dd2481f420ebc326364c6ff3d2e4e9b7a
[]
no_license
Pongsakorn0/BasicPython
3647e100887804d72b5c6ab4689caace7e8e5a7b
2a55c7864e780f7ec46acd20e027e5f69095814e
refs/heads/master
2022-04-27T01:05:25.098290
2020-04-26T08:03:12
2020-04-26T08:03:12
258,975,741
0
0
null
null
null
null
UTF-8
Python
false
false
369
py
# fullname = input("Enter you Name = ") # print(fullname) # age = int(input("Enter you Age =")) # age = 60-age # print(f"คุณจะทำงานอีก{age}ปี") user = input("Enter Username = ").lower pwd = input("Enter Passpord = ") if(user == "admin" and pwd == "1234"): print("Login Succes เย้ ") else: print("Oop ! Login Fail !!!")
[ "pongsakorn@nmu.ac.th" ]
pongsakorn@nmu.ac.th
6ea368b08d4ca10e81eb23b1a04eb415d2d750c7
88830b8dec8782a5355710172e0cc86f37ff950c
/wordcount/views.py
886e2a6ef73e376d9dc6b4efa10d33426371d598
[]
no_license
arcrowe/wordcount
17a472b899e138ccf79b551451e0ddca00a12996
4541bcef88cab8e167989c67d2fa6c8cedfef8fd
refs/heads/master
2020-11-25T01:18:41.660859
2019-12-16T16:15:22
2019-12-16T16:15:22
228,427,390
0
0
null
null
null
null
UTF-8
Python
false
false
658
py
from django.shortcuts import render import operator def home(request): return render(request, 'home.html') def count(request): fulltext = request.GET['textfield'] print(type(fulltext)) wordlist = fulltext.split() worddictionary = {} for word in wordlist: if word in worddictionary: worddictionary[word] += 1 else: worddictionary[word] = 1 sortedwords = sorted(worddictionary.items(), key=operator.itemgetter(1), reverse=True) return render(request, 'count.html', {'fulltext': fulltext, 'worddictionary': sortedwords}) def about(request): return render(request, 'about.html')
[ "alisa_crowe@hotmail.com" ]
alisa_crowe@hotmail.com
095a21f6e7e82a88a8fae7ce3fa8b0c6adccd2dd
dd7cd2d6f613cb7ed1fd1fb917cb351e19db46dd
/week8/codingbat/list-1/make_pi.py
009f45f2d14784488bdf27cd4bd54aa591d2318f
[]
no_license
ashkeyevli/webdevelopment
0da187b25f669ff00c2de9662d5d28cde6ad270c
57f32b384af80780f2578f109357c9451c7fc840
refs/heads/master
2023-01-24T03:14:08.574052
2020-04-18T02:19:08
2020-04-18T02:19:08
239,058,404
1
0
null
2023-01-07T15:29:57
2020-02-08T02:40:35
Python
UTF-8
Python
false
false
32
py
def make_pi(): return [3,1,4]
[ "ashkeyevli@gmail.com" ]
ashkeyevli@gmail.com
62b9d4fd5cdfa4dc38dfaf1807ea2d7d8a8c0b8c
5f288c3f5e4cae74350b7f82f59e291813c5ae80
/recommender.py
8ca6ec77f656843f8b1ebefa3a7a991037910335
[]
no_license
CAVINNN/Recommender-OpenRice
6e23562c7069c3db08572e1e4da76c34980e8059
b76add444d0e08751322bc31629e4e6c0ac79cd4
refs/heads/master
2020-05-31T08:59:46.809696
2019-09-22T03:14:29
2019-09-22T03:14:29
190,199,402
3
0
null
null
null
null
UTF-8
Python
false
false
12,670
py
import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer class UserCF: def __init__(self, rating_data): self.__rating_data = rating_data def get_user_rating_average(self, user): user_ratings_sum = 0 for rating in self.__rating_data[user].values(): user_ratings_sum += rating return user_ratings_sum / len(self.__rating_data[user]) def similarity_cosine(self, user1, user2): # Get related rating keys among two users related_rating_keys = list() for key in self.__rating_data[user2]: if key in self.__rating_data[user1]: related_rating_keys.append(key) # Accumulated sum of (r1 * r2) if len(related_rating_keys) != 0: users_mul_sum = 0 for key in related_rating_keys: users_mul_sum += self.__rating_data[user1][key] * self.__rating_data[user2][key] # Sqrt of accumulated sum of (r1^2) user1_sq_sum_sqrt = 0 for key in related_rating_keys: user1_sq_sum_sqrt += np.square(self.__rating_data[user1][key]) user1_sq_sum_sqrt = np.sqrt(user1_sq_sum_sqrt) # Sqrt of accumulated sum of (r2^2) user2_sq_sum_sqrt = 0 for key in related_rating_keys: user2_sq_sum_sqrt += np.square(self.__rating_data[user2][key]) user2_sq_sum_sqrt = np.sqrt(user2_sq_sum_sqrt) return users_mul_sum / (user1_sq_sum_sqrt * user2_sq_sum_sqrt) else: return 0 def similarity_pearson(self, user1, user2): # Get related rating keys among two users related_rating_keys = list() if len(self.__rating_data[user1]) >= len(self.__rating_data[user2]): for key in self.__rating_data[user1]: if key in self.__rating_data[user2]: related_rating_keys.append(key) else: for key in self.__rating_data[user2]: if key in self.__rating_data[user1]: related_rating_keys.append(key) # Accumulated sum of ((r1 - avg_u1) * (r2 - avg_u2)) subavgs_mul_sum = 0 for key in related_rating_keys: subavgs_mul_sum += (self.__rating_data[user1][key] - self.get_user_rating_average(self.__rating_data, user1)) * ( self.__rating_data[user2][key] - self.get_user_rating_average(self.__rating_data, user2)) # Sqrt of accumulated sum of ((r1 - avg_u1)^2) user1_subavg_sq_sum_sqrt = 0 for key in related_rating_keys: user1_subavg_sq_sum_sqrt += np.square(self.__rating_data[user1][key] - self.get_user_rating_average(self.__rating_data, user1)) user1_subavg_sq_sum_sqrt = np.sqrt(user1_subavg_sq_sum_sqrt) # Sqrt of accumulated sum of ((r2 - avg_u2)^2) user2_subavg_sq_sum_sqrt = 0 for key in related_rating_keys: user2_subavg_sq_sum_sqrt += np.square(self.__rating_data[user2][key] - self.get_user_rating_average(self.__rating_data, user2)) user2_subavg_sq_sum_sqrt = np.sqrt(user2_subavg_sq_sum_sqrt) return subavgs_mul_sum / (user1_subavg_sq_sum_sqrt * user2_subavg_sq_sum_sqrt) def top_match_users(self, user, similarity_method): similar_users = list() for rating_user in self.__rating_data: if rating_user == user: continue else: similar_user = (similarity_method(rating_user, user), rating_user) similar_users.append(similar_user) similar_users.sort() similar_users.reverse() if similar_users[0][0] == 0: return [] else: return similar_users def recommend(self, user, matched_users): # Items not rated(not viewed) by the user no_rating_items_set = set() for matched_user in matched_users: no_rating_items_set = no_rating_items_set | set(self.__rating_data[matched_user[1]].keys()) no_rating_items_set = no_rating_items_set - set(self.__rating_data[user].keys()) # User's average ratings user_rating_avg = self.get_user_rating_average(user) # Get recommended items with rating recommend_items = list() for item in no_rating_items_set: # Get Users who has rated the item evaluated_users = list() for matched_user in matched_users: if item in self.__rating_data[matched_user[1]]: evaluated_users.append(matched_user) # Sum of similarity similarity_sum = 0 for evaluated_user in evaluated_users: similarity_sum += evaluated_user[0] # Sum of similarity weighted average similarity_weighted_average = 0 for evaluated_user in evaluated_users: subavg = self.__rating_data[evaluated_user[1]][item] - self.get_user_rating_average(evaluated_user[1]) similarity_weighted_average += ((evaluated_user[0] * subavg) / similarity_sum) item_predict_rating = (user_rating_avg + similarity_weighted_average, item) recommend_items.append(item_predict_rating) recommend_items.sort() recommend_items.reverse() return recommend_items def get_recommend(self, user): match_users = list() for match_user in self.top_match_users(user, self.similarity_cosine): if match_user[0] > 0: match_users.append(match_user) return self.recommend(user, match_users) class ItemCF: def __init__(self, rating_data): self.__rating_data = rating_data def get_item_rating_average(self, item): item_ratings_sum = 0 item_ratings_len = 0 for user_key in self.__rating_data: for item_key in self.__rating_data[user_key]: if item_key == item: item_ratings_len += 1 item_ratings_sum += self.__rating_data[user_key][item_key] return item_ratings_sum / item_ratings_len def similarity_cosine(self, item1, item2): items_mul_sum = 0 item1_sq_sum_sqrt = 0 item2_sq_sum_sqrt = 0 for user_key in self.__rating_data: if item1 in self.__rating_data[user_key] and item2 in self.__rating_data[user_key]: items_mul_sum += self.__rating_data[user_key][item1] * self.__rating_data[user_key][item2] item1_sq_sum_sqrt += np.square(self.__rating_data[user_key][item1]) item2_sq_sum_sqrt += np.square(self.__rating_data[user_key][item2]) if item1_sq_sum_sqrt != 0 and item2_sq_sum_sqrt != 0: item1_sq_sum_sqrt = np.sqrt(item1_sq_sum_sqrt) item2_sq_sum_sqrt = np.sqrt(item2_sq_sum_sqrt) return items_mul_sum / (item1_sq_sum_sqrt * item2_sq_sum_sqrt) else: return 0 def similarity_pearson(self, item1, item2): subavgs_mul_sum = 0 item1_subavg_sq_sum_sqrt = 0 item2_subavg_sq_sum_sqrt = 0 for user_key in self.__rating_data: if item1 in self.__rating_data[user_key] and item2 in self.__rating_data[user_key]: subavgs_mul_sum += (self.__rating_data[user_key][item1] - self.get_item_rating_average(item1)) * ( self.__rating_data[user_key][item2] - self.get_item_rating_average(item2)) item1_subavg_sq_sum_sqrt += np.square( self.__rating_data[user_key][item1] - self.get_item_rating_average(item1)) item2_subavg_sq_sum_sqrt += np.square( self.__rating_data[user_key][item2] - self.get_item_rating_average(item2)) item1_subavg_sq_sum_sqrt = np.sqrt(item1_subavg_sq_sum_sqrt) item2_subavg_sq_sum_sqrt = np.sqrt(item2_subavg_sq_sum_sqrt) return subavgs_mul_sum / (item1_subavg_sq_sum_sqrt * item2_subavg_sq_sum_sqrt) def top_match_items(self, item, similarity_method): items_set = set() for user_key in self.__rating_data: items_set = items_set | set(self.__rating_data[user_key].keys()) similar_items = list() for match_item in items_set: if match_item == item: continue else: similar_item = (similarity_method(item, match_item), match_item) similar_items.append(similar_item) similar_items.sort() similar_items.reverse() if similar_items[0][0] == 0: return [] else: return similar_items def recommend(self, item, matched_items): # Users who do not rated(not viewed) the item no_rating_user_list = list() for user_key in self.__rating_data: if item not in self.__rating_data[user_key]: no_rating_user_list.append(user_key) item_rating_avg = self.get_item_rating_average(item) recommend_users = list() for no_rating_user in no_rating_user_list: evaluated_items = list() for matched_item in matched_items: if matched_item[1] in self.__rating_data[no_rating_user]: evaluated_items.append(matched_item) similarity_sum = 0 for evaluated_item in evaluated_items: similarity_sum += evaluated_item[0] similarity_weighted_average = 0 for evaluated_item in evaluated_items: subavg = self.__rating_data[no_rating_user][evaluated_item[1]] - self.get_item_rating_average( evaluated_item[1]) similarity_weighted_average += ((evaluated_item[0] * subavg) / similarity_sum) user_predict_rating = (item_rating_avg + similarity_weighted_average, no_rating_user) recommend_users.append(user_predict_rating) recommend_users.sort() recommend_users.reverse() return recommend_users def get_recommend(self, item): match_items = list() for match_item in self.top_match_items(item, self.similarity_cosine): if match_item[0] > 0: match_items.append(match_item) return self.recommend(item, match_items) class ContentBased: def __init__(self, rating_data, item_names, texts): self.__rating_data = rating_data vectorizer = TfidfVectorizer() tf_idf = vectorizer.fit_transform(texts).toarray() items_tfidf_dic = {} for index in range(len(tf_idf)): name = item_names[index] items_tfidf_dic[name] = tf_idf[index] self.__tfidf_dic = items_tfidf_dic def similarity_cosine(self, item1, item2): if len(item1) == len(item2): features_length = len(item1) else: print('Error in similarity_cosine, len(item1) not equals to len(item2)') return 0 items_mul_sum = 0 for feature_index in range(features_length): items_mul_sum += item1[feature_index] * item2[feature_index] item1_sq_sum_sqrt = 0 for feature_index in range(features_length): item1_sq_sum_sqrt += np.square(item1[feature_index]) item1_sq_sum_sqrt = np.sqrt(item1_sq_sum_sqrt) item2_sq_sum_sqrt = 0 for feature_index in range(features_length): item2_sq_sum_sqrt += np.square(item2[feature_index]) item2_sq_sum_sqrt = np.sqrt(item2_sq_sum_sqrt) return items_mul_sum / (item1_sq_sum_sqrt * item2_sq_sum_sqrt) def get_recommend(self, user): # Get sorted user rated list (high -> low) user_rating_list = list() for key in self.__rating_data[user]: rating_tuple = (self.__rating_data[user][key], key) user_rating_list.append(rating_tuple) user_rating_list.sort() user_rating_list.reverse() # Calculate similarity_cosine between fav_item and all other items fav_item = user_rating_list[0][1] recommend_list = list() for item_name in self.__tfidf_dic: if item_name != fav_item: tup = (self.similarity_cosine(self.__tfidf_dic[fav_item], self.__tfidf_dic[item_name]), item_name) recommend_list.append(tup) recommend_list.sort() recommend_list.reverse() # Get items which similarity_cosine > 0 recommend_items = list() for item in recommend_list: # if item[0] > 0: recommend_items.append(item) return recommend_items
[ "huang459546683@126.com" ]
huang459546683@126.com
7fde8b17edaadfc3aec1ce8efdfd7551140b67d2
273933aa74fc0507ad339fa55953c4e153b954ac
/ontologies_for_eval/evaluators/cf_results3/csv_read_subclass.py
344f364e8cd22c441a349cf454b0b1cc9aa8370c
[]
no_license
UcompWu1/Gwap-Protege-Plugin
d4075eda11c550309c11f813497762e2de0e01a2
030ee33daa6bdcd534b1e3cc199f7d996484f82a
refs/heads/master
2021-01-20T02:47:41.076284
2015-09-08T12:09:01
2015-09-08T12:09:01
41,797,772
2
0
null
null
null
null
UTF-8
Python
false
false
934
py
import csv,pickle,re FN='euro_sc.csv' FN='cc_sc.csv' RESULTCOL=6 QUESTIONCOL=8 results = {} pattern = "Is class (.*) a subclass of (.*)\?$" with open(FN, 'rb') as csvfile: csvr = csv.reader(csvfile) for row in csvr: print row # extract concepts from question q = row[QUESTIONCOL] if not q.find("subclass of")>0: continue print q concepta = re.search(pattern, q).group(1) conceptb = re.search(pattern, q).group(2) print concepta, conceptb if row[RESULTCOL] == "1": value = "true" elif row[RESULTCOL] == "2": value = "false" else: sys.exit("ERROR") results[concepta+"-"+conceptb] = value print results, len(results) for key in sorted(results): print key, results[key] pickle.dump(results, open(FN[:-6]+"subclass.pickle", "wb"))
[ "matthias.karacsonyi@gmail.com" ]
matthias.karacsonyi@gmail.com
7ed193e2cf057af1052cb581441a3c055b4c9f3b
6ebd4c6ab578a720d490013103503db2d1d6d620
/imagerieNumerique/TP_11/exercice_6.py
ea8f5e76ba6d88a550b332f4947d870041c652a8
[]
no_license
Joao-Quinta/Uni3eme_2
3ed1dda3b184fb4c9297999f355d38adda5ca50f
b08b4bfc1a6c8a50b8d9f9b010f890b4dd72c99e
refs/heads/master
2023-08-07T20:26:46.770341
2021-09-18T10:35:48
2021-09-18T10:35:48
343,127,229
0
0
null
null
null
null
UTF-8
Python
false
false
1,239
py
import numpy as np import lib import scipy.signal as sciSi import time # load images path = "img_001.jpg" path2 = "img_002.jpg" image1 = lib.loadImag(path) image2 = lib.loadImag(path2) # (a) start_a = time.time() dim1 = image1.shape dim2 = image2.shape dimRes = np.add(dim1, dim2) dimRes[0] = dimRes[0] - 1 dimRes[1] = dimRes[1] - 1 image2_flip_v = lib.matrixflip(image2, 'v') image2_flip_h_v = lib.matrixflip(image2_flip_v, 'h') pad1 = np.pad(image1, ((0, dimRes[0] - dim1[0]), (0, dimRes[1] - dim1[1]))) # image 1 padded pad2 = np.pad(image2_flip_h_v, ((0, dimRes[0] - dim2[0]), (0, dimRes[1] - dim2[1]))) # image 2 flipped and padded fft1 = np.fft.fft2(pad1) fft2 = np.fft.fft2(pad2) res = np.fft.ifft2(np.multiply(fft1, fft2)).real end_a = time.time() imagesToPlot = [res] label = ["exo 6 a"] lib.affichage_rows_cols_images(1, 1, imagesToPlot, label) # (b) image1b = image1 image2b = image2 start_b = time.time() image1b = image1b - image1b.mean() image2b = image2b - image2b.mean() res = sciSi.correlate2d(image1b, image2b) imagesToPlot = [res] label = ["image Lena"] lib.affichage_rows_cols_images(1, 1, imagesToPlot, label) end_b = time.time() # (c) print("A : ", end_a - start_a) print("B : ", end_b - start_b)
[ "56771749+Joao-Quinta@users.noreply.github.com" ]
56771749+Joao-Quinta@users.noreply.github.com
2ceb58fa369f15f7bf5f6b071cd36852ba00f592
55e84078f99314a896c770de5656eb95af5f4306
/detector/models/highlight_detector.py
ad54f23412633dad77c9313f062941035f2ac62f
[]
no_license
yongseongkim/highlight-generator
5c6dddc93a04186c191fd0d79dab9cd6196a5999
fc1e6ffcbe81ecbac4df9dd8b338880620707197
refs/heads/master
2022-12-14T23:01:51.395814
2020-02-28T05:11:11
2020-02-28T05:11:11
177,134,927
0
0
null
null
null
null
UTF-8
Python
false
false
1,082
py
import torch import torch.nn as nn import torchvision.models as models class HighlightDetector(nn.Module): def __init__(self, features_dim, hidden_dim, layer_dim, resnet_pretrained): super(HighlightDetector, self).__init__() self.features_dim = features_dim self.hidden_dim = hidden_dim self.layer_dim = layer_dim # 7장 중 하이라이트 장면에 포함되는 만큼 점수를 준다. ex) 10장 중 5장이 하이라이트 장면이면 output = 5 self.lstm = nn.LSTM(features_dim, hidden_dim, layer_dim) self.resnet = models.resnet18(pretrained=resnet_pretrained) self.resnet.fc = nn.Linear(512, features_dim) self.h2o = nn.Linear(hidden_dim, 1) def forward(self, imgs): batch_size, timesteps, C, H, W = imgs.size() resnet_in = imgs.view(batch_size * timesteps, C, H, W) resnet_out = self.resnet(resnet_in) features = resnet_out.view(batch_size, timesteps, -1) out, (hn, cn) = self.lstm(features) out = self.h2o(out[:, -1, :]) return out
[ "kys911015@gmail.com" ]
kys911015@gmail.com
af6883b7703006259952eb513f37b36b23b451e7
9842515c4472d602b5fe289ea7bf957afa2ecf85
/newapp/models.py
d224dbd693c6eb122e9f74ace3188faa62e7ce38
[]
no_license
Psbrar95/movierentingapp
ef3a9c9edc5f2da4ee8a7cbee368ec20b35c254b
68e6f4e8add5be962adc6bda0c529d09001bcaae
refs/heads/master
2020-03-28T13:13:10.270477
2018-09-11T20:30:02
2018-09-11T20:30:02
148,375,828
0
0
null
null
null
null
UTF-8
Python
false
false
788
py
from django.db import models # Create your models here. class Movies(models.Model): name = models.CharField(max_length= 150) genre= models.CharField(max_length= 30) price= models.DecimalField(max_digits=6, decimal_places=2) year = models.IntegerField() isRented= models.BooleanField(default=False) def __str__(self): return self.name class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone_number= models.CharField(max_length=40,null=True) address = models.CharField(max_length= 300,null=True) email = models.CharField(max_length= 100,null=True) movie = models.ForeignKey(Movies,on_delete=models.CASCADE,null = True,blank = True) def __str__(self): return self.first_name +" "+ self.last_name
[ "psbrar1995@gmail.com" ]
psbrar1995@gmail.com
f4ed214197c7fb0340760d7278d4c8314219063d
fbfbeba195653199d949a8c00ae6f0668f412ea6
/src/king_phisher/testing.py
7e8a5cc26719ac4b69e6543961d398060fead3a8
[ "BSD-3-Clause" ]
permissive
haxxer23/testor
0e07ab3abe58e635e0b10a86b77f5922fc59c4fa
b53f219c1e9a8d244b3403069ff3b57a4a78c870
refs/heads/master
2021-01-20T13:39:11.542572
2017-05-07T17:47:47
2017-05-07T17:47:47
90,511,387
1
0
null
null
null
null
UTF-8
Python
false
false
10,438
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # king_phisher/testing.py # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of the project nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # import functools import os import sys import threading import time import urllib from king_phisher import find from king_phisher.client import client_rpc from king_phisher.server import build from king_phisher.server import plugins from king_phisher.server import rest_api from king_phisher.server import server import advancedhttpserver import smoke_zephyr.configuration import smoke_zephyr.utilities if sys.version_info[0] < 3: import httplib http = type('http', (), {'client': httplib}) import urlparse urllib.parse = urlparse urllib.parse.urlencode = urllib.urlencode else: import http.client import urllib.parse # pylint: disable=ungrouped-imports __all__ = ( 'TEST_MESSAGE_TEMPLATE', 'TEST_MESSAGE_TEMPLATE_INLINE_IMAGE', 'KingPhisherTestCase', 'KingPhisherServerTestCase' ) TEST_MESSAGE_TEMPLATE_INLINE_IMAGE = '/path/to/fake/image.png' """A string with the path to a file used as an inline image in the :py:data:`.TEST_MESSAGE_TEMPLATE`.""" TEST_MESSAGE_TEMPLATE = """ <html> <body> Hello {{ client.first_name }} {{ client.last_name }},<br /> <br /> Lorem ipsum dolor sit amet, inani assueverit duo ei. Exerci eruditi nominavi ei eum, vim erant recusabo ex, nostro vocibus minimum no his. Omnesque officiis his eu, sensibus consequat per cu. Id modo vidit quo, an has detracto intellegat deseruisse. Vis ut novum solet complectitur, ei mucius tacimates sit. <br /> Duo veniam epicuri cotidieque an, usu vivendum adolescens ei, eu ius soluta minimum voluptua. Eu duo numquam nominavi deterruisset. No pro dico nibh luptatum. Ex eos iriure invenire disputando, sint mutat delenit mei ex. Mundi similique persequeris vim no, usu at natum philosophia. <a href="{{ url.webserver }}">{{ client.company_name }} HR Enroll</a><br /> <br /> {{ inline_image('""" + TEST_MESSAGE_TEMPLATE_INLINE_IMAGE + """') }} {{ tracking_dot_image_tag }} </body> </html> """ """A string representing a message template that can be used for testing.""" def skip_if_offline(test_method): """ A decorator to skip running tests when the KING_PHISHER_TEST_OFFLINE environment variable is set. This allows unit tests which require a internet connection to be skipped when network connectivity is known to be inactive. """ @functools.wraps(test_method) def decorated(self, *args, **kwargs): if os.environ.get('KING_PHISHER_TEST_OFFLINE'): self.skipTest('due to running in offline mode') return test_method(self, *args, **kwargs) return decorated def skip_on_travis(test_method): """ A decorator to skip running a test when executing in the travis-ci environment. """ @functools.wraps(test_method) def decorated(self, *args, **kwargs): if os.environ.get('TRAVIS'): self.skipTest('due to running in travis-ci environment') return test_method(self, *args, **kwargs) return decorated class KingPhisherRequestHandlerTest(server.KingPhisherRequestHandler): def on_init(self, *args, **kwargs): super(KingPhisherRequestHandlerTest, self).on_init(*args, **kwargs) self.rpc_handler_map['^/login$'] = self.rpc_test_login def rpc_test_login(self, username, password, otp=None): return True, 'success', self.server.session_manager.put(username) class KingPhisherTestCase(smoke_zephyr.utilities.TestCase): """ This class provides additional functionality over the built in :py:class:`unittest.TestCase` object, including better compatibility for methods across Python 2.x and Python 3.x. """ def assertIsEmpty(self, obj, msg=None): if len(obj): self.fail(msg or 'the object is not empty') def assertIsNotEmpty(self, obj, msg=None): if not len(obj): self.fail(msg or 'the object is empty') class KingPhisherServerTestCase(KingPhisherTestCase): """ This class can be inherited to automatically set up a King Phisher server instance configured in a way to be suitable for testing purposes. """ def setUp(self): find.data_path_append('data/server') web_root = os.path.join(os.getcwd(), 'data', 'server', 'king_phisher') config = smoke_zephyr.configuration.Configuration(find.data_file('server_config.yml')) config.set('server.address.host', '127.0.0.1') config.set('server.address.port', 0) config.set('server.addresses', []) config.set('server.database', 'sqlite://') config.set('server.geoip.database', os.environ.get('KING_PHISHER_TEST_GEOIP_DB', './GeoLite2-City.mmdb')) config.set('server.web_root', web_root) config.set('server.rest_api.enabled', True) config.set('server.rest_api.token', rest_api.generate_token()) self.config = config self.plugin_manager = plugins.ServerPluginManager(config) self.server = build.server_from_config(config, handler_klass=KingPhisherRequestHandlerTest, plugin_manager=self.plugin_manager) config.set('server.address.port', self.server.sub_servers[0].server_port) self.assertIsInstance(self.server, server.KingPhisherServer) self.server_thread = threading.Thread(target=self.server.serve_forever) self.server_thread.daemon = True self.server_thread.start() self.assertTrue(self.server_thread.is_alive()) self.shutdown_requested = False self.rpc = client_rpc.KingPhisherRPCClient(('localhost', self.config.get('server.address.port'))) self.rpc.login(username='unittest', password='unittest') def assertHTTPStatus(self, http_response, status): """ Check an HTTP response to ensure that the correct HTTP status code is specified. :param http_response: The response object to check. :type http_response: :py:class:`httplib.HTTPResponse` :param int status: The status to check for. """ self.assertIsInstance(http_response, http.client.HTTPResponse) error_message = "HTTP Response received status {0} when {1} was expected".format(http_response.status, status) self.assertEqual(http_response.status, status, msg=error_message) def assertRPCPermissionDenied(self, method, *args, **kwargs): """ Assert that the specified RPC method fails with a :py:exc:`~king_phisher.errors.KingPhisherPermissionError` exception. :param method: The RPC method that is to be tested """ try: self.rpc(method, *args, **kwargs) except advancedhttpserver.RPCError as error: name = error.remote_exception.get('name') if name.endswith('.KingPhisherPermissionError'): return self.fail("the rpc method '{0}' failed".format(method)) self.fail("the rpc method '{0}' granted permissions".format(method)) def http_request(self, resource, method='GET', include_id=True, body=None, headers=None): """ Make an HTTP request to the specified resource on the test server. :param str resource: The resource to send the request to. :param str method: The HTTP method to use for the request. :param bool include_id: Whether to include the the id parameter. :param body: The data to include in the body of the request. :type body: dict, str :param dict headers: The headers to include in the request. :return: The servers HTTP response. :rtype: :py:class:`httplib.HTTPResponse` """ if include_id: if isinstance(include_id, str): id_value = include_id else: id_value = self.config.get('server.secret_id') resource += "{0}id={1}".format('&' if '?' in resource else '?', id_value) conn = http.client.HTTPConnection('localhost', self.config.get('server.address.port')) request_kwargs = {} if isinstance(body, dict): body = urllib.parse.urlencode(body) if body: request_kwargs['body'] = body if headers: request_kwargs['headers'] = headers conn.request(method, resource, **request_kwargs) time.sleep(0.025) response = conn.getresponse() conn.close() return response def web_root_files(self, limit=None, include_templates=True): """ A generator object that yields valid files which are contained in the web root of the test server instance. This can be used to find resources which the server should process as files. The function will fail if no files can be found in the web root. :param int limit: A limit to the number of files to return. :param bool include_templates: Whether or not to include files that might be templates. """ limit = (limit or float('inf')) philes_yielded = 0 web_root = self.config.get('server.web_root') self.assertTrue(os.path.isdir(web_root), msg='The test web root does not exist') philes = (phile for phile in os.listdir(web_root) if os.path.isfile(os.path.join(web_root, phile))) for phile in philes: if not include_templates and os.path.splitext(phile)[1] in ('.txt', '.html'): continue if philes_yielded < limit: yield phile philes_yielded += 1 self.assertGreater(philes_yielded, 0, msg='No files were found in the web root') def tearDown(self): if not self.shutdown_requested: self.assertTrue(self.server_thread.is_alive()) self.server.shutdown() self.server_thread.join(10.0) self.assertFalse(self.server_thread.is_alive()) del self.server
[ "haxxer@gmx.com" ]
haxxer@gmx.com
f9b7ee977762ae5cc9961537a33f3dde790fefac
d24a6e0be809ae3af8bc8daa6dacfc1789d38a84
/ABC/ABC251-300/ABC261/B.py
82b39fd3459c8526f81da79d543af2d50a7983b2
[]
no_license
k-harada/AtCoder
5d8004ce41c5fc6ad6ef90480ef847eaddeea179
02b0a6c92a05c6858b87cb22623ce877c1039f8f
refs/heads/master
2023-08-21T18:55:53.644331
2023-08-05T14:21:25
2023-08-05T14:21:25
184,904,794
9
0
null
2023-05-22T16:29:18
2019-05-04T14:24:18
Python
UTF-8
Python
false
false
547
py
def solve(n, a): for i in range(n - 1): for j in range(i + 1, n): ij = a[i][j] ji = a[j][i] if ij == ji == "D": continue elif ij == "W" and ji == "L": continue elif ij == "L" and ji == "W": continue else: return "incorrect" return "correct" def main(): n = int(input()) a = [list(input()) for _ in range(n)] res = solve(n, a) print(res) if __name__ == "__main__": main()
[ "cashfeg@gmail.com" ]
cashfeg@gmail.com
bff0e29b8c3b1ab2e3738afe90b3e9a7e6bd8e04
652ccf83dec1e4164e6194ccc6baa9beca6ab0a2
/TKinterModules/Frames/Actions.py
ca21261dd5160c9a4ae794fdd77a2bcf30015029
[]
no_license
hajin-song/PaperMarker
069e4558b0e3d872002c3eabcf48614dbc7ddaca
f10b6aac91d7728f22c3c58da9bc29ce8f111e23
refs/heads/master
2021-06-14T06:14:26.508444
2017-05-07T12:19:07
2017-05-07T12:19:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
252
py
from Tkinter import * from ..AppFrame import AppFrame class ActionFrame(AppFrame): def __init__(self, root, parent, row, column, rowspan, columnspan, sticky): AppFrame.__init__(self, root, parent, row, column, rowspan, columnspan, sticky)
[ "hSong6230@gmail.com" ]
hSong6230@gmail.com
1616a02cf31874574e41d98cdc0dba4650eb03cb
d373146aae269c112c76b26be587eb4a7dc52ad6
/scrapers/magnets/settings.py
319c48df9ce246ddd3c8b2156b6070e5c7950687
[]
no_license
manova/dvd_ninja
a0e00054416e11e2af123b152fa794ca63f90664
6f0de1541fb526fba03098f01daa6e742168caf8
refs/heads/master
2020-05-16T03:42:27.696249
2015-01-25T00:38:18
2015-01-25T00:38:18
14,943,072
0
0
null
null
null
null
UTF-8
Python
false
false
605
py
# Scrapy settings for magnets project # # For simplicity, this file contains only the most important settings by # default. All the other settings are documented here: # # http://doc.scrapy.org/en/latest/topics/settings.html # BOT_NAME = 'magnets' SPIDER_MODULES = ['magnets.spiders'] NEWSPIDER_MODULE = 'magnets.spiders' # DEPTH_PRIORITY = 1 # SCHEDULER_DISK_QUEUE = 'scrapy.squeue.PickleFifoDiskQueue' # SCHEDULER_MEMORY_QUEUE = 'scrapy.squeue.FifoMemoryQueue' # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'magnets (+http://www.yourdomain.com)'
[ "eronskoh@gmail.com" ]
eronskoh@gmail.com
1988dbbe35e65a53e16d1e82fcb7233a489c52d7
6c0a94947fb0b8b17d96d1aa1ad2be8d4e822c9b
/creations_app/migrations/0004_delete_usermanager.py
3b7819c68ead51b735d5dc680c583cc0a24ea209
[]
no_license
Orantes-J/solo_project
e17de4d5198dd7b0e133592b03c3e87b67684ac7
75b9fa5bf9f64914e10d971bb1979181bc849c14
refs/heads/main
2023-04-04T10:01:24.450196
2021-04-19T04:56:06
2021-04-19T04:56:06
355,370,353
0
0
null
null
null
null
UTF-8
Python
false
false
297
py
# Generated by Django 2.2 on 2021-04-12 01:27 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('creations_app', '0003_usermanager'), ] operations = [ migrations.DeleteModel( name='UserManager', ), ]
[ "carlos.oran15@hotmail.com" ]
carlos.oran15@hotmail.com
604783e523d181a3faade46c376579c5a709636a
26cc5db81f589bf04c1d6f5e69d4727466af3f5f
/server/api/__init__.py
93a582e7ee0efeb1854e5a3d351c63126c4d386d
[ "MIT" ]
permissive
CSCDP/family-context-api
1c7f6834d2e004dc48622dde68b2f3fc9157ee99
ac3415cdc1ef649c10c85012a2bb2b24ab1d009e
refs/heads/master
2023-01-08T23:33:20.980857
2021-02-18T11:14:03
2021-02-18T11:14:03
213,444,879
3
1
MIT
2022-12-12T08:53:24
2019-10-07T17:26:44
Python
UTF-8
Python
false
false
48
py
from .auth_controller import check_cookie_auth
[ "kaj@k-si.com" ]
kaj@k-si.com
87d17f6d1d22d7a26c40a62f605953a96fae696c
8976a477fa0ff2e99ff215c1a55aebb9407cd8f3
/effects/off.py
a4a0e52757fd54dee672446e5223f904ef4a3394
[]
no_license
DungeonMaestro215/LED_Project
08ff6aebd2b343fa133581919737b8ea1652e0a0
cf43cb445f1310b414c8cc531f9244fa8a9e3320
refs/heads/master
2023-03-09T21:26:13.840014
2020-09-22T01:19:19
2020-09-22T01:19:19
296,741,932
0
0
null
null
null
null
UTF-8
Python
false
false
652
py
# Simple test for NeoPixels on Raspberry Pi import time import board import neopixel # Choose an open pin connected to the Data In of the NeoPixel strip, i.e. board.D18 # NeoPixels must be connected to D10, D12, D18 or D21 to work. pixel_pin = board.D12 # The number of NeoPixels num_pixels = 300 # The order of the pixel colors - RGB or GRB. Some NeoPixels have red and green reversed! # For RGBW NeoPixels, simply change the ORDER to RGBW or GRBW. ORDER = neopixel.GRB pixels = neopixel.NeoPixel( pixel_pin, num_pixels, brightness=0.2, auto_write=False, pixel_order=ORDER ) pixels.fill((0, 0, 0)) pixels.show()
[ "denmas22@live.unc.edu" ]
denmas22@live.unc.edu
b0c0094b7e01d0f65a78b4bb033b61f3f0c3b2ec
2258f3109fa89fcad70437d56db58ba96b4d9061
/app/discount.py
a029ac30da20d7412bb190f8b765c796cdd23de9
[]
no_license
gpsanches/bjss
3a96bf9e74cecab3813968771fd974e574b0f899
3553d9971771db53f6de9ca14333d63700d11d65
refs/heads/master
2022-12-16T18:00:47.053109
2020-09-17T14:54:33
2020-09-17T14:54:33
296,356,509
0
0
null
null
null
null
UTF-8
Python
false
false
816
py
# coding=utf-8 from utils import DiscountTypes class Discount: def __init__(self): self.discount = list() def add(self, value, product, _when_field=None, _when_op=None, _when_value=None, _to=None, discount_type=DiscountTypes.PERCENTAGE.name, description=None): self.discount.append(dict( product=product['name'], value=value, _when_field=_when_field, _when_op=_when_op, _when_value=_when_value, _to=_to, discount_type=discount_type, description=description)) def remove_all_discount(self): self.discount = list() def get_by_product(self, product_name): for i in self.discount: if i.get('product') == product_name: return i return False def get_all(self): return self.discount
[ "guilherme@apprl.com" ]
guilherme@apprl.com
eba55d35dff2a0a5852b658d11ca38c1b60ea428
20c580c52b745ca77ed0036d1b55ceb8234ddc67
/multiAgents.py
27439ef8ededcd0ffec9917403f834da706d47d1
[]
no_license
EricElmoznino/csc384-multiAgents
59924221c08384a4d9d3abc322c4a93e26ec24b4
59f5d99eb636345ca02ba55148acbfaede66ac19
refs/heads/master
2020-03-31T23:59:27.070207
2018-10-22T19:46:36
2018-10-22T19:46:36
152,677,200
0
0
null
null
null
null
UTF-8
Python
false
false
11,310
py
# multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to http://ai.berkeley.edu. # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel (pabbeel@cs.berkeley.edu). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" from util import manhattanDistance if successorGameState.isWin(): return 1000 if successorGameState.isLose(): return -1000 def less_food(s0, s1): f0, f1 = s0.getFood().asList(), s1.getFood().asList() f0, f1 = len(f0), len(f1) return float(f1 < f0) def closest_food(s0, s1): p0, p1 = s0.getPacmanPosition(), s1.getPacmanPosition() f0, f1 = s0.getFood().asList(), s1.getFood().asList() d0, d1 = [manhattanDistance(p0, f) for f in f0], [manhattanDistance(p1, f) for f in f1] d0, d1 = min(d0), min(d1) return float(d1 < d0) def closest_ghost(s0, s1): p0, p1 = s0.getPacmanPosition(), s1.getPacmanPosition() g0, g1 = s0.getGhostStates(), s1.getGhostStates() g0, g1 = [g.getPosition() for g in g0], [g.getPosition() for g in g1] g0, g1 = [manhattanDistance(p0, g) for g in g0], [manhattanDistance(p1, g) for g in g1] if len(g1) == 0 or len(g0) == 0: return 1.0 return float(g1 > g0) lf = 2 * less_food(currentGameState, successorGameState) cf = 1 * closest_food(currentGameState, successorGameState) cg = 0.9 * closest_ghost(currentGameState, successorGameState) return lf + cf + cg def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" def terminal(s, d): return d == 0 or s.isWin() or s.isLose() def df_min_max(s, a, d): bm = None if terminal(s, d): return bm, self.evaluationFunction(s) if a == 0: bv = -1000000 else: bv = 1000000 an = (a + 1) % s.getNumAgents() dn = d - 1 if an == 0 else d for m in s.getLegalActions(a): sn = s.generateSuccessor(a, m) _, v = df_min_max(sn, an, dn) if (a == 0 and bv < v) or (a > 0 and bv > v): bm, bv = m, v return bm, bv return df_min_max(gameState, 0, self.depth)[0] class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" def terminal(s, d): return d == 0 or s.isWin() or s.isLose() def df_min_max(s, a, d, alpha, beta): bm = None if terminal(s, d): return bm, self.evaluationFunction(s) if a == 0: bv = -1000000 else: bv = 1000000 an = (a + 1) % s.getNumAgents() dn = d - 1 if an == 0 else d for m in s.getLegalActions(a): sn = s.generateSuccessor(a, m) _, v = df_min_max(sn, an, dn, alpha, beta) if a == 0: if bv < v: bm, bv = m, v if bv >= beta: return bm, bv alpha = max(alpha, bv) else: if bv > v: bm, bv = m, v if bv <= alpha: return bm, bv beta = min(beta, bv) return bm, bv return df_min_max(gameState, 0, self.depth, -1000000, 1000000)[0] class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" def terminal(s, d): return d == 0 or s.isWin() or s.isLose() def df_min_max(s, a, d): bm = None if terminal(s, d): return bm, self.evaluationFunction(s) if a == 0: bv = -1000000 else: bv = 0 an = (a + 1) % s.getNumAgents() dn = d - 1 if an == 0 else d for m in s.getLegalActions(a): sn = s.generateSuccessor(a, m) _, v = df_min_max(sn, an, dn) if a == 0 and bv < v: bm, bv = m, v elif a > 0: bv += float(v) / len(s.getLegalActions(a)) return bm, bv return df_min_max(gameState, 0, self.depth)[0] def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" from util import manhattanDistance if currentGameState.isWin(): return 1000000 if currentGameState.isLose(): return -1000000 def num_food(s): food = s.getFood().asList() food = len(food) food = 1.0 / food return food def closest_food(s): pos = s.getPacmanPosition() food = s.getFood().asList() dist = [manhattanDistance(pos, f) for f in food] dist = min(dist) return 1.0 / dist def closest_ghost(s): pos = s.getPacmanPosition() ghost = s.getGhostStates() ghost = [g.getPosition() for g in ghost] dist = [manhattanDistance(pos, g) for g in ghost] + [1000000] dist = min(dist) return 1.0 - 1.0 / dist def scared_time(s): ghost = s.getGhostStates() times = [g.scaredTimer for g in ghost] return min(times) score = 1.0 * currentGameState.getScore() / 1000.0 lf = 0.0 * num_food(currentGameState) cf = 0.01 * closest_food(currentGameState) cg = 0.00025 * closest_ghost(currentGameState) st = 0.0005 * scared_time(currentGameState) return score + lf + cf + cg + st # Abbreviation better = betterEvaluationFunction # 1166.8
[ "eric.elmoznino@gmail.com" ]
eric.elmoznino@gmail.com
bd35b81c70ef4fb95a60692a11131c8ebadcc79f
6f70c6c7befd5029d33c6b8e20104e7a3f129f74
/twt_50_2.py
23dc3ebbf8e4f3154a69928100c79817e2a9f24b
[]
no_license
RDornodon/twt_challenges_weekly
31a09726d590d5145457fa56eb1732817c43a9a9
4b4f16c9fe1242efb83861190452f2c8e1275008
refs/heads/main
2023-06-26T03:40:10.090034
2021-07-05T12:27:08
2021-07-05T12:27:08
321,317,607
0
0
null
null
null
null
UTF-8
Python
false
false
291
py
def solution(a:int, b:str, c:int): if b == '+': v = a + b elif b == '-': v = a - b elif b == '*': v = a * b elif b == '/': v = a // b if c else 0 else: raise Exception('it wasn\'t agreed') return v solution=lambda a,c,b:[a*b,a+b,0,a-b,0,b and a//b][ord(c)%6]
[ "archelf.hun@gmail.com" ]
archelf.hun@gmail.com
502c81d8b6af046c1224cd8becc30ebaa34f3b3e
f27f346df9d603b26bb9c20217f9f32114914d86
/recipes/opencv/4.x/conanfile.py
0f9f46f8dac3ec4eb160f77ae372b73da2dd3e71
[ "MIT" ]
permissive
lukaszlaszko/conan-center-index
763c86d642faadbe187cd27e0dee0ff35b71f08e
285a830deccd378151e23da9de3c3c666dfff237
refs/heads/master
2023-04-09T01:30:38.462204
2021-04-20T05:31:18
2021-04-20T05:31:18
351,287,798
0
0
MIT
2021-04-07T23:01:48
2021-03-25T02:41:16
null
UTF-8
Python
false
false
33,885
py
from conans import ConanFile, CMake, tools from conans.errors import ConanInvalidConfiguration import os import textwrap required_conan_version = ">=1.33.0" class OpenCVConan(ConanFile): name = "opencv" license = "Apache-2.0" homepage = "https://opencv.org" description = "OpenCV (Open Source Computer Vision Library)" url = "https://github.com/conan-io/conan-center-index" topics = ("computer-vision", "deep-learning", "image-processing") settings = "os", "compiler", "build_type", "arch" options = { "shared": [True, False], "fPIC": [True, False], "contrib": [True, False], "contrib_freetype": [True, False], "contrib_sfm": [True, False], "parallel": [False, "tbb", "openmp"], "with_jpeg": [False, "libjpeg", "libjpeg-turbo"], "with_png": [True, False], "with_tiff": [True, False], "with_jpeg2000": [False, "jasper", "openjpeg"], "with_openexr": [True, False], "with_eigen": [True, False], "with_webp": [True, False], "with_gtk": [True, False], "with_quirc": [True, False], "with_cuda": [True, False], "with_cublas": [True, False] } default_options = { "shared": False, "fPIC": True, "parallel": False, "contrib": False, "contrib_freetype": False, "contrib_sfm": False, "with_jpeg": "libjpeg", "with_png": True, "with_tiff": True, "with_jpeg2000": "jasper", "with_openexr": True, "with_eigen": True, "with_webp": True, "with_gtk": True, "with_quirc": True, "with_cuda": False, "with_cublas": False } short_paths = True exports_sources = ["CMakeLists.txt", "patches/**"] generators = "cmake", "cmake_find_package" _cmake = None @property def _source_subfolder(self): return "source_subfolder" @property def _build_subfolder(self): return "build_subfolder" @property def _contrib_folder(self): return "contrib" def config_options(self): if self.settings.os == "Windows": del self.options.fPIC if self.settings.os != "Linux": del self.options.with_gtk def configure(self): if self.settings.compiler == "Visual Studio" and \ "MT" in str(self.settings.compiler.runtime) and self.options.shared: raise ConanInvalidConfiguration("Visual Studio and Runtime MT is not supported for shared library.") if self.settings.compiler == "clang" and tools.Version(self.settings.compiler.version) < "4": raise ConanInvalidConfiguration("Clang 3.x can build OpenCV 4.x due an internal bug.") if self.options.shared: del self.options.fPIC if not self.options.contrib: del self.options.contrib_freetype del self.options.contrib_sfm if self.options.with_cuda: raise ConanInvalidConfiguration("contrib must be enabled for cuda") if not self.options.with_cuda: del self.options.with_cublas self.options["libtiff"].jpeg = self.options.with_jpeg self.options["jasper"].with_libjpeg = self.options.with_jpeg if self.settings.os == "Android": self.options.with_openexr = False # disabled because this forces linkage to libc++_shared.so def requirements(self): self.requires("zlib/1.2.11") if self.options.with_jpeg == "libjpeg": self.requires("libjpeg/9d") elif self.options.with_jpeg == "libjpeg-turbo": self.requires("libjpeg-turbo/2.0.6") if self.options.with_jpeg2000 == "jasper": self.requires("jasper/2.0.25") elif self.options.with_jpeg2000 == "openjpeg": self.requires("openjpeg/2.4.0") if self.options.with_png: self.requires("libpng/1.6.37") if self.options.with_openexr: self.requires("openexr/2.5.5") if self.options.with_tiff: self.requires("libtiff/4.2.0") if self.options.with_eigen: self.requires("eigen/3.3.9") if self.options.parallel == "tbb": self.requires("tbb/2020.3") if self.options.with_webp: self.requires("libwebp/1.1.0") if self.options.get_safe("contrib_freetype"): self.requires("freetype/2.10.4") self.requires("harfbuzz/2.7.4") if self.options.get_safe("contrib_sfm"): self.requires("gflags/2.2.2") self.requires("glog/0.4.0") if self.options.with_quirc: self.requires("quirc/1.1") if self.options.get_safe("with_gtk"): self.requires("gtk/system") def source(self): tools.get(**self.conan_data["sources"][self.version][0]) os.rename("opencv-{}".format(self.version), self._source_subfolder) tools.get(**self.conan_data["sources"][self.version][1]) os.rename("opencv_contrib-{}".format(self.version), self._contrib_folder) def _patch_opencv(self): for patch in self.conan_data.get("patches", {}).get(self.version, []): tools.patch(**patch) for directory in ['libjasper', 'libjpeg-turbo', 'libjpeg', 'libpng', 'libtiff', 'libwebp', 'openexr', 'protobuf', 'zlib', 'quirc']: tools.rmdir(os.path.join(self._source_subfolder, '3rdparty', directory)) if self.options.with_openexr: find_openexr = os.path.join(self._source_subfolder, "cmake", "OpenCVFindOpenEXR.cmake") tools.replace_in_file(find_openexr, r'SET(OPENEXR_ROOT "C:/Deploy" CACHE STRING "Path to the OpenEXR \"Deploy\" folder")', "") tools.replace_in_file(find_openexr, "SET(OPENEXR_LIBSEARCH_SUFFIXES x64/Release x64 x64/Debug)", "") tools.replace_in_file(find_openexr, "SET(OPENEXR_LIBSEARCH_SUFFIXES Win32/Release Win32 Win32/Debug)", "") tools.replace_in_file(os.path.join(self._source_subfolder, "CMakeLists.txt"), "ANDROID OR NOT UNIX", "FALSE") tools.replace_in_file(os.path.join(self._source_subfolder, "modules", "imgcodecs", "CMakeLists.txt"), "JASPER_", "Jasper_") def _configure_cmake(self): if self._cmake: return self._cmake self._cmake = CMake(self) self._cmake.definitions["OPENCV_CONFIG_INSTALL_PATH"] = "cmake" self._cmake.definitions["OPENCV_BIN_INSTALL_PATH"] = "bin" self._cmake.definitions["OPENCV_LIB_INSTALL_PATH"] = "lib" self._cmake.definitions["OPENCV_3P_LIB_INSTALL_PATH"] = "lib" self._cmake.definitions["OPENCV_OTHER_INSTALL_PATH"] = "res" self._cmake.definitions["OPENCV_LICENSES_INSTALL_PATH"] = "licenses" self._cmake.definitions["BUILD_CUDA_STUBS"] = False self._cmake.definitions["BUILD_DOCS"] = False self._cmake.definitions["BUILD_EXAMPLES"] = False self._cmake.definitions["BUILD_FAT_JAVA_LIB"] = False self._cmake.definitions["BUILD_IPP_IW"] = False self._cmake.definitions["BUILD_ITT"] = False self._cmake.definitions["BUILD_JASPER"] = False self._cmake.definitions["BUILD_JAVA"] = False self._cmake.definitions["BUILD_JPEG"] = False self._cmake.definitions["BUILD_OPENEXR"] = False self._cmake.definitions["BUILD_OPENJPEG"] = False self._cmake.definitions["BUILD_TESTS"] = False self._cmake.definitions["BUILD_PROTOBUF"] = False self._cmake.definitions["BUILD_PACKAGE"] = False self._cmake.definitions["BUILD_PERF_TESTS"] = False self._cmake.definitions["BUILD_USE_SYMLINKS"] = False self._cmake.definitions["BUILD_opencv_apps"] = False self._cmake.definitions["BUILD_opencv_java"] = False self._cmake.definitions["BUILD_opencv_java_bindings_gen"] = False self._cmake.definitions["BUILD_opencv_js"] = False self._cmake.definitions["BUILD_ZLIB"] = False self._cmake.definitions["BUILD_PNG"] = False self._cmake.definitions["BUILD_TIFF"] = False self._cmake.definitions["BUILD_WEBP"] = False self._cmake.definitions["BUILD_TBB"] = False self._cmake.definitions["OPENCV_FORCE_3RDPARTY_BUILD"] = False self._cmake.definitions["BUILD_opencv_python2"] = False self._cmake.definitions["BUILD_opencv_python3"] = False self._cmake.definitions["BUILD_opencv_python_bindings_g"] = False self._cmake.definitions["BUILD_opencv_python_tests"] = False self._cmake.definitions["BUILD_opencv_ts"] = False self._cmake.definitions["WITH_1394"] = False self._cmake.definitions["WITH_ADE"] = False self._cmake.definitions["WITH_ARAVIS"] = False self._cmake.definitions["WITH_CLP"] = False self._cmake.definitions["WITH_CUFFT"] = False self._cmake.definitions["WITH_NVCUVID"] = False self._cmake.definitions["WITH_FFMPEG"] = False self._cmake.definitions["WITH_GSTREAMER"] = False self._cmake.definitions["WITH_HALIDE"] = False self._cmake.definitions["WITH_HPX"] = False self._cmake.definitions["WITH_IMGCODEC_HDR"] = False self._cmake.definitions["WITH_IMGCODEC_PFM"] = False self._cmake.definitions["WITH_IMGCODEC_PXM"] = False self._cmake.definitions["WITH_IMGCODEC_SUNRASTER"] = False self._cmake.definitions["WITH_INF_ENGINE"] = False self._cmake.definitions["WITH_IPP"] = False self._cmake.definitions["WITH_ITT"] = False self._cmake.definitions["WITH_LIBREALSENSE"] = False self._cmake.definitions["WITH_MFX"] = False self._cmake.definitions["WITH_NGRAPH"] = False self._cmake.definitions["WITH_OPENCL"] = False self._cmake.definitions["WITH_OPENCLAMDBLAS"] = False self._cmake.definitions["WITH_OPENCLAMDFFT"] = False self._cmake.definitions["WITH_OPENCL_SVM"] = False self._cmake.definitions["WITH_OPENGL"] = False self._cmake.definitions["WITH_OPENMP"] = False self._cmake.definitions["WITH_OPENNI"] = False self._cmake.definitions["WITH_OPENNI2"] = False self._cmake.definitions["WITH_OPENVX"] = False self._cmake.definitions["WITH_PLAIDML"] = False self._cmake.definitions["WITH_PROTOBUF"] = False self._cmake.definitions["WITH_PVAPI"] = False self._cmake.definitions["WITH_QT"] = False self._cmake.definitions["WITH_QUIRC"] = False self._cmake.definitions["WITH_V4L"] = False self._cmake.definitions["WITH_VA"] = False self._cmake.definitions["WITH_VA_INTEL"] = False self._cmake.definitions["WITH_VTK"] = False self._cmake.definitions["WITH_VULKAN"] = False self._cmake.definitions["WITH_XIMEA"] = False self._cmake.definitions["WITH_XINE"] = False self._cmake.definitions["WITH_LAPACK"] = False self._cmake.definitions["WITH_GTK"] = self.options.get_safe("with_gtk", False) self._cmake.definitions["WITH_GTK_2_X"] = self.options.get_safe("with_gtk", False) self._cmake.definitions["WITH_WEBP"] = self.options.with_webp self._cmake.definitions["WITH_JPEG"] = self.options.with_jpeg != False self._cmake.definitions["WITH_PNG"] = self.options.with_png self._cmake.definitions["WITH_TIFF"] = self.options.with_tiff self._cmake.definitions["WITH_JASPER"] = self.options.with_jpeg2000 == "jasper" self._cmake.definitions["WITH_OPENJPEG"] = self.options.with_jpeg2000 == "openjpeg" self._cmake.definitions["WITH_OPENEXR"] = self.options.with_openexr self._cmake.definitions["WITH_EIGEN"] = self.options.with_eigen self._cmake.definitions["HAVE_QUIRC"] = self.options.with_quirc # force usage of quirc requirement self._cmake.definitions["WITH_DSHOW"] = self.settings.compiler == "Visual Studio" self._cmake.definitions["WITH_MSMF"] = self.settings.compiler == "Visual Studio" self._cmake.definitions["WITH_MSMF_DXVA"] = self.settings.compiler == "Visual Studio" self._cmake.definitions["OPENCV_MODULES_PUBLIC"] = "opencv" if self.options.contrib: self._cmake.definitions['OPENCV_EXTRA_MODULES_PATH'] = os.path.join(self.build_folder, self._contrib_folder, 'modules') self._cmake.definitions['BUILD_opencv_freetype'] = self.options.get_safe("contrib_freetype", False) self._cmake.definitions['BUILD_opencv_sfm'] = self.options.get_safe("contrib_sfm", False) if self.options.with_openexr: self._cmake.definitions["OPENEXR_ROOT"] = self.deps_cpp_info["openexr"].rootpath if self.options.with_jpeg2000 == "openjpeg": openjpeg_version = tools.Version(self.deps_cpp_info["openjpeg"].version) self._cmake.definitions["OPENJPEG_MAJOR_VERSION"] = openjpeg_version.major self._cmake.definitions["OPENJPEG_MINOR_VERSION"] = openjpeg_version.minor self._cmake.definitions["OPENJPEG_BUILD_VERSION"] = openjpeg_version.patch if self.options.parallel: self._cmake.definitions["WITH_TBB"] = self.options.parallel == "tbb" self._cmake.definitions["WITH_OPENMP"] = self.options.parallel == "openmp" self._cmake.definitions["WITH_CUDA"] = self.options.with_cuda if self.options.with_cuda: # This allows compilation on older GCC/NVCC, otherwise build errors. self._cmake.definitions["CUDA_NVCC_FLAGS"] = "--expt-relaxed-constexpr" self._cmake.definitions["WITH_CUBLAS"] = self.options.get_safe("with_cublas", False) self._cmake.definitions["ENABLE_PIC"] = self.options.get_safe("fPIC", True) if self.settings.compiler == "Visual Studio": self._cmake.definitions["BUILD_WITH_STATIC_CRT"] = "MT" in str(self.settings.compiler.runtime) if self.settings.os == "Android": self._cmake.definitions["ANDROID_STL"] = "c++_static" self._cmake.definitions["ANDROID_NATIVE_API_LEVEL"] = self.settings.os.api_level self._cmake.definitions["ANDROID_ABI"] = tools.to_android_abi(str(self.settings.arch)) self._cmake.definitions["BUILD_ANDROID_EXAMPLES"] = False if "ANDROID_NDK_HOME" in os.environ: self._cmake.definitions["ANDROID_NDK"] = os.environ.get("ANDROID_NDK_HOME") self._cmake.configure(build_folder=self._build_subfolder) return self._cmake def build(self): self._patch_opencv() cmake = self._configure_cmake() cmake.build() def package(self): self.copy("LICENSE", dst="licenses", src=self._source_subfolder) cmake = self._configure_cmake() cmake.install() tools.rmdir(os.path.join(self.package_folder, "cmake")) if os.path.isfile(os.path.join(self.package_folder, "setup_vars_opencv4.cmd")): os.rename(os.path.join(self.package_folder, "setup_vars_opencv4.cmd"), os.path.join(self.package_folder, "res", "setup_vars_opencv4.cmd")) self._create_cmake_module_alias_targets( os.path.join(self.package_folder, self._module_subfolder, self._module_file), {component["target"]:"opencv::{}".format(component["target"]) for component in self._opencv_components} ) @staticmethod def _create_cmake_module_alias_targets(module_file, targets): content = "" for alias, aliased in targets.items(): content += textwrap.dedent("""\ if(TARGET {aliased} AND NOT TARGET {alias}) add_library({alias} INTERFACE IMPORTED) set_property(TARGET {alias} PROPERTY INTERFACE_LINK_LIBRARIES {aliased}) endif() """.format(alias=alias, aliased=aliased)) tools.save(module_file, content) @property def _module_subfolder(self): return os.path.join("lib", "cmake") @property def _module_file(self): return "conan-official-{}-targets.cmake".format(self.name) @property def _opencv_components(self): def imageformats_deps(): components = [] if self.options.with_jpeg2000: components.append("{0}::{0}".format(self.options.with_jpeg2000)) if self.options.with_png: components.append("libpng::libpng") if self.options.with_jpeg: components.append("{0}::{0}".format(self.options.with_jpeg)) if self.options.with_tiff: components.append("libtiff::libtiff") if self.options.with_openexr: components.append("openexr::openexr") if self.options.with_webp: components.append("libwebp::libwebp") return components def eigen(): return ["eigen::eigen"] if self.options.with_eigen else [] def parallel(): if self.options.parallel: return ["tbb::tbb"] if self.options.parallel == "tbb" else ["openmp"] return [] def quirc(): return ["quirc::quirc"] if self.options.with_quirc else [] def gtk(): return ["gtk::gtk"] if self.options.get_safe("with_gtk") else [] def freetype(): return ["freetype::freetype"] if self.options.get_safe("contrib_freetype") else [] def xfeatures2d(): return ["opencv_xfeatures2d"] if self.options.contrib else [] opencv_components = [ {"target": "opencv_core", "lib": "core", "requires": ["zlib::zlib"] + parallel() + eigen()}, {"target": "opencv_flann", "lib": "flann", "requires": ["opencv_core"] + eigen()}, {"target": "opencv_imgproc", "lib": "imgproc", "requires": ["opencv_core"] + eigen()}, {"target": "opencv_ml", "lib": "ml", "requires": ["opencv_core"] + eigen()}, {"target": "opencv_photo", "lib": "photo", "requires": ["opencv_core", "opencv_imgproc"] + eigen()}, {"target": "opencv_features2d", "lib": "features2d", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc"] + eigen()}, {"target": "opencv_imgcodecs", "lib": "imgcodecs", "requires": ["opencv_core", "opencv_imgproc", "zlib::zlib"] + eigen() + imageformats_deps()}, {"target": "opencv_videoio", "lib": "videoio", "requires": ["opencv_core", "opencv_imgproc", "opencv_imgcodecs"] + eigen()}, {"target": "opencv_calib3d", "lib": "calib3d", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_features2d"]+ eigen()}, {"target": "opencv_highgui", "lib": "highgui", "requires": ["opencv_core", "opencv_imgproc", "opencv_imgcodecs", "opencv_videoio"] + freetype() + eigen() + gtk()}, {"target": "opencv_objdetect", "lib": "objdetect", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_features2d", "opencv_calib3d"] + eigen() + quirc()}, {"target": "opencv_stitching", "lib": "stitching", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_features2d", "opencv_calib3d"] + xfeatures2d() + eigen()}, {"target": "opencv_video", "lib": "video", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_features2d", "opencv_calib3d"] + eigen()}, ] if self.options.contrib: opencv_components.extend([ {"target": "opencv_intensity_transform", "lib": "intensity_transform", "requires": ["opencv_core", "opencv_imgproc"] + eigen()}, {"target": "opencv_phase_unwrapping", "lib": "phase_unwrapping", "requires": ["opencv_core", "opencv_imgproc"] + eigen()}, {"target": "opencv_plot", "lib": "plot", "requires": ["opencv_core", "opencv_imgproc"] + eigen()}, {"target": "opencv_quality", "lib": "quality", "requires": ["opencv_core", "opencv_imgproc", "opencv_ml"] + eigen()}, {"target": "opencv_reg", "lib": "reg", "requires": ["opencv_core", "opencv_imgproc"] + eigen()}, {"target": "opencv_surface_matching", "lib": "surface_matching", "requires": ["opencv_core", "opencv_flann"] + eigen()}, {"target": "opencv_xphoto", "lib": "xphoto", "requires": ["opencv_core", "opencv_imgproc", "opencv_photo"] + eigen()}, {"target": "opencv_alphamat", "lib": "alphamat", "requires": ["opencv_core", "opencv_imgproc"] + eigen()}, {"target": "opencv_fuzzy", "lib": "fuzzy", "requires": ["opencv_core", "opencv_imgproc"] + eigen()}, {"target": "opencv_hfs", "lib": "hfs", "requires": ["opencv_core", "opencv_imgproc"] + eigen()}, {"target": "opencv_img_hash", "lib": "img_hash", "requires": ["opencv_core", "opencv_imgproc"] + eigen()}, {"target": "opencv_line_descriptor", "lib": "line_descriptor", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_features2d"] + eigen()}, {"target": "opencv_saliency", "lib": "saliency", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_features2d"] + eigen()}, {"target": "opencv_datasets", "lib": "datasets", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_ml", "opencv_imgcodecs"] + eigen()}, {"target": "opencv_rapid", "lib": "rapid", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_features2d", "opencv_calib3d"] + eigen()}, {"target": "opencv_rgbd", "lib": "rgbd", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_features2d", "opencv_calib3d"] + eigen()}, {"target": "opencv_shape", "lib": "shape", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_features2d", "opencv_calib3d"] + eigen()}, {"target": "opencv_structured_light", "lib": "structured_light", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_phase_unwrapping", "opencv_features2d", "opencv_calib3d"] + eigen()}, {"target": "opencv_videostab", "lib": "videostab", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_photo", "opencv_features2d", "opencv_imgcodecs", "opencv_videoio", "opencv_calib3d", "opencv_video"] + eigen()}, {"target": "opencv_xfeatures2d", "lib": "xfeatures2d", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_ml", "opencv_features2d", "opencv_calib3d", "opencv_shape", ] + eigen()}, {"target": "opencv_ximgproc", "lib": "ximgproc", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_features2d", "opencv_imgcodecs", "opencv_calib3d", "opencv_video"] + eigen()}, {"target": "opencv_xobjdetect", "lib": "xobjdetect", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_features2d", "opencv_imgcodecs", "opencv_calib3d", "opencv_objdetect"] + eigen()}, {"target": "opencv_aruco", "lib": "aruco", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_features2d", "opencv_imgcodecs", "opencv_calib3d"] + eigen()}, {"target": "opencv_bgsegm", "lib": "bgsegm", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_features2d", "opencv_calib3d", "opencv_video"] + eigen()}, {"target": "opencv_bioinspired", "lib": "bioinspired", "requires": ["opencv_core", "opencv_imgproc", "opencv_imgcodecs", "opencv_videoio", "opencv_highgui"] + eigen()}, {"target": "opencv_ccalib", "lib": "ccalib", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_features2d", "opencv_imgcodecs", "opencv_videoio", "opencv_calib3d", "opencv_highgui"] + eigen()}, {"target": "opencv_dpm", "lib": "dpm", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_features2d", "opencv_imgcodecs", "opencv_videoio", "opencv_calib3d", "opencv_highgui", "opencv_objdetect"] + eigen()}, {"target": "opencv_face", "lib": "face", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_photo", "opencv_features2d", "opencv_calib3d", "opencv_objdetect"] + eigen()}, {"target": "opencv_optflow", "lib": "optflow", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_video", "opencv_features2d", "opencv_imgcodecs", "opencv_calib3d", "opencv_video", "opencv_ximgproc"] + eigen()}, {"target": "opencv_superres", "lib": "superres", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_features2d", "opencv_imgcodecs", "opencv_videoio", "opencv_calib3d", "opencv_video", "opencv_ximgproc", "opencv_optflow"] + eigen()}, {"target": "opencv_tracking", "lib": "tracking", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_ml", "opencv_plot", "opencv_features2d", "opencv_imgcodecs", "opencv_calib3d", "opencv_datasets", "opencv_video"] + eigen()}, {"target": "opencv_stereo", "lib": "stereo", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_ml", "opencv_plot", "opencv_features2d", "opencv_imgcodecs", "opencv_calib3d", "opencv_datasets", "opencv_video", "opencv_tracking"] + eigen()}, ]) if self.options.get_safe("contrib_freetype"): opencv_components.extend([ {"target": "opencv_freetype", "lib": "freetype", "requires": ["opencv_core", "opencv_imgproc", "freetype::freetype", "harfbuzz::harfbuzz"] + eigen()}, ]) if self.options.get_safe("contrib_sfm"): opencv_components.extend([ {"target": "opencv_sfm", "lib": "sfm", "requires": ["opencv_core", "opencv_flann", "opencv_imgproc", "opencv_ml", "opencv_features2d", "opencv_imgcodecs", "opencv_calib3d", "opencv_shape", "opencv_xfeatures2d", "correspondence", "multiview", "numeric", "glog::glog", "gflags::gflags"] + eigen()}, {"target": "numeric", "lib": "numeric", "requires": eigen()}, {"target": "correspondence", "lib": "correspondence", "requires": ["multiview", "glog::glog"] + eigen()}, {"target": "multiview", "lib": "multiview", "requires": ["numeric", "gflags::gflags"] + eigen()}, ]) if self.options.with_cuda: opencv_components.extend([ {"target": "opencv_cudaarithm", "lib": "cudaarithm", "requires": ["opencv_core"] + eigen()}, {"target": "opencv_cudabgsegm", "lib": "cudabgsegm", "requires": ["opencv_core", "opencv_video"] + eigen()}, {"target": "opencv_cudacodec", "lib": "cudacodec", "requires": ["opencv_core"] + eigen()}, {"target": "opencv_features2d", "lib": "cudafeatures2d", "requires": ["opencv_core", "opencv_cudafilters"] + eigen()}, {"target": "opencv_cudafilters", "lib": "cudafilters", "requires": ["opencv_core", "opencv_imgproc"] + eigen()}, {"target": "opencv_cudaimgproc", "lib": "cudaimgproc", "requires": ["opencv_core", "opencv_imgproc"] + eigen()}, {"target": "opencv_cudalegacy", "lib": "cudalegacy", "requires": ["opencv_core", "opencv_video"] + eigen()}, {"target": "opencv_cudaobjdetect", "lib": "cudaobjdetect", "requires": ["opencv_core", "opencv_objdetect"] + eigen()}, {"target": "opencv_cudaoptflow", "lib": "cudaoptflow", "requires": ["opencv_core"] + eigen()}, {"target": "opencv_cudastereo", "lib": "cudastereo", "requires": ["opencv_core", "opencv_calib3d"] + eigen()}, {"target": "opencv_cudawarping", "lib": "cudawarping", "requires": ["opencv_core", "opencv_imgproc"] + eigen()}, {"target": "opencv_cudev", "lib": "cudev", "requires": [] + eigen()}, ]) return opencv_components def package_info(self): version = self.version.split(".") version = "".join(version) if self.settings.os == "Windows" else "" debug = "d" if self.settings.build_type == "Debug" and self.settings.compiler == "Visual Studio" else "" def get_lib_name(module): prefix = "" if module in ("correspondence", "multiview", "numeric") else "opencv_" return "%s%s%s%s" % (prefix, module, version, debug) def add_components(components): for component in components: conan_component = component["target"] cmake_target = component["target"] lib_name = get_lib_name(component["lib"]) requires = component["requires"] self.cpp_info.components[conan_component].names["cmake_find_package"] = cmake_target self.cpp_info.components[conan_component].names["cmake_find_package_multi"] = cmake_target self.cpp_info.components[conan_component].builddirs.append(self._module_subfolder) module_rel_path = os.path.join(self._module_subfolder, self._module_file) self.cpp_info.components[conan_component].build_modules["cmake_find_package"] = [module_rel_path] self.cpp_info.components[conan_component].build_modules["cmake_find_package_multi"] = [module_rel_path] self.cpp_info.components[conan_component].libs = [lib_name] self.cpp_info.components[conan_component].includedirs.append(os.path.join("include", "opencv4")) self.cpp_info.components[conan_component].requires = requires if self.settings.os == "Linux": self.cpp_info.components[conan_component].system_libs = ["dl", "m", "pthread", "rt"] if self.settings.os == "Android": self.cpp_info.components[conan_component].includedirs = [ os.path.join("sdk", "native", "jni", "include")] self.cpp_info.components[conan_component].system_libs.append("log") if int(str(self.settings.os.api_level)) > 20: self.cpp_info.components[conan_component].system_libs.append("mediandk") if not self.options.shared: self.cpp_info.components[conan_component].libdirs.append( os.path.join("sdk", "native", "staticlibs", tools.to_android_abi(str(self.settings.arch)))) if conan_component == "opencv_core": self.cpp_info.components[conan_component].libdirs.append("lib") self.cpp_info.components[conan_component].libs += tools.collect_libs(self) if self.settings.os == "iOS" or self.settings.os == "Macos": if not self.options.shared: if conan_component == "opencv_core": libs = list(filter(lambda x: not x.startswith("opencv"), tools.collect_libs(self))) self.cpp_info.components[conan_component].libs += libs # CMake components names cmake_component = component["lib"] if cmake_component != cmake_target: conan_component_alias = conan_component + "_alias" self.cpp_info.components[conan_component_alias].names["cmake_find_package"] = cmake_component self.cpp_info.components[conan_component_alias].names["cmake_find_package_multi"] = cmake_component self.cpp_info.components[conan_component_alias].requires = [conan_component] self.cpp_info.components[conan_component_alias].includedirs = [] self.cpp_info.components[conan_component_alias].libdirs = [] self.cpp_info.components[conan_component_alias].resdirs = [] self.cpp_info.components[conan_component_alias].bindirs = [] self.cpp_info.components[conan_component_alias].frameworkdirs = [] self.cpp_info.filenames["cmake_find_package"] = "OpenCV" self.cpp_info.filenames["cmake_find_package_multi"] = "OpenCV" add_components(self._opencv_components) if self.settings.os == "Windows": self.cpp_info.components["opencv_highgui"].system_libs = ["comctl32", "gdi32", "ole32", "setupapi", "ws2_32", "vfw32"] elif self.settings.os == "Macos": self.cpp_info.components["opencv_highgui"].frameworks = ["Cocoa"] self.cpp_info.components["opencv_videoio"].frameworks = ["Cocoa", "Accelerate", "AVFoundation", "CoreGraphics", "CoreMedia", "CoreVideo", "QuartzCore"] elif self.settings.os == "iOS": self.cpp_info.components["opencv_videoio"].frameworks = ["AVFoundation", "QuartzCore"]
[ "noreply@github.com" ]
lukaszlaszko.noreply@github.com
31aec91cb2ca7a5a5b2c15a2a2968260cb7063a8
2ac17a45280682da6d5c40625e16078245858b38
/matchzoo/models/drmm.py
08620c4359fffcd8c052e62ef1aaef570898dc8c
[ "Apache-2.0" ]
permissive
AdeDZY/MatchZoo
1dfeedd4b5be4abf5b81ff8e5ba3e6fa9d7b3e56
df199744b59d7c1b1768e87f6aa2dfe091e10fea
refs/heads/master
2021-05-07T08:12:41.562884
2017-11-01T15:25:04
2017-11-01T15:25:04
109,318,574
1
0
null
2017-11-02T21:02:43
2017-11-02T21:02:42
null
UTF-8
Python
false
false
3,092
py
# -*- coding=utf-8 -*- import keras import keras.backend as K from keras.models import Sequential, Model from keras.layers import Input, Embedding, Dense, Activation, Merge, Lambda, Permute from keras.layers import Reshape, Dot from keras.activations import softmax from model import BasicModel class DRMM(BasicModel): def __init__(self, config): super(DRMM, self).__init__(config) self._name = 'DRMM' self.check_list = [ 'text1_maxlen', 'hist_size', 'embed', 'embed_size', 'vocab_size', 'num_layers', 'hidden_sizes'] self.setup(config) self.initializer_fc = keras.initializers.RandomUniform(minval=-0.1, maxval=0.1, seed=11) self.initializer_gate = keras.initializers.RandomUniform(minval=-0.01, maxval=0.01, seed=11) if not self.check(): raise TypeError('[DRMM] parameter check wrong') print '[DRMM] init done' def setup(self, config): if not isinstance(config, dict): raise TypeError('parameter config should be dict:', config) self.set_default('text1_maxlen', 5) self.set_default('hist_size', 60) self.config.update(config) def build(self): def tensor_product(x): a = x[0] b = x[1] y = K.batch_dot(a, b, axis=1) y = K.einsum('ijk, ikl->ijl', a, b) return y query = Input(name='query', shape=(self.config['text1_maxlen'],)) print('[Input] query:\t%s' % str(query.get_shape().as_list())) doc = Input(name='doc', shape=(self.config['text1_maxlen'], self.config['hist_size'])) print('[Input] doc:\t%s' % str(doc.get_shape().as_list())) embedding = Embedding(self.config['vocab_size'], self.config['embed_size'], weights=[self.config['embed']], trainable = False) q_embed = embedding(query) print('[Embedding] q_embed:\t%s' % str(q_embed.get_shape().as_list())) q_w = Dense(1, kernel_initializer=self.initializer_gate, use_bias=False)(q_embed) print('[Dense] q_gate:\t%s' % str(q_w.get_shape().as_list())) q_w = Lambda(lambda x: softmax(x, axis=1), output_shape=(self.config['text1_maxlen'], ))(q_w) print('[Softmax] q_gate:\t%s' % str(q_w.get_shape().as_list())) z = doc for i in range(self.config['num_layers']): z = Dense(self.config['hidden_sizes'][i], kernel_initializer=self.initializer_fc)(z) z = Activation('tanh')(z) print('[Dense] z (full connection):\t%s' % str(z.get_shape().as_list())) z = Permute((2, 1))(z) z = Reshape((self.config['text1_maxlen'],))(z) print('[Reshape] z (matching) :\t%s' % str(z.get_shape().as_list())) q_w = Reshape((self.config['text1_maxlen'],))(q_w) print('[Reshape] q_w (gating) :\t%s' % str(q_w.get_shape().as_list())) out_ = Dot( axes= [1, 1])([z, q_w]) print('[Dot] out_ :\t%s' % str(out_.get_shape().as_list())) model = Model(inputs=[query, doc], outputs=[out_]) return model
[ "fanyixing111@hotmail.com" ]
fanyixing111@hotmail.com
9b49c5ee73c00f78dfa3c7b56e65e91b1d1bfcb9
c8e86f141b80858096ef84041a14b0be065c52e1
/sandy-disaster-recovery/aws.py
05cdcbe9110f870d2012da159f375536a4702094
[ "Apache-2.0" ]
permissive
DuaneNClark/crisiscleanup
9bd5184c5cd8d4d224ebed7bee51e1df82b17080
504ca3122e76e4f40f967036d0acde44c1dbe82c
refs/heads/master
2020-12-11T07:45:16.321813
2015-04-03T02:19:07
2015-04-03T02:24:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,540
py
""" Amazon Web Services API Rationale: the standard boto library throws errors on GAE, seemingly due to google.appengine.api.urlfetch """ import logging from time import mktime import datetime from wsgiref.handlers import format_date_time import hmac import hashlib import base64 from xml.etree import ElementTree from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from urllib import urlencode from google.appengine.api import urlfetch def rfc_1123_timestamp(dt): stamp = mktime(dt.timetuple()) return format_date_time(stamp) def iso_8601_timestamp(dt): return dt.strftime("%Y-%m-%dT%H:%M:%SZ") def aws_api_base_url(region_name): return u"https://email.%s.amazonaws.com" % region_name def post_signed(url, params, aws_access_key_id, aws_secret_access_key): if isinstance(aws_access_key_id, unicode): aws_access_key_id = aws_access_key_id.encode('ascii') if isinstance(aws_secret_access_key, unicode): aws_secret_access_key = aws_secret_access_key.encode('ascii') now = datetime.datetime.utcnow() rfc_timestamp = rfc_1123_timestamp(now) iso_timestamp = iso_8601_timestamp(now) hmac_hash = hmac.new(aws_secret_access_key, rfc_timestamp, hashlib.sha1) encoded_hash = base64.b64encode(hmac_hash.digest()) x_amzn_auth = ( "AWS3-HTTPS " + "AWSAccessKeyId=%s, " % aws_access_key_id + "Algorithm=HmacSHA1, " + "Signature=%s" % encoded_hash ) payload = dict({ "AWSAccessKeyId": aws_access_key_id, "Timestamp": iso_timestamp, }, **params ) response = urlfetch.fetch( url=url, method="POST", headers={ "Date": rfc_timestamp, "X-Amzn-Authorization": x_amzn_auth, }, payload=urlencode(payload), ) if "Error" in response.content: logging.error("AWS ERROR: %s" % response.content) return response def ses_get_verified_email_addresses( aws_region, aws_access_key_id, aws_secret_access_key, ): url = aws_api_base_url(aws_region) response = post_signed( url, params={ 'Action': 'ListIdentities', }, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, ) try: xml_tree = ElementTree.fromstring(response.content) identity_members = xml_tree.findall( ".//xmlns:Identities/xmlns:member", namespaces={'xmlns': 'http://ses.amazonaws.com/doc/2010-12-01/'} ) return [el.text for el in identity_members] except: return [] def ses_send_email( source, to_addresses, subject, body, cc=None, bcc=None, html_body=None, aws_region=None, aws_access_key_id=None, aws_secret_access_key=None, ): # construct multipart email msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = source msg['To'] = u', '.join(to_addresses) text_part = MIMEText(body, 'plain') msg.attach(text_part) if html_body: html_part = MIMEText(html_body, 'html') msg.attach(html_part) # post to AWS SES url = aws_api_base_url(aws_region) return post_signed( url, params={ 'Action': 'SendRawEmail', 'RawMessage.Data': base64.b64encode(msg.as_string()), }, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, )
[ "chris@wood.is" ]
chris@wood.is
b19e296e14053d689e9995c0c3db2c31aae5ef6f
1c3fb3c990bd07259c1701c709a28ec45cd0c748
/services/core-api/app/api/exports/response_models.py
487ed88be6d03eb97e804a09afb57dc551a1dd8e
[ "Apache-2.0" ]
permissive
usingtechnology/mds
f973106232f73f773bb4bb57737094dd32b1bd3c
c9c542f729df21511ee46e184ea752bad0b7d10c
refs/heads/master
2022-04-13T07:56:59.060216
2020-03-21T22:43:05
2020-03-21T22:43:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,537
py
from app.extensions import api from flask_restplus import fields from app.api.mines.response_models import MINE_TENURE_TYPE_CODE_MODEL, MINE_COMMODITY_CODE_MODEL, MINE_DISTURBANCE_CODE_MODEL, MINE_STATUS_CODE_MODEL, MINE_REGION_OPTION, MINE_REPORT_DEFINITION_CATEGORIES, MINE_REPORT_DEFINITION_MODEL, MINE_REPORT_SUBMISSION_STATUS from app.api.mines.permits.response_models import PERMIT_STATUS_CODE_MODEL from app.api.compliance.response_models import COMPLIANCE_ARTICLE_MODEL from app.api.incidents.response_models import MINE_INCIDENT_CATEGORY_MODEL, MINE_INCIDENT_DETERMINATION_TYPE_MODEL, MINE_INCIDENT_STATUS_CODE_MODEL, MINE_INCIDENT_DOCUMENT_TYPE_CODE_MODEL, MINE_INCIDENT_FOLLOWUP_INVESTIGATION_TYPE_MODEL from app.api.parties.response_models import MINE_PARTY_APPT_TYPE_MODEL, SUB_DIVISION_CODE_MODEL from app.api.variances.response_models import VARIANCE_APPLICATION_STATUS_CODE, VARIANCE_DOCUMENT_CATEGORY_CODE from app.api.now_applications.response_models import NOW_APPLICATION_DOCUMENT_TYPE_MODEL, NOW_APPLICATION_REVIEW_TYPES, NOW_APPLICATION_TYPES, UNIT_TYPES, NOW_ACTIVITY_TYPES, NOW_APPLICATION_STATUS_CODES, UNDERGROUND_EXPLORATION_TYPES, NOW_APPLICATION_PERMIT_TYPES, NOW_APPLICATION_REVIEW_TYPES, APPLICATION_PROGRESS_STATUS_CODES STATIC_CONTENT_MODEL = api.model( 'StaticContentModel', { 'mineDisturbanceOptions': fields.List(fields.Nested(MINE_DISTURBANCE_CODE_MODEL), attribute='MineDisturbanceCode'), 'mineCommodityOptions': fields.List(fields.Nested(MINE_COMMODITY_CODE_MODEL), attribute='MineCommodityCode'), 'mineStatusOptions': fields.List(fields.Nested(MINE_STATUS_CODE_MODEL), attribute='MineStatusXref'), 'mineRegionOptions': fields.List(fields.Nested(MINE_REGION_OPTION), attribute='MineRegionCode'), 'mineTenureTypes': fields.List(fields.Nested(MINE_TENURE_TYPE_CODE_MODEL), attribute='MineTenureTypeCode'), 'permitStatusCodes': fields.List(fields.Nested(PERMIT_STATUS_CODE_MODEL), attribute='PermitStatusCode'), 'incidentDocumentTypeOptions': fields.List( fields.Nested(MINE_INCIDENT_DOCUMENT_TYPE_CODE_MODEL), attribute='MineIncidentDocumentTypeCode'), 'incidentFollowupActionOptions': fields.List( fields.Nested(MINE_INCIDENT_FOLLOWUP_INVESTIGATION_TYPE_MODEL), attribute='MineIncidentFollowupInvestigationType'), 'incidentDeterminationOptions': fields.List( fields.Nested(MINE_INCIDENT_DETERMINATION_TYPE_MODEL), attribute='MineIncidentDeterminationType'), 'incidentStatusCodeOptions': fields.List( fields.Nested(MINE_INCIDENT_STATUS_CODE_MODEL), attribute='MineIncidentStatusCode'), 'incidentCategoryCodeOptions': fields.List(fields.Nested(MINE_INCIDENT_CATEGORY_MODEL), attribute='MineIncidentCategory'), 'provinceOptions': fields.List(fields.Nested(SUB_DIVISION_CODE_MODEL), attribute='SubDivisionCode'), 'complianceCodes': fields.List(fields.Nested(COMPLIANCE_ARTICLE_MODEL), attribute='ComplianceArticle'), 'varianceStatusOptions': fields.List( fields.Nested(VARIANCE_APPLICATION_STATUS_CODE), attribute='VarianceApplicationStatusCode'), 'varianceDocumentCategoryOptions': fields.List( fields.Nested(VARIANCE_DOCUMENT_CATEGORY_CODE), attribute='VarianceDocumentCategoryCode'), 'mineReportDefinitionOptions': fields.List(fields.Nested(MINE_REPORT_DEFINITION_MODEL), attribute='MineReportDefinition'), 'mineReportStatusOptions': fields.List( fields.Nested(MINE_REPORT_SUBMISSION_STATUS), attribute='MineReportSubmissionStatusCode'), 'mineReportCategoryOptions': fields.List( fields.Nested(MINE_REPORT_DEFINITION_CATEGORIES), attribute='MineReportCategory'), 'noticeOfWorkActivityTypeOptions': fields.List(fields.Nested(NOW_ACTIVITY_TYPES), attribute='ActivityType'), 'noticeOfWorkUnitTypeOptions': fields.List(fields.Nested(UNIT_TYPES), attribute='UnitType'), 'noticeOfWorkApplicationTypeOptions': fields.List(fields.Nested(NOW_APPLICATION_TYPES), attribute='NOWApplicationType'), 'noticeOfWorkApplicationStatusOptions': fields.List(fields.Nested(NOW_APPLICATION_STATUS_CODES), attribute='NOWApplicationStatus'), 'noticeOfWorkApplicationDocumentTypeOptions': fields.List( fields.Nested(NOW_APPLICATION_DOCUMENT_TYPE_MODEL), attribute='NOWApplicationDocumentType'), 'noticeOfWorkUndergroundExplorationTypeOptions': fields.List( fields.Nested(UNDERGROUND_EXPLORATION_TYPES), attribute='UndergroundExplorationType'), 'noticeOfWorkApplicationProgressStatusCodeOptions': fields.List( fields.Nested(APPLICATION_PROGRESS_STATUS_CODES), attribute='NOWApplicationProgressStatus'), 'noticeOfWorkApplicationPermitTypeOptions': fields.List( fields.Nested(NOW_APPLICATION_PERMIT_TYPES), attribute='NOWApplicationPermitType'), 'noticeOfWorkApplicationReviewOptions': fields.List( fields.Nested(NOW_APPLICATION_REVIEW_TYPES), attribute='NOWApplicationReviewType'), 'partyRelationshipTypes': fields.List( fields.Nested(MINE_PARTY_APPT_TYPE_MODEL), attribute='MinePartyAppointmentType') })
[ "bcgov-csnr-cd@gov.bc.ca" ]
bcgov-csnr-cd@gov.bc.ca
e5b584b90167e58b35886585b4797de3763f9990
283f702229d4570d4ddb48c42558f5e819e2c73b
/testedpy/def_intersectionEllipse_new.py
ab7ad7328596eabd0dfa34f2e87394b41b38dd3d
[ "BSD-2-Clause" ]
permissive
ljm0/RandomEllipse_CrowdingZone
cf478fba52adc5acc864b9e75532d830de32d47a
2c920abb0381cc79e5d3aa09429e37d5c5196832
refs/heads/master
2020-04-04T08:02:30.525976
2019-04-28T15:42:44
2019-04-28T15:42:44
155,769,077
0
0
null
null
null
null
UTF-8
Python
false
false
1,315
py
# -*- coding: utf-8 -*- """ Created on Sat Dec 1 18:06:20 2018 @author: MiaoLi """ import numpy as np from shapely.geometry.polygon import LinearRing import matplotlib.pyplot as plt def ellipse_polyline_intersection(ellipses, n=100): t = np.linspace(0, 2*np.pi, n, endpoint=False) st = np.sin(t) ct = np.cos(t) result = [] for x0, y0, a, b, angle in ellipses: angle = np.deg2rad(angle) sa = np.sin(angle) ca = np.cos(angle) p = np.empty((n, 2)) p[:, 0] = x0 + a * ca * ct - b * sa * st p[:, 1] = y0 + a * sa * ct + b * ca * st result.append(p) #ellipseA, ellipseB are the dots of two ellipse ellipseA = result[0] ellipseB = result[1] ea = LinearRing(ellipseA) eb = LinearRing(ellipseB) mp = ea.intersection(eb) #intersectionX, intersectionY are the intersections intersectionX = [p.x for p in mp] intersectionY = [p.y for p in mp] #if you want to draw the two ellipse: plt.plot(intersectionX, intersectionY, "o") plt.plot(ellipseA[:, 0], ellipseA[:, 1]) plt.plot(ellipseB[:, 0], ellipseB[:, 1]) plt.show() return intersectionX, intersectionY ellipses = [(1, 1, 1.5, 1.8, 90), (2, 0.5, 5, 1.5, -180)] intersectionX, intersectionY = ellipse_polyline_intersection(ellipses)
[ "chuoli223@yahoo.com" ]
chuoli223@yahoo.com
3c46e5cd8e2c42fe17964f81fddb273c2e6424fc
debc9ddbb577ed68e907cfdb85e0f2c801fdc8af
/rx/linq/observable/onerrorresumenext.py
490579fe1b84b19f1004b2c54d19d968ec1a33e2
[ "Apache-2.0" ]
permissive
pstiasny/RxPY
370eefc733de1241c1eac0dcdf8fa10780f71072
2bcf25ecbce1fbcd49d119bd73375572fbf9df5a
refs/heads/master
2021-01-09T20:01:18.664034
2014-07-27T22:19:39
2014-07-27T22:19:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,487
py
from six import add_metaclass from rx.observable import Observable from rx.anonymousobservable import AnonymousObservable from rx.disposables import CompositeDisposable, SingleAssignmentDisposable, \ SerialDisposable from rx.concurrency import immediate_scheduler from rx.internal import ExtensionMethod @add_metaclass(ExtensionMethod) class ObservableOnErrorResumeNext(Observable): def __init__(self, subscribe): self.on_error_resume_next = self.__on_error_resume_next def __on_error_resume_next(self, second): """Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. Keyword arguments: second -- Second observable sequence used to produce results after the first sequence terminates. Returns an observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. """ if not second: raise Exception('Second observable is required') return Observable.on_error_resume_next([self, second]) @classmethod def on_error_resume_next(cls, *args): """Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. 1 - res = Observable.on_error_resume_next(xs, ys, zs) 2 - res = Observable.on_error_resume_next([xs, ys, zs]) Returns an observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. """ if args and isinstance(args[0], list): sources = args[0] else: sources = list(args) def subscribe(observer): subscription = SerialDisposable() pos = [0] def action(this, state=None): if pos[0] < len(sources): current = sources[pos[0]] pos[0] += 1 d = SingleAssignmentDisposable() subscription.disposable = d d.disposable = current.subscribe(observer.on_next, lambda ex: this(), lambda: this()) else: observer.on_completed() cancelable = immediate_scheduler.schedule_recursive(action) return CompositeDisposable(subscription, cancelable) return AnonymousObservable(subscribe)
[ "dag@brattli.net" ]
dag@brattli.net
9953ddf0d5c71ebade38df3489edc444bbdade40
27248273a141aa8016bf6ecc286834a36e25c86b
/pipes/filter_odds.py
3ac4bfdbe1c00788154bf36166360edcf252cf27
[]
no_license
davidbrowning/pipingpi
c030e57e020ee76ed7113edb8951baf8809cfcde
ef8cef388a37800c4aadf1fbc5a678e585d4946a
refs/heads/master
2021-01-22T05:37:36.199943
2017-02-11T23:28:14
2017-02-11T23:28:14
81,689,652
0
0
null
null
null
null
UTF-8
Python
false
false
234
py
#!/usr/bin/python ## print odd numbers from file in sys.argv[1] import sys file_path = sys.argv[1] with open(file_path, 'r') as infile: for n in [int(x) for x in infile.readlines() if int(x) % 2 != 0]: print n
[ "dmbrowning21@gmail.com" ]
dmbrowning21@gmail.com
10537da4631fefb46009c0b77090dfae5c465b5c
c1692b4e11d4397c817d58264c50d0af05878175
/Text Adventure game/BadPokerGame.py
fc38ca68378db63d84fb249e7e9a37fbc3b30bb8
[]
no_license
IMDCGP105-1819/portfolio-Fred-Wright
de3421cdefb21f300b2a0027926ef97f4c57d288
2442f0b5d0a117c9ed072600dcb56d0795b0c045
refs/heads/master
2020-03-30T18:02:25.041713
2019-02-05T15:06:06
2019-02-05T15:06:06
151,480,938
0
0
null
null
null
null
UTF-8
Python
false
false
126,779
py
import sys print("Welcome back to the World Series Of Poker, I'm Lon McEachern and im here with Antonio Esfandiari") print("Esfandiari: Hey") print("And we are mere minutes away from finding out the final competitor to the main event, with the winner winning the illustrious WSOP bracelet") print("During this session, there will only be the table consisting of these 2 players, tune in tomorrow night for that (next game)") print("Esfandiari: Ive won 3 of them braclets and they're only collecting dust in a cabinet, they're here for that magical, life-changing fifteen million dollar payout") print("Lon: Yes of course, the highest prize-pot in the history of the main event, from the huge 8 thousand plus entrants, we have already deterined 8 players on the final table.") print("Esfandiari: Yeah, seriously strong set of players.") print("We are here on the pinultimate table of the World Series Of Poker main event with only 2 contestents left, of course we have Mr Antoine Labat") print("Esfandiari: Guy's come from from france with no real history, yet he's taken down some big dogs to get here, and would be only the third frenchamn to get to the main event.") print("Lon: And he's up against...") print("Your dad: Look, payday's already big, enough for some of your mom's treatment, you know it, I know it, but dont focus on that, everybody's already so proud of you, anything you do now, is just a bonus, Okay?") print("You let out a strong but shakey, nervous breath.. ") print("Your dad firmly places his hands on your shoulders, giving you a mild shake.") print("Dad: What's your name!?") name = str(input()) print("Do you know how to play poker!?") Played_before = input() while True: if Played_before == "yes": print("Good, because your here cause of how good you've played through this tournament.") print("MANAGER: TIME TO GO!") print("If ever you need my help, do: run hand through hair") print("i'll cough once to Fold, twice to Check/Call or three times to go big, you shouldnt need me though") print("Dont really know why we still have that camera on you, but whatever.") print("MANAGER: CAMERA'S ARE ROLLING, COME ON NOW!!") print(name,", You got this!") print("As you're walking away, your dad yells:") print("Im Proud of you son!") print("While walking through the back towards the poker table on stage, I walk up to you.") print("So, everything you can do is, chipcount, check, call, raise, which will lead to how much you wish to raise") print("all in, fold and RHTH, run hand through hair, to get some help") print("Try to enjoy") break if Played_before == "no": print("Your dad sigh's as if he's dissapointed") print("Clearly you've been relying on our cheating tactic's a little too much") print("MANAGER: TIME TO GO!") print("Right, when you play you hand and you don't know what to do, do: run hand through hair") print("i'll cough once to Fold, twice to Check/Call or three times to go big") print("That camera on you has helped quite alot through this journey, it still has its uses") print("if you do it too many times, someone may clock on, and we dont want that.") print("MANAGER: CAMERA'S ARE ROLLING, COME ON NOW!!") print(name, ", You got this!") print("As you're walking away, your dad yells:") print("Im Proud of you son!") print("While walking through the back towards the poker table on stage, I walk up to you.") print("Im sure you understand cards themselves, otherwise we have a big problem, google it") print("In poker, the aim is to reduce your opponents chips to 0, you do this by winning hands, at the start of each hand you are dealt 2 cards like 4♣ 9♦") print("The best 5 cards from your hand and the table are used.") print("Hand in order or worth from best to worst are Royal Flush: A♣ K♣ Q♣ J♣ 10♣, Straight flush J♣ 10♣ 9♣ 8♣ 7♣, Four of a kind: K♣ K♠ K♥ K♦ 10♦") print("Full house: K♦ K♠ K♥ 10♠ 10♥, Flush: A♥ 5♥ 6♥ 9♥ J♥, Straight: 5♥ 6♠ 7♠ 8♥ 9♦, Three of a kind: 5♥ 5♦ 5♠ 8♥ 9♦, Two pair: 4♣ 4♦ 7♠ K♠ K♠") print("One pair: 7♠ 7♣ 9♠ 10♣ K♠ and finally High Card: 2♥ 3♦ 6♣ 8♠ Q♣") print("Higher cards of the same value win hands, so a pair of Kings beat a pair of 10's") print("On each hand you can Fold, Check/Call or Raise/All in,") print("Fold means the hand ends and your opponents take the chips you've put in. Useful if you have a bad hand") print("Call means put in the same amount of chips as what the current highest amount is, or if none are in, then you can simply check.") print("Raise means increase the amount if chips others need to input to continue with the hand.") print("And all in... well means what it say's on the tin") print("You still following?") following = input() if following == "yes": print("Just checking, ha!, you see what i did there?... Ok.") print("The hand starts, you put in some chips then the flop comes, the first 3 cards, you then proceed") print("On the flop you could get a royal flush, highly unlikely but possible, if so, play like you only have a pair, and try to win as many chips as possible") print("Going All in straight away could scare opponents into folding, and you dont gain any chips") print("After the flop, there is the turn, another card, then the river, after it all plays out the player with the best hand wins.") print("The BabySteps feature is enable for if you need it, type !Help when prompted, but apparently your dad does some good advising... hmmm") print("So, everything you can do is, chipcount, check, call, raise, which will lead to how much you wish to raise") print("all in, fold and RHTH, run hand through hair, to get some help") break if following == "no": print("You're a lost cause, google it.") print("When you're done, come back") print("I'll enable the BabySteps feature during the first table vs Labat, if you're stuck or dont know what to do, type !Help when prompted") print("So, everything you can do is, chipcount, check, call, raise, which will lead to how much you wish to raise") print("all in, fold and RHTH, run hand through hair, to get some help") break else: print("What? A simple yes or no would do") following = input() else: print("I can tell you're nervous, you just mumbled, say that again?") Played_before = input() Chipcount = 550000 labat_chips = 300000 dad_coughs = 0 A = "What would you like to do?" if dad_coughs == 3: print("The security guard seems to pick up on your dads coughing") if dad_coughs == 5: print("The security guard walks over to your dad, politely asking him to stop coughing") if dad_coughs == 7: print("A switch seems to go off in the guards head, he calls over the MANAGER and proceeds to whisper in his ear") print("The manager looks at you, then at your dad, and squints his eyes, looking cautiously") if dad_coughs == 9: print("The MANAGER walks over and shoves your cards to the dealer, the security guards graps a hold of you and chucks you out of the buidling") print("You had enough warnings. You dont get any payout for the tournament, your mum dies of cancer, all beacuse of you.") sys.exit(0) print("Lon: And he's up against", name) print("Esfandiari: Complete nobody, he's from England, has no competitive poker, say's he's playing for his sick mother but i dont buy it! ") print("Probably a cover story for how he's been playing underground, racking up wins and needs a way to launder money") print("Lon: Ha! You really do think the worst of people.") print("Esfandiari: When you've been in the buisness as long as me, nothing suprises me anymore,") print("Esfandiari: Some guy said he was playing for his grandma's funeral costs, but she was just on a holiday in the bahamas!") print("Lon: 'sighs' Let's just get down to it, for the final place on the main event table its Antoine Labat versus", name, "!") print("As you walk through the curtains, applause already fills the room, you wave to thank your newfound supporters, showing respect, you shake your opponents hand, and take your seat.") print("You quickly do a stack count, you're on", Chipcount, "chips" "while he's on", labat_chips, "chips") print("The applause dies down, minor talking fills the room, a hell of a lot better than silence, the dealer shuffles.") print("WARNING: IF YOU INPUT WORDS WHEN PROMPTED FOR NUMBERS, VISE VERSA OR BE A GENERAL IDIOT, THIS GAME WILL BREAK.") print("She announces the beginning of the game and proceeds to deal you and your opponent 2 cards.") print("You take a deep breath in, exhale hard but silent, shuffle into your seat, notice the lights have dimmed from the audience in shine off the table") print("Before you know it, you feel right at home.") print("You look at your first hand, its a 4♣ 9♠, Labat raises to 30k, you fold immediately") print("Oh boy...") print("5 hands go by quickly, minor amounts get's raised between you and Labat, however it amasses to nothing") print("you see the next hand to be 4♠ & 5♠") print(A) hand1 = input() playing = True hand1_stake = 5000 hand1_pot = 0 while playing == True: if hand1 == "fold": print("As there is nothing to lose, and all to gain, this is pointless") hand1 = input() if hand1 == "check" or hand1 == "call": print("Labat calmly puts in the Blind, not revealing anything.") Chipcount = Chipcount - hand1_stake labat_chips = labat_chips - hand1_stake hand1_pot = hand1_stake * 2 break if hand1 == "raise": while playing == True: print("How much would you like to raise?") raise1 = int(input()) if raise1 < 10000: print("Thats too low, lowest bet is 10000") if raise1 >= 10000 and raise1 < 100000: print("Labat calmly puts in the calls your raise, not revealing anything.") Chipcount = Chipcount - raise1 labat_chips = labat_chips - raise1 hand1_pot = raise1 * 2 break if raise1 >= 100000 and raise1 < 200000: print("As you collect the chips and put them into the middle, a hush falls through the room.") print("Labat takes a few seconds to consider, arranges the chips needed to call, licks his lips and calls.") Chipcount = Chipcount - raise1 labat_chips = labat_chips - raise1 hand1_pot = raise1 * 2 break if raise1 >= 200000 and raise1 < Chipcount: print("You grab the chips needed, a large stack, but you hear your dad cough a loud 2 coughs, maybe play things a little steadier") print(A) hand1 = input() if raise1 > Chipcount: print("You dont have that much chips to use, you have:", Chipcount) print(A) hand1 = input() if raise1 == Chipcount: print("You grab the chips needed, a large stack, but you hear your dad cough a loud 2 coughs, maybe play things a little steadier") print(A) hand1 = input() else: print("That is not a valid bet") print("What would you like to do?") hand1 = input() break if hand1 == "RHTH": print("Your dad coughs twice") print(A) hand1 = input() dad_coughs = dad_coughs + 1 if hand1 == "AllIn": print("You grab all your chips, a large stack, but you hear your dad cough a loud 2 coughs, maybe play things a little steadier") print(A) hand1 = input() if hand1 == "chipcount": print(Chipcount) print(A) hand1 = input() if hand1 == "!Help": print("You have:", Chipcount, "Chips, id reccomend just calling as your hand is mediocre but has a lot of potential.") print("You can do: chipcount, check, call, raise, which will lead to how much you wish to raise, all in, fold !Help and run hand through hair") hand1 = input() else: print("Whats that? Type !Help if you're lost") hand1 = input() print("The dealer put one card aside, and reveals the flop:") print("|3♠||10♦||K♠|") print("Labat takes his time carefully, but cautiously looking at the cards") print("He proceeds to check.") print("You have:", Chipcount, "Labat has:", labat_chips, "& the pot is:", hand1_pot) print(A) hand2 = input() while playing == True: if hand2 == "fold": print("As there is nothing to lose, and all to gain, this is pointless") hand2 = input() if hand2 == "check" or hand2 == "call": print("The dealer puts one card away, and with no theatrical building, puts down..") print("The 9 of Spades!!!! A Flush!!!") print("Labat doesnt move, clearly in deep thought, after 30 seconds, he reaches for an amount of chips") print("Dealer: Raise 70 thousand.") labat_chips = labat_chips - 70000 hand1_pot = hand1_pot + 70000 print(A) hand3 = input() while playing == True: if hand3 == "fold": print("Folding a flush is a hard thing to do, however it seemingly must be done.") print("You throw your cards face down, he chooses to flip his cards face up, A pair of kings!") print("Your flush would have beat his kings, with the river left, your chances of winning were high, but its all in the past now.") print("Its the fist major hand, but as all hands pass, blinds will be raised to a point where you must go big or home.") labat_chips = labat_chips + hand1_pot hand1_pot = hand1_pot - hand1_pot break if hand3 == "raise": print("How much would you like to raise?") raise3 = int(input()) while playing == True: if raise3 <= 70000: print("Thats too low, lowest bet is 70001") raise3 = int(input()) if raise3 > 70000 and raise3 < 100000: Chipcount = Chipcount - raise3 labat_chips = labat_chips - (raise3 - 70000) hand1_pot = hand1_pot + ((raise3 * 2) - 70000) if labat_chips < 100000: print("You put", raise3, "chips to the middle, with your bet, Labat would be left with a small amount") print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip") print("He twiddles with it through his fingers and thumbs, he places it on the table and says:") print("All in.") print("You can either call or fold, and in a situation like this, no help can be given.") print("You have", Chipcount, "Chips, and would need to put in", (labat_chips - raise3), "to call.") print(A) handX = input() while playing == True: if handX == "call": print("As per rules of the game, both players place down their hand.") print("You place your 4♠ & 5♠, he places...") print("K♥...") print("K♦!!! A pair of kings, with a king on the board!?") print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!") print("Your father yells: Come on!") print("The room falls to silence as the dealer puts another card away for the river...") print("She puts down.. The three of hearts") print("A full house.. Labat wins. Dad:'Its alright", name, "You're still in this!") Chipcount = Chipcount - labat_chips hand1_pot = hand1_pot + (labat_chips * 2) labat_chips = labat_chips - labat_chips labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") print("Dad: Maybe going all in was not the best idea on the first main hand") break if handX == "fold": print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat") print("You throw your cards away and labat takes the big amount in the pot.") print("He also just throws away his cards not allowing you to see them") print("Dad: Your getting hasty son! This is your time!") labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") break else: print("You cant do that") print(A) handX = input() break if labat_chips >= 100000: print("Labat sees your weak re-raise, and capitalises immediately, he places 1 chip towards the middle and exclaims: All in.") print("You can either call or fold, and in a situation like this, no help can be given.") print("You have", Chipcount, "Chips, and would need to put in", (labat_chips - raise3), "to call.") print(A) handX = input() while playing == True: if handX == "call": print("As per rules of the game, both players place down their hand.") print("You place your 4♠ & 5♠, he places...") print("K♥...") print("K♦!!! A pair of kings, with a king on the board!?") print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!") print("Your father yells: Come on!") print("The room falls to silence as the dealer puts another card away for the river...") print("She puts down.. The three of hearts") print("A full house.. Labat wins. Dad:'Its alright", name, "You're still in this!") Chipcount = Chipcount - labat_chips hand1_pot = hand1_pot + (labat_chips * 2) labat_chips = labat_chips - labat_chips labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") print("Dad: Maybe going all in was not the best idea on the first main hand") break if handX == "fold": print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat") print("You throw your cards away and labat takes the big amount in the pot.") print("He also just throws away his cards not allowing you to see them") print("Dad: Your getting hasty son! This is your time!") labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") break else: print("You cant do that") print(A) handX = input() break if raise3 >= 100000 and raise3 < labat_chips: Chipcount = Chipcount - raise3 labat_chips = labat_chips - (raise3 - 70000) hand1_pot = hand1_pot + ((raise3 * 2) - 70000) print("You put", raise3, "chips to the middle, with your bet, Labat would be left with a small amount") print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip") print("He twiddles with it through his fingers and thumbs, he places it on the table and says:") print("All in.") print("You can either call or fold, and in a situation like this, no help can be given.") print("You have", Chipcount, "Chips, and would need to put in", (labat_chips - raise3), "to call.") print(A) handX = input() while playing == True: if handX == "call": print("As per rules of the game, both players place down their hand.") print("You place your 4♠ & 5♠, he places...") print("K♥...") print("K♦!!! A pair of kings, with a king on the board!?") print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!") print("Your father yells: Come on!") print("The room falls to silence as the dealer puts another card away for the river...") print("She puts down.. The three of hearts") print("A full house.. Labat wins. Dad:'Its alright", name, "You're still in this!") Chipcount = Chipcount - labat_chips hand1_pot = hand1_pot + (labat_chips * 2) labat_chips = labat_chips - labat_chips labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") print("Dad: Maybe going all in was not the best idea on the first main hand") break if handX == "fold": print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat") print("You throw your cards away and labat takes the big amount in the pot.") print("He also just throws away his cards not allowing you to see them") print("Dad: Your getting hasty son! This is your time!") labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") break else: print("You cant do that") print(A) handX = input() break if raise3 == labat_chips: print("You put", raise3, "chips to the middle, with your bet, Labat would be all in.") print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip") print("He twiddles with it through his fingers and thumbs, he places it on the table and says:") print("All in.") print("As per rules of the game, both players place down their hand.") print("You place your 4♠ & 5♠, he places...") print("K♥...") print("K♦!!! A pair of kings, with a king on the board!?") print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!") print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!") print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!") print("The room's silence has erupted, your father is shouting for the right card to come") print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.") print("The dealer puts one card away, and with no theatrical building, puts down..") print("The 9 of Spades!!!! A Flush!!!") print("Your father lets out a roar and you let out a huge sigh") print("The dealer puts another card away for the river...") print("She puts down.. The three of hearts") print("A full house.. 'Its alright", name, "You're still in this!") Chipcount = Chipcount - (labat_chips + 70000) hand1_pot = hand1_pot + ((labat_chips) * 2) + 70000 labat_chips = labat_chips - labat_chips labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") print("Dad: Maybe going all in was not the best idea on the first main hand") break if raise3 > labat_chips: print("Labat only has", labat_chips, "Please only bet and amount he can call.") raise3 = int(input()) else: print("Thats an invalid bet") raise3 = int(input()) break if hand3 == "check" or hand3 == "call": Chipcount = Chipcount - 70000 hand1_pot = hand1_pot + 70000 print("You take a while, thinking about the hand, after some time, place down the chips needed to call.") print("The dealer puts another card away for the river...") print("She puts down the three of hearts") print("The board is: |3♠||10♦||K♠||9♠||3♥|") print("Labat thinks long and hard, surveying the cards, 4 minutes pass") print("He puts a single chip into the middle and exclaims: All in") print("You can either call or fold, and in a situation like this, no help can be given.") print("You have", Chipcount, "Chips, and would need to put in", labat_chips, "to call.") print(A) handX = input() while playing == True: if handX == "call": print("As per rules of the game, both players place down their hand.") print("You place your 4♠ & 5♠, he places...") print("K♥...") print("K♦!!! A pair of kings, with a king on the board!?") print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!") print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!") print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!") print("The room's silence has erupted, your father is shouting for the right card to come") print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.") print("The dealer puts one card away, and with no theatrical building, puts down..") print("The 9 of Spades!!!! A Flush!!!") print("Your father lets out a roar and you let out a huge sigh") print("The dealer puts another card away for the river...") print("She puts down.. The three of hearts") print("A full house.. 'Its alright", name, "You're still in this!") Chipcount = Chipcount - labat_chips hand1_pot = hand1_pot + (labat_chips * 2) labat_chips = labat_chips - labat_chips labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") print("Dad: Maybe going all in was not the best idea on the first main hand") break if handX == "fold": print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat") print("You throw your cards away and labat takes the big amount in the pot.") print("He also just throws away his cards not allowing you to see them") print("Dad: Your getting hasty son! This is your time!") labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") break else: print("You cant do that") print(A) handX = input() break if hand3 == "RHTH": print("Your dad coughs three times") print(A) hand3 = input() dad_coughs = dad_coughs + 1 if hand3 == "allin": print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip") print("He twiddles with it through his fingers and thumbs, he places it on the table and says:") print("All in.") print("As per rules of the game, both players place down their hand.") print("You place your 4♠ & 5♠, he places...") print("K♥...") print("K♦!!! A pair of kings, with a king on the board!?") print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!") print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!") print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!") print("The room's silence has erupted, your father is shouting for the right card to come") print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.") print("The dealer puts one card away, and with no theatrical building, puts down..") print("The 9 of Spades!!!! A Flush!!!") print("Your father lets out a roar and you let out a huge sigh") print("The dealer puts another card away for the river...") print("She puts down.. The three of hearts") print("A full house.. 'Its alright", name, "You're still in this!") Chipcount = Chipcount - (labat_chips + 70000) hand1_pot = hand1_pot + ((labat_chips * 2) + 70000) labat_chips = labat_chips - labat_chips labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") print("Dad: Maybe going all in was not the best idea on the first main hand") break if hand3 == "chipcount": print("You have:", Chipcount, "Chips and Labat has:", labat_chips, "chips.") print(A) hand3 = input() if hand3 == "!Help": print("You have:", Chipcount, "Chips, id reccomend Raising as you have a flush.") print("You can do: chipcount, check, call, raise, which will lead to how much you wish to raise, all in, fold !Help and run hand through hair") hand3 = input() else: print("Whats that? Type !Help if you're lost") hand3 = input() break if hand2 == "raise": print("How much would you like to raise?") raise2 = int(input()) while playing == True: if raise2 < 10000: print("Thats too low, lowest bet is 10000") raise2 = int(input()) if raise2 >= 10000 and raise2 < 100000: Chipcount = Chipcount - raise2 labat_chips = labat_chips - raise2 hand1_pot = hand1_pot + (raise2 * 2) if labat_chips < 100000: print("You put", raise2, "chips to the middle, with your bet, Labat would be left with a small amount") print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip") print("He twiddles with it through his fingers and thumbs, he places it on the table and says:") print("All in.") print("You can either call or fold, and in a situation like this, no help can be given.") print("You have", Chipcount, "Chips, and would need to put in", (labat_chips - raise2), "to call.") print(A) handX = input() while playing == True: if handX == "call": print("As per rules of the game, both players place down their hand.") print("You place your 4♠ & 5♠, he places...") print("K♥...") print("K♦!!! A pair of kings, with a king on the board!?") print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!") print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!") print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!") print("The room's silence has erupted, your father is shouting for the right card to come") print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.") print("The dealer puts one card away, and with no theatrical building, puts down..") print("The 9 of Spades!!!! A Flush!!!") print("Your father lets out a roar and you let out a huge sigh") print("The dealer puts another card away for the river...") print("She puts down.. The three of hearts") print("A full house.. 'Its alright", name, "You're still in this!") Chipcount = Chipcount - labat_chips hand1_pot = hand1_pot + (labat_chips * 2) labat_chips = labat_chips - labat_chips labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") print("Dad: Maybe going all in was not the best idea on the first main hand") break if handX == "fold": print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat") print("You throw your cards away and labat takes the big amount in the pot.") print("He also just throws away his cards not allowing you to see them") print("Dad: Your getting hasty son! This is your time!") labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") break else: print("You cant do that") print(A) handX = input() break if labat_chips >= 100000: print("Labat takes his time, but in the end, calls.") print("The dealer puts one card away, and with no theatrical building, puts down..") print("The 9 of Spades!!!! A Flush!!!") print("Labat doesnt move, clearly in deep thought, after 30 seconds, he reaches for an amount of chips") print("Dealer: Raise 70 thousand.") labat_chips = labat_chips - 70000 hand1_pot = hand1_pot + 70000 print(A) hand4 = input() while playing == True: if hand4 == "fold": print("Folding a flush is a hard thing to do, however it seemingly must be done.") print("You throw your cards face down, he chooses to flip his cards face up, A pair of kings!") print("Your flush would hve beat his kings, with the river left, your chances of winning were high, but its all in the past now.") print("Its the fist major hand, but as all hands pass, blinds will be raised to a point where you must go big or home.") labat_chips = labat_chips + hand1_pot hand1_pot = hand1_pot - hand1_pot break if hand4 == "raise": print("How much would you like to raise?") raise4 = int(input()) while playing == True: if raise4 <= 70000: print("Thats too low, lowest bet is 70001") raise4 = int(input()) if raise4 > 70000 and raise4 < 100000: Chipcount = Chipcount - raise4 labat_chips = labat_chips - (raise4 - 70000) hand1_pot = hand1_pot + ((raise4 * 2) - 70000) if labat_chips < 100000: print("You put", raise4, "chips to the middle, with your bet, Labat would be left with a small amount") print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip") print("He twiddles with it through his fingers and thumbs, he places it on the table and says:") print("All in.") print("You can either call or fold, and in a situation like this, no help can be given.") print("You have", Chipcount, "Chips, and would need to put in", (labat_chips - raise4), "to call.") print(A) handX = input() while playing == True: if handX == "call": print("As per rules of the game, both players place down their hand.") print("You place your 4♠ & 5♠, he places...") print("K♥...") print("K♦!!! A pair of kings, with a king on the board!?") print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!") print("Your father yells: Come on!") print("The room falls to silence as the dealer puts another card away for the river...") print("She puts down.. The three of hearts") print("A full house.. Labat wins. Dad:'Its alright", name, "You're still in this!") Chipcount = Chipcount - labat_chips hand1_pot = hand1_pot + (labat_chips * 2) labat_chips = labat_chips - labat_chips labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") print("Dad: Maybe going all in was not the best idea on the first main hand") break if handX == "fold": print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat") print("You throw your cards away and labat takes the big amount in the pot.") print("He also just throws away his cards not allowing you to see them") print("Dad: Your getting hasty son! This is your time!") labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") break else: print("You cant do that") print(A) handX = input() if labat_chips >= 100000: print("Labat sees your weak re-raise, and capitalises immediately, he places 1 chip towards the middle and exclaims: All in.") print("You can either call or fold, and in a situation like this, no help can be given.") print("You have", Chipcount, "Chips, and would need to put in", (labat_chips - raise4), "to call.") print(A) handX = input() while playing == True: if handX == "call": print("As per rules of the game, both players place down their hand.") print("You place your 4♠ & 5♠, he places...") print("K♥...") print("K♦!!! A pair of kings, with a king on the board!?") print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!") print("Your father yells: Come on!") print("The room falls to silence as the dealer puts another card away for the river...") print("She puts down.. The three of hearts") print("A full house.. Labat wins. Dad:'Its alright", name, "You're still in this!") Chipcount = Chipcount - labat_chips hand1_pot = hand1_pot + (labat_chips * 2) labat_chips = labat_chips - labat_chips labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") print("Dad: Maybe going all in was not the best idea on the first main hand") break if handX == "fold": print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat") print("You throw your cards away and labat takes the big amount in the pot.") print("He also just throws away his cards not allowing you to see them") print("Dad: Your getting hasty son! This is your time!") labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") break else: print("You cant do that") print(A) handX = input() break if raise4 >= 100000 and raise4 < labat_chips: Chipcount = Chipcount - raise4 labat_chips = labat_chips - (raise4 - 70000) hand1_pot = hand1_pot + ((raise4 * 2) - 70000) print("You put", raise4, "chips to the middle, with your bet, Labat would be left with a small amount") print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip") print("He twiddles with it through his fingers and thumbs, he places it on the table and says:") print("All in.") print("You can either call or fold, and in a situation like this, no help can be given.") print("You have", Chipcount, "Chips, and would need to put in", (labat_chips - raise4), "to call.") print(A) handX = input() while playing == True: if handX == "call": print("As per rules of the game, both players place down their hand.") print("You place your 4♠ & 5♠, he places...") print("K♥...") print("K♦!!! A pair of kings, with a king on the board!?") print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!") print("Your father yells: Come on!") print("The room falls to silence as the dealer puts another card away for the river...") print("She puts down.. The three of hearts") print("A full house.. Labat wins. Dad:'Its alright", name, "You're still in this!") Chipcount = Chipcount - labat_chips hand1_pot = hand1_pot + (labat_chips * 2) labat_chips = labat_chips - labat_chips labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") print("Dad: Maybe going all in was not the best idea on the first main hand") break if handX == "fold": print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat") print("You throw your cards away and labat takes the big amount in the pot.") print("He also just throws away his cards not allowing you to see them") print("Dad: Your getting hasty son! This is your time!") labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") break else: print("You cant do that") print(A) handX = input() break if raise4 > labat_chips: print("You cant bet that amount as Labat only has", labat_chips, "chips.") raise4 = int(input()) if raise4 == labat_chips: print("You put", labat_chips, "chips to the middle") print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip") print("He twiddles with it through his fingers and thumbs, he places it on the table and says:") print("All in.") print("As per rules of the game, both players place down their hand.") print("You place your 4♠ & 5♠, he places...") print("K♥...") print("K♦!!! A pair of kings, with a king on the board!?") print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!") print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!") print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!") print("The room's silence has erupted, your father is shouting for the right card to come") print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.") print("The dealer puts one card away, and with no theatrical building, puts down..") print("The 9 of Spades!!!! A Flush!!!") print("Your father lets out a roar and you let out a huge sigh") print("The dealer puts another card away for the river...") print("She puts down.. The three of hearts") print("A full house.. 'Its alright", name, "You're still in this!") Chipcount = Chipcount - labat_chips - 70000 hand1_pot = hand1_pot + (labat_chips * 2) + 70000 labat_chips = labat_chips - labat_chips labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") print("Dad: Maybe going all in was not the best idea on the first main hand") break else: print("Thats an invalid bet") raise4 = int(input()) break if hand4 == "check" or hand4 == "call": Chipcount = Chipcount - 70000 hand1_pot = hand1_pot + 70000 print("You take a while, thinking about the hand, after some time, place down the chips needed to call.") print("The dealer puts another card away for the river...") print("She puts down the three of hearts") print("The board is: |3♠||10♦||K♠||9♠||3♥|") print("Labat thinks long and hard, surveying the cards, 4 minutes pass") print("He puts a single chip into the middle and exclaims: All in") print("You can either call or fold, and in a situation like this, no help can be given.") print("You have", Chipcount, "Chips, and would need to put in", (labat_chips), "to call.") print(A) handX = input() while playing == True: if handX == "call": print("As per rules of the game, both players place down their hand.") print("You place your 4♠ & 5♠, he places...") print("K♥...") print("K♦!!! A pair of kings, with a king on the board!?") print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!") print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!") print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!") print("The room's silence has erupted, your father is shouting for the right card to come") print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.") print("The dealer puts one card away, and with no theatrical building, puts down..") print("The 9 of Spades!!!! A Flush!!!") print("Your father lets out a roar and you let out a huge sigh") print("The dealer puts another card away for the river...") print("She puts down.. The three of hearts") print("A full house.. 'Its alright", name, "You're still in this!") Chipcount = Chipcount - labat_chips hand1_pot = hand1_pot + (labat_chips * 2) labat_chips = labat_chips - labat_chips labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") print("Dad: Maybe going all in was not the best idea on the first main hand") break if handX == "fold": print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat") print("You throw your cards away and labat takes the big amount in the pot.") print("He also just throws away his cards not allowing you to see them") print("Dad: Your getting hasty son! This is your time!") labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") break else: print("You cant do that") print(A) handX = input() break if hand4 == "RHTH": print("Your dad coughs three times") print(A) hand4 = input() if hand4 == "allin": print("You put", labat_chips, "chips to the middle") print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip") print("He twiddles with it through his fingers and thumbs, he places it on the table and says:") print("All in.") print("As per rules of the game, both players place down their hand.") print("You place your 4♠ & 5♠, he places...") print("K♥...") print("K♦!!! A pair of kings, with a king on the board!?") print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!") print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!") print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!") print("The room's silence has erupted, your father is shouting for the right card to come") print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.") print("The dealer puts one card away, and with no theatrical building, puts down..") print("The 9 of Spades!!!! A Flush!!!") print("Your father lets out a roar and you let out a huge sigh") print("The dealer puts another card away for the river...") print("She puts down.. The three of hearts") print("A full house.. 'Its alright", name, "You're still in this!") Chipcount = Chipcount - labat_chips - 70000 hand1_pot = hand1_pot + (labat_chips * 2) + 70000 labat_chips = labat_chips - labat_chips labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") print("Dad: Maybe going all in was not the best idea on the first main hand") break if hand4 == "chipcount": print("You have:", Chipcount, "Chips") print(A) hand4 = input() if hand4 == "!Help": print("You have:", Chipcount, "Chips, id reccomend Raising as you have a flush.") print("You can do: chipcount, check, call, raise, which will lead to how much you wish to raise, all in, fold !Help and run hand through hair") hand4 = input() else: print("Whats that? Type !Help if you're lost") hand4 = input() # break if raise2 > labat_chips: print("Labat only has", labat_chips, "Please only bet and amount he can call.") print(A) raise2 = int(input()) if raise2 >= 100000 and raise2 < 200000: Chipcount = Chipcount - raise2 labat_chips = labat_chips - raise2 hand1_pot = hand1_pot + (raise2 * 2) if labat_chips < 100000: print("You put", raise2, "chips to the middle, with your bet, Labat would be left with a small amount") print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip") print("He twiddles with it through his fingers and thumbs, he places it on the table and says:") print("All in.") print("You can either call or fold, and in a situation like this, no help can be given.") print("You have", Chipcount, "Chips, and would need to put in", (labat_chips - raise2), "to call.") print(A) handX = input() while playing == True: if handX == "call": print("As per rules of the game, both players place down their hand.") print("You place your 4♠ & 5♠, he places...") print("K♥...") print("K♦!!! A pair of kings, with a king on the board!?") print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!") print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!") print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!") print("The room's silence has erupted, your father is shouting for the right card to come") print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.") print("The dealer puts one card away, and with no theatrical building, puts down..") print("The 9 of Spades!!!! A Flush!!!") print("Your father lets out a roar and you let out a huge sigh") print("The dealer puts another card away for the river...") print("She puts down.. The three of hearts") print("A full house.. 'Its alright", name, "You're still in this!") Chipcount = Chipcount - labat_chips hand1_pot = hand1_pot + (labat_chips * 2) labat_chips = labat_chips - labat_chips labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") print("Dad: Maybe going all in was not the best idea on the first main hand") break if handX == "fold": print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat") print("You throw your cards away and labat takes the big amount in the pot.") print("He also just throws away his cards not allowing you to see them") print("Dad: Your getting hasty son! This is your time!") labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") break else: print("You cant do that") print(A) handX = input() break if labat_chips >= 100000: print("Labat takes a long while, but in the end, calls.") print("The dealer puts one card away, and with no theatrical building, puts down..") print("The 9 of Spades!!!! A Flush!!!") print("Labat doesnt move, clearly in deep thought, after 30 seconds, he reaches for an amount of chips") print("Dealer: Raise 70 thousand.") labat_chips = labat_chips - 70000 hand1_pot = hand1_pot + 70000 print(A) hand5 = input() while playing == True: if hand5 == "fold": print("Folding a flush is a hard thing to do, however it seemingly must be done.") print("You throw your cards face down, he chooses to flip his cards face up, A pair of kings!") print("Your flush would hve beat his kings, with the river left, your chances of winning were high, but its all in the past now.") print("Its the fist major hand, but as all hands pass, blinds will be raised to a point where you must go big or home.") labat_chips = labat_chips + hand1_pot hand1_pot = hand1_pot - hand1_pot break if hand5 == "raise": print("How much would you like to raise?") raise5 = int(input()) while playing == True: if raise5 <= 70000: print("Thats too low, lowest bet is 70001") raise5 = int(input()) if raise5 > 70000 and raise5 < 100000: Chipcount = Chipcount - raise5 labat_chips = labat_chips - (raise5 - 70000) hand1_pot = hand1_pot + (raise5 * 2) if labat_chips < 100000: print("You put", raise5, "chips to the middle, with your bet, Labat would be left with a small amount") print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip") print("He twiddles with it through his fingers and thumbs, he places it on the table and says:") print("All in.") print("You can either call or fold, and in a situation like this, no help can be given.") print("You have", Chipcount, "Chips, and would need to put in", (labat_chips - raise5), "to call.") print(A) handX = input() while playing == True: if handX == "call": print("As per rules of the game, both players place down their hand.") print("You place your 4♠ & 5♠, he places...") print("K♥...") print("K♦!!! A pair of kings, with a king on the board!?") print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!") print("Your father yells: Come on!") print("The room falls to silence as the dealer puts another card away for the river...") print("She puts down.. The three of hearts") print("A full house.. Labat wins. Dad:'Its alright", name, "You're still in this!") Chipcount = Chipcount - labat_chips hand1_pot = hand1_pot + ((labat_chips * 2) - 70000) labat_chips = labat_chips - labat_chips labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") print("Dad: Maybe going all in was not the best idea on the first main hand") break if handX == "fold": print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat") print("You throw your cards away and labat takes the big amount in the pot.") print("He also just throws away his cards not allowing you to see them") print("Dad: Your getting hasty son! This is your time!") labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") break else: print("You cant do that") print(A) handX = input() break if labat_chips >= 100000: print("Labat sees your weak re-raise, and capitalises immediately, he places 1 chip towards the middle and exclaims: All in.") print("You can either call or fold, and in a situation like this, no help can be given.") print("You have", Chipcount, "Chips, and would need to put in", (labat_chips - raise5), "to call.") print(A) handX = input() while playing == True: if handX == "call": print("As per rules of the game, both players place down their hand.") print("You place your 4♠ & 5♠, he places...") print("K♥...") print("K♦!!! A pair of kings, with a king on the board!?") print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!") print("Your father yells: Come on!") print("The room falls to silence as the dealer puts another card away for the river...") print("She puts down.. The three of hearts") print("A full house.. Labat wins. Dad:'Its alright", name, "You're still in this!") Chipcount = Chipcount - labat_chips hand1_pot = hand1_pot + (labat_chips * 2) labat_chips = labat_chips - labat_chips labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") print("Dad: Maybe going all in was not the best idea on the first main hand") if handX == "fold": print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat") print("You throw your cards away and labat takes the big amount in the pot.") print("He also just throws away his cards not allowing you to see them") print("Dad: Your getting hasty son! This is your time!") labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") else: print("You cant do that") print(A) handX = input() break if raise5 >= 100000 and raise5 <= labat_chips: Chipcount = Chipcount - raise5 hand1_pot = hand1_pot + raise5 + (raise5 - 70000) labat_chips = labat_chips - (raise5 - 70000) print("You put", raise5, "chips to the middle, with your bet, Labat would be left with a small amount") print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip") print("He twiddles with it through his fingers and thumbs, he places it on the table and says:") print("All in.") print("You can either call or fold, and in a situation like this, no help can be given.") print("You have", Chipcount, "Chips, and would need to put in", (labat_chips - raise5), "to call.") print(A) handX = input() while playing == True: if handX == "call": print("As per rules of the game, both players place down their hand.") print("You place your 4♠ & 5♠, he places...") print("K♥...") print("K♦!!! A pair of kings, with a king on the board!?") print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!") print("Your father yells: Come on!") print("The room falls to silence as the dealer puts another card away for the river...") print("She puts down.. The three of hearts") print("A full house.. Labat wins. Dad:'Its alright", name, "You're still in this!") Chipcount = Chipcount - labat_chips hand1_pot = hand1_pot + (labat_chips * 2) labat_chips = labat_chips - labat_chips labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") print("Dad: Maybe going all in was not the best idea on the first main hand") break if handX == "fold": print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat") print("You throw your cards away and labat takes the big amount in the pot.") print("He also just throws away his cards not allowing you to see them") print("Dad: Your getting hasty son! This is your time!") labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") break else: print("You cant do that") print(A) handX = input() break if raise5 > labat_chips: print("Labat only has", labat_chips, "Please only bet an amount he can call.") raise5 = int(input()) if raise5 == labat_chips: print("You put", labat_chips, "chips to the middle") print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip") print("He twiddles with it through his fingers and thumbs, he places it on the table and says:") print("All in.") print("As per rules of the game, both players place down their hand.") print("You place your 4♠ & 5♠, he places...") print("K♥...") print("K♦!!! A pair of kings, with a king on the board!?") print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!") print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!") print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!") print("The room's silence has erupted, your father is shouting for the right card to come") print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.") print("The dealer puts one card away, and with no theatrical building, puts down..") print("The 9 of Spades!!!! A Flush!!!") print("Your father lets out a roar and you let out a huge sigh") print("The dealer puts another card away for the river...") print("She puts down.. The three of hearts") print("A full house.. 'Its alright", name, "You're still in this!") Chipcount = Chipcount - labat_chips - 70000 hand1_pot = hand1_pot + (labat_chips * 2) + 70000 labat_chips = labat_chips - labat_chips labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") print("Dad: Maybe going all in was not the best idea on the first main hand") break else: print("Thats an invalid bet") raise4 = int(input()) break if hand5 == "check" or hand5 == "call": Chipcount = Chipcount - 70000 hand1_pot = hand1_pot + 70000 print("You take a while, thinking about the hand, after some time, place down the chips needed to call.") print("The dealer puts another card away for the river...") print("She puts down the three of hearts") print("The board is: |3♠||10♦||K♠||9♠||3♥|") print("Labat thinks long and hard, surveying the cards, 4 minutes pass") print("He puts a single chip into the middle and exclaims: All in") print("You can either call or fold, and in a situation like this, no help can be given.") print("You have", Chipcount, "Chips, and would need to put in", labat_chips, "to call.") print(A) handX = input() while playing == True: if handX == "call": print("As per rules of the game, both players place down their hand.") print("You place your 4♠ & 5♠, he places...") print("K♥...") print("K♦!!! A pair of kings, with a king on the board!?") print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!") print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!") print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!") print("The room's silence has erupted, your father is shouting for the right card to come") print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.") print("The dealer puts one card away, and with no theatrical building, puts down..") print("The 9 of Spades!!!! A Flush!!!") print("Your father lets out a roar and you let out a huge sigh") print("The dealer puts another card away for the river...") print("She puts down.. The three of hearts") print("A full house.. 'Its alright", name, "You're still in this!") Chipcount = Chipcount - labat_chips hand1_pot = hand1_pot + (labat_chips * 2) labat_chips = labat_chips - labat_chips labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") print("Dad: Maybe going all in was not the best idea on the first main hand") break if handX == "fold": print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat") print("You throw your cards away and labat takes the big amount in the pot.") print("He also just throws away his cards not allowing you to see them") print("Dad: Your getting hasty son! This is your time!") labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") break else: print("You cant do that") print(A) handX = input() break if hand5 == "RHTH": print("Your dad coughs three times") print(A) hand5 = input() dad_coughs = dad_coughs + 1 if hand5 == "allin": print("You put", labat_chips, "chips to the middle, with your bet, Labat would be all in.") print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip") print("He twiddles with it through his fingers and thumbs, he places it on the table and says:") print("All in.") print("As per rules of the game, both players place down their hand.") print("You place your 4♠ & 5♠, he places...") print("K♥...") print("K♦!!! A pair of kings, with a king on the board!?") print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!") print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!") print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!") print("The room's silence has erupted, your father is shouting for the right card to come") print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.") print("The dealer puts one card away, and with no theatrical building, puts down..") print("The 9 of Spades!!!! A Flush!!!") print("Your father lets out a roar and you let out a huge sigh") print("The dealer puts another card away for the river...") print("She puts down.. The three of hearts") print("A full house.. 'Its alright", name, "You're still in this!") Chipcount = Chipcount - labat_chips - 70000 hand1_pot = hand1_pot + (labat_chips * 2) + 70000 labat_chips = labat_chips - labat_chips labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") print("Dad: Maybe going all in was not the best idea on the first main hand") break if hand5 == "chipcount": print("You have:", Chipcount, "Chips and Labat has:", labat_chips, "chips.") print(A) hand5 = input() if hand5 == "!Help": print("You have:", Chipcount, "Chips, id reccomend Raising as you have a flush.") print("You can do: chipcount, check, call, raise, which will lead to how much you wish to raise, all in, fold !Help and run hand through hair") hand5 = input() else: print("Whats that? Type !Help if you're lost") hand5 = input() break if raise2 >= 200000 and raise2 < labat_chips: print("You put", raise2, "chips to the middle, with your bet, Labat would be left with a small amount") print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip") print("He twiddles with it through his fingers and thumbs, he places it on the table and says:") print("All in.") print("You can either call or fold, and in a situation like this, no help can be given.") print("You have", Chipcount, "Chips, and would need to put in", (labat_chips - raise2), "to call.") print(A) handX = input() while playing == True: if handX == "call": print("As per rules of the game, both players place down their hand.") print("You place your 4♠ & 5♠, he places...") print("K♥...") print("K♦!!! A pair of kings, with a king on the board!?") print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!") print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!") print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!") print("The room's silence has erupted, your father is shouting for the right card to come") print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.") print("The dealer puts one card away, and with no theatrical building, puts down..") print("The 9 of Spades!!!! A Flush!!!") print("Your father lets out a roar and you let out a huge sigh") print("The dealer puts another card away for the river...") print("She puts down.. The three of hearts") print("A full house.. 'Its alright", name, "You're still in this!") Chipcount = Chipcount - labat_chips hand1_pot = hand1_pot + (labat_chips * 2) labat_chips = labat_chips - labat_chips labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") print("Dad: Maybe going all in was not the best idea on the first main hand") break if handX == "fold": print("You wait a few minutes, pretending to hmm and arr, however this is just to unease Labat") print("You throw your cards away and labat takes the big amount in the pot.") print("He also just throws away his cards not allowing you to see them") print("Dad: Your getting hasty son! This is your time!") labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") break else: print("You cant do that") print(A) handX = input() break if raise2 == labat_chips: print("You put", raise2, "chips to the middle, with your bet, Labat would be all in.") print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip") print("He twiddles with it through his fingers and thumbs, he places it on the table and says:") print("All in.") print("As per rules of the game, both players place down their hand.") print("You place your 4♠ & 5♠, he places...") print("K♥...") print("K♦!!! A pair of kings, with a king on the board!?") print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!") print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!") print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!") print("The room's silence has erupted, your father is shouting for the right card to come") print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.") print("The dealer puts one card away, and with no theatrical building, puts down..") print("The 9 of Spades!!!! A Flush!!!") print("Your father lets out a roar and you let out a huge sigh") print("The dealer puts another card away for the river...") print("She puts down.. The three of hearts") print("A full house.. 'Its alright", name, "You're still in this!") Chipcount = Chipcount - labat_chips hand1_pot = hand1_pot + (labat_chips * 2) labat_chips = labat_chips - labat_chips labat_chips = labat_chips + hand1_pot print("You now have", Chipcount, "chips") print("Labat now has", labat_chips, "chips") print("Dad: Maybe going all in was not the best idea on the first main hand") break else: print("That is not a valid bet") raise2 = int(input()) break if hand2 == "RHTH": print("Your dad coughs twice") print(A) hand2 = input() dad_coughs = dad_coughs + 1 if hand2 == "all in": print("Labat thinks for a while, seemingly an eternety, he grabs a single $1000 chip") print("He twiddles with it through his fingers and thumbs, he places it on the table and says:") print("All in.") print("As per rules of the game, both players place down their hand.") print("You place your 4♠ & 5♠, he places...") print("K♥...") print("K♦!!! A pair of kings, with a king on the board!?") print("Esfandiari: A Huge moment in the game! And we're only a couple of hands in!") print("Lon: Theres a 73% Chance Labat comes home with it, doubling his chip count and putting himself in a commanding position!") print("Esfandiari:But of course", name, "can win! Ive seen alot worse odds, he should still feel good about himself!") print("The room's silence has erupted, your father is shouting for the right card to come") print("Both you and Labat are out of your chairs, you shake his hand and look down, hoping for anything.") print("The dealer puts one card away, and with no theatrical building, puts down..") print("The 9 of Spades!!!! A Flush!!!") print("Your father lets out a roar and you let out a huge sigh") print("The dealer puts another card away for the river...") print("She puts down.. The three of hearts") print("A full house.. 'Its alright", name, "You're still in this!") Chipcount = Chipcount - labat_chips hand1_pot = hand1_pot + (labat_chips * 2) labat_chips = labat_chips - labat_chips labat_chips = labat_chips + hand1_pot break if hand2 == "chipcount": print(Chipcount) print(A) hand2 = input() if hand2 == "!Help": print("You have:", Chipcount, "Chips, id reccomend just calling as your hand is mediocre but has a lot of potential.") print("You can do: chipcount, check, call, raise, which will lead to how much you wish to raise, all in, fold !Help and run hand through hair") hand2 = input() else: print("Whats that? Type !Help if you're lost") hand2 = input() print(Chipcount, labat_chips) if Chipcount < 300000: print("Esfandiari: Its been a bad start for", name, "Labat with one good hand, and a little bit of luck asserts a 300k lead.") labat_chips = 475000 Chipcount = 375000 print("Lon: Yes however dont count", name, "out, we said before that both these players have taken down big players to get here, however", name, "i believe has that better track record.") print("Esfandiari: Im prosuming you're talking about that nasty bluff against Phil Ivey, trip ace's versus a pair of 2's!", name, "has got balls, no doubt") print("Lon: I was reffering to when he knocked you out with the strai-") print("Esfandiari: Shutup! I would rather not relive that terrible experience.") print("Lon: Ha! Well we are back after 2 hours 30 of close action, after a few decent hands for", name, "he's back to only being 100k behind") if Chipcount >= 300000 and Chipcount < 450000: print("Esfandiari: Its been a alright start for", name, "Now both are moderately even in this showdown.") print("And i think", name, "has it in him to do this.") print("Lon: Yes however dont count Labat out, we said before that both these players have taken down big players to get here, however Labat i believe has that better track record.") print("Esfandiari: Im prosuming you're talking about that nasty bluff against Phil Ivey, trip ace's versus a pair of 2's! Labat has got balls, no doubt") print("Lon: Theres also", name, "Who knocked you out with the strai-") print("Esfandiari: Shutup! I would rather not relive that terrible experience.") print("Lon: Ha! Well we are back after 2 hours 30 of close action, after a few decent hands for", name, "he's now take a minor lead of 50k") Chipcount = 450000 labat_chips = 400000 if Chipcount >= 450000: Chipcount = 575000 labat_chips = 275000 print("Esfandiari: Its been a good start for", name, "Getting out of the first major hand is a skill all great players need") print("And i think", name, "has it in him to do this.") print("Lon: Yes however dont count Labat out, we said before that both these players have taken down big players to get here, however Labat i believe has that better track record.") print("Esfandiari: Im prosuming you're talking about that nasty bluff against Phil Ivey, trip ace's versus a pair of 2's! Labat has got balls, no doubt") print("Lon: I was reffering to when he knocked you out with the strai-") print("Esfandiari: Shutup! I would rather not relive that terrible experience.") print("Lon: Ha! Well we are back after 2 hours 30 of close action, after a few decent hands for", name, "he's now take a commanding lead of 300k") print("We now resume the action.") print("With a couple of good hands, you feel momentum is now on your side, lets see if the next hand can convert it.") print("The dealer shuffles, passing both you and Labat 2 cards, you reveal them to be:") print("Q♠ & Q♦") print(A) hand1 = input() labat_chips = labat_chips - 25000 Chipcount = Chipcount - 25000 hand2pot = 50000 while playing == True: pre-flop if hand1 == "fold": unable if hand1 == "check" or hand1 == "call": flop hand2 = input() while playing == True: if hand2 == "fold": unable if hand2 == "check" or hand2 == "call": turn hand3 = input() while playing == True: if hand3 == "fold": unable if hand3 == "check" or hand3 == "call": river hand4 = input() while playing == True: if hand4 == "fold": unable if hand4 == "check" or hand4 == "call": allin if hand4 == "raise": raise1 = int(input()) while playing == True: if raise1 < 10000: no if raise1 >= 10000 and raise1 < 100000: if labat_chips < 100000: k if labat_chips >= 100000: k if raise1 >= 100000 and raise1 < 200000: if labat_chips < 100000: k if labat_chips >= 100000: k if raise1 >= 200000 and raise1 < labat_chips: fold if raise1 > labat_chips: no if raise1 == labat_chips: allin else: print("Please place a valid bet") raise1 = int(input()) break if hand4 == "RHTH": p if hand4 == "AllIn": z if hand4 == "chipcount": z if hand4 == "!Help": z else: print("Whats that? Type !Help if you're lost") hand4 = input() break if hand3 == "raise": raise2 = int(input()) while playing == True: if raise2 < 10000: no if raise2 >= 10000 and raise2 < 100000: if labat_chips < 100000: k if labat_chips >= 100000: calls river hand5 = input() while playing == True: if hand5 == "fold": unable if hand5 == "check" or hand5 == "call": ok if hand5 == "raise": raise3 = int(input()) while playing == True: if raise3 < 10000: no if raise3 >= 10000 and raise3 < 100000: if labat_chips < 100000: k if labat_chips >= 100000: k if raise3 >= 100000 and raise3 < 200000: if labat_chips < 100000: k if labat_chips >= 100000: k if raise3 >= 200000 and raise3 < labat_chips: fold if raise3 > labat_chips: no if raise3 == labat_chips: allin else: print("Please place a valid bet") raise3 = int(input()) break if hand5 == "RHTH": p if hand5 == "AllIn": z if hand5 == "chipcount": z if hand5 == "!Help": z else: print("Whats that? Type !Help if you're lost") hand5 = input() break if raise2 >= 100000 and raise2 < 200000: if labat_chips < 100000: k if labat_chips >= 100000: calls river hand6 = input() while playing == True: if hand6 == "fold": unable if hand6 == "check" or hand6 == "call": ok if hand6 == "raise": raise4 = int(input()) while playing == True: if raise4 < 10000: no if raise4 >= 10000 and raise4 < 100000: if labat_chips < 100000: k if labat_chips >= 100000: k if raise4 >= 100000 and raise4 < 200000: if labat_chips < 100000: k if labat_chips >= 100000: k if raise4 >= 200000 and raise4 < labat_chips: fold if raise4 > labat_chips: no if raise4 == labat_chips: allin else: print("Please place a valid bet") raise4 = int(input()) break if hand6 == "RHTH": p if hand6 == "AllIn": z if hand6 == "chipcount": z if hand6 == "!Help": z else: print("Whats that? Type !Help if you're lost") hand6 = input() break if raise2 >= 200000 and raise2 < labat_chips: fold if raise2 > labat_chips: no if raise2 == labat_chips: allin else: print("Please place a valid bet") raise2 = int(input()) break if hand3 == "RHTH": p if hand3 == "AllIn": z if hand3 == "chipcount": z if hand3 == "!Help": z else: print("Whats that? Type !Help if you're lost") hand3 = input() break if hand2 == "raise": raise5 = int(input()) while playing == True: if raise5 < 10000: no if raise5 >= 10000 and raise5 < 100000: if labat_chips < 100000: k if labat_chips >= 100000: k if raise5 >= 100000 and raise5 < 200000: if labat_chips < 100000: k if labat_chips >= 100000: k if raise5 >= 200000 and raise5 < labat_chips: fold if raise5 > labat_chips: no if raise5 == labat_chips: allin else: print("Please place a valid bet") raise1 = int(input()) break if hand2 == "RHTH": p if hand2 == "AllIn": z if hand2 == "chipcount": z if hand2 == "!Help": z else: print("Whats that? Type !Help if you're lost") hand2 = input() break if hand1 == "raise": if raise = 70k: raise6 = int(input()) while playing == True: if raise6 < 10000: no if raise6 >= 10000 and raise6 < 125000: if labat_chips < 100000: k if labat_chips >= 100000: flop hand7 = input() while playing == True: if hand7 == "fold": unable if hand7 == "check" or hand7 == "call": turn hand8 = input() while playing == True: if hand8 == "fold": unable if hand8 == "check" or hand8 == "call": allin if hand8 == "raise": raise7 = int(input()) while playing == True: if raise7 < 10000: no if raise7 >= 10000 and raise7 < 100000: if labat_chips < 100000: k if labat_chips >= 100000: river hand9 = input() while playing == True: if hand9 == "fold": unable if hand9 == "check" or hand9 == "call": allin if hand9 == "raise": raise8 = int(input()) while playing == True: if raise8 < 10000: no if raise8 >= 10000 and raise8 < 100000: if labat_chips < 100000: k if labat_chips >= 100000: k if raise8 >= 100000 and raise8 < 200000: if labat_chips < 100000: k if labat_chips >= 100000: k if raise8 >= 200000 and raise8 < labat_chips: fold if raise8 > labat_chips: no if raise8 == labat_chips: allin else: print("Please place a valid bet") raise8 = int(input()) break if hand9 == "RHTH": p if hand9 == "AllIn": z if hand9 == "chipcount": z if hand9 == "!Help": z else: print("Whats that? Type !Help if you're lost") hand9 = input() break if raise7 >= 100000 and raise7 < 200000: if labat_chips < 100000: k if labat_chips >= 100000: river hand10 = input() while playing == True: if hand10 == "fold": unable if hand10 == "check" or hand10 == "call": allin if hand10 == "raise": raise9 = int(input()) while playing == True: if raise9 < 10000: no if raise9 >= 10000 and raise9 < 100000: if labat_chips < 100000: k if labat_chips >= 100000: k if raise9 >= 100000 and raise9 < 200000: if labat_chips < 100000: k if labat_chips >= 100000: k if raise9 >= 200000 and raise9 < labat_chips: fold if raise9 > labat_chips: no if raise9 == labat_chips: allin else: print("Please place a valid bet") raise9 = int(input()) break if hand10 == "RHTH": p if hand10 == "AllIn": z if hand10 == "chipcount": z if hand10 == "!Help": z else: print("Whats that? Type !Help if you're lost") hand10 = input() break if raise7 >= 200000 and raise7 < labat_chips: fold if raise7 > labat_chips: no if raise7 == labat_chips: allin else: print("Please place a valid bet") raise7 = int(input()) break if hand8 == "RHTH": p if hand8 == "AllIn": z if hand8 == "chipcount": z if hand8 == "!Help": z else: print("Whats that? Type !Help if you're lost") hand4 = input() break if hand7 == "raise": raise10 = int(input()) while playing == True: if raise10 < 10000: no if raise10 >= 10000 and raise10 < 100000: if labat_chips < 100000: k if labat_chips >= 100000: k if raise10 >= 100000 and raise10 < 200000: if labat_chips < 100000: k if labat_chips >= 100000: k if raise10 >= 200000 and raise10 < labat_chips: fold if raise10 > labat_chips: no if raise10 == labat_chips: allin else: print("Please place a valid bet") raise10 = int(input()) break if hand7 == "RHTH": p if hand7 == "AllIn": z if hand7 == "chipcount": z if hand7 == "!Help": z else: print("Whats that? Type !Help if you're lost") hand7 = input() break if raise6 >= 125000 and raise6 < 200000: if labat_chips < 100000: k if labat_chips >= 100000: k if raise6 >= 200000 and raise6 < labat_chips: fold if raise6 > labat_chips: no if raise6 == labat_chips: allin else: print("Please place a valid bet") raise6 = int(input()) break if hand1 == "RHTH": p if hand1 == "AllIn": z if hand1 == "chipcount": z if hand1 == "!Help": z else: print("Whats that? Type !Help if you're lost") hand1 = input()
[ "fredwright2000@live.co.uk" ]
fredwright2000@live.co.uk
d74f554aea68d203ac43a1f290f9c5db8750e3f0
d2b419ba3eff962135d2cc763babb9d042991112
/ac23.py
473391bf061c5c17dd4c7d238ac224066b3d5eb6
[]
no_license
mss-batch-16/batch16
e8000aedfd3de1bb7db6d7ece6d077bfb626b92a
8a30e54f5740595536da01814420b3d6431407d5
refs/heads/master
2020-12-04T00:17:15.754628
2020-01-08T10:21:35
2020-01-08T10:21:35
231,535,308
0
0
null
null
null
null
UTF-8
Python
false
false
81
py
hello guys, i will get a job in 3 months because i am preparing devops much more
[ "devops@gmail.com" ]
devops@gmail.com
0f8e34d48b3d1c84947d5930430793223a87c3ef
5b1e3abd07c4c048e429e0c58c2319e947ab8ffa
/lbforum/__init__.py
9107c2bfe8fffe679cdfee154b7e961e9f59fd29
[ "BSD-3-Clause" ]
permissive
MechanisM/LBForum
bdd84890faf28a5a7343fe4c8f3029a0423a9e69
5be3aedbba5c4974abc10c8bde245502e7484681
refs/heads/master
2021-01-16T23:14:48.432494
2011-08-05T13:57:43
2011-08-05T13:57:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
24
py
__version__ = '0.9.13'
[ "zbirder@gmail.com" ]
zbirder@gmail.com
29f3309483418acfc90bf76c8fb5920c33597cfe
962b3d0c0f3cb06557a84781716fe958cf9be983
/eval.py
0d5c79e2c125752666e943ab4d94fbe6accb0351
[]
no_license
SanandaB/Natural-Language-Processing
a37231e1bdf00ffd5863bb74f3f1165f318fcd24
338fea4818699520bfedf1e2b4479044eac55a51
refs/heads/master
2021-09-02T03:23:52.298209
2017-12-29T22:47:03
2017-12-29T22:47:03
115,755,892
0
0
null
null
null
null
UTF-8
Python
false
false
634
py
import sys def eval(keys, predictions): """ Simple minded eval system: file1 is gold standard, file2 is system outputs. Result is straight accuracy. """ count = 0.0 correct = 0.0 for key, prediction in zip(keys, predictions): key = key.strip() prediction = prediction.strip() if key == '': continue count += 1 if key == prediction: correct += 1 #print correct print("Evaluated ", count, " tags.") print("Accuracy is: ", correct / count) if __name__ == "__main__": keys = open(sys.argv[1]) predictions = open(sys.argv[2]) eval(keys, predictions)
[ "sananda.banerjee@hotmail.com" ]
sananda.banerjee@hotmail.com
5f403a5606342b53ee9da6cadc0ac20fc3af43d6
4594e67c529c5988e2f7606fe59248f402d38a76
/luddo.py
c598f8aa10a8519a249b2f5402f8ae317529d799
[]
no_license
pydeereddy792/PYTHON
199a13e33e71dde4285d52dad4c996e1d3ad1338
e078bd2c4ca113d3aecf824ace34b070c9f1526f
refs/heads/master
2020-03-28T12:00:20.469662
2018-11-16T10:57:42
2018-11-16T10:57:42
148,263,359
1
0
null
null
null
null
UTF-8
Python
false
false
151
py
#write a program to roll and quit the dice while True: i=input("enter 'n' to quit") if(i=='n'): print("bye") exit() else: print("try again")
[ "noreply@github.com" ]
pydeereddy792.noreply@github.com
b139025a4407afb8f70c6c0b6506e0b97968e561
de19ca3aa0b74a00b5f2ff24a097593ee6921eec
/a03_prickettr.py
fc74c1f7e23be0e99a5ef357f3321c9598190bc5
[ "MIT" ]
permissive
spring-2019-csc-226/a03-master
874ed2bbc0f5e88a1475db36d1b06b9652eab273
7be446b28d5aebfc4c4635cc418db0c0c0fadbca
refs/heads/master
2020-04-19T15:56:39.417986
2019-03-01T20:29:02
2019-03-01T20:29:02
168,289,029
0
1
MIT
2019-03-01T20:29:03
2019-01-30T06:09:27
Python
UTF-8
Python
false
false
2,356
py
################################################################################# # Author: Robert Prickett # Username: prickettr # # Assignment: A03: A Pair of Fully Functional Gitty Psychedelic Robotic Turtles # Link: https://docs.google.com/document/d/1gMddsifPMImntv5zzTSnBIvh6N03kJfG7NIatMYG7ok/edit# # Purpose: Learning how to define and call functions. ################################################################################# # Acknowledgements: # Black Sabbath # ################################################################################# import turtle def title_1(ozzy): """ This function draws the words Black Sabbath in purple :return: """ ozzy.color("purple") ozzy.hideturtle() ozzy.penup() ozzy.setposition(-25,190) ozzy.pendown() ozzy.write("BLACK", move=False, align='center', font=('Letraset', 75, ('italic', 'normal'))) ozzy.penup() ozzy.setposition(-50,75) ozzy.pendown() ozzy.write("SABBATH", move=False, align='center', font=('Letraset', 110, ('italic', 'normal'))) ozzy.penup() def title_2(ozzy): """ This function draws the words Masters Of Reality in #A1A1A1 color :return: """ ozzy.color("#A1A1A1") ozzy.penup() ozzy.setposition(-20,-30) ozzy.pendown() ozzy.write("MASTER", move=False, align='center', font=('Letraset', 110, ('italic', 'normal'))) ozzy.penup() ozzy.setposition(-60,-140) ozzy.pendown() ozzy.write("OF", move=False, align='center', font=('Letraset', 110, ('bold', 'normal'))) ozzy.penup() ozzy.setposition(-55,-260) ozzy.pendown() ozzy.write("REALITY", move=False, align='center', font=('Letraset', 110, ('italic', 'normal'))) ozzy.penup() def title_embelish(ozzy): """ This function draws some emblishments to make the album cover look somewhat authentic. :return: """ ozzy.setposition(-107,-90) ozzy.color("#A1A1A1") ozzy.pensize(40) ozzy.pendown() ozzy.begin_fill() for i in range(8): ozzy.left(45) ozzy.forward(30) def main(): """ This is the main function for drawing Masters Of Reality :return: """ wn = turtle.Screen() wn.bgcolor("black") ozzy = turtle.Turtle() title_1(ozzy) title_2(ozzy) title_embelish(ozzy) wn.exitonclick() main()
[ "thebrowniethatputmein@gmail.com" ]
thebrowniethatputmein@gmail.com
b6ebbb47ce8ed3feb705ac92c37cae8fce6f828d
842184bc3c73bef3dd5c2ab523eb33f34b7809ea
/ledger_processor/test_ledger_processor.py
0f1549e715a92ae4a28e218d752a9cddb2608f8c
[]
no_license
fawkesley/h-work-simulation
1cb51515fcb57d1f12c13178b049c4e7f8d1702d
3f150d773a73a2dc2646e7b9c102f298e26cb936
refs/heads/master
2021-05-29T22:12:30.148431
2015-06-12T16:53:32
2015-06-13T07:51:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,060
py
import datetime from decimal import Decimal from os.path import dirname, join as pjoin from nose.tools import assert_equal, assert_raises from .ledger_processor import LedgerProcessor EXAMPLE_LEDGER_FILENAME = pjoin(dirname(__file__), 'example_ledger.csv') TEST_CASES = [ ('john', datetime.date(2015, 1, 16), Decimal('0.00')), ('mary', datetime.date(2015, 1, 16), Decimal('0.00')), ('supermarket', datetime.date(2015, 1, 16), Decimal('0.00')), ('insurance', datetime.date(2015, 1, 16), Decimal('0.00')), ('mary', datetime.date(2015, 1, 17), Decimal('125.00')), ('john', datetime.date(2015, 1, 17), Decimal('-125.00')), ('john', datetime.date(2015, 1, 18), Decimal('-145.00')), ('supermarket', datetime.date(2015, 1, 18), Decimal('20.00')), ('mary', datetime.date(2015, 1, 18), Decimal('25.00')), ('insurance', datetime.date(2015, 1, 18), Decimal('100.00')), ] def test_get_balance(): for account, test_date, expected_balance in TEST_CASES: yield _assert_balance_equal, account, test_date, expected_balance def _assert_balance_equal(account, test_date, expected_balance): with open(EXAMPLE_LEDGER_FILENAME, 'r') as f: ledger = LedgerProcessor(f) got_balance = ledger.get_balance(account, test_date) assert_equal(expected_balance, got_balance) def test_get_all_balances(): with open(EXAMPLE_LEDGER_FILENAME, 'r') as f: ledger = LedgerProcessor(f) final_balances = ledger.get_all_balances(datetime.date(2015, 1, 18)) expected_final_balances = { 'john': Decimal('-145.00'), 'mary': Decimal('25.00'), 'supermarket': Decimal('20.00'), 'insurance': Decimal('100.00'), } assert_equal(expected_final_balances, final_balances) def test_ledger_cant_be_used_twice(): with open(EXAMPLE_LEDGER_FILENAME, 'r') as f: ledger = LedgerProcessor(f) def use_ledger(): ledger.get_all_balances(datetime.date(2015, 1, 18)) use_ledger() assert_raises(RuntimeError, use_ledger)
[ "paul@paulfurley.com" ]
paul@paulfurley.com
12b50bc82a6e2061cd5df1a929c36d92652ff5c1
03e134c849e8edb2d481b3f0f132d07f53e9c759
/alsShop/settings.py
55cae825a930dda94b9cc6180900e743d4838948
[]
no_license
MACmidiDEV/ALs-Bikes
ffd1193f01907dc833e81690c28a0a7884208d07
2d7335e82bf4370eb74782d1daf8199b0d720d13
refs/heads/master
2020-12-04T10:41:36.580484
2020-07-03T01:45:53
2020-07-03T01:45:53
231,732,763
0
0
null
null
null
null
UTF-8
Python
false
false
3,615
py
""" Django settings for alsShop project. Generated by 'Miguel Camacho' using Django 1.11.15. https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os import dj_database_url if os.path.exists('env.py'): import env # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ.get("SECRET_KEY") # WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [ 'als-bikestore.herokuapp.com','127.0.0.1', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_forms_bootstrap', 'home', 'accounts', 'bikes', ] 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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'alsShop.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', ], }, }, ] WSGI_APPLICATION = 'alsShop.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases if "DATABASE_URL" in os.environ: DATABASES = { 'default': dj_database_url.parse(os.environ.get('DATABASE_URL')) } else: print("Postgres URL not found, using sqlite instead") DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.11/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', }, ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'accounts.backends.CaseInsensitiveAuth', ] # Internationalization # https://docs.djangoproject.com/en/1.11/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.11/howto/static-files/ MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), ) MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'
[ "mcamacho1990@icloud.com" ]
mcamacho1990@icloud.com
26a78fbf1c2257047a8c3016c4b71785e51ab864
4ff61649205d6bd6038b932615e39d6c78a1ee5c
/code/Train_Single_View_ST.py
3901ae4a206a6f0c0fc477b43f702847b7ed80ef
[ "MIT" ]
permissive
rahul-islam/multi-view-gaze
f40c63361fb2b181a9b11115588ce3409bc851c5
5e1b6334b23ab5ed5f618b4e1e0ed9c2c23781cf
refs/heads/master
2022-04-01T18:47:42.636935
2020-01-12T15:39:40
2020-01-12T15:39:40
null
0
0
null
null
null
null
UTF-8
Python
false
false
14,605
py
""" @author: Dongze Lian @contact: liandz@shanghaitech.edu.cn @software: PyCharm @file: Train_Single_View_ST.py @time: 2020/1/11 22:01 """ import sys sys.path.append('..') import argparse import numpy as np import time import torch import torchvision.models as models import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import Dataset, DataLoader from torchvision import datasets, transforms from PIL import Image import logging import os import scipy.io as sio from tensorboardX import SummaryWriter import network.gazenet as gazenet import network.resnet as resnet import tools.utils as utils import pdb parser = argparse.ArgumentParser(description='Network and training parameters choices') # Network choices parser.add_argument('--network', type=str, default='ResNet-34', metavar='backbone') parser.add_argument('--data_dir', type=str, default='/path/to/ShanghaiTechGaze/', metavar='NET', help='dataset dir') parser.add_argument('--camera', type=str, default='leftcamera', metavar='camera', help='leftcamera, middlecamera, rightcamera (default: leftcamera)') parser.add_argument('--batch-size', type=int, default=128, metavar='N', help='input batch size for training (default: 64)') parser.add_argument('--test-batch-size', type=int, default=200, metavar='N', help='input batch size for testing (default: 1)') parser.add_argument('--epochs', type=int, default=15, metavar='N', help='number of epochs to train (default: 10)') parser.add_argument('--num_workers', type=int, default=16) parser.add_argument('--lr', type=float, default=1e-5, metavar='LR', help='learning rate (default: 0.01)') parser.add_argument('--lr-decay', type=int, default=10, metavar='N', help='lr decay interval with epoch (default: 10)') parser.add_argument('--momentum', type=float, default=0.9, metavar='M', help='SGD momentum (default: 0.9)') parser.add_argument('--weight-decay', type=float, default=5e-4, metavar='M', help='Weight decay (default: 5e-4)') parser.add_argument('--no-cuda', action='store_true', default=False, help='disables CUDA training') parser.add_argument('--resume', default='', type=str, help='path to the lastest checkpoint (default: none)') parser.add_argument('--seed', type=int, default=1, metavar='S', help='random seed (default: 1)') parser.add_argument('--print_freq', type=int, default=20, metavar='N') parser.add_argument('--ckpt_freq', type=int, default=5, metavar='N',) parser.add_argument('--gpu', type=int, default=0, metavar='N', help='which gpu device (default: 0)') args = parser.parse_args() args.cuda = not args.no_cuda and torch.cuda.is_available() # log path setting exp_path = os.path.join('/path/to/multi-view-gaze/exps', time.strftime('%Y-%m-%d-%H-%M', time.localtime(time.time()))) if not os.path.exists(exp_path): os.makedirs(exp_path) # tensorboardX setting writer = SummaryWriter(os.path.join(exp_path, 'runs')) # log setting log_file = os.path.join(exp_path, 'exp.log') logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s', filename=log_file, filemode='w') console = logging.StreamHandler() console.setLevel(logging.INFO) logging.getLogger('').addHandler(console) # print setting logging.info(args) # Dataset processing class GazeImageDataset(Dataset): def __init__(self, txt_file, txt_dir, transform=None): self.txt_dir = txt_dir self.transform = transform self.lefteye_name_list = utils.txt2list(os.path.join(self.txt_dir, txt_file[0])) self.righteye_name_list = utils.txt2list(os.path.join(self.txt_dir, txt_file[1])) self.eyelocation_name_list = utils.txt2list(os.path.join(self.txt_dir, txt_file[2])) self.gt_name_list = utils.txt2list(os.path.join(self.txt_dir, txt_file[3])) # pdb.set_trace() def __len__(self): return len(self.lefteye_name_list) def __getitem__(self, idx): lefteye_name = args.data_dir + self.lefteye_name_list[idx] righteye_name = args.data_dir + self.righteye_name_list[idx] eyelocation_name = args.data_dir + self.eyelocation_name_list[idx] gt_name = args.data_dir + self.gt_name_list[idx] lefteye = Image.open(lefteye_name) righteye = Image.open(righteye_name) eyelocation = sio.loadmat(eyelocation_name)['eyelocation'] gt = sio.loadmat(gt_name)['xy_gt'] # ground truth normalization gt[0] -= W_screen / 2 gt[1] -= H_screen / 2 sample = {} if self.transform: sample['le'] = self.transform(lefteye) sample['re'] = self.transform(righteye) sample['eyelocation'] = torch.squeeze(torch.FloatTensor(eyelocation)) sample['gt'] = torch.FloatTensor(gt) return sample # training def train(train_loader, model, criterion, optimizer, epoch): batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() error = AverageMeter() model.train() end = time.time() for batch_idx, input in enumerate(train_loader): data_time.update(time.time() - end) data, target = (input['le'], input['re'], input['eyelocation']), input['gt'] if args.cuda: data, target = (data[0].cuda(), data[1].cuda(), data[2].cuda()), target.cuda() output = model(*data) target = target.view(target.size(0), -1) loss = criterion(output, target) optimizer.zero_grad() loss.backward() optimizer.step() # Measure point error and record loss point_error = compute_error(output, target) losses.update(loss.item(), data[0].size(0)) error.update(point_error, data[0].size(0)) batch_time.update(time.time() - end) end = time.time() writer.add_scalar('Train/Loss', losses.avg, batch_idx + len(train_loader) * epoch) writer.add_scalar('Train/Error', error.avg, batch_idx + len(train_loader) * epoch) # print the intermediate results if batch_idx % args.print_freq == 0: logging.info('Time({}:{:.0f}), Train Epoch [{}]: [{}/{}]\t' 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 'Data {data_time.val:.3f} ({data_time.avg:.3f})\t' 'Loss {loss.val:.3f} ({loss.avg:.3f})\t' 'Error {error.val:.3f} ({error.avg:.3f})'.format( time.strftime('%Y-%m-%d %H:%M', time.localtime(time.time())), time.time() % 60, epoch, batch_idx, len(train_loader), batch_time=batch_time, data_time=data_time, loss=losses, error=error)) # testing def test(test_loader, model, criterion, epoch, minimal_error): batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() error = AverageMeter() with torch.no_grad(): model.eval() end = time.time() for batch_idx, input in enumerate(test_loader): data_time.update(time.time() - end) data, target = (input['le'], input['re'], input['eyelocation']), input['gt'] if args.cuda: data, target = (data[0].cuda(), data[1].cuda(), data[2].cuda()), target.cuda() output = model(*data) target = target.view(target.size(0), -1) loss = criterion(output, target) point_error = compute_error(output, target) losses.update(loss.item(), data[0].size(0)) error.update(point_error, data[0].size(0)) batch_time.update(time.time() - end) end = time.time() # print the intermediate results if batch_idx % args.print_freq == 0: logging.info('Time({}:{:.0f}), Test Epoch [{}]: [{}/{}]\t' 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 'Data {data_time.val:.3f} ({data_time.avg:.3f})\t' 'Loss {loss.val:.3f} ({loss.avg:.3f})\t' 'Error {error.val:.3f} ({error.avg:.3f})'.format( time.strftime('%Y-%m-%d %H:%M', time.localtime(time.time())), time.time() % 60, epoch, batch_idx, len(test_loader), batch_time=batch_time, data_time=data_time, loss=losses, error=error)) writer.add_scalar('Test/Loss', losses.avg, epoch) writer.add_scalar('Test/Error', error.avg, epoch) logging.info(' * Test Error {error.avg:.3f} Minimal_error {minimal_error:.3f}' .format(error=error, minimal_error=minimal_error)) return error.avg class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def compute_error(output, target): """Computes the point error between prediction and gt""" with torch.no_grad(): output = output.cpu().numpy() target = target.cpu().numpy() delta = (output - target) ** 2 error = np.sqrt(delta.sum(axis=1)).mean() return error def save_checkpoint(state, filename='checkpoint.pth.tar'): torch.save(state, filename) def adjust_learning_rate(optimizer, epoch): new_lr = args.lr * (0.1 ** (epoch // args.lr_decay)) for param_group in optimizer.param_groups: param_group['lr'] = new_lr return new_lr # ========================================== network config =============================================== minimal_error = 100000 W_screen = 59.77 # the width of screen H_screen = 33.62 # the height of screen #model = DN4Net.define_DN4Net(which_network=args.network) model = gazenet.GazeNet(backbone=args.network, pretrained=True) #model = resnet.resnet34(pretrained=True) model = nn.DataParallel(model).cuda() optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay) criterion = nn.MSELoss() # optionally resume from a checkpoint if args.resume: if os.path.isfile(args.resume): print("=> loading checkpoint '{}'".format(args.resume)) checkpoint = torch.load(args.resume) epoch_index = checkpoint['epoch'] minimal_error = checkpoint['minimal_error'] model.load_state_dict(checkpoint['state_dict']) optimizer.load_state_dict(checkpoint['optimizer']) print("=> loaded checkpoint '{}' (epoch {})".format(args.resume, checkpoint['epoch'])) else: print("=> no checkpoint found at '{}'".format(args.resume)) # ======================================= Build dataset ======================================= # image transform & normalization data_transforms = transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) train_dataset = GazeImageDataset( txt_file=[args.camera + '/lefteye.txt', args.camera + '/righteye.txt', args.camera + '/eyelocation.txt', 'gt.txt'], txt_dir=args.data_dir + 'annotations/txtfile/train_txt/', transform=data_transforms) logging.info('The number of training data is: {}'.format(len(train_dataset))) test_dataset = GazeImageDataset( txt_file=[args.camera + '/lefteye.txt', args.camera + '/righteye.txt', args.camera + '/eyelocation.txt', 'gt.txt'], txt_dir=args.data_dir + 'annotations/txtfile/test_txt/', transform=data_transforms) logging.info('The number of testing data is: {}'.format(len(test_dataset))) train_loader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True, num_workers=args.num_workers, pin_memory=True) test_loader = DataLoader(test_dataset, batch_size=args.test_batch_size, shuffle=False, num_workers=args.num_workers, pin_memory=True) # ======================================== Start Training =============================================== logging.info('\n............Start training............\n') #start_time = time.time() for epoch in range(args.epochs): new_lr = adjust_learning_rate(optimizer, epoch) logging.info('Current learning rate: {}'.format(new_lr)) # ============================================ Training =========================================== logging.info('============ Train stage ============') train(train_loader, model, criterion, optimizer, epoch) # =========================================== Evaluation ========================================== logging.info('============ Test stage ============') test_error = test(test_loader, model, criterion, epoch, minimal_error) # record the minimal error and save checkpoint is_best = test_error < minimal_error minimal_error = min(test_error, minimal_error) # save the checkpoint ckpt_path = os.path.join(exp_path, 'ckpts') if not os.path.exists(ckpt_path): os.makedirs(ckpt_path) if is_best: logging.info('Minimal error {} in epoch {}'.format(minimal_error, epoch)) save_checkpoint( { 'epoch': epoch, 'state_dict': model.state_dict(), 'minimal_error': minimal_error, 'optimizer': optimizer.state_dict(), }, os.path.join(ckpt_path, 'model_best.pth.tar')) if epoch % args.ckpt_freq == 0: filename = os.path.join(ckpt_path, 'epoch_%d.pth.tar' % epoch) save_checkpoint( { 'epoch': epoch, 'state_dict': model.state_dict(), 'minimal_error': minimal_error, 'optimizer': optimizer.state_dict(), }, filename)
[ "liandz@shanghaitech.edu.cn" ]
liandz@shanghaitech.edu.cn
9e9c18f7e871ac4aa81ee97d0a67835707d998a2
0cb05614be2a08c05ca5f03a5935c77918c64cb6
/Functions.py
3ff495e4d7854d6b99ce081b3ce4dfa60bba027d
[]
no_license
Arditagalliu/Python-Beginners-Notes
cb3fd0f773fa709ae722fcd3f37ea832382c060d
6c1bb18a427903120a4dcdfef016d01d695e6e7d
refs/heads/main
2023-02-04T17:57:34.222748
2020-12-23T15:13:04
2020-12-23T15:13:04
323,933,358
1
0
null
null
null
null
UTF-8
Python
false
false
1,550
py
def greeting(name): print("Welcome " + name) def counter(surname): count = len(surname) return count username = input("Whats your name ") greeting(username) user_surname = input("Whats your surname ") print("Your surname has ", counter(user_surname), " letters") if counter(user_surname) < 10: print("Your surname is small") elif counter(user_surname) > 10: print("Your surname is long") else: print("Your surname is medium") is_male = True is_female = False if (is_male or is_female) and not(is_male and is_female): if is_male: print("you are male") else: print("you are female") elif is_male and is_female: print("something is wrong you cant be both") def find_max(num1, num2): if num1 > num2: return "the first" elif num2 > num1: return "the second" elif num1 == num2: return "none! they are equal" number1 = int(input("Enter a number: ")) number2 = int(input("Enter a second number: ")) print("The highest number is:" + find_max(number1, number2)) fruits = ["apple", "banana", "cherry"] if "banana" in fruits: print("There is a banana in the fruits list") else: print("There is not a banana in the fruits list") def local_var(): var = "This is local" print(var) var = "This is global" local_var() print(var) def local_var2(): global var2 var2 = "Now is global" print(var2) var2 = "This is global" local_var2() print(var2)
[ "noreply@github.com" ]
Arditagalliu.noreply@github.com
d3821029fc73f48cb4f0236dd224d57b0203a6bb
76369dba56fa9d3b265486b9ab10279cd16de5e9
/python/retangulo.py
2d3b80fe8416b52fa558aff5348a35dcccb165d1
[]
no_license
acenelio/curso-algoritmos
29f24e49865a9a2626af7b67fa453c183ec060dc
71a46ddc6e7871e999cec529637b0e199a87b716
refs/heads/master
2023-01-13T06:43:17.099401
2023-01-03T23:55:37
2023-01-03T23:55:37
220,841,002
403
191
null
2022-12-13T01:59:29
2019-11-10T19:40:30
Java
UTF-8
Python
false
false
390
py
import math base: float; altura: float; area: float; perimetro: float; diagonal: float; base = float(input("Base do retangulo: ")) altura = float(input("Altura do retangulo: ")) area = base * altura perimetro = 2 * (base + altura) diagonal = math.sqrt(base * base + altura * altura) print(f"AREA = {area:.4f}") print(f"PERIMETRO = {perimetro:.4f}") print(f"DIAGONAL = {diagonal:.4f}")
[ "vhugo08.couto@gmail.com" ]
vhugo08.couto@gmail.com
1d0db4066b836fa8d910f76f964bfbac9cb3ebc5
751d5c1df8cea4dbbdac1d812a3f301a4328ff8e
/server/firmware/__init__.py
ae93dcc32cb607471356a0c3645b73e1d7fdd2f2
[ "MIT" ]
permissive
ms1solutionsg0/tcs
1fcda09ac45009ae3a8b6ee331846072b2f202f9
f5bd9b9c202fd45c8612020d6370fb1dabf7a536
refs/heads/master
2020-04-15T06:38:27.571684
2019-11-26T20:10:38
2019-11-26T20:10:38
164,467,334
0
0
MIT
2019-11-26T20:10:39
2019-01-07T17:29:56
JavaScript
UTF-8
Python
false
false
26
py
from .shield import Shield
[ "stanislaw.dac@gmail.com" ]
stanislaw.dac@gmail.com
6aa3828a32163e80c8d12eaeda888341881c4a0d
f26322b62be667711ca13f3ea73d89b79011459b
/py/models/__init__.py
b4d9c72fe94e27e7ca8052d7c88a8308c3887b88
[ "Apache-2.0" ]
permissive
zjZSTU/SPP-net
c37c3dcd05bd5fb04cf7ef7efda4ac7dfdc5f89d
e42166dddd37b9493a5aacef18303aa850b21be7
refs/heads/master
2022-07-09T22:46:16.254859
2020-04-04T15:09:19
2020-04-04T15:09:19
250,167,176
3
2
Apache-2.0
2022-06-22T01:36:06
2020-03-26T05:12:56
Python
UTF-8
Python
false
false
109
py
# -*- coding: utf-8 -*- """ @date: 2020/3/26 下午4:20 @file: __init__.py.py @author: zj @description: """
[ "505169307@qq.com" ]
505169307@qq.com
d4fdbed76383d85a2fa0b5a4b0e41628313a2037
080bbe77da955b3917435c25fc63b90b0f3c724e
/botorch/test_functions/multi_objective.py
5ea244ee18797620b86ffb02739a044648f09561
[ "MIT" ]
permissive
irinaespejo/botorch
3d15d962ff0f5bb34fbd11b2eb7549db755af705
e4dcf603fdaf83f0e5f8b9b392f943c89dfff7eb
refs/heads/master
2023-07-11T18:02:11.853790
2021-08-19T15:57:21
2021-08-19T15:58:12
316,017,084
0
0
MIT
2020-11-25T18:02:11
2020-11-25T18:02:09
null
UTF-8
Python
false
false
25,982
py
#! /usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. r""" Multi-objective optimization benchmark problems. References .. [Deb2005dtlz] K. Deb, L. Thiele, M. Laumanns, E. Zitzler, A. Abraham, L. Jain, R. Goldberg. "Scalable test problems for evolutionary multi-objective optimization" in Evolutionary Multiobjective Optimization, London, U.K.: Springer-Verlag, pp. 105-145, 2005. .. [Deb2005robust] K. Deb, H. Gupta. "Searching for Robust Pareto-Optimal Solutions in Multi-objective Optimization" in Evolutionary Multi-Criterion Optimization, Springer-Berlin, pp. 150-164, 2005. .. [GarridoMerchan2020] E. C. Garrido-Merch ́an and D. Hern ́andez-Lobato. Parallel Predictive Entropy Search for Multi-objective Bayesian Optimization with Constraints. arXiv e-prints, arXiv:2004.00601, Apr. 2020. .. [Gelbart2014] Michael A. Gelbart, Jasper Snoek, and Ryan P. Adams. 2014. Bayesian optimization with unknown constraints. In Proceedings of the Thirtieth Conference on Uncertainty in Artificial Intelligence (UAI’14). AUAI Press, Arlington, Virginia, USA, 250–259. .. [Oszycka1995] A. Osyczka, S. Kundu. 1995. A new method to solve generalized multicriteria optimization problems using the simple genetic algorithm. In Structural Optimization 10. 94–99. .. [Tanabe2020] Ryoji Tanabe, Hisao Ishibuchi, An easy-to-use real-world multi-objective optimization problem suite, Applied Soft Computing,Volume 89, 2020. .. [Yang2019a] K. Yang, M. Emmerich, A. Deutz, and T. Bäck. 2019. "Multi-Objective Bayesian Global Optimization using expected hypervolume improvement gradient" in Swarm and evolutionary computation 44, pp. 945--956, 2019. .. [Zitzler2000] E. Zitzler, K. Deb, and L. Thiele, “Comparison of multiobjective evolutionary algorithms: Empirical results,” Evol. Comput., vol. 8, no. 2, pp. 173–195, 2000. """ from __future__ import annotations import math from abc import ABC, abstractmethod from typing import Optional import torch from botorch.test_functions.base import ( ConstrainedBaseTestProblem, MultiObjectiveTestProblem, ) from botorch.test_functions.synthetic import Branin from botorch.utils.sampling import sample_hypersphere, sample_simplex from botorch.utils.transforms import unnormalize from scipy.special import gamma from torch import Tensor class BraninCurrin(MultiObjectiveTestProblem): r"""Two objective problem composed of the Branin and Currin functions. Branin (rescaled): f(x) = ( 15*x_1 - 5.1 * (15 * x_0 - 5) ** 2 / (4 * pi ** 2) + 5 * (15 * x_0 - 5) / pi - 5 ) ** 2 + (10 - 10 / (8 * pi)) * cos(15 * x_0 - 5)) Currin: f(x) = (1 - exp(-1 / (2 * x_1))) * ( 2300 * x_0 ** 3 + 1900 * x_0 ** 2 + 2092 * x_0 + 60 ) / 100 * x_0 ** 3 + 500 * x_0 ** 2 + 4 * x_0 + 20 """ dim = 2 num_objectives = 2 _bounds = [(0.0, 1.0), (0.0, 1.0)] _ref_point = [18.0, 6.0] _max_hv = 59.36011874867746 # this is approximated using NSGA-II def __init__(self, noise_std: Optional[float] = None, negate: bool = False) -> None: r"""Constructor for Branin-Currin. Args: noise_std: Standard deviation of the observation noise. negate: If True, negate the objectives. """ super().__init__(noise_std=noise_std, negate=negate) self._branin = Branin() def _rescaled_branin(self, X: Tensor) -> Tensor: # return to Branin bounds x_0 = 15 * X[..., 0] - 5 x_1 = 15 * X[..., 1] return self._branin(torch.stack([x_0, x_1], dim=-1)) @staticmethod def _currin(X: Tensor) -> Tensor: x_0 = X[..., 0] x_1 = X[..., 1] factor1 = 1 - torch.exp(-1 / (2 * x_1)) numer = 2300 * x_0.pow(3) + 1900 * x_0.pow(2) + 2092 * x_0 + 60 denom = 100 * x_0.pow(3) + 500 * x_0.pow(2) + 4 * x_0 + 20 return factor1 * numer / denom def evaluate_true(self, X: Tensor) -> Tensor: # branin rescaled with inputsto [0,1]^2 branin = self._rescaled_branin(X=X) currin = self._currin(X=X) return torch.stack([branin, currin], dim=-1) class DH(MultiObjectiveTestProblem, ABC): r"""Base class for DH problems for robust multi-objective optimization. In their paper, [Deb2005robust]_ consider these problems under a mean-robustness setting, and use uniformly distributed input perturbations from the box with edge lengths `delta_0 = delta`, `delta_i = 2 * delta, i > 0`, with `delta` ranging up to `0.01` for DH1 and DH2, and `delta = 0.03` for DH3 and DH4. These are d-dimensional problems with two objectives: f_0(x) = x_0 f_1(x) = h(x) + g(x) * S(x) for DH1 and DH2 f_1(x) = h(x) * (g(x) + S(x)) for DH3 and DH4 The goal is to minimize both objectives. See [Deb2005robust]_ for more details on DH. The reference points were set using `infer_reference_point`. """ num_objectives = 2 _ref_point: float = [1.1, 1.1] _x_1_lb: float _area_under_curve: float _min_dim: int def __init__( self, dim: int, noise_std: Optional[float] = None, negate: bool = False, ) -> None: if dim < self._min_dim: raise ValueError(f"dim must be >= {self._min_dim}, but got dim={dim}!") self.dim = dim self._bounds = [(0.0, 1.0), (self._x_1_lb, 1.0)] + [ (-1.0, 1.0) for _ in range(dim - 2) ] # max_hv is the area of the box minus the area of the curve formed by the PF. self._max_hv = self._ref_point[0] * self._ref_point[1] - self._area_under_curve super().__init__(noise_std=noise_std, negate=negate) @abstractmethod def _h(self, X: Tensor) -> Tensor: pass # pragma: no cover @abstractmethod def _g(self, X: Tensor) -> Tensor: pass # pragma: no cover @abstractmethod def _S(self, X: Tensor) -> Tensor: pass # pragma: no cover class DH1(DH): r"""DH1 test problem. d-dimensional problem evaluated on `[0, 1] x [-1, 1]^{d-1}`: f_0(x) = x_0 f_1(x) = h(x_0) + g(x) * S(x_0) h(x_0) = 1 - x_0^2 g(x) = \sum_{i=1}^{d-1} (10 + x_i^2 - 10 * cos(4 * pi * x_i)) S(x_0) = alpha / (0.2 + x_0) + beta * x_0^2 where alpha = 1 and beta = 1. The Pareto front corresponds to the equation `f_1 = 1 - f_0^2`, and it is found at `x_i = 0` for `i > 0` and any value of `x_0` in `(0, 1]`. """ alpha = 1.0 beta = 1.0 _x_1_lb = -1.0 _area_under_curve = 2.0 / 3.0 _min_dim = 2 def _h(self, X: Tensor) -> Tensor: return 1 - X[..., 0].pow(2) def _g(self, X: Tensor) -> Tensor: x_1_to = X[..., 1:] return torch.sum( 10 + x_1_to.pow(2) - 10 * torch.cos(4 * math.pi * x_1_to), dim=-1, ) def _S(self, X: Tensor) -> Tensor: x_0 = X[..., 0] return self.alpha / (0.2 + x_0) + self.beta * x_0.pow(2) def evaluate_true(self, X: Tensor) -> Tensor: f_0 = X[..., 0] # This may encounter 0 / 0, which we set to 0. f_1 = self._h(X) + torch.nan_to_num(self._g(X) * self._S(X)) return torch.stack([f_0, f_1], dim=-1) class DH2(DH1): r"""DH2 test problem. This is identical to DH1 except for having `beta = 10.0`. """ beta = 10.0 class DH3(DH): r"""DH3 test problem. d-dimensional problem evaluated on `[0, 1]^2 x [-1, 1]^{d-2}`: f_0(x) = x_0 f_1(x) = h(x_1) * (g(x) + S(x_0)) h(x_1) = 2 - 0.8 * exp(-((x_1 - 0.35) / 0.25)^2) - exp(-((x_1 - 0.85) / 0.03)^2) g(x) = \sum_{i=2}^{d-1} (50 * x_i^2) S(x_0) = 1 - sqrt(x_0) The Pareto front is found at `x_i = 0` for `i > 1`. There's a local and a global Pareto front, which are found at `x_1 = 0.35` and `x_1 = 0.85`, respectively. The approximate relationships between the objectives at local and global Pareto fronts are given by `f_1 = 1.2 (1 - sqrt(f_0))` and `f_1 = 1 - f_0`, respectively. The specific values on the Pareto fronts can be found by varying `x_0`. """ _x_1_lb = 0.0 _area_under_curve = 0.328449169794718 _min_dim = 3 @staticmethod def _exp_args(x: Tensor) -> Tensor: exp_arg_1 = -((x - 0.35) / 0.25).pow(2) exp_arg_2 = -((x - 0.85) / 0.03).pow(2) return exp_arg_1, exp_arg_2 def _h(self, X: Tensor) -> Tensor: exp_arg_1, exp_arg_2 = self._exp_args(X[..., 1]) return 2 - 0.8 * torch.exp(exp_arg_1) - torch.exp(exp_arg_2) def _g(self, X: Tensor) -> Tensor: return 50 * X[..., 2:].pow(2).sum(dim=-1) def _S(self, X: Tensor) -> Tensor: return 1 - X[..., 0].sqrt() def evaluate_true(self, X: Tensor) -> Tensor: f_0 = X[..., 0] f_1 = self._h(X) * (self._g(X) + self._S(X)) return torch.stack([f_0, f_1], dim=-1) class DH4(DH3): r"""DH4 test problem. This is similar to DH3 except that it is evaluated on `[0, 1] x [-0.15, 1] x [-1, 1]^{d-2}` and: h(x_0, x_1) = 2 - x_0 - 0.8 * exp(-((x_0 + x_1 - 0.35) / 0.25)^2) - exp(-((x_0 + x_1 - 0.85) / 0.03)^2) The Pareto front is found at `x_i = 0` for `i > 2`, with the local one being near `x_0 + x_1 = 0.35` and the global one near `x_0 + x_1 = 0.85`. """ _x_1_lb = -0.15 _area_under_curve = 0.22845 def _h(self, X: Tensor) -> Tensor: exp_arg_1, exp_arg_2 = self._exp_args(X[..., :2].sum(dim=-1)) return 2 - X[..., 0] - 0.8 * torch.exp(exp_arg_1) - torch.exp(exp_arg_2) class DTLZ(MultiObjectiveTestProblem): r"""Base class for DTLZ problems. See [Deb2005dtlz]_ for more details on DTLZ. """ def __init__( self, dim: int, num_objectives: int = 2, noise_std: Optional[float] = None, negate: bool = False, ) -> None: if dim <= num_objectives: raise ValueError( f"dim must be > num_objectives, but got {dim} and {num_objectives}." ) self.num_objectives = num_objectives self.dim = dim self.k = self.dim - self.num_objectives + 1 self._bounds = [(0.0, 1.0) for _ in range(self.dim)] self._ref_point = [self._ref_val for _ in range(num_objectives)] super().__init__(noise_std=noise_std, negate=negate) class DTLZ1(DTLZ): r"""DLTZ1 test problem. d-dimensional problem evaluated on `[0, 1]^d`: f_0(x) = 0.5 * x_0 * (1 + g(x)) f_1(x) = 0.5 * (1 - x_0) * (1 + g(x)) g(x) = 100 * \sum_{i=m}^{d-1} ( k + (x_i - 0.5)^2 - cos(20 * pi * (x_i - 0.5)) ) where k = d - m + 1. The pareto front is given by the line (or hyperplane) \sum_i f_i(x) = 0.5. The goal is to minimize both objectives. The reference point comes from [Yang2019]_. """ _ref_val = 400.0 @property def _max_hv(self) -> float: return self._ref_val ** self.num_objectives - 1 / 2 ** self.num_objectives def evaluate_true(self, X: Tensor) -> Tensor: X_m = X[..., -self.k :] X_m_minus_half = X_m - 0.5 sum_term = ( X_m_minus_half.pow(2) - torch.cos(20 * math.pi * X_m_minus_half) ).sum(dim=-1) g_X_m = 100 * (self.k + sum_term) g_X_m_term = 0.5 * (1 + g_X_m) fs = [] for i in range(self.num_objectives): idx = self.num_objectives - 1 - i f_i = g_X_m_term * X[..., :idx].prod(dim=-1) if i > 0: f_i *= 1 - X[..., idx] fs.append(f_i) return torch.stack(fs, dim=-1) def gen_pareto_front(self, n: int) -> Tensor: r"""Generate `n` pareto optimal points. The pareto points randomly sampled from the hyperplane sum_i f(x_i) = 0.5. """ f_X = 0.5 * sample_simplex( n=n, d=self.num_objectives, qmc=True, dtype=self.ref_point.dtype, device=self.ref_point.device, ) if self.negate: f_X *= -1 return f_X class DTLZ2(DTLZ): r"""DLTZ2 test problem. d-dimensional problem evaluated on `[0, 1]^d`: f_0(x) = (1 + g(x)) * cos(x_0 * pi / 2) f_1(x) = (1 + g(x)) * sin(x_0 * pi / 2) g(x) = \sum_{i=m}^{d-1} (x_i - 0.5)^2 The pareto front is given by the unit hypersphere \sum{i} f_i^2 = 1. Note: the pareto front is completely concave. The goal is to minimize both objectives. """ _ref_val = 1.1 @property def _max_hv(self) -> float: # hypercube - volume of hypersphere in R^d such that all coordinates are # positive hypercube_vol = self._ref_val ** self.num_objectives pos_hypersphere_vol = ( math.pi ** (self.num_objectives / 2) / gamma(self.num_objectives / 2 + 1) / 2 ** self.num_objectives ) return hypercube_vol - pos_hypersphere_vol def evaluate_true(self, X: Tensor) -> Tensor: X_m = X[..., -self.k :] g_X = (X_m - 0.5).pow(2).sum(dim=-1) g_X_plus1 = 1 + g_X fs = [] pi_over_2 = math.pi / 2 for i in range(self.num_objectives): idx = self.num_objectives - 1 - i f_i = g_X_plus1.clone() f_i *= torch.cos(X[..., :idx] * pi_over_2).prod(dim=-1) if i > 0: f_i *= torch.sin(X[..., idx] * pi_over_2) fs.append(f_i) return torch.stack(fs, dim=-1) def gen_pareto_front(self, n: int) -> Tensor: r"""Generate `n` pareto optimal points. The pareto points are randomly sampled from the hypersphere's positive section. """ f_X = sample_hypersphere( n=n, d=self.num_objectives, dtype=self.ref_point.dtype, device=self.ref_point.device, qmc=True, ).abs() if self.negate: f_X *= -1 return f_X class VehicleSafety(MultiObjectiveTestProblem): r"""Optimize Vehicle crash-worthiness. See [Tanabe2020]_ for details. The reference point is 1.1 * the nadir point from approximate front provided by [Tanabe2020]_. The maximum hypervolume is computed using the approximate pareto front from [Tanabe2020]_. """ _ref_point = [1864.72022, 11.81993945, 0.2903999384] _max_hv = 246.81607081187002 _bounds = [(1.0, 3.0)] * 5 dim = 5 num_objectives = 3 def evaluate_true(self, X: Tensor) -> Tensor: X1, X2, X3, X4, X5 = torch.split(X, 1, -1) f1 = ( 1640.2823 + 2.3573285 * X1 + 2.3220035 * X2 + 4.5688768 * X3 + 7.7213633 * X4 + 4.4559504 * X5 ) f2 = ( 6.5856 + 1.15 * X1 - 1.0427 * X2 + 0.9738 * X3 + 0.8364 * X4 - 0.3695 * X1 * X4 + 0.0861 * X1 * X5 + 0.3628 * X2 * X4 - 0.1106 * X1.pow(2) - 0.3437 * X3.pow(2) + 0.1764 * X4.pow(2) ) f3 = ( -0.0551 + 0.0181 * X1 + 0.1024 * X2 + 0.0421 * X3 - 0.0073 * X1 * X2 + 0.024 * X2 * X3 - 0.0118 * X2 * X4 - 0.0204 * X3 * X4 - 0.008 * X3 * X5 - 0.0241 * X2.pow(2) + 0.0109 * X4.pow(2) ) f_X = torch.cat([f1, f2, f3], dim=-1) return f_X class ZDT(MultiObjectiveTestProblem): r"""Base class for ZDT problems. See [Zitzler2000]_ for more details on ZDT. """ _ref_point = [11.0, 11.0] def __init__( self, dim: int, num_objectives: int = 2, noise_std: Optional[float] = None, negate: bool = False, ) -> None: if num_objectives != 2: raise NotImplementedError( f"{type(self).__name__} currently only supports 2 objectives." ) if dim < num_objectives: raise ValueError( f"dim must be >= num_objectives, but got {dim} and {num_objectives}" ) self.num_objectives = num_objectives self.dim = dim self._bounds = [(0.0, 1.0) for _ in range(self.dim)] super().__init__(noise_std=noise_std, negate=negate) @staticmethod def _g(X: Tensor) -> Tensor: return 1 + 9 * X[..., 1:].mean(dim=-1) class ZDT1(ZDT): r"""ZDT1 test problem. d-dimensional problem evaluated on `[0, 1]^d`: f_0(x) = x_0 f_1(x) = g(x) * (1 - sqrt(x_0 / g(x)) g(x) = 1 + 9 / (d - 1) * \sum_{i=1}^{d-1} x_i The reference point comes from [Yang2019a]_. The pareto front is convex. """ _max_hv = 120 + 2 / 3 def evaluate_true(self, X: Tensor) -> Tensor: f_0 = X[..., 0] g = self._g(X=X) f_1 = g * (1 - (f_0 / g).sqrt()) return torch.stack([f_0, f_1], dim=-1) def gen_pareto_front(self, n: int) -> Tensor: f_0 = torch.linspace( 0, 1, n, dtype=self.bounds.dtype, device=self.bounds.device ) f_1 = 1 - f_0.sqrt() f_X = torch.stack([f_0, f_1], dim=-1) if self.negate: f_X *= -1 return f_X class ZDT2(ZDT): r"""ZDT2 test problem. d-dimensional problem evaluated on `[0, 1]^d`: f_0(x) = x_0 f_1(x) = g(x) * (1 - (x_0 / g(x))^2) g(x) = 1 + 9 / (d - 1) * \sum_{i=1}^{d-1} x_i The reference point comes from [Yang2019a]_. The pareto front is concave. """ _max_hv = 120 + 1 / 3 def evaluate_true(self, X: Tensor) -> Tensor: f_0 = X[..., 0] g = self._g(X=X) f_1 = g * (1 - (f_0 / g).pow(2)) return torch.stack([f_0, f_1], dim=-1) def gen_pareto_front(self, n: int) -> Tensor: f_0 = torch.linspace( 0, 1, n, dtype=self.bounds.dtype, device=self.bounds.device ) f_1 = 1 - f_0.pow(2) f_X = torch.stack([f_0, f_1], dim=-1) if self.negate: f_X *= -1 return f_X class ZDT3(ZDT): r"""ZDT3 test problem. d-dimensional problem evaluated on `[0, 1]^d`: f_0(x) = x_0 f_1(x) = 1 - sqrt(x_0 / g(x)) - x_0 / g * sin(10 * pi * x_0) g(x) = 1 + 9 / (d - 1) * \sum_{i=1}^{d-1} x_i The reference point comes from [Yang2019a]_. The pareto front consists of several discontinuous convex parts. """ _max_hv = 128.77811613069076060 _parts = [ # this interval includes both end points [0, 0.0830015349], # this interval includes only the right end points [0.1822287280, 0.2577623634], [0.4093136748, 0.4538821041], [0.6183967944, 0.6525117038], [0.8233317983, 0.8518328654], ] # nugget to make sure linspace returns elements within the specified range _eps = 1e-6 def evaluate_true(self, X: Tensor) -> Tensor: f_0 = X[..., 0] g = self._g(X=X) f_1 = 1 - (f_0 / g).sqrt() - f_0 / g * torch.sin(10 * math.pi * f_0) return torch.stack([f_0, f_1], dim=-1) def gen_pareto_front(self, n: int) -> Tensor: n_parts = len(self._parts) n_per_part = torch.full( torch.Size([n_parts]), n // n_parts, dtype=torch.long, device=self.bounds.device, ) left_over = n % n_parts n_per_part[:left_over] += 1 f_0s = [] for i, p in enumerate(self._parts): left, right = p f_0s.append( torch.linspace( left + self._eps, right - self._eps, n_per_part[i], dtype=self.bounds.dtype, device=self.bounds.device, ) ) f_0 = torch.cat(f_0s, dim=0) f_1 = 1 - f_0.sqrt() - f_0 * torch.sin(10 * math.pi * f_0) f_X = torch.stack([f_0, f_1], dim=-1) if self.negate: f_X *= -1 return f_X # ------ Constrained Multi-Objective Test Problems ----- # class BNH(MultiObjectiveTestProblem, ConstrainedBaseTestProblem): r"""The constrained BNH problem. See [GarridoMerchan2020]_ for more details on this problem. Note that this is a minimization problem. """ dim = 2 num_objectives = 2 num_constraints = 2 _bounds = [(0.0, 5.0), (0.0, 3.0)] _ref_point = [0.0, 0.0] # TODO: Determine proper reference point def evaluate_true(self, X: Tensor) -> Tensor: return torch.stack( [4.0 * (X ** 2).sum(dim=-1), ((X - 5.0) ** 2).sum(dim=-1)], dim=-1 ) def evaluate_slack_true(self, X: Tensor) -> Tensor: c1 = 25.0 - (X[..., 0] - 5.0) ** 2 - X[..., 1] ** 2 c2 = (X[..., 0] - 8.0) ** 2 + (X[..., 1] + 3.0) ** 2 - 7.7 return torch.stack([c1, c2], dim=-1) class SRN(MultiObjectiveTestProblem, ConstrainedBaseTestProblem): r"""The constrained SRN problem. See [GarridoMerchan2020]_ for more details on this problem. Note that this is a minimization problem. """ dim = 2 num_objectives = 2 num_constraints = 2 _bounds = [(-20.0, 20.0), (-20.0, 20.0)] _ref_point = [0.0, 0.0] # TODO: Determine proper reference point def evaluate_true(self, X: Tensor) -> Tensor: obj1 = 2.0 + ((X - 2.0) ** 2).sum(dim=-1) obj2 = 9.0 * X[..., 0] - (X[..., 1] - 1.0) ** 2 return torch.stack([obj1, obj2], dim=-1) def evaluate_slack_true(self, X: Tensor) -> Tensor: c1 = 225.0 - ((X ** 2) ** 2).sum(dim=-1) c2 = -10.0 - X[..., 0] + 3 * X[..., 1] return torch.stack([c1, c2], dim=-1) class CONSTR(MultiObjectiveTestProblem, ConstrainedBaseTestProblem): r"""The constrained CONSTR problem. See [GarridoMerchan2020]_ for more details on this problem. Note that this is a minimization problem. """ dim = 2 num_objectives = 2 num_constraints = 2 _bounds = [(0.1, 10.0), (0.0, 5.0)] _ref_point = [10.0, 10.0] def evaluate_true(self, X: Tensor) -> Tensor: obj1 = X[..., 0] obj2 = (1.0 + X[..., 1]) / X[..., 0] return torch.stack([obj1, obj2], dim=-1) def evaluate_slack_true(self, X: Tensor) -> Tensor: c1 = 9.0 * X[..., 0] + X[..., 1] - 6.0 c2 = 9.0 * X[..., 0] - X[..., 1] - 1.0 return torch.stack([c1, c2], dim=-1) class ConstrainedBraninCurrin(BraninCurrin, ConstrainedBaseTestProblem): r"""Constrained Branin Currin Function. This uses the disk constraint from [Gelbart2014]_. """ dim = 2 num_objectives = 2 num_constraints = 1 _bounds = [(0.0, 1.0), (0.0, 1.0)] _con_bounds = [(-5.0, 10.0), (0.0, 15.0)] _ref_point = [80.0, 12.0] _max_hv = 608.4004237022673 # from NSGA-II with 90k evaluations def __init__(self, noise_std: Optional[float] = None, negate: bool = False) -> None: super().__init__(noise_std=noise_std, negate=negate) con_bounds = torch.tensor(self._con_bounds, dtype=torch.float).transpose(-1, -2) self.register_buffer("con_bounds", con_bounds) def evaluate_slack_true(self, X: Tensor) -> Tensor: X_tf = unnormalize(X, self.con_bounds) return 50 - (X_tf[..., 0:1] - 2.5).pow(2) - (X_tf[..., 1:2] - 7.5).pow(2) class C2DTLZ2(DTLZ2, ConstrainedBaseTestProblem): num_constraints = 1 _r = 0.2 # approximate from nsga-ii, TODO: replace with analytic _max_hv = 0.3996406303723544 def evaluate_slack_true(self, X: Tensor) -> Tensor: if X.ndim > 2: raise NotImplementedError("Batch X is not supported.") f_X = self.evaluate_true(X) term1 = (f_X - 1).pow(2) mask = ~(torch.eye(f_X.shape[-1], device=f_X.device).bool()) indices = torch.arange(f_X.shape[1], device=f_X.device).repeat(f_X.shape[1], 1) indexer = indices[mask].view(f_X.shape[1], f_X.shape[-1] - 1) term2_inner = ( f_X.unsqueeze(1) .expand(f_X.shape[0], f_X.shape[-1], f_X.shape[-1]) .gather(dim=-1, index=indexer.repeat(f_X.shape[0], 1, 1)) ) term2 = (term2_inner.pow(2) - self._r ** 2).sum(dim=-1) min1 = (term1 + term2).min(dim=-1).values min2 = ((f_X - 1 / math.sqrt(f_X.shape[-1])).pow(2) - self._r ** 2).sum(dim=-1) return -torch.min(min1, min2).unsqueeze(-1) class OSY(MultiObjectiveTestProblem, ConstrainedBaseTestProblem): r""" The OSY test problem from [Oszycka1995]_. Implementation from https://github.com/msu-coinlab/pymoo/blob/master/pymoo/problems/multi/osy.py Note that this implementation assumes minimization, so please choose negate=True. """ dim = 6 num_constraints = 6 num_objectives = 2 _bounds = [ (0.0, 10.0), (0.0, 10.0), (1.0, 5.0), (0.0, 6.0), (1.0, 5.0), (0.0, 10.0), ] _ref_point = [-75.0, 75.0] def evaluate_true(self, X: Tensor) -> Tensor: f1 = -( 25 * (X[..., 0] - 2) ** 2 + (X[..., 1] - 2) ** 2 + (X[..., 2] - 1) ** 2 + (X[..., 3] - 4) ** 2 + (X[..., 4] - 1) ** 2 ) f2 = (X ** 2).sum(-1) return torch.stack([f1, f2], dim=-1) def evaluate_slack_true(self, X: Tensor) -> Tensor: g1 = X[..., 0] + X[..., 1] - 2.0 g2 = 6.0 - X[..., 0] - X[..., 1] g3 = 2.0 - X[..., 1] + X[..., 0] g4 = 2.0 - X[..., 0] + 3.0 * X[..., 1] g5 = 4.0 - (X[..., 2] - 3.0) ** 2 - X[..., 3] g6 = (X[..., 4] - 3.0) ** 2 + X[..., 5] - 4.0 return torch.stack([g1, g2, g3, g4, g5, g6], dim=-1)
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
f096e3e0467b7f1aabe9b18bc1dbf1ce4de00d62
7103edec177ded3a19c88d050595c2f536662787
/media.py
f1f2b003c6cde6814322ea6ebac7fdff5496b290
[]
no_license
rodrigojsoliveira/ud036_StarterCode
7147ed031a9c36cc06db2705ddabe209c1b49b11
80ab6e0d006364e7e16392776c76710c702746ed
refs/heads/master
2020-03-30T07:59:43.034159
2018-10-04T00:32:04
2018-10-04T00:32:04
150,980,124
0
0
null
2018-09-30T15:36:47
2018-09-30T15:36:46
null
UTF-8
Python
false
false
661
py
""" Media Module This module contains entertainment medias. Examples of media that could be modelled are TV Shows, Music Concerts, Sports Broadcast, and so on. """ class Movie(): """ Class Movie A movie object will contain basic information of a movie, like its title, poster image url, and trailer url. Other properties can be created depending on the information you wish to display to the end user. """ # Class constructor. def __init__(self, title, poster_image_url, trailer_youtube_url): self.title = title self.poster_image_url = poster_image_url self.trailer_youtube_url = trailer_youtube_url
[ "rodrigojsoliveira@gmail.com" ]
rodrigojsoliveira@gmail.com
8e1b84454ca0d919b92c8122f5dffac42ca4ec4e
f1e5cf9912ced785dce880b757f3716ae8c1e651
/project/system_testing/cases.py
a11dbf8080d20868ab97fc6e6ddaf9e89a7c3376
[ "MIT" ]
permissive
slightlyLLL/tenhou-python-bot
2a735340c2e91142c876eac181dff6f7bcd0e107
df83948546d424ca8c2abd2e48aba72da1e224d3
refs/heads/master
2023-05-01T14:48:39.543636
2020-12-16T11:18:10
2020-12-16T11:18:10
null
0
0
null
null
null
null
UTF-8
Python
false
false
13,478
py
""" The package contains steps to reproduce real game situations and the result that we want to have after bot turn. It will help us to be sure that new changes in logic don't change the old fixed bugs with decisions. Also, this package contains tools to generate documentation and unit tests from the description of the situations. """ from utils.decisions_logger import MeldPrint ACTION_DISCARD = "discard" ACTION_MELD = "meld" ACTION_CRASH = "crash" SYSTEM_TESTING_CASES = [ { "index": 1, "description": "Bot discarded 2s by suji because of 2 additional ukeire in ryanshanten, instead of discarding the safe tile.", "reproducer_command": "python reproducer.py --log 2020102200gm-0001-7994-1143916f --player 0 --wind 2 --honba 3 --tile=1s --n 2 --action=draw", "action": ACTION_DISCARD, "allowed_discards": ["3s", "5s"], "with_riichi": False, }, { "index": 2, "description": "6m and 8m have equal ukeire, but 6m is safe.", "reproducer_command": "python reproducer.py --log 2020102204gm-0001-7994-fb636348 --player 3 --wind 7 --honba 0 --action=draw --tile=6z", "action": ACTION_DISCARD, "allowed_discards": ["6m", "3s"], "with_riichi": False, }, { "index": 3, "description": "It was a bad meld. We don't want to open hand here.", "reproducer_command": "python reproducer.py --log 2020102208gm-0009-0000-40337c9c --player Xenia --wind 3 --honba 0 --action enemy_discard --tile 1s", "action": ACTION_MELD, "meld": None, "tile_after_meld": None, }, { "index": 4, "description": "It was a bad meld. We don't want to open hand here.", "reproducer_command": "python reproducer.py --log 2020102208gm-0009-0000-40337c9c --player Xenia --wind 4 --honba 0 --action enemy_discard --tile 5s", "action": ACTION_MELD, "meld": None, "tile_after_meld": None, }, { "index": 5, "description": "Riichi dora tanki is a better move here.", "reproducer_command": "python reproducer.py --log 2020102517gm-0009-0000-67fd5f29 --player Xenia --wind 2 --honba 0 --action draw --n 1 --tile 7s", "action": ACTION_DISCARD, "allowed_discards": ["1p", "4p"], "with_riichi": True, }, { "index": 6, "description": "Let's defend here.", "reproducer_command": "python reproducer.py --log 2020102602gm-0009-0000-ba58220e --player Kaavi --wind 6 --honba 1 --action draw --n 2 --tile 1s", "action": ACTION_DISCARD, "allowed_discards": ["1s"], "with_riichi": False, }, { "index": 7, "description": "7p was wrongly detected as dangerous tile, it is not like this", "reproducer_command": "python reproducer.py --log 2020102608gm-0009-0000-ff33fd82 --player Wanjirou --wind 4 --honba 0 --action draw --n 1 --tile 7p", "action": ACTION_DISCARD, "allowed_discards": ["7p"], "with_riichi": False, }, { "index": 8, "description": "Honors are dangerous on this late stage of the game. And we have 2 shanten. Let's fold with 6s", "reproducer_command": "python reproducer.py --log 2020102619gm-0089-0000-dfaf5b1d --player Xenia --wind 4 --honba 0 --action draw --n 1 --tile 2m", "action": ACTION_DISCARD, "allowed_discards": ["6s"], "with_riichi": False, "skip_reason": "Need to investigate it.", }, { "index": 9, "description": "", "reproducer_command": "python reproducer.py --log 2020102701gm-0089-0000-8572de24 --player Ichihime --wind 7 --honba 1 --action draw --n 1 --tile 7s", "action": ACTION_DISCARD, "allowed_discards": ["3p"], "with_riichi": False, }, { "index": 10, "description": "", "reproducer_command": "python reproducer.py --log 2020102710gm-0009-7994-88f45f2d --player 3 --wind 5 --honba 0 --tile 4m --action enemy_discard", "action": ACTION_MELD, "meld": None, "tile_after_meld": None, }, { "index": 11, "description": "There is no need in damaten. Let's riichi.", "reproducer_command": "python reproducer.py --log 2020102720gm-0089-0000-65eb30bf --player Xenia --wind 8 --honba 2 --action draw --n 1 --tile 4m", "action": ACTION_DISCARD, "allowed_discards": ["7s"], "with_riichi": True, }, { "index": 12, "description": "Chun is too dangerous to discard.", "reproducer_command": "python reproducer.py --log 2020102721gm-0089-0000-67865130 --player Xenia --wind 5 --honba 0 --action draw --n 1 --tile 4m", "action": ACTION_DISCARD, "allowed_discards": ["7s"], "with_riichi": False, }, { "index": 13, "description": "Hatsu is too dangerous to discard.", "reproducer_command": "python reproducer.py --log 2020102821gm-0089-0000-49e1d208 --player Ichihime --wind 1 --honba 2 --action draw --n 1 --tile 6z", "action": ACTION_DISCARD, "allowed_discards": ["7m"], "with_riichi": False, }, { "index": 14, "description": "3p is genbutsu", "reproducer_command": "python reproducer.py --log 2020102908gm-0089-0000-e1512a30 --player Ichihime --wind 7 --honba 0 --action draw --n 2 --tile 6p", "action": ACTION_DISCARD, "allowed_discards": ["3p"], "with_riichi": False, }, { "index": 15, "description": "5p is too dangerous to discard", "reproducer_command": "python reproducer.py --log 2020102900gm-0089-0000-5cc13112 --player Xenia --wind 2 --honba 2 --tile 5p --n 2 --action draw", "action": ACTION_DISCARD, "allowed_discards": ["5s"], "with_riichi": False, }, { "index": 16, "description": "We need to fold here", "reproducer_command": "python reproducer.py --log 2020102921gm-0089-0000-764321f0 --player Xenia --wind 1 --honba 0 --action draw --n 1 --tile 3m", "action": ACTION_DISCARD, "allowed_discards": ["7s", "3m"], "with_riichi": False, }, { "index": 17, "description": "Bad meld for honitsu.", "reproducer_command": "python reproducer.py --log 2020102922gm-0089-0000-d3c4e90b --player Xenia --wind 1 --honba 0 --action enemy_discard --n 1 --tile 8p", "action": ACTION_MELD, "meld": None, "tile_after_meld": None, }, { "index": 18, "description": "", "reproducer_command": "python reproducer.py --log 2020103005gm-0089-0000-01fc4f4d --player Kaavi --wind 3 --honba 0 --action draw --n 3 --tile 6s", "action": ACTION_DISCARD, "allowed_discards": ["3p", "6s"], "with_riichi": False, }, { "index": 19, "description": "", "reproducer_command": "python reproducer.py --log 2020111101gm-0009-7994-f22b8c57 --wind 4 --honba 2 --player 2 --tile 8m --action enemy_discard", "action": ACTION_MELD, "meld": None, "tile_after_meld": None, }, { "index": 20, "description": "", "reproducer_command": "python reproducer.py --log 2020111111gm-0009-7994-5550ade1 --wind 8 --honba 1 --player 0 --tile 7z --action enemy_discard", "action": ACTION_MELD, "meld": {"type": MeldPrint.PON, "tiles": "777z"}, "tile_after_meld": "3p", }, { "index": 21, "description": "", "reproducer_command": "python reproducer.py --log 2020111401gm-0009-7994-7429e8e0 --wind 1 --honba 1 --action draw --tile 3s --player 3", "action": ACTION_CRASH, }, { "index": 22, "description": "", "reproducer_command": "python reproducer.py --log 2020111402gm-0009-7994-41f6c1a1 --wind 3 --honba 0 --action enemy_discard --tile 5p --player 1", "action": ACTION_CRASH, }, { "index": 23, "description": "", "reproducer_command": "python reproducer.py --file failed_2020-11-11_13_06_26_885.txt --wind 3 --honba 0 --tile 1z --n 2 --player 3", "action": ACTION_CRASH, }, { "index": 24, "description": "", "reproducer_command": "python reproducer.py --file failed_2020-11-11_12_52_06_023.txt --wind 8 --honba 0 --action enemy_discard --tile 3s --player 0", "action": ACTION_CRASH, }, { "index": 25, "description": "", "reproducer_command": "python reproducer.py --file failed_2020-11-11_12_19_20_515.txt --wind 3 --honba 1 --tile 6s --player 2", "action": ACTION_CRASH, }, { "index": 26, "description": "", "reproducer_command": "python reproducer.py --log 2020102620gm-0089-0000-c558d68c --player Kaavi --wind 1 --honba 2 --action draw --n 2 --tile 4p", "action": ACTION_DISCARD, "allowed_discards": ["3s"], "with_riichi": False, }, { "index": 27, "description": "", "reproducer_command": "python reproducer.py --log 2020102208gm-0009-0000-1d3d08c8 --player Ichihime --wind 5 --honba 1 --tile 1z --action draw", "action": ACTION_CRASH, }, { "index": 28, "description": "", "reproducer_command": "python reproducer.py --log 2020102008gm-0001-7994-9438a8f4 --player Wanjirou --wind 3 --honba 0 --tile 7p --action enemy_discard", "action": ACTION_MELD, "meld": None, "tile_after_meld": None, }, { "index": 29, "description": "There was crash after open kan in the real game.", "reproducer_command": "python reproducer.py --log 2020112003gm-0089-0000-72c1d092 --player Xenia --wind 7 --honba 0 --tile 1s", "action": ACTION_CRASH, }, { "index": 30, "description": "We are pushing here, even if it is karaten we still want to keep tempai.", "reproducer_command": "python reproducer.py --log 2020112215gm-0009-0000-9c894eca --player 1 --wind 8 --honba 0 --action draw --n 1 --tile 7m", "action": ACTION_DISCARD, "allowed_discards": ["5m"], "with_riichi": False, }, { "index": 31, "description": "Regression with honitsu and chinitsu detection", "reproducer_command": "python reproducer.py --log 2020112219gm-0089-0000-8de03653 --player 0 --wind 1 --honba 0 --action draw --n 1 --tile 1s", "action": ACTION_DISCARD, "allowed_discards": ["3z"], "with_riichi": False, }, { "index": 32, "description": "Dealer should open yakuhai with two valued pairs in the hand.", "reproducer_command": "python reproducer.py --log 2020112307gm-0089-0000-c294daec --player 3 --wind 8 --honba 0 --action enemy_discard --tile 2z", "action": ACTION_MELD, "meld": {"type": MeldPrint.PON, "tiles": "222z"}, "tile_after_meld": "3m", }, { "index": 33, "description": "Bot wrongly detected honitsu for shimocha discards.", "reproducer_command": "python reproducer.py --log 2020112309gm-0089-0000-53e7b431 --player 1 --wind 3 --honba 1 --action draw --n 1 --tile 6m", "action": ACTION_DISCARD, "allowed_discards": ["6p"], "with_riichi": False, }, { "index": 34, "description": "Bot pushed too much against multiple threats.", "reproducer_command": "python reproducer.py --log 2020112317gm-0089-0000-f4d22bba --player 2 --wind 6 --honba 0 --action draw --n 1 --tile 8s", "action": ACTION_DISCARD, "allowed_discards": ["9p"], "with_riichi": False, }, { "index": 35, "description": "Must riichi.", "reproducer_command": "python reproducer.py --log 2020112504gm-0089-0000-e125fd6f --player 2 --wind 8 --honba 0 --action draw --n 1 --tile 2s", "action": ACTION_DISCARD, "allowed_discards": ["3s"], "with_riichi": True, }, { "index": 36, "description": "Must fold with north tiles.", "reproducer_command": "python reproducer.py --log 2020112504gm-0089-0000-94960883 --player 1 --wind 1 --honba 0 --action draw --n 2 --tile 9p", "action": ACTION_DISCARD, "allowed_discards": ["4z"], "with_riichi": False, }, { "index": 37, "description": "Must open meld to secure 3rd place.", "reproducer_command": "python reproducer.py --log 2020112504gm-0029-0000-ca8a957c --player 2 --wind 8 --honba 0 --action enemy_discard --n 1 --tile 4z", "action": ACTION_MELD, "meld": {"type": MeldPrint.PON, "tiles": "444z"}, "tile_after_meld": "1p", }, { "index": 38, "description": "It is fine to riichi with that hand.", "reproducer_command": "python reproducer.py --log 2020112505gm-0089-0000-1a2861c9 --player 3 --wind 5 --honba 0 --action draw --n 1 --tile 9s", "action": ACTION_DISCARD, "allowed_discards": ["8p"], "with_riichi": True, }, { "index": 39, "description": "Better to fold that hand.", "reproducer_command": "python reproducer.py --log 2020112507gm-0089-0000-07c68413 --player 0 --wind 4 --honba 0 --action draw --n 2 --tile 4m", "action": ACTION_DISCARD, "allowed_discards": ["3m", "2p", "8p"], "with_riichi": False, }, ]
[ "alexey@nihisil.com" ]
alexey@nihisil.com
2169703622b2746d70684fe86329062ae29f25a9
24fb007b184170c6a7b22d201d97369c1338121f
/lesson03/case01.py
05209c2c966999a01faaaa9afdf3eaca3dcb02af
[]
no_license
johnnylin777/yzu_python
17f972946fa820a358acbcfcbb3b48005d5e70ab
e2887c59adaf1c01d86dbdefd5e9de6e75666041
refs/heads/master
2021-05-26T10:35:38.797655
2020-07-23T11:19:37
2020-07-23T11:19:37
254,092,948
0
0
null
null
null
null
UTF-8
Python
false
false
114
py
# 加入千分位 n = 123 * 99 * 1234 * 1.27 print(format(n, ',')) # 原始字串 s = r"C:\temp\nba.txt" print(s)
[ "u8860035@gmail.com" ]
u8860035@gmail.com
5f401aeb2ebced5923733b59d2ead7344ca582a7
8119af882118d2570727126e56c363b3f5fc6dca
/15/Dec15.py
c5f519b70442eb01ba6899d208befba3cc3972f9
[]
no_license
noglows/AdventOfCode2020
3c7811f1fc0f239e9845f8cfd4a1215aa8dc271b
706dbf0368b60da7c0dbd1e0a9499b8ae3457ec0
refs/heads/master
2023-02-12T20:15:49.234334
2021-01-11T18:02:32
2021-01-11T18:02:32
317,637,736
0
0
null
null
null
null
UTF-8
Python
false
false
1,195
py
# Open and read data numbers = open("/Users/jess/Documents/Code/Advent2020/15/Data.txt", "r") numbers = numbers.readlines() # Part One game_input = [] spoken = [] track = {} game = numbers[0].split(",") numbers_length = len(game_input) turn = 0 for item in game: spoken.append(int(item)) track[int(item)] = turn turn += 1 count = numbers_length + 1 iterator = 5 count = iterator + 1 while count < 2020: look = spoken[iterator] if look in track: spoken.append(iterator - track[look]) else: spoken.append(0) track[look] = iterator iterator +=1 count += 1 print("Part One Solution is: ") print(spoken[-1]) game_input = [] spoken = [] track = {} game = numbers[0].split(",") numbers_length = len(game_input) turn = 0 for item in game: spoken.append(int(item)) track[int(item)] = turn turn += 1 count = numbers_length + 1 iterator = 5 count = iterator + 1 while count < 30000000: look = spoken[iterator] if look in track: spoken.append(iterator - track[look]) else: spoken.append(0) track[look] = iterator iterator +=1 count += 1 print("Part Two Solution is: ") print(spoken[-1])
[ "jessica.noglows@outlook.com" ]
jessica.noglows@outlook.com
aea30ea3c7a58009592a16380f2a6e20dab639a1
c5a5eef399a539a466b3f191e496d0603708f4b9
/itemFeaturesMatrixGeneator.py
8519ebf78ae664ffe23c13149e818c157c71f6d6
[]
no_license
stuartcrobinson/hackdays2017
3c1de84955a7ddba15dd8dbd59823541c1e640c4
45372db04918ef4d0d7792cba722876fd5e799b4
refs/heads/master
2021-09-06T14:47:14.338742
2018-02-07T18:46:03
2018-02-07T18:46:03
105,793,085
1
0
null
null
null
null
UTF-8
Python
false
false
4,349
py
from __future__ import print_function from nltk.stem import PorterStemmer, WordNetLemmatizer from scipy import sparse import glob import csv import sys import io import html import string import numpy # import StringIO # https://stackoverflow.com/questions/26369051/python-read-from-file-and-remove-non-ascii-characters # TODO # # reload(sys) # sys.setdefaultencoding('utf8') #interactions coo_matrix shape [n_users, n_items] #item_features csr_matrix shape [n_items, n_item_features] stemmer = PorterStemmer() def get_words(doc): # replace punctuation with space replace_punctuation = str.maketrans(string.punctuation, ' '*len(string.punctuation)) doc = doc.translate(replace_punctuation) # split into tokens by white space tokens = doc.split() # remove remaining tokens that are not alphabetic tokens = [word for word in tokens if word.isalpha()] # make lower case tokens = [stemmer.stem(word.lower()) for word in tokens] return tokens def removeStopwords(words, stopwords): resultwords = [word for word in words if word not in stopwords] return resultwords stopwords = ['rst', 'll', 're', 'd', 've', 's', 't', 'br', 'li', 'nbsp', 'p', 'span', 'div', 'ul', 'ol', 'includes','a','able','about','across','after','all','almost','also','am','among','an','and','any','are','as','at','be','because','been','but','by','can','cannot','could','dear','did','do','does','either','else','ever','every','for','from','get','got','had','has','have','he','her','hers','him','his','how','however','i','if','in','into','is','it','its','just','least','let','like','likely','may','me','might','most','must','my','neither','no','nor','not','of','off','often','on','only','or','other','our','own','rather','said','say','says','she','should','since','so','some','than','that','the','their','them','then','there','these','they','this','tis','to','too','twas','us','wants','was','we','were','what','when','where','which','while','who','whom','why','will','with','would','yet','you','your'] def clean(text): return removeStopwords(get_words(text), stopwords) #product_id,active,title,description path = "fordocker/products_production_siteId_=35569/*.csv" d = {} for fname in glob.glob(path): print(fname) nonascii = bytearray(range(0x80, 0x100)) # with open(fname,'rb') as infile, open('fordocker/d_parsed.csv','wb') as outfile: with open(fname,'rb') as infile: next(infile) for line in infile: # b'\n'-separated lines (Linux, OSX, Windows) line = line.translate(None, nonascii) line = str(line,'utf-8') for row in csv.reader([line]): print(row[0]) k,v = row[0], clean(row[2] + " " + row[3])[:-1] # v = row[3] d[k] = v print(len(d)) shared = {} tags = {} for key in d: print(key) shared = set(d[key]) tags = set(d[key]) print('original shared:') print(shared) break print('') for key in d: print(key) print((d[key])) shared = shared.intersection(d[key]) tags = tags.union(d[key]) print('new shared:') print(shared) print('new union:') print(tags) # print(html.unescape(d[key])) print('shared tokens (could be none)') print(shared) print('all tokens') print(tags) print('') #done making item features!!!!!! what next? collect all tags into a single list/vector. now, made maps! seeeeee map_index_tag = dict(enumerate(tags)) map_tag_index = {x:i for i,x in enumerate(tags)} print(b) # okay next .... build into a matrix . then convert to csr or coo idk. # rows: items # cols: features vector # a = numpy.zeros(shape=(5,2)) a = numpy.zeros(shape=(len(d),len(tags))) orderedProductIds = [] for i, key in enumerate(d): orderedProductIds.append(key) for tag in d[key]: tag_index = map_tag_index[tag] a[i][tag_index] += 1 r = 0 print(orderedProductIds[r]) print() for i in range(0, len(a[r])): if a[r][i] > 0: print(map_index_tag[i], ": ", a[r][i]) # next build interaction matrix # convert a to csr_matrix # https://stackoverflow.com/questions/7922487/how-to-transform-numpy-matrix-or-array-to-scipy-sparse-matrix sA = sparse.csr_matrix(a) #now create coo matrix from interactions. need browse. lets make new python file
[ "stuart.robinson@bronto.com" ]
stuart.robinson@bronto.com
2278a6e04b6abc2f0be4c29ca21670712ee64e1e
e7650cb5cb3a3f186ff7ccf64c9b3c8752b0d7dd
/items/other_items.py
476e8b25ffeb75e5feff2e4f1b50e82b77536092
[]
no_license
JamesFraserXedo/automated_product_update
c39009de34303f78178d1424815bfdd9957c08f0
4559fbf6869d6f26e7927d9f03aa134f15e6e464
refs/heads/master
2021-01-20T18:44:14.863284
2016-07-01T12:37:50
2016-07-01T12:37:50
62,325,596
0
0
null
null
null
null
UTF-8
Python
false
false
692
py
from items.base_item import BaseItem class VoyageItem(BaseItem): def __init__(self, style, comments, uk_wholesale_price, colours_available, uk_size_range, collection): super().__init__(style, uk_wholesale_price, colours_available, uk_size_range, collection) self.comments = comments def __repr__(self): return str({ "style": self.style, "comments": self.comments, "uk_wholesale_price": self.uk_wholesale_price, "colours_available": self.colours_available, "uk_size_range": self.uk_size_range, "collection": self.collection, "marketing_info": self.marketing_info })
[ "james.fraser@xedosoftware.com" ]
james.fraser@xedosoftware.com